blib/script/mashtree_jackknife.pl untested

filter: Statementstmt 0.0% 0 / 290 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 45 MC/DCmcdc 0.0% 0 / 25 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 445 CC 28 SCAR 52.2
CC
28
Cov
0%
main
462.0
assess_bootstrap
30.0
subsampleMashSketchesWorker
20.0
CRAP 184.8
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 use strict;
7 use warnings;
8 use Data::Dumper;
9 use Getopt::Long;
10 use File::Temp qw/tempdir tempfile/;
11 use File::Basename qw/basename dirname fileparse/;
12 use File::Copy qw/cp mv/;
13 use List::Util qw/shuffle/;
14 use List::MoreUtils qw/part/;
15 use POSIX qw/floor/;
16 # if JSON::XS is installed, it will be automatically used.
17 # Specify () so that no functions are exported. We will use OO.
18 use JSON ();
19 use IO::Handle; # allows me to autoflush file handles
20  
21 #use Fcntl qw/:flock LOCK_EX LOCK_UN/;
22  
23 use threads;
24 use Thread::Queue;
25 use threads::shared;
26  
27 use FindBin;
28 use lib "$FindBin::RealBin/../lib";
29 use Mashtree qw/logmsg @fastqExt @fastaExt createTreeFromPhylip mashDist/;
30 use Mashtree::Db;
31 use Bio::SeqIO;
32 use Bio::TreeIO;
33 use Bio::Tree::DistanceFactory;
34 use Bio::Tree::Statistics;
35  
36 my $writeStick :shared;
37 my $readStick :shared; # limit disk IO by reading some files one at a time
38  
39 local $0=basename $0;
40  
41 exit main();
42  
43 sub main{
44 my $settings={};
45 my @wrapperOptions=qw(help file-of-files outmatrix=s tempdir=s reps=i numcpus=i);
46 GetOptions($settings,@wrapperOptions) or die $!;
47 $$settings{reps}//=1;
48 $$settings{numcpus}||=1;
49 die usage() if($$settings{help});
50 die usage() if(@ARGV < 1);
51  
52 $$settings{tempdir}||=tempdir("MASHTREE_WRAPPER.XXXXXX",CLEANUP=>1,TMPDIR=>1);
53 mkdir($$settings{tempdir}) if(!-d $$settings{tempdir});
54 logmsg "Temporary directory will be $$settings{tempdir}";
55  
56 if($$settings{reps} < 1){
57 die "ERROR: no reps were given!";
58 }
59 if($$settings{reps} < 100){
60 logmsg "WARNING: You have very few reps planned on this mashtree run. Recommended reps are at least 100.";
61 }
62 # Give a warning if JSON is going to be slow later
63 my $jsonTmp = JSON->new();
64 if(! $jsonTmp->is_xs){
65 logmsg "WARNING: the currently installed JSON module will make this script very slow when jack knifing. To avoid this error, install the JSON::XS module like so: `cpanm ~l ~ JSON::XS`.";
66 }
67
68 ## Catch some options that are not allowed to be passed
69 # Tempdir: All mashtree temporary directories will be under the
70 # wrapper's tempdir.
71 if(grep(/^\-+tempdir$/,@ARGV) || grep(/^\-+t$/,@ARGV)){
72 die "ERROR: tempdir was specified for mashtree but should be an option for $0";
73 }
74 # Numcpus: this needs to be specified in the wrapper and will
75 # appropriately be transferred to the mashtree script
76 if(grep(/^\-+numcpus$/,@ARGV) || grep(/^\-+n$/,@ARGV)){
77 die "ERROR: numcpus was specified for mashtree but should be an option for $0";
78 }
79 # Outmatrix: the wrapper script needs to control where
80 # the matrix goes because it can only have the outmatrix
81 # for the observed run and not the replicates for speed's
82 # sake.
83 if(grep(/^\-+outmatrix$/,@ARGV) || grep(/^\-+o$/,@ARGV)){
84 die "ERROR: outmatrix was specified for mashtree but should be an option for $0";
85 }
86 # --file-of-files: should be something to give to mashtree directly
87 if(grep(/^\-+file-of-files$/,@ARGV) || grep(/^\-+f$/,@ARGV)){
88 die "ERROR: file-of-files was specified for mashtree but should be an option for $0";
89 }
90
91 # Separate flagged options from reads in the mashtree options
92 my @reads = ();
93 my @mashOptions = ();
94 for(my $i=0;$i<@ARGV;$i++){
95 if(-e $ARGV[$i]){
96 push(@reads, $ARGV[$i]);
97 } else {
98 push(@mashOptions, $ARGV[$i]);
99 }
100 }
101 if($$settings{'file-of-files'}){
102 push(@mashOptions, '--file-of-files');
103 }
104 my $mashOptions=join(" ",@mashOptions);
105 my $reads = join(" ", @reads);
106
107 # Some filenames we'll expect
108 my $observeddir="$$settings{tempdir}/observed";
109 my $obsDistances="$observeddir/distances.phylip";
110 my $observedTree="$$settings{tempdir}/observed.dnd";
111 my $outmatrix="$$settings{tempdir}/observeddistances.tsv";
112 my $mshList = "$$settings{tempdir}/mash.list";
113 my $mergedMash = "$$settings{tempdir}/merged.msh";
114 my $mergedJSON = "$$settings{tempdir}/merged.msh.json.gz";
115  
116 # Make the observed directory and run Mash
117 logmsg "Running mashtree on full data (".scalar(@reads)." targets)";
118 mkdir($observeddir);
119 system("$FindBin::RealBin/mashtree --outmatrix $outmatrix.tmp --tempdir $observeddir --numcpus $$settings{numcpus} $mashOptions $reads > $observedTree.tmp");
120 die if $?;
121 mv("$observedTree.tmp",$observedTree) or die $?;
122 mv("$outmatrix.tmp",$outmatrix) or die $?;
123  
124 # Merge the mash files to make the threads go faster later
125 my @msh = glob("$observeddir/*.msh");
126 open(my $mshListFh, ">", $mshList) or die "ERROR writing to mash list $mshList: $!";
127 for(@msh){
128 print $mshListFh $_."\n";
129 }
130 close $mshListFh;
131 unlink($mergedMash) if(-e $mergedMash); # mash complains about overwriting an existing file
132 system("mash paste -l $mergedMash $mshList >&2"); die "ERROR merging mash files" if $?;
133 # max compression on the json file so that it can be a
134 # smaller footprint and so that it can be read faster
135 # in each thread.
136 system("mash info -d $mergedMash | gzip -c9 > $mergedJSON");
137 die "ERROR with mash info | gzip -c9" if $?;
138 unlink($_) for(@msh); # remove redundant files to the merged msh
139
140 # Round-robin sample the replicate number, so that it's
141 # well-balanced.
142 my @repNumber = (1..$$settings{reps});
143 my @reps;
144 for(my $i=0;$i<$$settings{reps};$i++){
145 my $thrIndex = $i % $$settings{numcpus};
146 push(@{$reps[$thrIndex]}, $i);
147 }
148  
149 # Sample the mash sketches with replacement for rapid bootstrapping
150 my @bsThread;
151 for my $i(0..$$settings{numcpus}-1){
152 my %settingsCopy = %$settings;
153 $bsThread[$i] = threads->new(\&subsampleMashSketchesWorker, $mergedJSON, $reps[$i], \%settingsCopy);
154 }
155  
156 my @bsTree;
157 for my $thr(@bsThread){
158 my $fileArr = $thr->join;
159 if(ref($fileArr) ne 'ARRAY'){
160 die "ERROR: one or more threads did not return an array of jack knife tree files as expected.";
161 }
162 for my $file(@$fileArr){
163 my $treein = Bio::TreeIO->new(-file=>$file);
164 while(my $tree=$treein->next_tree){
165 push(@bsTree, $tree);
166 }
167 }
168 }
169
170 # Combine trees into a bootstrapped tree and write it
171 # to an output file. Then print it to stdout.
172 logmsg "Adding bootstraps to tree";
173 my $guideTree=Bio::TreeIO->new(-file=>"$observeddir/tree.dnd")->next_tree;
174 my $bsTree=assess_bootstrap($guideTree,\@bsTree,$guideTree);
175 for my $node($bsTree->get_nodes){
176 next if($node->is_Leaf);
177 my $id=$node->bootstrap||$node->id||0;
178 $node->id($id);
179 }
180 open(my $treeFh,">","$$settings{tempdir}/bstree.dnd") or die "ERROR: could not write to $$settings{tempdir}/bstree.dnd: $!";
181 print $treeFh $bsTree->as_text('newick');
182 print $treeFh "\n";
183 close $treeFh;
184  
185 system("cat $$settings{tempdir}/bstree.dnd"); die if $?;
186  
187 if($$settings{'outmatrix'}){
188 cp($outmatrix,$$settings{'outmatrix'});
189 }
190
191 return 0;
192 }
193  
194 sub subsampleMashSketchesWorker{
195 my($mergedJSON, $reps, $settings) = @_;
196 $reps //= [];
197  
198 my @treeFile;
199 return \@treeFile if(@$reps <1);
200  
201 # Initialize our JSON reader
202 my $json = JSON->new;
203 $json->utf8; # If we only expect characters 0..255. Makes it fast.
204 $json->allow_nonref; # can convert a non-reference into its corresponding string
205 $json->allow_blessed; # encode method will not barf when it encounters a blessed reference
206 $json->pretty; # enables indent, space_before and space_after
207 # Only let one thread at a time read the large JSON file
208 my $mashInfoStr=""; # must be declared outside of the block because we are parsing it after the block
209 {
210 lock($readStick);
211 logmsg "Reading huge JSON file describing all mash distances, $mergedJSON";
212 $mashInfoStr = `gzip -cd $mergedJSON`;
213 die "ERROR running gzip -cd $mergedJSON: $!" if $?;
214 }
215 my $mashInfoHash = $json->decode($mashInfoStr);
216 $mashInfoStr=""; # clear some ram
217 my $kmerlength = $$mashInfoHash{kmer}; # find the kmer length right away
218  
219 my $numReps = @$reps;
220 my $numSketches = scalar(@{ $$mashInfoHash{sketches} });
221 my $msg="Initializing thread with $numReps replicates: ";
222 for my $i(0..2){
223 my $repID = $$reps[$i] // "";
224 $msg.="$repID, ";
225 }
226 $msg=~s/[ ,]+$//; # right trim
227 if($numReps > 3){
228 $msg.="...";
229 }
230 logmsg $msg;
231 for(my $repI=0;$repI<@$reps;$repI++){
232 my $rep = $$reps[$repI];
233  
234 my $subsampleDir = "$$settings{tempdir}/rep$rep";
235 mkdir $subsampleDir;
236 my $log = "$subsampleDir/jackknife.log";
237 open(my $logFh, ">", $log) or die "ERROR: cannot write to log $log: $!";
238 $logFh->autoflush();
239 logmsg "rep$rep: $subsampleDir (".($repI+1)." out of $numReps in this thread)";
240  
241 my @name;
242 # Start off a distances string for printing to file later
243 my %dist = ();
244 for(my $sketchCounter=0; $sketchCounter<$numSketches; $sketchCounter++){
245 my $nameI = basename($$mashInfoHash{sketches}[$sketchCounter]{name},(@fastqExt,@fastaExt));
246 print $logFh "Subsampling sketches from entry $sketchCounter, $nameI\n";
247  
248 # subsample the hashes of one genome at a time as compared
249 # to the other genomes, to get a jack knife distance.
250 my $numHashes = scalar(@{ $$mashInfoHash{sketches}[$sketchCounter]{hashes} });
251 my $keepHashes = int($numHashes / 2); # based on half the hashes
252 my @subsampleHash = @{ $$mashInfoHash{sketches}[$sketchCounter]{hashes} };
253 @subsampleHash = (shuffle(@subsampleHash))[0..$keepHashes-1];
254 @subsampleHash = sort{$a<=>$b} @subsampleHash;
255  
256 print $logFh "Distances between $nameI and other genomes";
257 # Initialize the distances string with the query name.
258 # Use this string as a buffer for the distances file
259 # to help avoid too much disk IO.
260 push(@name, $nameI);
261 for(my $j=0; $j<$numSketches; $j++){
262 my $nameJ = basename($$mashInfoHash{sketches}[$j]{name},(@fastqExt,@fastaExt));
263 my $distance = mashDist(\@subsampleHash, $$mashInfoHash{sketches}[$j]{hashes}, $kmerlength);
264 $dist{$nameI}{$nameJ} = $distance;
265 print $logFh ".";
266 }
267 print $logFh "\n";
268 }
269  
270 # Add distances to database
271 print $logFh "Creating database, $subsampleDir/distances.db.tsv\n";
272 my $mashtreeDb = Mashtree::Db->new("$subsampleDir/distances.db.tsv");
273 $mashtreeDb->addDistancesFromHash(\%dist);
274 # Convert to Phylip
275 my $phylipFile = "$subsampleDir/distances.phylip";
276 print $logFh "Creating phylip file, $phylipFile\n";
277 open(my $phylipFh, ">", $phylipFile) or die "ERROR: could not write to $phylipFile: $!";
278 print $phylipFh $mashtreeDb->toString(\@name, "phylip");
279 close $phylipFh;
280  
281 print $logFh "Creating tree file, $subsampleDir/tree.dnd\n";
282 my $treeObj = createTreeFromPhylip($phylipFile, $subsampleDir, $settings);
283 push(@treeFile, "$subsampleDir/tree.dnd");
284  
285 print $logFh "DONE!\n";
286 close $logFh;
287 }
288  
289 return \@treeFile;
290 }
291  
292 # Fixed bootstrapping function from bioperl
293 # https://github.com/bioperl/bioperl-live/pull/304
294 sub assess_bootstrap{
295 my ($self,$bs_trees,$guide_tree) = @_;
296 my @consensus;
297  
298 if(!defined($bs_trees) || ref($bs_trees) ne 'ARRAY'){
299 die "ERROR: second parameter in assess_bootstrap() must be a list";
300 }
301 my $num_bs_trees = scalar(@$bs_trees);
302 if($num_bs_trees < 1){
303 die "ERROR: no bootstrap trees were passed to assess_bootstrap()";
304 }
305  
306 # internal nodes are defined by their children
307  
308 my (%lookup,%internal);
309 my $i = 0;
310 for my $tree ( $guide_tree, @$bs_trees ) {
311 # Do this as a top down approach, can probably be
312 # improved by caching internal node states, but not going
313 # to worry about it right now.
314  
315 my @allnodes = $tree->get_nodes;
316 my @internalnodes = grep { ! $_->is_Leaf } @allnodes;
317 for my $node ( @internalnodes ) {
318 my @tips = sort map { $_->id }
319 grep { $_->is_Leaf() } $node->get_all_Descendents;
320 my $id = "(".join(",", @tips).")";
321 if( $i == 0 ) {
322 $internal{$id} = $node->internal_id;
323 } else {
324 $lookup{$id}++;
325 }
326 }
327 $i++;
328 }
329 #my @save; # unsure why this variable is needed
330 for my $l ( keys %lookup ) {
331 if( defined $internal{$l} ) {#&& $lookup{$l} > $min_seen ) {
332 my $intnode = $guide_tree->find_node(-internal_id => $internal{$l});
333 $intnode->bootstrap(sprintf("%d",100 * $lookup{$l} / $num_bs_trees));
334 }
335 }
336 return $guide_tree;
337 }
338  
339 #######
340 # Utils
341 #######
342  
343 sub usage{
344 my $usage="$0: a wrapper around mashtree.
345 Usage: $0 [options] [-- mashtree options] *.fastq.gz *.fasta > tree.dnd
346 --outmatrix '' Output file for distance matrix
347 --reps 0 How many bootstrap repetitions to run;
348 If zero, no bootstrapping.
349 --numcpus 1 This will be passed to mashtree and will
350 be used to multithread reps.
351 --tempdir A directory path that will be created to
352 store temporary files
353 --file-of-files If specified, mashtree will try to read
354 filenames from each input file. The file of
355 files format is one filename per line. This
356 file of files cannot be compressed.
357
358 -- Used to separate options for $0 and mashtree
359 MASHTREE OPTIONS:\n".
360 # Print the mashtree options starting with numcpus,
361 # skipping the tempdir option.
362 `mashtree --help 2>&1 | grep -A 999 "TREE OPTIONS" | grep -v ^Stopped`;
363  
364 return $usage;
365 }
366