bin/mashtree

filter: Statementstmt 93.9% 31 / 33 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 11 / 11 Podpod n/a totaltotal 95.4% 42 / 44 CC 1 SCAR 0.3
CC
1
Cov
94%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« lib/Mashtree.pm ↑ Summary
1 #!/usr/bin/env perl
2 # Author: Lee Katz <lkatz@cdc.gov>
3 # Uses Mash and BioPerl to create a NJ tree based on distances.
4 # Run this script with -h for help and usage.
5  
6 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Getopt::Long;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use File::Temp qw/tempdir tempfile/;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use File::Basename qw/basename dirname fileparse/;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use File::Copy qw/copy/;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use POSIX qw/floor/;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 1 ▶use List::Util qw/min max/;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use Scalar::Util qw/looks_like_number/;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 0 ▶use threads;
Subroutine BEGIN: called CC=1 SCAR=2.6
18 use threads::shared;
19  
20 use FindBin;
21 use lib "$FindBin::RealBin/../lib";
22 use lib "$FindBin::RealBin/../lib/perl5";
23 use File::Which qw/which/;
24 use Mashtree qw/logmsg @fastqExt @fastaExt @mshExt @richseqExt _truncateFilename createTreeFromPhylip $MASHTREE_VERSION/;
25 use Mashtree::Db;
26 use Bio::Tree::DistanceFactory;
27 use Bio::Matrix::IO;
28 use Bio::Tree::Statistics;
29 use Bio::SeqIO;
30  
31 #my %delta :shared=(); # change in amplitude for peak detection, for each fastq
32 my $scriptDir=dirname $0;
33 my $dbhLock :shared; # Use this as a lock so that only one thread writes to the db at a time
34 my $abundanceFinderLock :shared; # a lock to limit min abundance finder instances
35 local $0=basename $0;
36  
37 exit main();
38  
39 sub main{
40 my $settings={};
41 GetOptions($settings,qw(help sigfigs|significant-digits=i file-of-files outtree=s outmatrix=s tempdir=s numcpus=i genomesize=i mindepth|min-depth=i truncLength=i kmerlength=i sort-order=s sketch-size=i citation version save-sketches:s seed=i)) or die $!;
42 $$settings{numcpus}||=1;
43 $$settings{truncLength}||=250; # how long a genome name is
44 $$settings{sigfigs} ||= 10;
45 $$settings{tempdir}||=tempdir("MASHTREE.XXXXXX",CLEANUP=>1,TMPDIR=>1);
46 $$settings{'sort-order'}||="ABC";
47  
48 # Mash-specific options
49 $$settings{genomesize}||=5000000;
50 $$settings{mindepth}//=5;
51 $$settings{kmerlength}||=21;
52 $$settings{'sketch-size'}||=10000;
53 $$settings{seed}||=42;
54  
55 # Make some settings lowercase
56 for(qw(sort-order)){
57 $$settings{$_}=lc($$settings{$_});
58 }
59  
60 if($$settings{help}){
61 print usage();
62 return 0;
63 }
64 if($$settings{version}){
65 print "Mashtree $MASHTREE_VERSION\n";
66 return 0;
67 }
68 if($$settings{citation}){
69 print "Katz, L. S., Griswold, T., Morrison, S., Caravas, J., Zhang, S., den Bakker, H.C., Deng, X., and Carleton, H. A., (2019). Mashtree: a rapid comparison of whole genome sequence files. Journal of Open Source Software, 4(44), 1762, https://doi.org/10.21105/joss.01762\n";
70 return 0;
71 }
72  
73 # "reads" are either fasta assemblies or fastq reads
74 my @reads=@ARGV;
75 die "need more arguments\n".usage() if(@reads < 1);
76  
77 # Check for prereq executables.
78 for my $exe(qw(mash quicktree)){
79 if(!which($exe)){
80 die "ERROR: could not find $exe in your PATH";
81 }
82 }
83  
84 # Check mash version
85 my $mashVersion = `mash --version`;
86 die "ERROR running mash: $!" if $?;
87 chomp($mashVersion);
88 $mashVersion=~s/\..*//;
89 die "ERROR: need mash version > 2" if($mashVersion < 2);
90 logmsg "Found mash version $mashVersion - ".which('mash');
91  
92 # Distributed cpus if we have few genomes but high numcpus
93 $$settings{cpus_per_mash}=floor($$settings{numcpus}/@reads);
94 $$settings{cpus_per_mash}=1 if($$settings{cpus_per_mash} < 1);
95 $$settings{numthreads}=min(scalar(@reads), $$settings{numcpus});
96  
97 #die Dumper [$$settings{cpus_per_mash},$$settings{numthreads},\@reads];
98 #$$settings{cpus_per_mash}=1;
99 #$$settings{numthreads}=$$settings{numcpus};
100  
101 logmsg "Temporary directory will be $$settings{tempdir}";
102 logmsg "$0 on ".scalar(@reads)." files";
103  
104 my %seen;
105 my @tmp;
106 for my $reads(@ARGV){
107 if(!-e $reads){
108 die "ERROR: I could not find reads path at $reads";
109 }
110 my $basename=basename($reads);
111 if($seen{$basename}++){
112 logmsg "Skipping $reads: already seen $basename";
113 next;
114 }
115  
116 # If the user wants to specify files of files then check
117 # on whether it is a file of files. Otherwise do not check
118 # because of disk IO speeds.
119 if($$settings{'file-of-files'}){
120 # If we have file-of-files in play, don't try to optimize
121 # too early.
122 $$settings{cpus_per_mash}=1;
123 $$settings{numthreads}=$$settings{numcpus};
124 open(my $possibleFileOfFiles, "<", $reads) or die "ERROR: could not read $reads: $!";
125 my $firstfile = <$possibleFileOfFiles>;
126 $firstfile=~s/^\s+|\s+$//g; #whitespace trim
127 chomp($firstfile);
128 if(-e $firstfile){
129 push(@tmp, $firstfile);
130 while(<$possibleFileOfFiles>){
131 s/^\s+|\s+$//g; #whitespace trim
132 push(@tmp, $_);
133 }
134 } else {
135 logmsg "WARNING: user specified --file-of-files but $reads does not seem to be a file of files (ignore this warning if this was not supposed to be a file of files";
136 push(@tmp, $reads);
137 }
138 close $possibleFileOfFiles;
139 } else {
140 push(@tmp,$reads);
141 }
142 }
143 @reads=@tmp;
144  
145 my $sketches=sketchAll(\@reads,"$$settings{tempdir}",$settings);
146  
147 my $phylip = mashDistance($sketches,\@reads,$$settings{tempdir},$settings);
148  
149 my $treeObj = createTreeFromPhylip($phylip,$$settings{tempdir},$settings);
150  
151 # Write the tree
152 if($$settings{outtree}){
153 open(my $treeFh, ">", $$settings{outtree}) or die "ERROR writing tree to $$settings{outtree}: $!";
154 print $treeFh $treeObj->as_text('newick');
155 close $treeFh
156 } else {
157 print $treeObj->as_text('newick');
158 print "\n";
159 }
160  
161 return 0;
162 }
163  
164 # Run mash sketch on everything, multithreaded.
165 sub sketchAll{
166 my($reads,$sketchDir,$settings)=@_;
167  
168 mkdir $sketchDir if(!-d $sketchDir);
169  
170 # Make an array of genomes that would distribute well
171 # across threads. For example, don't put all raw-read
172 # genomes into a single thread and all the assemblies
173 # into another.
174 my %filesize=();
175 for(@$reads){
176 $filesize{$_} = -s $_;
177 }
178 my @sortedReads=sort {$filesize{$a} <=> $filesize{$b}} @$reads;
179 my @threadArr=();
180 for(my $i=0; $i<@sortedReads; $i++){
181 # Since each genome is sorted smallest to leargest,
182 # they can be sent round-robin to each thread to
183 # ensure balance.
184 my $threadIndex = $i % $$settings{numcpus};
185 push(@{ $threadArr[$threadIndex] }, $sortedReads[$i]);
186 }
187  
188 # Initiate the threads
189 my @thr;
190 for(0..$$settings{numthreads}-1){
191 # If there are more threads than samples, then we need to set the number in this thread to empty array
192 $threadArr[$_] //= [];
193  
194 $thr[$_]=threads->new(\&mashSketch,$sketchDir,$threadArr[$_],$settings);
195 }
196  
197 my @mshList;
198 for(@thr){
199 my $mashfiles=$_->join;
200 for my $file(@$mashfiles){
201 push(@mshList,$file);
202 }
203 }
204  
205 return \@mshList;
206 }
207  
208 # Individual mash sketch worker
209 sub mashSketch{
210 my($sketchDir,$genomeArr,$settings)=@_;
211  
212 # If any file needs to be converted, it will end up in
213 # this directory.
214 my $tempdir=tempdir("$$settings{tempdir}/convertSeq.XXXXXX", CLEANUP=>1);
215  
216 my $numFiles = scalar(@$genomeArr);
217 logmsg "This thread will work on $numFiles sketches";
218  
219 my @msh;
220 my $fileCounter=0;
221 # $fastq is a misnomer: it could be any kind of accepted sequence file
222 for my $fastq(@$genomeArr){
223 logmsg "Working on file ".++$fileCounter." out of $numFiles";
224 my($fileName,$filePath,$fileExt)=fileparse($fastq,@fastqExt,@fastaExt,@richseqExt,@mshExt);
225  
226 # Unzip the file. This temporary file will
227 # only exist if the correct extensions are detected.
228 my $unzipped="$tempdir/".basename($fastq);
229 $unzipped=~s/\.(gz|bz2?|zip)$//i;
230 my $was_unzipped=0;
231 # Don't bother unzipping if it's a fastq or fasta file b/c Mash can read those
232 if(!grep {$_ eq $fileExt} (@fastqExt,@fastaExt)){
233 if($fastq=~/\.gz$/i){
234 # Don't actually decompress fastq.gz files because they are
235 # read natively by mash.
236 if($fastq =~ /\.fastq.gz$|\.fq.gz$/){
237 $was_unzipped=0;
238 } else {
239 system("gzip -cd $fastq > $unzipped");
240 die "ERROR with gzip -cd $fastq" if $?;
241 $was_unzipped=1;
242 }
243 } elsif($fastq=~/\.bz2?$/i){
244 system("bzip2 -cd $fastq > $unzipped");
245 die "ERROR with bzip2 -cd $fastq" if $?;
246 $was_unzipped=1;
247 } elsif($fastq=~/\.zip$/i){
248 system("unzip -p $fastq > $unzipped");
249 die "ERROR with unzip -p $fastq" if $?;
250 $was_unzipped=1;
251 }
252 }
253  
254 # If the file was uncompressed, parse the filename again.
255 if($was_unzipped){
256 $fastq=$unzipped;
257 ($fileName,$filePath,$fileExt)=fileparse($fastq,@fastqExt,@fastaExt,@richseqExt,@mshExt);
258 }
259  
260 # If we see a richseq (e.g., gbk or embl), then convert it to fasta
261 # TODO If Mash itself accepts richseq, then consider
262 # doing away with this section.
263 if(grep {$_ eq $fileExt} @richseqExt){
264 # Make a temporary fasta file, but it needs to have a
265 # consistent name in case Mashtree is being run with
266 # the wrapper for bootstrap values.
267 # I can't exactly make a consistent filename in case
268 # different mashtree invocations collide, so
269 # I need to make a new temporary directory with a
270 # consistent filename.
271 my $tmpfasta="$tempdir/$fileName$fileExt.fasta";
272 my $in=Bio::SeqIO->new(-file=>$fastq);
273 my $out=Bio::SeqIO->new(-file=>">$tmpfasta", -format=>"fasta");
274 while(my $seq=$in->next_seq){
275 $out->write_seq($seq);
276 }
277 logmsg "Wrote $tmpfasta";
278  
279 # Update our filename for downstream
280 $fastq=$tmpfasta;
281 ($fileName,$filePath,$fileExt)=fileparse($tmpfasta, @fastaExt);
282 }
283  
284 my $outPrefix="$sketchDir/".basename($fastq, @mshExt);
285 if(-e "$outPrefix.msh"){
286 logmsg "already mashed: $fastq. Skipping.";
287 push(@msh,"$outPrefix.msh");
288 next;
289 }
290  
291 # Do different things depending on fastq vs fasta
292 my $sketchXopts="";
293 if(grep {$_ eq $fileExt} @fastqExt){
294 my $minDepth=determineMinimumDepth($fastq,$$settings{mindepth},$$settings{kmerlength},$settings);
295 $sketchXopts.="-m $minDepth -g $$settings{genomesize} ";
296 } elsif(grep {$_ eq $fileExt} @fastaExt) {
297 $sketchXopts.=" ";
298 } elsif(grep {$_ eq $fileExt} @mshExt){
299 $sketchXopts.=" ";
300 } else {
301 logmsg "WARNING: I could not understand what kind of file this is by its extension ($fileExt): $fastq";
302 }
303
304 # See if the user already mashed this file locally
305 if(-e "$fastq.msh"){
306 logmsg "Found locally mashed file $fastq.msh. I will use it.";
307 copy("$fastq.msh","$outPrefix.msh");
308 }
309 if(grep {$_ eq $fileExt} @mshExt){
310 logmsg "Input file is a sketch file itself and will be used as such: $fastq";
311 copy($fastq, "$outPrefix.msh");
312 }
313  
314 if(-e "$outPrefix.msh"){
315 logmsg "WARNING: ".basename($fastq)." was already mashed.";
316 } elsif(-s $fastq < 1){
317 logmsg "WARNING: $fastq is a zero byte file. Skipping.";
318 next;
319 } else {
320 my $sketchCommand="mash sketch -S $$settings{seed} -k $$settings{kmerlength} -s $$settings{'sketch-size'} $sketchXopts -o \Q$outPrefix\E \Q$fastq\E 2>&1";
321 my $stdout = `$sketchCommand`;
322 if ($?){
323 logmsg "ERROR running $sketchCommand!\n $stdout";
324 die;
325 }
326 }
327  
328 push(@msh,"$outPrefix.msh");
329  
330 # Save sketches into a local directory if requested
331 if($$settings{'save-sketches'}){
332 my $dir=$$settings{'save-sketches'};
333 my $target = "$fastq.msh";
334 if(defined($dir)){
335 mkdir($dir) if(!-e $dir);
336 $target = "$dir/".basename($fastq).".msh";
337 }
338 #try to hard link because this is basically a read-only file,
339 #but if not, copying is fine.
340 link("$outPrefix.msh", $target) || copy("$outPrefix.msh", $target)
341 || die "ERROR hard-linking or copying $outPrefix.msh to $target: $!";
342 }
343 }
344  
345 system("rm -rf $tempdir");
346  
347 return \@msh;
348 }
349  
350 # Parallelized mash distance
351 sub mashDistance{
352 my($mshList,$reads,$outdir,$settings)=@_;
353  
354 # Make a list of names that will appear in the database
355 # in exactly the right format.
356 my @genomeName;
357  
358 # Make a temporary file with one line per mash file.
359 # Helps with not running into the max number of command line args.
360 my $mshListFilename="$outdir/mshList.txt";
361 open(my $mshListFh,">",$mshListFilename) or die "ERROR: could not write to $mshListFilename: $!";
362 for(@$mshList){
363 print $mshListFh $_."\n";
364 push(@genomeName,_truncateFilename($_,$settings));
365 }
366 close $mshListFh;
367  
368 # Instatiate the database and create the table before the threads get to it
369 my $mashtreeDbFilename="$outdir/distances.db.tsv";
370 my $mashtreeDb=Mashtree::Db->new($mashtreeDbFilename,{significant_figures=>$$settings{sigfigs}});
371  
372 # Make an array of distance files for each thread.
373 # Because distance files take about the same amount
374 # of time to analyze, there is no need to sort.
375 my @threadArr=();
376 for(my $i=0; $i<@$mshList; $i++){
377 my $threadIndex = $i % $$settings{numcpus};
378 push(@{ $threadArr[$threadIndex] }, $$mshList[$i]);
379 }
380  
381 # Initialize the threads
382 my @thr;
383 for(0..$$settings{numthreads}-1){
384 $thr[$_]=threads->new(\&mashDist,$outdir,$threadArr[$_],$mshListFilename,$settings);
385 }
386  
387 my $numThreads=@thr;
388 for(my $t=0; $t<@thr; $t++){
389 my $T=$t+1;
390 my $formattedThreadName = "$T/$numThreads, TID".$thr[$t]->tid;
391 logmsg "Waiting to join thread ($formattedThreadName)";
392 my $distHash = $thr[$t]->join; # returns ref to scalar b/c the str could be very large
393  
394 logmsg "Databasing distances ($formattedThreadName)";
395 $mashtreeDb->addDistancesFromHash($distHash);
396 }
397  
398 my $phylip = "$outdir/distances.phylip";
399 logmsg "Converting to phylip format into $phylip";
400 open(my $phylipFh, ">", $phylip) or die "ERROR: could not write to $phylip: $!";
401 print $phylipFh $mashtreeDb->toString(\@genomeName,"phylip");
402 close $phylipFh;
403  
404 if($$settings{outmatrix}){
405 logmsg "Writing a distance matrix to $$settings{outmatrix}";
406 open(my $matrixFh, ">", $$settings{outmatrix}) or die "ERROR: could not write to $$settings{outmatrix}: $!";
407 print $matrixFh $mashtreeDb->toString(\@genomeName,"matrix");
408 close $matrixFh;
409 }
410
411  
412 return $phylip;
413 }
414  
415 # Individual mash distance
416 sub mashDist{
417 my($outdir,$mshArr,$mshList,$settings)=@_;
418  
419 my $numQueries=0;
420 my %dist;
421 for my $msh(@$mshArr){
422 #my $outfile="$outdir/".basename($msh).".tsv";
423 logmsg "Distances for $msh";
424 my $cmd = "mash dist -t \Q$msh\E -l $mshList";
425 my @distRes = `$cmd`;
426 die "ERROR with $cmd" if $?;
427 chomp(@distRes);
428  
429 my $query="";
430 my $queryLine = shift(@distRes);
431 if($queryLine=~/#\s*query\s+(.+)/){
432 $query = _truncateFilename($1);
433 } else {
434 die "ERROR parsing for the query in $queryLine";
435 }
436 for(@distRes){
437 my($hit, $dist)=split /\t/;
438 $hit = _truncateFilename($hit);
439 $dist{$query}{$hit} = $dist;
440 }
441  
442 $numQueries++;
443 }
444 return \%dist;
445 #return \$distStr; # return the reference because the str could be quite large
446 }
447  
448 sub determineMinimumDepth{
449 my($fastq,$mindepth,$kmerlength,$settings)=@_;
450  
451 my $defaultDepth=5; # if no valley is detected
452  
453 return $mindepth if($mindepth > 0);
454  
455 my $basename=basename($fastq,@fastqExt);
456
457 # Run the min abundance finder to find the valleys
458 my $minAbundanceTempdir="$$settings{tempdir}/$basename.minAbundance.tmp";
459 mkdir $minAbundanceTempdir;
460 my $minAbundanceCommand="min_abundance_finder.pl --numcpus $$settings{cpus_per_mash} $fastq --kmer $kmerlength --tempdir $minAbundanceTempdir";
461 #lock($abundanceFinderLock); logmsg "DEBUG: running single mode for $fastq with $$settings{numcpus} cpus in the single thread";
462 my $minKmerCount = `$minAbundanceCommand`;
463 # If there is an error, just try running one at a time.
464 # I am not sure why there is a seg fault sometimes when
465 # more than one are running at the same time though.
466 #if($?){
467 # lock($abundanceFinderLock);
468 # @valleyLines=`$minAbundanceCommand`;
469 #}
470 die "ERROR with min_abundance_finder.pl on $fastq: $!" if($?);
471 chomp($minKmerCount);
472 # Some cleanup of large files
473 # Avoid some weird segfault error associated with the unlink()
474 #unlink $_ for(glob("$minAbundanceTempdir/*"));
475 #rmdir $minAbundanceTempdir;
476 system("rm -rf $minAbundanceTempdir");
477  
478 # If there is no valley, return a default value
479 if(!$minKmerCount){
480 return $defaultDepth;
481 }
482
483 # Set a minimum just in case
484 $minKmerCount=1 if($minKmerCount < 1);
485  
486 logmsg "Setting the min depth as $minKmerCount for $fastq";
487  
488 return $minKmerCount;
489 }
490  
491 sub usage{
492 "$0: use distances from Mash (min-hash algorithm) to make a NJ tree
493 Usage: $0 [options] *.fastq *.fasta *.gbk *.msh > tree.dnd
494 NOTE: fastq files are read as raw reads;
495 fasta, gbk, and embl files are read as assemblies;
496 Input files can be gzipped.
497 --tempdir '' If specified, this directory will not be
498 removed at the end of the script and can
499 be used to cache results for future
500 analyses.
501 If not specified, a dir will be made for you
502 and then deleted at the end of this script.
503 --numcpus 1 This script uses Perl threads.
504 --outmatrix '' If specified, will write a distance matrix
505 in tab-delimited format
506 --file-of-files If specified, mashtree will try to read
507 filenames from each input file. The file of
508 files format is one filename per line. This
509 file of files cannot be compressed.
510 --outtree If specified, the tree will be written to
511 this file and not to stdout. Log messages
512 will still go to stderr.
513 --version Display the version and exit
514 --citation Display the preferred citation and exit
515  
516 TREE OPTIONS
517 --truncLength 250 How many characters to keep in a filename
518 --sigfigs 10 How many decimal places to use in mash distances
519 --sort-order ABC For neighbor-joining, the sort order can
520 make a difference. Options include:
521 ABC (alphabetical), random, input-order
522  
523 MASH SKETCH OPTIONS
524 --genomesize 5000000
525 --mindepth 5 If mindepth is zero, then it will be
526 chosen in a smart but slower method,
527 to discard lower-abundance kmers.
528 --kmerlength 21
529 --sketch-size 10000
530 --seed 42 Seed for mash sketch
531 --save-sketches '' If a directory is supplied, then sketches
532 will be saved in it.
533 If no directory is supplied, then sketches
534 will be saved alongside source files.
535 "
536 }
537  
« lib/Mashtree.pm ↑ Summary