-
Notifications
You must be signed in to change notification settings - Fork 8
/
ASCAT.R
executable file
·2496 lines (2159 loc) · 88.9 KB
/
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
# TODO: Add comment
#
# Author: FWang9
###############################################################################
# ASCAT 2.4.3
# author: Peter Van Loo
# PCF and ASPCF: Gro Nilsen
# GC correction: Jiqiu Cheng
#' @title ascat.loadData
#' @description Function to read in SNP array data
#' @details germline data files can be NULL - in that case these are not read in
#' @param Tumor_LogR_file file containing logR of tumour sample(s)
#' @param Tumor_BAF_file file containing BAF of tumour sample(s)
#' @param Germline_LogR_file file containing logR of germline sample(s), NULL
#' @param Germline_BAF_file file containing BAF of germline sample(s), NULL
#' @param chrs a vector containing the names for the chromosomes (e.g. c(1:22,"X"))
#' @param gender a vector of gender for each cases ("XX" or "XY"). Default = all female ("XX")
#' @param sexchromosomes a vector containing the names for the sex chromosomes
#'
#' @return ascat data structure containing:\cr
#' 1. Tumor_LogR data matrix\cr
#' 2. Tumor_BAF data matrix\cr
#' 3. Tumor_LogR_segmented: placeholder, NULL\cr
#' 4. Tumor_BAF_segmented: placeholder, NULL\cr
#' 5. Germline_LogR data matrix\cr
#' 6. Germline_BAF data matrix\cr
#' 7. SNPpos: position of all SNPs\cr
#' 8. ch: a list containing vectors with the indices for each chromosome (e.g. Tumor_LogR[ch[[13]],] will output the Tumor_LogR data of chromosome 13\cr
#' 9. chr: a list containing vectors with the indices for each distinct part that can be segmented separately (e.g. chromosome arm, stretch of DNA between gaps in the array design)\cr
#' 10. gender: a vector of gender for each cases ("XX" or "XY"). Default = NULL: all female ("XX")\cr
#'
#' @export
#'
ascat.loadData = function(Tumor_LogR_file, Tumor_BAF_file, Germline_LogR_file = NULL, Germline_BAF_file = NULL, chrs = c(1:22,"X","Y"), gender = NULL, sexchromosomes = c("X","Y")) {
# read in SNP array data files
print.noquote("Reading Tumor LogR data...")
Tumor_LogR <- read.table(Tumor_LogR_file, header=T, row.names=1, comment.char="", sep = "\t", check.names=F)
print.noquote("Reading Tumor BAF data...")
Tumor_BAF <- read.table(Tumor_BAF_file, header=T, row.names=1, comment.char="", sep = "\t", check.names=F)
#infinite values are a problem - change those
Tumor_LogR[Tumor_LogR==-Inf]=NA
Tumor_LogR[Tumor_LogR==Inf]=NA
Germline_LogR = NULL
Germline_BAF = NULL
if(!is.null(Germline_LogR_file)) {
print.noquote("Reading Germline LogR data...")
Germline_LogR <- read.table(Germline_LogR_file, header=T, row.names=1, comment.char="", sep = "\t", check.names=F)
print.noquote("Reading Germline BAF data...")
Germline_BAF <- read.table(Germline_BAF_file, header=T, row.names=1, comment.char="", sep = "\t", check.names=F)
#infinite values are a problem - change those
Germline_LogR[Germline_LogR==-Inf]=NA
Germline_LogR[Germline_LogR==Inf]=NA
}
# make SNPpos vector that contains genomic position for all SNPs and remove all data not on chromosome 1-22,X,Y (or whatever is given in the input value of chrs)
print.noquote("Registering SNP locations...")
SNPpos <- Tumor_LogR[,1:2]
SNPpos = SNPpos[SNPpos[,1]%in%chrs,]
# if some chromosomes have no data, just remove them
chrs = intersect(chrs,unique(SNPpos[,1]))
Tumor_LogR = Tumor_LogR[rownames(SNPpos),c(-1,-2),drop=F]
Tumor_BAF = Tumor_BAF[rownames(SNPpos),c(-1,-2),drop=F]
# make sure it is all converted to numerical values
for (cc in 1:dim(Tumor_LogR)[2]) {
Tumor_LogR[,cc]=as.numeric(as.vector(Tumor_LogR[,cc]))
Tumor_BAF[,cc]=as.numeric(as.vector(Tumor_BAF[,cc]))
}
if(!is.null(Germline_LogR_file)) {
Germline_LogR = Germline_LogR[rownames(SNPpos),c(-1,-2),drop=F]
Germline_BAF = Germline_BAF[rownames(SNPpos),c(-1,-2),drop=F]
for (cc in 1:dim(Germline_LogR)[2]) {
Germline_LogR[,cc]=as.numeric(as.vector(Germline_LogR[,cc]))
Germline_BAF[,cc]=as.numeric(as.vector(Germline_BAF[,cc]))
}
}
# sort all data by genomic position
last = 0;
ch = list();
SNPorder = vector(length=dim(SNPpos)[1])
for (i in 1:length(chrs)) {
chrke = SNPpos[SNPpos[,1]==chrs[i],]
chrpos = chrke[,2]
names(chrpos) = rownames(chrke)
chrpos = sort(chrpos)
ch[[i]] = (last+1):(last+length(chrpos))
SNPorder[ch[[i]]] = names(chrpos)
last = last+length(chrpos)
}
SNPpos = SNPpos[SNPorder,]
Tumor_LogR=Tumor_LogR[SNPorder,,drop=F]
Tumor_BAF=Tumor_BAF[SNPorder,,drop=F]
if(!is.null(Germline_LogR_file)) {
Germline_LogR = Germline_LogR[SNPorder,,drop=F]
Germline_BAF = Germline_BAF[SNPorder,,drop=F]
}
# split the genome into distinct parts to be used for segmentation (e.g. chromosome arms, parts of genome between gaps in array design)
print.noquote("Splitting genome in distinct chunks...")
chr = split_genome(SNPpos)
if (is.null(gender)) {
gender = rep("XX",dim(Tumor_LogR)[2])
}
return(list(Tumor_LogR = Tumor_LogR, Tumor_BAF = Tumor_BAF,
Tumor_LogR_segmented = NULL, Tumor_BAF_segmented = NULL,
Germline_LogR = Germline_LogR, Germline_BAF = Germline_BAF,
SNPpos = SNPpos, ch = ch, chr = chr, chrs = chrs,
samples = colnames(Tumor_LogR), gender = gender,
sexchromosomes = sexchromosomes,
failedarrays = NULL))
}
#' @title ascat.plotRawData
#' @description Plots SNP array data
#' @param ASCATobj an ASCAT object (e.g. data structure from ascat.loadData)
#'
#' @return Produces png files showing the logR and BAF values for tumour and germline samples
#'
#' @export
ascat.plotRawData = function(ASCATobj) {
print.noquote("Plotting tumor data")
for (i in 1:dim(ASCATobj$Tumor_LogR)[2]) {
png(filename = paste(ASCATobj$samples[i],".tumour.png",sep=""), width = 2000, height = 1000, res = 200)
par(mar = c(0.5,5,5,0.5), mfrow = c(2,1), cex = 0.4, cex.main=3, cex.axis = 2, pch = ifelse(dim(ASCATobj$Tumor_LogR)[1]>100000,".",20))
plot(c(1,dim(ASCATobj$Tumor_LogR)[1]), c(-1,1), type = "n", xaxt = "n", main = paste(ASCATobj$samples[i], ", tumor data, LogR", sep = ""), xlab = "", ylab = "")
points(ASCATobj$Tumor_LogR[,i],col="red")
#points(ASCATobj$Tumor_LogR[,i],col=rainbow(24)[ASCATobj$SNPpos$Chr])
abline(v=0.5,lty=1,col="lightgrey")
chrk_tot_len = 0
for (j in 1:length(ASCATobj$ch)) {
chrk = ASCATobj$ch[[j]];
chrk_tot_len_prev = chrk_tot_len
chrk_tot_len = chrk_tot_len + length(chrk)
vpos = chrk_tot_len;
tpos = (chrk_tot_len+chrk_tot_len_prev)/2;
text(tpos,1,ASCATobj$chrs[j], pos = 1, cex = 2)
abline(v=vpos+0.5,lty=1,col="lightgrey")
}
plot(c(1,dim(ASCATobj$Tumor_BAF)[1]), c(0,1), type = "n", xaxt = "n", main = paste(ASCATobj$samples[i], ", tumor data, BAF", sep = ""), xlab = "", ylab = "")
points(ASCATobj$Tumor_BAF[,i],col="red")
abline(v=0.5,lty=1,col="lightgrey")
chrk_tot_len = 0
for (j in 1:length(ASCATobj$ch)) {
chrk = ASCATobj$ch[[j]];
chrk_tot_len_prev = chrk_tot_len
chrk_tot_len = chrk_tot_len + length(chrk)
vpos = chrk_tot_len;
tpos = (chrk_tot_len+chrk_tot_len_prev)/2;
text(tpos,1,ASCATobj$chrs[j], pos = 1, cex = 2)
abline(v=vpos+0.5,lty=1,col="lightgrey")
}
dev.off()
}
if(!is.null(ASCATobj$Germline_LogR)) {
print.noquote("Plotting germline data")
for (i in 1:dim(ASCATobj$Germline_LogR)[2]) {
png(filename = paste(ASCATobj$samples[i],".germline.png",sep=""), width = 2000, height = 1000, res = 200)
par(mar = c(0.5,5,5,0.5), mfrow = c(2,1), cex = 0.4, cex.main=3, cex.axis = 2, pch = ifelse(dim(ASCATobj$Tumor_LogR)[1]>100000,".",20))
plot(c(1,dim(ASCATobj$Germline_LogR)[1]), c(-1,1), type = "n", xaxt = "n", main = paste(ASCATobj$samples[i], ", germline data, LogR", sep = ""), xlab = "", ylab = "")
points(ASCATobj$Germline_LogR[,i],col="red")
abline(v=0.5,lty=1,col="lightgrey")
chrk_tot_len = 0
for (j in 1:length(ASCATobj$ch)) {
chrk = ASCATobj$ch[[j]];
chrk_tot_len_prev = chrk_tot_len
chrk_tot_len = chrk_tot_len + length(chrk)
vpos = chrk_tot_len;
tpos = (chrk_tot_len+chrk_tot_len_prev)/2;
text(tpos,1,ASCATobj$chrs[j], pos = 1, cex = 2)
abline(v=vpos+0.5,lty=1,col="lightgrey")
}
plot(c(1,dim(ASCATobj$Germline_BAF)[1]), c(0,1), type = "n", xaxt = "n", main = paste(ASCATobj$samples[i], ", germline data, BAF", sep = ""), xlab = "", ylab = "")
points(ASCATobj$Germline_BAF[,i],col="red")
abline(v=0.5,lty=1,col="lightgrey")
chrk_tot_len = 0
for (j in 1:length(ASCATobj$ch)) {
chrk = ASCATobj$ch[[j]];
chrk_tot_len_prev = chrk_tot_len
chrk_tot_len = chrk_tot_len + length(chrk)
vpos = chrk_tot_len;
tpos = (chrk_tot_len+chrk_tot_len_prev)/2;
text(tpos,1,ASCATobj$chrs[j], pos = 1, cex = 2)
abline(v=vpos+0.5,lty=1,col="lightgrey")
}
dev.off()
}
}
}
#' @title ascat.GCcorrect
#' @description Corrects logR of the tumour sample(s) with genomic GC content
#' @param ASCATobj an ASCAT object
#' @param GCcontentfile File containing the GC content around every SNP for increasing window sizes
#' @details Note that probes not present in the GCcontentfile will be lost from the results
#' @return ASCAT object with corrected tumour logR
#'
#' @export
ascat.GCcorrect = function(ASCATobj, GCcontentfile = NULL) {
if(is.null(GCcontentfile)) {
print.noquote("Error: no GC content file given!")
}
else {
GC_newlist<-read.table(file=GCcontentfile,header=TRUE,as.is=TRUE)
colnames(GC_newlist)[c(1,2)] = c("Chr","Position")
GC_newlist$Chr<-as.character(GC_newlist$Chr)
GC_newlist$Position<-as.numeric(as.character(GC_newlist$Position))
ovl = intersect(row.names(ASCATobj$Tumor_LogR),row.names(GC_newlist))
GC_newlist<-GC_newlist[ovl,]
SNPpos = ASCATobj$SNPpos[ovl,]
Tumor_LogR = ASCATobj$Tumor_LogR[ovl,,drop=F]
Tumor_BAF = ASCATobj$Tumor_BAF[ovl,,drop=F]
chrs = intersect(ASCATobj$chrs,unique(SNPpos[,1]))
Germline_LogR = NULL
Germline_BAF = NULL
if(!is.null(ASCATobj$Germline_LogR)) {
Germline_LogR = ASCATobj$Germline_LogR[ovl,,drop=F]
Germline_BAF = ASCATobj$Germline_BAF[ovl,,drop=F]
}
last = 0;
ch = list();
for (i in 1:length(ASCATobj$chrs)) {
chrke = SNPpos[SNPpos[,1]==ASCATobj$chrs[i],]
chrpos = chrke[,2]
names(chrpos) = rownames(chrke)
chrpos = sort(chrpos)
ch[[i]] = (last+1):(last+length(chrpos))
last = last+length(chrpos)
}
for (s in 1:length(ASCATobj$samples)) {
print.noquote(paste("Sample ", ASCATobj$samples[s], " (",s,"/",length(ASCATobj$samples),")",sep=""))
Tumordata = Tumor_LogR[,s]
names(Tumordata) = rownames(Tumor_LogR)
# Calculate weighted correlation
length_tot<-NULL
corr_tot<-NULL
for(chrindex in unique(SNPpos[,1])) {
GC_newlist_chr<-GC_newlist[GC_newlist$Chr==chrindex,]
td_chr<-Tumordata[GC_newlist$Chr==chrindex]
flag_nona<-(complete.cases(td_chr) & complete.cases(GC_newlist_chr))
#only work with chromosomes that have variance
if(length(td_chr[flag_nona])>0 & var(td_chr[flag_nona])>0){
corr<-cor(GC_newlist_chr[flag_nona,3:ncol(GC_newlist_chr)],td_chr[flag_nona])
corr_tot<-cbind(corr_tot,corr)
length_tot<-c(length_tot,length(td_chr))
}
}
corr<-apply(corr_tot,1,function(x) sum(abs(x*length_tot))/sum(length_tot))
index_1M<-c(which(names(corr)=="X1M"),which(names(corr)=="X1Mb"))
maxGCcol_short<-which(corr[1:(index_1M-1)]==max(corr[1:(index_1M-1)]))
maxGCcol_long<-which(corr[index_1M:length(corr)]==max(corr[index_1M:length(corr)]))
maxGCcol_long<-(maxGCcol_long+(index_1M-1))
cat("weighted correlation: ",paste(names(corr),format(corr,digits=2), ";"),"\n")
cat("Short window size: ",names(GC_newlist)[maxGCcol_short+2],"\n")
cat("Long window size: ",names(GC_newlist)[maxGCcol_long+2],"\n")
# Multiple regression
flag_NA<-(is.na(Tumordata))|(is.na(GC_newlist[,2+maxGCcol_short]))|(is.na(GC_newlist[,2+maxGCcol_long]))
td_select<-Tumordata[!flag_NA]
GC_newlist_select <- GC_newlist[!flag_NA,]
x1<-GC_newlist_select[,2+maxGCcol_short]
x2<-GC_newlist_select[,2+maxGCcol_long]
x3<-(x1)^2
x4<-(x2)^2
model<-lm(td_select~x1+x2+x3+x4,y=TRUE)
GCcorrected<-Tumordata
GCcorrected[]<-NA
GCcorrected[!flag_NA] <- model$residuals
Tumor_LogR[,s] = GCcorrected
chr = split_genome(SNPpos)
}
# add some plotting code for each sample while it is generated!!!!
return(list(Tumor_LogR = Tumor_LogR, Tumor_BAF = Tumor_BAF,
Tumor_LogR_segmented = NULL, Tumor_BAF_segmented = NULL,
Germline_LogR = Germline_LogR, Germline_BAF = Germline_BAF,
SNPpos = SNPpos, ch = ch, chr = chr, chrs = chrs,
samples = colnames(Tumor_LogR), gender = ASCATobj$gender,
sexchromosomes = ASCATobj$sexchromosomes))
}
}
#' @title ascat.aspcf
#' @description run ASPCF segmentation
#' @details This function can be easily parallelised by controlling the selectsamples parameter\cr
#' it saves the results in LogR_PCFed[sample]_[segment].txt and BAF_PCFed[sample]_[segment].txt
#' @param ASCATobj an ASCAT object
#' @param selectsamples a vector containing the sample number(s) to PCF. Default = all
#' @param ascat.gg germline genotypes (NULL if germline data is available)
#' @param penalty penalty of introducing an additional ASPCF breakpoint (expert parameter, don't adapt unless you know what you're doing)
#'
#' @return output: ascat data structure containing:\cr
#' 1. Tumor_LogR data matrix\cr
#' 2. Tumor_BAF data matrix\cr
#' 3. Tumor_LogR_segmented: matrix of LogR segmented values\cr
#' 4. Tumor_BAF_segmented: list of BAF segmented values; each element in the list is a matrix containing the segmented values for one sample (only for probes that are germline homozygous)\cr
#' 5. Germline_LogR data matrix\cr
#' 6. Germline_BAF data matrix\cr
#' 7. SNPpos: position of all SNPs\cr
#' 8. ch: a list containing vectors with the indices for each chromosome (e.g. Tumor_LogR[ch[[13]],] will output the Tumor_LogR data of chromosome 13\cr
#' 9. chr: a list containing vectors with the indices for each distinct part that can be segmented separately (e.g. chromosome arm, stretch of DNA between gaps in the array design)\cr
#'
#' @export
#'
ascat.aspcf = function(ASCATobj, selectsamples = 1:length(ASCATobj$samples), ascat.gg = NULL, penalty = 25) {
#first, set germline genotypes
gg = NULL
if(!is.null(ascat.gg)) {
gg = ascat.gg$germlinegenotypes
}
else {
gg = ASCATobj$Germline_BAF < 0.3 | ASCATobj$Germline_BAF > 0.7
}
# calculate germline homozygous stretches for later resegmentation
ghs = predictGermlineHomozygousStretches(ASCATobj$chr, gg)
segmentlengths = unique(c(penalty,25,50,100,200,400,800))
segmentlengths = segmentlengths[segmentlengths>=penalty]
Tumor_LogR_segmented = matrix(nrow = dim(ASCATobj$Tumor_LogR)[1], ncol = dim(ASCATobj$Tumor_LogR)[2])
rownames(Tumor_LogR_segmented) = rownames(ASCATobj$Tumor_LogR)
colnames(Tumor_LogR_segmented) = colnames(ASCATobj$Tumor_LogR)
Tumor_BAF_segmented = list();
for (sample in selectsamples) {
print.noquote(paste("Sample ", ASCATobj$samples[sample], " (",sample,"/",length(ASCATobj$samples),")",sep=""))
logrfilename = paste(ASCATobj$samples[sample],".LogR.PCFed.txt",sep="")
baffilename = paste(ASCATobj$samples[sample],".BAF.PCFed.txt",sep="")
logRPCFed = numeric(0)
bafPCFed = numeric(0)
for (segmentlength in segmentlengths) {
logRPCFed = numeric(0)
bafPCFed = numeric(0)
tbsam = ASCATobj$Tumor_BAF[,sample]
names(tbsam) = rownames(ASCATobj$Tumor_BAF)
homosam = gg[,sample]
for (chrke in 1:length(ASCATobj$chr)) {
lr = ASCATobj$Tumor_LogR[ASCATobj$chr[[chrke]],sample]
#winsorize to remove outliers
#this has a problem with NAs
lrwins = vector(mode="numeric",length=length(lr))
lrwins[is.na(lr)] = NA
lrwins[!is.na(lr)] = madWins(lr[!is.na(lr)],2.5,25)$ywin
baf = tbsam[ASCATobj$chr[[chrke]]]
homo = homosam[ASCATobj$chr[[chrke]]]
Select_het <- !homo & !is.na(homo) & !is.na(baf) & !is.na(lr)
bafsel = baf[Select_het]
# winsorize BAF as well (as a safeguard)
bafselwinsmirrored = madWins(ifelse(bafsel>0.5,bafsel,1-bafsel),2.5,25)$ywin
bafselwins = ifelse(bafsel>0.5,bafselwinsmirrored,1-bafselwinsmirrored)
indices = which(Select_het)
logRaveraged = NULL;
if(length(indices)!=0) {
averageIndices = c(1,(indices[1:(length(indices)-1)]+indices[2:length(indices)])/2,length(lr)+0.01)
startindices = ceiling(averageIndices[1:(length(averageIndices)-1)])
endindices = floor(averageIndices[2:length(averageIndices)]-0.01)
if(length(indices)==1) {
startindices = 1
endindices = length(lr)
}
nrIndices = endindices - startindices + 1
logRaveraged = vector(mode="numeric",length=length(indices))
for(i in 1:length(indices)) {
if(is.na(endindices[i])) {
endindices[i]=startindices[i]
}
logRaveraged[i]=mean(lrwins[startindices[i]:endindices[i]], na.rm=T)
}
}
# if there are no probes in the segment (after germline homozygous removal), don't do anything, except add a LogR segment
if(length(logRaveraged)>0) {
logRASPCF = NULL
bafASPCF = NULL
if(length(logRaveraged)<6) {
logRASPCF = rep(mean(logRaveraged),length(logRaveraged))
bafASPCF = rep(mean(bafselwins),length(logRaveraged))
}
else {
PCFed = fastAspcf(logRaveraged,bafselwins,6,segmentlength)
logRASPCF = PCFed$yhat1
bafASPCF = PCFed$yhat2
}
names(bafASPCF)=names(indices)
logRc = numeric(0)
for(probe in 1:length(logRASPCF)) {
if(probe == 1) {
logRc = rep(logRASPCF[probe],indices[probe])
}
# if probe is 1, set the beginning, and let the loop go:
if(probe == length(logRASPCF)) {
logRc = c(logRc,rep(logRASPCF[probe],length(lr)-indices[probe]))
}
else if(logRASPCF[probe]==logRASPCF[probe+1]) {
logRc = c(logRc, rep(logRASPCF[probe],indices[probe+1]-indices[probe]))
}
else {
#find best breakpoint
d = numeric(0)
totall = indices[probe+1]-indices[probe]
for (bp in 0:(totall-1)) {
dis = sum(abs(lr[(1:bp)+indices[probe]]-logRASPCF[probe]), na.rm=T)
if(bp!=totall) {
dis = sum(dis, sum(abs(lr[((bp+1):totall)+indices[probe]]-logRASPCF[probe+1]), na.rm=T), na.rm=T)
}
d = c(d,dis)
}
breakpoint = which.min(d)-1
logRc = c(logRc,rep(logRASPCF[probe],breakpoint),rep(logRASPCF[probe+1],totall-breakpoint))
}
}
#2nd step: adapt levels!
logRd = numeric(0)
seg = rle(logRc)$lengths
startprobe = 1
endprobe = 0
for (i in 1:length(seg)) {
endprobe = endprobe+seg[i]
level = mean(lr[startprobe:endprobe], na.rm=T)
logRd = c(logRd, rep(level,seg[i]))
startprobe = startprobe + seg[i]
}
logRPCFed = c(logRPCFed,logRd)
bafPCFed = c(bafPCFed,bafASPCF)
}
# add a LogR segment
else {
level = mean(lr,na.rm=T)
reps = length(lr)
logRPCFed = c(logRPCFed,rep(level,reps))
}
# correct wrong segments in germline homozygous stretches:
homsegs = ghs[[sample]][ghs[[sample]][,1]==chrke,]
startchr = min(ASCATobj$chr[[chrke]])
endchr = max(ASCATobj$chr[[chrke]])
# to solve an annoying error when homsegs has length 1:
if(length(homsegs)==3) {
homsegs=t(as.matrix(homsegs))
}
if(!is.null(homsegs)&&!is.na(homsegs)&&dim(homsegs)[1]!=0) {
for (i in 1:dim(homsegs)[1]) {
# note that only the germline homozygous segment is resegmented, plus a bit extra (but this is NOT replaced)
startpos = max(homsegs[i,2],startchr)
endpos = min(homsegs[i,3],endchr)
# PCF over a larger fragment
startpos2 = max(homsegs[i,2]-100,startchr)
endpos2 = min(homsegs[i,3]+100,endchr)
# take into account a little extra (difference between startpos2 and startpos3 is not changed)
startpos3 = max(homsegs[i,2]-5,startchr)
endpos3 = min(homsegs[i,3]+5,endchr)
# note that the parameters are arbitrary, but <100 seems to work on the ERBB2 example!
# segmentlength is lower here, as in the full data, noise on LogR is higher!
# do this on Winsorized data too!
towins = ASCATobj$Tumor_LogR[startpos2:endpos2,sample]
winsed = madWins(towins[!is.na(towins)],2.5,25)$ywin
pcfed = vector(mode="numeric",length=length(towins))
pcfed[!is.na(towins)] = exactPcf(winsed,6,floor(segmentlength/4))
pcfed2 = pcfed[(startpos3-startpos2+1):(endpos3-startpos2+1)]
dif = abs(pcfed2-logRPCFed[startpos3:endpos3])
#0.3 is hardcoded here, in order not to have too many segments!
#only replace if enough probes differ (in order not to get singular probes with different breakpoints)
if(!is.na(dif)&&sum(dif>0.3)>5) {
#replace a bit more to make sure no 'lone' probes are left (startpos3 instead of startpos)
logRPCFed[startpos3:endpos3]=ifelse(dif>0.3,pcfed2,logRPCFed[startpos3:endpos3])
}
}
}
}
#fill in NAs (otherwise they cause problems):
#some NA probes are filled in with zero, replace those too:
nakes = c(which(is.na(logRPCFed)),which(logRPCFed==0))
nonnakes = which(!is.na(logRPCFed)&!(logRPCFed==0))
if(length(nakes)>0) {
for (nake in 1:length(nakes)) {
pna = nakes[nake]
closestnonna = which.min(abs(nonnakes-pna))
logRPCFed[pna] = logRPCFed[closestnonna]
}
}
#adapt levels again
seg = rle(logRPCFed)$lengths
logRPCFed = numeric(0)
startprobe = 1
endprobe = 0
prevlevel = 0
for (i in 1:length(seg)) {
endprobe = endprobe+seg[i]
level = mean(ASCATobj$Tumor_LogR[startprobe:endprobe,sample], na.rm=T)
#making sure no NA's get filled in...
if(is.nan(level)) {
level=prevlevel
}
else {
prevlevel=level
}
logRPCFed = c(logRPCFed, rep(level,seg[i]))
startprobe = startprobe + seg[i]
}
#put in names and write results to files
names(logRPCFed) = rownames(ASCATobj$Tumor_LogR)
# if less than 800 segments: this segmentlength is ok, otherwise, rerun with higher segmentlength
if(length(unique(logRPCFed))<800) {
break
}
}
write.table(logRPCFed,logrfilename,sep="\t",col.names=F)
write.table(bafPCFed,baffilename,sep="\t",col.names=F)
bafPCFed = as.matrix(bafPCFed)
Tumor_LogR_segmented[,sample] = logRPCFed
Tumor_BAF_segmented[[sample]] = 1-bafPCFed
}
ASCATobj = list(Tumor_LogR = ASCATobj$Tumor_LogR,
Tumor_BAF = ASCATobj$Tumor_BAF,
Tumor_LogR_segmented = Tumor_LogR_segmented,
Tumor_BAF_segmented = Tumor_BAF_segmented,
Germline_LogR = ASCATobj$Germline_LogR,
Germline_BAF = ASCATobj$Germline_BAF,
SNPpos = ASCATobj$SNPpos,
ch = ASCATobj$ch,
chr = ASCATobj$chr,
chrs = ASCATobj$chrs,
samples = colnames(ASCATobj$Tumor_LogR), gender = ASCATobj$gender,
sexchromosomes = ASCATobj$sexchromosomes, failedarrays = ascat.gg$failedarrays)
return(ASCATobj)
}
#' @title ascat.plotSegmentedData
#' @description plots the SNP array data before and after segmentation
#'
#' @param ASCATobj an ASCAT object (e.g. from ascat.aspcf)
#'
#' @return png files showing raw and segmented tumour logR and BAF
#'
#' @export
#'
ascat.plotSegmentedData = function(ASCATobj) {
for (arraynr in 1:dim(ASCATobj$Tumor_LogR)[2]) {
Select_nonNAs = rownames(ASCATobj$Tumor_BAF_segmented[[arraynr]])
AllIDs = 1:dim(ASCATobj$Tumor_LogR)[1]
names(AllIDs) = rownames(ASCATobj$Tumor_LogR)
HetIDs = AllIDs[Select_nonNAs]
png(filename = paste(ASCATobj$samples[arraynr],".ASPCF.png",sep=""), width = 2000, height = 1000, res = 200)
par(mar = c(0.5,5,5,0.5), mfrow = c(2,1), cex = 0.4, cex.main=3, cex.axis = 2)
r = ASCATobj$Tumor_LogR_segmented[rownames(ASCATobj$Tumor_BAF_segmented[[arraynr]]),arraynr]
beta = ASCATobj$Tumor_BAF_segmented[[arraynr]][,]
plot(c(1,length(r)), c(-1,1), type = "n", xaxt = "n", main = paste(colnames(ASCATobj$Tumor_BAF)[arraynr],", LogR",sep=""), xlab = "", ylab = "")
points(ASCATobj$Tumor_LogR[rownames(ASCATobj$Tumor_BAF_segmented[[arraynr]]),arraynr], col = "red", pch=ifelse(dim(ASCATobj$Tumor_LogR)[1]>100000,".",20))
points(r,col="green")
abline(v=0.5,lty=1,col="lightgrey")
chrk_tot_len = 0
for (j in 1:length(ASCATobj$ch)) {
chrk = intersect(ASCATobj$ch[[j]],HetIDs);
chrk_tot_len_prev = chrk_tot_len
chrk_tot_len = chrk_tot_len + length(chrk)
vpos = chrk_tot_len;
tpos = (chrk_tot_len+chrk_tot_len_prev)/2;
text(tpos,1,ASCATobj$chrs[j], pos = 1, cex = 2)
abline(v=vpos+0.5,lty=1,col="lightgrey")
}
plot(c(1,length(beta)), c(0,1), type = "n", xaxt = "n", main = paste(colnames(ASCATobj$Tumor_BAF)[arraynr],", BAF",sep=""), xlab = "", ylab = "")
points(ASCATobj$Tumor_BAF[rownames(ASCATobj$Tumor_BAF_segmented[[arraynr]]),arraynr], col = "red", pch=ifelse(dim(ASCATobj$Tumor_LogR)[1]>100000,".",20))
points(beta, col = "green")
points(1-beta, col = "green")
abline(v=0.5,lty=1,col="lightgrey")
chrk_tot_len = 0
for (j in 1:length(ASCATobj$ch)) {
chrk = intersect(ASCATobj$ch[[j]],HetIDs);
chrk_tot_len_prev = chrk_tot_len
chrk_tot_len = chrk_tot_len + length(chrk)
vpos = chrk_tot_len;
tpos = (chrk_tot_len+chrk_tot_len_prev)/2;
text(tpos,1,ASCATobj$chrs[j], pos = 1, cex = 2)
abline(v=vpos+0.5,lty=1,col="lightgrey")
}
dev.off()
}
}
#' @title ascat.runAscat
#' @description ASCAT main function, calculating the allele-specific copy numbers
#' @param ASCATobj an ASCAT object from ascat.aspcf
#' @param gamma technology parameter, compaction of Log R profiles (expected decrease in case of deletion in diploid sample, 100\% aberrant cells; 1 in ideal case, 0.55 of Illumina 109K arrays)
#' @param pdfPlot Optional flag if nonrounded plots and ASCAT profile in pdf format are desired. Default=F
#' @param y_limit Optional parameter determining the size of the y axis in the nonrounded plot and ASCAT profile. Default=5
# @param textFlag Optional flag to add the positions of fragments located outside of the plotting area to the plots. Default=F
#' @param circos Optional file to output the non-rounded values in Circos track format. Default=NA
#' @param rho_manual optional argument to override ASCAT optimization and supply rho parameter (not recommended)
#' @param psi_manual optional argument to override ASCAT optimization and supply psi parameter (not recommended)
#' @details Note: for copy number only probes, nA contains the copy number value and nB = 0.
#' @return an ASCAT output object, containing:\cr
#' 1. nA: copy number of the A allele\cr
#' 2. nB: copy number of the B allele\cr
#' 3. aberrantcellfraction: the aberrant cell fraction of all arrays\cr
#' 4. ploidy: the ploidy of all arrays\cr
#' 5. failedarrays: arrays on which ASCAT analysis failed\cr
#' 6. nonaberrantarrays: arrays on which ASCAT analysis indicates that they show virtually no aberrations\cr
#' 7. segments: an array containing the copy number segments of each sample (not including failed arrays)\cr
#' 8. segments_raw: an array containing the copy number segments of each sample without any rounding applied\cr
#' 9. distance_matrix: distances for a range of ploidy and tumor percentage values
#'
#' @export
#'
ascat.runAscat = function(ASCATobj, gamma = 0.55, pdfPlot = F, y_limit = 5, circos=NA, rho_manual = NA, psi_manual = NA) {
goodarrays=NULL
res = vector("list",dim(ASCATobj$Tumor_LogR)[2])
for (arraynr in 1:dim(ASCATobj$Tumor_LogR)[2]) {
print.noquote(paste("Sample ", ASCATobj$samples[arraynr], " (",arraynr,"/",length(ASCATobj$samples),")",sep=""))
lrr=ASCATobj$Tumor_LogR[,arraynr]
names(lrr)=rownames(ASCATobj$Tumor_LogR)
baf=ASCATobj$Tumor_BAF[,arraynr]
names(baf)=rownames(ASCATobj$Tumor_BAF)
lrrsegm = ASCATobj$Tumor_LogR_segmented[,arraynr]
names(lrrsegm) = rownames(ASCATobj$Tumor_LogR_segmented)
bafsegm = ASCATobj$Tumor_BAF_segmented[[arraynr]][,]
names(bafsegm) = rownames(ASCATobj$Tumor_BAF_segmented[[arraynr]])
failedqualitycheck = F
if(ASCATobj$samples[arraynr]%in%ASCATobj$failedarrays) {
failedqualitycheck = T
}
ending = ifelse(pdfPlot, "pdf", "png")
circosName=NA
if(!is.na(circos)){
circosName=paste(circos,"_",ASCATobj$samples[arraynr],sep="")
}
if(is.na(rho_manual)) {
res[[arraynr]] = runASCAT(lrr,baf,lrrsegm,bafsegm,ASCATobj$gender[arraynr],ASCATobj$SNPpos,ASCATobj$ch,ASCATobj$chrs,ASCATobj$sexchromosomes, failedqualitycheck,
paste(ASCATobj$samples[arraynr],".sunrise.png",sep=""),paste(ASCATobj$samples[arraynr],".ASCATprofile.", ending ,sep=""),
paste(ASCATobj$samples[arraynr],".rawprofile.", ending ,sep=""),NA,
gamma,NA,NA,pdfPlot, y_limit, circosName)
} else {
res[[arraynr]] = runASCAT(lrr,baf,lrrsegm,bafsegm,ASCATobj$gender[arraynr],ASCATobj$SNPpos,ASCATobj$ch,ASCATobj$chrs,ASCATobj$sexchromosomes, failedqualitycheck,
paste(ASCATobj$samples[arraynr],".sunrise.png",sep=""),paste(ASCATobj$samples[arraynr],".ASCATprofile.", ending,sep=""),
paste(ASCATobj$samples[arraynr],".rawprofile.", ending,sep=""),NA,
gamma,rho_manual[arraynr],psi_manual[arraynr], pdfPlot, y_limit, circosName)
}
if(!is.na(res[[arraynr]]$rho)) {
goodarrays[length(goodarrays)+1] = arraynr
}
}
if(length(goodarrays)>0) {
n1 = matrix(nrow = dim(ASCATobj$Tumor_LogR)[1], ncol = length(goodarrays))
n2 = matrix(nrow = dim(ASCATobj$Tumor_LogR)[1], ncol = length(goodarrays))
rownames(n1) = rownames(ASCATobj$Tumor_LogR)
rownames(n2) = rownames(ASCATobj$Tumor_LogR)
colnames(n1) = colnames(ASCATobj$Tumor_LogR)[goodarrays]
colnames(n2) = colnames(ASCATobj$Tumor_LogR)[goodarrays]
for (i in 1:length(goodarrays)) {
n1[,i] = res[[goodarrays[i]]]$nA
n2[,i] = res[[goodarrays[i]]]$nB
}
distance_matrix = vector("list",length(goodarrays))
names(distance_matrix) <- colnames(ASCATobj$Tumor_LogR)[goodarrays]
for (i in 1:length(goodarrays)) {
distance_matrix[[i]] = res[[goodarrays[i]]]$distance_matrix
}
tp = vector(length=length(goodarrays))
psi = vector(length=length(goodarrays))
ploidy = vector(length=length(goodarrays))
goodnessOfFit = vector(length=length(goodarrays))
naarrays = NULL
for (i in 1:length(goodarrays)) {
tp[i] = res[[goodarrays[i]]]$rho
psi[i] = res[[goodarrays[i]]]$psi
ploidy[i] = mean(res[[goodarrays[i]]]$nA+res[[goodarrays[i]]]$nB,na.rm=T)
goodnessOfFit[i] = res[[goodarrays[i]]]$goodnessOfFit
if(res[[goodarrays[i]]]$nonaberrant) {
naarrays = c(naarrays,ASCATobj$samples[goodarrays[i]])
}
}
fa = colnames(ASCATobj$Tumor_LogR)[-goodarrays]
names(tp) = colnames(n1)
names(ploidy) = colnames(n1)
names(psi) = colnames(n1)
names(goodnessOfFit) = colnames(n1)
seg = NULL
for (i in 1:length(goodarrays)) {
segje = res[[goodarrays[i]]]$seg
seg = rbind(seg,cbind(ASCATobj$samples[goodarrays[i]],as.vector(ASCATobj$SNPpos[segje[,1],1]),
ASCATobj$SNPpos[segje[,1],2],
ASCATobj$SNPpos[segje[,2],2],segje[,3],segje[,4]))
}
colnames(seg) = c("sample","chr","startpos","endpos","nMajor","nMinor")
seg = data.frame(seg,stringsAsFactors=F)
seg[,3]=as.numeric(seg[,3])
seg[,4]=as.numeric(seg[,4])
seg[,5]=as.numeric(seg[,5])
seg[,6]=as.numeric(seg[,6])
seg_raw = NULL
for (i in 1:length(goodarrays)) {
segje = res[[goodarrays[i]]]$seg_raw
seg_raw = rbind(seg_raw,cbind(ASCATobj$samples[goodarrays[i]],as.vector(ASCATobj$SNPpos[segje[,1],1]),
ASCATobj$SNPpos[segje[,1],2],
ASCATobj$SNPpos[segje[,2],2],segje[,3],segje[,4:ncol(segje)]))
}
colnames(seg_raw) = c("sample","chr","startpos","endpos","nMajor","nMinor","nAraw","nBraw")
seg_raw = data.frame(seg_raw,stringsAsFactors=F)
seg_raw[,3]=as.numeric(seg_raw[,3])
seg_raw[,4]=as.numeric(seg_raw[,4])
seg_raw[,5]=as.numeric(seg_raw[,5])
seg_raw[,6]=as.numeric(seg_raw[,6])
seg_raw[,7]=as.numeric(seg_raw[,7])
seg_raw[,8]=as.numeric(seg_raw[,8])
}
else {
n1 = NULL
n2 = NULL
tp = NULL
ploidy = NULL
psi = NULL
goodnessOfFit = NULL
fa = colnames(ASCATobj$Tumor_LogR)
naarrays = NULL
seg = NULL
seg_raw = NULL
distance_matrix = NULL
}
return(list(nA = n1, nB = n2, aberrantcellfraction = tp, ploidy = ploidy, psi = psi, goodnessOfFit = goodnessOfFit,
failedarrays = fa, nonaberrantarrays = naarrays, segments = seg, segments_raw = seg_raw, distance_matrix = distance_matrix))
}
# helper function to split the genome into parts
split_genome = function(SNPpos) {
# look for gaps of more than 5Mb (arbitrary treshold to account for big centremeres or other gaps) and chromosome borders
bigHoles = which(diff(SNPpos[,2])>=5000000)+1
chrBorders = which(SNPpos[1:(dim(SNPpos)[1]-1),1]!=SNPpos[2:(dim(SNPpos)[1]),1])+1
holes = unique(sort(c(bigHoles,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)
}
#' @title predictGermlineHomozygousStretches
#' @description helper function to predict germline homozyguous segments for later re-segmentation
#' @param chr a list containing vectors with the indices for each distinct part that can be segmented separately
#' @param hom germline genotypes
#'
#' @keywords internal
#'
#' @return germline homozyguous segments
#'
#'
predictGermlineHomozygousStretches = function(chr, hom) {
# contains the result: a list of vectors of probe numbers in homozygous stretches for each sample
HomoStretches = list()
for (sam in 1:dim(hom)[2]) {
homsam = hom[,sam]
perchom = sum(homsam,na.rm=T)/sum(!is.na(homsam))
# NOTE THAT A P-VALUE THRESHOLD OF 0.001 IS HARDCODED HERE
homthres = ceiling(log(0.001,perchom))
allhprobes = NULL
for (chrke in 1:length(chr)) {
hschr = homsam[chr[[chrke]]]
hprobes = vector(length=0)
for(probe in 1:length(hschr)) {
if(!is.na(hschr[probe])) {
if(hschr[probe]) {
hprobes = c(hprobes,probe)
}
else {
if(length(hprobes)>=homthres) {
allhprobes = rbind(allhprobes,c(chrke,chr[[chrke]][min(hprobes)],chr[[chrke]][max(hprobes)]))
}
hprobes = vector(length=0)
}
}
}
# if the last probe is homozygous, this is not yet accounted for
if(!is.na(hschr[probe]) & hschr[probe]) {
if(length(hprobes)>=homthres) {
allhprobes = rbind(allhprobes,c(chrke,chr[[chrke]][min(hprobes)],chr[[chrke]][max(hprobes)]))
}
}
}
HomoStretches[[sam]]=allhprobes
}
return(HomoStretches)
}
#' @title make_segments
#' @description Function to make segments of constant LRR and BAF.\cr
#' This function is more general and does not depend on specific ASPCF output, it can also handle segmention performed on LRR and BAF separately
#' @param r segmented logR
#' @param b segmented BAF
#' @return segments of constant logR and BAF including their lengths
#' @keywords internal
#' @export
make_segments = function(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))[,]
return(pcf_segments);
}
# 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
create_distance_matrix = function(segments, gamma) {
s = segments
psi_pos = seq(1,6,0.05)
rho_pos = seq(0.1,1.05,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]
nA = (rho-1-(s[,"b"]-1)*2^(s[,"r"]/gamma)*((1-rho)*2+rho*psi))/rho
nB = (rho-1+s[,"b"]*2^(s[,"r"]/gamma)*((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)
}
}
return(d)
}
#' @title runASCAT
#' @description the ASCAT main function
#' @param lrr (unsegmented) log R, in genomic sequence (all probes), with probe IDs
#' @param baf (unsegmented) B Allele Frequency, in genomic sequence (all probes), with probe IDs
#' @param lrrsegmented log R, segmented, in genomic sequence (all probes), with probe IDs
#' @param bafsegmented B Allele Frequency, segmented, in genomic sequence (only probes heterozygous in germline), with probe IDs
#' @param gender a vector of gender for each cases ("XX" or "XY"). Default = NULL: all female ("XX")
#' @param SNPpos position of all SNPs
#' @param chromosomes a list containing c vectors, where c is the number of chromosomes and every vector contains all probe numbers per chromosome
#' @param chrnames a vector containing the names for the chromosomes (e.g. c(1:22,"X"))
#' @param sexchromosomes a vector containing the names for the sex chromosomes
#' @param failedqualitycheck did the sample fail any previous quality check or not?
#' @param distancepng if NA: distance is plotted, if filename is given, the plot is written to a .png file
#' @param copynumberprofilespng if NA: possible copy number profiles are plotted, if filename is given, the plot is written to a .png file
#' @param nonroundedprofilepng if NA: copy number profile before rounding is plotted (total copy number as well as the copy number of the minor allele), if filename is given, the plot is written to a .png file
#' @param aberrationreliabilitypng aberration reliability score is plotted if filename is given
#' @param gamma technology parameter, compaction of Log R profiles (expected decrease in case of deletion in diploid sample, 100\% aberrant cells; 1 in ideal case, 0.55 of Illumina 109K arrays)
#' @param rho_manual optional argument to override ASCAT optimization and supply rho parameter (not recommended)
#' @param psi_manual optional argument to override ASCAT optimization and supply psi parameter (not recommended)
#' @param pdfPlot Optional flag if nonrounded plots and ASCAT profile in pdf format are desired. Default=F
#' @param circos Optional file to output the non-rounded values in Circos track format. Default=NA
#' @param y_limit Optional parameter determining the size of the y axis in the nonrounded plot and ASCAT profile. Default=5
#'
#' @keywords internal
#'
#' @return list containing optimal purity and ploidy
#'
#' @import RColorBrewer
#'
#' @export
runASCAT = function(lrr, baf, lrrsegmented, bafsegmented, gender, SNPpos, chromosomes, chrnames, sexchromosomes, failedqualitycheck = F,
distancepng = NA, copynumberprofilespng = NA, nonroundedprofilepng = NA, aberrationreliabilitypng = NA, gamma = 0.55,
rho_manual = NA, psi_manual = NA, pdfPlot = F, y_limit = 5, circos=NA) {
ch = chromosomes
chrs = chrnames
b = bafsegmented
r = lrrsegmented[names(bafsegmented)]
SNPposhet = SNPpos[names(bafsegmented),]
autoprobes = !(SNPposhet[,1]%in%sexchromosomes)
b2 = b[autoprobes]
r2 = r[autoprobes]
s = make_segments(r2,b2)
d = create_distance_matrix(s, gamma)