forked from molgenis/CoNVaDING
-
Notifications
You must be signed in to change notification settings - Fork 3
/
CoNVaDING.pl
3135 lines (2849 loc) · 151 KB
/
CoNVaDING.pl
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
#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;
use File::Glob ':glob';
use File::Basename;
use Getopt::Long;
use List::Util qw(sum);
use Math::Complex;
use POSIX qw(ceil);
use POSIX qw(floor);
#use Term::ProgressBar;
use Statistics::Normality 'shapiro_wilk_test';
use File::Temp qw/ tempfile tempdir /;
use Data::Dumper;
######CHANGE VERSION PARAMETER IF VERSION IS UPDATED#####
our $VERSION = '1.5.3';
my $version_reload = $VERSION;
my $version = $VERSION;
##############################################################################################
##############################################################################################
## CoNVaDING reload, copy number variation detecting in next-generation ##
## sequencing gene panels ##
## ##
## this is a fork from the original program written by ##
## Copyright (C) 2015 Freerk van Dijk & Lennart Johansson ##
## ##
## This file is part of CoNVaDING. ##
## ##
## CoNVaDING is free software: you can redistribute it and/or modify ##
## it under the terms of the GNU Lesser General Public License as published by ##
## the Free Software Foundation, either version 3 of the License, or ##
## (at your option) any later version. ##
## ##
## CoNVaDING is distributed in the hope that it will be useful, ##
## but WITHOUT ANY WARRANTY; without even the implied warranty of ##
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ##
## GNU Lesser General Public License for more details. ##
## ##
## You should have received a copy of the GNU Lesser General Public License ##
## along with CoNVaDING. If not, see <http://www.gnu.org/licenses/>. ##
##############################################################################################
##############################################################################################
#Commandline variables
my $params = {};
#set defaults
$params->{regionThreshold} = 20;
$params->{ratioCutOffLow} = 0.65;
$params->{ratioCutOffHigh} = 1.4;
$params->{zScoreCutOffLow} = -3;
$params->{zScoreCutOffHigh} = 3;
$params->{sampleRatioScore} = 0.09;
$params->{percentageLessReliableTargets} = 20;
$params->{numBestMatchSamplesCmdL} = 30;
$params->{mode} = "StartWithBam";
$params->{samtoolsdepthmaxcov} = 8000;
$params->{ampliconcov} = 0;
$params->{mosdepth_fastmode} = 1;
$params->{mosdepth_threads} = 4;
#### get options
GetOptions(
"mode:s" => \$params->{mode}, #For options, see list below (default="StartWithBam")
"inputDir:s" => \$params->{inputdir},# required for all modes except GenerateTargetQcList
"outputDir=s" => \$params->{outputdir}, # required always
"controlsDir:s" => \$params->{controlsdir}, #optional
"bed:s" => \$params->{bedfile}, #optional
"controlSamples:i" => \$params->{numBestMatchSamplesCmdL}, #optional
"regionThreshold:s" => \$params->{regionThreshold}, #optional
"rmDup" => \$params->{rmdup}, #optional
"sexChr" => \$params->{sexchr}, #optional
"fasta|fasta_file|fa" => \$params->{fasta}, #optional
"useSampleAsControl:s" => \$params->{sampleAsControl}, #optional
"ratioCutOffLow:s" => \$params->{ratioCutOffLow}, #optional
"ratioCutOffHigh:s" => \$params->{ratioCutOffHigh}, #optional
"zScoreCutOffLow:s" => \$params->{zScoreCutOffLow}, #optional
"zScoreCutOffHigh:s" => \$params->{zScoreCutOffHigh}, #optional
"sampleRatioScore:s" => \$params->{sampleRatioScore}, #optional
"targetQcList:s" => \$params->{targetQcList}, #optional
"percentageLessReliableTargets:s" => \$params->{percentageLessReliableTargets}, #optional
"samtoolsdepthmaxcov:i" => \$params->{samtoolsdepthmaxcov},#optional for startwitham
"ampliconcov:f" => \$params->{ampliconcov},#optional for startwithbam
"samtools-depth" => \$params->{samtools_depth},
"mosdepth-fast-mode!" => \$params->{mosdepth_fastmode},#on by default
"mosdepth-threads:i" => \$params->{mosdepth_threads},#4 by by default (max)
"mosdepth-median" => \$params->{mosdepth_median},
"verbose" => \$params->{verbose},
"h|help" => sub { usage() and exit(1)},
"version" => sub { print "CoNVaDING relaod v".$version_reload." modified fork from CoNVaDING v".$version."\n" and exit(1)}
);
# ((defined $params->{sampleAsControl} && defined $params->{controlsdir})&& $params->{controlsdir} ne $params->{outputdir})
#Obligatory args
usage() and exit(1) unless $params->{mode};
usage() and exit(1) unless $params->{outputdir};
#Add more parameters later
#Check input parameters
unless ($params->{mode} eq "PipelineFromBams" ||
$params->{mode} eq "PipelineFromCounts" ||
$params->{mode} eq "addToControls" ||
$params->{mode} eq "StartWithBam" ||
$params->{mode} eq "StartWithAvgCount" ||
$params->{mode} eq "StartWithMatchScore" ||
$params->{mode} eq "StartWithBestScore" ||
$params->{mode} eq "GenerateTargetQcList" ||
$params->{mode} eq "CreateFinalList") {
die "Mode ".$params->{mode}." is not supported. Please read the manual.\n";
}
#If controlsdir is specified while running best score mode, throw warning
#Set default threshold values
if ($params->{mode} eq "StartWithBestScore"){
if (defined $params->{controlsdir}){
print "\n##### WARNING ##### WARNING #####\n";
print "User specified parameter \"controlsDir\" not used in best score analysis.";
print "\n##### WARNING ##### WARNING #####\n";
}
}
#Check if output directory exists, otherwise create it
if (!-d $params->{outputdir}) { #Output directory does not exist, create it
mkdir $params->{outputdir};
}
my @bedfile;
#Check if BED file is specified for StartWithBam and StartWithAvgCount, else die and throw error message
if ($params->{mode} eq "PipelineFromBams" ||
$params->{mode} eq "PipelineFromCounts" ||
$params->{mode} eq "addToControls" ||
$params->{mode} eq "StartWithBam" ||
$params->{mode} eq "StartWithAvgCount"){
if (not defined $params->{bedfile}){
die "Required BED file not specified, please specify to continue analysis.\n";
}
}elsif ($params->{mode} eq "StartWithMatchScore" ||
$params->{mode} eq "StartWithBestScore"){ #Throw warning saying BED file is not used in this analysis.
if (defined $params->{bedfile}){
print STDERR "\n##### WARNING ##### WARNING #####\n";
print STDERR "User specified parameter \"bed\" not used in this analysis.";
print STDERR "\n##### WARNING ##### WARNING #####\n";
}
}
if ($params->{mode} eq "addToControls"){
if (not defined $params->{sampleAsControl}){
print STDERR "#####\n#Parameter sampleAsControl forcebly defined\n#####\n";
$params->{sampleAsControl} = 1;
}
if (not defined $params->{controlsDir} && not defined $params->{outputdir}){
die "Required --controlsDir or --outputDir not defined, please specify to continue analysis.\n";
}elsif(defined $params->{controlsDir} && defined $params->{outputdir} && $params->{controlsDir} != $params->{outputdir}){
die "in addToControls both controlsDir and outputDir should be the same. Only need to define 1 or the two\n";
}elsif(not defined $params->{controlsDir}){
$params->{controlsDir} = $params->{outputdir};
}elsif(not defined $params->{outputdir}){
$params->{outputdir} = $params->{controlsDir};
}
}
#Check if controlsdir exists for four param options
#if ($params->{mode} eq "StartWithBam" || $params->{mode} eq "StartWithAvgCount" || $params->{mode} eq "StartWithMatchScore" || $params->{mode} eq "GenerateTargetQcList"){ #Check if controlsdir is specified
if ($params->{mode} eq "PipelineFromBams" ||
$params->{mode} eq "PipelineFromCounts" ||
$params->{mode} eq "StartWithBam" ||
$params->{mode} eq "StartWithAvgCount" ||
$params->{mode} eq "StartWithMatchScore" ||
$params->{mode} eq "addToControls" ||
$params->{mode} eq "GenerateTargetQcList"
){
#Check if controlsdir is specified
if (not defined $params->{controlsdir}) { #Throw error when controlsdir is not specified
die "Directory for controlsamples (-controlsDir) is not specified, please specify to continue analysis.\n";
}elsif (!-d $params->{controlsdir}) {
#Check if controls directory exists, otherwise create it except in pipeline modes
if ( $params->{mode} eq "StartWithAvgCount" ||
$params->{mode} eq "StartWithMatchScore" ||
$params->{mode} eq "addToControls"){
mkdir $params->{controlsdir};
}elsif($params->{mode} eq "PipelineFromBams" ||
$params->{mode} eq "PipelineFromCounts" ||
$params->{mode} eq "GenerateTargetQcList"){
die "Directory for controlsamples (-controlsDir) does not exist please specify to continue analysis.\n";
}
}
if ($params->{mode} eq "PipelineFromBams" || $params->{mode} eq "PipelineFromCounts"){
if (not defined $params->{targetQcList}){
$params->{targetQcList} = $params->{outputdir}."/"."targetQcList.txt";
}
}
#Check if controldir contains avg count files when useSampleAsControl paramater is not specified
if (not defined $params->{sampleAsControl}){
opendir(DIRHANDLE, $params->{controlsdir}) || die "Couldn't open directory ".$params->{controlsdir}.": $!\n";
my @txt = grep { /\.normalized.coverage.txt$/ && -f $params->{controlsdir}."/".$_ } readdir DIRHANDLE;
closedir DIRHANDLE;
if (@txt) { #not empty
#continue
my $numFiles = scalar(@txt); #If match score or best score mode is used, check if number of control sample files is greater than or equal to what user requested via parameter.
if ($params->{mode} eq "StartWithMatchScore") {
if ( $numFiles < $params->{numBestMatchSamplesCmdL}){
die "The number of controlsamples in ".$params->{controlsdir}." is less than specified number of ".$params->{numBestMatchSamplesCmdL}." controlsamples by \"controlSamples\" parameter.\n";
}
}
}else{
die "Directory specified by \"controlsDir\" parameter does not contain normalized coverage files.\n";
}
}
}
#Check if input directory exists for all modes that require it
unless ($params->{mode} eq "GenerateTargetQcList"){
if (not defined $params->{inputdir}) { #Throw error when inputdir is not specified
die "Directory for input samples (-inputDir) is not specified, this is a requirement on all modes\n."
."with the exception GenerateTargetQcList. Please specify input folder to continue analysis.\n";
}
}else{
if (not defined $params->{inputdir}){
$params->{inputdir} = $params->{controlsdir};
}
}
#Checks when running in CreateFinalList mode
if ($params->{mode} eq "CreateFinalList"){ #Check if targetQcList is specified
if (not defined $params->{targetQcList}) { #Throw error when targetQcList is not specified
die "Target QC list (-targetQcList) is not specified, please specify to continue analysis.\n";
}
}
#Retrieve and print starttime
my $starttime = localtime();
print STDERR "\nStarting analysis $starttime\n";
print STDERR "\n#######################################\n";
print STDERR "Parameteres in effect in this Run:\n";
foreach my $key (keys %{$params}){
if(defined($params->{$key})){
warn "\t$key:\t".$params->{$key}."\n";
}else{
warn "\t$key:\tundef=(FLAG in off position)\n";
}
}
print STDERR "#######################################\n";
#sometimes the script want to modify the outputdir and input dir to temp folders.
# these are therefore stored as additional parameteres
$params->{outputdirOriginal} = $params->{outputdir};
$params->{inputdirOriginal} = $params->{inputdir};
#pipeline mode
if ($params->{mode} eq "PipelineFromBams" || $params->{mode} eq "PipelineFromCounts"){
#mode to run complete pipeline from fresh bam inputs
if ($params->{mode} eq "PipelineFromBams"){
startWithBamMode();
}
#mode to run complete pipeline from previous counts
if ($params->{mode} eq "PipelineFromCounts"){
startWithAvgCountMode()
}
$params->{inputdir} = $params->{outputdir} ;
startWithMatchScoreMode();
startWithBestScoreMode();
unless (-e $params->{targetQcList}){
$params->{inputdir} = $params->{controlsdir};
generateTargetQcListMode();
$params->{inputdir} = $params->{outputdir};
}
createFinalListMode();
#add any found CRAM or BAMs on input file to controls
}elsif ($params->{mode} eq "addToControls"){
addToControlsMode();
#Start analysis from BAM file
}elsif ($params->{mode} eq "StartWithBam"){
startWithBamMode();
#Start analysis from average count files
}elsif ($params->{mode} eq "StartWithAvgCount"){
startWithAvgCountMode();
#Start analysis from match score
}elsif ($params->{mode} eq "StartWithMatchScore"){
startWithMatchScoreMode();
#Start analysis from best score
}elsif ($params->{mode} eq "StartWithBestScore"){
startWithBestScoreMode();
#Generate target QC list from all controlsamples
}elsif ($params->{mode} eq "GenerateTargetQcList"){
generateTargetQcListMode();
#Create final list based on target QC file
}elsif ($params->{mode} eq "CreateFinalList"){ #Apply the target filtering using the file created in previous step
createFinalListMode();
}
#Retrieve and print end time
my $endtime = localtime();
print STDERR "\nFinished analysis $endtime\n";
########################################################################################################
########## SUBS #################### SUBS #################### SUBS #################### SUBS ##########
########################################################################################################
##########################################################
## Main subs for each mode ##
##########################################################
sub addToControlsMode{
if (defined $params->{rmdup}) { #Remove duplicate switch added in cmdline
print "\n############\nrmdup switch detected, duplicate removal included in analysis\n############\n\n";
print "Starting removing duplicates and creating new BAM files..\n";
}
#Read BAM files
print "Reading files to process..\n";
my @inputCRAMiles = readFile($params->{inputdir}, ".cram");
if (@inputCRAMiles || ! defined $params->{fasta}){
usage("User has specifed CRAM files to process but has not given a location for the required fasta files with the parameter --fasta");
}
#Start analysis from CRAM files
startWithBam(\@inputCRAMiles);
my @inputBAMfiles = readFile($params->{inputdir}, ".bam");
#Start analysis from BAM file
startWithBam(\@inputBAMfiles);
}
sub startWithBamMode{
if (defined $params->{rmdup}) { #Remove duplicate switch added in cmdline
print "\n############\nrmdup switch detected, duplicate removal included in analysis\n############\n\n";
print "Starting removing duplicates and creating new BAM files..\n";
}
#Read BAM files
print "Reading BAM files to process..\n";
my @inputBamfiles = readFile($params->{inputdir}, ".bam");
#Start analysis from BAM file
startWithBam(\@inputBamfiles);
my @inputCramfiles = readFile($params->{inputdir}, ".cram");
if( ! defined $params->{fasta} && @inputCramfiles){
usage("User has included Cram files but has not specified a required fasta file for decompressing CRAMS with parameter --fasta");
}
startWithBam(\@inputCramfiles);
}
sub startWithAvgCountMode{
#Read count TXT files
print "Reading count files..\n";
my @inputfiles = readFile($params->{inputdir}, ".txt");
print "Starting counts analysis..\n";
startWithAvgCount(\@inputfiles);
}
sub startWithMatchScoreMode{
if (defined $params->{sexchr}) { #Use sex chromosomes switch added in cmdline
print "\n\n############\nsexchr switch detected, sex chromosomes included in analysis\n############\n\n";
}
#Read count TXT files
print "Starting search for best match scores..\n";
print "Reading count files..\n";
my @inputfiles = readFile($params->{inputdir}, ".normalized.coverage.txt"); #Read files in input directory
my @controlfiles = readFile($params->{controlsdir}, ".normalized.coverage.txt"); #Read files in controls directory
print "Starting match score analysis..\n";
#Start analysis from match score file
startWithMatchScore( ".normalized.coverage.txt", \@inputfiles, \@controlfiles);
}
sub startWithBestScoreMode{
#continue
if (defined $params->{sexchr}) { #Use sex chromosomes switch added in cmdline
print "\n\n############\nsexchr switch detected, sex chromosomes included in analysis\n############\n\n";
}
#Read count TXT files
print "Starting search for best scores..\n";
#Read all normalized autosomal coverage control files into array
my @normAutoControls = readFile($params->{inputdir}, ".normalized.autosomal.coverage.all.controls.txt"); #Read files in input directory
#Read best match score files
print "Reading best match score files..\n";
my @inputfiles = readFile($params->{inputdir}, ".best.match.score.txt"); #Read files in input directory
print "Starting best score analysis..\n";
#Start CNV detection analysis
startWithBestScore(".best.match.score.txt", \@inputfiles, \@normAutoControls);
}
sub generateTargetQcListMode{
#Read count TXT files
print "Reading controls directory..\n";
#Read all *.txt files in control directory into array
my @inputfiles = readFile($params->{inputdir}, ".normalized.coverage.txt"); #Read files in input directory
my @controlfiles = readFile($params->{controlsdir}, ".normalized.coverage.txt"); #Read files in controls directory
#Set temporary dirs to do intermediate work
my $tmpStartWithMatchScore = File::Temp->newdir();
my $tmpStartWithBestScore = File::Temp->newdir();
$params->{outputdir} = $tmpStartWithMatchScore->dirname;
#Start analysis from match score file
startWithMatchScore(".normalized.coverage.txt", \@inputfiles, \@controlfiles);
#Read count TXT files
print "Starting search for best scores..\n";
#Read all normalized autosomal coverage control files into array
my @normAutoControls = readFile($tmpStartWithMatchScore->dirname, ".normalized.autosomal.coverage.all.controls.txt"); #Read files in input directory
#Read best match score files
print "Reading best match score files..\n";
@inputfiles = readFile($tmpStartWithMatchScore->dirname, ".best.match.score.txt"); #Read files in input directory
print STDERR "Starting best score analysis..\n";
$params->{inputdir} = $tmpStartWithMatchScore->dirname;
$params->{outputdir} = $tmpStartWithBestScore->dirname;
#Start CNV detection analysis
startWithBestScore(".normalized.coverage.txt", \@inputfiles, \@normAutoControls);
#Read all *.log files in control directory into array
$params->{inputdir} = $tmpStartWithBestScore->dirname;
my @logfiles = readFile($tmpStartWithBestScore->dirname, ".log"); #Read files in controls directory
#Extract sampleratio from *.log file
print STDERR "\n#######################################\n";
print STDERR "\n\nSamples failing sample CV threshold of ".$params->{sampleRatioScore}.":\n\n";
my @passSampleRatioSamples;
my $dirname= $tmpStartWithBestScore->dirname;
foreach my $logfile (@logfiles){
my $grep = `grep SAMPLE_CV: $dirname/$logfile`;
chomp $grep;
if ($grep =~ m/SAMPLE_CV: ([0-9].+)/gs){ #Check if sampleratio is below threshold(default 0.09), otherwise don't use it in targetlist analysis
my $sampleRatio = $1;
if ($sampleRatio <= $params->{sampleRatioScore}) {
$logfile =~ s/.log/.totallist.txt/gs; #Change *.log extension to *.totallist.txt
push(@passSampleRatioSamples, $dirname."/".$logfile);
}else{
#Print samples failing sample CV score to stdout
print "$logfile\n";
}
}
}
print "\n\n#######################################\n\n";
print "\nGenerating target QC list..\n";
#Calculate target autoVC
generateTargetQcList(@passSampleRatioSamples);
print "\nDone generating target QC list\n";
}
sub createFinalListMode{
#Read shortlist TXT files
print "Reading input directory..\n";
#Read all *.txt files in input directory into array
my @inputfiles = readFile($params->{inputdir}, ".shortlist.txt"); #Read files in controls directory
#Generate the final list
createFinalList(\@inputfiles);
}
###############################################
## Main code to generate final list using ##
## the target QC list ##
sub createFinalList{
my ($inputfiles) = @_;
#Read target QC list into array;
open(FILE, $params->{targetQcList}) or die("Unable to open file: $!"); #Read count file
my @file= <FILE>;
close(FILE);
#Retrieve chr, start, stop and genename from file by searching column indices
my $header = uc($file[0]); #Header in uppercase
chomp $header;
#Extract columns from header and use as index
my @colNames = qw(CHR START STOP GENE);
my @indices = getColumnIdx($header, \@colNames);
my $chrIdx = $indices[0];
my $startIdx = $indices[1];
my $stopIdx = $indices[2];
my $geneIdx = $indices[3];
my $lastFileIdx=$#file;
#Push every index into hash, to exclude from analysis later
my %toExclude;
foreach my $index (@indices){
$toExclude{ $index } = $index;
}
my @indicesCalculation;
#Iterate over header to extract indices to calculate 20% quality over
my @Header = split("\t", $header);
my $lastHeaderIdx = $#Header;
for (my $j=0; $j <= $lastHeaderIdx; $j++){
if (exists $toExclude{ $j }){
#Exclude from calculation
}else{
push(@indicesCalculation, $j);
}
}
my %targetQC;
#Retrieve chr, start, stop, gene for each line in target QC list
for (my $i=1; $i<=$lastFileIdx; $i++){ #Iterate over lines in file
my $line=$file[$i];
chomp $line;
$line =~ s/(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])//; #Remove Unix and Dos style line endings
my @lines=split("\t",$line);
my $chr = $lines[$chrIdx];
my $start = $lines[$startIdx];
my $stop = $lines[$stopIdx];
my $gene = $lines[$geneIdx];
#Calculate number of samples passing cutoff, setting target to PASS or FAIL
my $key = "$chr\t$start\t$stop\t$gene";
my $total=0;
my $highQual=0;
my $lowQual=0;
foreach my $element (@indicesCalculation){
my $autoVC = $lines[$element];
$total++;
if ($autoVC eq "NA"){
$lowQual++;
}elsif ($autoVC <= 0.10) { #Good quality
$highQual++;
}else{ #Low quality target
$lowQual++;
}
}
my $perc = (($lowQual/$total)*100); #percentage low quality targets
if ($perc > $params->{percentageLessReliableTargets}){ #More than X percentage (default 20%) of targets are low quality, so FAIL
$targetQC{ $key } = "FAIL";
}else{
$targetQC{ $key } = "PASS";
}
}
#Iterate over input files, asses if failing targets are within the calls in the shortlist file
foreach my $shortlist (@$inputfiles){
print STDERR"\n\n#######################################\n";
print STDERR"Analyzing sample: $shortlist..\n";
#Read file into array;
my ($file,$dir,$ext) = fileparse($shortlist, qr/\.[^.]*/);
$file =~ s/.shortlist//gs;
open(FILE, "$params->{inputdir}/$shortlist") or die("Unable to open file: $!"); #Read count file
my @file= <FILE>;
close(FILE);
#Retrieve chr, start, stop, genename and region coverage from file by searching column indices
my $header = uc($file[0]); #Header in uppercase
chomp $header;
my $outputToWrite = "$header\n";
my $outputfileBedToWrite = "#gfftags\n";
my @colNames = qw(CHR START STOP GENE);
my $indices = getColumnIdx($header, \@colNames);
my $chrIdx = $indices[0];
my $startIdx = $indices[1];
my $stopIdx = $indices[2];
my $geneIdx = $indices[3];
my $lastFileIdx=$#file;
#Retrieve chr, start, stop, gene and regcov for each line in avg count file
for (my $k=1; $k<=$lastFileIdx; $k++){
my $line=$file[$k];
chomp $line;
$line =~ s/(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])//; #Remove Unix and Dos style line endings
my @lines=split("\t",$line);
my $chr=$lines[$chrIdx];
$chr =~ s/X/23/g;
$chr =~ s/Y/24/g;
$chr =~ s/Z/25/g;
my $start=$lines[$startIdx];
my $stop=$lines[$stopIdx];
my $gene=$lines[$geneIdx];
my $totalTargets=0;
my $targetsFail=0;
#Check if all targets within a single event fail, if true filter event out of finallist.txt
foreach my $target (sort keys %targetQC){
my @targets = split("\t", $target);
my $chrQC = $targets[0];
$chrQC =~ s/X/23/g;
$chrQC =~ s/Y/24/g;
$chrQC =~ s/Z/25/g;
my $startQC = $targets[1];
my $stopQC = $targets[2];
my $geneQC = $targets[3];
if ($chrQC == $chr && $startQC >= $start && $stopQC <= $stop) { #chromosomes matching and start and stop of targetQC falls within the region extracted from *.shortlist.txt file
$totalTargets++;
#Check if target is pass or fail
my $check = $targetQC{ $target };
if ($check eq "FAIL") { #Target failed QC, count it
$targetsFail++;
}
}
}
#Check if number of failing targets equals number of total targets within this event, if true event fails quality threshold and is removed from *.finallist.txt
if ($totalTargets == $targetsFail) {
#event fails QC, don't write it to output
print STDERR"\nEvent failing target QC: $line\n";
}else{
$outputToWrite .= "$line\n";
my @fields = split /\t/, $line;
my $chr = shift @fields;
my $start = shift @fields;
my $end = shift @fields;
my $gene = shift @fields;
my $gene_targets = shift @fields;
my $n_targets = shift @fields;
my $n_targets_SHAPIRO = shift @fields;
my $abberation = shift @fields;
my $namestring = "Name=".$abberation.">>$gene>>chr$chr:$start-$end;".
"Gene=".$gene.";".
"GeneTargets=".$gene_targets.";".
"TypeAberration=".$abberation.";".
"NUMBER_OF_TARGETS=".$n_targets.";".
"NUMBER_OF_TARGETS_PASS_SHAPIRO-WILK_TEST=".$n_targets_SHAPIRO.";";
$outputfileBedToWrite .= join "\t", $chr,
$start,
$end,
$namestring."\n";
}
}
#Write output to *.finallist.txt file
my $outputfile = $params->{outputdir}."/".$file.".finallist.txt"; #Output filename
writeOutput($outputfile, $outputToWrite); #Write output to above specified file
my $nr_of_lines = ($outputfileBedToWrite =~ tr/\n//);
if ($nr_of_lines > 1) {
my $outputfileBed = $params->{outputdir}."/".$file.".finallist.bed"; #Output filename
$outputfileBedToWrite =~ s/ /%20/g;
writeOutput($outputfileBed, $outputfileBedToWrite); #Write output to above specified file
}
print STDERR "#######################################\n\n";
undeff($outputToWrite);
}
}
###############################################
## Main code to generate target QC list from ##
## files in controls directory ##
sub generateTargetQcList{
my @passSampleRatioSamples = @_;
#Set header for output file
my $outputToWrite = "CHR\tSTART\tSTOP\tGENE"; #Instantiate header to write
my %autoVcHash;
my @keyFiles;
my $lastInputfilesIdx = $#passSampleRatioSamples; #Idx of last inputfile
my @autoVCsToOutput;
for (my $j=0; $j <= $lastInputfilesIdx; $j++){ #Iterate over inputfiles
my $totallist = $passSampleRatioSamples[$j];
#Read file into array;
my ($file,$dir,$ext) = fileparse($totallist, qr/\.[^.]*/);
#Append filename to outputToWrite to create header
$outputToWrite .= "\t$file";
open(FILE, "$totallist") or die("Unable to open file: $!"); #Read count file
my @file= <FILE>;
close(FILE);
#Retrieve chr, start, stop, genename and region coverage from file by searching column indices
my $header = uc($file[0]); #Header in uppercase
chomp $header;
#Extract columns from header and use as index
my @colNames = qw(CHR START STOP GENE AUTO_VC);
my @indices = getColumnIdx($header, \@colNames);
my $chrIdx = $indices[0];
my $startIdx = $indices[1];
my $stopIdx = $indices[2];
my $geneIdx = $indices[3];
my $autoVcIdx = $indices[4];
my $lastFileIdx=$#file;
#Retrieve chr, start, stop, gene and regcov for each line in avg count file
my @autoVCs;
for (my $i=1; $i<=$lastFileIdx; $i++){ #Iterate over lines in file
my $line=$file[$i];
chomp $line;
$line =~ s/(?>\x0D\x0A?|[\x0A-\x0C\x85\x{2028}\x{2029}])//; #Remove Unix and Dos style line endings
my @lines=split("\t",$line);
my $chr = $lines[$chrIdx];
my $start = $lines[$startIdx];
my $stop = $lines[$stopIdx];
my $gene = $lines[$geneIdx];
my $autoVc = $lines[$autoVcIdx];
if ($j == 0){ #If first file to pass, add chr,start,stop,gene to array, to use in output later
push(@autoVCsToOutput, "$chr\t$start\t$stop\t$gene");
}
push(@autoVCs, $autoVc); #Push autoVC in array
}
my $autoVcString = join("_", @autoVCs); #Join all autoVCs and push into string
$autoVcHash{ $file } = $autoVcString; #Push filename as key and string as value into hash
push(@keyFiles, $file); #Save filenames in particular order for output later
}
$outputToWrite .= "\n";
my $lastKeyFilesIdx = $#keyFiles; #Retrieve last idx from files
my @autoVcOutput;
#Loop through files to create matrix of autoVCs
for (my $i=0; $i <= $lastKeyFilesIdx; $i++){
my $key = $keyFiles[$i]; #Loop through filenames, take value from hash, split into array and loop through array per line
my @autoVCsToPrint = split("_", $autoVcHash{ $key }); #Push splitted value into array to iterate over later
my $lastAutoVCsToPrintIdx = $#autoVCsToPrint; #Last index from autoVC array
#Loop through all values and add them to original value in autoVCsToOutput array
for( my $k=0; $k<=$lastAutoVCsToPrintIdx; $k++){ #Iterate over all autoVC values for sample
my $autoVcToAppend = $autoVCsToPrint[$k]; #Retrieve autoVC for target k from sample
my $newElement;
if ($i == $lastKeyFilesIdx) { #last file to process, so add additional linebreak to value
$newElement = $autoVCsToOutput[$k] . "\t$autoVcToAppend\n"; #Take original value from array and append new autoVC for target k to it
}else{
$newElement = $autoVCsToOutput[$k] . "\t$autoVcToAppend";
}
#Splice output element k from array and update with new (above created) element
splice(@autoVCsToOutput, $k, 1, $newElement);
}
}
#Concat array with autoVCs to output string
my $outputString = join("", @autoVCsToOutput);
$outputToWrite .= $outputString;
#reset outputs and inputs to original folders
$params->{outputdir} = $params->{outputdirOriginal};
$params->{inputdir} = $params->{inputdirOriginal};
#Write output to file
my $outputfile = ($params->{targetQcList} ? $params->{targetQcList} : $params->{outputdir}."/targetQcList.txt");
writeOutput($outputfile, $outputToWrite); #Write output to above specified file
}
###############################################
## Main code to extract region coverage from ##
## BAM file(s) ##
sub startWithBam{
my ($inputfiles) = @_;
###############################################
## Main code to extract region coverage from ##
## BAM file(s) ##
foreach my $bam (@$inputfiles){
#Check if *.bam.bai or *.bai file exist, otherwise skip this bam file
my ($file,$dir,$ext) = fileparse($bam, qr/\.[^.]*/);
print STDERR "Processing $file..\n";
my $bai_file = $file.".bai";
my $file_to_count;
unless (-e $params->{inputdir}."/".$bai_file) {
#Don't process this file, because it doesn't have an indexfile
print STDERR "##### WARNING #####WARNING #####\n".
"Cannot find an index file for file: ".$params->{inputdir}."/".$bam."\n".
"\t,skipping this file from analysis\n".
"##### WARNING ##### WARNING #####\n\n";
}else{
#set temp files... if necessary
my $tmp_dir = File::Temp->newdir();
my $rmdup_bam = File::Temp->new( TEMPLATE => 'tempXXXXX',DIR => $tmp_dir, SUFFIX => '.rmdup.bam' );
#Check if duplicates need to be removed
if (defined $params->{rmdup}){
#Process BAM files generating duplicate removed BAM files
rmDupBam($bam, $rmdup_bam, $tmp_dir);
print STDERR "Starting counts analysis..\n"; #Start to count regions
$file_to_count = $rmdup_bam;
if ($ext =~ /cram/i){
$ext = "bam";
}
}else{ #BAM files are already rmdupped, add them to list of files to process (retrieve them from inputdir cmdline)
$file_to_count = $params->{inputdir}."/".$bam;
}
print STDERR "Starting counts analysis..\n";
countFromBam($file_to_count, $file, $ext);
}
}
}
sub startWithAvgCount{
my ($inputfiles) = @_;
foreach my $txt (@$inputfiles){
#Set header for output file
my $outputToWrite = "CHR\tSTART\tSTOP\tGENE\tTARGET\tREGION_COV\tAVG_AUTOSOMAL_COV\tAVG_TOTAL_COV\tAVG_GENE_COV\tNORMALIZED_AUTOSOMAL\tNORMALIZED_TOTAL\tNORMALIZED_GENE\n";
#Read file into array;
my ($file,$dir,$ext) = fileparse($txt, qr/\.[^.]*/);
open(FILE, $params->{inputdir}."/".$txt) or die("Unable to open file: $!"); #Read count file
my @file= <FILE>;
close(FILE);
#Retrieve chr, start, stop, genename and region coverage from file by searching column indices
my $header = uc($file[0]); #Header in uppercase
chomp $header;
my @colNames = qw(CHR START STOP GENE TARGET REGION_COV);
my @indices = getColumnIdx($header, \@colNames);
my $args;
$args->{chrIdx} = $indices[0];
$args->{startIdx} = $indices[1];
$args->{stopIdx} = $indices[2];
$args->{geneIdx} = $indices[3];
$args->{targetIdx} = (defined $indices[4] ? $indices[4] : undef);
$args->{regcovIdx} = $indices[5];
$args->{lastFileIdx} =$#file;
#Calculate coverage on gene
my ($coverage, $genehash, $genes, $covchrauto, $covchrsex) = calcGeneCov($args, @file);
#Calculate coverage including sex chromomsomes
my ($covchrautoval, $covchrall, $counts) = calcCovAutoSex($genes, $covchrauto, $covchrsex);
#Foreach line in input file write away all calculated stats/values
$outputToWrite .= writeCountFile($args, $covchrautoval, $covchrall, $genehash, $counts, $coverage, @file);
my $outputfile = $params->{outputdir}."/".$file.".normalized.coverage.txt"; #Output filename
print STDERR "Writing normalized coverage counts to: $outputfile\n\n\n";
writeOutput($outputfile, $outputToWrite); #Write output to above specified file
print STDERR "Finished processing file: $txt\n\n\n";
}
}
##########################################################
## Main code to select most informative control samples ##
##########################################################
sub startWithMatchScore{
my $extension = shift;
my ($inputfiles) = $_[0];
my ($controlfiles) = $_[1];
foreach my $inputfile (@$inputfiles){ #Open sample file
my $outputExtnsn = "normalized.autosomal.coverage.all.controls.txt"; #Specify extension for output normalized coverage file
my $colsToExtract = "CHR START STOP GENE TARGET REGION_COV NORMALIZED_AUTOSOMAL NORMALIZED_TOTAL"; #Specify Columns to extract
my ($autodiff, $sexdiff, $perfectMatch) = createNormalizedCoverageFiles($inputfile, $extension, $outputExtnsn, $colsToExtract, \@$controlfiles); #Give input file to analyze, extension, columns to extract and list of controlfiles to use to function to retrieve normalized coverage
my %autodiffh = %$autodiff;
my %sexdiffh = %$sexdiff;
#Open output bestmatch file
my ($outputPostfixRemoved,$dir,$ext) = fileparse($inputfile, $extension);
#$outputPostfixRemoved =~ s/$extension//g; #Remove old extension from inputfile
my $outputfile = $params->{outputdir}."/".$outputPostfixRemoved.".best.match.score.txt"; #Output filename
#Do additional checks to detect perfect match samples and check when this occurs if there still are enough samples available in controlsdirectory to continues analysis
my $numBestMatchSamplesToProcess = keys %autodiffh; #Count number of samples to process (all - perfectMatch)
my $numBestMatchSamples=$params->{numBestMatchSamplesCmdL};
if ( $perfectMatch > 0){
if ($numBestMatchSamplesToProcess == $numBestMatchSamples){ #Detected perfect matches, but number of samples to process is the same as number of samples requested on cmdline
print STDERR "\n##### WARNING ##### WARNING #####\n";
print STDERR "Detected $perfectMatch perfect match(es) between sample and controlsamples, excluding these samples from the analysis.";
print STDERR "\n##### WARNING ##### WARNING #####\n";
}elsif ($numBestMatchSamplesToProcess >= ($numBestMatchSamples+$perfectMatch)){ #If there are more or equal #samples in controlsdir then specified on cmdline, use best #cmdline samples
$numBestMatchSamples=$numBestMatchSamples;
}else{ #Less samples than cmdline specified available, continue analysis but throw warning
print STDERR "\n##### WARNING ##### WARNING #####\n";
print STDERR "Detected $perfectMatch perfect match(es) between sample and controlsamples, which means only $numBestMatchSamplesToProcess instead of $numBestMatchSamples samples from controls directory are used for Match score analysis.";
print STDERR "\n##### WARNING ##### WARNING #####\n";
$numBestMatchSamples = $numBestMatchSamplesToProcess;
}
}
$perfectMatch=0; #Reset perfectMatch variable
print STDERR "\n#################################################################\n";
print STDERR "Selecting best $numBestMatchSamples control samples for analysis..\n";
print STDERR "###################################################################\n";
my @keys;
my @vals;
if (defined $params->{sexchr}) { #Use sex chromosomes switch, print all abs diffs including sex chromosomes
@keys = sort { $sexdiffh{$a} <=> $sexdiffh{$b} } keys(%sexdiffh);
@vals = @sexdiffh{@keys};
}else { #Only use autosomal chrs
@keys = sort { $autodiffh{$a} <=> $autodiffh{$b} } keys(%autodiffh);
@vals = @autodiffh{@keys};
}
my $outputToWrite= "SAMPLE\tSAMPLE_PATH\tCONTROL_SAMPLE\tCONTROL_SAMPLE_PATH\tAVERAGE_BEST_MATCH_SCORE\n"; #Assign header to output best match file
for (my $k=0; $k < $numBestMatchSamples; $k++){
print STDERR "Control: " . $keys[$k] . "\t\t\tAvg abs diff: " . $vals[$k] . "\n";
my $lin = join "\t", $inputfile,
$params->{inputdir}."/".$inputfile,$keys[$k],
$params->{controlsdir}."/".$keys[$k],$vals[$k]."\n";
$outputToWrite .= $lin; #concatenate full generated line to files
}
print STDERR "#######################################\n\n";
writeOutput($outputfile, $outputToWrite); #Write output to above specified file
}
}
###############################################
## Main code to detect CNVs ##
###############################################
sub startWithBestScore{
my $extension = shift;
my ($inputfiles_ref) = shift;
my ($normAutoControls_ref) = shift;
my @inputfiles = @$inputfiles_ref;
my @normAutoControls = @$normAutoControls_ref;
my $n_files = scalar @inputfiles;
for (my $m=0; $m < $n_files; $m++){
my $inputfilename = $inputfiles[$m];
my @sampleFile;
my @controlFile;
my @controlChr;
my @controlStart;
my @controlStop;
my @controlGene;
my @controlTarget;
my @sampleRatio;
print STDERR "\nAnalyzing sample: $inputfilename..\n";
my $outputToWrite= "CHR\tSTART\tSTOP\tGENE\tTARGET\t$inputfilename\t"; #Assign header to output best match file
open(INPUTFILE, $params->{inputdir}."/".$inputfilename) or die("Unable to open file: $!"); #Read best match file
my @inputfiledata= <INPUTFILE>;
close(INPUTFILE);
my $header = uc($inputfiledata[0]); #Header in uppercase
chomp $header;
my @colNames = qw(SAMPLE SAMPLE_PATH CONTROL_SAMPLE CONTROL_SAMPLE_PATH);
my @indices = getColumnIdx($header, \@colNames);
my $sampleIdx = $indices[0];
my $samplePathIdx = $indices[1];
my $controlIdx = $indices[2];
my $controlPathIdx = $indices[3];
my @array = split("\t", $header);
my $samplename = $array[$sampleIdx];
my $samplefile = $array[$samplePathIdx];
my $controlname = $array[$controlIdx];
my $controlfile = $array[$controlPathIdx];
my $lastLine=$#inputfiledata;
#Initialize arrays for arrayreferences
my @NORMAUTOSOMAL;
my @NORMTOTAL;
my @NORMGENE;
# Read samplefile into array (only do this once)
my $currentline = $inputfiledata[1]; #Open first samplefile from inputfile
my @crntlnArray = split("\t", $currentline);
# Read input samplefile into array
open(SAMPLEFILE, $crntlnArray[$samplePathIdx]) or die("Unable to open file: $!"); #Read SAMPLE best match file
@sampleFile= <SAMPLEFILE>;
close(SAMPLEFILE);
my $headerSample = uc($sampleFile[0]); #Header in uppercase
chomp $headerSample;
# Read normalized_autosomal values file
#Open norm auto file, further on calculate if sample is within 3SD from mean, otherwise exclude in sampleratio calculation
my @normAutoCon = @normAutoControls;
my $normautofile = $normAutoCon[$m];
open(NORMAUTOFILE, $params->{inputdir}."/".$normautofile) or die("Unable to open file: $!"); #Read count file
my @normautofile= <NORMAUTOFILE>;
close(NORMAUTOFILE);
#Extract sample file header indices
@colNames = qw(CHR START STOP GENE TARGET NORMALIZED_AUTOSOMAL NORMALIZED_TOTAL NORMALIZED_GENE);
my @indices_control = getColumnIdx($headerSample, \@colNames);
my $chrIdxControl = $indices_control[0];
my $startIdxControl = $indices_control[1];
my $stopIdxControl = $indices_control[2];
my $geneIdxControl = $indices_control[3];
my $targetIdxControl = $indices_control[4];
my $normAutoIdxSample = $indices_control[5];
my $normSexIdxSample = $indices_control[6];
my $normGeneIdxSample = $indices_control[7];
#Read through samplefile and push all three values into array of arrays;
my $lastLineSampleFile = $#sampleFile;
my @sampleNormAuto;
my @sampleNormTotal;
my @sampleNormGene;
for (my $i=1; $i<=$lastLineSampleFile; $i++){
my $currentline = $sampleFile[$i];
my @crntlnArray = split("\t", $currentline);
push(@controlChr , $crntlnArray[$chrIdxControl] );
push(@controlStart , $crntlnArray[$startIdxControl] );
push(@controlStop , $crntlnArray[$stopIdxControl] );
push(@controlGene , $crntlnArray[$geneIdxControl] );
push(@controlTarget , (defined $targetIdxControl ? $crntlnArray[$targetIdxControl] : "-" ));
push(@sampleNormAuto , $crntlnArray[$normAutoIdxSample]);
push(@sampleNormTotal, $crntlnArray[$normSexIdxSample] );
push(@sampleNormGene , $crntlnArray[$normGeneIdxSample]);
}
my $refNormAuto = \@sampleNormAuto; #Create array references
my $refNormTotal = \@sampleNormTotal;
my $refNormGene = \@sampleNormGene;
push(@NORMAUTOSOMAL, $refNormAuto);
push(@NORMTOTAL, $refNormTotal);
push(@NORMGENE, $refNormGene);
#Finalize header line for outputfile
my $lin = "AUTO_RATIO\tAUTO_ZSCORE\tAUTO_VC\tGENE_RATIO\tGENE_ZSCORE\tGENE_VC\tSHAPIRO-WILK\n";
$outputToWrite .= $lin; #concatenate full generated line to files