forked from Wedge-lab/battenberg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclonal_ascat.R
executable file
·1723 lines (1381 loc) · 67.3 KB
/
clonal_ascat.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
####################################################################################################
#' A helper function to split the genome into parts
#' @param SNPpos A data.frame with a row for each SNP. First column is chromosome, second column position
#' @noRd
split_genome = function(SNPpos) {
# look for gaps of more than 1Mb and chromosome borders
holesOver1Mb = which(diff(SNPpos[,2])>=1000000)+1
chrBorders = which(diff(as.numeric(factor(SNPpos[,1],levels=unique(SNPpos[,1]))))!=0)+1
holes = unique(sort(c(holesOver1Mb,chrBorders)))
# find which segments are too small
joincandidates=which(diff(c(0,holes,dim(SNPpos)[1]))<200)
# if it's the first or last segment, just join to the one next to it, irrespective of chromosome and positions
while (1 %in% joincandidates) {
holes=holes[-1]
joincandidates=which(diff(c(0,holes,dim(SNPpos)[1]))<200)
}
while ((length(holes)+1) %in% joincandidates) {
holes=holes[-length(holes)]
joincandidates=which(diff(c(0,holes,dim(SNPpos)[1]))<200)
}
while(length(joincandidates)!=0) {
# the while loop is because after joining, segments may still be too small..
startseg = c(1,holes)
endseg = c(holes-1,dim(SNPpos)[1])
# for each segment that is too short, see if it has the same chromosome as the segments before and after
# the next always works because neither the first or the last segment is in joincandidates now
previoussamechr = SNPpos[endseg[joincandidates-1],1]==SNPpos[startseg[joincandidates],1]
nextsamechr = SNPpos[endseg[joincandidates],1]==SNPpos[startseg[joincandidates+1],1]
distanceprevious = SNPpos[startseg[joincandidates],2]-SNPpos[endseg[joincandidates-1],2]
distancenext = SNPpos[startseg[joincandidates+1],2]-SNPpos[endseg[joincandidates],2]
# if both the same, decide based on distance, otherwise if one the same, take the other, if none, just take one.
joins = ifelse(previoussamechr&nextsamechr,
ifelse(distanceprevious>distancenext, joincandidates, joincandidates-1),
ifelse(nextsamechr, joincandidates, joincandidates-1))
holes=holes[-joins]
joincandidates=which(diff(c(0,holes,dim(SNPpos)[1]))<200)
}
# if two neighboring segments are selected, this may make bigger segments then absolutely necessary, but I'm sure this is no problem.
startseg = c(1,holes)
endseg = c(holes-1,dim(SNPpos)[1])
chr=list()
for (i in 1:length(startseg)) {
chr[[i]]=startseg[i]:endseg[i]
}
return(chr)
}
####################################################################################################
#' Helper function that calculates a t-statistic
#' @noRd
studentise <-function( sample_size, sample_mean, sample_SD, mu_pop ) # kjd 18-12-2013
{
tvar = ( sample_mean - mu_pop ) * sqrt( sample_size ) / sample_SD
return( tvar )
}
####################################################################################################
#' This function calculates a P-value, for a test where the null hypothesis is that
#' the sample was drawn from a Gaussian population with the specified mean "mu_pop".
#' @noRd
calc_Pvalue_t_twotailed <-function( sample_size, sample_mean, sample_SD, mu_pop, max_dist) # kjd 18-12-2013
{
tvar = ( sample_mean - mu_pop ) * sqrt( sample_size ) / sample_SD
if( tvar < 0 )
{
lower_tail_prob = pt( tvar , df = sample_size - 1 , lower.tail = TRUE )
}else
{
lower_tail_prob = 1 - pt( tvar , df = sample_size - 1 , lower.tail = TRUE )
}
pval = 2 * lower_tail_prob
#DCW 250314
if(abs(sample_mean - mu_pop)<max_dist){
pval = 1
}
return( pval )
}
####################################################################################################
#' Helper function that calculates a binomial probability
#' @noRd
calc_binomial_prob <-function( sample_proportion, sample_size, pop_proportion ) # kjd 10-2-2014
{
sample_count = round( sample_proportion * sample_size , 0 )
if( sample_count < 0 ){
sample_count = 0
}
if( sample_count > sample_size ){
sample_count = sample_size
}
if( pop_proportion < 0 ){
pop_proportion = 0
}
if( pop_proportion > 1 ){
pop_proportion = 1
}
prob = dbinom( sample_count, sample_size, pop_proportion )
return( prob )
}
####################################################################################################
#' This function calculates a log likelihood ratio where the two hypotheses are that
#' the tumour genome segment in question is "clonal".
#' The first hypothesis is the "best fit" model we can find.
#' The second hypothesis is the "second best fit" model we can find.
#' @noRd
calc_ln_likelihood_ratio <-function( LogR, BAFreq, BAF.length, BAF.size, BAF.mean, read_depth, rho, psi, gamma_param, maxdist_BAF ) # kjd 18-12-2013
{
pooled_BAF.size = read_depth * BAF.size
# if we don't have a value for LogR, fill in 0
if (is.na(LogR)) {
LogR = 0
}
nMajor = (rho-1+BAFreq*psi*2^(LogR/gamma_param))/rho
nMinor = (rho-1+(1-BAFreq)*psi*2^(LogR/gamma_param))/rho
# to make sure we're always in a positive square:
#if(nMajor < 0) {
# nMajor = 0.01
#}
#
#if(nMinor < 0) {
# nMinor = 0.01
#}
#DCW - increase nMajor and nMinor together, to avoid impossible combinations (with negative subclonal fractions)
if(nMinor<0 | is.na(nMinor)){
if(BAFreq==1){
#avoid calling infinite copy number
nMajor = 1000
}else{
nMajor = nMajor + BAFreq * (0.01 - nMinor) / (1-BAFreq)
if (nMajor<0) nMajor=1000
}
nMinor = 0.01
}
if (!is.finite(nMajor)) {
nMajor = 0.01
}
# Check if there is a viable solution
if (!is.na(BAFreq)) {
nearest_edge = GetNearestCorners_bestOption( rho, psi, BAFreq, nMajor, nMinor ) # kjd 14-2-2014
nMaj = nearest_edge$nMaj # kjd 14-2-2014
nMin = nearest_edge$nMin # kjd 14-2-2014
BAF_levels = (1-rho+rho*nMaj)/(2-2*rho+rho*(nMaj+nMin))
index_vect = which( is.finite(BAF_levels) ) # kjd 14-2-2014
BAF_levels = BAF_levels[ index_vect ] # kjd 14-2-2014
if( length( BAF_levels ) > 1 ) # kjd 14-2-2014
{
likelihood_vect = sapply( BAF_levels , function(x){ calc_binomial_prob( BAF.mean, pooled_BAF.size, x ) } )
likelihood_vect = sort( likelihood_vect, decreasing = TRUE )
if( ( likelihood_vect[1] > 0 ) && ( likelihood_vect[2] > 0 ) )
{
ln_lratio = log( likelihood_vect[1] ) - log( likelihood_vect[2] )
}else
{
ln_lratio = 0
}
}else
{
ln_lratio = 0
}
} else {
ln_lratio = 0
}
return( ln_lratio )
}
####################################################################################################
#' Calculate a two tailed binomial p-value
#' @noRd
calc_Pvalue_binomial_twotailed <-function( sample_count, sample_size, pop_proportion ) # kjd 27-2-2014
{
lower_tail_prob = pbinom( sample_count, sample_size, pop_proportion , lower.tail = TRUE )
if( lower_tail_prob < 0.5 )
{
pval = 2 * lower_tail_prob
}else
{
pval = 2 * ( 1 - lower_tail_prob )
}
return( pval )
}
####################################################################################################
#' Helper function that calculates a p-value for a set of BAF values summarised by their mean
#' TODO: this function is not used in Battenberg
#' @noRd
calc_BAF_Pvalue <-function( BAF.mean, pooled_BAF.size, maxdist_BAF, BAF_level ) # kjd 27-2-2014
{
if( is.finite( BAF_level ) && pooled_BAF.size > 0 )
{
sample_size = round( pooled_BAF.size , 0 )
sample_count = round( BAF.mean * pooled_BAF.size , 0 )
if( sample_count < 0 ){
sample_count = 0
}
if( sample_count > sample_size ){
sample_count = sample_size
}
pop_proportion = BAF_level
if( BAF_level < 0 ){
pop_proportion = 0
}
if( BAF_level > 1 ){
pop_proportion = 1
}
pval = calc_Pvalue_binomial_twotailed( sample_count, sample_size, pop_proportion )
if( abs( BAF.mean - BAF_level ) < maxdist_BAF ) {
pval=1
}
}else
{
pval = 0
}
return( pval )
}
####################################################################################################
#' Calculate a p-value for a LogR value
#' TODO: this function is not used in Battenberg
#' @noRd
calc_LogR_Pvalue <-function( LogR, maxdist_LogR, LogR_level ) # kjd 27-2-2014
{
if( is.finite( LogR_level ) )
{
pval = 0
if( abs( LogR - LogR_level ) < maxdist_LogR ) {
pval=1
}
}else
{
pval = 0
}
return( pval )
}
#' Helper function to estimate rho from a given copy number state and it's BAF. The LogR is not used.
#' @noRd
estimate_rho <-function( LogR_value, BAFreq_value, nA_value, nB_value ) # kjd 10-3-2014
{
rho_value = (2*BAFreq_value-1)/(2*BAFreq_value-BAFreq_value*(nA_value+nB_value)-1+nA_value)
return( rho_value )
}
####################################################################################################
#' Helper function to calculate psi from a copy number fit, BAF, LogR, rho and a platform gamma
#' @noRd
estimate_psi <-function( LogR_value, BAFreq_value, nA_value, nB_value, rho_value, gamma_param ) # kjd 10-3-2014
{
temp_value = 2^( - LogR_value / gamma_param )
temp_value = temp_value * ( 2 + ( rho_value * ( nA_value + nB_value - 2 ) ) )
#return(temp_value) # DCW this returns psi rather than psi_t, i.e. the average ploidy of normal and tumour cells
temp_value = temp_value - ( 2 * ( 1 - rho_value ) )
psi_value = temp_value / rho_value
return( psi_value )
}
#' Function that calculates rho and psi from a given reference segment, defined by ref_seg, with copy number state nA_ref and nB_ref
#' @noRd
get.psi.rho.from.ref.seg <-function( ref_seg, s, nA_ref, nB_ref, gamma_param = 1)
{
BAFreq = s[ ref_seg, "b" ]
LogR = s[ ref_seg, "r" ]
rho = estimate_rho( LogR, BAFreq, nA_ref, nB_ref )
psi = estimate_psi( LogR, BAFreq, nA_ref, nB_ref, rho, gamma_param )
# ploidy is recalculated based on results, to avoid bias (due to differences in normalization of LogR)
nA = (rho-1-(s[,"b"]-1)*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+s[,"b"]*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
ploidy = sum((nA+nB) * s[,"length"]) / sum(s[,"length"])
# TODO DEBUG
if (rho > 0) {
ref_segment_info = list( psi = psi, rho = rho, ploidy = ploidy )
} else {
ref_segment_info = list( psi = NA, rho = NA, ploidy = NA )
}
return( ref_segment_info )
}
#' This function decides if a segment is "clonal" (= TRUE) or not (= FALSE).
#' (The alternative hypothesis is that the tumour genome segment in question exhibits "sub-clonal" variation.)
#' We test the integer solutions for all 4 corners. Also, along side the hypothesis test for the BAF.
#' We use a decision rule based on LogR (we could use a hypothesis test which takes account of the variance in LogR, or a fixed “tolerance”).
#' If the null hypothesis is accepted for at least one corner, then we accept that
#' the tumour genome segment in question is "clonal".
#' @noRd
is.segment.clonal <-function( LogR, BAFreq, BAF.length, BAF.size, BAF.mean, BAF.sd, read_depth, rho, psi, gamma_param, siglevel_BAF, maxdist_BAF, siglevel_LogR, maxdist_LogR ) # kjd 21-2-2014
{
# TODO: read_depth, siglevel_LogR and maxdist_LogR are no longer in use
#270314 no longer used
#pooled_BAF.size = read_depth * BAF.size
# if we don't have a value for LogR, fill in 0
if (is.na(LogR)) {
LogR = 0
}
nA = (rho-1-(BAFreq-1)*2^(LogR/gamma_param)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+BAFreq*2^(LogR/gamma_param)*((1-rho)*2+rho*psi))/rho
# if (any(is.na(nA) | is.na(nB)) | any(nA < 0 | nB < 0)) {
# # Reset any negative copy number to 0
# index = which(is.na(nA) | is.na(nB) | nA < 0 | nB < 0)
# print(paste("is.segment.clonal: Found negative copy number for segment", index, "BAF:", BAFreq[index], "logR:", LogR[index], "seg size:", BAF.size[index], "baf.sd:", BAF.sd[index]))
# nA[nA < 0 | is.na(nA)] = 0
# nB[nB < 0 | is.na(nB)] = 0
# }
nMajor = max(nA,nB, na.rm=T)
nMinor = min(nA,nB, na.rm=T)
# check for big shifts in nMajor - if there's a big shift, we shouldn't trust a clonal call
nMajor.saved = nMajor
## to make sure we're always in a positive square:
#if(nMajor < 0) {
# nMajor = 0.01
#}
#
#if(nMinor < 0) {
# nMinor = 0.01
#}
#DCW - increase nMajor and nMinor together, to avoid impossible combinations (with negative subclonal fractions)
if(nMinor<0){
if(BAFreq==1){
#avoid calling infinite copy number
nMajor = 1000
}else{
nMajor = nMajor + BAFreq * (0.01 - nMinor) / (1-BAFreq)
if (nMajor<0) nMajor=1000
}
nMinor = 0.01
}
# note that these are sorted in the order of ascending BAF:
nMaj = c(floor(nMajor),ceiling(nMajor),floor(nMajor),ceiling(nMajor))
nMin = c(ceiling(nMinor),ceiling(nMinor),floor(nMinor),floor(nMinor))
x = floor(nMinor)
y = floor(nMajor)
# total copy number, to determine priority options
ntot = nMajor + nMinor
BAF_levels = (1-rho+rho*nMaj)/(2-2*rho+rho*(nMaj+nMin))
#problem if rho=1 and nMaj=0 and nMin=0
BAF_levels[nMaj==0 & nMin==0] = 0.5
LogR_levels = gamma_param * log( (2-2*rho+rho*(nMaj+nMin))/(2-2*rho+rho*psi) , 2 ) # kjd 21-2-2014
#DCW - just test corners on the nearest edge to determine clonality
#If the segment is called as subclonal, this is the edge that will be used to determine the subclonal proportions that are reported first
all.edges = orderEdges(BAF_levels, BAFreq, ntot,x,y)
nMaj.test = all.edges[1,c(1,3)]
nMin.test = all.edges[1,c(2,4)]
test.BAF_levels = (1-rho+rho*nMaj.test)/(2-2*rho+rho*(nMaj.test+nMin.test))
#problem if rho=1 and nMaj=0 and nMin=0
test.BAF_levels[nMaj.test==0 & nMin.test==0] = 0.5
whichclosestlevel.test = which.min(abs(test.BAF_levels-BAFreq))
#270713 - problem caused by segments with constant BAF (usually 1 or 2)
if(BAF.sd==0){
pval=0
}else{
#pval[i] = t.test(BAFreq,alternative="two.sided",mu=BAF_levels[whichclosestlevel])$p.value
#pval = t.test(BAFreq,alternative="two.sided",mu=test.BAF_levels[whichclosestlevel.test])$p.value
pval = calc_Pvalue_t_twotailed( BAF.size, BAFreq, BAF.sd, test.BAF_levels[whichclosestlevel.test], maxdist_BAF)
}
#not necessary, because checked in calc_Pvalue_t_twotailed
#if(min(abs(l-test.BAF_levels[whichclosestlevel.test]))<maxdist_BAF) {
# pval=1
#}
balanced = nMaj.test[whichclosestlevel.test] == nMin.test[whichclosestlevel.test]
is.clonal = (pval > siglevel_BAF)
# check for big shifts in nMajor - if there's a big shift, we shouldn't trust a clonal call
# This is particularly problematic for very high cellularity samples, like some of the ovarian samples
is.clonal = (pval > siglevel_BAF & nMajor - nMajor.saved <1)
segment_info = list( is.clonal = is.clonal, balanced = balanced, nMaj.test = nMaj.test[whichclosestlevel.test] , nMin.test = nMin.test[whichclosestlevel.test] )
return( segment_info )
}
####################################################################################################
#' This function calculates a t variate.
#' @noRd
calc_standardised_error <-function( LogR, BAFreq, BAF.length, BAF.size, BAF.mean, BAF.sd, rho, psi, gamma_param, maxdist_BAF ) # kjd 31-1-2014
{
# if we don't have a value for LogR, fill in 0
if (is.na(LogR)) {
LogR = 0
}
nMajor = (rho-1+BAFreq*psi*2^(LogR/gamma_param))/rho
nMinor = (rho-1+(1-BAFreq)*psi*2^(LogR/gamma_param))/rho
# to make sure we're always in a positive square:
if(nMajor < 0 | is.na(nMajor)) {
nMajor = 0.01
}
if(nMinor < 0 | is.na(nMinor)) {
nMinor = 0.01
}
# note that these are sorted in the order of ascending BAF:
nMaj = c(floor(nMajor),ceiling(nMajor),floor(nMajor),ceiling(nMajor))
nMin = c(ceiling(nMinor),ceiling(nMinor),floor(nMinor),floor(nMinor))
x = floor(nMinor)
y = floor(nMajor)
# total copy number, to determine priority options
ntot = nMajor + nMinor
index_vect = which( (2-2*rho+rho*(nMaj+nMin)) != 0 ) # kjd 13-1-2014
nMaj = nMaj[ index_vect ] # kjd 13-1-2014
nMin = nMin[ index_vect ] # kjd 13-1-2014
BAF_levels = (1-rho+rho*nMaj)/(2-2*rho+rho*(nMaj+nMin))
whichclosestlevel = which.min(abs(BAF_levels-BAFreq))
# if 0.5 and there are multiple options, finetune, because a random option got chosen
if( length( BAF_levels ) >= 3 ) { # kjd 13-1-2014
if (BAF_levels[whichclosestlevel]==0.5 && BAF_levels[2]==0.5 && BAF_levels[3]==0.5) {
whichclosestlevel = ifelse(ntot>x+y+1,2,3)
}
} # kjd 13-1-2014
mu=BAF_levels[whichclosestlevel] # kjd 28-1-2014
included_segment = 0 # kjd 31-1-2014
if( BAF.size>0 ) { # kjd 13-1-2014
if( BAF.sd==0 | length(mu)==0) {
# pval=0 # kjd 31-1-2014
tvar=0 # kjd 31-1-2014
}else{
# pval = t.test(BAFke,alternative="two.sided",mu=BAF_levels[whichclosestlevel])$p.value
pval = calc_Pvalue_t_twotailed( BAF.size, BAF.mean, BAF.sd, mu, maxdist_BAF ) # kjd 31-1-2014
tvar = studentise( BAF.size, BAF.mean, BAF.sd, mu ) # kjd 31-1-2014
included_segment = 1 # kjd 31-1-2014
}
}else{ # kjd 13-1-2014
# pval = 1 # kjd 13-1-2014 # kjd 31-1-2014
tvar=0 # kjd 31-1-2014
} # kjd 13-1-2014
standard_error_info = list( included_segment = included_segment , tvar = tvar ) # kjd 31-1-2014
return( standard_error_info )
}
####################################################################################################
#' This function computes various "distances", which are used as penalties for a copy number solution.
#' This function is called when searching for a clonal copy number solution.
#' One such distance is an estimate of the proportion of the tumour genome which is clonal.
#' For each segment of the genome, we test the null hypothesis is that
#' the tumour genome segment in question is "clonal". The alternative hypothesis is that
#' the tumour genome segment in question exhibits "sub-clonal" variation.
#' @noRd
calc_distance <-function( segs, dist_choice, rho, psi, gamma_param, uninformative_BAF_threshold=0.51 ) # kjd 10-2-2014
{
s = segs
if( dist_choice == 0 ) # original ASCAT distance
{
nA = (rho-1-(s[,"b"]-1)*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+s[,"b"]*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
# choose the minor allele
nMinor = NULL
if (sum(nA,na.rm=T) < sum(nB,na.rm=T)) {
nMinor = nA
}
else {
nMinor = nB
}
#d[i,j] = sum(abs(nMinor - pmax(round(nMinor),0))^2 * s[,"length"] * ifelse(s[,"b"]==0.5,0.05,1), na.rm=T)
#DCW 180711 - try weighting BAF=0.5 equally with other points
#dist_value = sum(abs(nMinor - pmax(round(nMinor),0))^2 * s[,"length"], na.rm=T)
#DCW 310314 - retry weighting
dist_value = sum(abs(nMinor - pmax(round(nMinor),0))^2 * s[,"length"] * ifelse(s[,"b"]<=uninformative_BAF_threshold,0.05,1), na.rm=T)
minimise = TRUE
}else if( dist_choice == 1 ){ # new similarity measure suggested by DW 7-3-2014
nA = (rho-1-(s[,"b"]-1)*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+s[,"b"]*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
# choose the minor allele
nMinor = NULL
if (sum(nA,na.rm=T) < sum(nB,na.rm=T)) {
nMinor = nA
}
else {
nMinor = nB
}
#d[i,j] = sum(abs(nMinor - pmax(round(nMinor),0))^2 * s[,"length"] * ifelse(s[,"b"]==0.5,0.05,1), na.rm=T)
#DCW 180711 - try weighting BAF=0.5 equally with other points
# dist_value = sum(abs(nMinor - pmax(round(nMinor),0))^2 * s[,"length"], na.rm=T)
dist_value = sum((0.5-abs(nMinor - pmax(round(nMinor),0)))^2 * s[,"length"], na.rm=T)
minimise = FALSE
}else if( dist_choice == 2 ){ # adapted DW's 7-3-2014 measure by SD 8-8-2014 that takes into account both major and minor alleles
nA = (rho-1-(s[,"b"]-1)*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+s[,"b"]*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
# choose the minor allele
nMinor = NULL
nMajor = NULL
if (sum(nA,na.rm=T) < sum(nB,na.rm=T)) {
nMinor = nA
nMajor = nB
}
else {
nMinor = nB
nMajor = nA
}
dist_value = 0.5*sum(((0.5-abs(nMinor - pmax(round(nMinor),0)))^2 + (0.5-abs(nMajor - pmax(round(nMajor),0)))^2) * s[,"length"], na.rm=T)
minimise = FALSE
}else if( dist_choice == 3 ){ # adapted DW's 7-3-2014 measure by SD 8-8-2014 that takes into account both major and minor alleles and takes the mean, while it also penalises for the number of homozygous deletions
nA = (rho-1-(s[,"b"]-1)*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+s[,"b"]*2^(s[,"r"]/gamma_param)*((1-rho)*2+rho*psi))/rho
# choose the minor allele
nMinor = NULL
nMajor = NULL
if (sum(nA,na.rm=T) < sum(nB,na.rm=T)) {
nMinor = nA
nMajor = nB
}
else {
nMinor = nB
nMajor = nA
}
# Penalise homozygous deletions twice as hard as other segments
# - the penalty term is increased to make it less likely that hom dels occur
# - the segment length is increased to penalise harder for longer segments
segs_penalty = (0.5-abs(nMinor - pmax(round(nMinor),0)))^2 + (0.5-abs(nMajor - pmax(round(nMajor),0)))^2
hom_del = nMinor<0.5 & nMajor<0.5 & nMinor>=0 & nMajor>=0
segs_penalty[which(hom_del)] = segs_penalty[which(hom_del)]*4
dist_value = 0.5*sum(segs_penalty * (s[,"length"] * ifelse(hom_del, 2, 1)), na.rm=T)
minimise = FALSE
}
distance_info = list( distance_value = dist_value , minimise = minimise )
return( distance_info )
}
####################################################################################################
#' This function computes various "distances", which are used as penalties for a copy number solution
#' One such distance is an estimate of the proportion of the tumour genome which is clonal.
#' For each segment of the genome, we test the null hypothesis is that
#' the tumour genome segment in question is "clonal". The alternative hypothesis is that
#' the tumour genome segment in question exhibits "sub-clonal" variation.
#' @noRd
calc_distance_clonal <-function( segs, dist_choice, rho, psi, gamma_param, read_depth, siglevel_BAF, maxdist_BAF, siglevel_LogR, maxdist_LogR, uninformative_BAF_threshold) # kjd 10-2-2014
{
s = segs
pval = NULL
# BAFpvals = vector(length=length(BAFseg))
genome_size = 0
clonal_genome_size = 0
seg_count = 0 # kjd 24-1-2014
clonal_seg_count = 0 # kjd 24-1-2014
n_included_segments = 0 # kjd 31-1-2014
included_genome_size = 0 # kjd 31-1-2014
sum1 = 0 # kjd 31-1-2014
sum2 = 0 # kjd 31-1-2014
sum3 = 0 # kjd 31-1-2014
sum_ln_lratio = 0 # kjd 10-2-2014
max_clonal_segment = 0 # There may be no clonal segments, in which case this remains zero.
max_clonal_segment_size = 0
ref_maj = NA
ref_min = NA
for(i in 1:nrow(s)) {
BAFreq = s[ i, "b" ] # l = BAFlevels[i]
if( BAFreq > uninformative_BAF_threshold )
{
LogR = s[ i, "r" ]
BAF.length = s[ i, "length" ]
BAF.size = s[ i, "size" ]
BAF.mean = s[ i, "mean" ]
BAF.sd = s[ i, "sd" ]
#
# Calculate P values
#
segment_info = is.segment.clonal( LogR, BAFreq, BAF.length, BAF.size, BAF.mean, BAF.sd, read_depth, rho, psi, gamma_param, siglevel_BAF, maxdist_BAF, siglevel_LogR, maxdist_LogR ) # kjd 21-2-2014
is.clonal = segment_info$is.clonal # kjd 21-2-2014
nMaj = segment_info$nMaj
nMin = segment_info$nMin
is.balanced = segment_info$balanced
segment_size = BAF.length # OR segment_size = BAF.size ?
genome_size = genome_size + segment_size
seg_count = seg_count + 1 # kjd 24-1-2014
# if( pval[i] > siglevel_BAF ){
if(is.clonal){ # kjd 21-2-2014
clonal_genome_size = clonal_genome_size + segment_size
clonal_seg_count = clonal_seg_count + 1 # kjd 24-1-2014
if( max_clonal_segment_size < segment_size & !is.balanced) #balanced check added by DCW 160314
{
max_clonal_segment = i
max_clonal_segment_size = segment_size
ref_maj = nMaj
ref_min = nMin
}
}
#
# Calculate "standardised error"
#
standard_error_info = calc_standardised_error( LogR, BAFreq, BAF.length, BAF.size, BAF.mean, BAF.sd, rho, psi, gamma_param, maxdist_BAF ) # kjd 31-1-2014
included_segment = standard_error_info$included_segment # kjd 31-1-2014
tvar = standard_error_info$tvar # kjd 31-1-2014
n_included_segments = n_included_segments + included_segment # kjd 31-1-2014
if( included_segment > 0 )
{
included_genome_size = included_genome_size + segment_size # kjd 31-1-2014
}
sum1 = sum1 + tvar^2 # kjd 31-1-2014
sum2 = sum2 + ( BAFreq - BAF.mean )^2
sum3 = sum3 + ( segment_size * ( BAFreq - BAF.mean )^2 )
#
# Calculate log likelihood ratio
#
ln_lratio = calc_ln_likelihood_ratio( LogR, BAFreq, BAF.length, BAF.size, BAF.mean, read_depth, rho, psi, gamma_param, maxdist_BAF ) # kjd 10-2-2014
sum_ln_lratio = sum_ln_lratio + ln_lratio
}
}
#
# Calculate proportion of genome which is "clonal":
#
clonal_proportion = 0
if( genome_size > 0 ){
clonal_proportion = clonal_genome_size / genome_size
}
#
# Calculate "distances":
#
dist1 = 0 # kjd 3-2-2014
if( n_included_segments > 0 ){
dist1 = sum1 / n_included_segments
} # kjd 3-2-2014
dist2 = 0 # kjd 3-2-2014
if( seg_count > 0 ){
dist2 = sum2 / seg_count
} # kjd 3-2-2014
dist3 = 0 # kjd 3-2-2014
if( genome_size > 0 ){
dist3 = sum3 / genome_size
} # kjd 3-2-2014
if( dist_choice == 0 )
{
dist_value = clonal_proportion
minimise = FALSE
}
if( dist_choice == 1 )
{
dist_value = dist1
minimise = TRUE
}
if( dist_choice == 2 )
{
dist_value = dist2
minimise = TRUE
}
if( dist_choice == 3 )
{
dist_value = dist3
minimise = TRUE
}
if( dist_choice == 4 )
{
dist_value = sum_ln_lratio
minimise = FALSE
}
distance_info = list( distance_value = dist_value , minimise = minimise , max_clonal_segment = max_clonal_segment, ref_maj = ref_maj, ref_min = ref_min ) # kjd 10-2-2014
# return( clonal_proportion ) # kjd 24-1-2014
return( distance_info ) # kjd 10-2-2014
}
#' Function extends the ASCAT \code{make_segments} function to make segments
#' of constant BAF and LogR. This function returns a matrix with for each
#' segment the LogR, BAF, the length of the segment (twice), and the mean and
#' standard deviation of the BAF values
#' @noRd
get_segment_info = function(segLogR , segBAF.table) {
segBAF = segBAF.table[,5]
names(segBAF) = rownames(segBAF.table)
names(segLogR) = rownames(segBAF.table)
b = segBAF
r = segLogR[names(segBAF)]
pcf_segments = ASCAT::make_segments(r,b)
# m = matrix(ncol = 2, nrow = length(b))
# m[,1] = r
# m[,2] = b
# m = as.matrix(na.omit(m))
# pcf_segments = matrix(ncol = 3, nrow = dim(m)[1])
# colnames(pcf_segments) = c("r","b","length");
# index = 0;
# previousb = -1;
# previousr = 1E10;
# for (i in 1:dim(m)[1]) {
# if (m[i,2] != previousb || m[i,1] != previousr) {
# index=index+1;
# count=1;
# pcf_segments[index, "r"] = m[i,1];
# pcf_segments[index, "b"] = m[i,2];
# }
# else {
# count = count + 1;
# }
# pcf_segments[index, "length"] = count;
# previousb = m[i,2];
# previousr = m[i,1];
# }
#
# # pcf_segments = as.matrix(na.omit(pcf_segments))[,] # kjd 10-1-2014 This version caused bug in R on laptop.
# pcf_segments = as.matrix(na.omit(pcf_segments)) # kjd 10-1-2014 This version resolved bug in R on laptop. (Problem with installed version of R?)
#
segs = matrix(ncol = 6, nrow = nrow(pcf_segments))
colnames(segs) = c("r","b","length","size", "mean", "sd")
segs[ , c("r","b","length")] = pcf_segments
for( i in 1:nrow(segs) ) {
BAFreq = segs[i, "b"] # l = BAFlevels[i]
index_vect = which( segBAF.table[ , 5] == BAFreq )
BAFke = segBAF.table[index_vect, 4] # column 4 contains "phased BAF" values; # kjd 6-1-2014
segs[i, "size"] = length(BAFke)
segs[i, "mean"] = mean(BAFke)
segs[i, "sd"] = sd(BAFke)
}
return(segs);
}
####################################################################################################
#' Helper function to find new rho and psi boundaries given a current optimum pair.
#' @noRd
get_new_bounds = function( input_optimum_pair, ininitial_bounds ) # kjd 21-2-2014
{
psi_optimum = input_optimum_pair$psi
rho_optimum = input_optimum_pair$rho
psi_min_initial = ininitial_bounds$psi_min
psi_max_initial = ininitial_bounds$psi_max
rho_min_initial = ininitial_bounds$rho_min
rho_max_initial = ininitial_bounds$rho_max
psi_range = 0.1 * ( psi_max_initial - psi_min_initial )
#rho_range = 0.1 * ( rho_max_initial - rho_min_initial )
#DCW 170314 - rho range depends on optimum value of rho
rho_range = 0.1 * rho_optimum
if( (psi_optimum - 0.5 * psi_range) < psi_min_initial )
{
psi_min = psi_min_initial
psi_max = psi_min_initial + psi_range
}else
{
if( (psi_optimum + 0.5 * psi_range) > psi_max_initial )
{
psi_min = psi_max_initial - psi_range
psi_max = psi_max_initial
}else
{
psi_min = psi_optimum - 0.5 * psi_range
psi_max = psi_optimum + 0.5 * psi_range
}
}
if( (rho_optimum - 0.5 * rho_range) < rho_min_initial )
{
rho_min = rho_min_initial
rho_max = rho_min_initial + rho_range
}else
{
if( (rho_optimum + 0.5 * rho_range) > rho_max_initial )
{
rho_min = rho_max_initial - rho_range
rho_max = rho_max_initial
}else
{
rho_min = rho_optimum - 0.5 * rho_range
rho_max = rho_optimum + 0.5 * rho_range
}
}
new_bounds = list( psi_min = psi_min, psi_max = psi_max, rho_min = rho_min, rho_max = rho_max )
return( new_bounds )
}
####################################################################################################
#' function to create the distance matrix (distance for a range of ploidy and tumor percentage values)
#' input: segmented LRR and BAF and the value for gamma_param
#' @noRd
create_distance_matrix = function(s, dist_choice, gamma_param, uninformative_BAF_threshold=0.51, min_rho=0.1, max_rho=1, min_psi=1, max_psi=5.4) {
psi_pos = seq(min_psi,max_psi,0.05)
rho_pos = seq(min_rho,max_rho,0.01)
d = matrix(nrow = length(psi_pos), ncol = length(rho_pos))
rownames(d) = psi_pos
colnames(d) = rho_pos
dmin = 1E20;
for(i in 1:length(psi_pos)) {
psi = psi_pos[i]
for(j in 1:length(rho_pos)) {
rho = rho_pos[j]
distance_info = calc_distance( s, dist_choice, rho, psi, gamma_param, uninformative_BAF_threshold=uninformative_BAF_threshold ) # kjd 10-2-2014
d[i,j] = distance_info$distance_value
# minimise = distance_info$minimise
}
}
minimise = distance_info$minimise
distance_matrix_info = list( distance_matrix = d , minimise = minimise )
# return(d)
return( distance_matrix_info )
}
#' Helper function to create the clonal distance matrix for a range of
#' rho and psi values
#' @noRd
create_distance_matrix_clonal = function( segs, dist_choice, gamma_param, read_depth, siglevel_BAF, maxdist_BAF, siglevel_LogR, maxdist_LogR, uninformative_BAF_threshold, new_bounds) # kjd 18-12-2013
{
psi_min = new_bounds$psi_min
psi_max = new_bounds$psi_max
rho_min = new_bounds$rho_min
rho_max = new_bounds$rho_max
s = segs
psi_range = psi_max - psi_min
rho_range = rho_max - rho_min
delta_psi = psi_range / 100
delta_rho = rho_range / 100
psi_pos = seq( psi_min, psi_max, delta_psi )
rho_pos = seq( rho_min, rho_max, delta_rho )
# psi_pos = seq(1,5.4,0.05)
# rho_pos = seq(0.1,1.05,0.01)
ref_seg_matrix = matrix(nrow = length(psi_pos), ncol = length(rho_pos))
ref_major = matrix(nrow = length(psi_pos), ncol = length(rho_pos))
ref_minor = matrix(nrow = length(psi_pos), ncol = length(rho_pos))
rownames(ref_seg_matrix) = psi_pos