-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtriPOD.pl
3798 lines (3576 loc) · 155 KB
/
triPOD.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/perl
###############################################################################
#
# The triPOD software detects chromosomal abnormalities using
# the Parent-of-Origin-based Detection (POD) method.
# Author and maintainer: Joseph D. Baugher.
# Email:jbaughe2(at)jhmi.edu.
#
# This file is part of the triPOD software.
# triPOD is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# triPOD 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 General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with triPOD. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
use strict;
use warnings;
use Algorithm::Cluster 'kcluster';
use Cwd 'getcwd';
use File::Path qw(make_path remove_tree);
use File::Temp 'tempfile';
use Getopt::Long;
use POSIX qw(ceil floor);
use threads;
use Time::HiRes 'usleep';
use Tree::Interval;
use FindBin;
use lib $FindBin::Bin;
use Version_info;
my $version_info = Version_info->new();
print "\n", $version_info->get_name, " ", $version_info->get_version, "\n\n";
my $CMD_LINE = join(" ", $0, @ARGV);
# Detect the total number of cores
my $MAX_CORES = 1;
my $os = $^O;
if ($os =~ /mswin/i){warn("triPOD has not been tested on Windows!")}
elsif($os =~ /darwin/i){$MAX_CORES= `sysctl -n hw.ncpu`}
elsif($os =~ /linux/i){$MAX_CORES= `cat /proc/cpuinfo | grep processor | wc -l`}
my $THE_TIME = cpu_time();
# Get process ID, current working directory, and current time
my $CWD = getcwd();
# Default Parameters
my $ALPHA = 0.1;
my $BATCH;
my $BUILD_FILE = "./genome_build/hg18_centromeres.txt";
my $CITE;
my $CORES = $MAX_CORES - 1;
my $GENDER = 0;
my $GRAPHICS = "none";
my $HD = "T";
my $HELP;
# Number of stdevs from the heterozygous BAF mean - used as boundaries
# for detection of informative SNPs. (The intent is to ignore at least 50%
# of the members of the "normal" heterozygous SNP distribution.)
my $HET_SD = 1.414213562373095; # sqrt(2)
# Number of stdevs from the homozygous BAF means - used as boundaries
# for mBAF conversions. (The intent is to ignore nearly all
# of the members of the "normal" homozygous SNP distribution.)
my $HOM_SD = 4;
my $MI1 = "T";
my $NC_THRESH = 0.03;
my $OUTPUT_DIR;
my $POD = "T";
my $PODcr = "T";
my $SIZE_SMALL_WINDOW = 100;
my $STATS;
my $verbose = "T";
# Get optional input parameters (e.g. --cores=2 --alpha=0.05)
GetOptions( 'alpha=f' => \$ALPHA, 'homSD=f' => \$HOM_SD,
'batch=s' => \$BATCH, 'mi1!' => \$MI1,
'build=s' => \$BUILD_FILE, 'nc=f' => \$NC_THRESH,
'cite!' => \$CITE, 'out=s' => \$OUTPUT_DIR,
'cores=i' => \$CORES, 'pod!' => \$POD,
'gender=s' => \$GENDER, 'podcr!' => \$PODcr,
'graph=s' => \$GRAPHICS, 'stats!' => \$STATS,
'hd!' => \$HD, 'verbose!' => \$verbose,
'help!' => \$HELP, 'win=i' => \$SIZE_SMALL_WINDOW,
'hetSD=f' => \$HET_SD
);
help() if $HELP;
if ($CITE) {print $version_info->get_reference, "\n\n"; exit 0}
my $SIZE_LARGE_WINDOW = $SIZE_SMALL_WINDOW * 5;
my $CORES_PER_SAMPLE = $CORES;
my $AMP = 0.1;
my ($HD_LOW, $HD_HI) = (-2, -1.5);
my ($DEL_UPPER, $DEL_LOWER) = (-0.1, -2);
# Array indices and various constants
use constant {
CHR => 1, POS => 2, START => 1, STOP => 2,
LRR => 1, BAF => 2, MALE => 1, FEMALE => 2,
# Detection method
POD => 1, HD => 2, MI1 => 3, PODcr => 4,
# ID and contribution
FATHER => 1, MOTHER => 2, CHILD => 3, NONE => 4,
BOTH => 5, UNKNOWN => 6, UNKNOWN_MI1 => 7, OUTLIER => 8,
CHR_X => 23, NA => -1000,
PI => 4 * atan2(1, 1)
};
# Determine if gender was assigned
if ($GENDER =~ /^m/i) {$GENDER = MALE}
elsif ($GENDER =~ /^f/i) {$GENDER = FEMALE}
elsif ($GENDER =~ /^n/i) {$GENDER = 0}
elsif ($GENDER) {
$GENDER = 0;
print "The gender specification cannot be recognized. Please use M or F.",
"\nProceeding without analysis of Chromosome X.\n\n";
}
if ($GRAPHICS ne "none" && $GRAPHICS ne "NA") {
unless ($GRAPHICS eq "png" || $GRAPHICS eq "pdf" || $GRAPHICS eq "both") {
if ($GRAPHICS eq "PNG") {$GRAPHICS = "png"}
elsif ($GRAPHICS eq "PDF") {$GRAPHICS = "pdf"}
elsif ($GRAPHICS eq "BOTH") {$GRAPHICS = "both"}
else {
print STDERR "WARNING: The graphics input was not recognized\n. ",
"Acceptable graphics input options are --graph=none, ",
"--graph=png, --graph=pdf, or --graph=both.\n",
"The analysis will proceed without graphical output.\n";
$GRAPHICS = "";
}
}
}
else {$GRAPHICS = ""}
# Check if batch or single mode is correctly set by user
my $check_batch = ($BATCH) ? $BATCH : $ARGV[-1];
if(!open(INPUT_FILE, "<", $check_batch)) {
print STDERR "ERROR: Could not open input file: $check_batch!\n";
die;
}
my $line = <INPUT_FILE>;
chomp($line);
my @line = split("\t", $line);
close INPUT_FILE;
if (scalar(@line) == 1 && defined($line[0]) && !$BATCH) {
$BATCH = $check_batch;
print STDERR "WARNING: The input appears to be a list of files. ",
"Switching to BATCH mode.\n";
}
elsif (scalar(@line) == 12 && $BATCH) {
push(@ARGV, $check_batch);
$BATCH = 0;
print STDERR "WARNING: The input does not appear to be a list of files. ",
"Switching to single sample mode.\n";
}
# Open batch file if supplied
my (@files, @batch, @batches);
if ($BATCH) {
$verbose = "";
open(BATCH_FILE, "<", $BATCH) || die("Could not open batch file!\n");
while (<BATCH_FILE>) {
my $file = $_;
chomp($file);
push(@files, $file);
}
close BATCH_FILE;
$CORES_PER_SAMPLE = 1;
}
else {
if ($ARGV[-1]) {
$batches[0] = [$ARGV[-1]];
push(@files, $ARGV[-1]);
}
else {die("Please include an input file.\n")}
}
# Open genome build file
my @CENTRO_REFS;
open(BUILD_FILE, "<", $BUILD_FILE)
|| die("\nCould not open genome build file!\n",
"Please provide a correct file path.\n",
"(e.g. --build=./hg18_centromeres.txt)\n\n");
<BUILD_FILE> for 1..2;
while (<BUILD_FILE>) {
my $line = $_;
chomp($line);
my @line_array = split(/\t/, $line);
$line_array[1] = (split(/chr/, $line_array[1]))[1];
# Check Chromosome column for anything other than acceptable
# chromosomes
if ($line_array[1] !~ /^[1-9]$|^[1][0-9]|^[2][0-2]$|x|y|xy|m|mt/i) {
print "\nUnrecognized character in Chromosome column of genome ",
"build file!\n";
print_proper_format();
die;
}
# Check Position columns for non-numeric characters and negative
# numbers
elsif ($line_array[2] !~ /^-?\d/ || $line_array[2] < 0) {
print "\nUnrecognized character in Position Start column of genome ",
"build file!\n";
print_proper_format();
die();
}
elsif ($line_array[3] !~ /^-?\d/ || $line_array[3] < 0) {
print "\nUnrecognized character in Position End column of genome ",
"build file!\n";
print_proper_format();
die();
}
if ($line_array[CHR] !~ /^\d/) {
($line_array[CHR] eq "X" && $GENDER) ? $line_array[CHR] = CHR_X : next;
}
$CENTRO_REFS[$line_array[1]] = [@line_array[1..3]];
}
my $input_name;
if ($BATCH) {$input_name = (split(/[\/]/,(split(/.txt/, $BATCH))[0]))[-1]}
else {$input_name = (split(/[\/]/,(split(/.txt/, $ARGV[-1]))[0]))[-1]}
if (!$OUTPUT_DIR) {$OUTPUT_DIR = "$CWD/triPOD_Results/$input_name"}
# If user input contains a trailing backslash, remove it
else {$OUTPUT_DIR =~ s|/\z||}
make_path("$OUTPUT_DIR/log_files");
-e "$OUTPUT_DIR/log_files" || die "Could not create output directory: ",
"$OUTPUT_DIR\n";
print "Output directory = $OUTPUT_DIR/\n";
print "Number of Samples = ", scalar(@files), "\n";
my $OUTPUT_FILE;
if ($BATCH){$OUTPUT_FILE = "$OUTPUT_DIR/$input_name\_triPOD_Batch_Results.txt"}
else {$OUTPUT_FILE = "$OUTPUT_DIR/$input_name\_triPOD_Results.txt"}
open(OUTPUT_FILE, '>', $OUTPUT_FILE) || die
"Could not create output file - $OUTPUT_FILE!\n";
print OUTPUT_FILE join("\n", $THE_TIME, $CMD_LINE), "\n";
print OUTPUT_FILE $version_info->get_name, "\t", $version_info->get_version,
"\tAuthor: ", $version_info->get_author, "\t",
$version_info->get_author_email, "\n\n";
if ($BATCH) {
print OUTPUT_FILE "Detected Chromosomal Abnormalities", "\n",
join("\t", qw(Sample Chr Start Stop Type Parent_of_Origin
Inheritance Size(SNPs) Informative_SNPs Size(bp)
Detection Median_mBAF Median_LRR Father-Median_mBAF
Father-Median_LRR Mother-Median_mBAF Mother-Median_LRR)
),"\n";
}
my $BED_FILE = "$OUTPUT_DIR/$input_name\_triPOD_Results.bed";
open(BED_FILE,'>',$BED_FILE) || die "Could not create bed file - $BED_FILE!\n";
print BED_FILE "track name=\"triPOD Results\" type=bedDetail ",
"description=\"triPOD : Chromosomal Abnormality Detection\" visibility=2 ",
"itemRgb=\"On\"\n";
# Redirect STDERR to a log file
my $PERL_LOG = "$OUTPUT_DIR/log_files/$input_name\_triPOD_log.txt";
open(STDERR, '>', $PERL_LOG) || die
"Could not create log file - $PERL_LOG!\n";
# Create stats file if requested
my $STATS_FILE;
if ($STATS) {
$STATS_FILE = "$OUTPUT_DIR/$input_name\_triPOD_stats.txt";
open(STATS_FILE, '>', $STATS_FILE) || die
"Could not create stats file - $STATS_FILE!\n";
print STATS_FILE "File\tChild\tFather\tMother\tChild_NC_rate\t",
"Father_NC_rate\tMother_NC_rate\tChild_HD_rate\tChild_Min_HD\t",
"Father_HD_rate\tFather_Min_HD\tMother_HD_rate\tMother_Min_HD\t",
"MI1_rate\tMin_MI1\tMI1_Upper_Thresh\tMI1_Lower_Thresh\tMin_POD\t",
"Corrected_alpha\talpha\tError_rate\tAcceptable_Errors\tAA_Bound\t",
"BB_bound\tAB_upper_bound\tAB_lower_bound\tDetected_Regions\t",
"POD_regions\tPODcr_regions\tMI1_regions\tHD_regions\n";
}
# Declare global variables
my ($AA_BOUND, $AB_LOWER_BOUND, $AB_UPPER_BOUND, $ACCEPTABLE_ERRORS,
$BB_BOUND, $BOUNDARY_EXTENSION, $CH_LRR_MED, $CH_mBAF_MED, $CH_NAME,
$CURR_FILE, $ERROR_RATE, $FILENAME, $HET_MI1_CT, $HET_MI1_RATE, $hUPD_RATE,
$INPUT_FILE,$LARGE_POD_ALPHA,$LARGE_WIN_ACCEPTABLE_ERRORS,$LOCAL_CH_BAF_MEAN,
$LOCAL_CH_mBAF_MED, $LOCAL_CH_LRR_MED, $LOCAL_P1_mBAF_MED,$LOCAL_P1_LRR_MED,
$LOCAL_P2_mBAF_MED, $LOCAL_P2_LRR_MED, $MI1_LOWER_THRESH, $MI1_UPPER_THRESH,
$MIN_BAF_OUT, $MIN_CH_HD, $MIN_hUPD, $MIN_MI1, $MIN_LARGE_POD, $MIN_P1_HD,
$MIN_P2_HD, $MIN_POD, $P1_AA_BOUND, $P1_BB_BOUND, $P2_AA_BOUND,$P2_BB_BOUND,
$P1_LRR_MED, $P1_mBAF_MED, $P1_NAME, $P2_LRR_MED, $P2_mBAF_MED, $P2_NAME,
$PERL_TO_R_FILE, $PERL_TO_R_FILENAME, $POD_ALPHA, $PODCR_LOWER_THRESH,
$PODCR_UPPER_THRESH, $REFINING);
my (@BAF_OUTLIERS, @CURR_CHR_REFS, @LRR_REFS, @P1_INF_SNPS, @P2_INF_SNPS);
my (%BAF_BY_POS, %BAF_OUTLIERS_BY_POS, %CH_HD_BY_POS, %LRR_BY_POS, %MI1_BY_POS,
%P1_HD_BY_POS, %P1_INF_SNP_BY_POS, %P2_HD_BY_POS, %P2_INF_SNP_BY_POS,
%SNP_BY_NUM, %SNP_BY_POS);
# Count of completed samples - [0] = with abn, [1] = no abn
my @completed = (0,0);
my (@batch_threads, @output, @sorted_output, @stats, @trio_def);
my $next_file = 0;
my $main_results;
my @bed_array;
if ($BATCH) {
for (my $i = 1; $i <= $CORES; $i++) {
if ($next_file <= $#files) {
$CURR_FILE = $files[$i - 1];
my $batch_thread = threads->new(\&main_program);
push(@batch_threads, $batch_thread);
$next_file++;
}
}
}
else {
$CURR_FILE = $files[0];
$main_results = main_program();
if ($main_results) {
if ($main_results->[0]) {
push(@output, @{$main_results->[0]});
@sorted_output = sort {
$$a[1] <=> $$b[1] || $$a[2] <=> $$b[2]} @output;
if ($STATS) {
push(@stats, @{$main_results->[1]});
map {print STATS_FILE join("\t", @{$_}), "\n"} @stats;
}
if ($main_results->[3]) {$completed[0]++}
}
elsif($main_results->[3]) {$completed[1]++}
}
print OUTPUT_FILE join("\n", @trio_def), "\n\n";
print OUTPUT_FILE "Detected Chromosomal Abnormalities", "\n",
join("\t", qw(Sample Chr Start Stop Type Parent_of_Origin
Inheritance Size(SNPs) Informative_SNPs Size(bp)
Detection Median_mBAF Median_LRR Father-Median_mBAF
Father-Median_LRR Mother-Median_mBAF Mother-Median_LRR)
),"\n";
map {print OUTPUT_FILE join("\t", @{$_}), "\n"} @sorted_output;
to_bed(\@sorted_output);
}
if ($BATCH) {
# Check if threads are finished
while (threads->list(threads::running)) {
sleep(1);
for (0..$#batch_threads) {
if ($batch_threads[$_]->is_joinable()) {
$main_results = $batch_threads[$_]->join();
if ($main_results) {
if ($main_results->[0]) {
push(@output, @{$main_results->[0]});
@sorted_output = sort {
$$a[1] <=> $$b[1] || $$a[2] <=> $$b[2]} @output;
map {print OUTPUT_FILE join("\t", @{$_}), "\n"}
@sorted_output;
to_bed(\@sorted_output);
if ($STATS) {
push(@stats, @{$main_results->[1]});
map{print STATS_FILE join("\t", @{$_}),"\n"}@stats;
}
if ($main_results->[3]) {$completed[0]++}
(@output, @sorted_output, @stats) = (()) x 3;
}
elsif($main_results->[3]) {$completed[1]++}
}
if ($next_file <= $#files) {
$CURR_FILE = $files[$next_file];
my $batch_thread = threads->new(\&main_program);
push(@batch_threads, $batch_thread);
$next_file++;
}
}
}
}
}
for (0..$#batch_threads) {
if ($batch_threads[$_]->is_joinable()) {
$main_results = $batch_threads[$_]->join();
if ($main_results) {
if ($main_results->[0]) {
push(@output, @{$main_results->[0]});
@sorted_output = sort {
$$a[1] <=> $$b[1] || $$a[2] <=> $$b[2]} @output;
map {print OUTPUT_FILE join("\t",@{$_}),"\n"}@sorted_output;
to_bed(\@sorted_output);
if ($STATS) {
push(@stats, @{$main_results->[1]});
map {print STATS_FILE join("\t", @{$_}), "\n"} @stats;
}
if ($main_results->[3]) {$completed[0]++}
(@output, @sorted_output, @stats) = (()) x 3;
}
elsif($main_results->[3]) {$completed[1]++}
}
(@output, @sorted_output, @stats) = (()) x 3;
}
}
if ($GENDER == 1) {$GENDER = "male"}
elsif ($GENDER == 2) {$GENDER = "female"}
$GENDER ||= "NA";
my @tot_param;
push(@tot_param, "alpha=$ALPHA");
push(@tot_param, "batch=$BATCH") if ($BATCH);
push(@tot_param, "build=$BUILD_FILE", "cores=$CORES", "gender=$GENDER",
($GRAPHICS) ? "graph=$GRAPHICS" : "nograph", ($HD) ? "hd" : "nohd",
"hetSD=$HET_SD", "homSD=$HOM_SD", ($MI1) ? "mi1" : "nomi1",
"out=$OUTPUT_DIR/", ($POD) ? "pod" : "nopod", "nc=$NC_THRESH",
"win=$SIZE_SMALL_WINDOW");
print OUTPUT_FILE "\n\nPARAMETERS:\n--", join(" --", @tot_param);
close OUTPUT_FILE;
close BED_FILE;
close STATS_FILE if $STATS;
my $temp = join("_", "$OUTPUT_DIR\/log_files\/temp.txt");
my $cleanup_script
= "grep -v 'Wanted\\|Parameter' $PERL_LOG > $temp\nmv $temp $PERL_LOG";
system($cleanup_script);
my $successful = $completed[0] + $completed[1];
print "Number of successful samples = $successful \n";
print "Number of failed samples = ", scalar(@files) - $successful, "\n"
if (scalar(@files) - $successful);
print "Samples with no detectable abnormalities = $completed[1]\n"
if ($completed[1]);
print STDERR "Number of successful samples = $successful\n";
print STDERR "Number of failed samples = ",
scalar(@files) - $successful, "\n";
print STDERR "Samples with no detectable abnormalities = $completed[1]\n";
if (!$successful && !$completed[1]) {
print STDERR "ERROR: This analysis was unsuccessful!\n";
die;
}
close STDERR;
exit 0;
#THE END
################################# Sub Functions ################################
############################### Main Sub Function ##############################
sub main_program {
my (@output, @stats, @trio_def);
my $completed = 0;
clear_global_variables();
# Input file, tab delim, sorted by chromosome and position,
# format = SNP Name, Chromosome, Position, Father, Father BAF, Father LRR,
# Mother, Mother BAF, Mother LRR, Child, Child BAF, Child LRR
$INPUT_FILE = $CURR_FILE;
if(!open(INPUT_FILE, "<", $INPUT_FILE)) {
print "Could not open input file: $INPUT_FILE!\n";
print STDERR "ERROR: Could not open input file: $INPUT_FILE!\n";
return();
}
# Get filename
$FILENAME = (split(/[\/]/,(split(/.txt/, $CURR_FILE))[0]))[-1];
my @input_check_array;
while (<INPUT_FILE>) {
my $line = $_;
chomp($line);
my @line_array = split(/\t/, $line);
if (scalar(@line_array) > 100) {
print "\nERROR: This Perl script is likely unable to detect the newline\n",
"characters present in the input file. The program currently\n",
"expects newlines in the Unix format: LF (Line feed,",
" \'\\n\', 0x0A).\n\n";
print STDERR "ERROR: This Perl script is likely unable to detect the ",
"newline characters present in the input file. The program currently",
"expects newlines in the Unix ormat: LF (Line feed,",
" \'\\n\', 0x0A).\n";
exit 3;
}
if ($. > 1) {push(@input_check_array, \@line_array)}
if ($. == 1000) {
my $passed = check_input_format(\@input_check_array);
if(!$passed) {
if($BATCH) {return()}
else {exit 3}
}
}
}
close(INPUT_FILE);
if(!open(INPUT_FILE, "<", $INPUT_FILE)) {
print "Could not open input file: $INPUT_FILE!\n";
print STDERR "ERROR: Could not open input file: $INPUT_FILE!\n";
return();
}
# Get sample names
my $HEADERS = <INPUT_FILE>;
$P1_NAME = (split(/[.]/, (split(/\t/, $HEADERS))[3]))[0];
$P2_NAME = (split(/[.]/, (split(/\t/, $HEADERS))[6]))[0];
$CH_NAME = (split(/[.]/, (split(/\t/, $HEADERS))[9]))[0];
# Initial Calculations
print "Performing Initial Calculations...\n\n" if $verbose;
my $init_results = parse_file($INPUT_FILE, \&initial_calculations);
return() unless $init_results;
my (@init_ch_stats, @init_p1_stats, @init_p2_stats);
map {push(@init_ch_stats, $$_[0])} @$init_results;
map {push(@init_p1_stats, $$_[1])} @$init_results;
map {push(@init_p2_stats, $$_[2])} @$init_results;
my @sorted_init_p1 = sort {
$$a[0] <=> $$b[0] || $$a[1] <=> $$b[1]} @init_p1_stats;
my @sorted_init_p2 = sort {
$$a[0] <=> $$b[0] || $$a[1] <=> $$b[1]} @init_p2_stats;
my @sorted_init_ch = sort {
$$a[0] <=> $$b[0] || $$a[1] <=> $$b[1]} @init_ch_stats;
(my $p1_normals, $P1_mBAF_MED, $P1_LRR_MED, my $p1_nc_rate,
$P1_AA_BOUND, $P1_BB_BOUND) = calc_init_stats(\@sorted_init_p1, 9);
(my $p2_normals, $P2_mBAF_MED, $P2_LRR_MED, my $p2_nc_rate,
$P2_AA_BOUND, $P2_BB_BOUND) = calc_init_stats(\@sorted_init_p2, 9);
(my $ch_normals, $CH_mBAF_MED, $CH_LRR_MED, my $ch_nc_rate,
$AA_BOUND, $BB_BOUND, $AB_UPPER_BOUND, $AB_LOWER_BOUND)
= calc_init_stats(\@sorted_init_ch, 9);
# Calculate MI1 thresholds
my ($ab_sums, $ab_sum_sq, $ab_ct) = (0) x 3;
foreach (@$ch_normals) {
$ab_sums += $$_[2]->[3];
$ab_sum_sq += $$_[2]->[4];
$ab_ct += $$_[2]->[5];
}
my @AB_stats = st_dev($ab_sums, $ab_sum_sq, $ab_ct);
$MI1_UPPER_THRESH = $AB_stats[0] + ($AB_stats[1] * 5);
$MI1_UPPER_THRESH = 0.95 if $MI1_UPPER_THRESH > 0.95;
$MI1_LOWER_THRESH = $AB_stats[0] - ($AB_stats[1] * 5);
$MI1_LOWER_THRESH = 0.05 if $MI1_LOWER_THRESH < 0.05;
$PODCR_UPPER_THRESH = $AB_stats[0] + ($AB_stats[1] * 2);
$PODCR_LOWER_THRESH = $AB_stats[0] - ($AB_stats[1] * 2);
# Set initial estimate of acceptable errors
$ACCEPTABLE_ERRORS = 3;
# Determine largest number of informative SNPs in window for each arm
my $max_windows = parse_file($INPUT_FILE, \&max_window);
return() unless $max_windows;
my @sorted_max_windows = sort {
$$a[0] <=> $$b[0] || $$a[1] <=> $$b[1]} @$max_windows;
map {$$_[2] ||= 5} @sorted_max_windows;
for (0..$#sorted_init_ch) {
push(@{$sorted_init_ch[$_]}, $sorted_max_windows[$_]->[2]);
}
($ch_normals, $CH_mBAF_MED, $CH_LRR_MED, $ch_nc_rate,
$AA_BOUND, $BB_BOUND, $AB_UPPER_BOUND, $AB_LOWER_BOUND)
= calc_init_stats(\@sorted_init_ch, -1);
my $rounded_AA_bound = sprintf("%.3f",$AA_BOUND);
my $rounded_BB_bound = sprintf("%.3f",$BB_BOUND);
my $rounded_AB_up_bound = sprintf("%.3f",$AB_UPPER_BOUND);
my $rounded_AB_low_bound = sprintf("%.3f",$AB_LOWER_BOUND);
# Recalculate MI1 thresholds
($ab_sums, $ab_sum_sq, $ab_ct) = (0) x 3;
foreach (@$ch_normals) {
$ab_sums += $$_[2]->[3];
$ab_sum_sq += $$_[2]->[4];
$ab_ct += $$_[2]->[5];
}
@AB_stats = st_dev($ab_sums, $ab_sum_sq, $ab_ct);
$MI1_UPPER_THRESH = $AB_stats[0] + ($AB_stats[1] * 5);
$MI1_UPPER_THRESH = 0.95 if $MI1_UPPER_THRESH > 0.95;
$MI1_LOWER_THRESH = $AB_stats[0] - ($AB_stats[1] * 5);
$MI1_LOWER_THRESH = 0.05 if $MI1_LOWER_THRESH < 0.05;
$PODCR_UPPER_THRESH = $AB_stats[0] + ($AB_stats[1] * 2);
$PODCR_LOWER_THRESH = $AB_stats[0] - ($AB_stats[1] * 2);
###### Recalculate largest window sizes and get counts for HD, MI1, ########
###### and outliers, and pvalues for FDR calculations
my $secondary_results = parse_file($INPUT_FILE, \&secondary_counts);
return() unless $secondary_results;
my @sorted_secondary = sort {
$$a[0] <=> $$b[0] || $$a[1] <=> $$b[1]} @$secondary_results;
for (0..$#sorted_secondary) {
push(@{$sorted_secondary[$_]}, @{$sorted_init_ch[$_]}[6,7]);
}
my (@scan_stat_array, @normals);
# Make an array of refs for kmeans
map {push(@scan_stat_array, [$$_[2]])} @sorted_secondary;
# Cluster refined scan statistics
my $y = 0.5;
my ($num_clusters, $normal_cluster, $cluster_ref)
= cluster(\@scan_stat_array, $y);
if ($num_clusters == 1) {@normals = @sorted_secondary}
else {
my @temp = @sorted_secondary;
until ($num_clusters == 1) {
@normals = @scan_stat_array = ();
for (my $i = 0; $i < @temp; $i++) {
if ($$cluster_ref[$i] == $normal_cluster) {
push(@normals, $temp[$i]);
}
}
map {push(@scan_stat_array, [$$_[2]])} @normals;
@temp = @normals;
#last if (@normals == 1);
$y -= 0.025;
($num_clusters, $normal_cluster, $cluster_ref)
= cluster(\@scan_stat_array, $y);
}
}
# Remove any values in normal cluster > 4SDs of mean
if (@normals > 1) {
my ($stdev, $mean) = st_dev([map{$$_[2]} @normals]);
my @adj_normals;
for (0..$#normals) {
my $curr_value = $normals[$_]->[2];
unless (abs($curr_value) > $mean + $stdev * 4) {
push (@adj_normals, $normals[$_]);
}
}
@normals = @adj_normals;
}
my ($baf_snp_ct, $norm_baf_ct) = (0) x 2;
$baf_snp_ct += $_ for map {$$_[-2]} @sorted_secondary;
$norm_baf_ct += $_ for map {$$_[-2]} @normals;
my $adjusted_mi1_ct = 0;
$adjusted_mi1_ct += $_ for map {$$_[3]} @normals;
my $mi1_rate = $adjusted_mi1_ct / $norm_baf_ct;
$MIN_MI1 = calc_min_adj_snps($norm_baf_ct, $mi1_rate, $ALPHA);
my $total_mi1_ct;
map {$total_mi1_ct += "$$_[3]\t"} @sorted_secondary;
my $total_mi1_rate = $total_mi1_ct / $baf_snp_ct;
map {$HET_MI1_CT += "$$_[8]\t"} @normals;
$HET_MI1_RATE = $HET_MI1_CT / $norm_baf_ct;
my $baf_outliers;
$ab_ct = 0;
map {$baf_outliers += "$$_[9]\t"} @normals;
map {$ab_ct += "$$_[10]\t"} @normals;
my $baf_outlier_rate = $baf_outliers / $ab_ct;
$MIN_BAF_OUT = calc_min_adj_snps($ab_ct, $baf_outlier_rate, $ALPHA);
my $next = check_quality($total_mi1_rate, $p1_nc_rate, $p2_nc_rate,
$ch_nc_rate);
if ($next) {
if ($BATCH) {return()}
else {exit 5}
}
# Calculate hd rates and minimum size of hd regions
my ($p1_hd_ct, $p2_hd_ct, $ch_hd_ct, $norm_lrr_snp_ct) = (0) x 4;
$p1_hd_ct += $_ for map {$$_[5]} @normals;
$p2_hd_ct += $_ for map {$$_[6]} @normals;
$ch_hd_ct += $_ for map {$$_[7]} @normals;
$norm_lrr_snp_ct += $_ for map {$$_[-1]} @normals;
my $p1_hd_rate = $p1_hd_ct / $norm_lrr_snp_ct;
my $p2_hd_rate = $p2_hd_ct / $norm_lrr_snp_ct;
my $ch_hd_rate = $ch_hd_ct / $norm_lrr_snp_ct;
$MIN_P1_HD = calc_min_adj_snps($norm_lrr_snp_ct, $p1_hd_rate, $ALPHA);
$MIN_P2_HD = calc_min_adj_snps($norm_lrr_snp_ct, $p2_hd_rate, $ALPHA);
$MIN_CH_HD = calc_min_adj_snps($norm_lrr_snp_ct, $ch_hd_rate, $ALPHA);
# Default assumption of error rate is 3.75 times the rate of single
# Mendelian errors as determined by the ratio of all single
# errors derived from mutating all genotype combinations
# of normal inheritance to all detectable errors (24 detectable
# changes out of 90 possible changes). The ratio (90/24) is then used
# to estimate the overall "error" rate (single Mendelian errors and
# single SNP biological abnormalities). In a previous step, single
# Mendelian errors were counted while discarding any which were
# adjacent to reduce influence of large biological abnormalities in
# error rate estimations.
$ERROR_RATE = $mi1_rate * 3.75;
my $rounded_error_rate = sprintf("%.5f", $ERROR_RATE);
# Calculate minimum window size (informative SNPs)
my $inf_snp_ct;
$inf_snp_ct += $_ for map {$$_[4]} @normals;
my $inf_hUPD_ct;
map {$inf_hUPD_ct += "$$_[11]\t"} @normals;
unless (@normals) {print STDERR "cluster problem - no normals $FILENAME\n"}
$hUPD_RATE = $inf_hUPD_ct / $inf_snp_ct;
my $inf_snp_rate = $inf_snp_ct / $norm_baf_ct;
$inf_snp_ct = int(($inf_snp_rate * $baf_snp_ct) + 0.5);
($MIN_POD, $POD_ALPHA) = calculate_threshold($SIZE_SMALL_WINDOW, 6,
$inf_snp_ct, $baf_snp_ct, $ALPHA);
($MIN_LARGE_POD, $LARGE_POD_ALPHA) = calculate_threshold(
$SIZE_SMALL_WINDOW * 5, 12, $inf_snp_ct, $baf_snp_ct, $ALPHA);
# If no possible POD regions given alpha, continue running
# without POD analysis if other detection methods are selected
if (!$MIN_POD) {
if ($HD || $MI1 || $PODcr) {($POD, $MIN_POD) = ("",9)}
else {
print OUTPUT_FILE "\n\nNo regions of abnormal parental ",
"contribution were detected at this alpha level.\n\n"
unless $BATCH;
print STDERR "Sample $FILENAME : No regions of abnormal parental ",
"contribution were detected at this alpha level.\n" if $BATCH;
print "\n\nNo regions of abnormal parental contribution were ",
"detected at this alpha level.\n\n" if $verbose;
if ($BATCH) {return([0,0,0,1])}
else {exit 4}
}
}
# Calculate Acceptable Errors
my ($stop, $errors) = (0) x 2;
until ($stop) {
my $pvalue = bin_test($errors, $SIZE_SMALL_WINDOW, $ERROR_RATE, "g");
if ($pvalue <= 0.001) {
$stop = 1;
$ACCEPTABLE_ERRORS = $errors - 1;
$ACCEPTABLE_ERRORS ||= 0;
}
$errors++;
}
($stop, $errors) = (0) x 2;
until ($stop) {
my $pvalue = bin_test($errors, $SIZE_LARGE_WINDOW, $ERROR_RATE, "g");
if ($pvalue <= 0.001) {
$stop = 1;
$LARGE_WIN_ACCEPTABLE_ERRORS = $errors - 1;
$LARGE_WIN_ACCEPTABLE_ERRORS ||= 0;
}
$errors++;
}
################################## Analysis ################################
my $analysis_results = parse_file($INPUT_FILE, \&manage_chromosome_arm,
"main");
my (@detected_regions, @local_meds, @local_meds_by_chr);
for (@$analysis_results) {
push(@detected_regions, @{$$_[0]});
# Store local medians
if ($$_[1]) {
push(@local_meds, $$_[2]);
$local_meds_by_chr[$$_[1]] = $$_[2];
}
}
# Refine autosomal medians to reflect only normal regions in child
$P1_mBAF_MED = median([map {$$_[0]} @local_meds]);
$P2_mBAF_MED = median([map {$$_[1]} @local_meds]);
$CH_mBAF_MED = median([map {$$_[2]} @local_meds]);
$P1_LRR_MED = median([map {$$_[3]} @local_meds]);
$P2_LRR_MED = median([map {$$_[4]} @local_meds]);
$CH_LRR_MED = median([map {$$_[5]} @local_meds]);
####################### Descriptive Calculations #######################
# Check if regions were detected
if ($#detected_regions < 0) {
print OUTPUT_FILE "\n\nNo regions of abnormal parental contribution ",
"were detected at this alpha level.\n\n" unless $BATCH;
print STDERR "Sample $FILENAME : No regions of abnormal parental ",
"contribution were detected at this alpha level.\n" if $BATCH;
print "\n\nNo regions of abnormal parental contribution were ",
"detected at this alpha level.\n\n" if $verbose;
if($BATCH) {return([0,0,0,1])}
else {exit 4}
}
# Sort output array by chromosome and position
my @sorted_detected_regions = sort {
$$a[0] <=> $$b[0] || $$a[1] <=> $$b[1]} @detected_regions;
######################## Prepare results for output file ####################
my ($count, $num_pod, $num_mi1, $num_hd, $num_podcr) = (0) x 5;
foreach my $ref (@sorted_detected_regions) {
if ($$ref[17] == POD) {$num_pod++}
elsif ($$ref[17] == MI1) {$num_mi1++}
elsif ($$ref[17] == HD) {$num_hd++}
elsif ($$ref[17] == PODcr) {$num_podcr++}
# If a region comprised most of a chromosome arm and underwent
# a single round of analyses, adjust the regions medians by
# the medians of the normal SNPs from the other arm, or if
# most of the chromosome is abnormal, adjust using the autosomal
# medians.
my ($p1_mBAF, $p2_mBAF, $ch_mBAF, $p1_LRR, $p2_LRR, $ch_LRR);
if ($$ref[19] == 1) {
if ($local_meds_by_chr[$$ref[0]]) {
# local medians
($p1_mBAF, $p2_mBAF, $ch_mBAF, $p1_LRR, $p2_LRR, $ch_LRR) =
@{$local_meds_by_chr[$$ref[0]]};
}
else {
# refined autosomal medians
($p1_mBAF, $p2_mBAF, $ch_mBAF, $p1_LRR, $p2_LRR, $ch_LRR) =
($P1_mBAF_MED, $P2_mBAF_MED, $CH_mBAF_MED,
$P1_LRR_MED, $P2_LRR_MED, $CH_LRR_MED);
}
$$ref[10] = sprintf("%.4f", $$ref[10] - ($ch_mBAF - 0.5))
unless $$ref[10] eq "NA";
$$ref[11] = sprintf("%.4f", $$ref[11] - $ch_LRR)
unless $$ref[11] eq "NA";
$$ref[12] = sprintf("%.4f", $$ref[12] - ($p1_mBAF - 0.5))
unless $$ref[12] eq "NA";
$$ref[13] = sprintf("%.4f", $$ref[13] - $p1_LRR)
unless $$ref[13] eq "NA";
$$ref[14] = sprintf("%.4f", $$ref[14] - ($p2_mBAF - 0.5))
unless $$ref[14] eq "NA";
$$ref[15] = sprintf("%.4f", $$ref[15] - $p2_LRR)
unless $$ref[15] eq "NA";
if ($$ref[11] > $AMP + $ch_LRR) {$$ref[3] = "AMP"}
elsif ($$ref[11] < $DEL_UPPER + $ch_LRR &&
$$ref[11] > $HD_HI + $ch_LRR) {$$ref[3] = "DEL"}
elsif ($$ref[11] <= $HD_HI + $ch_LRR) {$$ref[3] = "HD"}
#else {$$ref[3] = " "}
$$ref[20] = call_inheritance($ref);
unless($$ref[10] eq "NA") {
$$ref[10] = sprintf("%.4f", 0.5) if ($$ref[10] < 0.5)}
unless($$ref[12] eq "NA") {
$$ref[12] = sprintf("%.4f", 0.5) if ($$ref[12] < 0.5)}
unless($$ref[14] eq "NA") {
$$ref[14] = sprintf("%.4f", 0.5) if ($$ref[14] < 0.5)}
}
if ($$ref[4] == FATHER) {$$ref[4] = "Father"}
elsif ($$ref[4] == MOTHER) {$$ref[4] = "Mother"}
elsif ($$ref[4] == NONE) {$$ref[4] = "None"}
elsif ($$ref[4] == BOTH) {$$ref[4] = "Both"}
elsif ($$ref[4] == UNKNOWN) {$$ref[4] = "Unknown"}
if ($$ref[3] eq " " && ($$ref[4] eq "Father" || $$ref[4] eq "Mother")) {
$$ref[4] = $$ref[4] . "(C)";
}
my $detection;
if ($$ref[17] == HD) {$detection = "HD"}
elsif ($$ref[17] == MI1) {$detection = "MI1"}
elsif ($$ref[17] == POD) {$detection = "POD"}
elsif ($$ref[17] == PODcr) {$detection = "PODcr"}
push(@output, [$CH_NAME, @$ref[0..4,20,5..7], $detection,
@$ref[10..15]]);
}
push(@trio_def, "Trio Definition Autosomal NoCall Rate",
"Father = $P1_NAME\t$p1_nc_rate",
"Mother = $P2_NAME\t$p2_nc_rate",
"Child = $CH_NAME\t$ch_nc_rate") unless ($BATCH);
############## Create file to pass results to R script ##################
if ($GRAPHICS) {
($PERL_TO_R_FILE, $PERL_TO_R_FILENAME) = tempfile(UNLINK => 1);
print $PERL_TO_R_FILE "Chr\tStart\tStop\tType\tParent\tSNPs",
"\tInformative SNPs\tSize of Region (bp)\tRadius of region for R",
"\tbp of midpoint for R\tMedian BAF\tMedian LRR\tFather-Median ",
"BAF\tFather-Median LRR\tMother-Median BAF\tMother-Median LRR\n";
map {print $PERL_TO_R_FILE join("\t", @{$_}[0..15]), "\n"}
@sorted_detected_regions;
print "Creating Graphics ...\n" if $verbose;
start_R();
}
map{$$_[4] = "NA" if $$_[4] eq " "} @output;
map{$$_[6] = "NA" if $$_[6] eq " "} @output;
if ($STATS) {
push(@stats, [$FILENAME, $CH_NAME, $P1_NAME, $P2_NAME, $ch_nc_rate,
$p1_nc_rate, $p2_nc_rate, $ch_hd_rate, $MIN_CH_HD, $p1_hd_rate,
$MIN_P1_HD, $p2_hd_rate, $MIN_P2_HD, $mi1_rate, $MIN_MI1,
$MI1_UPPER_THRESH, $MI1_LOWER_THRESH, $MIN_POD, $POD_ALPHA, $ALPHA,
$ERROR_RATE, $ACCEPTABLE_ERRORS, $AA_BOUND, $BB_BOUND,
$AB_UPPER_BOUND, $AB_LOWER_BOUND, $#sorted_detected_regions,
$num_pod, $num_podcr, $num_mi1, $num_hd]);
}
$completed = 1;
return([\@output, \@stats, \@trio_def, $completed]);
}
########################### Sub Functions ###########################
sub baf_stats_for_stdev {
my ($baf, $lower, $upper, $baf_ref, $mbaf_ref) = @_;
my ($aa_sum, $aa_sum_squares, $aa_count, $ab_sum, $ab_sum_squares,
$ab_count, $bb_sum, $bb_sum_squares, $bb_count, $baf_sum,
$baf_ct);
# $baf_ref array indices = aa_sum, aa_sum_squares, aa_count, ab_sum,
# ab_sum_squares, ab_count, bb_sum, bb_sum_squares, bb_count,
# baf sum for mbaf, baf ct for mbaf
if ($baf < $upper) {
if ($baf <= $lower) {
# AA
$$baf_ref[0] += $baf;
$$baf_ref[1] += $baf**2;
$$baf_ref[2]++;
}
else {
# AB
$$baf_ref[3] += $baf;
$$baf_ref[4] += $baf**2;
$$baf_ref[5]++;
push(@$mbaf_ref, $baf);
$$baf_ref[9] += $baf;
$$baf_ref[10]++;
}
}
else {
# BB
$$baf_ref[6] += $baf;
$$baf_ref[7] += $baf**2;
$$baf_ref[8]++;
}
}
sub bin_coeff {
# Estimates and returns the binomial coefficient for n and k.
my ($n, $k) = @_;
return 1 if $k == 0;
my $r = $n - $k + 1;
for (2..$k) {$r *= (($n - $k)/$_ + 1)}
return ($r);
}
sub bin_test {
# Performs an approximation of the binomial test.
# alternative hypothesis = "t" = two-tailed, "l" = one-tailed <= k,
# "g" = one-tailed >= k
my ($k, $n, $p, $tail) = @_;
my ($pvalue, $x, $y) = (0) x 3;
if ($tail eq "t") {
if ($n / 2 == $k) {return(1)}
else {($x, $y) = ($k <= $n / 2) ? (0, $k) : ($k, $n)}
}
elsif ($tail eq "l") {($x, $y) = (0, $k)}
elsif ($tail eq "g") {($x, $y) = ($k, $n)}
for ($x..$y) {$pvalue += dbinom($_, $n, $p)}
$pvalue = 2 * $pvalue if ($tail eq "t");
$pvalue = 1 if ($pvalue > 1);
return($pvalue);
}
sub calc_init_stats {
my ($init_stats, $index) = @_;
# Identify and ignore abnormal chromosome arms
my (@values, @normals) = ();
map {push(@values, [$$_[$index]])} @$init_stats;
my $y = 0.5;
my ($num_clusters, $normal_cluster, $cluster_ref)
= cluster(\@values, $y);
my $ct = 0;
if ($num_clusters == 1) {@normals = @$init_stats}
else {
my @temp = @$init_stats;
until ($num_clusters == 1) {
@normals = @values = ();
for (my $i = 0; $i < @temp; $i++) {
if ($$cluster_ref[$i] == $normal_cluster) {
push(@normals, $temp[$i]);
}
}
map {push(@values, [$$_[$index]])} @normals;
@temp = @normals;
#last if (@normals == 1);
$ct++;
$y -= 0.025 * $ct;
($num_clusters, $normal_cluster, $cluster_ref)
= cluster(\@values, $y);
}
}
# Remove any values in normal cluster > 4SDs of mean
if (@normals > 1) {
my ($stdev, $mean) = st_dev([map{$$_[$index]} @normals]);
my @adj_normals;
for (0..$#normals) {
my $curr_value = $normals[$_]->[$index];
unless (abs($curr_value) > $mean + $stdev * 4) {
push (@adj_normals, $normals[$_]);
}
}
@normals = @adj_normals;
}
# Calculate median of mBAF medians of "normal" chromosome arms
my $mBAF_med = median([map{$$_[3]} @normals]);
my $lrr_med = median([map{$$_[4]} @normals]);
# Calculate NC rate of "normal" chromosome arms
my ($nc_ct, $nc_snp_ct, $nc_rate) = (0) x 3;
$nc_ct += $_ for map {$$_[5]} @normals;
$nc_snp_ct += $_ for map {$$_[8]} @normals;
$nc_rate = sprintf("%.4f", $nc_ct / $nc_snp_ct) if $nc_snp_ct;
$nc_rate ||= 0;
# Calculate BAF thresholds
my ($aa_sums, $aa_sum_sq, $aa_ct) = (0) x 3;
foreach (@normals) {
$aa_sums += $$_[2]->[0];
$aa_sum_sq += $$_[2]->[1];
$aa_ct += $$_[2]->[2];