| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | # Find the minimum abundance of kmers | ||
| 4 | # Original script was in Python at | ||
| 5 | # https://gist.github.com/alexjironkin/4ed43412878723491240814a0d5a6ed6/223dea45d70c9136703a4afaab0178cdbfbd2042 | ||
| 6 | # Original author of python script: @alexjironkin, Public Health Englad | ||
| 7 | # I wanted to increase capatibility with Perl and have a more | ||
| 8 | # standalone script instead of relying on the khmer package. | ||
| 9 | # Author: Lee Katz <lkatz@cdc.gov> | ||
| 10 | |||
| 11 | use strict; | ||
| 12 | use warnings; | ||
| 13 | use Getopt::Long qw/GetOptions/; | ||
| 14 | use Data::Dumper qw/Dumper/; | ||
| 15 | use File::Basename qw/basename fileparse/; | ||
| 16 | use File::Temp qw/tempdir/; | ||
| 17 | use List::Util qw/max/; | ||
| 18 | |||
| 19 | use threads; | ||
| 20 | use Thread::Queue; | ||
| 21 | |||
| 22 | # http://perldoc.perl.org/perlop.html#Symbolic-Unary-Operators | ||
| 23 | # +Inf and -Inf will be a binary complement of all zeros | ||
| 24 | use constant MAXINT => ~0; | ||
| 25 | use constant MININT => -~0; | ||
| 26 | |||
| 27 | local $0=basename $0; | ||
| 28 | sub logmsg{print STDERR "$0: @_\n";} | ||
| 29 | |||
| 30 | exit main(); | ||
| 31 | |||
| 32 | sub main{ | ||
| 33 | my $settings={}; | ||
| 34 | GetOptions($settings,qw(help kmerlength|kmer=i kmerCounter=s delta=i gt|greaterthan=i tempdir=s numcpus=i)) or die $!; | ||
| 35 | $$settings{kmerlength} ||=21; | ||
| 36 | $$settings{kmerCounter}||=""; | ||
| 37 | $$settings{gt} ||=1; | ||
| 38 | $$settings{tempdir} ||=tempdir(TEMPLATE=>"$0.XXXXXX",CLEANUP=>1,TMPDIR=>1); | ||
| 39 | $$settings{numcpus} ||=1; | ||
| 40 | |||
| 41 | if($$settings{delta}){ | ||
| 42 | logmsg "WARNING: --delta has been deprecated"; | ||
| 43 | } | ||
| 44 | |||
| 45 | my($fastq)=@ARGV; | ||
| 46 | die usage() if(!$fastq || $$settings{help}); | ||
| 47 | die "ERROR: I could not find fastq at $fastq" if(!-e $fastq); | ||
| 48 | |||
| 49 | ## Find valleys with multithreading | ||
| 50 | # List all kmer sizes per thread. | ||
| 51 | my @kmerlength; | ||
| 52 | my $i=0; | ||
| 53 | for(my $k=7; $k<=32; $k+=3){ | ||
| 54 | my $whichThread = $i % $$settings{numcpus}; | ||
| 55 | push(@{$kmerlength[$whichThread]}, $k); | ||
| 56 | $i++; | ||
| 57 | } | ||
| 58 | |||
| 59 | # Launch the threads with the various kmer length sub-arrays. | ||
| 60 | my @thr; | ||
| 61 | for my $kArray(@kmerlength){ | ||
| 62 | # Ensure that each thing getting sent to the thread is independent | ||
| 63 | # of this main subroutine memory space. | ||
| 64 | my %settingsCopy = %$settings; | ||
| 65 | my @kArrayCopy = @$kArray; | ||
| 66 | # Launch the thread. | ||
| 67 | push(@thr, | ||
| 68 | threads->new(\&valleyWorker, $fastq, \@kArrayCopy,\%settingsCopy) | ||
| 69 | ); | ||
| 70 | } | ||
| 71 | |||
| 72 | my %firstValleyVote; | ||
| 73 | for(@thr){ | ||
| 74 | my $firstValley = $_->join; | ||
| 75 | for my $minimum(@$firstValley){ | ||
| 76 | next if(!$minimum); | ||
| 77 | $firstValleyVote{$minimum}++; | ||
| 78 | } | ||
| 79 | } | ||
| 80 | |||
| 81 | # If no valleys were found, simply set the stage so that | ||
| 82 | # the minimum depth will be set to 0. | ||
| 83 | if(keys(%firstValleyVote) < 1){ | ||
| 84 | logmsg "NOTE: no valleys were found and so I am inserting an imaginary vote for a valley at cov=1"; | ||
| 85 | $firstValleyVote{0} = 1; | ||
| 86 | } | ||
| 87 | |||
| 88 | logmsg "For various values of k, valleys were found:"; | ||
| 89 | my $firstValley=0; | ||
| 90 | # Average out the votes | ||
| 91 | my $totalFirstValley = 0; | ||
| 92 | my $totalVotes = 0; | ||
| 93 | my @vote; | ||
| 94 | # Sort bins by their votes, highest to lowest | ||
| 95 | for my $bin(sort{$firstValleyVote{$b}<=>$firstValleyVote{$a} || $a<=>$b} keys(%firstValleyVote)){ | ||
| 96 | my $value=$firstValleyVote{$bin}; | ||
| 97 | $firstValley||=$bin; # set the valley to the first bin we come to | ||
| 98 | for(1..$value){ | ||
| 99 | push(@vote, $bin); | ||
| 100 | } | ||
| 101 | |||
| 102 | $totalFirstValley += $bin * $value; | ||
| 103 | $totalVotes += $value; | ||
| 104 | } | ||
| 105 | @vote = sort {$a<=>$b} @vote; | ||
| 106 | logmsg @vote; | ||
| 107 | my $medianFirstValley = $vote[ int(scalar(@vote)/2) ]; | ||
| 108 | |||
| 109 | # Get the average first valley across many kmers | ||
| 110 | my $avgFirstValley = $totalFirstValley/$totalVotes; | ||
| 111 | logmsg " Average first valley is $avgFirstValley"; | ||
| 112 | logmsg " However, I will use the median valley: $medianFirstValley"; | ||
| 113 | printf("%0.0f\n", $medianFirstValley); | ||
| 114 | |||
| 115 | #print join("\t",qw(kmer count))."\n"; | ||
| 116 | #print join("\t", $firstValley, 1)."\n"; | ||
| 117 | return 0; | ||
| 118 | |||
| 119 | } | ||
| 120 | |||
| 121 | # Poor man's way of subsampling | ||
| 122 | # Thanks to Nick Greenfield for pointing this out. | ||
| 123 | sub mashHistogram{ | ||
| 124 | my($fastq,$k,$settings)=@_; | ||
| 125 | my $sketch="$$settings{tempdir}/sketch.$k.msh"; | ||
| 126 | system("mash sketch -k $k -m 1 -o $sketch $fastq > /dev/null 2>&1"); | ||
| 127 | die if $?; | ||
| 128 | |||
| 129 | my @histogram; | ||
| 130 | open(my $fh, "mash info -c $sketch | ") or die "ERROR: could not get mash info on sketch $sketch"; | ||
| 131 | while(my $line=<$fh>){ | ||
| 132 | $line=~s/^\s+|\s+$//g; # whitespace trim | ||
| 133 | next if($line=~/^#/); | ||
| 134 | my($filename, $bin, $frequency)=split(/\t/, $line); | ||
| 135 | $histogram[$bin]=$frequency; | ||
| 136 | } | ||
| 137 | close $fh; | ||
| 138 | $histogram[$_]||=0 for(0..@histogram); | ||
| 139 | return \@histogram; | ||
| 140 | } | ||
| 141 | |||
| 142 | sub readHistogram{ | ||
| 143 | my($infile,$settings)=@_; | ||
| 144 | my @hist=(0); | ||
| 145 | open(HIST,$infile) or die "ERROR: could not read $infile: $!"; | ||
| 146 | logmsg "Reading histogram from $infile"; | ||
| 147 | while(<HIST>){ | ||
| 148 | chomp; | ||
| 149 | my($count,$countOfCounts)=split /\t/; | ||
| 150 | $hist[$count]=$countOfCounts; | ||
| 151 | } | ||
| 152 | close HIST; | ||
| 153 | |||
| 154 | # ensure defined values | ||
| 155 | for(my $i=0;$i<@hist;$i++){ | ||
| 156 | $hist[$i] //= 0; | ||
| 157 | } | ||
| 158 | |||
| 159 | return \@hist; | ||
| 160 | } | ||
| 161 | |||
| 162 | sub valleyWorker{ | ||
| 163 | my($fastq, $kArray, $settings)=@_; | ||
| 164 | my @firstValley; | ||
| 165 | |||
| 166 | for my $kmerlength(@$kArray){ | ||
| 167 | logmsg "Counting $kmerlength-kmers in $fastq"; | ||
| 168 | my $histogram = mashHistogram($fastq,$kmerlength,$settings); | ||
| 169 | my $firstValley = findFirstValley($histogram, $settings); | ||
| 170 | push(@firstValley, $firstValley); | ||
| 171 | } | ||
| 172 | return \@firstValley; | ||
| 173 | } | ||
| 174 | |||
| 175 | # https://www.perlmonks.org/?node_id=629742 | ||
| 176 | sub localMinimaMaxima{ | ||
| 177 | my($array, $settings)=@_; | ||
| 178 | |||
| 179 | my @arr = @$array; | ||
| 180 | |||
| 181 | my @minima; | ||
| 182 | my @maxima; | ||
| 183 | my $prev_cmp = 0; | ||
| 184 | |||
| 185 | my $num = @arr - 2; | ||
| 186 | for my $i (0 .. $num){ | ||
| 187 | my $cmp = $arr[$i] <=> $arr[$i+1]; | ||
| 188 | if ($cmp != $prev_cmp) { | ||
| 189 | # have a minimum only after there has been a maximum | ||
| 190 | if($cmp < 0 && @maxima > 0){ | ||
| 191 | push @minima, $i; | ||
| 192 | } | ||
| 193 | elsif($cmp > 0){ | ||
| 194 | push @maxima, $i; | ||
| 195 | } | ||
| 196 | # when this and next elements are ==, defer checking for | ||
| 197 | # minima/maxima till next loop iteration | ||
| 198 | $prev_cmp = $cmp if $cmp; | ||
| 199 | } | ||
| 200 | } | ||
| 201 | |||
| 202 | # Uncomment the following if we want to look at the very | ||
| 203 | # last number in the array. | ||
| 204 | #if (@$array) { | ||
| 205 | # push @minima, $num if $prev_cmp >= 0; | ||
| 206 | # push @maxima, $num if $prev_cmp <= 0; | ||
| 207 | #} | ||
| 208 | |||
| 209 | ## debugging | ||
| 210 | #splice(@$array, 30); | ||
| 211 | #print join(".",@minima)."\n".join(",", @$array)."\n\n"; | ||
| 212 | |||
| 213 | return(\@minima, \@maxima); | ||
| 214 | } | ||
| 215 | |||
| 216 | sub findFirstValley{ | ||
| 217 | my($array, $settings)=@_; | ||
| 218 | my($minima, $maxima) = localMinimaMaxima($array, $settings); | ||
| 219 | |||
| 220 | # Return the first minimum if it's not the first element | ||
| 221 | # or if there are no other minima. | ||
| 222 | if($$minima[0] > 0 || !$$minima[1]){ | ||
| 223 | return $$minima[0]; | ||
| 224 | } else { | ||
| 225 | return $$minima[1]; | ||
| 226 | } | ||
| 227 | } | ||
| 228 | |||
| 229 | # http://www.perlmonks.org/?node_id=761662 | ||
| 230 | sub which{ | ||
| 231 | my($exe,$settings)=@_; | ||
| 232 | |||
| 233 | my $tool_path=""; | ||
| 234 | for my $path ( split /:/, $ENV{PATH} ) { | ||
| 235 | if ( -f "$path/$exe" && -x "$path/$exe" ) { | ||
| 236 | $tool_path = "$path/$exe"; | ||
| 237 | last; | ||
| 238 | } | ||
| 239 | } | ||
| 240 | |||
| 241 | return $tool_path; | ||
| 242 | } | ||
| 243 | |||
| 244 | sub usage{ | ||
| 245 | " | ||
| 246 | $0: | ||
| 247 | Find the valley between two peaks on a set of kmers | ||
| 248 | such that you can discard the kmers that are | ||
| 249 | likely representative of contamination. | ||
| 250 | This script does not require any dependencies. | ||
| 251 | |||
| 252 | Usage: $0 file.fastq[.gz] | ||
| 253 | --gt 1 Look for the first peak at this kmer count | ||
| 254 | and then the next valley. | ||
| 255 | --kmer 21 kmer length | ||
| 256 | --numcpus 1 This script will apply one thread per kmer | ||
| 257 | length. Multiple values of k are tested to | ||
| 258 | get a consensus value. | ||
| 259 | |||
| 260 | MISC | ||
| 261 | --kmerCounter '' The kmer counting program to use. | ||
| 262 | Default: (empty string) auto-choose | ||
| 263 | Options: perl, jellyfish | ||
| 264 | " | ||
| 265 | } | ||
| 266 |