-
Notifications
You must be signed in to change notification settings - Fork 55
/
detect_cnv.pl
executable file
·4151 lines (3539 loc) · 222 KB
/
detect_cnv.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 warnings;
use strict;
use Carp;
use Pod::Usage;
use Getopt::Long;
BEGIN {($_=$0)=~s{[^\\\/]+$}{};$_||="./"}
use lib $_, $_."kext";
eval {
require "khmm.pm";
};
if ($@ and $@ =~ m/^Can't locate loadable object/ || $@ =~ m/^Floating point exception/ || $@ =~ m/^Core dumped/) { #'
require Config;
my $arch = $Config::Config{archname} || 'UNKNOWN';
print STDERR "PennCNV compilation error: $@\n";
print STDERR "PennCNV compilation error: Your system architecture is '$arch', which is not compatible with pre-compiled executables in PennCNV package.\n";
print STDERR "PennCNV compilation error: Please download source code from http://www.openbioinformatics.org/penncnv and compile executable program.\n";
exit (100);
}
if ($@ and $@ =~ m/^Can't locate khmm.pm/) { #'
print STDERR "PennCNV module error: Can't locate khmm.pm in $_/kext\n";
print STDERR "PennCNV module error: Please make sure that $_/kext/khmm.pm file exists after decompressing the PennCNV package\n";
exit (200);
}
if ($@) {
print STDERR "PennCNV error: $@\n";
print STDERR "PennCNV compilation error: Please download source code from http://www.openbioinformatics.org/penncnv/ and compile executable program.\n";
exit (400);
}
our $VERSION = '$Revision: bbb13c8a31de6a6e9a1e71ca347a7d02a855a27b $';
our $LAST_CHANGED_DATE = '$LastChangedDate: 2013-02-08 11:10:50 -0800 (Fri, 08 Feb 2013) $';
our ($verbose, $help, $man);
our ($inputfile, @inputfile);
our ($train, $ctrain, $test, $hmmfile, $region, $loh, $minsnp, $minlength, $minconf, $pfbfile, $trio, $quartet, $chrx, $chry, $medianadjust, $cnvfile, $heterosomic_threshold, $denovo_rate, $sdadjust, $bafadjust, $sexfile, $fmprior, $listfile, $exclude_heterosomic, $output, $joint, $record_count, $logfile, $summary, $confidence, $tabout, $coordinate_from_input, $gcmodelfile, $cctest, $phenofile, $onesided, $control_label, $type_filter, $directory, $flush, $validate, $delfreq, $dupfreq, $backfreq, $startsnp, $endsnp, $candlist, $bafxhet_threshold, $valilog, $cnprior, $tseq, $gamma, $paramfile, $lastchr, $cache, $stroma, $refchr, $refgcfile, @ref_median);
our (@fmprior, @cnprior, $gamma_k, $gamma_theta);
processArgument ();
if ($train) {
trainCHMM (\@inputfile, $hmmfile, $pfbfile, $gcmodelfile, $directory);
} elsif ($ctrain) {
ctrainCHMM ($inputfile[0], $hmmfile);
} elsif ($test) {
my $hmm = readHMMFile ($hmmfile);
$loh and $hmm->{B1_mean}[3] > 1 and pod2usage ("Error: the supplied -hmmfile $hmmfile is not suitable for LOH inference, but for CNV detection only");
if ($stroma) {
newtumorCHMM (\@inputfile, $hmmfile, $pfbfile, $sexfile, $gcmodelfile, $directory);
} else {
newtestCHMM (\@inputfile, $hmmfile, $pfbfile, $sexfile, $gcmodelfile, $directory);
}
} elsif ($validate) {
my $candregion;
if ($candlist) {
$candregion = retrieveCandidateRegion ($candlist);
} else {
if ($cnprior) {
$candregion = [[$startsnp, $endsnp, @cnprior]];
$verbose and print STDERR "NOTICE: For validating CNV calls of $startsnp-$endsnp, the prior distribution is given as @cnprior\n";
} else {
$candregion = [[$startsnp, $endsnp, convertDelDupFreqToPrior ($delfreq, $dupfreq, $backfreq)]];
$verbose and print STDERR "NOTICE: For validating CNV calls of $startsnp-$endsnp, the prior distribution is set at ", join (",", convertDelDupFreqToPrior ($delfreq, $dupfreq, $backfreq)), "\n";
}
}
newvalidateCNVCall (\@inputfile, $hmmfile, $pfbfile, $sexfile, $gcmodelfile, $directory, $candregion);
} elsif ($trio) {
scalar (@inputfile) % 3 == 0 or pod2usage ("Error in argument: the inputfiles do not appear to form one or more complete trios (${\(scalar @inputfile)} inputifles provided)");
for my $i (0 .. @inputfile/3-1) {
my @trioinputfile = @inputfile[$i*3..($i*3+2)];
print STDERR "NOTICE: Recalling CNVs for trio: @trioinputfile\n";
newtestTrioCNVFile (\@trioinputfile, $hmmfile, $pfbfile, $cnvfile, $sexfile, $gcmodelfile, $directory);
}
} elsif ($quartet) {
scalar (@inputfile) % 4 == 0 or pod2usage ("Error in argument: the inputfiles do not appear to form one or more complete quartets (${\(scalar @inputfile)} inputifles provided)");
for my $i (0 .. @inputfile/4-1) {
my @quartetinputfile = @inputfile[$i*4..($i*4+3)];
print STDERR "NOTICE: Recalling CNVs for quartet: @quartetinputfile\n";
newtestQuartetCNVFile (\@quartetinputfile, $hmmfile, $pfbfile, $cnvfile, $sexfile, $gcmodelfile, $directory);
}
} elsif ($exclude_heterosomic) {
excludeHeterosomic ($cnvfile);
} elsif ($summary) {
calculateSampleSummary (\@inputfile, $pfbfile, $gcmodelfile, $directory);
} elsif ($joint) {
scalar (@inputfile) % 3 == 0 or pod2usage ("Error in argument: the inputfiles do not appear to form one or more complete trios (${\(scalar @inputfile)} inputifles provided)");
for my $i (0 .. @inputfile/3-1) {
my @familyfile = @inputfile[$i*3..($i*3+2)];
jointCNVCall (\@familyfile, $hmmfile, $pfbfile, $sexfile, $chrx||0, $chry||0, $gcmodelfile, $directory);
}
} elsif ($cctest) {
cctestCNV ($cnvfile, $phenofile, $pfbfile);
} elsif ($tseq) {
testSEQ (\@inputfile, $hmmfile);
}
#check the validity of arguments supplied to the program, and assign default values to various arguments
sub read_refgcfile {
print $refgcfile."\n";
open (REFGC, $refgcfile) or confess "\nERROR: cannot read from refgcfile $refgcfile: $!\n";
chomp (@ref_median = <REFGC>);
close REFGC;
}
sub processArgument {
my @command_line = @ARGV; #command line argument
GetOptions ('verbose|v'=>\$verbose, 'help|h'=>\$help, 'man|m'=>\$man,
'train'=>\$train, 'ctrain'=>\$ctrain, 'test|wgs'=>\$test, 'trio'=>\$trio, 'quartet'=>\$quartet, 'joint'=>\$joint, 'summary'=>\$summary, 'cctest'=>\$cctest, 'validate'=>\$validate,
'hmmfile=s'=>\$hmmfile, 'pfbfile=s'=>\$pfbfile, 'cnvfile=s'=>\$cnvfile, 'output=s'=>\$output, 'sexfile=s'=>\$sexfile, 'logfile=s'=>\$logfile,
'minsnp=i'=>\$minsnp, 'minlength=s'=>\$minlength, 'minconf=f'=>\$minconf,
'chrx'=>\$chrx, 'chry'=>\$chry, 'medianadjust!'=>\$medianadjust, 'bafadjust!'=>\$bafadjust, 'sdadjust!'=>\$sdadjust,
'heterosomic_threshold=i'=>\$heterosomic_threshold, 'denovo_rate=f'=>\$denovo_rate,
'fmprior=s'=>\$fmprior, 'listfile=s'=>\$listfile, 'exclude_heterosomic'=>\$exclude_heterosomic, 'record_count=i'=>\$record_count,
'confidence'=>\$confidence, 'tabout'=>\$tabout, 'loh'=>\$loh,
'coordinate_from_input'=>\$coordinate_from_input, 'phenofile=s'=>\$phenofile,
'onesided'=>\$onesided, 'control_label=s'=>\$control_label, 'type_filter=s'=>\$type_filter, 'gcmodelfile|gcwavefile=s'=>\$gcmodelfile,
'directory=s'=>\$directory, 'flush!'=>\$flush, 'startsnp=s'=>\$startsnp, 'endsnp=s'=>\$endsnp, 'delfreq=f'=>\$delfreq, 'dupfreq=f'=>\$dupfreq,
'backfreq=f'=>\$backfreq, 'candlist=s'=>\$candlist, 'region=s'=>\$region, 'bafxhet=f'=>\$bafxhet_threshold, 'valilog=s'=>\$valilog, 'cnprior=s'=>\$cnprior,
'tseq'=>\$tseq, 'gamma=s'=>\$gamma, 'paramfile=s'=>\$paramfile, 'lastchr=i'=>\$lastchr, 'cache'=>\$cache, 'stroma=f'=>\$stroma,
'refchr=s' => \$refchr, 'refgcfile=s' => \$refgcfile,
) or pod2usage ();
$help and pod2usage (-verbose=>1, -exitval=>1, -output=>\*STDOUT);
$man and pod2usage (-verbose=>2, -exitval=>1, -output=>\*STDOUT);
#CHECK THE NUMBER OF OPERATIONS SPECIFIED IN COMMAND LINE; ONE AND ONLY ONE OPERATION IS ALLOWED
my $num_operation = 0;
$train and $num_operation++;
$ctrain and $num_operation++;
$test and $num_operation++;
$validate and $num_operation++;
$trio and $num_operation++;
$quartet and $num_operation++;
$exclude_heterosomic and $num_operation++;
$summary and $num_operation++;
$joint and $num_operation++;
$cctest and $num_operation++;
$tseq and $num_operation++;
$num_operation == 1 or pod2usage ("Error in argument: please specify one and only one operation such as --test, --trio, --quartet, --joint, --summary or --cctest");
#CHECK THE REQUIRED ARGUMENTS FOR EACH OPERATION; WARN THE USER ABOUT MISSING REQUIRED ARGUMENTS
if ($train) {
defined $hmmfile and defined $pfbfile and defined $output or pod2usage ("Error in argument: please specify the -hmmfile, --pfbfile and --output arguments for the --train operation");
} elsif ($ctrain) {
defined $hmmfile and defined $output or pod2usage ("Error in argument: please specify the -hmmfile and --output arguments for the --train operation");
} elsif ($test) {
defined $hmmfile and defined $pfbfile or pod2usage ("Error in argument: please specify the -hmmfile and --pfbfile arguments for the --test operation");
} elsif ($validate) {
defined $hmmfile and defined $pfbfile or pod2usage ("Error in argument: please specify the -hmmfile and --pfbfile arguments for the --validate operation");
if ($candlist) {
if ($cnprior) {
pod2usage ("Error in argument: please do NOT specify --cnprior when --candlist is provided");
}
if ($startsnp or $endsnp or defined $delfreq or defined $dupfreq) {
pod2usage ("Error in argument: please do NOT specify --startsnp or --endsnp or --delfreq or --dupfreq for --validate operation when --candlist is provided");
}
} elsif ($cnprior) {
defined $startsnp and defined $endsnp or pod2usage ("Error in argument: please specify --startsnp and --endsnp for the --validate operation when --candlist is not provided");
if (defined $delfreq or defined $dupfreq) {
pod2usage ("Error in argument: please do NOT specify --delfreq or --dupfreq for --validate operation when --cnprior is provided");
}
} else {
defined $delfreq || defined $dupfreq or pod2usage ("Error in argument: please specify --delfreq or --dupfreq or --cnprior for the --validate operation when --candlist is not provided");
defined $startsnp and defined $endsnp or pod2usage ("Error in argument: please specify --startsnp and --endsnp for the --validate operation when --candlist is not provided");
defined $delfreq and $delfreq <= 1 && $delfreq >=0 || pod2usage ("Error in argument: the --delfreq ($delfreq) must be between 0 and 1");
defined $dupfreq and $dupfreq <= 1 && $dupfreq >=0 || pod2usage ("Error in argument: the --delfreq ($dupfreq) must be between 0 and 1");
defined $delfreq and defined $dupfreq and $delfreq+$dupfreq<1 || pod2usage ("Error in argument: the sum of --delfreq ($delfreq) and --dupfreq ($dupfreq) must be less than 1");
}
} elsif ($trio) {
defined $hmmfile and defined $pfbfile and defined $cnvfile or pod2usage ("Error in argument: please specify the --hmmfile and --pfbfile and --cnvfile arguments for the --trio operation");
} elsif ($quartet) {
defined $hmmfile and defined $pfbfile and defined $cnvfile or pod2usage ("Error in argument: please specify the --hmmfile and --pfbfile and --cnvfile arguments for the --quartet operation");
} elsif ($exclude_heterosomic) {
$cnvfile or pod2usage ("Error in argument: please specify --cnvfile for the --exclude_heterosomic operation");
} elsif ($summary) {
defined $pfbfile or pod2usage ("Error in argument: please specify the --pfbfile arguments for the --summary operation");
} elsif ($joint) {
defined $hmmfile and defined $pfbfile or pod2usage ("Error in argument: please specify the --hmmfile and --pfbfile arguments for the --joint operation");
} elsif ($cctest) {
defined $pfbfile and defined $cnvfile and $phenofile or pod2usage ("Error in argument: please specify the --pfbfile and --cnvfile and --phenofile arguments for the --cctest opearation");
} elsif ($tseq) {
defined $hmmfile or pod2usage ("Error in argument: please specify the -hmmfile arguments for the --tseq operation");
}
#CHECK OPERATION-SPECIFIC ARGUMENTS: PREVENT USER FROM SPECIFYING USELESS ARGUMENTS TO THE PROGRAM
if ($startsnp or $endsnp or defined $delfreq or defined $dupfreq or defined $backfreq or defined $candlist) {
$validate or pod2usage ("Error in argument: the --startsnp, --endsnp, --delfreq, --dupfreq, --backfreq or --candlist argument is only supported for the --validate operation");
}
if ($cnvfile) {
$trio or $quartet or $exclude_heterosomic or $cctest or pod2usage ("Error in argument: the --cnvfile argument is only supported for the --trio or --quartet or --exclude_heterosomic or --cctest operation");
}
if (defined $minconf or $confidence) {
$test or $validate or pod2usage ("Error in argument: the --confidence or --minconf argument is supported only for the --test and --validate operation");
}
if ($loh) {
print STDERR "WARNING in argument: the --loh argument is obselete and may be removed in future releases!!!\n";
$test or pod2usage ("Error in argument: the --loh argument is supported only for the --test operation");
}
if (defined $type_filter or defined $control_label or defined $phenofile or $onesided) {
$cctest or pod2usage ("Error in argument: the --type_filter, --control_label, --phenofile or --onesided argument is supported only for the --cctest operation");
}
if (defined $fmprior or defined $denovo_rate) {
$trio or $quartet or pod2usage ("Error in argument: the --fmprior or --denovo_rate argument is supported only for the --trio and --quartet operation");
}
if (defined $cnprior) {
$validate or pod2usage ("Error in argument: the --cnprior argument is supported only for the --validate operation");
}
if ($hmmfile) {
$train or $ctrain or $test or $trio or $quartet or $joint or $tseq or $validate or pod2usage ("Error in argument: the --hmmfile argument is supported only for the --train, --ctrain, --test, --trio, --quartet, --joint, --validation or --tseq operations");
}
if (defined $directory) {
$test or $trio or $quartet or $joint or $validate or $summary or pod2usage ("Error in argument: the --directory argument is supported only for the --test, --trio, --quartet, --joint, --validation or --summary operations");
}
if (defined $heterosomic_threshold) {
$exclude_heterosomic or pod2usage ("Error in argument: the --heterosomic_threshold argument is only supported for the --exclude_heterosomic operation");
}
if (defined $record_count) {
$ctrain or pod2usage ("Error in argument: the --record_count argument is only supported for the --ctrain operation");
}
#CNV-calling related arguments should not be specified when performing non-calling operations
if ($chrx or $chry) {
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --chrx or --chry argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if ($medianadjust or $bafadjust or $sdadjust) {
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --medianadjust, --bafadjust or --sdadjust argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if ($gcmodelfile) {
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --gcmodelfile argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if (defined $refchr){
defined $refgcfile or pod2usage("Error in argument: the --refgcfile argument must be specified if --refchr is specified.")
}
if (defined $refgcfile){
defined $refchr or pod2usage("Error in argument: the --refchr argument must be specified if --refgcfile is specified.")
}
if (defined $refchr and defined $refgcfile){
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --refchr and --refgcfile argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if (defined $refgcfile) {
read_refgcfile ();
}else{
$refchr = '11';
@ref_median = qw/54.8207535282258 56.8381472081218 53.1218950320513 46.9484174679487 39.9367227359694 38.3365384615385 41.9867788461538 40.4431401466837 44.5320512820513 42.1979166666667 41.6984215561224 43.1598557692308 43.4388020833333 40.8104967948718 39.8444475446429 41.5357572115385 38.7496995192308 45.0213249362245 42.3251201923077 43.5287459935897 40.7440808354592 37.0492788461538 36.5006009615385 35.8518016581633 35.2767427884615 35.1972155448718 36.5286192602041 39.4890825320513 36.5779246794872 36.7275641025641 38.3256935586735 37.791266025641 41.1777844551282 41.950534119898 42.3639823717949 41.9208733974359 41.2061543367347 35.4974959935897 35.2123397435897 36.5101841517857 36.7135416666667 36.8268229166667 37.6945153061224 40.7453926282051 47.7049278846154 47.3233173076923 44.7361288265306 46.6585536858974 39.1593549679487 36.5684789540816 38.2718466806667 37.184425 37.184425 37.184425 37.184425 35.9227764423077 41.1157852564103 41.6662348533163 39.7402844551282 40.0149238782051 46.6417211415816 49.9136618589744 45.2016225961538 51.3019172512755 52.0818309294872 51.1320112179487 49.9807185102302 49.9807185102302 49.5874473187766 50.547349024718 50.7186498397436 45.6435347576531 46.3352363782051 42.4091546474359 46.6399274553571 43.7746394230769 45.0160256410256 41.8526642628205 43.8899075255102 38.5112179487179 36.1038661858974 36.1689851721939 39.8506610576923 37.0439703525641 36.8012595663265 40.2521033653846 39.661858974359 37.5013769093564 35.5448717948718 36.9039979272959 35.2046274038462 38.2195512820513 40.074537627551 40.7097355769231 40.5470753205128 38.4104380072343 36.131109775641 35.3915264423077 34.9693080357143 36.2953725961538 37.9602363782051 39.1942362882653 37.4464142628205 36.8879206730769 35.7242588141026 36.7556202168367 37.0639022435897 40.6929086538462 38.385084502551 39.4121594551282 40.2410857371795 42.0772879464286 43.2935697115385 43.2345753205128 40.9113919005102 44.9575320512821 46.2513020833333 46.4753069196429 48.3886217948718 47.8520633012821 43.8001802884615 39.808274872449 44.5042067307692 38.3835136217949 44.9097177933673 45.5366586538462 41.7346754807692 39.2198461415816 41.9489182692308 44.3351362179487 42.7910754145408 42.3190104166667 42.0425681089744 47.0514787946429 45.3482603740699/;
}
if ($tabout or $coordinate_from_input) {
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --tabout or --coordinate_from_input argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if (defined $minsnp or defined $minlength) {
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --minsnp or --minlength argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if (defined $region) {
$test or $trio or $quartet or $joint or $validate or pod2usage ("Error in argument: the --region argument is supported only for the --test, --trio, --quartet, --joint or --validation operations");
}
if (defined $gamma) {
$tseq or pod2usage ("Error in argument: the --gamma argument is supported only for the --tseq operation");
$gamma =~ m/^[\d\.]+,[\d\.]+$/ or pod2usage ("Error in argument: the --gamma argument should be specified as two floating point numbers separated by comma");
($gamma_k, $gamma_theta) = split (/,/, $gamma);
}
if (defined $paramfile) {
defined $gamma and pod2usage ("Error in argument: please do not specify --gamma and --paramfile simultaneously");
open (PARAM, $paramfile) or confess "Error: cannot read from --paramfile $paramfile: $!\n";
while (<PARAM>) {
if (m/k=([\d\.]+)\s+theta\d?=([\d\.]+)/) {
($gamma_k, $gamma_theta) = ($1, $2);
}
}
close (PARAM);
$gamma_k or confess "Error: unable to read gamma values from the --paramfile $paramfile\n";
}
#GET THE LIST OF INPUT FILE NAMES USED IN THE SUBSEQUENT ANALYSIS
if (not $cctest and not $exclude_heterosomic) { #these two operations do NOT require signal files as input
if (@ARGV) {
$listfile and pod2usage ("Error in argument: please do not specify the --listfile argument ($listfile) and provide signal file names (@ARGV) in command line simultaneously");
@inputfile = @ARGV;
} else {
$listfile or pod2usage ("Error in argument: please either specify the --listfile argument or provide signal file names in command line\n");
open (LIST, $listfile) or confess "\nERROR: cannot read from listfile $listfile: $!";
while (<LIST>) {
s/^\s+|\s*[\r\n]+$//g; #get rid of leading and trailing spaces
$_ or print STDERR "WARNING: blank lins in $listfile detected and skipped\n" and next;
if ($trio or $joint) {
m/^([^\t]+)\t([^\t]+)\t([^\t]+)$/ or confess "\nERROR: the --listfile should contain 3 tab-delimited file names per line for the --trio or --joint operation (invalid line found: <$_>)\n";
push @inputfile, $1, $2, $3;
} elsif ($quartet) {
m/^([^\t]+)\t([^\t]+)\t([^\t]+)\t([^\t]+)$/ or confess "\nERROR: the --listfile should contain 4 tab-delimited file names per line for the --quartet operation (invalid line found: <$_>)\n";
push @inputfile, $1, $2, $3, $4;
} else {
m/^([^\t]+)$/ or confess "\nERROR: the --listfile should contain one file name per line without tab character (invalid line found: <$_>)\n";
push @inputfile, $1;
}
}
close (LIST);
}
}
defined $flush or $flush = 1;
$flush and $| = 1; #flush input/output buffer to minitor program progress in real time (when using remote connections)
if (defined $minlength) {
$minlength =~ m/^\d+(k|m)?$/i or pod2usage ("Error in argument: the --minlength argument should be a positive integer (suffix of k or m is okay)");
$minlength =~ s/k$/000/i;
$minlength =~ s/m$/000000/i;
}
defined $minconf and $confidence = 1; #automatically set the --confidence argument to 1 for confidence score calculation
defined $hmmfile and readHMMFile ($hmmfile); #check the validity of HMM file
$minsnp ||= 3; #by default only call CNVs containing more than or equal to 3 SNPs for Illumina HumanHap550 array
$heterosomic_threshold ||= 5; #by default if there are more than 5 CNVs in the same chromosome with same CN state, it is likely to be caused by cell-line artifacts
$denovo_rate ||= 0.0001; #by default de novo rate is 0.0001 (the rationale is that 1% individuals have denovo CNVs, but each individual may have 20-100 detectable CNVs, so the prior is somewhere around 0.0001 for any given CNV call)
defined $medianadjust or $medianadjust = 1; #by default --medianadjust is turned on, since it usually improve calling
defined $sdadjust or $sdadjust = 1; #as of Jan 2008, this is on by default (to reduce false positve rate for low-quality samples empirically)
defined $bafadjust or $bafadjust = 1; #as of June 2008, this is on by default (to reduce false positve rate for low-quality samples empirically)
defined $bafxhet_threshold or $bafxhet_threshold = 0.1; #as of Jan 2009, this becomes an argumen that user can change (by default is 10% markers have BAF around 0.5 the same is predicted as female; it works for Illumina SNP arrays well but not for Affy arrays).
$bafxhet_threshold > 0 and $bafxhet_threshold < 1 or pod2usage ("Error in argument: the --bafxhet argument ($bafxhet_threshold) should be between 0 and 1");
$chrx and $chry and pod2usage ("Error in argument: please do not specify --chrx and --chry simultaneously");
if ($chrx or $chry) {
$chrx and $chry and pod2usage ("Error in argument: please do NOT specify both --chrx and --chry argument");
$region and pod2usage ("Error in argument: the --region argument should NOT be specified when --chrx or --chry is provided");
}
if (defined $sexfile) {
$chrx or $chry or pod2usage ("Error in argument: the --sexfile argument should NOT be specified when neither --chrx nor --chry is provided");
}
if (defined $lastchr) {
$lastchr > 0 or pod2usage ("Error in argument: the --lastchr argument must be a positive integer");
} else {
$lastchr = 22;
}
if ($chrx) {
$region = 'X';
} elsif ($chry) {
$region = 'Y';
} else {
$region ||= "1-$lastchr";
}
if (defined $type_filter) {
$type_filter eq 'dup' or $type_filter eq 'del' or pod2usage ("Error in argument: the --type_filter can be only 'del' or 'dup' but not '$type_filter'");
}
$control_label ||= 'control'; #default text label for control is "control" (or the number 1)
if ($fmprior) {
@fmprior = split (/,/, $fmprior);
map {s/^$/0/} @fmprior; #handle situations where no number is given for a state (blank between consecutive commas)
@fmprior == 6 or pod2usage ("Error in argument: the --fmprior argument should be 6 comma-separated numbers that sum up to 1");
abs (sum (\@fmprior) - 1) < 0.01 or pod2usage ("Error in argument: the --fmprior argument should be 6 comma-separated numbers that sum up to 1");
unshift @fmprior, 0; #fill in the first element of array so hidden state starts from subscript 1 to 6
} else {
@fmprior = (0, 0.01*0.5, 0.49*0.5, 0.5, 0, 0.49*0.5, 0.01*0.5);
}
if ($cnprior) {
@cnprior = split (/,/, $cnprior);
map {s/^$/0/} @cnprior;
map {$_||=1e-9} @cnprior;
@cnprior == 5 or pod2usage ("Error in argument: the --cnprior argument should be 5 comma-separated numbers, corresponding to probability for CN=0 to CN=4");
}
if (defined $backfreq) {
$backfreq > 0 and $backfreq < 0.5 or pod2usage ("Error in argument: the --backfreq argument ($backfreq) should be less than 0.5");
} else {
$backfreq = 0.0001; #by default, the background freq means that 0.01% of whole genome markers are in CNV
}
if ($validate) {
defined $delfreq or $delfreq = $backfreq;
defined $dupfreq or $dupfreq = $backfreq;
}
if (defined $output) { #default output is STDOUT
open (STDOUT, ">$output") or confess "\nERROR: cannot write to output file $output";
}
if ($logfile) {
open (LOG, ">$logfile") or die "Error: cannot write to log file $logfile: $!\n";
print LOG "PennCNV Version:\n\t", q/$LastChangedDate: 2013-02-08 11:10:50 -0800 (Fri, 08 Feb 2013) $/, "\n";
print LOG "PennCNV Information:\n\tFor questions, comments, documentation, bug reports and program update, please visit http://www.openbioinformatics.org/penncnv/\n";
print LOG "PennCNV Command:\n\t$0 @command_line\n";
print LOG "PennCNV Started:\n\t", scalar (localtime), "\n";
close (LOG);
my $notee = 0;
my $msg = qx/perl -v | tee 2>&1/; #check whether tee is installed in the system
if ($msg =~ m/tee/ or not $msg) { #system error message should contain "tee" word
$notee++;
} else {
eval {
open(STDERR, " | tee $logfile 1>&2"); #redirect STDERR to a logfile, but also print out the message to STDERR
};
$@ and $notee++;
}
if ($notee) {
$verbose and print STDERR "WARNING: cannot set up dual-output of notification/warning message to STDERR and to log file $logfile (unable to execute 'tee' command in your system)\n";
print STDERR "NOTICE: All program notification/warning messages will be written to log file $logfile\n";
open (STDERR, ">>$logfile") or confess "\nERROR: unable to write to log file $logfile: $!\n";
} else {
print STDERR "NOTICE: All program notification/warning messages that appear in STDERR will be also written to log file $logfile\n";
}
}
}
#this subroutine is used to generate an offspring_state array that contains all possible combinations of offspring states. Right now it only support up to two offsprings
sub generateOstateArray {
my ($num_element, $symbol) = @_;
my @return;
if ($num_element == 2) {
for my $i (@$symbol) {
for my $j (@$symbol) {
push @return, [$i, $j];
}
}
} else {
confess "\nERROR: the generateOstateArray subroutine can only handle two offsprings at this time (but you gave $num_element)\n";
}
return @return;
}
#this subroutine converts an index into three states (state range from 1 to 6)
sub convertTrioIndex2State {
my ($index) = @_;
my $fstate = int ($index / 49);
my $mstate = int (($index - $fstate*49) / 7);
my $ostate = ($index - $fstate*49) % 7;
return ($fstate, $mstate, $ostate);
}
#this subroutine converts an index into four states (state range from 1 to 6)
sub convertQuartetIndex2State {
my ($index) = @_;
my $o2state = int ($index/343);
my $o1state = int (int ($index - $o2state * 343) / 49);
my $mstate = int (($index - $o2state*343 - $o1state*49) / 7);
my $fstate = $index - $o2state*343 - $o1state*49 - $mstate*7;
return ($fstate, $mstate, $o1state, $o2state);
}
#read transition matrix from the HMM file
sub readTransitionMatrix {
my ($hmmfile) = @_;
my ($found_transition, $transition);
push @$transition, 0; #convert 0-based index to 1-based index
open (HMM, $hmmfile) or confess "\nERROR: cannot read from HMM file $hmmfile: $!\n";
while (<HMM>) {
m/^A:/ and ++$found_transition and next;
m/^B:/ and last;
if ($found_transition) {
s/^\s+|\s*[\r\n]+$//g;
my @trans = split (/\s+/, $_);
unshift @trans, 0; #convert 0-based index to 1-based index
push @$transition, [@trans];
}
}
close (HMM);
return ($transition);
}
#from siginfo, get the LRR/BAF values for a specific genomic region
sub getRegionInfo {
my ($siginfo, $pfbinfo, $nextregion, $startname, $endname) = @_;
my ($region_name, $region_chr, $region_pos, $region_lrr, $region_baf, $region_pfb, $region_snpdist);
my ($c, $s, $e) = @$nextregion;
my ($found, $last);
my $info = $siginfo->{$c};
my ($name, $pos, $lrr, $baf) = ($info->{name}, $info->{pos}, $info->{lrr}, $info->{baf});
for my $i (0 .. @$name-1) {
if ($name->[$i] eq $s) {
$found = 1;
} elsif ($name->[$i] eq $e) {
$last = 1;
}
if ($found) {
push @$region_name, $name->[$i];
push @$region_chr, $c;
push @$region_pos, $pos->[$i];
push @$region_lrr, $lrr->[$i];
push @$region_baf, $baf->[$i];
my @temp = split (/\t/, $pfbinfo->{$name->[$i]});
push @$region_pfb, $temp[2];
if ($i < @$name-1) {
push @$region_snpdist, ($pos->[$i+1]-$pos->[$i]) || 1;
} else {
push @$region_snpdist, 100_000_000;
}
}
$last and last;
}
#generally speaking, we try to make the start of the block open (shift the startsnp), but the end of the block solid (keep the endsnp)
if ($endname->{$s}) {
shift @$region_name; shift @$region_chr; shift @$region_pos; shift @$region_lrr; shift @$region_baf; shift @$region_pfb; shift @$region_snpdist;
}
if ($startname->{$e}) {
if (not $endname->{$e}) {
#when there is only one element (when startsnp is the end of previous block, and endsnp is begin of next block), arbitrarily create a single-SNP block
if (@$region_name == 1) {
$endname->{$e}++; #mark this SNP as constituting an end SNP, even though it is not a endSNP in the CNV file
} else {
pop @$region_name; pop @$region_chr; pop @$region_pos; pop @$region_lrr; pop @$region_baf; pop @$region_pfb; pop @$region_snpdist;
}
}
}
return ($region_name, $region_chr, $region_pos, $region_lrr, $region_baf, $region_pfb, $region_snpdist);
}
#read the HMM file
sub readHMMFile {
my ($inputfile) = @_;
my (%hmm, @cell);
open (HMM, $inputfile) or confess "\nERROR: cannot read from HMM file $hmmfile: $!\n";
my @line = <HMM>;
map {s/[\r\n]+$//} @line;
$line[0] eq 'M=6' or confess "\nERROR: invalid record found in HMM file: <$_> ('M=6' expected)\n";
$line[1] eq 'N=6' or confess "\nERROR: invalid record found in HMM file: <$_> ('N=6' expected)\n";
$line[2] eq 'A:' or confess "\nERROR: invalid record found in HMM file: <$_> ('A:' expected)\n";
$line[9] eq 'B:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B:' expected)\n";
$line[16] eq 'pi:' or confess "\nERROR: invalid record found in HMM file: <$_> ('pi:' expected)\n";
$line[18] eq 'B1_mean:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B1_mean:' expected)\n";
$line[20] eq 'B1_sd:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B1_sd:' expected)\n";
$line[22] eq 'B1_uf:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B1_uf:' expected)\n";
$line[24] eq 'B2_mean:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B2_mean:' expected)\n";
$line[26] eq 'B2_sd:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B2_sd:' expected)\n";
$line[28] eq 'B2_uf:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B2_uf:' expected)\n";
if (@line > 30) {
#print STDERR "NOTICE: HMM model file $inputfile contains parameters for non-polymorphic (NP) probes\n";
@line == 36 or @line == 38 or confess "\nERROR: invalid number of records found in HMM file: 30 or 36 or 38 lines expected\n";
$line[30] eq 'B3_mean:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B3_mean:' expected)\n";
$line[32] eq 'B3_sd:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B3_sd:' expected)\n";
$line[34] eq 'B3_uf:' or confess "\nERROR: invalid record found in HMM file: <$_> ('B3_uf:' expected)\n";
if (@line == 38) {
$line[36] eq 'DIST:' or confess "\nERROR: invalid record found in HMM file: <$_> ('DIST:' expected)\n";
}
}
for my $i (3 .. 8) {
@cell = split (/\s+/, $line[$i]);
abs (sum (\@cell) - 1) < 1e-5 or confess "\nERROR: invalid line ${\($i+1)} in HMM file: <$_> (sum of line should be 1)\n";
push @{$hmm{'A'}}, [@cell];
}
@cell = split (/\s+/, $line[17]);
abs (sum (\@cell) - 1) < 1e-5 or confess "\nERROR: invalid line in HMM file: <$line[17]> (sum of line should be 1)\n";
push @{$hmm{'pi'}}, @cell;
@cell = split (/\s+/, $line[19]);
@cell == 6 or confess "\nERROR: invalid line in HMM file: <@cell> (6 fields expected)\n";
push @{$hmm{'B1_mean'}}, @cell;
@cell = split (/\s+/, $line[21]);
@cell == 6 or confess "\nERROR: invalid line in HMM file: <@cell> (6 fields expected)\n";
push @{$hmm{'B1_sd'}}, @cell;
grep {$_>0} @cell == 6 or confess "\nERROR: invalid line in HMM file: <@cell> (all values should be between greater than zero)\n";
@cell = split (/\s+/, $line[23]);
@cell == 1 or confess "\nERROR: invalid line in HMM file: <@cell> (1 fields expected)\n";
push @{$hmm{'B1_uf'}}, @cell;
@cell = split (/\s+/, $line[25]);
@cell == 5 or confess "\nERROR: invalid line in HMM file: <@cell> (5 fields expected)\n";
push @{$hmm{'B2_mean'}}, @cell;
@cell = split (/\s+/, $line[27]);
@cell == 5 or confess "\nERROR: invalid line in HMM file: <@cell> (5 fields expected)\n";
push @{$hmm{'B2_sd'}}, @cell;
grep {$_>0} @cell == 5 or confess "\nERROR: invalid line in HMM file: <@cell> (all values should be between greater than zero)\n";
@cell = split (/\s+/, $line[29]);
@cell == 1 or confess "\nERROR: invalid line in HMM file: <@cell> (1 fields expected)\n";
push @{$hmm{'B2_uf'}}, @cell;
if (@line > 30) {
@cell = split (/\s+/, $line[31]);
@cell == 6 or confess "\nERROR: invalid line in HMM file: <@cell> (6 fields exepcted)\n";
push @{$hmm{'B3_mean'}}, @cell;
@cell = split (/\s+/, $line[33]);
@cell == 6 or confess "\nERROR: invalid line in HMM file: <@cell> (6 fields expected)\n";
push @{$hmm{'B3_sd'}}, @cell;
grep {$_>0} @cell == 6 or confess "\nERROR: invalid line in HMM file: <@cell> (all values should be between greater than zero)\n";
@cell = split (/\s+/, $line[35]);
@cell == 1 or confess "\nERROR: invalid line in HMM file: <@cell> (1 fields expected)\n";
push @{$hmm{'B3_uf'}}, @cell;
}
if (@line == 38) {
$line[37] =~ m/^\d+$/ or confess "Error: invalid line in HMM file: <$line[37]> (an integer expected for DIST)\n";
$hmm{dist} = $line[37];
}
close (HMM);
return (\%hmm);
}
sub trainCHMM {
my ($ref_inputfile, $hmmfile, $pfbfile, $gcmodelfile, $directory) = @_;
my ($pfbinfo) = newreadPFB ($pfbfile);
my $hmm = readHMMFile ($hmmfile);
my $gcmodel;
defined $gcmodelfile and $gcmodel = newreadGCModel ($gcmodelfile, $pfbinfo); #read the gc model for SNPs defined in snp_chr
open (LOGR_B_PFB, ">$output.lrr_baf_pfb") or confess "\nERROR: cannot write to temporary file $output.lrr_baf_pfb: $!\n";
my ($counter, $counter_file, $siginfo, $sigdesc);
for my $inputfile (@$ref_inputfile) {
$region ||= "1-$lastchr";
($siginfo, $sigdesc) = readLRRBAF ($inputfile, $region, $pfbinfo, $gcmodel, $directory);
#if the file processing fails and no signal data is read from file, move on to the next file
%$siginfo or next;
print STDERR "NOTICE: quality summary for $inputfile: LRR_mean=", sprintf ("%.4f", $sigdesc->{lrr_mean}), " LRR_median=", sprintf ("%.4f", $sigdesc->{lrr_median}), " LRR_SD=", sprintf ("%.4f", $sigdesc->{lrr_sd}),
" BAF_mean=", sprintf ("%.4f", $sigdesc->{baf_mean}), " BAF_median=", sprintf ("%.4f", $sigdesc->{baf_median}), " BAF_SD=", sprintf ("%.4f", $sigdesc->{baf_sd}), " BAF_DRIFT=", sprintf ("%.6f", $sigdesc->{baf_drift}), " WF=", sprintf("%.4f", $sigdesc->{wf}), "\n";
$sigdesc->{lrr_sd} > $hmm->{B1_sd}[2]+0.05 || $sigdesc->{lrr_sd} < $hmm->{B1_sd}[2]-0.05 and print STDERR "NOTICE: Sample does not pass quality control for training due to its LRR_SD ($sigdesc->{lrr_sd})!\n" and next;
$sigdesc->{baf_median} >= 0.55 || $sigdesc->{baf_median} <= 0.45 and print STDERR "NOTICE: Sample does not pass quality control for training due to its BAF_MEDIAN ($sigdesc->{baf_median})!\n" and next;
$sigdesc->{baf_drift} >= $hmm->{B1_uf}/10 and print STDERR "NOTICE: Sample does not pass quality control for training due to its large BAF_DRIFT ($sigdesc->{baf_drift})!\n" and next;
if ($sigdesc->{cn_count}) {
if (not $hmm->{B3_mean}) {
print STDERR "WARNING: The signal file $inputfile contains Non-Polymorphic markers but the HMM file $hmmfile is for SNP markers only. It is recommended to use a HMM file containing parameters specifically for non-polymorphic markers.\n";
}
}
#perform signal pre-processing to adjust the median LRR and BAF values
if ($medianadjust) { #THIS IS A MANDATORY ARGUMENT NOW, SINCE IT ALWAYS IMPROVE PERFORMANCE!!! (use "--nomedianadjust" to disable this feature)
print STDERR "NOTICE: Median-adjusting LRR values for all autosome markers from $inputfile by ", sprintf ("%.4f", $sigdesc->{lrr_median}), "\n";
adjustLRR ($siginfo, $sigdesc->{lrr_median});
$sigdesc->{lrr_mean} -= $sigdesc->{lrr_median};
$sigdesc->{lrr_median} = 0;
}
if ($bafadjust) {
print STDERR "NOTICE: Median-adjusting BAF values for all autosome markers from $inputfile by ", sprintf ("%.4f", $sigdesc->{baf_median}-0.5), "\n";
adjustBAF ($siginfo, $sigdesc->{baf_median}-0.5);
$sigdesc->{baf_mean} -= $sigdesc->{baf_median}-0.5;
$sigdesc->{baf_median} = 0.5;
}
for my $curchr (keys %$siginfo) {
$curchr =~ m/^(\d+)$/ or next; #only consider autosomes
my $pos = $siginfo->{$curchr}{pos};
my $lrr = $siginfo->{$curchr}{lrr};
my $baf = $siginfo->{$curchr}{baf};
my $pfb = $siginfo->{$curchr}{pfb};
my @snpdist = @$pos;
my $logprob = 0;
for my $i (1 .. @snpdist-2) {
$snpdist[$i] = $snpdist[$i+1]-$snpdist[$i];
}
$snpdist[@snpdist-1] = 100_000_000;
for my $i (1 .. @$lrr-1) { #first element in the array is ignored
print LOGR_B_PFB $lrr->[$i], "\t", $baf->[$i], "\t", $pfb->[$i], "\t", $snpdist[$i], "\n";
$counter++;
}
}
$counter_file++;
}
$counter or confess "\nERROR: none of the files (@$ref_inputfile) pass quality control threshold for training HMM model\n";
print STDERR "NOTICE: Total of $counter markers in $counter_file files will be used in training HMM models\n";
#the following paragraph sets up pseudocounts in the array to handle cases where the state is extremely rare, and it is unlikely that the training set contains such state
my (@alllogr, @allbaf, @allpfb, @allsnpdist);
push @alllogr, ($hmm->{'B1_mean'}[0]) x 100; push @allbaf, ('0.5') x 100; push @allsnpdist, ('5000')x99, 10_000_000; #state1
push @alllogr, ('0') x 1000; for (1..250) {push @allbaf, 0.001, 0.5, 0.5, 0.999}
push @allpfb, ('0.5') x 1100; push @allsnpdist, ('5000')x999, 10_000_000;
push @alllogr, ($hmm->{'B1_mean'}[1]) x 100; for (1..50) {push @allbaf, 0.001, 0.999} push @allsnpdist, ('5000')x99, 10_000_000; #state2
push @alllogr, ('0') x 1000; for (1..250) {push @allbaf, 0.001, 0.5, 0.5, 0.999}
push @allpfb, ('0.5') x 1100; push @allsnpdist, ('5000')x999, 10_000_000;
push @alllogr, ('0') x 100; for (1..50) {push @allbaf, 0, 1} push @allsnpdist, ('5000')x99, 10_000_000; #state4
push @alllogr, ('0') x 1000; for (1..250) {push @allbaf, 0.001, 0.5, 0.5, 0.999}
push @allpfb, ('0.5') x 1100; push @allsnpdist, ('5000')x999, 10_000_000;
push @alllogr, ($hmm->{'B1_mean'}[4]) x 100; for (1..25) {push @allbaf, 0.001, 0.33, 0.66, 0.999} push @allsnpdist, ('5000')x99, 10_000_000; #state5
push @alllogr, ('0') x 1000; for (1..250) {push @allbaf, 0.001, 0.5, 0.5, 0.999}
push @allpfb, ('0.5') x 1100; push @allsnpdist, ('5000')x999, 10_000_000;
push @alllogr, ($hmm->{'B1_mean'}[5]) x 100; for (1..25) {push @allbaf, 0.001, 0.75, 0.25, 0.5} push @allsnpdist, ('5000')x99, 10_000_000; #state6
push @alllogr, ('0') x 1000; for (1..250) {push @allbaf, 0.001, 0.5, 0.5, 0.999}
push @allpfb, ('0.5') x 1100; push @allsnpdist, ('5000')x999, 10_000_000;
@alllogr==@allsnpdist and @alllogr==@allbaf and @alllogr==@allbaf or confess "FATAL ERROR: discordance in array elements: ${\(scalar @alllogr)} vs ${\(scalar @allsnpdist)} vs ${\(scalar @allbaf)}\n";
for my $i (0 .. @alllogr-1) {
print LOGR_B_PFB $alllogr[$i], "\t", $allbaf[$i], "\t", $allpfb[$i], "\t", $allsnpdist[$i], "\n";
$counter++;
}
close (LOGR_B_PFB);
my $system_command = "$0 --ctrain --record_count $counter --hmmfile $hmmfile $output.lrr_baf_pfb --output $output";
print STDERR "NOTICE: Handing over the command '$system_command' to your operating system to continue Baum-Welch training\n";
exec ($system_command) or confess "FATAL ERROR: Unable to execute system command <$system_command> via your operating system\n";
}
sub testSEQ {
my ($ref_inputfile, $hmmfile) = @_;
for my $inputfile (@$ref_inputfile) {
my @mlstate;
my $fh_temp = khmm::fopen ($inputfile, "r");
my $record_count = 0;
my ($curchr, $name);
push @$name, 'padding_element';
open (SIG, $inputfile) or confess "Error: cannot read from signal file $inputfile: $!\n";
$_ = <SIG>;
while (<SIG>) {
$record_count++;
m/^(\S+)/ or confess "Error: invalid record found: <$_>\n";
push @$name, $1;
push @mlstate, 0;
}
close (SIG);
$name->[1] =~ m/^(\w+)/ or confess "Error: invalid marker name";
$curchr = $1;
$record_count or confess "\nERROR: the signal file $inputfile does not contain any signal values for CNV calling\n";
print STDERR "NOTICE: Calling CNVs on $record_count records\n";
my $hmm_model = khmm::ReadCHMM ($hmmfile);
khmm::callCNVFromFile_SEQ ($hmm_model, $record_count, $fh_temp, \@mlstate, $gamma_k||0, $gamma_theta||0);
print STDERR "mlstate(1000-1500)=@mlstate[1000..1500]\n";
my ($normal_state, $found_signal, $cnv, $startpos, $endpos, $stretch_start_i) = (3);
for my $i (1 .. @mlstate-1) {
if ($mlstate[$i] != $normal_state) {
if ($found_signal and $found_signal ne $mlstate[$i]) {
$name->[$stretch_start_i] =~ m/^\w+:(\d+)/ or confess "Error: invalid name";
$startpos = $1;
$name->[$i-1] =~ m/^\w+:\d+\-(\d+)/ or confess "Error: invalid name"; #"
$endpos = $1;
push @{$cnv->{$found_signal}}, [$curchr, $startpos, $endpos, $i-$stretch_start_i, $name->[$stretch_start_i], $name->[$i-1]];
$stretch_start_i = $i;
$found_signal = $mlstate[$i];
} elsif ($found_signal) {
1;
} else {
$found_signal = $mlstate[$i];
$stretch_start_i = $i;
}
} else {
if ($found_signal) {
$name->[$stretch_start_i] =~ m/^\w+:(\d+)/ or confess "Error: invalid name";
$startpos = $1;
$name->[$i-1] =~ m/^\w+:\d+\-(\d+)/ or confess "Error: invalid name"; #"
$endpos = $1;
push @{$cnv->{$found_signal}}, [$curchr, $startpos, $endpos, $i-$stretch_start_i, $name->[$stretch_start_i], $name->[$i-1]];
$found_signal = 0;
}
}
}
if ($found_signal) {
$name->[$stretch_start_i] =~ m/^\w+:(\d+)/ or confess "Error: invalid name";
$startpos = $1;
$name->[@$name-1] =~ m/^\w+:\d+\-(\d+)/ or confess "Error: invalid name"; #"
$endpos = $1;
push @{$cnv->{$found_signal}}, [$curchr, $startpos, $endpos, @$name-1-$stretch_start_i, $name->[$stretch_start_i], $name->[@$name-1]];
}
#print all CNV calls, sorted by copy numbers first, then by chromosomes
if ($tabout) {
printTabbedCNV ($cnv, $inputfile); #use tab-delimited output
} else {
printFormattedCNV ($cnv, $inputfile);
}
}
}
sub ctrainCHMM {
my ($sigfile, $hmmfile, $record_count) = @_;
my $fh_stdout = khmm::fh_stdout ();
my $hmm_model = khmm::ReadCHMM ($hmmfile);
print "<--------------------ORIGINAL HMM-------------------------\n";
khmm::PrintCHMM ($fh_stdout, $hmm_model);
print "--------------------------------------------------------->\n";
if (not $record_count) { #when record_count is not given, open the file and count the number of lines
$record_count = 0;
open (SIG, $sigfile) or confess "\nERROR: cannot read from signal file $sigfile: $!\n";
while (<SIG>) {
$record_count++;
}
close (SIG);
$record_count or confess "\nERROR: the signal file $sigfile does not contain any signal values for Baum-Welch training\n";
}
my ($logprobinit, $logprobfinal, $num_iteration) = (0, 0, 0, 0);
my $fh1 = khmm::fopen ($sigfile, "r");
khmm::estHMMFromFile_CHMM ($hmm_model, $record_count, $fh1, \$num_iteration, \$logprobinit, \$logprobfinal);
print STDERR "NOTICE: Baum-Welch estimation done with initp=$logprobinit endp=$logprobfinal delta=${\($logprobfinal-$logprobinit)} num_iteration=$num_iteration\n";
print STDERR "NOTICE: The final HMM model is below (the model is also written to $output.hmm file):\n";
khmm::PrintCHMM ($fh_stdout, $hmm_model);
my $fh2 = khmm::fopen ("$output.hmm", 'w');
khmm::PrintCHMM ($fh2, $hmm_model);
khmm::FreeCHMM ($hmm_model);
khmm::fclose ($fh1);
khmm::fclose ($fh2);
}
sub calculateSampleSummary {
my ($ref_inputfile, $pfbfile, $gcmodelfile, $directory) = @_;
my ($pfbinfo) = newreadPFB ($pfbfile);
my $gcmodel;
defined $gcmodelfile and $gcmodel = newreadGCModel ($gcmodelfile, $pfbinfo); #read the gc model for SNPs defined in snp_chr
for my $inputfile (@$ref_inputfile) {
my ($siginfo, $sigdesc) = readLRRBAF ($inputfile, "1-$lastchr", $pfbinfo, $gcmodel, $directory);
#if the file processing fails and no signal data is read from file, move on to the next file
%$siginfo or next;
print "$inputfile";
print "\tLRR_MEAN=", sprintf("%.4f", $sigdesc->{lrr_mean});
print "\tLRR_MEDIAN=", sprintf("%.4f", $sigdesc->{lrr_median});
print "\tLRR_SD=", sprintf ("%.4f", $sigdesc->{lrr_sd});
print "\tLRR_XMEAN=", sprintf("%.4f", $sigdesc->{lrr_xmean});
print "\tLRR_XMEDIAN=", sprintf("%.4f", $sigdesc->{lrr_xmedian});
print "\tLRR_XSD=", sprintf ("%.4f", $sigdesc->{lrr_xsd});
print "\tBAF_MEAN=", sprintf ("%.4f", $sigdesc->{baf_mean});
print "\tBAF_MEDIAN=", sprintf ("%.4f", $sigdesc->{baf_median});
print "\tBAF_SD=", sprintf ("%.4f", $sigdesc->{baf_sd});
print "\tBAF_DRIFT=", sprintf ("%.6f", $sigdesc->{baf_drift}); #this number is usually small
print "\tBAF_XHET=", sprintf ("%.4f", $sigdesc->{baf_xhet});
print "\tWF=", sprintf ("%.4f", $sigdesc->{wf});
print "\n";
}
}
#the new testCHMM subroutine treat each chromosome separately, to reduce the burden of system memory, when analyzing a large number of markers
sub newtestCHMM {
my ($ref_inputfile, $hmmfile, $pfbfile, $sexfile, $gcmodelfile, $directory) = @_;
my $pfbinfo = newreadPFB ($pfbfile);
my $hmm = readHMMFile ($hmmfile);
my ($file_sex, $gcmodel) = ({});
defined $sexfile and $file_sex = readSexFile ($sexfile);
defined $gcmodelfile and $gcmodel = newreadGCModel ($gcmodelfile, $pfbinfo); #read the GC model for SNPs defined in snp_chr
for my $inputfile (@$ref_inputfile) {
my ($siginfo, $sigdesc, $sample_sex);
($siginfo, $sigdesc) = readLRRBAF ($inputfile, $region, $pfbinfo, $gcmodel, $directory);
#if the file processing fails and no signal data is read from file, move on to the next file
%$siginfo or print STDERR "WARNING: Skipping $inputfile since no signal values can be retrieved from the file\n" and next;
$sample_sex = QCSignal ($inputfile, $siginfo, $sigdesc, $hmm, $file_sex->{$inputfile});
#read HMM model file
my $hmm_model = khmm::ReadCHMM ($hmmfile);
#Now a mandatory step to handle low-quality samples and reduce false-positve calls, through matching the SD measure for sample and model
if ($sdadjust) {
if ($chrx) {
khmm::adjustBSD ($hmm_model, $sigdesc->{lrr_xsd});
} elsif ($chry) {
khmm::adjustBSD ($hmm_model, $sigdesc->{lrr_ysd});
} else {
khmm::adjustBSD ($hmm_model, $sigdesc->{lrr_sd});
}
}
#do the CNV calling for each chromosome separately, save the CNV calls in $cnvcall hash
my $cnvcall = {};
for my $curchr (keys %$siginfo) {
my $name = $siginfo->{$curchr}{name};
my $pos = $siginfo->{$curchr}{pos};
my $lrr = $siginfo->{$curchr}{lrr};
my $baf = $siginfo->{$curchr}{baf};
@$pos >= 10 or print STDERR "WARNING: Skipping chromosome $curchr due to insufficient data points (<10 markers)!\n" and next;
my $pfb = [@{$siginfo->{$curchr}{pfb}}]; #we will use PFB again later (for assigning confidence scores)
my $snpdist = [@$pos];
my $logprob = 0;
my $curcnvcall = {};
for my $i (1 .. @$snpdist-2) {
$snpdist->[$i] = ($snpdist->[$i+1]-$snpdist->[$i]) || 1; #sometimes two markers have the same chromosome location (in Affymetrix array annotation)
}
#generate CNV calls
my $probe_count = scalar (@$lrr)-1;
khmm::testVit_CHMM ($hmm_model, $probe_count, $lrr, $baf, $pfb, $snpdist, \$logprob);
analyzeStateSequence ($curcnvcall, $curchr, $pfb, $name, $pos, $sample_sex);
#assign confidence scores (if the --conf argument is given)
if ($confidence) {
$pfb = $siginfo->{$curchr}{pfb}; #reassign value to PFB as it has been changed
assignConfidence ($curcnvcall, $hmm_model, $name, $lrr, $baf, $pfb, $snpdist);
}
#add the new CNV calls for one chromosome to the total CNV calls
for my $key (keys %$curcnvcall) {
push @{$cnvcall->{$key}}, @{$curcnvcall->{$key}};
}
}
#print all CNV calls, sorted by copy numbers first, then by chromosomes
if ($tabout) {
printTabbedCNV ($cnvcall, $inputfile); #use tab-delimited output
} else {
printFormattedCNV ($cnvcall, $inputfile);
}
khmm::FreeCHMM ($hmm_model);
}
}
#the new tumorCHMM is copied from newtestCHMM, with tiny changes.
sub newtumorCHMM {
my ($ref_inputfile, $hmmfile, $pfbfile, $sexfile, $gcmodelfile, $directory) = @_;
my $pfbinfo = newreadPFB ($pfbfile);
my $hmm = readHMMFile ($hmmfile);
my ($file_sex, $gcmodel) = ({});
defined $sexfile and $file_sex = readSexFile ($sexfile);
defined $gcmodelfile and $gcmodel = newreadGCModel ($gcmodelfile, $pfbinfo); #read the GC model for SNPs defined in snp_chr
for my $inputfile (@$ref_inputfile) {
my ($siginfo, $sigdesc, $sample_sex);
($siginfo, $sigdesc) = readLRRBAF ($inputfile, $region, $pfbinfo, $gcmodel, $directory);
#if the file processing fails and no signal data is read from file, move on to the next file
%$siginfo or print STDERR "WARNING: Skipping $inputfile since no signal values can be retrieved from the file\n" and next;
$sample_sex = QCSignal ($inputfile, $siginfo, $sigdesc, $hmm, $file_sex->{$inputfile});
#read HMM model file
my $hmm_model = khmm::ReadCHMM ($hmmfile);
#Now a mandatory step to handle low-quality samples and reduce false-positve calls, through matching the SD measure for sample and model
if ($sdadjust) {
if ($chrx) {
khmm::adjustBSD ($hmm_model, $sigdesc->{lrr_xsd});
} elsif ($chry) {
khmm::adjustBSD ($hmm_model, $sigdesc->{lrr_ysd});
} else {
khmm::adjustBSD ($hmm_model, $sigdesc->{lrr_sd});
}
}
#do the CNV calling for each chromosome separately, save the CNV calls in $cnvcall hash
my $cnvcall = {};
for my $curchr (keys %$siginfo) {
my $name = $siginfo->{$curchr}{name};
my $pos = $siginfo->{$curchr}{pos};
my $lrr = $siginfo->{$curchr}{lrr};
my $baf = $siginfo->{$curchr}{baf};
@$pos >= 10 or print STDERR "WARNING: Skipping chromosome $curchr due to insufficient data points (<10 markers)!\n" and next;
my $pfb = [@{$siginfo->{$curchr}{pfb}}]; #we will use PFB again later (for assigning confidence scores)
my $snpdist = [@$pos];
my $logprob = 0;
my $curcnvcall = {};
for my $i (1 .. @$snpdist-2) {
$snpdist->[$i] = ($snpdist->[$i+1]-$snpdist->[$i]) || 1; #sometimes two markers have the same chromosome location (in Affymetrix array annotation)
}
#generate CNV calls
my $probe_count = scalar (@$lrr)-1;
#------------------------------------------------------------------------------------------
#khmm::testVit_CHMM ($hmm_model, $probe_count, $lrr, $baf, $pfb, $snpdist, \$logprob);
khmm::tumorVit_CHMM ($hmm_model, $probe_count, $lrr, $baf, $pfb, $snpdist, \$logprob, $stroma);
#------------------------------------------------------------------------------------------
analyzeStateSequence ($curcnvcall, $curchr, $pfb, $name, $pos, $sample_sex);
#assign confidence scores (if the --conf argument is given)
if ($confidence) {
$pfb = $siginfo->{$curchr}{pfb}; #reassign value to PFB as it has been changed
assignConfidence ($curcnvcall, $hmm_model, $name, $lrr, $baf, $pfb, $snpdist);
}