-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathsnpgenie.pl
executable file
·15994 lines (14214 loc) · 624 KB
/
snpgenie.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 is a Perl program that calculates dN/dS, piN/piS, and gene diversity
# from NGS SNP Reports generated from pooled DNA samples.
# Copyright (C) 2015, 2016, 2017, 2018, 2019 Chase W. Nelson
#########################################################################################
## 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/>.
#########################################################################################
# DATE CREATED: April 10, 2015
# AUTHOR: Chase W. Nelson
# CONTACT1: cnelson@amnh.org
# CONTACT2: cwnelson88@gmail.com
# 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.
use strict;
#use warnings;
use IO::Handle;
use Data::Dumper;
use File::Temp qw(tempfile);
use Getopt::Long;
use List::Util qw(max sum);
my $time1 = time;
my $local_time1 = localtime;
# Die if no arguments, explaining what they should be
#unless (@ARGV) {
# die "\nThis program accepts arguments:\n[1] Blah;\n[2] Blah2;\n[3] Blah3.\n\n";
#}
# GET THE TIME
# Initialize variables
my $minfreq; # the min. allele freq. to be considered (prop., not percentage)
my $snpreport;
my $vcfformat; ##SAMVCF
my $fastafile;
my $gtffile;
my $slidingwindow;
# Flag variables
my $clc_mode = 0;
my $geneious_mode = 0;
my $vcf_mode = 0;
my $generate_random_fastas = 0;
#my $progress_period_count = 0;
my @snp_report_file_names_arr;
my $the_fasta_file = '';
my @fasta_file_names_arr;
my $fasta_arr_size;
my $cds_file;
my $multi_fasta_mode;
my $help;
my $h;
my $version;
my $v;
# Allow use to define working and/or output directory
my $outdir;
my $workdir;
my $param_file_contents = "SNPGenie parameter log.\n\n";
# Get user input, if given. If a Boolean argument is passed, its value is 1; else undef
GetOptions( "minfreq:f" => \$minfreq, # optional floating point parameter
"snpreport:s" => \$snpreport, # optional string parameter
"vcfformat:i" => \$vcfformat, # optional integer parameter ##SAMVCF
"fastafile:s" => \$fastafile, # optional string parameter
"multi_fasta_mode" => \$multi_fasta_mode, # optional Boolean parameter
"gtffile:s" => \$gtffile, # optional string parameter
"outdir:s" => \$outdir, # optional string parameter
"slidingwindow:i" => \$slidingwindow,
"workdir=s" => \$workdir,
"help" => \$help,
"h" => \$h,
"version" => \$version,
"v" => \$v)
or die "\n### WARNING: Error in command line arguments. SNPGenie terminated.\n\n";
if($help || $h) {
&print_usage_message();
}
if($version || $v) {
print "SNPGenie version 2019.10.31\n";
exit;
}
# N.B.: When an argument, e.g., slidingwindow, is called only as a flag, its value is 0
# When it is not called at all, it is null
# Set or get the working directory
if($workdir) { # $workdir passed as argument
if(-d $workdir) { # $workdir is a real directory
#print "\n### DIRECTORY TO BEGIN ANALYSIS:\n";
chomp($workdir);
#print "WORKING_DIRECTORY=$workdir\n";
} else { # $workdir is NOT a real directory
print "\n### WARNING: DIRECTORY $workdir DOESN'T EXIST. USING WORKING DIRECTORY TO BEGIN ANALYSIS:\n";
$workdir = `pwd`;
chomp($workdir);
#print "WORKING_DIRECTORY=$workdir\n";
}
} else {
#print "\n### BEGIN ANALYSIS IN WORKING DIRECTORY:\n";
$workdir = `pwd`;
chomp($workdir);
#print "WORKING_DIRECTORY=$workdir\n";
}
my $WORK;
if($workdir ne '') {
$WORK = $workdir; # better nomenclature
} else {
die "\n### WARNING: Working directory does not exist or could not be obtained; please " .
"retry using the --workdir option. SNPGenie terminated.\n\n";
}
# ENTER WORKING DIRECTORY
chdir("$WORK"); # in case we're not already there
# Decipher the results directory
my $OUT_DIR;
if($outdir =~ /\w/) { # there's at least one letter
if($outdir =~ /\//) { # it's already a path, so use it as-is
$OUT_DIR = $outdir;
} else { # bare name, not path, so add it to the working directory path
$OUT_DIR = "$WORK\/$outdir";
}
} else { # nothing specified; use default
$OUT_DIR = "$WORK\/SNPGenie_Results";
}
# Create the results directory
if(-d $OUT_DIR) { # $OUT_DIR already exists
die "\n### WARNING: Results directory already exists; " .
"please retry with another --outdir. SNPGenie terminated.\n";
} else {
mkdir("$OUT_DIR");
}
# Make sure creating the directory worked
unless(-d $OUT_DIR) {
my $specific_warning = "### TERMINATED: Problem creating results directory; please retry with another --outdir " .
"using a full path or single name.\n";
&print_usage_message($specific_warning);
}
#print "RESULTS_DIRECTORY=$OUT_DIR\n";
# Set OPTIONS given the user's INPUT, and RECORD PARAMETERS
if(! $minfreq) {
$minfreq = 0;
$param_file_contents .= "MINIMUM ALLELE FREQUENCY: Default used; all SNPs included\n";
} elsif(($minfreq >= 1) || ($minfreq < 0)) {
die "\n## WARNING: The --minfreq option must be a decimal between 0 and 1\n".
"## SNPGenie terminated.\n\n";
} else {
$param_file_contents .= "MINIMUM ALLELE FREQUENCY: $minfreq\n";
}
if($slidingwindow > 0) {
$param_file_contents .= "SLIDING WINDOW LENGTH: $slidingwindow\n";
} else {
$param_file_contents .= "SLIDING WINDOW LENGTH: None\n";
}
if(! $multi_fasta_mode) {
$multi_fasta_mode = 0; # default behavior: no separate codon files for each SNP Report
$param_file_contents .= "MULTI-FASTA MODE: Default used; No\n";
} else {
$multi_fasta_mode = 1;
$param_file_contents .= "MULTI-FASTA MODE: Yes\n";
}
# Get SNP Report name(s)
if(! $snpreport) {
@snp_report_file_names_arr = &get_txt_file_names;
my @snp_report_file_names_ADD_arr = &get_csv_file_names;
my @snp_report_file_names_ADD_VCF_arr = &get_vcf_file_names;
push(@snp_report_file_names_arr,@snp_report_file_names_ADD_arr);
push(@snp_report_file_names_arr,@snp_report_file_names_ADD_VCF_arr);
$param_file_contents .= "SNP REPORTS: Default auto-detected file(s): @snp_report_file_names_arr\n";
} else {
@snp_report_file_names_arr = ($snpreport);
$param_file_contents .= "SNP REPORTS: User submitted file: $snpreport\n";
}
#print "\n@snp_report_file_names_arr\n\n";
if (scalar (@snp_report_file_names_arr) == 0) {
die "\n\n## WARNING: There are no SNP Reports. SNPGenie terminated.\n\n";
} else {
foreach(@snp_report_file_names_arr) {
if($_ =~ /\.vcf/ && ! $vcfformat) {
rmdir("$OUT_DIR");
die "\n\n### WARNING: User must specify the specific SNP report format when using\n".
"### VCF files. Use the --vcfformat option. SNPGENIE TERMINATED.\n\n";
}
}
}
# Identify FASTA file
if(! $fastafile) {
@fasta_file_names_arr = &get_fasta_file_names;
#print "\nWorking directory fasta files are: @fasta_file_names_arr\n\n";
$param_file_contents .= "REFERENCE FASTA FILE: Default auto-detected file(s): @fasta_file_names_arr\n";
} else {
$fasta_file_names_arr[0] = $fastafile;
$param_file_contents .= "REFERENCE FASTA FILE: User submitted file: $fastafile\n";
}
$fasta_arr_size = scalar(@fasta_file_names_arr);
#print "\nThe size of the fasta array is $fasta_arr_size\n";
if($fasta_arr_size > 1) {
if(! $multi_fasta_mode) {
die "\n\n## WARNING: There are multiple FASTA (.fa or .fasta) files in the working directory.\n".
"## There must be only one reference genome in single-FASTA mode. SNPGenie terminated.\n\n";
}
} elsif($fasta_arr_size == 1) {
$the_fasta_file = $fasta_file_names_arr[0];
# Go through FASTA to make sure there's only one sequence
my $seen_seq = 0;
open (INFILE, $the_fasta_file);
while (<INFILE>) {
if (/>/) {
if($seen_seq == 0) {
$seen_seq = 1;
} else {
die "\n\n### WARNING: There are multiple sequences in the FASTA file.\n".
"### There must be only one reference genome. SNPGenie terminated.\n\n";
}
}
}
close INFILE;
} else {
die "\n\n## WARNING: There are no FASTA (.fa or .fasta) files in the working directory. ".
"SNPGenie terminated.\n\n";
}
# Identify GTF file
if(! $gtffile) { # default behavior
$cds_file = &get_cds_file_name;
$param_file_contents .= "GTF FILE: Default auto-detected file: $cds_file\n";
} else {
$cds_file = $gtffile;
$param_file_contents .= "GTF FILE: User submitted file: $cds_file\n";
}
#print "\n@fasta_file_names_arr\n\n";
STDOUT->autoflush(1);
# Initialize files
open(PARAM_FILE,">>$OUT_DIR\/SNPGenie\_parameters\.txt");
print PARAM_FILE "$param_file_contents";
close PARAM_FILE;
### NUCLEOTIDE DIVERSITY FILE
open(OUTFILE_NT_DIV,">>$OUT_DIR\/codon\_results\.txt");
my $ntd_headers_to_print = "file\tproduct\tsite\tcodon\tnum_overlap_ORF_nts\t".
#"mean_coverage\t".
"N_diffs\tS_diffs\t";
$ntd_headers_to_print .= "N_sites\tS_sites\t";
$ntd_headers_to_print .= "N_sites_ref\tS_sites_ref\t";
#$ntd_headers_to_print .= "piN\tpiS\t";
$ntd_headers_to_print .= "N_diffs_vs_ref\tS_diffs_vs_ref\t".
"gdiv\tN_gdiv\tS_gdiv\n";
#$ntd_headers_to_print .= "mean_dN_vs_ref\tmean_dS_vs_ref\n"; # \tAverage_cov
print OUTFILE_NT_DIV "$ntd_headers_to_print";
close OUTFILE_NT_DIV;
### GENE DIVERSITY FILE
open(OUTFILE_GENE_DIV,">>$OUT_DIR\/site\_results\.txt");
print OUTFILE_GENE_DIV "file\tproduct\tsite\tref_nt\tmaj_nt\t".
"position_in_codon\t".
"overlapping_ORFs\tcodon_start_site\tcodon\tpi\t".
#"Polymorphic (Y=1; N=0)\t".
"gdiv\t".
"class_vs_ref\tclass\t".
"coverage\t".
"A\tC\tG\tT\n";
close OUTFILE_GENE_DIV;
### PRODUCT SUMMARY FILE
open(PRODUCT_SUMMARY,">>$OUT_DIR\/product\_results\.txt");
print PRODUCT_SUMMARY "file\tproduct\tN_diffs\tS_diffs\t".
"N_diffs_vs_ref\tS_diffs_vs_ref\t".
"N_sites\tS_sites\t".
"piN\tpiS\tmean_dN_vs_ref\tmean_dS_vs_ref\t".
"mean_gdiv_polymorphic\tmean_N_gdiv\tmean_S_gdiv\n";
close PRODUCT_SUMMARY;
### POPULATION SUMMARY NONCODING RESULTS
open(POP_SUMMARY,">>$OUT_DIR\/population\_summary\.txt");
print POP_SUMMARY "file\tsites\tsites_coding\tsites_noncoding\t".
"pi\tpi_coding\tpi_noncoding\t".
#"mean_nonsyn_diffs\tmean_syn_diffs\t".
#"mean_nonsyn_diffs_vs_ref\tmean_syn_diffs_vs_ref\t".
"N_sites\tS_sites\t".
"piN\tpiS\tmean_dN_vs_ref\tmean_dS_vs_ref\t".
"mean_gdiv_polymorphic\tmean_N_gdiv\tmean_S_gdiv\t".
"mean_gdiv\t".
"sites_polymorphic\t".
"mean_gdiv_coding_poly\t".
"sites_coding_poly\t".
"mean_gdiv_noncoding_poly\t".
"sites_noncoding_poly\n";
close POP_SUMMARY;
### A LOG file
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "file\tproduct\tsite\t".
"LOG\n";
close ERROR_FILE;
# Hash for storing which product we've seen, just for error-reporting purposes
my %seen_product_early_stop_hash;
my %seen_no_start_hash;
my %seen_no_stop_hash;
# Executive error switches
my $exec_errors = 0;
my $warn_5nt = 0;
my $warn_frequencies = 0;
my $warn_file_type_not_supported = 0;
my $seen_sense_strand_products = 0;
my $SNP_report_counter = 0;
print "\n\n################################################################################".
"\n## ##".
"\n## SNPGenie Initiated! ##".
"\n## ##".
"\n################################################################################\n";
# Print LICENSE
print "\n ############################### LICENSE: #################################\n";
print " ## SNPGenie Copyright (C) 2015-19 Chase W. Nelson ##\n".
" ## This program comes with ABSOLUTELY NO WARRANTY; ##\n".
" ## This is free software, and you are welcome to redistribute it ##\n".
" ## under certain conditions; see LICENSE.txt. ##";
print "\n ############################################################################\n";
# REPORT DIRECTORIES
print "\nWORKING_DIRECTORY=$WORK\n";
print "RESULTS_DIRECTORY=$OUT_DIR\n";
# GET THE TIME
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "NA\tNA\tNA\t".
"SNPGenie initiated at local time $local_time1\n";
close ERROR_FILE;
if($minfreq > 0) {
print "\nYour MIN. MINOR ALLELE FREQ. is $minfreq. All variants falling below this frequency will be ignored.\n";
} else {
print "\nYou have not selected a MIN. MINOR ALLELE FREQ. All variants in the SNP report(s) will be included.\n";
}
# We will
# [1] determine whether COMPLEMENT ENTRIES are to be considered, and
# [2] if so, construct some way to DO EVERYTHING BELOW, but do it for the
# rev. complement SNP reports against the rev. complement FASTA with respect to the
# "-" strand records in the GTF file.
# Complement mode?
my $complementmode = &determine_complement_mode($cds_file);
# Announce and initialize REVERSE COMPLEMENT MODE
my %hh_compl_position_info; # REGARDLESS OF SNP REPORT. saved with respect to the + strand
#my @curr_compl_products;
my @curr_compl_products_ordered_by_start;
if($complementmode) {
print "\nThere are antisense ('-') strand records in the GTF file. COMPLEMENT MODE activated...\n";
open(PARAM_FILE,">>$OUT_DIR\/SNPGenie\_parameters\.txt");
print PARAM_FILE "COMPLEMENT MODE: Yes\n";
close PARAM_FILE;
# Look through the GTF file for the - strand entries
# translate the start and stop sites to + strand sites using $fasta_length
#my $rev_complement_seq = &reverse_complement_from_fasta($fasta_to_open);
#my $rev_compl_seq = &reverse_complement_from_fasta($the_fasta_file);
#my $seq_length = length($rev_compl_seq);
open(GTF_FILE_AGAIN, "$cds_file") or die "\nCould not open the GTF file $cds_file - $!\n\n";
while(<GTF_FILE_AGAIN>) { # each record in the GTF file
my $this_product;
# Reverse complement - strand
my $rev_compl_start; # Where the gene itself actually STOPS
my $rev_compl_stop; # Where the gene itself actually STARTS
if($_ =~ /CDS\t(\d+)\t(\d+)\t[\.\d]+\t\-\t\d+\t\s*gene_id\s*\"gene\:([\w\s\.\-\:']+)\"/) { # Line is - strand
$rev_compl_start = $1; # Where the gene itself actually STOPS
$rev_compl_stop = $2; # Where the gene itself actually STARTS
$this_product = $3;
} elsif($_ =~ /CDS\t(\d+)\t(\d+)\t[\.\d]+\t\-\t\d+\t\s*gene_id\s*\"([\w\s\.\-\:']+ [\w\s\.\-\:']+)\"/) {
$rev_compl_start = $1; # Where the gene itself actually STOPS
$rev_compl_stop = $2; # Where the gene itself actually STARTS
$this_product = $3;
} elsif($_ =~ /CDS\t(\d+)\t(\d+)\t[\.\d]+\t\-\t\d+\t\s*gene_id\s*\"([\w\s\.\-\:']+)\"/) {
$rev_compl_start = $1; # Where the gene itself actually STOPS
$rev_compl_stop = $2; # Where the gene itself actually STARTS
$this_product = $3;
# NOW, IN CASE transcript_id comes first
} elsif($_ =~ /CDS\t(\d+)\t(\d+)\t[\.\d]+\t\-\t\d+\ttranscript_id \"[\w\s\.\-\:']+\"\s*;\s*gene_id\s*\"gene\:([\w\s\.\-\:']+)\"/) {
$rev_compl_start = $1; # Where the gene itself actually STOPS
$rev_compl_stop = $2; # Where the gene itself actually STARTS
$this_product = $3;
} elsif($_ =~ /CDS\t(\d+)\t(\d+)\t[\.\d]+\t\-\t\d+\ttranscript_id \"[\w\s\.\-\:']+\"\s*;\s*gene_id\s*\"([\w\s\.\-\:']+ [\w\s\.\-\:']+)\"/) {
$rev_compl_start = $1; # Where the gene itself actually STOPS
$rev_compl_stop = $2; # Where the gene itself actually STARTS
$this_product = $3;
} elsif($_ =~ /CDS\t(\d+)\t(\d+)\t[\.\d]+\t\-\t\d+\ttranscript_id \"[\w\s\.\-\:']+\"\s*;\s*gene_id\s*\"([\w\s\.\-\:']+)\"/) {
$rev_compl_start = $1; # Where the gene itself actually STOPS
$rev_compl_stop = $2; # Where the gene itself actually STARTS
$this_product = $3;
}
# New segments approach for reverse complement - strand
if($rev_compl_start) { # it's a revcom record
#print "\nDo we ever get here 1? Yes, for $this_product\n";
# so we have this record's product name, start, and stop
my $curr_start_key = 'start_1';
my $curr_stop_key = 'stop_1';
my $segment_number = 1;
if(! $hh_compl_position_info{$this_product}->{$curr_start_key}) { # no first segment yet
#print "\nDo we ever get here 2? Yes, for $this_product\n";
if($this_product ne '') {
$hh_compl_position_info{$this_product}->{$curr_start_key} = $rev_compl_start;
$hh_compl_position_info{$this_product}->{$curr_stop_key} = $rev_compl_stop;
}
} else { # already a start_1
while($hh_compl_position_info{$this_product}->{$curr_start_key}) {
#print "\nDo we ever get here 3? Yes, for $this_product\n";
my $curr_segment_number = $segment_number;
$segment_number++;
$curr_start_key =~ s/\_$curr_segment_number/\_$segment_number/;
$curr_stop_key =~ s/\_$curr_segment_number/\_$segment_number/;
}
if($this_product ne '') {
$hh_compl_position_info{$this_product}->{$curr_start_key} = $rev_compl_start;
$hh_compl_position_info{$this_product}->{$curr_stop_key} = $rev_compl_stop;
}
}
# Store (initiate OR update) number of segments
$hh_compl_position_info{$this_product}->{num_segments} = $segment_number;
}
}
close GTF_FILE_AGAIN;
#@curr_compl_products = sort(keys %hh_compl_position_info);
@curr_compl_products_ordered_by_start = sort { $hh_compl_position_info{$a}->{start_1} <=> $hh_compl_position_info{$b}->{start_1} } keys %hh_compl_position_info;
#print "\nproduct\tstart\tstop\n";
#foreach (@curr_compl_products_ordered_by_start) {
# print "$_\t" . $hh_compl_position_info{$_}->{start_1} . "\t" . $hh_compl_position_info{$_}->{stop_1} . "\n";
#}
} else {
#print "\nThere are NO - strand records in the GTF file. COMPLEMENT MODE NOT activated...\n";
open(PARAM_FILE,">>$OUT_DIR\/SNPGenie\_parameters\.txt");
print PARAM_FILE "COMPLEMENT MODE: No\n";
close PARAM_FILE;
}
#foreach my $this_product(keys %hh_compl_position_info) {
# foreach(sort keys $hh_compl_position_info{$this_product}) {
# print "\n product $this_product key position $_\n";
# }
#}
# Streamline attainment of product coordinates
# All products should be in GTF file, so don't need to get them from SNP reports as before
my @product_names_arr = &get_product_names_from_gtf($cds_file);
@product_names_arr = sort {$a <=> $b} @product_names_arr;
# DIE if no sense + strand products seen
if(! $seen_sense_strand_products) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_WARNINGS\.txt");
print ERROR_FILE "$cds_file\tNA\tNA\t".
"Does not contain any sense (+) strand products. SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $cds_file does not contain any sense (+) strand products. SNPGenie terminated.\n\n";
}
# Determine all product coordinates from the start
my %product_coordinates_harr;
foreach my $product_name (@product_names_arr) {
#print "\nproduct name is: $product_name\n";
my @product_coord_arr = &get_product_coordinates($product_name);
#print "\n$product_name product_coord arr: @product_coord_arr\n";
# Save to a hash of arrays
push(@{$product_coordinates_harr{$product_name}->{product_coord_arr}},@product_coord_arr);
#print "\n$product_name product_coord arr in harr: @{$product_coordinates_harr{$product_name}->{product_coord_arr}} \n\n";
}
# Streamline bulding of sequence
# Using the fasta file, record the sequence in a variable
my $seq;
#my @seq_by_index_arr;
if(! $multi_fasta_mode) {
print "\nReading in FASTA file... ";
open (INFILE, $the_fasta_file);
while (<INFILE>) {
unless (/>/) {
chomp;
# CHOMP for 3 operating systems
if($_ =~ /\r\n$/) {
$_ =~ s/\r\n//;
} elsif($_ =~ /\r$/) {
$_ =~ s/\r//;
} elsif($_ =~ /\n$/) {
$_ =~ s/\n//;
}
$seq .= $_;
}
}
close INFILE;
print "COMPLETED.\n";
# In case it's lowercase
#$seq =~ tr/acgt/ACGT/;
$seq = uc($seq);
$seq =~ tr/U/T/;
# # Record in an array by index (old %seq_by_pos_hash)
# print "\nIndexing sequence... ";
#
# for (my $i = 0; $i < length($seq); $i++) {
# $seq_by_index_arr[$i] = substr($seq, $i, 1); # This is $position - 1
# }
# print "COMPLETED.\n";
}
#########################################################################################
# GENERATE TEMP VCF SNP REPORTS IFF FORMAT 4
my @temp_vcf4_file_names;
# If it's VCF file format 4, it's possible that there are multiple samples in the same
# VCF file. Unfortunately, SNPGenie is modular in the sense that I designed it to be run
# on ONE SNP REPORT. Thus, to make a quick fix and avoid rewriting the whole concept,
# we'll just make each sample into its own temporary SNP report.
if($vcfformat == 4) { # generate as many SNP reports as there are sample columns
# Find out if there is more than one sample by counting columns after FORMAT
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT sample1
my $header_line = '';
open (ORIGINAL_SNP_REPORT, $snp_report_file_names_arr[0]); # always just one
while (<ORIGINAL_SNP_REPORT>) {
chomp;
if($_ =~ /^#(\w+)/) {
$header_line = $_;
if(!($_ =~/\t/)) {
die "\n\n## WARNING:\n## The SNP Report $snp_report_file_names_arr[0] is ".
"not TAB-delimited (\\t), or there is only one column.\n\n";
}
last;
}
}
close ORIGINAL_SNP_REPORT;
if($header_line eq '') {
die "\n\n## WARNING:\n## The SNP Report $snp_report_file_names_arr[0] has no header." .
"\n## TERMINATED.\n\n";
}
$header_line =~ s/^#//;
#print "\nHEADER LINE IS: $header_line\n\n";
my @header_arr = split("\t",$header_line,-1);
#print "\nHEADER ARRAY IS: @header_arr\n\n";
# Determine the INDEX of FORMAT
my $FORMAT_index;
for (my $vcf_i = 0; $vcf_i < scalar(@header_arr); $vcf_i++) {
if($header_arr[$vcf_i] eq 'FORMAT') {
$FORMAT_index = $vcf_i;
last;
}
}
# Count the number of samples (i.e., columns after FORMAT)
my $num_samples = 0;
my @sample_names;
for(my $samp_index = $FORMAT_index+1; $samp_index < scalar(@header_arr); $samp_index++) {
if($header_arr[$samp_index] =~ /[\w\d\_\.]+/) {
$num_samples++;
push(@sample_names, $&);
}
}
#print "\n### VCF FORMAT 4 with $num_samples samples.\n\n";
# Generate TEMP VCF SNP reports, ranging from index ($FORMAT_index+1) to ($FORMAT_index+$num_samples)
for(my $sample_index = ($FORMAT_index+1); $sample_index <= ($FORMAT_index+$num_samples); $sample_index++) {
my $new_temp_vcf4_file_name = 'temp_vcf4_' . $header_arr[$sample_index] . '.vcf';
push(@temp_vcf4_file_names, $new_temp_vcf4_file_name);
print "Creating $new_temp_vcf4_file_name\...\n";
if(-f "$new_temp_vcf4_file_name") {
warn "\n\n### WARNING: $new_temp_vcf4_file_name already present. Replacing...\n\n";
unlink $new_temp_vcf4_file_name; # just in case
}
open(THIS_NEW_VCF,">>$new_temp_vcf4_file_name");
# Find out if there is more than one sample by counting columns after FORMAT
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT sample1
my $header_line;
open (ORIGINAL_SNP_REPORT, $snp_report_file_names_arr[0]); # always just one
my $seen_vcf4_header = 0;
while (<ORIGINAL_SNP_REPORT>) {
chomp;
if($_ =~ /^##(\w+)/) { # STILL METADATA; print
print THIS_NEW_VCF "$_\n";
} elsif($_ =~ /^#(\w+)/) { # header
my $this_new_header_line = '#';
for(my $vcf_i = 0; $vcf_i <= $FORMAT_index; $vcf_i++) {
$this_new_header_line .= "$header_arr[$vcf_i]\t";
}
$this_new_header_line .= "$header_arr[$sample_index]";
print THIS_NEW_VCF "$this_new_header_line\n";
$seen_vcf4_header = 1;
} elsif($seen_vcf4_header == 1) {
my @this_line_arr = split(/\t/,$_,-1);
my $this_new_variant_line;
# This will include records with 0 coverage; eliminate later if necessary
for(my $vcf_i = 0; $vcf_i <= $FORMAT_index; $vcf_i++) {
$this_new_variant_line .= "$this_line_arr[$vcf_i]\t";
}
$this_new_variant_line .= "$this_line_arr[$sample_index]";
print THIS_NEW_VCF "$this_new_variant_line\n";
}
}
close ORIGINAL_SNP_REPORT;
close THIS_NEW_VCF;
}
@snp_report_file_names_arr = @temp_vcf4_file_names; # THESE are the SNP REPORTS now
}
#########################################################################################
# WNV pseudogenic code
# FOR METAPOPULATION STORAGE -- provided all sites are with respect to the same reference
#my %master_frequencies_hh; # $master_frequencies_hh -> {site_num} -> {@A_props_arr}/{@C_props_arr}/{@G_props_arr}/{@T_props_arr}
#########################################################################################
# PROCESS THE SNP REPORTS
foreach my $curr_snp_report_name (@snp_report_file_names_arr) {
my $file_nm = $curr_snp_report_name;
#my $curr_newline = &detect_newline_char($curr_snp_report_name);
#$/ = $curr_newline;
my %h_nc_results;
my $seen_percent_warning = 0;
print "\n\n########################### CURRENTLY PROCESSING: ###########################\n".
"$file_nm... ";
#print "\n\n$_\n\n";
if($multi_fasta_mode) {
my $did_we_detect = 0;
my $snp_report_prefix;
if($file_nm =~ /^([\w\.]+?)_/) {
$snp_report_prefix = $1;
}
foreach my $potential_fasta (@fasta_file_names_arr) {
my $potential_fasta_prefix;
if($potential_fasta =~ /^$snp_report_prefix\_/) {
$the_fasta_file = $potential_fasta;
$did_we_detect = 1;
last;
}
}
unless($did_we_detect == 1) {
die "\n\nWe did not detect a FASTA for $file_nm in multi-fasta mode\n\n";
}
print "\nReading in FASTA file $the_fasta_file\... ";
$seq = '';
open (INFILE, $the_fasta_file);
while (<INFILE>) {
unless (/>/) {
chomp;
# CHOMP for 3 operating systems
if($_ =~ /\r\n$/) {
$_ =~ s/\r\n//;
} elsif($_ =~ /\r$/) {
$_ =~ s/\r//;
} elsif($_ =~ /\n$/) {
$_ =~ s/\n//;
}
$seq .= $_;
}
}
close INFILE;
print "COMPLETED.\n";
# In case it's lowercase
#$seq =~ tr/acgt/ACGT/;
$seq = uc($seq);
$seq =~ tr/U/T/;
# # Record in an array by index (old %seq_by_pos_hash)
# print "\nIndexing sequence... ";
#
# # THIS WILL OVERWRITE
# for (my $i = 0; $i < length($seq); $i++) {
# $seq_by_index_arr[$i] = substr($seq,$i,1); # This is $position - 1
# }
# print "COMPLETED.\n";
} # end recording of individual FASTA in multi-FASTA mode
# Generate new file name prefix
my $new_file_prefix;
if($curr_snp_report_name =~/\.txt/) {
$new_file_prefix = $`;
} elsif($curr_snp_report_name =~/\.csv/) {
$new_file_prefix = $`;
} else {
$new_file_prefix = "inFile";
}
#print "\nPrefix for $curr_snp_report_name: $new_file_prefix\n\n";
# At first, created the tempfile before getting its headers; we've reversed the
# order so we can determine the format of the SNP Report (e.g., Geneious or CLC)
# before creating the tempfile. Should not create problems.
my @header_names_arr = &get_header_names($curr_snp_report_name,$curr_snp_report_name);
#print "@header_names_arr";
# CHECK FOR NON-CLC SNP REPORT, and reset the MODE if so
foreach (@header_names_arr) {
if($_ eq 'Minimum' || $_ eq 'Polymorphism Type' || $_ eq 'Change') {
# Switch to GENEIOUS mode
$geneious_mode = 1;
$clc_mode = 0;
$vcf_mode = 0;
#print "\n\nWe are in GENEIOUS MODE!\n\n";
} elsif($_ eq 'Reference Position' || $_ eq 'Overlapping annotations') {
# We remain in CLC mode
$geneious_mode = 0;
$clc_mode = 1;
$vcf_mode = 0;
#print "\n\nWe are in CLC MODE!\n\n";
} elsif($curr_snp_report_name =~ /\.vcf/) {
# Switch to VCF mode
$geneious_mode = 0;
$clc_mode = 0;
$vcf_mode = 1;
}
}
##SAMVCF: changed to simple Boolean
if($geneious_mode && ! $clc_mode && ! $vcf_mode) {
print "GENEIOUS format detected\n";
} elsif(! $geneious_mode && $clc_mode && ! $vcf_mode) {
print "CLC GENOMICS WORKBENCH format detected\n";
} elsif(! $geneious_mode && ! $clc_mode && $vcf_mode) {
print "VCF format detected\n";
} else {
die "\n## WARNING: Conflicting SNP Report formats detected. Does the file extension match expectation? If not, please contact author. ".
"## SNPGenie TERMINATED.\n\n";
}
# Create tempfiles
my $temp_snp_report_TEMPLATE = "temp_snp_report_XXXX";
# Remember, the following automatically OPENS the file, too.
my ($TEMP_SNP_REPORT_HANDLE,$temp_snp_report_name) =
tempfile($temp_snp_report_TEMPLATE, SUFFIX => ".txt", UNLINK => 1);
#print "\n\n\nTEMP FILE: $temp_snp_report_name\n\n\n";
##SAMVCF: changed to simple Boolean
# POPULATE the temporary file based on FORMAT MODE
if($clc_mode) {
&populate_tempfile_clc($curr_snp_report_name, $temp_snp_report_name);
$curr_snp_report_name = $temp_snp_report_name;
} elsif($geneious_mode) {
# (1) snpgenie_prep_geneious;
# (2) snpgnie_geneious_to_clc;
&populate_tempfile_geneious($curr_snp_report_name, $temp_snp_report_name);
$curr_snp_report_name = $temp_snp_report_name;
} elsif($vcf_mode) {
if(! $vcfformat) {
die "\n## WARNING: User must specify VCF format, e.g., --vcfformat=4. ".
"## SNPGenie TERMINATED.\n\n";
}
&populate_tempfile_vcf($curr_snp_report_name, $temp_snp_report_name, $cds_file);
$curr_snp_report_name = $temp_snp_report_name;
}
# Includes the automatic deletion of the tempfile afterwards.
my @new_header_names_arr = &get_header_names($curr_snp_report_name,$file_nm);
@header_names_arr = @new_header_names_arr;
#print "\n\nHEADER:\n@header_names_arr\n\n";
my $index_ref_pos;
my $index_type;
my $index_ref;
my $index_allele;
my $index_count;
my $index_cov;
my $index_freq;
my $index_over_annot;
#my $index_cod_reg_chg;
#my $index_ami_aci_chg;
my $seen_index_ref_pos = 0;
my $seen_index_type = 0;
my $seen_index_ref = 0;
my $seen_index_allele = 0;
my $seen_index_count = 0;
my $seen_index_cov = 0;
my $seen_index_freq = 0;
my $seen_index_over_annot = 0;
#my $seen_index_cod_reg_chg = 0;
#my $seen_index_ami_aci_chg = 0;
#print "\nref_pos: $index_ref_pos length: $index_len ref: $index_ref allele: $index_allele ".
# "count: $index_count cov: $index_cov freq: $index_freq over_annot: $index_over_annot ".
# "cod_reg_chg: $index_cod_reg_chg amino acid chg: $index_ami_aci_chg\n";
#print "\n\n$_\n\n";
# Determine the index of each column -- this is CLC
for (my $i=0; $i<scalar(@header_names_arr); $i++) {
if ($header_names_arr[$i] =~ /Reference Position/) {
$index_ref_pos = $i;
$seen_index_ref_pos = 1;
} elsif ($header_names_arr[$i] =~ /Type/) {
$index_type = $i;
$seen_index_type = 1;
} elsif ($header_names_arr[$i] =~ /Reference/) { # Since this comes AFTER
# "Reference Position, we're fine
$index_ref = $i;
$seen_index_ref = 1;
} elsif ($header_names_arr[$i] =~ /Allele/) {
$index_allele = $i;
$seen_index_allele = 1;
} elsif ($header_names_arr[$i] =~ /Count/) {
$index_count = $i;
$seen_index_count = 1;
} elsif ($header_names_arr[$i] =~ /Coverage/) {
$index_cov = $i;
$seen_index_cov = 1;
} elsif ($header_names_arr[$i] =~ /Frequency/) {
$index_freq = $i;
$seen_index_freq = 1;
} elsif ($header_names_arr[$i] =~ /Overlapping annotations/) {
$index_over_annot = $i;
$seen_index_over_annot = 1;
# } elsif ($header_names_arr[$i] =~ /Coding region change/) {
# $index_cod_reg_chg = $i;
# $seen_index_cod_reg_chg = 1;
# } elsif ($header_names_arr[$i] =~ /Amino acid change/) {
# $index_ami_aci_chg = $i;
# $seen_index_ami_aci_chg = 1;
}
}
if($seen_index_ref_pos == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Reference Position\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Reference Position\". SNPGenie terminated.\n\n";
} elsif($seen_index_type == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Type\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Type\". SNPGenie terminated.\n\n";
} elsif($seen_index_ref == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Reference\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Reference\". SNPGenie terminated.\n\n";
} elsif($seen_index_allele == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Allele\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Allele\". SNPGenie terminated.\n\n";
} elsif($seen_index_count == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Count\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Count\". SNPGenie terminated.\n\n";
} elsif($seen_index_cov == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Coverage\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Coverage\". SNPGenie terminated.\n\n";
} elsif($seen_index_freq == 0) {
open(ERROR_FILE,">>$OUT_DIR\/SNPGenie\_LOG\.txt");
print ERROR_FILE "$file_nm\tNA\tNA\t".
"Does not contain the column header \"Frequency\". SNPGenie terminated.\n";
close ERROR_FILE;
die "\n\n## WARNING: $file_nm does not contain the column header \"Frequency\". SNPGenie terminated.\n\n";