-
Notifications
You must be signed in to change notification settings - Fork 37
/
snpgenie_within_group.pl
executable file
·18020 lines (17658 loc) · 269 KB
/
snpgenie_within_group.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
# PROGRAM: SNPGenie for within-group analysis is a Perl program that calculates dN/dS,
# piN/piS, and gene diversity for a single aligned FASTA file, with accompanying CDS
# annotations in a GTF file.
#########################################################################################
# EXAMPLE CALL:
#########################################################################################
# snpgenie_within_group.pl --fasta_file_name=<aligned_seqs>.fa --gtf_file_name=<CDS_annotations>.gtf --num_bootstraps=10000 --procs_per_node=16
#########################################################################################
#########################################################################################
## LICENSE
## This program 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.
##
## This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
#########################################################################################
# AUTHOR: Chase W. Nelson
# Copyright (C) 2017 Chase W. Nelson
# CONTACT1: [email protected]
# CONTACT2: [email protected]
# AFFILIATION1: Sackler Institute for Comparative Genomics, American Museum of Natural
# History, New York, NY 10024, USA
# AFFILIATION2: Special Volunteer, Division of Cancer Epidemiology & Genetics, National
# Cancer Institute, National Institutes of Health, Rockville, MD 20850, USA
# AFFILIATION3: BigPlant Consortium, Center for Genomics and Systems Biology, New York
# University, New York, NY 10003, USA
# CITATION1: SNPGenie, https://github.com/chasewnelson/snpgenie
# CITATION2: Nelson CW, Moncla LH, Hughes AL (2015) SNPGenie: estimating evolutionary
# parameters to detect natural selection using pooled next-generation sequencing data.
# Bioinformatics 31(22):3709-11, doi: 10.1093/bioinformatics/btv449.
# SNPGenie for use with HPV!
# WAS snpgenie_between_group.pl
# We have co-opted by natural selection. That's what this is.
# ADD:
# —SORT codons before entry into the NNN-NNN comps hh, so we don't have, e.g., both AAG-AAA and AAA-AAG
# —ADD MAJORITY CODON to codon file
# —PROBLEM with min-codon-count in variant results
use strict;
#use warnings;
use Data::Dumper;
use List::Util qw(max);
#use Math::Random::OO::Bootstrap;
#use Statistics::Basic qw(:all);
use Parallel::ForkManager;
#use Statistics::Basic qw(:all); # includes median(), mean(), variance(), stddev(), covariance(), correlation()
use Getopt::Long;
STDOUT->autoflush(1);
# Get the time
my $time1 = time;
my $local_time1 = localtime;
#########################################################################################
# INITIALIZE (OPTIONAL) INPUT VARIABLES
my $fasta_file_name;
my $gtf_file_name;
my $procs_per_node;
#my $sliding_window_size;
#my $sliding_window_step;
my $num_bootstraps;
# Get user input, if given. If a Boolean argument is passed, its value is 1; else undef
GetOptions( "fasta_file_name=s" => \$fasta_file_name,
"gtf_file_name=s" => \$gtf_file_name,
"procs_per_node=i" => \$procs_per_node,
# "sliding_window_size:i" => \$sliding_window_size, # optional integer parameter
# "sliding_window_step:i" => \$sliding_window_step, # optional integer parameter
"num_bootstraps=i" => \$num_bootstraps)
or die "\n### WARNING: Error in command line arguments. Script terminated.\n\n";
# If an argument is called as a flag, its value is 0; if not called, it's null
unless($fasta_file_name =~ /.fa/) {
die "\n### WARNING: The --fasta_file_name option must be a file with a .fa or .fasta extension\n".
"### SNPGenie terminated.\n\n";
}
unless($gtf_file_name =~ /.gtf/) {
die "\n### WARNING: The --gtf_file_name option must be a file with a .gtf or .gtf extension\n".
"### SNPGenie terminated.\n\n";
}
if(! $procs_per_node) {
if($procs_per_node != 0) {
$procs_per_node = 1; # DEFAULT is 1
}
# $param_file_contents .= "MINIMUM ALLELE FREQUENCY: Default used; all SNPs included\n";
} elsif($procs_per_node < 1) {
die "\n### WARNING: The --procs_per_node option must be an integer ≥1\n".
"### SNPGenie terminated.\n\n";
} #else {
# $param_file_contents .= "MINIMUM ALLELE FREQUENCY: $minfreq\n";
#}
#if(! $sliding_window_size) {
# if($sliding_window_size != 0) { # Called as a flag, but given no value
# $sliding_window_size = 10; # default behavior: 10-mer peptide
# }
## $param_file_contents .= "SLIDING WINDOW LENGTH: Default used; 9 codons\n";
#} elsif($sliding_window_size < 1) {
# die "\n### WARNING: The --sliding_window_size option must be an integer ≥1\n".
# "### SNPGenie terminated.\n\n";
#} #else {
## $param_file_contents .= "SLIDING WINDOW LENGTH: None\n";
##}
#
#if(! $sliding_window_step) {
# if($sliding_window_step != 0) { # Called as a flag, but given no value
# $sliding_window_step = 1; # default behavior: one codon
# }
#} elsif($sliding_window_step < 1) {
# die "\n### WARNING: The --sliding_window_step option must be an integer ≥1\n".
# "### SNPGenie terminated.\n\n";
#}
if(! $num_bootstraps) {
if($num_bootstraps != 0) { # Called as a flag, but given no value
$num_bootstraps = 1000; # default behavior: nonamer peptide
}
# $param_file_contents .= "SLIDING WINDOW LENGTH: Default used; 9 codons\n";
} elsif($num_bootstraps < 2) {
die "\n### WARNING: The --num_bootstraps option must be an integer ≥2\n".
"### SNPGenie terminated.\n\n";
} #else {
# $param_file_contents .= "SLIDING WINDOW LENGTH: None\n";
#}
### Prepare for bootstrapping
##if(! $num_bootstraps) { # null or 0
## $num_bootstraps = 0; # default behavior
##} elsif(! $num_bootstraps >= 10) {
## die "\n### WARNING: The --num_bootstraps option must ≥10\n".
## "### Script terminated.\n\n";
##}
##
### Optional BOOTSTRAP argument
##if($num_bootstraps >= 10) {
## print "\n# Bootstrapping will be performed with $num_bootstraps replicates.\n";
##} else {
## print "\n# No bootstrapping will occur.\n";
##}
##
### Set up parallelism
##if(! $procs_per_node) { # null or 0
## $procs_per_node = 1; # default behavior
##} elsif($procs_per_node < 1) {
## die "\n### WARNING: The --procs_per_node option must ≥1\n".
## "### Script terminated.\n\n";
##}
print "\n# Number of parallel processes to be invoked is $procs_per_node\.\n";
print "\n################################################################################".
"\n## ##".
"\n## Within-Group SNPGenie Initiated! ##".
"\n## ##".
"\n################################################################################\n";
print "\nSNPGenie initiated at local time $local_time1\n";
#my $fasta_file_name = $ARGV[0];
#my $gtf_file_name = $ARGV[1];
#unless($fasta_file_name =~ /.fa/) { die "\n\n# FASTA file must contain .fa or .fasta extension. TERMINATED\n\n"; }
#unless($gtf_file_name =~ /.gtf/) { die "\n\n# GTF file must contain .gtf extension. TERMINATED\n\n"; }
# Store product information
my @product_names_arr = &get_product_names_from_gtf($gtf_file_name);
@product_names_arr = sort {$a <=> $b} @product_names_arr;
#print "\nProduct names: @product_names_arr\n";
# Determine all product coordinates
my %product_coordinates_ha;
foreach my $product_name (@product_names_arr) {
#print "product name is: $product_name\n";
my @product_coord_arr = &get_product_coordinates($product_name);
#print "\n\n$product_name product_coord arr: @product_coord_arr\n\n";
# Save to a hash of arrays
push(@{$product_coordinates_ha{$product_name}->{product_coord_arr}},@product_coord_arr);
#print "\n\n$product_name product_coord arr in harr: @{$product_coordinates_ha{$product_name}->{product_coord_arr}} \n\n";
}
# Read in the group of sequences from the fasta file
my $seq = '';
my @seqs_arr;
#my $header = '';
#my @headers_arr;
my $seq_num = 0;
my $last_seq_length;
open(IN_FASTA, "$fasta_file_name") or die "Could not open file $fasta_file_name\n";
print "\nRecording coding sequence data for $fasta_file_name...\n";
while(<IN_FASTA>) {
chomp;
if(/>/) {
if($seq_num == 0) {
#$header = $_;
$seq_num ++;
} else {
$seq = uc($seq);
$seq =~ tr/U/T/;
push(@seqs_arr,$seq);
#push(@headers_arr,$header);
#$header = $_;
$seq_num ++;
my $this_seq_length = length($seq);
#print "\nseq $seq_num is of length $this_seq_length\n";
#print "\nseq: $seq\n";
if($last_seq_length && ($last_seq_length != $this_seq_length)) {
die "\n\nDIE: The sequences must be aligned, i.e., must be the same length. TERMINATED.\n\n";
} else {
$last_seq_length = $this_seq_length;
#print "\nseq: $seq\n";
$seq = '';
}
}
} else {
$seq .= $_;
}
}
close IN_FASTA;
$seq = uc($seq);
$seq =~ tr/U/T/;
push(@seqs_arr,$seq);
#push(@headers_arr,$header);
print "\n";
# Go through each product and DO DIS THANG
# HERE'S HOW to get the first array:
#print "@{$seqs_aa[0]}\n";
#my $counter=1;
#foreach(@{$seqs_aa[0]}) {
# print "$counter: $_\n\n";
# $counter++;
#}
my %products_seqs_hh;
# FORMAT:
#%products_seqs_hh = {
# 'ORF1a' => {
# 'seq_1' => 'ACGT',
# 'seq_2' => 'ACGT',
# ... ,
# 'seq_n' => 'ACGT',
# },
#
# 'ORF1b' => {
# 'seq_1' => 'ACGT',
# 'seq_2' => 'ACGT',
# ... ,
# 'seq_n' => 'ACGT',
# }
# }
#};
foreach(@product_names_arr) { # FOR EACH PRODUCT
my $product_name = $_;
my @product_coord_arr = @{$product_coordinates_ha{$product_name}->{product_coord_arr}};
# New segments approach
my %product_starts;
my %product_stops;
my $num_segments = (@product_coord_arr / 2);
for(my $i=1; $i<=$num_segments; $i++) { # $i<=scalar(@product_coord_arr) # FOR EACH SEGMENT (2) # COME BACK COMEBACK
$product_starts{$i} = $product_coord_arr[2*$i-2];
$product_stops{$i} = $product_coord_arr[2*$i-1];
}
# Build an array of all the sequences, JUST ONE GROUP
my $seq_num = 0;
foreach my $sequence (@seqs_arr) { # for each seq in alignment (max coverage)
$seq_num ++;
my $seq_id = 'seq_' . $seq_num;
#build the product seq and add it to full group list
my $this_product_seq = '';
for(my $seg=1; $seg<=$num_segments; $seg++) { # for each segment
#my $this_index = $seg - 1;
#my $this_start = $product_starts[$this_index];
my $this_start = $product_starts{$seg};
my $this_start_index = $this_start - 1;
#my $this_stop = $product_stop[$this_index];
my $this_stop = $product_stops{$seg};
my $this_stop_index = $this_stop - 1;
my $this_seg_length = ($this_stop - $this_start + 1);
$this_product_seq .= substr($sequence,$this_start_index,$this_seg_length);
} # done building sequence with all segments
# Add the sequence to an array of all sequences for this product in the group
$products_seqs_hh{$product_name}->{$seq_id} = $this_product_seq;
}
}
#my @test_keys = keys %{$products_groups_seqs_hh{'ORF5'}->{'group_1'}};
#@test_keys = keys %products_groups_seqs_hh;
#print "\n\n @test_keys \n\n";
#my $test_seq = $products_groups_seqs_hh{'ORF5'}->{'group_1'}->{'seq_1'};
#print "\n\n $test_seq \n\n";
open(CODON_FILE,">>within\_group\_codon\_results\.txt");
print CODON_FILE "file\tproduct\tcodon\tvariability\tcomparisons\t".
"N_sites\tS_sites\tN_diffs\tS_diffs\n";
close CODON_FILE;
open(VARIANT_FILE,">>within\_group\_variant\_results\.txt");
print VARIANT_FILE "file\tproduct_name\tcodon_num\tconsensus_codon\tnum_alleles\t".
"codons\tamino_acids\tvariant_type\tcodon_counts\tcount_total\tcodon_freqs\t".
"max_codon_count\tmin_codon_count\tnum_defined_seqs\n";
close VARIANT_FILE;
open(OUTFILE,">>within\_group\_product\_results\.txt");
print OUTFILE "file\tproduct\tN_sites\tS_sites\tN_diffs\tS_diffs\tdN\tdS\t";
if($num_bootstraps > 1) {
print OUTFILE "SE_dN\tSE_dS\t";
}
print OUTFILE "dN_minus_dS\tdN_over_dS";
if($num_bootstraps > 1) {
print OUTFILE "\tSE_dN_minus_dS\tZ_value\tsignificance\n";
} else {
print OUTFILE "\n";
}
## Preparing sliding window output
#open(OUTFILE_WITHIN_SW,">>within\_group\_sw_" . $sliding_window_size . "codons\_results.txt");
#print OUTFILE_WITHIN_SW "analysis\tfamily\tpartition\tgroup_1\tgroup_2\twindow\tfirst_codon\tlast_codon\t".
# "num_defined_codons_g1\tnum_defined_codons_g2\tmean_num_defined_codons\tmin_num_defined_codons\t".
# "N_sites\tS_sites\t".
# "N_diffs\tS_diffs\t".
# "dN\tdS\t".
# "dN\-dS\t".
# "dN\/dS\tdN\>total_dS";
#
#if($num_bootstraps > 1) {
# print OUTFILE_WITHIN_SW "\tSE(dN-dS)\tZ_value\tsignificance\n";
#} else {
# print OUTFILE_WITHIN_SW "\n";
#}
#
#close OUTFILE_WITHIN_SW;
#print "product\tN_sites\tS_sites\tN_diffs\tS_diffs\n";
# YES, it all works
#my %product_data_hh;
my $total_N_sites = 0;
my $total_S_sites = 0;
my $total_N_diffs = 0;
my $total_S_diffs = 0;
# We HAVE all the sequences stored by product in %products_seqs_hh as
# $products_seqs_hh{$product_name}->{$seq_id}
# Next, let's simply build/analyze all codons for each as we go; so
# (1) loop products
# (2) loop codons
# (3) analyze as we go
#my $last_num_codons;
my %min_count2num_alleles_TOTALS;
foreach my $product_name (keys %products_seqs_hh) { # for each product
# FOREACH SEQUENCE IN FASTA?
# foreach my $sequence (@seqs_arr)
print "\n################################################################################".
"\nANALYZING $product_name:\n";
# I want, for this product:
#codonum_codon_aa[codon_index]->array of all codons at that site
my @codonum_codon_aa;
my $last_num_codons;
# STORE all codons here
foreach my $seq_id (keys %{$products_seqs_hh{$product_name}}) { # for each sequence
my $product_seq = $products_seqs_hh{$product_name}->{$seq_id};
my $product_length = length($product_seq);
#print "\nProduct $product_name is $product_length nucleotides long:\n$product_seq\n\n";
#foreach codon as in 1 + 3 + 3
# Make sure it's a complete set of codons
if(($product_length % 3) != 0) {
die "\n\nDIE: A sequence in $product_name is not a multiple of 3 (complete codon set). TERMINATED.\n\n";
}
# Build all codons, put in @aa with @codon_num->@codons
my $num_codons = $product_length / 3;
if((! $last_num_codons) && ($last_num_codons ne '') && ($num_codons != $last_num_codons)) {
die "\n\nDIE: In $product_name, there are sequences of different length ($last_num_codons and $num_codons). TERMINATED.\n\n";
} else {
$last_num_codons = $num_codons;
#print "changed\n";
}
my $codon_index = 0; # so we're going to populate $codonum_codon_aa[0]->@
for(my $i=1; $i<=$num_codons; $i++) { # for each codon
my $array_index = $i - 1;
#my $codon = substr($sequence,$codon_index,3);
# More efficient to call substr at beginning and gobble
my $codon = substr($product_seq,0,3,"");
#print "$codon ";
# Note that some may contain N's
push(@{$codonum_codon_aa[$array_index]},$codon);
#$codon_index+=3;
}
#print "\n";
} # end sequences loop; end STORING codon information
# ANALYZE all codons here; compare all codons to one another; all pairwise comparisons
# We're going one product at a time, so we're within just one product now,
# having all codons stored in @codonum_codon_aa{INDEX IN SEQ}->@ARRAY OF CODONS AT INDEX FOR ALL SEQS
# e.g., SIX (6) BIRDS, 15 comparisons
my $num_seqs = scalar @{$codonum_codon_aa[0]};
my @num_seqs_defined;
#print "\nNum seqs: $num_seqs\n";
my $num_codons_in_product = scalar @codonum_codon_aa;
my @polymorphic_codons_arr; # same indices as codons; value 0 if invariant, 1 if poly
# PARALLELIZE IT
mkdir("$product_name\_polymorphic_codons_arr");
chdir("$product_name\_polymorphic_codons_arr");
my $pm_poly = Parallel::ForkManager->new($procs_per_node);
# QUICKLY CHECK IF IT'S POLYMORPHIC to save time. It's faster just to check,
# EVEN IF not polymorphic
# FOR EACH CODON IN PRODUCT
for(my $codon_index = 0; $codon_index < $num_codons_in_product; $codon_index++) {
$pm_poly->start and next; # this is IT
#print "Codon $codon_index\n";
#my $codon_to_print = $groups_codons_aa[$i]->[$codon_index]->[1];
#$| = 1;
#print "$codon_to_print";
my $between_s_comparisons = 0;
my $this_codon_poly = 0;
my $this_codon_num_seqs_defined = $num_seqs;
OUTER: for (my $si_seq_index = 0; $si_seq_index < $num_seqs; $si_seq_index++) { # for each si sequence at this codon
my $codon_si = $codonum_codon_aa[$codon_index]->[$si_seq_index];
# Codon to compare against
if(! ($codon_si =~ 'N') && ! ($codon_si =~ '-') ) {
INNER: for (my $sj_seq_index = $si_seq_index+1; $sj_seq_index < $num_seqs; $sj_seq_index++) { # for each sj sequence at this codon
#if ($codon_index == 0) { print "pw comparison\n"; }
my $codon_sj = $codonum_codon_aa[$codon_index]->[$sj_seq_index];
#print "Comparing codons $codon_si and $codon_sj\n";
if($codon_si ne $codon_sj && ! ($codon_sj =~ 'N') && ! ($codon_sj =~ '-')) {
$this_codon_poly = 1;
last OUTER; # gotta break of out TWO loops here and go to next codon in product
}
} # INNER
} else {
$this_codon_num_seqs_defined -= 1;
}
} # OUTER
open(THIS_POLY_TEMP_FILE,">>$codon_index");
print THIS_POLY_TEMP_FILE "$this_codon_poly\t$this_codon_num_seqs_defined";
close THIS_POLY_TEMP_FILE;
$pm_poly->finish; # special name
# push(@polymorphic_codons_arr,$this_codon_poly);
# $num_seqs_defined[$codon_index] = $this_codon_num_seqs_defined;
} # done checking if polymorphic
$pm_poly->wait_all_children; # special name, methods within module
my @polymorphic_codons_FILES_arr = glob "*";
@polymorphic_codons_FILES_arr = sort {$a <=> $b} @polymorphic_codons_FILES_arr;
#print "sorted polymorphic_codons_FILE_arr: @polymorphic_codons_FILES_arr\n";
foreach(@polymorphic_codons_FILES_arr) { # file names, actually
my $poly_file = $_;
open(CURR_POLY_FILE, $poly_file) or die "\n## Cannot open $poly_file. TERMINATED.\n\n";
while(<CURR_POLY_FILE>) {
chomp;
my @line_arr = split(/\t/,$_,-1);
push(@polymorphic_codons_arr,$line_arr[0]);
$num_seqs_defined[$poly_file] = $line_arr[1];
}
close CURR_POLY_FILE;
unlink $poly_file;
}
chdir("..");
rmdir("$product_name\_polymorphic_codons_arr");
# Finish parallelism for polymorphism detection
#print "\nDone recording polymorphism in $product_name\nIt is: @polymorphic_codons_arr\n\n";
print "\nAnalyzing polymorphic codons in $product_name\...\n";
# Calculate number of total codons so that we can track % progress?
# INTRO: skip if not poly, just do values for the first codon observed
my $product_N_sites_sum = 0;
my $product_S_sites_sum = 0;
my $product_N_diffs_sum = 0;
my $product_S_diffs_sum = 0;
open(CODON_FILE,">>within\_group\_codon\_results\.txt");
# COMEBACK: make a number of sites subroutine for the whole codon, not just the sites
# OR, instead of calling the subroutine every time, just COUNT the comparisons!
# $hh_comps{CGA}->{CGG}->256 YES!!
# PARALLEL
## mkdir("$product_name\_codon\_analysis");
## chdir("$product_name\_codon\_analysis");
## my $pm_codons = Parallel::ForkManager->new($procs_per_node);
# To do this, must write all output to files during the loop
# after all codons finished, then we must read through and scoop results
# while storing in the appropriate places
### NEW POLYMORPHIC SITE ANALYSIS
my %poly_site_data_hh; # $poly_site_data_hh{codon_index}->{unique_variants}
my %codon_to_results_hh; # for bootstraps
COMPL_DEL: for(my $codon_index = 0; $codon_index < $num_codons_in_product; $codon_index++) { # for each codon in product
## $pm_codons->start and next; # this is IT
my $codon_num = $codon_index+1;
print CODON_FILE "$fasta_file_name\t$product_name\t" . $codon_num . " \t";
if($polymorphic_codons_arr[$codon_index]) { # if codon is polymorphic, value is 1
print CODON_FILE "polymorphic\t";
my %comps_hh;
for (my $si_seq_index = 0; $si_seq_index < $num_seqs; $si_seq_index++) { # for each si sequence at this codon
my $codon_si = $codonum_codon_aa[$codon_index]->[$si_seq_index];
# Sequence (codon) to compare against
if(! ($codon_si =~ 'N') && ! ($codon_si =~ '-')) {
for (my $sj_seq_index = $si_seq_index+1; $sj_seq_index < $num_seqs; $sj_seq_index++) { # for each sj sequence at this codon
my $codon_sj = $codonum_codon_aa[$codon_index]->[$sj_seq_index];
if(! ($codon_sj =~ 'N') && ! ($codon_sj =~ '-')) { # they don't have to be the same; syn still stored here
$comps_hh{$codon_si}->{$codon_sj}+=1;
}
}
}
}
# SUM UP STUFF HERE
my $between_s_comparisons = 0;
my $sum_N_sites = 0;
my $sum_S_sites = 0;
my $sum_N_diffs = 0;
my $sum_S_diffs = 0;
foreach my $codon_si (keys %comps_hh) {
foreach my $codon_sj (keys %{$comps_hh{$codon_si}}) {
if($codon_si =~ /-/ || $codon_sj =~ /-/) { # these will skip all additions
print CODON_FILE "COMPLETE_DELETION\tNA\tNA\tNA\tNA\n";
next COMPL_DEL;
} else {
my $weight = $comps_hh{$codon_si}->{$codon_sj};
### NEW POLYMORPHIC SITE ANALYSIS ADDED
$poly_site_data_hh{$codon_index}->{$codon_si} += $weight;
$poly_site_data_hh{$codon_index}->{$codon_sj} += $weight;
### PARALLEL: NEED TO FIGURE THIS OUT
print CODON_FILE "($codon_si\-$codon_sj)";
## $this_codon_output .= "($codon_si\-$codon_sj)";
# Sites codon gi
my @codon_si_sites_1_arr = &get_number_of_sites($codon_si,1);
my @codon_si_sites_2_arr = &get_number_of_sites($codon_si,2);
my @codon_si_sites_3_arr = &get_number_of_sites($codon_si,3);
my $codon_si_N_sites = ($codon_si_sites_1_arr[0] + $codon_si_sites_2_arr[0] + $codon_si_sites_3_arr[0]);
my $codon_si_S_sites = ($codon_si_sites_1_arr[1] + $codon_si_sites_2_arr[1] + $codon_si_sites_3_arr[1]);
# Site codon gj
my @codon_sj_sites_1_arr = &get_number_of_sites($codon_sj,1);
my @codon_sj_sites_2_arr = &get_number_of_sites($codon_sj,2);
my @codon_sj_sites_3_arr = &get_number_of_sites($codon_sj,3);
my $codon_sj_N_sites = ($codon_sj_sites_1_arr[0] + $codon_sj_sites_2_arr[0] + $codon_sj_sites_3_arr[0]);
my $codon_sj_S_sites = ($codon_sj_sites_1_arr[1] + $codon_sj_sites_2_arr[1] + $codon_sj_sites_3_arr[1]);
#print "\nComparing codons $codon_si and $codon_sj:\n";
my $mean_comp_N_sites = ($codon_si_N_sites + $codon_sj_N_sites) / 2;
my $mean_comp_S_sites = ($codon_si_S_sites + $codon_sj_S_sites) / 2;
$sum_N_sites += $weight * $mean_comp_N_sites;
$sum_S_sites += $weight * $mean_comp_S_sites;
# Differences
my $N_diffs = 0;
my $S_diffs = 0;
if($codon_si ne $codon_sj) {
my @diffs_arr = &return_avg_diffs($codon_si,$codon_sj);
$N_diffs = $diffs_arr[0];
$S_diffs = $diffs_arr[1];
}
$sum_N_diffs += $weight * $N_diffs;
$sum_S_diffs += $weight * $S_diffs;
$between_s_comparisons += $weight;
}
}
}
print CODON_FILE "\t";
## $this_codon_output .= "\t";
#print "\nfor a total of $between_s_comparisons comparisons\n";
my $mean_N_diffs = ($sum_N_diffs / $between_s_comparisons);
my $mean_S_diffs = ($sum_S_diffs / $between_s_comparisons);
my $mean_N_sites = ($sum_N_sites / $between_s_comparisons);
my $mean_S_sites = ($sum_S_sites / $between_s_comparisons);
print CODON_FILE "$mean_N_sites\t$mean_S_sites\t$mean_N_diffs\t$mean_S_diffs\n";
## $this_codon_output .= "$mean_N_sites\t$mean_S_sites\t$mean_N_diffs\t$mean_S_diffs\n";
$product_N_diffs_sum += $mean_N_diffs;
$product_S_diffs_sum += $mean_S_diffs;
$product_N_sites_sum += $mean_N_sites;
$product_S_sites_sum += $mean_S_sites;
#print ".. and it's all done.\n";
# For bootstraps
if($num_bootstraps > 1) {
$codon_to_results_hh{$codon_num}->{N_diffs} = $mean_N_diffs;
$codon_to_results_hh{$codon_num}->{S_diffs} = $mean_S_diffs;
$codon_to_results_hh{$codon_num}->{N_sites} = $mean_N_sites;
$codon_to_results_hh{$codon_num}->{S_sites} = $mean_S_sites;
}
} else { # not polymorphic; just use first codon from the first group because it's conserved
my $conserved_codon = '';
FIND_CONSERVED_CODON: for(my $k = 0; $k < $num_seqs; $k++) { # for each codon in product
my $curr_codon_rep = $codonum_codon_aa[$codon_index]->[$k]; # grab first codon THAT DOESN'T CONTAIN N
if($curr_codon_rep =~ "N" || $curr_codon_rep =~ "-") {
next FIND_CONSERVED_CODON;
} else {
$conserved_codon = $curr_codon_rep;
last FIND_CONSERVED_CODON;
}
}
my @codon_sites_1_arr = &get_number_of_sites($conserved_codon,1);
my @codon_sites_2_arr = &get_number_of_sites($conserved_codon,2);
my @codon_sites_3_arr = &get_number_of_sites($conserved_codon,3);
my $codon_N_sites = ($codon_sites_1_arr[0] + $codon_sites_2_arr[0] + $codon_sites_3_arr[0]);
my $codon_S_sites = ($codon_sites_1_arr[1] + $codon_sites_2_arr[1] + $codon_sites_3_arr[1]);
print CODON_FILE "conserved\t$conserved_codon\t".
"$codon_N_sites\t$codon_S_sites\t0\t0\n";
## $this_codon_output .= "conserved\t$conserved_codon\t".
## "$codon_N_sites\t$codon_S_sites\t0\t0\n";
$product_N_sites_sum += $codon_N_sites;
$product_S_sites_sum += $codon_S_sites;
# For bootstraps
if($num_bootstraps > 1) {
$codon_to_results_hh{$codon_num}->{N_diffs} = 0;
$codon_to_results_hh{$codon_num}->{S_diffs} = 0;
$codon_to_results_hh{$codon_num}->{N_sites} = $codon_N_sites;
$codon_to_results_hh{$codon_num}->{S_sites} = $codon_S_sites;
}
} # end not polymorphic
## open(THIS_CODON_TEMP_FILE,">>$codon_index");
## print THIS_CODON_TEMP_FILE "$this_codon_output";
## close THIS_CODON_TEMP_FILE;
## $pm_codons->finish; # special name
} # end all codons in product
close CODON_FILE;
## # PARALLEL
## $pm_codons->wait_all_children; # special name, methods within module
##
## # Vacuum up output and delete temp files
## my @codon_lines_arr;
## my @codon_analysis_FILES_arr = glob "*";
## @codon_analysis_FILES_arr = sort {$a <=> $b} @codon_analysis_FILES_arr;
##
## #print "sorted polymorphic_codons_FILE_arr: @polymorphic_codons_FILES_arr\n";
##
## foreach(@codon_analysis_FILES_arr) { # file names, actually
## my $codon_file = $_; # this is the INDEX
##
## open(CURR_CODON_FILE, $codon_file) or die "\n## Cannot open $codon_file. TERMINATED.\n\n";
## while(<CURR_CODON_FILE>) {
## chomp;
##
## push(@codon_lines_arr,$_);
##
## my @this_line_arr = split(/\t/,$_,-1);
## #product / group_1 / group_2 / codon / variability / comparisons / N_sites / S_sites / N_diffs / S_diffs
## my $poly = $this_line_arr[4];
##
## # IF POLY
## if($poly eq 'polymorphic') {
## $product_N_sites_sum += $this_line_arr[6];
## $product_S_sites_sum += $this_line_arr[7];
## $product_N_diffs_sum += $this_line_arr[8];
## $product_S_diffs_sum += $this_line_arr[9];
##
## # IF CONSERVED
## } elsif($poly eq 'conserved') {
## $product_N_sites_sum += $this_line_arr[6];
## $product_S_sites_sum += $this_line_arr[7];
##
## #STORE THIS CONSERVED CODON FOR LATER USE IN BOOTSTRAPPING
## $codonIndex_conserved{$codon_file} = $this_line_arr[5]; # COMPARISONS column
## # PROBLEM
## } else {
## die "\nPROBLEM: site neither conserved nor polymorphic!? DIE\n\n";
## }
##
##
##
##
##
## }
## close CURR_CODON_FILE;
## unlink $codon_file;
## }
##
## chdir("..");
## rmdir("$product_name\_codon\_analysis");
## # done sweeping output
##
## # Concatenate and print parallelized codon results to a results file
## open(CODON_FILE,">>between\_group\_codon\_results\.txt");
## foreach(@codon_lines_arr) {
## print CODON_FILE "$_\n";
## }
## close CODON_FILE;
#################
# BOOTSTRAPPING
my $SE_piN_minus_piS = 0;
my $product_boot_Z = 'NA';
my $SE_dN;
my $SE_dS;
if($num_bootstraps > 1) {
# MAKE BOOTSTRAP FILE
open(BOOT_FILE_PRODUCT,">>$product_name\_bootstrap\_results\.txt");
print BOOT_FILE_PRODUCT "file\tproduct_name\tbootstrap_num\tsim_product_N_sites_sum\t".
"sim_product_S_sites_sum\tsim_product_N_diffs_sum\tsim_product_S_diffs_sum\n";
#################
# BOOTSTRAPPING TO CALCULATE STANDARD ERROR HERE?
print "\nBootstrapping for standard error...\n";
#print "num_codons_in_product: $num_codons_in_product\n";
my @sim_N_sites_arr;
my @sim_S_sites_arr;
my @sim_N_diffs_arr;
my @sim_S_diffs_arr;
## # PARALLELIZE IT
## mkdir("$product_name\_bootstrap_temp_files");
## chdir("$product_name\_bootstrap_temp_files");
## #my $procs = 60; # number to do at once, cores to assign simultaneously, machine-limited. CUVIER has 80
## my $pm = Parallel::ForkManager->new($procs_per_node);
for(my $bootstrap_num = 1; $bootstrap_num <= $num_bootstraps; $bootstrap_num++) {
## $pm->start and next; # this is IT
srand();
# New bootstrap run, of $num_bootstraps
#print "bootstrap $bootstrap_num\n";
my $sim_product_N_sites_sum = 0;
my $sim_product_S_sites_sum = 0;
my $sim_product_N_diffs_sum = 0;
my $sim_product_S_diffs_sum = 0;
#my $random_sum = 0;
my %sim_poly_site_data_hh; # $sim_poly_site_data_hh{codon_index}->{unique_variants}
# SO, HERE'S the problem: we shouldn't sample WITHIN SITES, but rather SAMPLE
# THE SITES THEMSELVES!!
# (1) indeed, go through $num_codons_in_product
# (2) for each, selection a random codon position's results: Nd, Sd, Ns, Ss.
# where are the aforementioned stored? We've just added the following to do so:
# $codon_to_results_hh{$codon_num}->{N_diffs}
# $codon_to_results_hh{$codon_num}->{S_diffs}
# $codon_to_results_hh{$codon_num}->{N_sites}
# $codon_to_results_hh{$codon_num}->{S_sites}
# SAMPLE codon sites, up to the actual number of codons
for(my $codon_index = 0; $codon_index < $num_codons_in_product; $codon_index++) {
# Which codon site do we choose?
my $random_codon_num = int(rand($num_codons_in_product + 1));
my $mean_N_diffs = $codon_to_results_hh{$random_codon_num}->{N_diffs};
my $mean_S_diffs = $codon_to_results_hh{$random_codon_num}->{S_diffs};
my $mean_N_sites = $codon_to_results_hh{$random_codon_num}->{N_sites};
my $mean_S_sites = $codon_to_results_hh{$random_codon_num}->{S_sites};
$sim_product_N_diffs_sum += $mean_N_diffs;
$sim_product_S_diffs_sum += $mean_S_diffs;
$sim_product_N_sites_sum += $mean_N_sites;
$sim_product_S_sites_sum += $mean_S_sites;
# print CODON_FILE "$mean_N_sites\t$mean_S_sites\t$mean_N_diffs\t$mean_S_diffs\n";
} # finished compiling all sampled codons (cols in alignment)
# Print product totals for BOOTSTRAP
my $out_line_boot = "$fasta_file_name\t$product_name\t$bootstrap_num\t$sim_product_N_sites_sum\t".
"$sim_product_S_sites_sum\t$sim_product_N_diffs_sum\t$sim_product_S_diffs_sum\n";
print BOOT_FILE_PRODUCT "$out_line_boot";
#print "$out_line_boot";
push(@sim_N_diffs_arr,$sim_product_N_diffs_sum);
push(@sim_S_diffs_arr,$sim_product_S_diffs_sum);
push(@sim_N_sites_arr,$sim_product_N_sites_sum);
push(@sim_S_sites_arr,$sim_product_S_sites_sum);
#print $random_sum . "\n";
} # end last bootstrap
close BOOT_FILE_PRODUCT;
my $actual_piN = '*';
my $actual_piS = '*';
my $actual_piN_minus_piS = '*';
if($product_N_sites_sum > 0) {
$actual_piN = $product_N_diffs_sum / $product_N_sites_sum;
}
if($product_S_sites_sum > 0) {
$actual_piS = $product_S_diffs_sum / $product_S_sites_sum;
}
if($actual_piN >= 0 && $actual_piS >= 0) {
$actual_piN_minus_piS = $actual_piN - $actual_piS;
}
# CALCULATE BOOTSTRAP STANDARD ERROR HERE! NEI & KUMAR (2000) EQUATIONS
my @sim_piN_minus_piS;
my @sim_dN;
my @sim_dS;
for(my $sim_num = 0; $sim_num < scalar(@sim_N_sites_arr); $sim_num++) {
my $this_round_piN = '*';
if($sim_N_sites_arr[$sim_num] > 0) {
$this_round_piN = $sim_N_diffs_arr[$sim_num] / $sim_N_sites_arr[$sim_num];
}
my $this_round_piS = '*';
if($sim_S_sites_arr[$sim_num] > 0) {
$this_round_piS = $sim_S_diffs_arr[$sim_num] / $sim_S_sites_arr[$sim_num];
}
my $this_round_piN_minus_piS = '*';
if($this_round_piN >= 0 && $this_round_piS >= 0) {
$this_round_piN_minus_piS = $this_round_piN - $this_round_piS;
}
push(@sim_piN_minus_piS,$this_round_piN_minus_piS);
push(@sim_dN, $this_round_piN);
push(@sim_dS, $this_round_piS);
}
$SE_piN_minus_piS = &standard_deviation(@sim_piN_minus_piS);
$SE_dN = &standard_deviation(@sim_dN);
$SE_dS = &standard_deviation(@sim_dS);
if($SE_piN_minus_piS > 0) {
$product_boot_Z = $actual_piN_minus_piS / $SE_piN_minus_piS;
}
if($SE_piN_minus_piS == 0) {
$SE_piN_minus_piS = 'NA';
}
# print "\nproduct SE(dN-dS) = $SE_piN_minus_piS\n".
# "product Z-value = $product_boot_Z\n\n";
} # END BOOTSTRAPS
# Print product totals
my $product_piN;
my $product_piS;
my $product_piN_over_piS;
if($product_N_sites_sum > 0) {
$product_piN = $product_N_diffs_sum / $product_N_sites_sum;
} else {
$product_piN = '*';
}
if($product_S_sites_sum > 0) {
$product_piS = $product_S_diffs_sum / $product_S_sites_sum;
} else {
$product_piS = '*';
}
my $product_piN_minus_piS = $product_piN - $product_piS;
if($product_piS > 0) {