/
signature.rs
1260 lines (1089 loc) · 39.5 KB
/
signature.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Compressed representations of genomic data
//!
//! A signature is a collection of sketches for a genomic dataset.
use core::iter::FusedIterator;
use std::fs::File;
use std::io;
use std::iter::Iterator;
use std::path::Path;
use std::str;
use cfg_if::cfg_if;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;
use crate::encodings::{aa_to_dayhoff, aa_to_hp, revcomp, to_aa, HashFunctions, VALID};
use crate::prelude::*;
use crate::selection::{Select, Selection};
use crate::sketch::minhash::KmerMinHash;
use crate::sketch::Sketch;
use crate::Error;
use crate::HashIntoType;
// TODO: this is the behavior expected from Sketch, but that name is already
// used. Sketchable?
pub trait SigsTrait {
fn size(&self) -> usize;
fn to_vec(&self) -> Vec<u64>;
fn ksize(&self) -> usize;
fn check_compatible(&self, other: &Self) -> Result<(), Error>;
fn seed(&self) -> u64;
fn hash_function(&self) -> HashFunctions;
fn add_hash(&mut self, hash: HashIntoType);
fn add_sequence(&mut self, seq: &[u8], force: bool) -> Result<(), Error> {
let ready_hashes = SeqToHashes::new(
seq,
self.ksize(),
force,
false,
self.hash_function(),
self.seed(),
);
for hash_value in ready_hashes {
match hash_value {
Ok(0) => continue,
Ok(x) => self.add_hash(x),
Err(err) => return Err(err),
}
}
// Should be always ok
Ok(())
}
fn add_protein(&mut self, seq: &[u8]) -> Result<(), Error> {
let ready_hashes = SeqToHashes::new(
seq,
self.ksize(),
false,
true,
self.hash_function(),
self.seed(),
);
for hash_value in ready_hashes {
match hash_value {
Ok(0) => continue,
Ok(x) => self.add_hash(x),
Err(err) => return Err(err),
}
}
// Should be always ok
Ok(())
}
}
impl SigsTrait for Sketch {
fn size(&self) -> usize {
match *self {
Sketch::MinHash(ref mh) => mh.size(),
Sketch::LargeMinHash(ref mh) => mh.size(),
Sketch::HyperLogLog(ref hll) => hll.size(),
}
}
fn to_vec(&self) -> Vec<u64> {
match *self {
Sketch::MinHash(ref mh) => mh.to_vec(),
Sketch::LargeMinHash(ref mh) => mh.to_vec(),
Sketch::HyperLogLog(ref hll) => hll.to_vec(),
}
}
fn ksize(&self) -> usize {
match *self {
Sketch::MinHash(ref mh) => mh.ksize(),
Sketch::LargeMinHash(ref mh) => mh.ksize(),
Sketch::HyperLogLog(ref hll) => hll.ksize(),
}
}
fn seed(&self) -> u64 {
match *self {
Sketch::MinHash(ref mh) => mh.seed(),
Sketch::LargeMinHash(ref mh) => mh.seed(),
Sketch::HyperLogLog(ref hll) => hll.seed(),
}
}
fn hash_function(&self) -> HashFunctions {
match *self {
Sketch::MinHash(ref mh) => mh.hash_function(),
Sketch::LargeMinHash(ref mh) => mh.hash_function(),
Sketch::HyperLogLog(ref hll) => hll.hash_function(),
}
}
fn add_hash(&mut self, hash: HashIntoType) {
match *self {
Sketch::MinHash(ref mut mh) => mh.add_hash(hash),
Sketch::LargeMinHash(ref mut mh) => mh.add_hash(hash),
Sketch::HyperLogLog(ref mut hll) => hll.add_hash(hash),
}
}
fn check_compatible(&self, other: &Self) -> Result<(), Error> {
match *self {
Sketch::MinHash(ref mh) => match other {
Sketch::MinHash(ref ot) => mh.check_compatible(ot),
_ => Err(Error::MismatchSignatureType),
},
Sketch::LargeMinHash(ref mh) => match other {
Sketch::LargeMinHash(ref ot) => mh.check_compatible(ot),
_ => Err(Error::MismatchSignatureType),
},
Sketch::HyperLogLog(ref hll) => match other {
Sketch::HyperLogLog(ref ot) => hll.check_compatible(ot),
_ => Err(Error::MismatchSignatureType),
},
}
}
fn add_sequence(&mut self, seq: &[u8], force: bool) -> Result<(), Error> {
match *self {
Sketch::MinHash(ref mut mh) => mh.add_sequence(seq, force),
Sketch::LargeMinHash(ref mut mh) => mh.add_sequence(seq, force),
Sketch::HyperLogLog(_) => unimplemented!(),
}
}
fn add_protein(&mut self, seq: &[u8]) -> Result<(), Error> {
match *self {
Sketch::MinHash(ref mut mh) => mh.add_protein(seq),
Sketch::LargeMinHash(ref mut mh) => mh.add_protein(seq),
Sketch::HyperLogLog(_) => unimplemented!(),
}
}
}
// Iterator for converting sequence to hashes
pub struct SeqToHashes {
sequence: Vec<u8>,
kmer_index: usize,
k_size: usize,
max_index: usize,
force: bool,
is_protein: bool,
hash_function: HashFunctions,
seed: u64,
hashes_buffer: Vec<u64>,
dna_configured: bool,
dna_rc: Vec<u8>,
dna_ksize: usize,
dna_len: usize,
dna_last_position_check: usize,
prot_configured: bool,
aa_seq: Vec<u8>,
translate_iter_step: usize,
}
impl SeqToHashes {
pub fn new(
seq: &[u8],
k_size: usize,
force: bool,
is_protein: bool,
hash_function: HashFunctions,
seed: u64,
) -> SeqToHashes {
let mut ksize: usize = k_size;
// Divide the kmer size by 3 if protein
if is_protein || !hash_function.dna() {
ksize = k_size / 3;
}
// By setting _max_index to 0, the iterator will return None and exit
let _max_index = if seq.len() >= ksize {
seq.len() - ksize + 1
} else {
0
};
SeqToHashes {
// Here we convert the sequence to upper case
sequence: seq.to_ascii_uppercase(),
k_size: ksize,
kmer_index: 0,
max_index: _max_index,
force,
is_protein,
hash_function,
seed,
hashes_buffer: Vec::with_capacity(1000),
dna_configured: false,
dna_rc: Vec::with_capacity(1000),
dna_ksize: 0,
dna_len: 0,
dna_last_position_check: 0,
prot_configured: false,
aa_seq: Vec::new(),
translate_iter_step: 0,
}
}
}
/*
Iterator that return a kmer hash for all modes except translate.
In translate mode:
- all the frames are processed at once and converted to hashes.
- all the hashes are stored in `hashes_buffer`
- after processing all the kmers, `translate_iter_step` is incremented
per iteration to iterate over all the indeces of the `hashes_buffer`.
- the iterator will die once `translate_iter_step` == length(hashes_buffer)
More info https://github.com/sourmash-bio/sourmash/pull/1946
*/
impl Iterator for SeqToHashes {
type Item = Result<u64, Error>;
fn next(&mut self) -> Option<Self::Item> {
if (self.kmer_index < self.max_index) || !self.hashes_buffer.is_empty() {
// Processing DNA or Translated DNA
if !self.is_protein {
// Setting the parameters only in the first iteration
if !self.dna_configured {
self.dna_ksize = self.k_size;
self.dna_len = self.sequence.len();
if self.dna_len < self.dna_ksize
|| (!self.hash_function.dna() && self.dna_len < self.k_size * 3)
{
return None;
}
// pre-calculate the reverse complement for the full sequence...
self.dna_rc = revcomp(&self.sequence);
self.dna_configured = true;
}
// Processing DNA
if self.hash_function.dna() {
let kmer = &self.sequence[self.kmer_index..self.kmer_index + self.dna_ksize];
for j in std::cmp::max(self.kmer_index, self.dna_last_position_check)
..self.kmer_index + self.dna_ksize
{
if !VALID[self.sequence[j] as usize] {
if !self.force {
return Some(Err(Error::InvalidDNA {
message: String::from_utf8(kmer.to_vec()).unwrap(),
}));
} else {
self.kmer_index += 1;
// Move the iterator to the next step
return Some(Ok(0));
}
}
self.dna_last_position_check += 1;
}
// ... and then while moving the k-mer window forward for the sequence
// we move another window backwards for the RC.
// For a ksize = 3, and a sequence AGTCGT (len = 6):
// +-+---------+---------------+-------+
// seq RC |i|i + ksize|len - ksize - i|len - i|
// AGTCGT ACGACT +-+---------+---------------+-------+
// +-> +-> |0| 2 | 3 | 6 |
// +-> +-> |1| 3 | 2 | 5 |
// +-> +-> |2| 4 | 1 | 4 |
// +-> +-> |3| 5 | 0 | 3 |
// +-+---------+---------------+-------+
// (leaving this table here because I had to draw to
// get the indices correctly)
let krc = &self.dna_rc[self.dna_len - self.dna_ksize - self.kmer_index
..self.dna_len - self.kmer_index];
let hash = crate::_hash_murmur(std::cmp::min(kmer, krc), self.seed);
self.kmer_index += 1;
Some(Ok(hash))
} else if self.hashes_buffer.is_empty() && self.translate_iter_step == 0 {
// Processing protein by translating DNA
// TODO: Implement iterator over frames instead of hashes_buffer.
for frame_number in 0..3 {
let substr: Vec<u8> = self
.sequence
.iter()
.cloned()
.skip(frame_number)
.take(self.sequence.len() - frame_number)
.collect();
let aa = to_aa(
&substr,
self.hash_function.dayhoff(),
self.hash_function.hp(),
)
.unwrap();
aa.windows(self.k_size).for_each(|n| {
let hash = crate::_hash_murmur(n, self.seed);
self.hashes_buffer.push(hash);
});
let rc_substr: Vec<u8> = self
.dna_rc
.iter()
.cloned()
.skip(frame_number)
.take(self.dna_rc.len() - frame_number)
.collect();
let aa_rc = to_aa(
&rc_substr,
self.hash_function.dayhoff(),
self.hash_function.hp(),
)
.unwrap();
aa_rc.windows(self.k_size).for_each(|n| {
let hash = crate::_hash_murmur(n, self.seed);
self.hashes_buffer.push(hash);
});
}
Some(Ok(0))
} else {
if self.translate_iter_step == self.hashes_buffer.len() {
self.hashes_buffer.clear();
self.kmer_index = self.max_index;
return Some(Ok(0));
}
let curr_idx = self.translate_iter_step;
self.translate_iter_step += 1;
Some(Ok(self.hashes_buffer[curr_idx]))
}
} else {
// Processing protein
// The kmer size is already divided by 3
if self.hash_function.protein() {
let aa_kmer = &self.sequence[self.kmer_index..self.kmer_index + self.k_size];
let hash = crate::_hash_murmur(aa_kmer, self.seed);
self.kmer_index += 1;
Some(Ok(hash))
} else {
if !self.prot_configured {
self.aa_seq = match &self.hash_function {
HashFunctions::Murmur64Dayhoff => {
self.sequence.iter().cloned().map(aa_to_dayhoff).collect()
}
HashFunctions::Murmur64Hp => {
self.sequence.iter().cloned().map(aa_to_hp).collect()
}
invalid => {
return Some(Err(Error::InvalidHashFunction {
function: format!("{}", invalid),
}));
}
};
}
let aa_kmer = &self.aa_seq[self.kmer_index..self.kmer_index + self.k_size];
let hash = crate::_hash_murmur(aa_kmer, self.seed);
self.kmer_index += 1;
Some(Ok(hash))
}
}
} else {
// End the iterator
None
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone, TypedBuilder)]
#[cfg_attr(
feature = "rkyv",
derive(rkyv::Serialize, rkyv::Deserialize, rkyv::Archive)
)]
pub struct Signature {
#[serde(default = "default_class")]
#[builder(default = default_class())]
class: String,
#[serde(default)]
#[builder(default)]
email: String,
#[builder(setter(into))]
hash_function: String,
#[builder(default)]
filename: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(crate) name: Option<String>,
#[serde(default = "default_license")]
#[builder(default = default_license())]
license: String,
pub(crate) signatures: Vec<Sketch>,
#[serde(default = "default_version")]
#[builder(default = default_version())]
version: f64,
}
fn default_license() -> String {
"CC0".to_string()
}
fn default_class() -> String {
"sourmash_signature".to_string()
}
fn default_version() -> f64 {
0.4
}
impl Signature {
pub fn name(&self) -> String {
if let Some(name) = &self.name {
name.clone()
} else if let Some(filename) = &self.filename {
filename.clone()
} else {
self.md5sum()
}
}
pub fn set_name(&mut self, name: &str) {
self.name = Some(name.into())
}
pub fn filename(&self) -> String {
if let Some(filename) = &self.filename {
filename.clone()
} else {
"".into()
}
}
pub fn set_filename(&mut self, name: &str) {
self.filename = Some(name.into())
}
pub fn size(&self) -> usize {
self.signatures.len()
}
pub fn sketches(&self) -> Vec<Sketch> {
self.signatures.clone()
}
pub fn reset_sketches(&mut self) {
self.signatures = vec![];
}
pub fn push(&mut self, sketch: Sketch) {
self.signatures.push(sketch);
}
pub fn license(&self) -> String {
self.license.clone()
}
pub fn class(&self) -> String {
self.class.clone()
}
pub fn hash_function(&self) -> String {
self.hash_function.clone()
}
pub fn email(&self) -> String {
self.email.clone()
}
pub fn md5sum(&self) -> String {
if self.signatures.len() == 1 {
match &self.signatures[0] {
Sketch::MinHash(mh) => mh.md5sum(),
Sketch::LargeMinHash(mh) => mh.md5sum(),
Sketch::HyperLogLog(_) => unimplemented!(),
}
} else {
// TODO: select the correct signature
unimplemented!()
}
}
pub fn select_sketch(&self, sketch: &Sketch) -> Option<&Sketch> {
if let Sketch::MinHash(template) = sketch {
for sk in &self.signatures {
if let Sketch::MinHash(mh) = sk {
if mh.check_compatible(template).is_ok() {
return Some(sk);
}
} else {
unimplemented!()
}
}
} else {
unimplemented!()
}
None
}
// return single corresponding sketch
pub fn get_sketch(&self) -> Option<&Sketch> {
if self.signatures.len() != 1 {
if self.signatures.len() > 1 {
todo!("Multiple sketches found! Please run select first.");
}
return None;
}
self.signatures.iter().find(|sk| {
matches!(
sk,
Sketch::MinHash(_) | Sketch::LargeMinHash(_) | Sketch::HyperLogLog(_)
)
})
}
// return minhash directly
pub fn minhash(&self) -> Option<&KmerMinHash> {
if self.signatures.len() != 1 {
if self.signatures.len() > 1 {
todo!("Multiple sketches found! Please run select first.");
}
return None;
}
self.signatures.iter().find_map(|sk| {
if let Sketch::MinHash(mh) = sk {
Some(mh)
} else {
None
}
})
}
pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Vec<Signature>, Error> {
let mut reader = io::BufReader::new(File::open(path)?);
Signature::from_reader(&mut reader)
}
pub fn from_reader<R>(rdr: R) -> Result<Vec<Signature>, Error>
where
R: io::Read,
{
let (rdr, _format) = niffler::get_reader(Box::new(rdr))?;
let sigs: Vec<Signature> = serde_json::from_reader(rdr)?;
Ok(sigs)
}
pub fn load_signatures<R>(
buf: R,
ksize: Option<usize>,
moltype: Option<HashFunctions>,
_scaled: Option<u64>,
) -> Result<Vec<Signature>, Error>
where
R: io::Read,
{
let orig_sigs = Signature::from_reader(buf)?;
let flat_sigs = orig_sigs.into_iter().flat_map(|s| {
s.signatures
.iter()
.map(|mh| {
let mut new_s = s.clone();
new_s.signatures = vec![mh.clone()];
new_s
})
.collect::<Vec<Signature>>()
});
let filtered_sigs = flat_sigs.filter_map(|mut sig| {
let good_mhs: Vec<Sketch> = sig
.signatures
.into_iter()
.filter(|sig| {
match sig {
Sketch::MinHash(mh) => {
if let Some(k) = ksize {
if k != mh.ksize() {
return false;
}
};
match &moltype {
Some(x) => {
if mh.hash_function() == *x {
return true;
}
}
None => return true, // TODO: match previous behavior
};
}
Sketch::LargeMinHash(mh) => {
if let Some(k) = ksize {
if k != mh.ksize() {
return false;
}
};
match &moltype {
Some(x) => {
if mh.hash_function() == *x {
return true;
}
}
None => return true, // TODO: match previous behavior
};
}
Sketch::HyperLogLog(_) => unimplemented!(),
};
false
})
.collect();
if good_mhs.is_empty() {
return None;
};
sig.signatures = good_mhs;
Some(sig)
});
Ok(filtered_sigs.collect())
}
pub fn add_sequence(&mut self, seq: &[u8], force: bool) -> Result<(), Error> {
cfg_if! {
if #[cfg(feature = "parallel")] {
self.signatures
.par_iter_mut()
.try_for_each(|sketch| {
sketch.add_sequence(seq, force) }
)?;
} else {
for sketch in self.signatures.iter_mut(){
sketch.add_sequence(seq, force)?;
}
}
}
Ok(())
}
pub fn add_protein(&mut self, seq: &[u8]) -> Result<(), Error> {
cfg_if! {
if #[cfg(feature = "parallel")] {
self.signatures
.par_iter_mut()
.try_for_each(|sketch| {
sketch.add_protein(seq) }
)?;
} else {
self.signatures
.iter_mut()
.try_for_each(|sketch| {
sketch.add_protein(seq) }
)?;
}
}
Ok(())
}
pub fn iter_mut(&mut self) -> IterMut<'_> {
let length = self.signatures.len();
IterMut {
iter: self.signatures.iter_mut(),
length,
}
}
pub fn iter(&self) -> Iter<'_> {
let length = self.signatures.len();
Iter {
iter: self.signatures.iter(),
length,
}
}
}
pub struct IterMut<'a> {
iter: std::slice::IterMut<'a, Sketch>,
length: usize,
}
impl<'a> IntoIterator for &'a mut Signature {
type Item = &'a mut Sketch;
type IntoIter = IterMut<'a>;
fn into_iter(self) -> IterMut<'a> {
self.iter_mut()
}
}
impl<'a> Iterator for IterMut<'a> {
type Item = &'a mut Sketch;
fn next(&mut self) -> Option<&'a mut Sketch> {
if self.length == 0 {
None
} else {
self.length -= 1;
self.iter.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
}
pub struct Iter<'a> {
iter: std::slice::Iter<'a, Sketch>,
length: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a Sketch;
fn next(&mut self) -> Option<&'a Sketch> {
if self.length == 0 {
None
} else {
self.length -= 1;
self.iter.next()
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.length, Some(self.length))
}
}
impl FusedIterator for Iter<'_> {}
impl ExactSizeIterator for Iter<'_> {
fn len(&self) -> usize {
self.length
}
}
impl Clone for Iter<'_> {
fn clone(&self) -> Self {
Iter {
iter: self.iter.clone(),
length: self.length,
}
}
}
impl ToWriter for Signature {
fn to_writer<W>(&self, writer: &mut W) -> Result<(), Error>
where
W: io::Write,
{
serde_json::to_writer(writer, &vec![&self])?;
Ok(())
}
}
impl Select for Signature {
fn select(mut self, selection: &Selection) -> Result<Self, Error> {
self.signatures.retain(|s| {
let mut valid = true;
valid = if let Some(ksize) = selection.ksize() {
let k = s.ksize() as u32;
let adjusted_ksize = match s.hash_function() {
HashFunctions::Murmur64Protein
| HashFunctions::Murmur64Dayhoff
| HashFunctions::Murmur64Hp => ksize * 3,
_ => ksize,
};
k == adjusted_ksize
} else {
valid
};
// keep compatible scaled if applicable
valid = if let Some(sel_scaled) = selection.scaled() {
match s {
Sketch::MinHash(mh) => valid && mh.scaled() <= sel_scaled as u64,
// TODO: test LargeMinHash
// Sketch::LargeMinHash(lmh) => valid && lmh.scaled() <= sel_scaled as u64,
_ => valid, // other sketch types or invalid cases
}
} else {
valid // if selection.scaled() is None, keep prior valid
};
/*
valid = if let Some(abund) = selection.abund() {
valid && *s.with_abundance() == abund
} else {
valid
};
valid = if let Some(moltype) = selection.moltype() {
valid && s.moltype() == moltype
} else {
valid
};
*/
valid
});
// downsample the retained sketches if needed.
if let Some(sel_scaled) = selection.scaled() {
for sketch in self.signatures.iter_mut() {
// TODO: also account for LargeMinHash
if let Sketch::MinHash(mh) = sketch {
if (mh.scaled() as u32) < sel_scaled {
*sketch = Sketch::MinHash(mh.downsample_scaled(sel_scaled as u64)?);
}
}
}
}
Ok(self)
}
}
impl Default for Signature {
fn default() -> Signature {
Signature {
class: default_class(),
email: "".to_string(),
hash_function: "0.murmur64".to_string(),
license: default_license(),
filename: None,
name: None,
signatures: Vec::<Sketch>::new(),
version: default_version(),
}
}
}
impl PartialEq for Signature {
fn eq(&self, other: &Signature) -> bool {
let metadata = self.class == other.class
&& self.email == other.email
&& self.hash_function == other.hash_function
&& self.filename == other.filename
&& self.name == other.name;
// TODO: find the right signature
// as long as we have a matching
if let Sketch::MinHash(mh) = &self.signatures[0] {
if let Sketch::MinHash(other_mh) = &other.signatures[0] {
return metadata && (mh == other_mh);
}
} else {
unimplemented!()
}
metadata
}
}
#[cfg(test)]
mod test {
use std::convert::TryInto;
use std::fs::File;
use std::io::{BufReader, Read};
use std::path::PathBuf;
use needletail::parse_fastx_reader;
use crate::cmd::ComputeParameters;
use crate::signature::SigsTrait;
use super::Signature;
use crate::prelude::Select;
use crate::selection::Selection;
use crate::sketch::Sketch;
#[test]
fn load_sig() {
let mut filename = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
filename.push("../../tests/test-data/.sbt.v3/60f7e23c24a8d94791cc7a8680c493f9");
let mut reader = BufReader::new(File::open(filename).unwrap());
let sigs = Signature::load_signatures(
&mut reader,
Some(31),
Some("DNA".try_into().unwrap()),
None,
)
.unwrap();
let _sig_data = sigs[0].clone();
// TODO: check sig_data
}
#[test]
fn load_signature() {
let mut filename = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
filename.push("../../tests/test-data/genome-s10+s11.sig");
let file = File::open(filename).unwrap();
let reader = BufReader::new(file);
let sigs: Vec<Signature> = serde_json::from_reader(reader).expect("Loading error");
assert_eq!(sigs.len(), 4);
let sig = sigs.get(0).unwrap();
assert_eq!(sig.class, "sourmash_signature");
assert_eq!(sig.email, "");
if let Some(ref filename) = sig.filename {
assert_eq!(filename, "-");
}
assert_eq!(sig.hash_function, "0.murmur64");
if let Some(ref name) = sig.name {
assert_eq!(name, "genome-s10+s11");
}
assert_eq!(sig.signatures.len(), 1);
}
#[test]
fn signature_from_computeparams() {
let params = ComputeParameters::builder()
.ksizes(vec![2, 3, 4])
.num_hashes(3u32)
.build();
let mut sig = Signature::from_params(¶ms);
sig.add_sequence(b"ATGC", false).unwrap();
assert_eq!(sig.signatures.len(), 3);
dbg!(&sig.signatures);
assert_eq!(sig.signatures[0].size(), 3);
assert_eq!(sig.signatures[1].size(), 2);
assert_eq!(sig.signatures[2].size(), 1);
}
#[test]
fn signature_slow_path() {
let params = ComputeParameters::builder()
.ksizes(vec![2, 3, 4, 5])
.num_hashes(3u32)
.build();
let mut sig = Signature::from_params(¶ms);
sig.add_sequence(b"ATGCTN", true).unwrap();
assert_eq!(sig.signatures.len(), 4);
dbg!(&sig.signatures);
assert_eq!(sig.signatures[0].size(), 3);
assert_eq!(sig.signatures[1].size(), 3);
assert_eq!(sig.signatures[2].size(), 2);
assert_eq!(sig.signatures[3].size(), 1);
}
#[test]
fn signature_add_sequence_protein() {
let params = ComputeParameters::builder()
.ksizes(vec![3, 6])
.num_hashes(3u32)
.protein(true)
.dna(false)
.build();
let mut sig = Signature::from_params(¶ms);
sig.add_sequence(b"ATGCAT", false).unwrap();
assert_eq!(sig.signatures.len(), 2);
dbg!(&sig.signatures);
assert_eq!(sig.signatures[0].size(), 3);