blib/lib/Bio/Sketch/Mash.pm untested

filter: Statementstmt 0.0% 0 / 169 Branchbran 0.0% 0 / 30 Conditioncond 0.0% 0 / 26 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 271 CC 16 SCAR 30.2
CC
16
Cov
0%
raw_mash_distance
72.0
new
12.0
loadJson
12.0
CRAP 20.5
1 #!/usr/bin/env perl
2 package Bio::Sketch::Mash;
3 use strict;
4 use warnings;
5 use Class::Interface qw/implements/;
6 use Exporter qw(import);
7 use File::Basename qw/fileparse basename dirname/;
8 use Data::Dumper;
9  
10 use JSON ();
11 use Encode qw/encode decode/;
12  
13 &implements( 'Bio::Sketch' );
14  
15 our $VERSION = 0.9;
16  
17 our @EXPORT_OK = qw(raw_mash_distance);
18  
19 local $0=basename $0;
20  
21 # If this is used in a scalar context, $self->toString() is called
22 use overload '""' => 'toString';
23  
24 # These functions are unimplemented but have to be
25 # listed because of the interface.
26 sub sketch{
27 ...;
28 }
29 sub paste{
30 ...;
31 }
32  
33 =pod
34  
35 =head1 NAME
36  
37 Bio::Sketch::Mash
38  
39 =head1 SYNOPSIS
40  
41 A module to read `mash info` output and transform it
42  
43 use strict;
44 use warnings;
45 use Bio::Sketch::Mash;
46  
47 # Sketch all fastq files into one mash file.
48 # Mash sketching is not implemented in this module.
49 system("mash sketch *.fastq.gz > all.msh");
50 die if $?;
51  
52 # Read the mash file.
53 my $msh = Bio::Sketch::Mash->new("all.msh");
54 # All-vs-all distances
55 my $distHash = $msh->dist($msh);
56  
57 # Read a mash file, write it to a json-formatted file
58 my $msh2 = Bio::Sketch::Mash->new("all.msh");
59 $msh2->writeJson("all.json");
60 # Read the json file
61 my $mashJson = Bio::Sketch::Mash->new("all.json");
62 my $dist = $msh2->dist($mashJson); # yields a zero distance
63  
64 =head1 DESCRIPTION
65  
66 This is a module to read mash files produced by the Mash executable. For more information on Mash, see L<mash.readthedocs.org>. This module is capable of reading mash files. Future versions will read/write mash files.
67  
68 =head1 METHODS
69  
70 =over
71  
72 =item Bio::Sketch::Mash->new("filename.msh",\%options);
73  
74 Create a new instance of Bio::Sketch::Mash. One object per set of files.
75  
76 Arguments: Sketch filename (valid types/extensions are .msh, .json, .json.gz)
77 Hash of options (none so far)
78 Returns: Bio::Sketch::Mash object
79  
80 =back
81  
82 =cut
83  
84 sub new{
85 my($class,$filename,$settings)=@_;
86  
87 my $self={
88 file => $filename,
89 kmer => -1, # eg, 21
90 preserveCase=>-1,# eg, false
91 alphabet => "", # eg, AGCT
92 canonical => -1, # eg, true/false
93 sketchSize=> -1, # eg, 1000
94 hashType => "", # eg, "MurmurHash3_x64_128"
95 hashBits => -1, # eg, 64
96 hashSeed => -1, # eg, 42
97 sketches => [], # Array of hashes. Each hash has keys
98 # name => original filename
99 # length => integer of estimated genome size
100 # comment => string description
101 # hashes => list of integers
102 };
103 bless($self,$class);
104  
105 if(!defined($filename)){
106 die "ERROR: no file was given to ".$class."->new";
107 return {};
108 }
109 if(!-e $filename){
110 die "ERROR: could not find file $filename";
111 }
112  
113 $self->loadMsh($filename)
114 or $self->loadJson($filename)
115 or die "ERROR: could not load $filename as either msh or json";
116  
117 return $self;
118 }
119  
120  
121 =pod
122  
123 =over
124  
125 =item $msh->loadMsh("filename.msh")
126  
127 Changes which file is used in the object and updates internal object information. This method is ordinarily used internally only.
128  
129 Arguments: One mash file
130 Returns: self
131  
132 =back
133  
134 =cut
135  
136 sub loadMsh{
137 my($self,$msh)=@_;
138
139 my $json=JSON->new;
140 $json->utf8; # If we only expect characters 0..255. Makes it fast.
141 $json->allow_nonref; # can convert a non-reference into its corresponding string
142 $json->allow_blessed; # encode method will not barf when it encounters a blessed reference
143 $json->pretty; # enables indent, space_before and space_after
144  
145 my $jsonStr = `mash info -d $msh 2>/dev/null`;
146 #die "ERROR running mash on $msh" if $?;
147 if($?){
148 return 0;
149 }
150  
151 # Need to check for valid utf8 or not
152 eval{ my $strCopy=$jsonStr; decode('utf8', $strCopy, Encode::FB_CROAK) }
153 or die "ERROR: mash info -d yielded non-utf8 characters for this file: $msh\nContents shown below:\n$jsonStr\n";
154  
155 my $mashInfo = $json->decode($jsonStr);
156  
157 for my $key(qw(kmer preserveCase alphabet canonical sketchSize hashType hashBits hashSeed sketches)){
158 $$self{$key} = $$mashInfo{$key};
159 }
160
161 return $self;
162 }
163  
164 =pod
165  
166 =over
167  
168 =item $msh->loadJson("filename.msh")
169  
170 Changes which file is used in the object and updates internal object information. This method is ordinarily used internally only.
171  
172 Arguments: One JSON file describing a Mash sketch
173 Returns: self
174  
175 =back
176  
177 =cut
178  
179 sub loadJson{
180 my($self,$filename)=@_;
181
182 my $json=JSON->new;
183 $json->utf8; # If we only expect characters 0..255. Makes it fast.
184 $json->allow_nonref; # can convert a non-reference into its corresponding string
185 $json->allow_blessed; # encode method will not barf when it encounters a blessed reference
186 $json->pretty; # enables indent, space_before and space_after
187  
188 my $jsonStr="";
189 my $fh;
190 if($filename=~/\.gz$/i){
191 open($fh, "gzip -cd '$filename' |") or die "ERROR: could not gzip -cd $filename: $!";
192 } else {
193 open($fh, $filename) or die "ERROR: could not read $filename: $!";
194 }
195 while(<$fh>){
196 $jsonStr.=$_;
197 }
198 close $fh;
199  
200 # Need to check for valid utf8 or not
201 eval{ my $strCopy=$jsonStr; decode('utf8', $strCopy, Encode::FB_CROAK) }
202 or die "ERROR: this file has non-utf8 characters: $filename";
203  
204 my $mashInfo = eval{
205 $json->decode($jsonStr);
206 };
207 if($@){
208 return 0;
209 }
210  
211 for my $key(qw(kmer preserveCase alphabet canonical sketchSize hashType hashBits hashSeed sketches)){
212 $$self{$key} = $$mashInfo{$key};
213 }
214  
215 return $self;
216 }
217  
218 =pod
219  
220 =over
221  
222 =item $msh->writeJson("filename.json")
223  
224 Writes contents to a file in JSON format
225  
226 Arguments: One filename
227 Returns: self
228  
229 =back
230  
231 =cut
232  
233 sub writeJson{
234 my($self, $filename) = @_;
235  
236 my $json=JSON->new;
237 $json->utf8; # If we only expect characters 0..255. Makes it fast.
238 $json->allow_nonref; # can convert a non-reference into its corresponding string
239 $json->allow_blessed; # encode method will not barf when it encounters a blessed reference
240 $json->pretty; # enables indent, space_before and space_after
241
242 my $hash={};
243 for my $key(qw(kmer preserveCase alphabet canonical sketchSize hashType hashBits hashSeed sketches)){
244 $$hash{$key} = $$self{$key};
245 }
246  
247 my $fh;
248 if($filename=~/\.gz$/){
249 open($fh, " | gzip -c > $filename") or die "ERROR: could not write gzipped contents to $filename: $!";
250 } else {
251 open($fh, ">", $filename) or die "ERROR: could not write to $filename: $!";
252 }
253 print $fh $json->encode($hash);
254 close $fh;
255  
256 return $self;
257 }
258  
259 =pod
260  
261 =over
262  
263 =item $msh->dist($msh2)
264  
265 Returns a hash describing distances between sketches represented by
266 this object and another object. If there are multiple sketches per
267 object, then all sketches in this object will be compared against
268 all sketches in the other object.
269  
270 Arguments: One Bio::Sketch::Mash object
271 Returns: reference to a hash of hashes. Each value is a number.
272  
273 Aliases: distance(), mashDist()
274  
275 =back
276  
277 =cut
278  
279 sub dist{
280 my($self, $other)=@_;
281 my %dist = ();
282  
283 my $k = $$self{kmer};
284  
285 # TODO check class of $other
286  
287 my $numFromSketches = scalar(@{ $self->{sketches} });
288 my $numToSketches = scalar(@{ $other->{sketches} });
289  
290 for(my $i=0; $i<$numFromSketches; $i++){
291 my $fromHashes = $$self{sketches}[$i]{hashes};
292 my $fromName = $$self{sketches}[$i]{name};
293 for(my $j=0; $j<$numToSketches; $j++){
294 my $toHashes = $$other{sketches}[$j]{hashes};
295 my $toName = $$other{sketches}[$j]{name};
296  
297 my ($common, $total) = raw_mash_distance($fromHashes, $toHashes);
298 if($total == 0){
299 die "Internal error: total kmers compared between $fromName and $toName were zero!";
300 }
301 my $jaccard = $common/$total;
302 my $mashDist = 0; # by default
303 if($jaccard > 0){
304 $mashDist= -1/$k * log(2*$jaccard / (1+$jaccard));
305 }
306 $mashDist = sprintf("%0.7f", $mashDist); # rounding to maintain compatibility with exec
307 $dist{$fromName}{$toName} = $mashDist;
308 $dist{$toName}{$fromName} = $mashDist;
309 }
310 }
311 return \%dist;
312 }
313 # Some aliases for dist()
314 sub distance{
315 goto &dist;
316 }
317 sub mashDist{
318 goto &dist;
319 }
320  
321 =pod
322  
323 =over
324  
325 =item Bio::Sketch::Mash::raw_mash_distance($array1, $array2)
326  
327 Returns the number of sketches in common and the total number of sketches between two lists.
328 The return type is an array of two elements.
329 This function is used internally with $msh->dist and assumes that the
330 hashes are already sorted.
331  
332 Arguments: A list of integers
333 A list of integers
334 Returns: (countOfInCommon, totalNumber)
335  
336 Example:
337
338 my $R1 = [1,2,3];
339 my $R2 = [1,2,4];
340 my($common, $total) = Bio::Sketch::Mash::raw_mash_distance($R1,$R2);
341 # $common => 2
342 # $total => 3
343  
344 =back
345  
346 =cut
347  
348 # https://github.com/onecodex/finch-rs/blob/master/src/distance.rs#L34
349 sub raw_mash_distance{
350 my($hashes1, $hashes2) = @_;
351  
352 my $i = 0;
353 my $j = 0;
354 my $common = 0;
355 my $total = 0;
356  
357 my $sketch_size = @$hashes1;
358 my $sketch_size2= @$hashes2;
359 while($total < $sketch_size && $i < $sketch_size && $j < $sketch_size2){
360  
361 if($$hashes1[$i] < $$hashes2[$j]){
362 $i+=1;
363 } elsif($$hashes1[$i] > $$hashes2[$j]){
364 $j+=1;
365 } elsif($$hashes1[$i] == $$hashes2[$j]){
366 $i+=1;
367 $j+=1;
368 $common+=1;
369 }
370  
371 $total += 1;
372 }
373  
374 #if($total < $sketch_size){
375 if($total < $sketch_size || $total < $sketch_size2){
376 if($i < $sketch_size){
377 $total += $sketch_size - 1;
378 }
379  
380 if($j < $sketch_size2){
381 $total += $sketch_size2 - 1;
382 }
383  
384 if($total > $sketch_size){
385 $total = $sketch_size;
386 }
387 }
388  
389 return ($common, $total);
390 }
391  
392 =pod
393  
394 =over
395  
396 =item $msh->fix()
397  
398 Fixes a mash sketch if it is broken at all. For now this
399 just sorts hashes but this subroutine could contain more
400 fixes in the future.
401  
402 Arguments: None
403 Returns: $self
404  
405 =back
406  
407 =cut
408  
409 sub fix{
410 my($self) = @_;
411  
412 for my $sketches(@{ $self->{sketches} }){
413 my @sortedHashes = sort {$a <=> $b} @{ $$sketches{hashes} };
414 $$sketches{hashes} = \@sortedHashes;
415 }
416  
417 return $self;
418 }
419  
420 ##### Utility methods
421  
422 sub toString{
423 my($self)=@_;
424 my $return="Bio::Sketch::Mash object with " .scalar(@{ $self->{sketches} })." file(s):\n";
425 for my $sketch(@{ $self->{sketches} }){
426 $return.=$$sketch{name}."\n";
427 }
428
429 return $return;
430 }
431  
432 =pod
433  
434 =head1 COPYRIGHT AND LICENSE
435  
436 MIT license.
437  
438 =head1 AUTHOR
439  
440 Author: Lee Katz <lkatz@cdc.gov>
441  
442 For additional help, go to https://github.com/lskatz/perl-mash
443  
444 CPAN module at http://search.cpan.org/~lskatz/perl-mash
445  
446 =cut
447  
448 1; # gotta love how we we return 1 in modules. TRUTH!!!
449