forked from chollenbeck/rad_haplotyper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrad_haplotyper.pl
executable file
·1762 lines (1402 loc) · 50.1 KB
/
rad_haplotyper.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
use strict;
use Vcf;
use Data::Dumper;
use Getopt::Long;
use Pod::Usage;
use Bio::Cigar;
use List::MoreUtils qw/uniq firstidx/;
use List::Util qw/shuffle/;
use Term::ProgressBar;
use Parallel::ForkManager;
my $version = '1.1.5';
my $command = 'rad_haplotyper ' . join(" ", @ARGV);
pod2usage(-verbose => 1) if @ARGV == 0;
my $opt_version = '';
my $vcffile = '';
my $tsvfile = '';
my $outfile = '';
my $genepop = '';
my $vcfout = '';
my $imafile = '';
my $parent1 = '';
my $parent2 = '';
my $loc_cutoff = '';
my $reference = '';
my $debug = '';
my $depth = 20;
my $indels = '';
my $only_paired = '';
my $complex = 'skip';
my $threads = '';
my $miss_cutoff = 0.9;
my $popmap = '';
my $hap_num_filt = 100;
my @samp_subset;
my $max_paralog_inds = 1000000;
my $max_low_cov_inds = 1000000;
my $hap_rescue = 0.05;
GetOptions( 'version' => \$opt_version,
'vcffile|v=s' => \$vcffile,
'tsvfile|t=s' => \$tsvfile,
'genepop|g=s' => \$genepop,
'vcfout|o=s' => \$vcfout,
'ima|a=s' => \$imafile,
'cutoff|u=s' => \$loc_cutoff,
'reference|r=s' => \$reference,
'samples|s{1,}=s' => \@samp_subset,
'parent1|p1=s' => \$parent1,
'parent2|p2=s' => \$parent2,
'depth|d=s' => \$depth,
'keep_single_indels|n' => \$indels,
'use_only_paired' => \$only_paired,
'complex|c' => \$complex,
'miss_cutoff|m=s' => \$miss_cutoff,
'threads|x=s' => \$threads,
'debug|e' => \$debug,
'popmap|p=s' => \$popmap,
'hap_count|h=s' => \$hap_num_filt,
'max_paralog_inds|mp=s' => \$max_paralog_inds,
'max_low_cov_inds|ml=s' => \$max_low_cov_inds,
'hap_rescue|z=s' => \$hap_rescue
);
#open(DUMP, ">", 'debug.out') or die $!;
if ($opt_version) {
die "Version ", $version, "\n";
}
# Open extra log files for debugging
if ($debug) {
open(ALLELES, ">", 'allele_dump.out');
open(HAPS, ">", 'haplo_dump.out');
open(SNPS, ">", 'snp_dump.out');
open(FAIL, ">", 'fail.log');
open(LOG, ">", 'hap_log.out') unless $threads;
}
# Some warnings for common input errors
if ($genepop && ! $popmap) {
warn "\nGenepop output requires a population map to be specified\n";
pod2usage(-verbose => 1) if @ARGV == 0;
}
if ($tsvfile && (! $parent1 || ! $parent2)) {
warn "\nTSV output requires parents to be specified\n";
pod2usage(-verbose => 1) if @ARGV == 0;
}
if ($imafile && ! $reference) {
warn "\nIMa output requires a reference FASTA sequence\n";
pod2usage(-verbose => 1) if @ARGV == 0;
}
my %stats;
$stats{'filtered_loci_missing'} = 0;
$stats{'filtered_loci_paralog'} = 0;
$stats{'filtered_loci_low_cov'} = 0;
$stats{'filtered_loci_hapcount'} = 0;
$stats{'attempted_loci'} = 0;
$stats{'attempted_snps'} = 0;
$stats{'attempted_indels'} = 0;
my %status;
# Count the total number of SNPs and RAD-tags for reporting purposes
my $total_snps = `grep -cv '#' $vcffile`;
my $total_loci = `grep -v '#' $vcffile | cut -f 1 | sort | uniq | wc -l`;
my @all_loci = `grep -v '#' $vcffile | cut -f 1 | sort | uniq`;
chomp($total_snps);
chomp($total_loci);
foreach (@all_loci) {
chomp;
}
$stats{'total_snps'} = $total_snps;
$stats{'total_loci'} = $total_loci;
# If specified, will remove from consideration loci with more SNPs than a given threshold
if ($loc_cutoff) {
open (VCF, "<", $vcffile) or die $!;
open (VCFTEMP, ">", 'temp.vcf') or die $!;
my @lines;
my $last_id = '';
my $loc_removed = 0;
my $snps_removed = 0;
while (<VCF>) {
if ($_ =~ /^#/) {
print VCFTEMP $_;
next;
}
my @bits = split;
if ($bits[0] ne $last_id && $last_id) {
if ((scalar(@lines) <= $loc_cutoff) && @lines) {
foreach my $line (@lines) {
print VCFTEMP $line;
}
} else {
$loc_removed++;
$snps_removed += scalar(@lines);
$status{$last_id} = 'Filtered - Over SNP cutoff';
}
@lines = ();
push @lines, $_;
} else {
push @lines, $_;
}
$last_id = $bits[0];
}
if (scalar(@lines) <= $loc_cutoff) {
foreach my $line (@lines) {
print VCFTEMP $line;
}
} else {
$loc_removed++;
$snps_removed += scalar(@lines);
$status{$last_id} = 'Filtered - Over SNP cutoff';
}
$stats{'loci_removed_over_thresh'} = $loc_removed;
$stats{'snps_removed_over_thresh'} = $snps_removed;
print "Removed $loc_removed loci ($snps_removed SNPs) with more than $loc_cutoff SNPs at a locus\n";
close VCF;
close VCFTEMP;
$vcffile = 'temp.vcf';
}
# Read in the vcf file and get some information
my $vcf = Vcf->new(file => $vcffile);
$vcf->parse_header();
my (@samples) = $vcf->get_samples();
# Parse through the VCF file, recording genotypes
my %snps;
my %alleles;
my $prev_id = '';
my %loc_codes;
my %prev_loc_snps;
my %prev_loc_alleles;
my @complex_loci;
my %complex;
while (my $x = $vcf->next_data_array()) {
my $id = $$x[0];
my $site_num = $$x[1];
my $ref = $$x[3];
my $alt = $$x[4];
# Skip if either the reference or alternative bases are an 'N'
if ($ref eq 'N' || $alt eq 'N') {
next;
}
# Flag the site as a complex polymorphism
if (length($ref) > 1 || length($alt) > 1) {
$complex{$id} = 1; # So that the parser will evaluate the locus as containing complex loci
$loc_codes{$id}{$site_num} = 'complex';
} else {
$loc_codes{$id}{$site_num} = 'snp';
}
# Get the SNP genotypes
my @genotypes;
for (my $i = 0; $i < scalar(@samples); $i++) {
my ($geno, @indiv_codes) = split(':', $$x[9 + $i]);
$geno =~ s/[\/\|]//;
push @genotypes, $geno;
}
if ($prev_id eq '') { # First locus
$prev_loc_snps{$site_num} = \@genotypes;
my @alleles = ($ref, split(',', $alt));
$prev_loc_alleles{$site_num} = \@alleles;
} elsif ($id ne $prev_id) { # New locus
# Evaluate the previous locus
if (defined $complex{$prev_id}) { # The previous locus had complex polymorphisms
# If there is only one polymorphic site at the locus
if (scalar(keys %prev_loc_snps) == 1) {
if ($indels) {
$snps{$prev_id} = {%prev_loc_snps};
$alleles{$prev_id} = {%prev_loc_alleles};
$stats{'attempted_indels'}++;
$stats{'attempted_loci'}++;
} else {
$stats{'loci_removed_complex'}++;
$status{$prev_id} = 'Filtered - Complex polymorphism';
push @complex_loci, $prev_id;
}
} else { # There is more than one polymorphic site
if ($complex eq 'skip') {
# Remove the complex sites and keep the others
my %new_prev_loc_snps;
my %new_prev_loc_alleles;
foreach my $site (keys %prev_loc_snps) {
if (! $loc_codes{$prev_id}{$site}) {
print join("\t", $prev_id, $site), "\n";
print Dumper($loc_codes{$prev_id});
print Dumper(\%prev_loc_snps);
#print Dumper(\%snps);
die;
}
if ($loc_codes{$prev_id}{$site} eq 'complex') {
next;
} else {
$new_prev_loc_snps{$site} = $prev_loc_snps{$site};
$new_prev_loc_alleles{$site} = $prev_loc_alleles{$site};
}
}
if (scalar(keys %new_prev_loc_snps) == 0) { # All of the sites are complex
$stats{'loci_removed_complex'}++;
$status{$prev_id} = 'Filtered - Complex polymorphism';
push @complex_loci, $prev_id;
} else { # There are sites that are not complex
$snps{$prev_id} = {%new_prev_loc_snps};
$alleles{$prev_id} = {%new_prev_loc_alleles};
$stats{'attempted_snps'} += scalar(keys %prev_loc_snps);
$stats{'attempted_loci'}++;
}
} elsif ($complex eq 'remove') {
$stats{'loci_removed_complex'}++;
$status{$prev_id} = 'Filtered - Complex polymorphism';
push @complex_loci, $prev_id;
}
}
} else { # The previous locus did not have complex polymorphisms
# Add it to the SNPs hash
#print "Here!: $prev_id\n";
$snps{$prev_id} = {%prev_loc_snps};
$alleles{$prev_id} = {%prev_loc_alleles};
$stats{'attempted_snps'} += scalar(keys %prev_loc_snps);
$stats{'attempted_loci'}++;
}
# Clear the data structures for the new locus
undef %prev_loc_snps;
undef %prev_loc_alleles;
# Add the info for the first SNP at the new locus
$prev_loc_snps{$site_num} = \@genotypes;
my @alleles = ($ref, split(',', $alt));
$prev_loc_alleles{$site_num} = \@alleles;
#print Dumper(\%snps);
#print Dumper(\%prev_loc_snps);
} else { # Same locus, new SNP
$prev_loc_snps{$site_num} = \@genotypes;
my @alleles = ($ref, split(',', $alt));
$prev_loc_alleles{$site_num} = \@alleles;
}
#$alleles{$id}{$$x[1]} =~ s/,//;
$prev_id = $id;
if (eof) {
# Evaluate the final locus
if (defined $complex{$prev_id}) { # The previous locus had complex polymorphisms
# If there is only one polymorphic site at the locus
if (scalar(keys %prev_loc_snps) == 1) {
if ($indels) {
$snps{$prev_id} = {%prev_loc_snps};
$alleles{$prev_id} = {%prev_loc_alleles};
$stats{'attempted_indels'}++;
$stats{'attempted_loci'}++;
} else {
$stats{'loci_removed_complex'}++;
$status{$prev_id} = 'Filtered - Complex polymorphism';
push @complex_loci, $prev_id;
}
} else { # There is more than one polymorphic site
if ($complex eq 'skip') {
# Remove the complex sites and keep the others
my %new_prev_loc_snps;
my %new_prev_loc_alleles;
foreach my $site (keys %prev_loc_snps) {
if (! $loc_codes{$prev_id}{$site}) {
print join("\t", $prev_id, $site), "\n";
print Dumper($loc_codes{$prev_id});
print Dumper(\%prev_loc_snps);
#print Dumper(\%snps);
die;
}
if ($loc_codes{$prev_id}{$site} eq 'complex') {
next;
} else {
$new_prev_loc_snps{$site} = $prev_loc_snps{$site};
$new_prev_loc_alleles{$site} = $prev_loc_alleles{$site};
}
}
if (scalar(keys %new_prev_loc_snps) == 0) { # All of the sites are complex
$stats{'loci_removed_complex'}++;
$status{$prev_id} = 'Filtered - Complex polymorphism';
push @complex_loci, $prev_id;
} else { # There are sites that are not complex
$snps{$prev_id} = {%new_prev_loc_snps};
$alleles{$prev_id} = {%new_prev_loc_alleles};
$stats{'attempted_snps'} += scalar(keys %prev_loc_snps);
$stats{'attempted_loci'}++;
}
} elsif ($complex eq 'remove') {
$stats{'loci_removed_complex'}++;
$status{$prev_id} = 'Filtered - Complex polymorphism';
push @complex_loci, $prev_id;
}
}
} else { # The previous locus did not have complex polymorphisms
# Add it to the SNPs hash
#print "Here!: $prev_id\n";
$snps{$prev_id} = {%prev_loc_snps};
$alleles{$prev_id} = {%prev_loc_alleles};
$stats{'attempted_snps'} += scalar(keys %prev_loc_snps);
$stats{'attempted_loci'}++;
#print Dumper(\%snps);
}
}
}
$vcf->close;
# Clear up some potentially large variables
undef %complex;
undef %loc_codes;
print ALLELES Dumper(\%alleles) if $debug;
print SNPS Dumper(\%snps) if $debug;
# Index the individuals before taking the subset to keep track of their positions in the data structures
my %indiv_index;
my $ind_counter = 0;
foreach my $ind (@samples) {
$indiv_index{$ind} = $ind_counter;
$ind_counter++;
}
# Take a subset of samples, if specified at the command line
if (@samp_subset) {
@samples = @samp_subset;
}
my %failed;
my %haplotypes;
my $pm = Parallel::ForkManager->new($threads) if $threads;
foreach my $ind (@samples) {
if ($threads) {
$pm->start and next;
open(TEMP, ">", "$ind.haps");
open(IFAIL, ">", "$ind.fail.log");
if ($debug) {
open(LOG, ">", "$ind.haps.log");
}
}
my $indiv_no = $indiv_index{$ind};
print LOG "---------$ind----------\n" if $debug;
print "Building haplotypes for $ind\n";
my $progress = Term::ProgressBar->new(scalar(keys %snps)) unless $threads;
my $snps_processed = 0;
my %fail_codes;
foreach my $locus (keys %snps) {
my @haplotypes;
if (scalar(keys %{$snps{$locus}}) == 1) { # There is only one SNP at this locus - build haplotypes out of the genotype
my @position = keys %{$snps{$locus}};
my @genotype = split('', $snps{$locus}{$position[0]}[$indiv_no]);
if ($genotype[0] eq '.') { # missing data
$fail_codes{$locus} = 3; # fail code for missing genotype
$snps_processed++;
$progress->update($snps_processed) unless $threads;
# Update the missing data log if the genotype is missing
print IFAIL join("\t", $locus, $fail_codes{$locus}), "\n" if $threads;
next;
}
my @haps;
foreach my $bin_base (@genotype) {
my $base = $alleles{$locus}{$position[0]}[$bin_base];
push @haps, $base;
}
my @uniq_haps = uniq(@haps);
$haplotypes{$locus}{$ind} = \@uniq_haps;
print LOG $locus, ": Single SNP, Looks good\n" if $debug;
# Update the progress bar
$snps_processed++;
$progress->update($snps_processed) unless $threads;
print TEMP join("\t", $locus, @uniq_haps), "\n" if $threads;
next;
} else { # There is more than one SNP at the locus
my $miss_bool = 0;
my @positions = keys %{$snps{$locus}};
foreach my $snp (@positions) {
my @genotype = split('', $snps{$locus}{$snp}[$indiv_no]);
$miss_bool = 1 if $genotype[0] eq '.'; # missing data
}
if ($miss_bool == 1) {
$fail_codes{$locus} = 3; # fail code for missing genotype
$snps_processed++;
$progress->update($snps_processed) unless $threads;
# Update the missing data log if the genotype is missing
print IFAIL join("\t", $locus, $fail_codes{$locus}), "\n" if $threads;
next;
}
}
my ($hap_ref, $failed) = build_haps($locus, $ind, $reference, \%snps, \%alleles, \%indiv_index, $depth, $hap_rescue);
@haplotypes = @{$hap_ref};
if ($failed) {
print LOG "Failed, trying to recover...\n" if $debug;
my ($hap_ref, $failed2) = build_haps($locus, $ind, $reference, \%snps, \%alleles, \%indiv_index, 100, $hap_rescue);
if ($failed2) {
print LOG "Failed again...\n" if $debug;
$fail_codes{$locus} = $failed2;
} else {
print LOG "Fixed... huzzah!\n" if $debug;
@haplotypes = @{$hap_ref};
$haplotypes{$locus}{$ind} = \@haplotypes;
}
} else {
$haplotypes{$locus}{$ind} = \@haplotypes;
}
# Print to a temporary file if processing in parallel
if ($threads) {
print TEMP join("\t", $locus, @haplotypes), "\n" unless $fail_codes{$locus};
print IFAIL join("\t", $locus, $fail_codes{$locus}), "\n" if $fail_codes{$locus};
}
# Update the progress bar
$snps_processed++;
$progress->update($snps_processed) unless $threads;
}
close TEMP if $threads;
close LOG if $threads;
close IFAIL if $threads;
#$failed{$ind} = \@failed_loci;
my $success_loci = $stats{'attempted_loci'} - scalar(keys %fail_codes);
if (! $threads) {
# Add the list of failed loci for each individual to the '%failed' hash
foreach my $locus (keys %fail_codes) {
$failed{$locus}{$ind} = $fail_codes{$locus};
}
print "Successfully haplotyped loci: ", $success_loci, "\n";
print "Failed loci: ", scalar(keys %fail_codes), "\n";
print "Collapsed $stats{'attempted_snps'} SNPs into ", $success_loci, ' haplotypes', "\n";
}
$pm->finish if $threads;
}
$pm->wait_all_children if $threads;
# Combine information into common data structures and clean up individual files, if run in parallel
if ($threads) {
if ($debug) {
open(LOGOUT, ">", 'hap_log.out') or die $!;
}
my %comb_haps;
foreach my $ind (@samples) {
# Read the individual haplotype logs into a common data structure (%comb_haps)
open(TEMPIN, "<", "$ind.haps") or die $!;
while(<TEMPIN>) {
my ($locus, @haps) = split;
$comb_haps{$locus}{$ind} = \@haps;
}
close TEMPIN;
unlink "$ind.haps";
# Read the individual fail logs into the %failed hash
open(FAILIN, "<", "$ind.fail.log") or die $!;
while(<FAILIN>) {
chomp;
my ($locus, $code) = split;
$failed{$locus}{$ind} = $code;
}
close FAILIN;
unlink "$ind.fail.log";
if ($debug) {
# Print the individual log files to a single file
open(LOGIN, "<", "$ind.haps.log") or die $!;
while(<LOGIN>) {
print LOGOUT $_;
}
close LOGIN;
unlink "$ind.haps.log";
}
}
%haplotypes = %comb_haps;
}
# Print some log files if running in debug mode
if ($debug) {
# Print the haplotypes observed for each individual
print HAPS Dumper(\%haplotypes);
# Print a file with all failed individuals
foreach my $locus (keys %failed) {
foreach my $ind (keys %{$failed{$locus}}) {
print FAIL join("\t", $locus, $ind, $failed{$locus}{$ind}), "\n";
}
}
}
# Filter loci with too much missing data or an excess of haplotypes
my ($filt_hap_ref, $snp_hap_count_ref, $miss_ref) = filter_haplotypes(\%haplotypes, \@samples, $miss_cutoff, $max_paralog_inds, $max_low_cov_inds, \@all_loci, \%failed);
%haplotypes = %{$filt_hap_ref};
my %snp_hap_count = %{$snp_hap_count_ref};
my %missing = %{$miss_ref};
print 'Filtered ', $stats{'filtered_loci_missing'}, ' loci below missing data cutoff', "\n";
print 'Filtered ', $stats{'filtered_loci_paralog'}, ' possible paralogs', "\n";
print 'Filtered ', $stats{'filtered_loci_low_cov'}, ' loci with low coverage or genotyping errors', "\n";
print 'Filtered ', $stats{'filtered_loci_hapcount'}, ' loci with an excess of haplotypes', "\n";
if ($vcfout) {
write_vcf(\%haplotypes, \%failed);
}
# Write output files if specified on the command line
if ($tsvfile) {
print "Writing tsv file: $tsvfile\n";
write_tsv($parent1, $parent2, \@samples, \%haplotypes);
}
if ($genepop) {
print "Writing Genepop file: $genepop\n";
# Code haplotypes as numbers for genepop output
my %haplo_map = recode_haplotypes(\%haplotypes);
write_genepop(\%haplotypes, \%haplo_map, $genepop, $popmap);
open(LOCI, '>', 'hap_loci.txt') or die $!;
foreach my $locus (keys %haplotypes) {
my @positions = sort {$a <=> $b} keys %{$snps{$locus}};
foreach my $pos (@positions) {
print LOCI join("\t", $locus, $pos), "\n";
}
}
close LOCI;
if ($debug) {
open(RECODE, ">", 'haplo_recode.log');
print RECODE Dumper(\%haplo_map);
close RECODE;
}
}
if ($imafile) {
print "Writing IMa file: $imafile\n";
write_ima(\%haplotypes, \%snps, $reference, \@samples, $imafile, $popmap);
}
# Print out some stats files for the run
open(STATS, ">", 'stats.out') or die $!;
print STATS $command, "\n";
#print STATS Dumper(\%status);
print STATS join("\t", 'Locus', 'Sites', 'Haplotypes', 'Inds_Haplotyped', 'Total_Inds', 'Prop_Haplotyped', 'Status', 'Poss_Paralog', 'Low_Cov/Geno_Err', 'Miss_Geno', 'Comment'), "\n";
my %ind_stats;
foreach my $locus (@all_loci) {
my $poss_paralog = 0;
my $low_cov = 0;
my $miss_geno = 0;
my $comment = '';
if ($failed{$locus}) {
my %count;
foreach my $ind (keys %{$failed{$locus}}) {
$count{$failed{$locus}{$ind}}++;
$ind_stats{$ind}{$failed{$locus}{$ind}}++;
$ind_stats{$ind}{'Total_Failed'}++;
}
foreach my $code (keys %count) {
if ($code == 1) {
$poss_paralog = $count{$code};
} elsif ($code == 2) {
$low_cov = $count{$code};
} elsif ($code == 3) {
$miss_geno = $count{$code};
}
}
}
if ($status{$locus} eq 'PASSED') {
print STATS join("\t", $locus, $snp_hap_count{$locus}[0], $snp_hap_count{$locus}[1], $missing{$locus}[0], $missing{$locus}[1], sprintf("%.3f", $missing{$locus}[2]), 'PASSED', $poss_paralog, $low_cov, $miss_geno, $comment), "\n";
}
if ($status{$locus} =~ 'missing') {
# Figure out the most likely cause of failure by counting the fail codes for each individual
# my %count;
# foreach my $ind (keys %{$failed{$locus}}) {
# $count{$failed{$locus}{$ind}}++;
# }
# my $max = 0;
# my $most_prob;
# my $reason;
# foreach my $code (keys %count) {
# $most_prob = $count{$code} if $count{$code} > $max;
# }
# if ($most_prob == 1) {
# $reason = 'Possible paralog';
# } elsif ($most_prob == 2) {
# $reason = 'Low coverage or miscalled SNPs';
# } else {
# $reason = '-';
# }
print STATS join("\t", $locus, $snp_hap_count{$locus}[0], $snp_hap_count{$locus}[1], $missing{$locus}[0], $missing{$locus}[1], sprintf("%.3f", $missing{$locus}[2]), 'FILTERED', $poss_paralog, $low_cov, $miss_geno, 'Missing data'), "\n";
}
if ($status{$locus} =~ /complex/i) {
print STATS join("\t", $locus, '-', '-', '-', '-', '-', 'FILTERED', $poss_paralog, $low_cov, $miss_geno, 'Complex'), "\n";
}
if ($status{$locus} =~ /Over SNP cutoff/i) {
print STATS join("\t", $locus, '-', '-', '-', '-', '-', 'FILTERED', $poss_paralog, $low_cov, $miss_geno, 'Excess SNPs'), "\n";
}
if ($status{$locus} =~ /Too many haplotypes/i) {
print STATS join("\t", $locus, $snp_hap_count{$locus}[0], $snp_hap_count{$locus}[1], $missing{$locus}[0], $missing{$locus}[1], sprintf("%.3f", $missing{$locus}[2]), 'FILTERED', $poss_paralog, $low_cov, $miss_geno, 'Excess haplotypes'), "\n";
}
if ($status{$locus} =~ /paralog/i) {
print STATS join("\t", $locus, $snp_hap_count{$locus}[0], $snp_hap_count{$locus}[1], $missing{$locus}[0], $missing{$locus}[1], sprintf("%.3f", $missing{$locus}[2]), 'FILTERED', $poss_paralog, $low_cov, $miss_geno, 'Possible paralog'), "\n";
}
if ($status{$locus} =~ /low coverage/i) {
print STATS join("\t", $locus, $snp_hap_count{$locus}[0], $snp_hap_count{$locus}[1], $missing{$locus}[0], $missing{$locus}[1], sprintf("%.3f", $missing{$locus}[2]), 'FILTERED', $poss_paralog, $low_cov, $miss_geno, 'Low Coverage/Genotyping Errors'), "\n";
}
#print STATS join("\t", $locus, $snps, scalar(@uniq_haps)), "\n";
}
open(INDOUT, ">", 'ind_stats.out') or die $!;
print INDOUT join("\t", 'Ind', 'Poss_Paralogs', 'Low_Coverage/Errors', 'Miss_Genotype', 'Total_Failed', 'Total_Loci', 'Prop_Success'), "\n";
foreach my $ind (@samples) {
for (my $i = 1; $i <= 3; $i++) {
$ind_stats{$ind}{$i} = 0 unless $ind_stats{$ind}{$i};
}
$ind_stats{$ind}{'Total_Failed'} = 0 unless $ind_stats{$ind}{'Total_Failed'};
print INDOUT join("\t", $ind, $ind_stats{$ind}{1}, $ind_stats{$ind}{2}, $ind_stats{$ind}{3}, $ind_stats{$ind}{'Total_Failed'}, scalar(@all_loci), 1 - ($ind_stats{$ind}{'Total_Failed'}) / scalar(@all_loci)), "\n";
}
#print join("\t", $stats{'total_loci'}, "($stats{'attempted_loci'})"), "\n";
#print join("\t", $stats{'total_snps'}, "($stats{'attempted_snps'})"), "\n";
# print $stats{'total_snps'}, "\n";
# print $stats{'snps_removed_over_thresh'}, "\n";
# print $stats{'loci_removed_complex'}, "\n";
# print $stats{'attempted_snps'}, "\n";
# print $stats{'attempted_loci'}, "\n";
##### Subroutines #####
sub write_phased_vcf { # Not currently supported
my %haplotypes = %{$_[0]};
my %failed = %{$_[1]};
open(IN, "<", $vcffile) or die $!;
open(OUT, ">", $vcfout) or die $!;
my $site_no = 0;
my $prev_locus;
while(<IN>) {
if ($_ =~ /^#/) {
print OUT $_;
next;
}
my @fields = split;
if ($fields[0] eq $prev_locus) {
$site_no++;
} else {
$site_no = 0;
}
my @new_geno_strings;
for (my $i = 0; $i < scalar(@samples); $i++) {
my ($geno, @other_fields) = split(':', $fields[9 + $i]);
my $new_geno_string;
my $matches = grep(/\b$fields[0]\b/, @{$failed{$samples[$i]}});
if ($matches > 0) {
$new_geno_string = $fields[9 + $i];
#print join(' ', @{$failed{$samples[$i]}}), "\n";
push @new_geno_strings, $new_geno_string;
next;
}
my $hap1 = $haplotypes{$fields[0]}{$samples[$i]}[0];
my $hap2;
if (! $haplotypes{$fields[0]}{$samples[$i]}[1]) {
$hap2 = $hap1;
} else {
$hap2 = $haplotypes{$fields[0]}{$samples[$i]}[1];
}
my $bin_allele_1;
my $bin_allele_2;
if (substr($hap1, $site_no, 1) eq $fields[3]) {
$bin_allele_1 = 0;
} elsif (substr($hap1, $site_no, 1) eq $fields[4]) {
$bin_allele_1 = 1;
} elsif ($fields[4] =~ /,/) {
my @alt_alleles = split(',', $fields[4]);
for (my $j = 1; $j < scalar(@alt_alleles); $j++) {
if (substr($hap1, $site_no, 1) eq $alt_alleles[$j]) {
$bin_allele_1 = $j;
last;
}
}
}
if (substr($hap2, $site_no, 1) eq $fields[3]) {
$bin_allele_2 = 0;
} elsif (substr($hap2, $site_no, 1) eq $fields[4]) {
$bin_allele_2 = 1;
} elsif ($fields[4] =~ /,/) {
my @alt_alleles = split(',', $fields[4]);
for (my $j = 1; $j < scalar(@alt_alleles); $j++) {
if (substr($hap2, $site_no, 1) eq $alt_alleles[$j]) {
$bin_allele_2 = $j;
last;
}
}
}
my $phased_geno = $bin_allele_1 . '|' . $bin_allele_2;
$new_geno_string = join(':', $phased_geno, @other_fields);
push @new_geno_strings, $new_geno_string;
}
print OUT join("\t", @fields[0 .. 8], @new_geno_strings), "\n";
$prev_locus = $fields[0];
}
}
sub write_vcf {
my %haplotypes = %{$_[0]};
my %failed = %{$_[1]};
open(IN, "<", $vcffile) or die $!;
open(OUT, ">", $vcfout) or die $!;
while(<IN>) {
if ($_ =~ /^#/) {
print OUT $_;
next;
}
#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT
my ($locus, $pos, $id, $ref, $alt, $qual, $filter, $info, $format, @genos) = split;
next unless $haplotypes{$locus};
my @new_geno_strings;
for (my $i = 0; $i < scalar(@samples); $i++) {
my ($geno, @other_fields) = split(':', $genos[$i]);
if ($haplotypes{$locus}{$samples[$i]}) {
push @new_geno_strings, join(':', $geno, @other_fields);
} else { # Missing data
push @new_geno_strings, join(':', './.', @other_fields);
}
}
print OUT join("\t", $locus, $pos, $id, $ref, $alt, $qual, $filter, $info, $format, @new_geno_strings), "\n";
}
}
sub write_genepop {
my %haplotypes = %{$_[0]};
my %haplo_map = %{$_[1]};
my $genepop = $_[2];
my $popmap = $_[3];
open(POP, "<", $popmap) or die $!;
my %pops;
while(<POP>) {
next if $_ =~ /^\s/;
chomp;
my ($sample, $pop) = split;
$pops{$pop} = [] unless $pops{$pop};
push @{$pops{$pop}}, $sample;
}
close POP;
open(GEN, ">", $genepop) or die $!;
my @loci = keys %haplotypes;
print GEN $genepop, "\n";
print GEN join("\n", @loci), "\n";
foreach my $pop (sort keys %pops) {
print GEN 'POP', "\n";
foreach my $ind (@{$pops{$pop}}) {
next unless (grep(/\b$ind\b/, @samples));
print GEN $ind, ',', "\t";
foreach my $locus (@loci) {
if ($haplotypes{$locus}{$ind}) {
my @genotype = @{$haplotypes{$locus}{$ind}};
if (scalar(@genotype) == 1) { # homozygote
print GEN sprintf('%03s', $haplo_map{$locus}{$genotype[0]}), sprintf('%03s', $haplo_map{$locus}{$genotype[0]}), "\t";
} elsif (scalar(@genotype) == 2) { # heterozygote
print GEN sprintf('%03s', $haplo_map{$locus}{$genotype[0]}), sprintf('%03s', $haplo_map{$locus}{$genotype[1]}), "\t";
} else {
print GEN '000000', "\t";
}
} else {
print GEN '000000', "\t";
}
}
print GEN "\n";
}
}
open(REC, ">", 'codes.' . $genepop) or die $!;
foreach my $locus (@loci) {
my $code_str = join(",", map { "$_:" . sprintf('%03s',$haplo_map{$locus}{$_}) } sort { $haplo_map{$locus}{$a} <=> $haplo_map{$locus}{$b} } keys %{$haplo_map{$locus}});
print REC join("\t", $locus, $code_str), "\n";
}
}
sub write_tsv {
my $parent1 = $_[0];
my $parent2 = $_[1];
my @samples = @{$_[2]};
my %haplotypes = %{$_[3]};
my @progeny;
foreach my $ind (@samples) {
next if $ind eq $parent1 || $ind eq $parent2;
push @progeny, $ind;
}
open(SUM, ">", 'hap_summary.txt') or die $!;
print SUM join("\t", 'Locus', 'N_SNPs', 'Codes'), "\n";
open(TSV, ">", $tsvfile) or die $!;
print TSV join("\t", 'Locus', 'Parents', 'Count', 'F', @progeny), "\n";
my @loci = keys %haplotypes;
foreach my $locus (@loci) {
# Determine the segregation type
my %recode_map;
my @par1_haps;
my @par2_haps;
if ($haplotypes{$locus}{$parent1}) {
@par1_haps = @{$haplotypes{$locus}{$parent1}};
}
if ($haplotypes{$locus}{$parent2}) {
@par2_haps = @{$haplotypes{$locus}{$parent2}};
}
my $par1_code;
if (@par1_haps) {
$recode_map{$par1_haps[0]} = 'a';
$par1_code = 'a';
if ($par1_haps[1]) {
$recode_map{$par1_haps[1]} = 'b';
$par1_code = $par1_code . 'b';
} else {
$par1_code = $par1_code . 'a';
}
} else {
$par1_code = '--';
}
my $par2_code;
if (@par2_haps) {
if ($recode_map{$par2_haps[0]}) {
$par2_code = $recode_map{$par2_haps[0]};
} elsif ($par1_code eq '--') {
$recode_map{$par2_haps[0]} = 'a';
$par2_code = 'a';
} elsif ($par1_code eq 'aa') {
$recode_map{$par2_haps[0]} = 'b';
$par2_code = 'b';
} elsif ($par1_code eq 'ab') {
$recode_map{$par2_haps[0]} = 'c';
$par2_code = 'c';