-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpogenom.pl
2098 lines (2019 loc) · 101 KB
/
pogenom.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 -w
=head1 NAME
pogenom.pl - Calculates population genomic parameters from a VCF file
=head1 USAGE (minimum input)
perl pogenom.pl --vcf_file <VCF_FILE> --out <OUTPUT_FILES_PREFIX> --genome_size <GENOME_SIZE>
or:
perl pogenom.pl --vcf_file <VCF_FILE> --out <OUTPUT_FILES_PREFIX> --gff_file <GFF_FILE>
or:
perl pogenom.pl --vcf_file <VCF_FILE> --out <OUTPUT_FILES_PREFIX> --fasta_file <FASTA_FILE>
=head1 REQUIRED ARGUMENTS
--vcf_file <VCF_FILE Specify vcf file with data from a single or multiple samples
--out <OUTPUT_FILES_PREFIX Specify the prefix of the output file name(s) (overwrites existing files with same names)
--genome_size <GENOME_SIZE Specify genome size (in bp; integer). Not required if --gff_file or --fasta_file with genome sequence is given
=head1 OPIONAL ARGUMENTS
--gff_file <GFF_FILE> Specify gff file. Either this, --genome_size or --fasta_file must be given
--fasta_file <FASTA_FILE> Specify fasta file. Either this, --genome_size or --gff_file must be given
--genetic_code_file <GENETIC_CODE_FILE> Specify genetic code file. E.g. standard_genetic_code.txt in the POGENOM distribution
--loci_file <LOCI_FILE> Specify file with ids of loci to be included
--sample_file <SAMPLE_FILE> Specify file with ids of samples to be included
--min_count <MIN_COUNT> Specify minimum coverage for a locus to be included for the sample
--min_found <MIN_FOUND_IN> Specify minimum number of samples that a locus needs to be present in to be included
--subsample <SUBSAMPLE> Specify coverage level at which to subsample
--keep_haplotypes If used, POGENOM will not split haplotypes into single-nucleotide variants, which is otherwise the default
--vcf_format <VCF_FORMAT> Specify VCF file format version. Can be set to freebayes (default) or GATK
--fst_perm <FST_PERM> Specify number of permutations (integer) for making randomised gene-wise Fst. Use with caution, output can be huge
--pi_only If used, POGENOM will only calculate and output genome-wide pi
--split_fasta_header If used, if a fasta file header includes space character(s), POGENOM will only use the part preceeding the first space
--help Prints this help message
[Press q to close this help message]
=cut
use Getopt::Long;
use List::MoreUtils qw(uniq);
$genome_size = undef;
$min_found_in = 1;
$min_count = 2;
$vcf_file = undef;
$gff_file = undef;
$fasta_file = undef;
$genetic_code_file = undef;
$loci_file = undef;
$sample_file = undef;
$outprefix = undef;
$reference = undef;
$keep_haplotypes = undef;
$pi_only = undef;
$split_fasta_header = undef;
$use_pseudocounts = undef;
$subsample = undef;
$vcf_format = "freebayes";
$na_if_missing_loci = 1;
$n_fst_permutations = undef;
&GetOptions('vcf_file=s' => \$vcf_file, 'vcf_format=s' => \$vcf_format, 'gff_file=s' => \$gff_file, 'fasta_file=s' => \$fasta_file, 'genetic_code_file=s' => \$genetic_code_file, 'output=s' => \$outprefix, 'min_count=i' => \$min_count, 'min_found=i' => \$min_found_in, 'ref=s' => \$reference, 'genome_size=i' => \$genome_size, 'keep_haplotypes!' => \$keep_haplotypes, 'loci_file=s' => \$loci_file, 'sample_file=s' => \$sample_file, 'subsample=s' => \$subsample, 'use_pseudocounts' => \$use_pseudocounts, 'fst_perm=i' => \$n_fst_permutations, 'pi_only!' => \$pi_only, 'split_fasta_header!' => \$split_fasta_header, 'h!' => \$help);
if (!$outprefix) {
system ('perldoc', $0);
exit;
}
if ($help) {
system ('perldoc', $0);
exit;
}
if (!$vcf_file) {
system ('perldoc', $0);
exit;
}
if (!$genome_size and !$gff_file and !$fasta_file) {
system ('perldoc', $0);
exit;
}
if ($min_count < 2) {
print"Error: min_count cannot be set to <2\n";
exit;
}
if ($vcf_format ne "freebayes") {
if ($vcf_format ne "GATK") {
print"\nError: Unrecognized vcf_format. Should be either freebayes (default) or GATK\n\n";
exit;
}
}
####################
$logtext = "vcf_file: $vcf_file\n";
if ($gff_file) {
$logtext = $logtext."gff_file: $gff_file\n";
}
if ($fasta_file) {
$logtext = $logtext."fasta_file: $fasta_file\n";
}
if ($genetic_code_file) {
$logtext = $logtext."genetic_code_file: $genetic_code_file\n";
}
print"\n### Running pogenom ###\n";
if ($genome_size) {
$logtext = $logtext."genome_size set to: $genome_size\n";
} elsif ($fasta_file) {
$logtext = $logtext."genome_size calculated from fasta file\n";
} elsif ($gff_file) {
$logtext = $logtext."genome_size calculated from GFF file\n";
}
$logtext = $logtext."min_count set to: $min_count\n";
if ($min_found_in == 0) {
$logtext = $logtext."min_found set to: number of samples\n";
}
if ($min_found_in > 0) {
$logtext = $logtext."min_found set to: $min_found_in\n";
}
if ($subsample) {
$logtext = $logtext."Subsampling set to: $subsample reads per locus\n";
}
if ($pi_only) {
$logtext = $logtext."Running in pi_only mode\n";
}
if ($loci_file) {
$logtext = $logtext."Analysis restricted to loci in file: $loci_file\n";
&read_loci_to_include;
}
if ($sample_file) {
$logtext = $logtext."Analysis restricted to samples in file: $sample_file\n";
&read_samples_to_include;
}
if ($n_fst_permutations) {
$logtext = $logtext."Permuted gene-wise fst calculated with: $n_fst_permutations permutations\n";
}
print"$logtext\n";
print"\n### Read variant data ###\n";
if ($keep_haplotypes) {
&get_snp_data_combined_vcf;
} else {
&get_snp_data_combined_vcf_split_haplotypes;
}
if ($subsample) {
&subsample_allele_counts;
#&subsample_allele_counts_dupl;
}
if ($gff_file) {
print"\n### Reading GFF file ###\n";
&read_gff;
}
if ($fasta_file) {
print"\n### Reading fasta sequence file ###\n";
&read_fasta;
}
if ($genetic_code_file) {
print"\n### Reading Genetic Code file ###\n";
&read_genetic_code;
}
print"\n### Calculating Nucleotide Diversity (pi) ###\n";
&calc_pi;
if (@samples > 1) {
&estimate_genome_coverage;
}
if ($gff_file and !$pi_only) {
print"\n### Calculating Gene-wise Nucleotide Diversity (pi) ###\n";
&calc_per_gene_pi;
if ($genetic_code_file) {
print"\n### Calculating Gene-wise Aminoacid Diversity (aa-pi) ###\n";
&calc_per_gene_aminoacid_pi;
print"\n### Calculating Aminoacid Frequencies ###\n";
&calc_aminoacid_frequencies;
print"\n### Calculating Gene-wise pN/pS ###\n";
&calc_pN_pS; # comment this out to speed up
}
}
if ((@samples > 1) and !$pi_only) {
print"\n### Calculating Fixation Index (FST) ###\n";
&calc_fst;
if ($gff_file) {
print"\n### Calculating Gene-wise Fixation Index (FST) ###\n";
&calc_per_gene_fst;
if ($n_fst_permutations) {
print"\n### Calculating Permuted Gene-wise Fixation Index (FST) ###\n";
&calc_per_gene_fst_permuted;
}
if ($genetic_code_file) {
print"\n### Calculating Gene-wise Aminoacid Fixation Index (aa-FST) ###\n";
&calc_per_gene_aminoacid_fst;
#print"\n### Calculating Gene-wise Neutrality Index (NI) ###\n";
#&calc_NI;
}
}
}
print"\n### Printing results to files ###\n";
&print_output_to_file;
print"\n### Finished pogenom succesfully ###\n\n";
####################
sub read_loci_to_include {
open (INFILE, "$loci_file") || die ("Error: can't open $loci_file");
while (<INFILE>) {
$_ =~ s/\R//g;
$row = $_;
@fields = split(/\t/, $row);
$locus = $fields[0]."|".$fields[1];
$include_locus{$locus} = 1;
}
$temp = keys %include_locus;
$logtext = $logtext."Number of loci specified in file: $temp\n";
}
sub read_samples_to_include {
open (INFILE, "$sample_file") || die ("Error: can't open $sample_file");
while (<INFILE>) {
$_ =~ s/\R//g;
$row = $_;
$include_sample{$row} = 1;
}
$temp = keys %include_sample;
$logtext = $logtext."Number of samples specified in file: $temp\n";
}
sub read_gff {
$fasta_started = 0;
$seq = "";
open (INFILE, "$gff_file") || die ("Error: can't open $gff_file");
print"Reading $gff_file\n";
while (<INFILE>) {
$_ =~ s/\R//g;
$row = $_;
if ($fasta_started == 1) {
if (substr($row, 0, 1) eq ">") {
if ($seq ne "") {
$contig_seq{$contig} = $seq;
}
$contig = $row;
substr($contig, 0, 1) = "";
#die;
$seq = "";
} else {
$seq = $seq.$_;
$contig_seq{$contig} = uc $seq;
}
}
elsif (substr($row, 0, 7) eq "##FASTA") {
$fasta_started = 1;
} else {
next if (substr($row, 0, 1) eq "#");
@fields = split(/\t/, $row);
next if (@fields == 1);
next if ($fields[2] ne "CDS");
$contig = $fields[0];
$start = $fields[3];
$end = $fields[4];
$strand = $fields[6];
$end = $end - 3 if ($strand eq "+"); # to exclude the stop codon
$start = $start + 3 if ($strand eq "-"); # to exclude the stop codon
$annotation = $fields[8];
@subfields = split(/;/, $annotation);
$gene = $subfields[0];
if (defined $gene_start{$gene}) {
print"Error: Non-unique gene identifiers in GFF file. The program will exit without finishing.\n\n"; exit;
}
$gene_start{$gene} = $start;
$gene_end{$gene} = $end;
$gene_strand{$gene} = $strand;
$gene_length{$gene} = $gene_end{$gene} - $gene_start{$gene} + 1;
$gene_contig{$gene} = $contig;
if (!defined $contig_genes{$contig}) {
push(@contigs, $contig);
}
push(@{ $contig_genes{$contig} }, $gene);
for ($pos = $start; $pos < $end; $pos++) {
$locus = $contig."|".$pos;
if (defined $locus_found{$locus}) {
if ($locus_found{$locus} >= $min_found_in) {
$gene_locus{$gene}{$locus} = 1;
}
}
}
}
}
close (INFILE);
if ($fasta_started == 1) {
$temp_genome_size = 0;
foreach $contig (@contigs) {
if (!defined $contig_seq{$contig}) {
print"\nError: Missmatch between contig id ($contig) in upper and lower part of gff file\n\n"; exit;
}
$temp_genome_size = $temp_genome_size + length($contig_seq{$contig});
@genes = @{ $contig_genes{$contig} };
foreach $gene (@genes) {
if ($gene_strand{$gene} eq "+") {
$gene_seq{$gene} = substr($contig_seq{$contig}, ($gene_start{$gene} - 1), $gene_length{$gene});
#$peptide = "";
#for ($j = 0; $j < $gene_length{$gene}; $j=$j+3) {
# $codon = substr($gene_seq{$gene}, $j, 3);
# $peptide = $peptide.$codon_aminoacid{$codon};
#}
#print">$gene\n$gene_seq{$gene}\n";
#print">$gene\n$peptide\n";
}
if ($gene_strand{$gene} eq "-") {
$gene_seq{$gene} = substr($contig_seq{$contig}, ($gene_start{$gene} - 1), $gene_length{$gene});
$gene_seq{$gene} = &make_revcomp($gene_seq{$gene});
#$peptide = "";
#for ($j = 0; $j < $gene_length{$gene}; $j=$j+3) {
# $codon = substr($gene_seq{$gene}, $j, 3);
# $peptide = $peptide.$codon_aminoacid{$codon};
#}
#print">$gene\n$gene_seq{$gene}\n";
#print">$gene\n$peptide\n";
}
}
}
}
if (!$genome_size and !$fasta_file) {
if ($fasta_started == 1) {
$genome_size = $temp_genome_size;
print"Genome size calculated from GFF to $genome_size bp\n";
$logtext = $logtext."Genome size calculated from GFF to $genome_size bp\n";
} else {
print"Error: Genome size could not be calculated from GFF file\n\n"; exit;
}
}
}
sub read_fasta {
%contig_seq = ();
$seq = "";
open (INFILE, "$fasta_file") || die ("Error: can't open $fasta_file");
print"Reading $fasta_file\n";
while (<INFILE>) {
$_ =~ s/\R//g;
$row = $_;
if (substr($row, 0, 1) eq ">") {
if ($seq ne "") {
$contig_seq{$contig} = $seq;
}
$contig = $row;
if ($split_fasta_header) {
@subfields = split(/\s+/, $row);
$contig = $subfields[0];
}
substr($contig, 0, 1) = "";
$seq = "";
} else {
$seq = $seq.$_;
$contig_seq{$contig} = uc $seq;
}
}
if (!$genome_size) {
$genome_size = 0;
foreach $contig (keys %contig_seq) {
$genome_size = $genome_size + length($contig_seq{$contig});
}
}
print"Genome size calculated from fasta file to $genome_size bp\n";
$logtext = $logtext."Genome size calculated from fasta file to $genome_size bp\n";
if (defined $gff_file) {
foreach $contig (@contigs) {
if (!defined $contig_seq{$contig}) {
print"\nError: Missmatch between contig id in gff ($contig) and fasta file\n\n"; exit;
}
@genes = @{ $contig_genes{$contig} };
foreach $gene (@genes) {
if ($gene_strand{$gene} eq "+") {
$gene_seq{$gene} = substr($contig_seq{$contig}, ($gene_start{$gene} - 1), $gene_length{$gene});
}
if ($gene_strand{$gene} eq "-") {
$gene_seq{$gene} = substr($contig_seq{$contig}, ($gene_start{$gene} - 1), $gene_length{$gene});
$gene_seq{$gene} = &make_revcomp($gene_seq{$gene});
}
}
}
}
}
sub read_genetic_code {
open(INFILE, "$genetic_code_file") || die ("Error: can't open $genetic_code_file");
print"Reading $genetic_code_file\n";
while (<INFILE>) {
$_ =~ s/\R//g;
@fields = split(/\t/);
$codon_aminoacid{$fields[0]} = $fields[1];
}
close (INFILE);
}
sub get_snp_data_combined_vcf {
local($ok_sample);
%nt = ('A', 1, 'T', 1, 'C', 1, 'G', 1);
@samples = ();
@samples_plus = ();
open (INFILE, "$vcf_file") || die ("Error: can't open $vcf_file");
print"Reading $vcf_file\n";
while (<INFILE>) {
$_ =~ s/\R//g;
$row = $_;
@fields = split(/\t/, $row);
if (substr($row, 0, 6) eq "#CHROM") {
for ($i = 9; $i < @fields; $i++) {
$sample = $fields[$i];
$samples[$i - 9] = $sample;
$include_sample{$sample} = 1 if (!$sample_file);
$ok_sample++ if (defined $include_sample{$sample});
}
@samples_plus = (@samples, 'All_samples_combined');
$min_found_in = $ok_sample if ($min_found_in == 0);
}
next if (substr($row, 0, 1) eq "#");
#next if (@fields == 1);
$contig = $fields[0];
$pos = $fields[1];
$locus = $contig."|".$pos;
#print"$locus $locus_found{$locus} $min_found_in\n";
if ($loci_file) {
#print"$locus\n";
next if (!defined $include_locus{$locus});
}
@subfields = split(/:/, $fields[8]);
$nformat_fields = @subfields;
if ($vcf_format eq "GATK") {
$count_ix = undef;
for ($i = 0; $i < @subfields; $i++) {
$count_ix = $i if ($subfields[$i] eq "AD");
}
if (!$count_ix) {
print"\nError: Field AD is lacking in the Format column of the VCF file at CHROM: $contig POS: $pos\n\n"; exit;
}
} elsif ($vcf_format eq "freebayes") {
$tot_count_ix = $ref_count_ix = $alt_count_ix = undef;
for ($i = 0; $i < @subfields; $i++) {
#$tot_count_ix = $i if ($subfields[$i] eq "DP");
$ref_count_ix = $i if ($subfields[$i] eq "RO");
$alt_count_ix = $i if ($subfields[$i] eq "AO");
}
if (!$ref_count_ix or !$alt_count_ix) {
print"\nError: Either field RO or AO is lacking in the Format column of the VCF file at CHROM: $contig POS: $pos\n\n"; exit;
}
}
$locus_found{$locus} = 0;
for ($i = 9; $i < @fields; $i++) {
@subfields = split(/:/, $fields[$i]);
$sample = $samples[$i - 9];
next if (!defined $include_sample{$sample});
if (@subfields == $nformat_fields) {
if ($vcf_format eq "GATK") {
@allele_count = split(/,/, $subfields[$count_ix]);
} elsif ($vcf_format eq "freebayes") {
@allele_count = split(/,/, $subfields[$alt_count_ix]);
unshift(@allele_count, $subfields[$ref_count_ix]);
}
if ($allele_count[0] ne ".") {
$tot_count = 0;
for ($j = 0; $j < @allele_count; $j++) {
$tot_count = $tot_count + $allele_count[$j];
}
if ($tot_count >= $min_count) {
$locus_found{$locus}++;
#print"$locus_found{$locus}\n";
$sample_foundlocus{$sample}{$locus} = 1; # this is for estimating genome coverage
}
}
}
}
next if ($locus_found{$locus} < $min_found_in);
$contig_pos{$contig}{$pos} = 1;
$ref = $fields[3];
@alleles = split(/,/, $fields[4]);
unshift(@alleles, $ref);
$sample_locus_totcount{'All_samples_combined'}{$locus} = 0;
for ($i = 9; $i < @fields; $i++) {
$sample = $samples[$i - 9];
next if (!defined $include_sample{$sample});
@subfields = split(/:/, $fields[$i]);
next if (@subfields != $nformat_fields);
if ($vcf_format eq "GATK") {
@allele_count = split(/,/, $subfields[$count_ix]);
} elsif ($vcf_format eq "freebayes") {
@allele_count = split(/,/, $subfields[$alt_count_ix]);
unshift(@allele_count, $subfields[$ref_count_ix])
}
$tot_count = 0;
if ($allele_count[0] ne ".") {
for ($j = 0; $j < @allele_count; $j++) {
$tot_count = $tot_count + $allele_count[$j];
}
}
next if ($allele_count[0] eq ".");
next if ($tot_count < $min_count);
$sample_locus_ref{$sample}{$locus} = $ref;
$sample_locus_totcount{$sample}{$locus} = $tot_count;
$sample_locus_totcount{'All_samples_combined'}{$locus} = $sample_locus_totcount{'All_samples_combined'}{$locus} + $tot_count;
#print"Ref: #$ref# $ref_count\n";
for ($j = 0; $j < @alleles; $j++) {
$sample_locus_allel_counts{$sample}{$locus}{$alleles[$j]} = $allele_count[$j];
$sample_locus_allel_counts{'All_samples_combined'}{$locus}{$alleles[$j]} = 0 if (!defined $sample_locus_allel_counts{'All_samples_combined'}{$locus}{$alleles[$j]});
$sample_locus_allel_counts{'All_samples_combined'}{$locus}{$alleles[$j]} = $sample_locus_allel_counts{'All_samples_combined'}{$locus}{$alleles[$j]} + $allele_count[$j];
}
}
foreach $string (@alleles) {
$contig_pos{$contig}{$pos} = 0 if (!defined $nt{$string});
}
}
foreach $locus (keys %locus_found) {
$found[$locus_found{$locus}]++;
}
$i = (@found - 1);
$cumulative_found = $found[$i];
print"Number of loci found $i times: $cumulative_found\n";
for ($i = (@found - 2); $i > 0; $i--) {
$cumulative_found = $cumulative_found + $found[$i];
print"Number of loci found >= $i times: $cumulative_found\n";
}
if ((keys %sample_locus_allel_counts) == 0) {
print"Zero loci found fulfilling criteria\n";
print"No files will be generated\n";
exit;
}
# removing unwanted samples from @samples
local(@include);
for ($i = 0; $i < @samples; $i++) {
push(@include, $i) if (defined $include_sample{$samples[$i]});
}
@samples = @samples[@include];
@samples_plus = (@samples, 'All_samples_combined');
}
sub get_snp_data_combined_vcf_split_haplotypes {
local($ok_sample);
%nt = ('A', 1, 'T', 1, 'C', 1, 'G', 1);
@samples = ();
@samples_plus = ();
open (INFILE, "$vcf_file") || die ("Error: can't open $vcf_file");
print"Reading $vcf_file\n";
print"Haplotypes will be split into individual bases\n";
while (<INFILE>) {
$_ =~ s/\R//g;
$row = $_;
@fields = split(/\t/, $row);
if (substr($row, 0, 6) eq "#CHROM") {
for ($i = 9; $i < @fields; $i++) {
$sample = $fields[$i];
$samples[$i - 9] = $sample;
$include_sample{$sample} = 1 if (!$sample_file);
$ok_sample++ if (defined $include_sample{$sample});
}
@samples_plus = (@samples, 'All_samples_combined');
$min_found_in = $ok_sample if ($min_found_in == 0);
}
next if (substr($row, 0, 1) eq "#");
$contig = $fields[0];
$pos = $fields[1];
$ref = $fields[3];
@alleles = split(/,/, $fields[4]);
unshift(@alleles, $ref);
$indel = undef;
for ($i = 1; $i < @alleles; $i++) {
if (length($alleles[$i]) != length($ref)) {
$indel = 1;
}
}
next if $indel;
#print"Ref: $ref Alt: @alt\n";
@subfields = split(/:/, $fields[8]);
$nformat_fields = @subfields;
if ($vcf_format eq "GATK") {
$count_ix = undef;
for ($i = 0; $j < @subfields; $i++) {
$count_ix = $i if ($subfields[$i] eq "AD");
}
if (!$count_ix) {
print"\nError: Field AD is lacking in the Format column of the VCF file at CHROM: $contig POS: $pos\n\n"; exit;
}
} elsif ($vcf_format eq "freebayes") {
$tot_count_ix = $ref_count_ix = $alt_count_ix = undef;
for ($i = 0; $i < @subfields; $i++) {
#$tot_count_ix = $i if ($subfields[$i] eq "DP");
$ref_count_ix = $i if ($subfields[$i] eq "RO");
$alt_count_ix = $i if ($subfields[$i] eq "AO");
}
if (!$ref_count_ix or !$alt_count_ix) {
print"\nError: Either field RO or AO is lacking in the Format column of the VCF file at CHROM: $contig POS: $pos\n\n"; exit;
}
}
for ($i = 0; $i < length($ref); $i++) {
$modpos = $pos + $i;
$locus = $contig."|".$modpos;
if ($loci_file) {
next if (!defined $include_locus{$locus});
}
$variant = 0;
for ($j = 0; $j < @alleles; $j++) {
#print"$i $j $alleles[$j] $ref\n";
if (substr($alleles[$j], $i, 1) ne substr($ref, $i, 1)) {
$variant = 1;
}
}
#print"variant: $variant\n\n";
next if ($variant == 0); # for excluding invariant loci (common within haplotypes)
$locus_found{$locus} = 0;
for ($j = 9; $j < @fields; $j++) {
$sample = $samples[$j - 9];
next if (!defined $include_sample{$sample});
@subfields = split(/:/, $fields[$j]);
if (@subfields == $nformat_fields) {
if ($vcf_format eq "GATK") {
@allele_count = split(/,/, $subfields[$count_ix]);
} elsif ($vcf_format eq "freebayes") {
@allele_count = split(/,/, $subfields[$alt_count_ix]);
unshift(@allele_count, $subfields[$ref_count_ix]);
}
if ($allele_count[0] ne ".") {
$tot_count = 0;
for ($k = 0; $k < @allele_count; $k++) {
$tot_count = $tot_count + $allele_count[$k];
}
if ($tot_count >= $min_count) {
$locus_found{$locus}++;
$sample_foundlocus{$sample}{$locus} = 1; # this is for estimating genome coverage
}
}
}
}
next if ($locus_found{$locus} < $min_found_in);
$contig_pos{$contig}{$modpos} = 1;
$subref = substr($ref, $i, 1);
$contig_pos{$contig}{$modpos} = 0 if (!defined $nt{$subref});
$sample_locus_totcount{'All_samples_combined'}{$locus} = 0;
for ($j = 9; $j < @fields; $j++) {
$sample = $samples[$j - 9];
@subfields = split(/:/, $fields[$j]);
next if (@subfields != $nformat_fields);
if ($vcf_format eq "GATK") {
@allele_count = split(/,/, $subfields[$count_ix]);
} elsif ($vcf_format eq "freebayes") {
@allele_count = split(/,/, $subfields[$alt_count_ix]);
unshift(@allele_count, $subfields[$ref_count_ix])
}
$tot_count = 0;
if ($allele_count[0] ne ".") {
for ($k = 0; $k < @allele_count; $k++) {
$tot_count = $tot_count + $allele_count[$k];
}
}
next if ($allele_count[0] eq ".");
next if ($tot_count < $min_count);
$sample_locus_ref{$sample}{$locus} = $subref;
$sample_locus_totcount{$sample}{$locus} = $tot_count;
$sample_locus_totcount{'All_samples_combined'}{$locus} = $sample_locus_totcount{'All_samples_combined'}{$locus} + $tot_count;
#print" Sample: $sample Subpos: $i Modpos: $modpos\n";
#print" Subref: $subref $ref_count\n";
for ($k = 0; $k < @alleles; $k++) {
$subal = substr($alleles[$k], $i, 1);
if (defined $sample_locus_allel_counts{$sample}{$locus}{$subal}) {
$sample_locus_allel_counts{$sample}{$locus}{$subal} = $sample_locus_allel_counts{$sample}{$locus}{$subal} + $allele_count[$k];
} else {
$sample_locus_allel_counts{$sample}{$locus}{$subal} = $allele_count[$k];
}
$sample_locus_allel_counts{'All_samples_combined'}{$locus}{$subal} = 0 if (!defined $sample_locus_allel_counts{'All_samples_combined'}{$locus}{$subal});
$sample_locus_allel_counts{'All_samples_combined'}{$locus}{$subal} = $sample_locus_allel_counts{'All_samples_combined'}{$locus}{$subal} + $allele_count[$k];
$contig_pos{$contig}{$modpos} = 0 if (!defined $nt{$subal});
#print" Subal: $subal $allele_count[$k] $sample_locus_allel_counts{$sample}{$locus}{$subal}\n";
}
}
}
}
foreach $locus (keys %locus_found) {
$found[$locus_found{$locus}]++;
}
$i = (@found - 1);
$cumulative_found = $found[$i];
print"Number of loci found $i times: $cumulative_found\n";
for ($i = (@found - 2); $i > 0; $i--) {
$cumulative_found = $cumulative_found + $found[$i] if (defined $found[$i]);
print"Number of loci found >= $i times: $cumulative_found\n";
}
if ((keys %sample_locus_allel_counts) == 0) {
print"Zero loci found fulfilling criteria\n";
print"No files will be generated\n";
exit;
}
# removing unwanted samples from @samples
local(@include);
for ($i = 0; $i < @samples; $i++) {
push(@include, $i) if (defined $include_sample{$samples[$i]});
}
@samples = @samples[@include];
@samples_plus = (@samples, 'All_samples_combined');
}
sub subsample_allele_counts {
foreach $sample (@samples_plus) {
foreach $locus (keys %{$sample_locus_allel_counts{$sample}}) {
if ($sample_locus_totcount{$sample}{$locus} > $subsample) {
@alleles = (keys %{$sample_locus_allel_counts{$sample}{$locus}});
@temp = ();
foreach $allele (@alleles) {
$count = $sample_locus_allel_counts{$sample}{$locus}{$allele};
for ($i = 0; $i < $count; $i++) {
push(@temp, $allele);
}
$sample_locus_allel_counts{$sample}{$locus}{$allele} = 0;
}
for ($i = 0; $i < $subsample; $i++) {
$ix = int(rand(@temp));
$sample_locus_allel_counts{$sample}{$locus}{$temp[$ix]}++;
}
$sample_locus_totcount{$sample}{$locus} = $subsample;
}
}
}
}
sub subsample_allele_counts_dupl {
foreach $sample (@samples_plus) {
$sample_dupl = $sample."_duplicate";
push(@samples_plus_dupl, $sample);
push(@samples_plus_dupl, $sample_dupl);
foreach $locus (keys %{$sample_locus_allel_counts{$sample}}) {
if ($sample_locus_totcount{$sample}{$locus} > $subsample) {
@alleles = (keys %{$sample_locus_allel_counts{$sample}{$locus}});
@temp = ();
foreach $allele (@alleles) {
$count = $sample_locus_allel_counts{$sample}{$locus}{$allele};
for ($i = 0; $i < $count; $i++) {
push(@temp, $allele);
}
$sample_locus_allel_counts{$sample}{$locus}{$allele} = 0;
$sample_locus_allel_counts{$sample_dupl}{$locus}{$allele} = 0;
}
for ($i = 0; $i < $subsample; $i++) {
$ix = int(rand(@temp));
$sample_locus_allel_counts{$sample}{$locus}{$temp[$ix]}++;
}
for ($i = 0; $i < $subsample; $i++) {
$ix = int(rand(@temp));
$sample_locus_allel_counts{$sample_dupl}{$locus}{$temp[$ix]}++;
}
$sample_locus_totcount{$sample}{$locus} = $subsample;
$sample_locus_totcount{$sample_dupl}{$locus} = $subsample;
}
}
}
@samples = @samples_plus = @samples_plus_dupl;
}
sub estimate_genome_coverage {
foreach $sample (@samples) {
@loci = (keys %{$sample_locus_allel_counts{$sample}});
if (@loci == 0) {
return; # since estimating genome coverage does not work if any of the samples has 0 loci
}
}
local($shared);
$est_num_loci = 0;
foreach $sample (@samples) {
$sample_estcov{$sample} = 0;
foreach $sample2 (@samples) {
next if ($sample2 eq $sample);
$shared = 0;
foreach $locus (keys %{$sample_foundlocus{$sample2}}) {
if (defined ($sample_foundlocus{$sample}{$locus})) {
$shared++;
}
}
$sample_estcov{$sample} = $sample_estcov{$sample} + $shared/(keys %{$sample_foundlocus{$sample2}});
#local($temp) = $shared/(keys %{$sample_foundlocus{$sample2}});
#print " $sample $temp\n";
}
$sample_estcov{$sample} = $sample_estcov{$sample}/(@samples - 1); # this is the estimated proportion of the genome with coverage fulfilling the -min_count criteria
$est_num_loci = $est_num_loci + (keys %{$sample_foundlocus{$sample}})/$sample_estcov{$sample};
#local($temp) = (keys %{$sample_foundlocus{$sample}})/$sample_estcov{$sample};
#print "##$sample $num_loci{$sample} $sample_estcov{$sample} $temp\n";
}
$est_num_loci = $est_num_loci/@samples; # this is the estimated total number of loci with variation for the pool of samples, after splitting up haplotypes
}
sub estimate_genome_coverage_old {
local($shared);
foreach $sample (@samples) {
$sample_estcov{$sample} = 0;
foreach $sample2 (@samples) {
next if ($sample2 eq $sample);
$shared = 0;
foreach $locus (keys %{$sample_locus_totcount{$sample2}}) {
if (defined ($sample_locus_totcount{$sample}{$locus})) {
$shared++;
}
}
$sample_estcov{$sample} = $sample_estcov{$sample} + $shared/(keys %{$sample_locus_totcount{$sample2}});
#local($temp) = $shared/(keys %{$sample_locus_totcount{$sample2}});
#print " $sample $temp\n";
}
$sample_estcov{$sample} = $sample_estcov{$sample}/(@samples - 1);
#print "#$sample $sample_estcov{$sample}\n\n";
}
}
sub calc_pi {
print "Sample\tpi\tTotal_num_loci\tTotal_num_alleles\tAverage_depth\n";
foreach $sample (@samples_plus) {
$intra_pi = 0;
$tot_alleles = 0;
$av_count = 0;
@loci = (keys %{$sample_locus_allel_counts{$sample}});
foreach $locus (@loci) {
$tot_count = $sample_locus_totcount{$sample}{$locus};
#print"Locus totcount $locus $tot_count\n";
@alleles = (keys %{$sample_locus_allel_counts{$sample}{$locus}});
#print"Alleles: @alleles\n";
$av_count = $av_count + $tot_count;
$locus_intra_pi = 0;
for ($i = 0; $i < @alleles; $i++) {
#print"Allele 1: $alleles[$i]\n";
$counts_1 = $sample_locus_allel_counts{$sample}{$locus}{$alleles[$i]};
#print"Counts1: $counts_1\n";
$tot_alleles++ if ($counts_1 > 0);
for ($j = 0; $j < @alleles; $j++) {
next if ($alleles[$i] eq $alleles[$j]);
#print"Allele 2: $alleles[$j]\n";
$counts_2 = $sample_locus_allel_counts{$sample}{$locus}{$alleles[$j]};
#print"Counts2: $counts_2\n";
$locus_intra_pi = $locus_intra_pi + ($counts_1/$tot_count)*($counts_2/($tot_count - 1)); # According to Schloising
#$locus_intra_pi = $locus_intra_pi + ($counts_1/$tot_count)*($counts_2/($tot_count)); # According to our initial version
}
}
#print"$locus $locus_intra_pi\n\n";
$sample_locus_pi{$sample}{$locus} = $locus_intra_pi;
$intra_pi = $intra_pi + $locus_intra_pi;
}
if (@loci > 0) {
$intra_pi = $intra_pi/$genome_size;
$av_count = $av_count/@loci;
} else {
$av_count = "NA";
$intra_pi = "NA";
$tot_alleles = "NA";
}
$sample_pi{$sample} = $intra_pi;
$sample_avcount{$sample} = $av_count;
$sample_totalleles{$sample} = $tot_alleles;
$num_loci{$sample} = @loci;
print "$sample\t$intra_pi\t$num_loci{$sample}\t$tot_alleles\t$av_count\n";
}
}
sub calc_per_gene_pi {
foreach $contig (@contigs) {
#print "$contig\n";
@genes = @{ $contig_genes{$contig} };
#print "@genes\n"; die;
foreach $gene (@genes) {
foreach $sample (@samples_plus) {
$intra_pi = 0;
$missing_loci = 0;
foreach $locus (keys %{$gene_locus{$gene}}) {
#print "$locus/n";
$missing_loci = 1 if (!defined $sample_locus_pi{$sample}{$locus});
next if (!defined $sample_locus_pi{$sample}{$locus});
$intra_pi = $intra_pi + $sample_locus_pi{$sample}{$locus};
}
$intra_pi = $intra_pi/$gene_length{$gene};
$sample_gene_pi{$sample}{$gene} = $intra_pi;
if ($na_if_missing_loci == 1 && $missing_loci > 0) {
$sample_gene_pi{$sample}{$gene} = "NA";
}
}
}
}
}
sub calc_per_gene_aminoacid_pi {
foreach $sample (@samples_plus) {
$tot_peptides = 0;
foreach $contig (@contigs) {
@genes = @{ $contig_genes{$contig} };
foreach $gene (@genes) {
$intra_pi = 0;
$missing_loci = 0;
#print"\n$gene\n";
foreach $locus (keys %{$gene_locus{$gene}}) {
$missing_loci = 1 if (!defined $sample_locus_pi{$sample}{$locus});
next if (!defined $sample_locus_pi{$sample}{$locus});
@fields = split(/\|/, $locus);
$contig = $fields[0];
$pos = $fields[1];
$tot_count = $sample_locus_totcount{$sample}{$locus};
@alleles = (keys %{$sample_locus_allel_counts{$sample}{$locus}});
#print"Alleles: @alleles\n";
for ($i = 0; $i < @alleles; $i++) {
$mod_contig_seq = $contig_seq{$contig};
substr($mod_contig_seq, ($pos-1), length($alleles[$i])) = $alleles[$i];
$mod_gene_seq = substr($mod_contig_seq, ($gene_start{$gene} - 1), $gene_length{$gene}); # OBS!!!
$mod_gene_seq = &make_revcomp($mod_gene_seq) if ($gene_strand{$gene} eq "-");
$peptide = "";
for ($j = 0; $j < $gene_length{$gene}; $j=$j+3) {
$codon = substr($mod_gene_seq, $j, 3);
$peptide = $peptide.$codon_aminoacid{$codon};
}
if (defined $sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}{$peptide}) {
$sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}{$peptide} = $sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}{$peptide} + $sample_locus_allel_counts{$sample}{$locus}{$alleles[$i]};
} else {
$sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}{$peptide} = $sample_locus_allel_counts{$sample}{$locus}{$alleles[$i]};
}
}
$locus_intra_pi = 0;
@peptides = (keys %{$sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}});
for ($i = 0; $i < @peptides; $i++) {
#print"\nPeptide 1: $peptides[$i]\n";
$counts_1 = $sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}{$peptides[$i]};
#print"Counts1: $counts_1\n";
$tot_peptides++ if ($counts_1 > 0);
for ($j = 0; $j < @peptides; $j++) {
next if ($peptides[$i] eq $peptides[$j]);
#print"Peptide 2: $peptides[$j]\n";
$counts_2 = $sample_locus_gene_peptide_counts{$sample}{$locus}{$gene}{$peptides[$j]};
#print"Counts2: $counts_2\n";
$locus_intra_pi = $locus_intra_pi + ($counts_1/$tot_count)*($counts_2/($tot_count - 1)); # According to Schloising
#$locus_intra_pi = $locus_intra_pi + ($counts_1/$tot_count)*($counts_2/($tot_count)); # According to our initial version
}
}
#print"Sample: $sample $locus locus_intra_pi: $locus_intra_pi\n";
$sample_locus_aminoacid_pi{$sample}{$locus} = $locus_intra_pi;
$intra_pi = $intra_pi + $locus_intra_pi;
#print"Sample: $sample $locus intra_pi: $intra_pi\n\n";
}
$intra_pi = $intra_pi/$gene_length{$gene};
$sample_gene_aminoacid_pi{$sample}{$gene} = $intra_pi;
#$sample_totpeptides{$sample} = $tot_peptides;
#print"Sample: $sample $locus intra_pi: $intra_pi\n\n";
if ($na_if_missing_loci == 1 && $missing_loci == 1) {
$sample_gene_aminoacid_pi{$sample}{$gene} = "NA";
}
}
}
}
}
sub calc_aminoacid_frequencies {
# calculate mean count (avrunda till närmaste heltal?) för varje aa, baserat på alla locus som överlappar en codon/aminosyra-position.
# först ta reda på vilka loci som överlappar varje position.
# skippa loci som har alleler av varierande längd (kan bli frameshifts)
foreach $contig (@contigs) {
@genes = @{ $contig_genes{$contig} };
foreach $gene (@genes) {
#next if ($gene ne "ID=PROKKA_MOD_00014");
#print"$gene\n";
$contig_seq = $contig_seq{$contig};
if ($gene_strand{$gene} eq "+") {
$gene_seq = substr($contig_seq, ($gene_start{$gene} - 1), $gene_length{$gene});
#print"$gene_seq\n";
@loci = (keys %{$gene_locus{$gene}});
next if (@loci == 0);
%codonposition_n_locus = ();
#print"loci @loci\n";
foreach $locus (@loci) {
next if ($sample_locus_totcount{'All_samples_combined'}{$locus} == 0);
@alleles = (keys %{$sample_locus_allel_counts{'All_samples_combined'}{$locus}});
@fields = split(/\|/, $locus);
#print"fields1 @fields\n";
$pos = $fields[1];
%lengths = ();
for ($k = 0; $k < @alleles; $k++) {
$length = length($alleles[$k]);
$lengths{$length} = 1;
}
next if ((keys %lengths) > 1); # skip loci that have alleles that differ in length
$gene_pos = $pos - $gene_start{$gene}; # 0 equals first nucleotide of first (i.e. start) codon