| 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 | use IO::Handle; # allows me to autoflush file handles | ||
| 17 | |||
| 18 | #use Fcntl qw/:flock LOCK_EX LOCK_UN/; | ||
| 19 | |||
| 20 | use threads; | ||
| 21 | use Thread::Queue; | ||
| 22 | use threads::shared; | ||
| 23 | |||
| 24 | use FindBin; | ||
| 25 | use lib "$FindBin::RealBin/../lib"; | ||
| 26 | use Mashtree qw/logmsg @fastqExt @fastaExt createTreeFromPhylip mashDist/; | ||
| 27 | use Mashtree::Db; | ||
| 28 | use Bio::SeqIO; | ||
| 29 | use Bio::TreeIO; | ||
| 30 | use Bio::Tree::DistanceFactory; | ||
| 31 | use Bio::Tree::Statistics; | ||
| 32 | |||
| 33 | my $writeStick :shared; | ||
| 34 | my $readStick :shared; # limit disk IO by reading some files one at a time | ||
| 35 | |||
| 36 | local $0=basename $0; | ||
| 37 | |||
| 38 | exit main(); | ||
| 39 | |||
| 40 | sub main{ | ||
| 41 | my $settings={}; | ||
| 42 | my @wrapperOptions=qw(help file-of-files outmatrix=s tempdir=s reps=i numcpus=i); | ||
| 43 | GetOptions($settings,@wrapperOptions) or die $!; | ||
| 44 | $$settings{reps}//=1; | ||
| 45 | $$settings{numcpus}||=1; | ||
| 46 | die usage() if($$settings{help}); | ||
| 47 | die usage() if(@ARGV < 1); | ||
| 48 | |||
| 49 | $$settings{tempdir}||=tempdir("MASHTREE_BOOTSTRAP.XXXXXX",CLEANUP=>1,TMPDIR=>1); | ||
| 50 | mkdir($$settings{tempdir}) if(!-d $$settings{tempdir}); | ||
| 51 | logmsg "Temporary directory will be $$settings{tempdir}"; | ||
| 52 | |||
| 53 | if($$settings{reps} < 1){ | ||
| 54 | die "ERROR: no reps were given!"; | ||
| 55 | } | ||
| 56 | if($$settings{reps} < 100){ | ||
| 57 | logmsg "WARNING: You have very few reps planned on this mashtree run. Recommended reps are at least 100."; | ||
| 58 | } | ||
| 59 | |||
| 60 | ## Catch some options that are not allowed to be passed | ||
| 61 | # Tempdir: All mashtree temporary directories will be under the | ||
| 62 | # wrapper's tempdir. | ||
| 63 | if(grep(/^\-+tempdir$/,@ARGV) || grep(/^\-+t$/,@ARGV)){ | ||
| 64 | die "ERROR: tempdir was specified for mashtree but should be an option for $0"; | ||
| 65 | } | ||
| 66 | # Numcpus: this needs to be specified in the wrapper and will | ||
| 67 | # appropriately be transferred to the mashtree script | ||
| 68 | if(grep(/^\-+numcpus$/,@ARGV) || grep(/^\-+n$/,@ARGV)){ | ||
| 69 | die "ERROR: numcpus was specified for mashtree but should be an option for $0"; | ||
| 70 | } | ||
| 71 | # Outmatrix: the wrapper script needs to control where | ||
| 72 | # the matrix goes because it can only have the outmatrix | ||
| 73 | # for the observed run and not the replicates for speed's | ||
| 74 | # sake. | ||
| 75 | if(grep(/^\-+outmatrix$/,@ARGV) || grep(/^\-+o$/,@ARGV)){ | ||
| 76 | die "ERROR: outmatrix was specified for mashtree but should be an option for $0"; | ||
| 77 | } | ||
| 78 | # --file-of-files: should be something to give to mashtree directly | ||
| 79 | if(grep(/^\-+file-of-files$/,@ARGV) || grep(/^\-+f$/,@ARGV)){ | ||
| 80 | die "ERROR: file-of-files was specified for mashtree but should be an option for $0"; | ||
| 81 | } | ||
| 82 | |||
| 83 | # Separate flagged options from reads in the mashtree options | ||
| 84 | my @reads = (); | ||
| 85 | my @mashOptions = (); | ||
| 86 | for(my $i=0;$i<@ARGV;$i++){ | ||
| 87 | if(-e $ARGV[$i]){ | ||
| 88 | push(@reads, $ARGV[$i]); | ||
| 89 | } else { | ||
| 90 | push(@mashOptions, $ARGV[$i]); | ||
| 91 | } | ||
| 92 | } | ||
| 93 | if($$settings{'file-of-files'}){ | ||
| 94 | push(@mashOptions, '--file-of-files'); | ||
| 95 | } | ||
| 96 | my $mashOptions=join(" ",@mashOptions); | ||
| 97 | my $reads = join(" ", @reads); | ||
| 98 | |||
| 99 | # Some filenames we'll expect | ||
| 100 | my $observeddir="$$settings{tempdir}/observed"; | ||
| 101 | my $obsDistances="$observeddir/distances.phylip"; | ||
| 102 | my $observedTree="$$settings{tempdir}/observed.dnd"; | ||
| 103 | my $outmatrix="$$settings{tempdir}/observeddistances.tsv"; | ||
| 104 | my $mshList = "$$settings{tempdir}/mash.list"; | ||
| 105 | my $mergedMash = "$$settings{tempdir}/merged.msh"; | ||
| 106 | |||
| 107 | # Make the observed directory and run Mash | ||
| 108 | logmsg "Running mashtree on full data (".scalar(@reads)." targets)"; | ||
| 109 | mkdir($observeddir); | ||
| 110 | system("$FindBin::RealBin/mashtree --outmatrix $outmatrix.tmp --tempdir $observeddir --numcpus $$settings{numcpus} $mashOptions $reads > $observedTree.tmp"); | ||
| 111 | die if $?; | ||
| 112 | mv("$observedTree.tmp",$observedTree) or die $?; | ||
| 113 | mv("$outmatrix.tmp",$outmatrix) or die $?; | ||
| 114 | |||
| 115 | # Round-robin sample the replicate number, so that it's | ||
| 116 | # well-balanced. | ||
| 117 | my @repNumber = (1..$$settings{reps}); | ||
| 118 | my @reps; | ||
| 119 | for(my $i=0;$i<$$settings{reps};$i++){ | ||
| 120 | my $thrIndex = $i % $$settings{numcpus}; | ||
| 121 | push(@{$reps[$thrIndex]}, $i); | ||
| 122 | } | ||
| 123 | |||
| 124 | # Sample the mash sketches with replacement for rapid bootstrapping | ||
| 125 | logmsg "Running mashtree single-threaded among $$settings{reps} replicates using $$settings{numcpus} total threads."; | ||
| 126 | my @bsThread; | ||
| 127 | for my $i(0..$$settings{numcpus}-1){ | ||
| 128 | my %settingsCopy = %$settings; | ||
| 129 | $bsThread[$i] = threads->new(\&mashtreeRepWorker, $reps[$i], $reads, $mashOptions, \%settingsCopy); | ||
| 130 | } | ||
| 131 | |||
| 132 | my @bsTree; | ||
| 133 | for my $t(@bsThread){ | ||
| 134 | my $treeArr = $t->join; | ||
| 135 | for my $file(@$treeArr){ | ||
| 136 | my $treein = Bio::TreeIO->new(-file=>$file); | ||
| 137 | while(my $tree=$treein->next_tree){ | ||
| 138 | push(@bsTree, $tree); | ||
| 139 | } | ||
| 140 | } | ||
| 141 | } | ||
| 142 | |||
| 143 | # Combine trees into a bootstrapped tree and write it | ||
| 144 | # to an output file. Then print it to stdout. | ||
| 145 | logmsg "Adding bootstraps to tree"; | ||
| 146 | my $guideTree=Bio::TreeIO->new(-file=>"$observeddir/tree.dnd")->next_tree; | ||
| 147 | my $bsTree=assess_bootstrap($guideTree,\@bsTree,$guideTree); | ||
| 148 | for my $node($bsTree->get_nodes){ | ||
| 149 | next if($node->is_Leaf); | ||
| 150 | my $id=$node->bootstrap||$node->id||0; | ||
| 151 | $node->id($id); | ||
| 152 | } | ||
| 153 | open(my $treeFh,">","$$settings{tempdir}/bstree.dnd") or die "ERROR: could not write to $$settings{tempdir}/bstree.dnd: $!"; | ||
| 154 | print $treeFh $bsTree->as_text('newick'); | ||
| 155 | print $treeFh "\n"; | ||
| 156 | close $treeFh; | ||
| 157 | |||
| 158 | system("cat $$settings{tempdir}/bstree.dnd"); die if $?; | ||
| 159 | |||
| 160 | if($$settings{'outmatrix'}){ | ||
| 161 | cp($outmatrix,$$settings{'outmatrix'}); | ||
| 162 | } | ||
| 163 | |||
| 164 | return 0; | ||
| 165 | } | ||
| 166 | |||
| 167 | sub mashtreeRepWorker{ | ||
| 168 | my($reps, $reads, $mashtreeOptions, $settings) = @_; | ||
| 169 | |||
| 170 | my @tree; | ||
| 171 | my $largeInt = ~0; | ||
| 172 | |||
| 173 | for my $rep(@$reps){ | ||
| 174 | logmsg "Rep $rep"; | ||
| 175 | my $tempdir = $$settings{tempdir}."/$rep"; | ||
| 176 | my $seed = int(rand(4.29497e+09)); # apparently 4.29497e+09 is the largest int for mash sketch | ||
| 177 | my $repMashtreeOptions = $mashtreeOptions . " --seed $seed"; | ||
| 178 | my $stdout = `$FindBin::RealBin/mashtree --tempdir $tempdir --numcpus 1 $repMashtreeOptions $reads 2>&1`; | ||
| 179 | die "ERROR on rep $rep\n$stdout" if $?; | ||
| 180 | |||
| 181 | push(@tree, "$$settings{tempdir}/$rep/tree.dnd"); | ||
| 182 | } | ||
| 183 | |||
| 184 | return \@tree; | ||
| 185 | } | ||
| 186 | |||
| 187 | |||
| 188 | # Fixed bootstrapping function from bioperl | ||
| 189 | # https://github.com/bioperl/bioperl-live/pull/304 | ||
| 190 | sub assess_bootstrap{ | ||
| 191 | my ($self,$bs_trees,$guide_tree) = @_; | ||
| 192 | my @consensus; | ||
| 193 | |||
| 194 | if(!defined($bs_trees) || ref($bs_trees) ne 'ARRAY'){ | ||
| 195 | die "ERROR: second parameter in assess_bootstrap() must be a list"; | ||
| 196 | } | ||
| 197 | my $num_bs_trees = scalar(@$bs_trees); | ||
| 198 | if($num_bs_trees < 1){ | ||
| 199 | die "ERROR: no bootstrap trees were passed to assess_bootstrap()"; | ||
| 200 | } | ||
| 201 | |||
| 202 | # internal nodes are defined by their children | ||
| 203 | |||
| 204 | my (%lookup,%internal); | ||
| 205 | my $i = 0; | ||
| 206 | for my $tree ( $guide_tree, @$bs_trees ) { | ||
| 207 | # Do this as a top down approach, can probably be | ||
| 208 | # improved by caching internal node states, but not going | ||
| 209 | # to worry about it right now. | ||
| 210 | |||
| 211 | my @allnodes = $tree->get_nodes; | ||
| 212 | my @internalnodes = grep { ! $_->is_Leaf } @allnodes; | ||
| 213 | for my $node ( @internalnodes ) { | ||
| 214 | my @tips = sort map { $_->id } | ||
| 215 | grep { $_->is_Leaf() } $node->get_all_Descendents; | ||
| 216 | my $id = "(".join(",", @tips).")"; | ||
| 217 | if( $i == 0 ) { | ||
| 218 | $internal{$id} = $node->internal_id; | ||
| 219 | } else { | ||
| 220 | $lookup{$id}++; | ||
| 221 | } | ||
| 222 | } | ||
| 223 | $i++; | ||
| 224 | } | ||
| 225 | #my @save; # unsure why this variable is needed | ||
| 226 | for my $l ( keys %lookup ) { | ||
| 227 | if( defined $internal{$l} ) {#&& $lookup{$l} > $min_seen ) { | ||
| 228 | my $intnode = $guide_tree->find_node(-internal_id => $internal{$l}); | ||
| 229 | $intnode->bootstrap(sprintf("%d",100 * $lookup{$l} / $num_bs_trees)); | ||
| 230 | } | ||
| 231 | } | ||
| 232 | return $guide_tree; | ||
| 233 | } | ||
| 234 | |||
| 235 | ####### | ||
| 236 | # Utils | ||
| 237 | ####### | ||
| 238 | |||
| 239 | sub usage{ | ||
| 240 | my $usage="$0: a wrapper around mashtree for bootstrapping. | ||
| 241 | Usage: $0 [options] [-- mashtree options] *.fastq.gz *.fasta > tree.dnd | ||
| 242 | --outmatrix '' Output file for distance matrix | ||
| 243 | --reps 0 How many bootstrap repetitions to run; | ||
| 244 | If zero, no bootstrapping. | ||
| 245 | --numcpus 1 This will be passed to mashtree and will | ||
| 246 | be used to multithread reps. | ||
| 247 | --tempdir A directory path that will be created to | ||
| 248 | store temporary files | ||
| 249 | |||
| 250 | --file-of-files If specified, mashtree will try to read | ||
| 251 | filenames from each input file. The file of | ||
| 252 | files format is one filename per line. This | ||
| 253 | file of files cannot be compressed. | ||
| 254 | |||
| 255 | -- Used to separate options for $0 and mashtree | ||
| 256 | MASHTREE OPTIONS:\n". | ||
| 257 | # Print the mashtree options starting with numcpus, | ||
| 258 | # skipping the tempdir option. | ||
| 259 | `mashtree --help 2>&1 | grep -A 999 "TREE OPTIONS" | grep -v ^Stopped`; | ||
| 260 | |||
| 261 | return $usage; | ||
| 262 | } | ||
| 263 |