-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathphylipFilterPops.pl
More file actions
executable file
·595 lines (495 loc) · 14.8 KB
/
phylipFilterPops.pl
File metadata and controls
executable file
·595 lines (495 loc) · 14.8 KB
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
#! /usr/bin/perl
# Contributions by Tyler K. Chafin, Steven M. Mussmann, Max R. Bangs
# Contact: tkchafin@uark.edu
use strict;
use warnings;
use Getopt::Std;
use List::Util qw(shuffle);
#Die if no arguments given
if( scalar( @ARGV ) == 0 ){
&help;
die "No options given\n\n";
}
#Parse arguments
my %opts;
getopts( 'p:i:o:hn:N:gPxrOm:sr:w:R:P', \%opts );
# kill if help option is true
if( $opts{h} ){
&help;
die "Help menu\n\n";
}
#get options
my ($map, $phy, $out, $threshold, $globalThresh, $gapFalse, $minPop, $skipMiss, $randSample, $weightSample, $alleleSample, $poplabels) = &parseArgs(\%opts);
#sanity check
if ($weightSample && $randSample || $weightSample && $alleleSample || $alleleSample && $randSample){
die("-r, -R, and -w options cannot be combined\n")
}
if ($randSample){
print("Randomly sampling $randSample samples per population\n");
}
if ($weightSample){
print("Sampling $weightSample samples of highest coverage per population\n");
}
if ($alleleSample){
print("Randomly sampling $alleleSample alleles per population (not working yet)\n");
}
# hash of loci with too much missing data
my %blacklist;
#parse popmap file into a hash with ind as key and popID as value
my $assignRef = &parsePopmap($map);
#parse phylip file into a hash with ind as key and array of seqs as value
my ($allRef, $ntax, $nchar) = &parsePhylip($phy);
#Print argument report
print "\nPopmap file is: $map\n";
print "Phylip file is: $phy\n";
print "Total taxa in phylip file: $ntax\n";
print "Total characters in phylip data matrix: $nchar\n\n";
#Get pop alignments only with ind as key and array of seqs as value
my @vals = values %$assignRef;
my @pops = uniq(@vals);
my $popAligns = &getSepMultPops($assignRef, $allRef, \@pops);
#remove pops with too little data
foreach my $p (keys %{$popAligns}){
my $count=0;
foreach my $ind (keys %{$popAligns->{$p}}){
$count++;
}
if ($count < $minPop){
print "Deleting population $p: Less than $minPop samples (N=$count).\n";
delete $popAligns->{$p};
}
}
# foreach my $p (keys %{$popAligns}){
# print $p, "\n";
# }
if ($skipMiss == 0){
if ($gapFalse == 1){
&getBlacklistSep($popAligns, $threshold, $globalThresh, \%blacklist);
}else{
&getBlacklistGap($popAligns, $threshold, $globalThresh, \%blacklist);
}
my $nFail = (keys %blacklist);
print($nFail ," loci had greater than ",$threshold, " missing data. Removing them.\n");
}else{
print "Skipping calculation of missing data.\n";
}
print("Writing new PHYLIP file <$out>\n");
open (PHY, "> $out");
my $locnum = 0;
my $indnum = 0;
for (my $loc = 0; $loc < $nchar; $loc++){
if(!exists $blacklist{$loc+1}){
$locnum++;
}
}
foreach my $pop (keys %{$popAligns}){
foreach my $ind (keys %{$popAligns->{$pop}}){
$indnum++;
}
}
sub min{
if ($_[0] > $_[1]){
return ($_[1]);
}else{
return($_[0])
}
}
$indnum = 0;
foreach my $pop (keys %{$popAligns}){
my $p = scalar(keys %{$popAligns});
if ($weightSample){
$indnum += min($weightSample, $p);
}elsif ($randSample){
$indnum += min($randSample, $p);
}elsif ($alleleSample){
$indnum += min($alleleSample, $p);
}else{
$indnum += $p;
}
}
print PHY $indnum, " ", $locnum, "\n";
#Get missing data per sample if needed
my %sampleCoverage;
if ($weightSample){
%sampleCoverage = &getCoverage($popAligns);
# foreach my $ind (keys %sampleCoverage){
# print $ind, ": ", $sampleCoverage{$ind}, "\n";
# }
# exit()
}
#print data
foreach my $pop (keys %{$popAligns}){
my $popCounter = 1;
#if random sample, randomly order keys to continue, and only choose X number
#if allele sample, grab all alleles and sample up to X non-N alleles
#if weight sample, order keys by completeness of sampling (%sampCoverage)
my @keys;
my $max;
if ($weightSample){
@keys = sort { $sampleCoverage{$a} <=> $sampleCoverage{$b} } keys %{$popAligns->{$pop}};
$max = $weightSample;
}elsif ($randSample){
@keys = shuffle (keys %{$popAligns->{$pop}});
$max = $randSample;
}else{
@keys = keys %{$popAligns->{$pop}};
$max = scalar(@keys);
}
#If not rand allele sampling, then sample based on the above order
if (!$alleleSample){
my $sampled = 0;
foreach my $ind (@keys){
$sampled++;
#print $ind, "\n";
my $name;
if ($poplabels){
if ($weightSample || $randSample){
if ($max > 1){
$name = $pop + "_" + $sampled;
}else{
$name = $pop;
}
}
}else{
$name = $ind;
}
print PHY $name, "\t";
for (my $l = 0; $l < $nchar; $l++){
if(!exists $blacklist{$l+1}){
#check if samples should be relabeled
#if -r, -R, or -w equal 1, don't append number
print PHY ${$popAligns->{$pop}->{$ind}}[$l];
}
}
print PHY "\n";
if ($sampled >= $max){
last;
}
}
$popCounter++; #increment count per pop
}
}
close PHY;
exit 0;
########################### SUBROUTINES ###############################
sub help{
print "\nphylipFilterPops.pl by Tyler Chafin, w/ contributions by Steve Mussmann and Max Bangs\n";
print "\nThis script filters rows and columns from a phylip file based on population assignments\n";
print "A population map should be given in a tab-delimited file, formatted as:\n";
print "\n\tSampleName\tPopID\n\n";
print "Where PopID can be a string or integer, and SampleName must exactly match a corresponsing line in the phylip file. Any samples not in the popmap will not be included in the output files.\n\n";
print "Options:\n";
print "\t-p : Path to popmap file (tab-delimited)\n";
print "\t-i : Path to input file (phylip)\n";
print "\t-m : Minimum number of samples to keep a population\n";
print "\t-n : Proportion missing data allowed per population per SNP (default=0.5)\n";
print "\t-N : Proportion of globally missing data allowed per SNP (default=0.5)\n";
print "\t-g : Toggle on to TURN OFF default behavior of treating gaps as missing data\n";
print "\t-s : Skip calculating missing data, and just drop populations with too few inds\n";
print "\t-r : Randomly sample up to <x> individuals from each population\n";
print "\t-w : Sample up to <x> individuals from each population with the least missing data\n";
print "\t-R : Randomly sample up to <x> ALLELES from each population (per column, for SNPs)\n";
print "\t-P : Print samples using pop names (numbered as \"_x\" if more than 1 sample)\n";
print "\t-o : Output file name\n";
print "\t-h : Displays this help message\n";
print "\n\n";
}
#parse arguments
sub parseArgs{
my( $params ) = @_;
my %opts = %$params;
#defaults
my $map = $opts{p} or die "\nPopmap not specified.\n\n";
my $phy = $opts{i} or die "\nPhylip file not specified.\n\n";
my $threshold = $opts{n} || 0.5;
my $gapFalse = 0;
my $phyNew = 0;
my $skip = 0;
$opts{s} and $skip = 1;
my $minPop = $opts{m} || 0;
$opts{g} and $gapFalse = 1;
my $globalThresh = $opts{N} || 0.5;
my $out = $opts{o} || "out.phy";
my $randSample = $opts{r} || 0;
my $weightSample = $opts{w} || 0;
my $alleleSample = $opts{R} || 0;
my $poplabels = 0;
$opts{P} and $poplabels = 1;
#return
return ($map, $phy, $out, $threshold, $globalThresh, $gapFalse, $minPop, $skip, $randSample, $weightSample, $alleleSample, $poplabels);
}
sub uniq {
my %seen;
return grep { !$seen{$_}++ } @_;
}
#parse popmap file
sub parsePopmap{
my $toParse = $_[0];
#vars
my %toReturn;
#open popmap
open (POP, $toParse) or die "Oh no! Cannot open $toParse: $!\n";
while (my $line = <POP>){
chomp $line;
#ignore if blank
if( $line =~ /^\w/ ){
my @temp = split( /\s+/, $line);
#push into our hash
$toReturn{$temp[0]} = $temp[1];
}
}
close POP;
return( \%toReturn);
}
#parse phylip file -> This version returns array refs, not strings, of sequences
sub parsePhylip{
my $toParse = shift(@_);
#vars
my %toReturn;
my @seq;
my $ntax;
my $nchar;
#open popmap
open (PHY, $toParse) or die "Oh no! Cannot open $toParse: $!\n";
my $num = 0;
while (my $line = <PHY>){
$num++;
chomp $line;
#Skip first line
if ($num == 1){
my @temp = split( /\s+/, $line);
$ntax = $temp[0];
$nchar = $temp[1];
next;
}
#ignore if blank
if( $line =~ /^\w/ ){
my @temp = split( /\s+/, $line);
my @arr = split(//, $temp[1]);
#push array ref into our hash
$toReturn{$temp[0]} = \@arr;
}
}
close PHY;
return( \%toReturn, $ntax, $nchar);
}
#Get alignments for only populations of interest
sub getPops{
my $pops = $_[0];
my $seqs = $_[1];
my $first = $_[2];
my $second = $_[3];
my %pop1;
my %pop2;
foreach my $key (keys %{$pops}){
#If pop ID matches
if ($pops->{$key} eq $first){
${$pop1{$key}} = $seqs->{$key};
}elsif ($pops->{$key} eq $second){
${$pop2{$key}} = $seqs->{$key};
}
}
return(\%pop1, \%pop2);
}
#Modified getPops subroutine, gets all pops matching array of options, returns as one hash
sub getSepMultPops{
my $popRef = $_[0];
my $seqRef = $_[1];
my $toGetRef = $_[2];
my %pop; #hash of hashes
foreach my $id (@{$toGetRef}){
#print $id, "\n";
my %local;
$pop{$id} = \%local;
}
foreach my $id (@{$toGetRef}){
foreach my $key (keys %{$popRef}){
#If pop ID matches, get sequence
if ($popRef->{$key} eq $id){
if (exists $seqRef->{$key}){
$pop{$id}{$key} = $seqRef->{$key};
}else{
print "Warning: Sample <$key> was not found in sequence file. Skipping.\n";
}
}
}
}
return(\%pop);
}
# subroutine to put sequence alignment into a hash with the index value of the alignment as the key and a string of nucleotides at that index as the value
# modified from a subroutine steve wrote
sub getColumns{
my( $hashref ) = @_;
my %align; # hash of arrays to hold position in alignment (hash key) and all characters at that position in alignment (value)
#For each individual
foreach my $key( sort keys %{ $hashref } ){
my $index = 0;
my @seq = split( //, ${$hashref->{$key}} );
#for each nucleotide
foreach my $item( @seq ){
$align{$index} .= $item;
$index++;
}
}
return( \%align );
}
#Subroutine to parse the alignment
sub parsePopAlignment{
my $p1 = $_[0];
my $p2 = $_[1];
my $thresholdN = $_[2];
my $thresholdG = $_[3];
my @blacklist;
#To track fixed alleles in each pop
my $alleles1 = parseColumn($p1, $thresholdN, $thresholdG, \@blacklist);
my $alleles2 = parseColumn($p2, $thresholdN, $thresholdG, \@blacklist);
#Make sure both pops have same number of columns
if ((scalar(@{$alleles1})) != (scalar(@{$alleles1}))){
die "\nError: Y ur populations have not same sequence leNGTH???\n\n";
}else{
#Only keep loci which are differentially fixed
#Make sure to check anything fixed in pop1 is different
#from fixed in pop2
for(my $i=0; $i < scalar(@{$alleles1}); $i++){
my $check1 = $alleles1->[$i] =~ tr/NV-/NV-/;
my $check2 = $alleles2->[$i] =~ tr/NV-/NV-/;
#If either pop was variable, or fixed for gaps or Ns
if ($check1 > 0 || $check2 > 0){
next;
}else{
#If both fixed for same allele
if ($alleles1->[$i] eq $alleles2->[$i]){
push(@blacklist, $i);
next;
}
}
}
}
return(\@blacklist);
}
# subroutine to remove columns from an alignment, given the alignment contained in a hash and an array of positions in each value to be removed
sub removeColumns{
my( $hashref, $remove ) = @_;
my @blacklist = uniq($remove);
# replace columns to be removed with a special character
foreach my $key( sort keys %{ $hashref } ){
foreach my $item( @blacklist ){
substr(${$hashref}{$key}, $item, 1) = 'z';
}
}
# replace the special characters with nothing
foreach my $key( sort keys %{ $hashref } ){
${$hashref}{$key} =~ s/z//g;
}
}
sub calcMissingSep{
my( $hashref, $blacklistref ) = @_;
foreach my $ind( sort keys %$hashref ){
my $counter = 0;
foreach my $locus( @${$$hashref{$ind}} ){
$counter++;
if($locus eq "N"){
$$blacklistref{$counter}++;
}else{
$$blacklistref{$counter}+=0;
}
}
}
}
sub getCoverage{
my $popsRef = $_[0];
my %coverage;
foreach my $pop (keys %{$popsRef}){
foreach my $ind (keys %{$popsRef->{$pop}}){
my $totalcount = 0;
my $ncount = 0;
foreach my $locus ( @{$popsRef->{$pop}->{$ind}} ){
if ($locus eq "N"){
$ncount++;
}
$totalcount++;
}
$coverage{$ind} = ($ncount/$totalcount);
}
}
return(%coverage);
}
sub getBlacklistSep{
my( $popsRef, $thresh, $globalThresh, $blacklistref ) = @_;
my $globalInds = 0;
my %globalCount;
#Check loci in each population
foreach my $pop (keys %{$popsRef}){
my %ncount;
my $inds;
foreach my $ind (keys %{$popsRef->{$pop}}){
$inds++;
$globalInds++;
my $counter = 0;
foreach my $locus ( @{$popsRef->{$pop}->{$ind}} ){
$counter++;
$ncount{$counter} = 0 unless exists $ncount{$counter};
$globalCount{$counter} = 0 unless exists $globalCount{$counter};
if ($locus eq "N"){
$ncount{$counter}++;
$globalCount{$counter}++;
}
}
}
#blacklist any loci with too high n proportion (in THIS pop)
foreach my $loc(sort keys %ncount){
if (($ncount{$loc} / $inds) > $threshold){
$$blacklistref{$loc} = ($ncount{$loc} / $inds) unless exists $$blacklistref{$loc};
#print("Locus:",$loc," - Failed (pop", $pop,"): ",($ncount{$loc} / $inds), "\n");
}
#print("Nprop:",($ncount{$loc} / $inds), "\n");
}
}
#Blacklist loci with globally too high missing data
foreach my $loc(sort keys %globalCount){
if (($globalCount{$loc} / $globalInds) > $threshold){
$$blacklistref{$loc} = ($globalCount{$loc} / $globalInds) unless exists $$blacklistref{$loc};
#print("Locus:",$loc," - Failed (global): ",($globalCount{$loc} / $globalInds), "\n");
}
}
}
sub getBlacklistGap{
my( $popsRef, $thresh, $globalThresh, $blacklistref ) = @_;
my $globalInds = 0;
my %globalCount;
#Check loci in each population
foreach my $pop (keys %{$popsRef}){
my %ncount;
my $inds;
foreach my $ind (keys %{$popsRef->{$pop}}){
#print("Ind: ", $ind, "\n");
$inds++;
$globalInds++;
my $counter = 0;
foreach my $locus ( @{$popsRef->{$pop}->{$ind}} ){
$counter++;
$ncount{$counter} = 0 unless exists $ncount{$counter};
$globalCount{$counter} = 0 unless exists $globalCount{$counter};
if ($locus eq "N" || $locus eq "-"){
$ncount{$counter}++;
$globalCount{$counter}++;
}
}
}
#blacklist any loci with too high n proportion (in THIS pop)
foreach my $loc(sort keys %ncount){
if (($ncount{$loc} / $inds) > $threshold){
$$blacklistref{$loc} = ($ncount{$loc} / $inds) unless exists $$blacklistref{$loc};
#print("Locus:",$loc," - Failed (pop", $pop,"): ",($ncount{$loc} / $inds), "\n");
}
#print("Nprop:",($ncount{$loc} / $inds), "\n");
}
}
#Blacklist loci with globally too high missing data
foreach my $loc(sort keys %globalCount){
if (($globalCount{$loc} / $globalInds) > $threshold){
$$blacklistref{$loc} = ($globalCount{$loc} / $globalInds) unless exists $$blacklistref{$loc};
#print("Locus:",$loc," - Failed (global): ",($globalCount{$loc} / $globalInds), "\n");
}
}
}