/
minhash.rs
1579 lines (1348 loc) · 45.5 KB
/
minhash.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
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::f64::consts::PI;
use std::fmt::Write;
use std::iter::{Iterator, Peekable};
use std::str;
use std::sync::Mutex;
use serde::de::Deserializer;
use serde::ser::{SerializeStruct, Serializer};
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;
use crate::_hash_murmur;
use crate::encodings::HashFunctions;
use crate::signature::SigsTrait;
use crate::sketch::hyperloglog::HyperLogLog;
use crate::Error;
#[cfg(all(target_arch = "wasm32", target_vendor = "unknown"))]
use wasm_bindgen::prelude::*;
pub fn max_hash_for_scaled(scaled: u64) -> u64 {
match scaled {
0 => 0,
1 => u64::max_value(),
_ => (u64::max_value() as f64 / scaled as f64) as u64,
}
}
pub fn scaled_for_max_hash(max_hash: u64) -> u64 {
match max_hash {
0 => 0,
_ => (u64::max_value() as f64 / max_hash as f64) as u64,
}
}
#[cfg_attr(all(target_arch = "wasm32", target_vendor = "unknown"), wasm_bindgen)]
#[derive(Debug, TypedBuilder)]
pub struct KmerMinHash {
num: u32,
ksize: u32,
#[builder(setter(into), default = HashFunctions::murmur64_DNA)]
hash_function: HashFunctions,
#[builder(default = 42u64)]
seed: u64,
#[builder(default = u64::max_value())]
max_hash: u64,
#[builder(default)]
mins: Vec<u64>,
#[builder(default)]
abunds: Option<Vec<u64>>,
#[builder(default)]
md5sum: Mutex<Option<String>>,
}
impl PartialEq for KmerMinHash {
fn eq(&self, other: &KmerMinHash) -> bool {
// TODO: check all other fields?
self.md5sum() == other.md5sum()
}
}
impl Clone for KmerMinHash {
fn clone(&self) -> Self {
KmerMinHash {
num: self.num,
ksize: self.ksize,
hash_function: self.hash_function,
seed: self.seed,
max_hash: self.max_hash,
mins: self.mins.clone(),
abunds: self.abunds.clone(),
md5sum: Mutex::new(Some(self.md5sum())),
}
}
}
impl Default for KmerMinHash {
fn default() -> KmerMinHash {
KmerMinHash {
num: 1000,
ksize: 21,
hash_function: HashFunctions::murmur64_DNA,
seed: 42,
max_hash: 0,
mins: Vec::with_capacity(1000),
abunds: None,
md5sum: Mutex::new(None),
}
}
}
impl Serialize for KmerMinHash {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let n_fields = match &self.abunds {
Some(_) => 8,
_ => 7,
};
let mut partial = serializer.serialize_struct("KmerMinHash", n_fields)?;
partial.serialize_field("num", &self.num)?;
partial.serialize_field("ksize", &self.ksize)?;
partial.serialize_field("seed", &self.seed)?;
partial.serialize_field("max_hash", &self.max_hash)?;
partial.serialize_field("mins", &self.mins)?;
partial.serialize_field("md5sum", &self.md5sum())?;
if let Some(abunds) = &self.abunds {
partial.serialize_field("abundances", abunds)?;
}
partial.serialize_field("molecule", &self.hash_function.to_string())?;
partial.end()
}
}
impl<'de> Deserialize<'de> for KmerMinHash {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct TempSig {
num: u32,
ksize: u32,
seed: u64,
max_hash: u64,
md5sum: String,
mins: Vec<u64>,
abundances: Option<Vec<u64>>,
molecule: String,
}
let tmpsig = TempSig::deserialize(deserializer)?;
let num = if tmpsig.max_hash != 0 { 0 } else { tmpsig.num };
let hash_function = match tmpsig.molecule.to_lowercase().as_ref() {
"protein" => HashFunctions::murmur64_protein,
"dayhoff" => HashFunctions::murmur64_dayhoff,
"hp" => HashFunctions::murmur64_hp,
"dna" => HashFunctions::murmur64_DNA,
_ => unimplemented!(), // TODO: throw error here
};
// This shouldn't be necessary, but at some point we
// created signatures with unordered mins =(
let (mins, abunds) = if let Some(abunds) = tmpsig.abundances {
let mut values: Vec<(_, _)> = tmpsig.mins.iter().zip(abunds.iter()).collect();
values.sort();
let mins = values.iter().map(|(v, _)| **v).collect();
let abunds = values.iter().map(|(_, v)| **v).collect();
(mins, Some(abunds))
} else {
let mut values: Vec<_> = tmpsig.mins.into_iter().collect();
values.sort_unstable();
(values, None)
};
Ok(KmerMinHash {
num,
ksize: tmpsig.ksize,
seed: tmpsig.seed,
max_hash: tmpsig.max_hash,
md5sum: Mutex::new(Some(tmpsig.md5sum)),
mins,
abunds,
hash_function,
})
}
}
impl KmerMinHash {
pub fn new(
scaled: u64,
ksize: u32,
hash_function: HashFunctions,
seed: u64,
track_abundance: bool,
num: u32,
) -> KmerMinHash {
let mins: Vec<u64>;
let abunds: Option<Vec<u64>>;
if num > 0 {
mins = Vec::with_capacity(num as usize);
} else {
mins = Vec::with_capacity(1000);
}
if track_abundance {
abunds = Some(Vec::with_capacity(mins.capacity()));
} else {
abunds = None
}
let max_hash = max_hash_for_scaled(scaled);
KmerMinHash {
num,
ksize,
hash_function,
seed,
max_hash,
mins,
abunds,
md5sum: Mutex::new(None),
}
}
pub fn num(&self) -> u32 {
self.num
}
pub fn is_protein(&self) -> bool {
self.hash_function == HashFunctions::murmur64_protein
}
pub fn max_hash(&self) -> u64 {
self.max_hash
}
pub fn scaled(&self) -> u64 {
scaled_for_max_hash(self.max_hash)
}
pub fn clear(&mut self) {
self.mins.clear();
if let Some(ref mut abunds) = self.abunds {
abunds.clear();
}
}
pub fn is_empty(&self) -> bool {
self.mins.is_empty()
}
pub fn set_hash_function(&mut self, h: HashFunctions) -> Result<(), Error> {
if self.hash_function == h {
return Ok(());
}
if !self.is_empty() {
return Err(Error::NonEmptyMinHash {
message: "hash_function".into(),
});
}
self.hash_function = h;
Ok(())
}
pub fn track_abundance(&self) -> bool {
self.abunds.is_some()
}
pub fn enable_abundance(&mut self) -> Result<(), Error> {
if !self.mins.is_empty() {
return Err(Error::NonEmptyMinHash {
message: "track_abundance=True".into(),
});
}
self.abunds = Some(vec![]);
Ok(())
}
pub fn disable_abundance(&mut self) {
self.abunds = None;
}
fn reset_md5sum(&self) {
let mut data = self.md5sum.lock().unwrap();
if data.is_some() {
*data = None;
}
}
pub fn md5sum(&self) -> String {
let mut data = self.md5sum.lock().unwrap();
if data.is_none() {
let mut buffer = String::with_capacity(20);
let mut md5_ctx = md5::Context::new();
write!(&mut buffer, "{}", self.ksize()).unwrap();
md5_ctx.consume(&buffer);
buffer.clear();
for x in &self.mins {
write!(&mut buffer, "{}", x).unwrap();
md5_ctx.consume(&buffer);
buffer.clear();
}
*data = Some(format!("{:x}", md5_ctx.compute()));
}
data.clone().unwrap()
}
pub fn add_hash(&mut self, hash: u64) {
self.add_hash_with_abundance(hash, 1);
}
pub fn add_hash_with_abundance(&mut self, hash: u64, abundance: u64) {
let current_max = match self.mins.last() {
Some(&x) => x,
None => u64::max_value(),
};
if hash > self.max_hash && self.max_hash != 0 {
// This is a scaled minhash, and we don't need to add the new hash
return;
}
if self.num == 0 && self.max_hash == 0 {
// why did you create this minhash? it will always be empty...
return;
}
if abundance == 0 {
// well, don't add it.
return;
}
// From this point on, hash is within scaled (or no scaled specified).
// empty mins? add it.
if self.mins.is_empty() {
self.mins.push(hash);
if let Some(ref mut abunds) = self.abunds {
abunds.push(abundance);
self.reset_md5sum();
}
return;
}
if hash <= self.max_hash || hash <= current_max || (self.mins.len() as u32) < self.num {
// "good" hash - within range, smaller than current entry, or
// still have space available
let pos = match self.mins.binary_search(&hash) {
Ok(p) => p,
Err(p) => p,
};
if pos == self.mins.len() {
// at end - must still be growing, we know the list won't
// get too long
self.mins.push(hash);
self.reset_md5sum();
if let Some(ref mut abunds) = self.abunds {
abunds.push(abundance);
}
} else if self.mins[pos] != hash {
// didn't find hash in mins, so inserting somewhere
// in the middle; shrink list if needed.
self.mins.insert(pos, hash);
if let Some(ref mut abunds) = self.abunds {
abunds.insert(pos, abundance);
}
// is it too big now?
if self.num != 0 && self.mins.len() > (self.num as usize) {
self.mins.pop();
if let Some(ref mut abunds) = self.abunds {
abunds.pop();
}
}
self.reset_md5sum();
} else if let Some(ref mut abunds) = self.abunds {
// pos == hash: hash value already in mins, inc count by abundance
abunds[pos] += abundance;
}
}
}
pub fn set_hash_with_abundance(&mut self, hash: u64, abundance: u64) {
let mut found = false;
if let Ok(pos) = self.mins.binary_search(&hash) {
if self.mins[pos] == hash {
found = true;
if let Some(ref mut abunds) = self.abunds {
abunds[pos] = abundance;
}
}
}
if !found {
self.add_hash_with_abundance(hash, abundance);
}
}
pub fn add_word(&mut self, word: &[u8]) {
let hash = _hash_murmur(word, self.seed);
self.add_hash(hash);
}
pub fn remove_hash(&mut self, hash: u64) {
if let Ok(pos) = self.mins.binary_search(&hash) {
if self.mins[pos] == hash {
self.mins.remove(pos);
self.reset_md5sum();
if let Some(ref mut abunds) = self.abunds {
abunds.remove(pos);
}
}
};
}
pub fn remove_many(&mut self, hashes: &[u64]) -> Result<(), Error> {
for min in hashes {
self.remove_hash(*min);
}
Ok(())
}
pub fn merge(&mut self, other: &KmerMinHash) -> Result<(), Error> {
self.check_compatible(other)?;
let max_size = self.mins.len() + other.mins.len();
let mut merged: Vec<u64> = Vec::with_capacity(max_size);
let mut merged_abunds: Vec<u64> = Vec::with_capacity(max_size);
{
let mut self_iter = self.mins.iter();
let mut other_iter = other.mins.iter();
let mut self_abunds_iter: Option<std::slice::Iter<'_, u64>>;
if let Some(ref mut abunds) = self.abunds {
self_abunds_iter = Some(abunds.iter());
} else {
self_abunds_iter = None;
}
let mut other_abunds_iter: Option<std::slice::Iter<'_, u64>>;
if let Some(ref abunds) = other.abunds {
other_abunds_iter = Some(abunds.iter());
} else {
other_abunds_iter = None;
}
let mut self_value = self_iter.next();
let mut other_value = other_iter.next();
while self_value.is_some() {
let value = self_value.unwrap();
match other_value {
None => {
merged.push(*value);
merged.extend(self_iter);
if let Some(sai) = self_abunds_iter {
merged_abunds.extend(sai);
}
break;
}
Some(x) if x < value => {
merged.push(*x);
other_value = other_iter.next();
if let Some(ref mut oai) = other_abunds_iter {
if let Some(v) = oai.next() {
merged_abunds.push(*v)
}
}
}
Some(x) if x == value => {
merged.push(*x);
other_value = other_iter.next();
self_value = self_iter.next();
if let Some(ref mut oai) = other_abunds_iter {
if let Some(v) = oai.next() {
if let Some(ref mut sai) = self_abunds_iter {
if let Some(s) = sai.next() {
merged_abunds.push(*v + *s)
}
}
}
}
}
Some(x) if x > value => {
merged.push(*value);
self_value = self_iter.next();
if let Some(ref mut sai) = self_abunds_iter {
if let Some(v) = sai.next() {
merged_abunds.push(*v)
}
}
}
Some(_) => {}
}
}
if let Some(value) = other_value {
merged.push(*value);
}
merged.extend(other_iter);
if let Some(oai) = other_abunds_iter {
merged_abunds.extend(oai);
}
}
if merged.len() < (self.num as usize) || (self.num as usize) == 0 {
self.mins = merged;
self.abunds = if merged_abunds.is_empty() {
if self.abunds.is_some() {
Some(vec![])
} else {
None
}
} else {
Some(merged_abunds)
};
} else {
self.mins = merged.into_iter().take(self.num as usize).collect();
self.abunds = if merged_abunds.is_empty() {
if self.abunds.is_some() {
Some(vec![])
} else {
None
}
} else {
Some(merged_abunds.into_iter().take(self.num as usize).collect())
}
}
self.reset_md5sum();
Ok(())
}
pub fn add_from(&mut self, other: &KmerMinHash) -> Result<(), Error> {
for min in &other.mins {
self.add_hash(*min);
}
Ok(())
}
pub fn add_many(&mut self, hashes: &[u64]) -> Result<(), Error> {
for min in hashes {
self.add_hash(*min);
}
Ok(())
}
pub fn add_many_with_abund(&mut self, hashes: &[(u64, u64)]) -> Result<(), Error> {
for item in hashes {
self.add_hash_with_abundance(item.0, item.1);
}
Ok(())
}
pub fn count_common(&self, other: &KmerMinHash, downsample: bool) -> Result<u64, Error> {
if downsample && self.max_hash != other.max_hash {
let (first, second) = if self.max_hash < other.max_hash {
(self, other)
} else {
(other, self)
};
let downsampled_mh = second.downsample_max_hash(first.max_hash)?;
first.count_common(&downsampled_mh, false)
} else {
self.check_compatible(other)?;
let iter = if self.size() < other.size() {
Intersection::new(self.mins.iter(), other.mins.iter())
} else {
Intersection::new(other.mins.iter(), self.mins.iter())
};
Ok(iter.count() as u64)
}
}
pub fn intersection(&self, other: &KmerMinHash) -> Result<(Vec<u64>, u64), Error> {
self.check_compatible(other)?;
let mut combined_mh = KmerMinHash::new(
self.scaled(),
self.ksize,
self.hash_function,
self.seed,
self.abunds.is_some(),
self.num,
);
combined_mh.merge(&self)?;
combined_mh.merge(&other)?;
let it1 = Intersection::new(self.mins.iter(), other.mins.iter());
// TODO: there is probably a way to avoid this Vec here,
// and pass the it1 as left in it2.
let i1: Vec<u64> = it1.cloned().collect();
let it2 = Intersection::new(i1.iter(), combined_mh.mins.iter());
let common: Vec<u64> = it2.cloned().collect();
Ok((common, combined_mh.mins.len() as u64))
}
// FIXME: intersection_size and count_common should be the same?
pub fn intersection_size(&self, other: &KmerMinHash) -> Result<(u64, u64), Error> {
self.check_compatible(other)?;
let mut combined_mh = KmerMinHash::new(
self.scaled(),
self.ksize,
self.hash_function,
self.seed,
self.abunds.is_some(),
self.num,
);
combined_mh.merge(&self)?;
combined_mh.merge(&other)?;
let it1 = Intersection::new(self.mins.iter(), other.mins.iter());
// TODO: there is probably a way to avoid this Vec here,
// and pass the it1 as left in it2.
let i1: Vec<u64> = it1.cloned().collect();
let it2 = Intersection::new(i1.iter(), combined_mh.mins.iter());
Ok((it2.count() as u64, combined_mh.mins.len() as u64))
}
// calculate Jaccard similarity, ignoring abundance.
pub fn jaccard(&self, other: &KmerMinHash) -> Result<f64, Error> {
self.check_compatible(other)?;
if let Ok((common, size)) = self.intersection_size(other) {
Ok(common as f64 / u64::max(1, size) as f64)
} else {
Ok(0.0)
}
}
// compare two minhashes, with abundance;
// calculate their angular similarity.
pub fn angular_similarity(&self, other: &KmerMinHash) -> Result<f64, Error> {
self.check_compatible(other)?;
if self.abunds.is_none() || other.abunds.is_none() {
// TODO: throw error, we need abundance for this
unimplemented!() // @CTB fixme
}
// TODO: check which one is smaller, swap around if needed
let abunds = self.abunds.as_ref().unwrap();
let other_abunds = other.abunds.as_ref().unwrap();
let mut prod = 0;
let mut other_iter = other.mins.iter().enumerate();
let mut next_hash = other_iter.next();
let a_sq: u64 = abunds.iter().map(|a| (a * a)).sum();
let b_sq: u64 = other_abunds.iter().map(|a| (a * a)).sum();
for (i, hash) in self.mins.iter().enumerate() {
while let Some((j, k)) = next_hash {
match k.cmp(hash) {
Ordering::Less => next_hash = other_iter.next(),
Ordering::Equal => {
// Calling `get_unchecked` here is safe since
// both `i` and `j` are valid indices
// (`i` and `j` came from valid iterator calls)
unsafe {
prod += abunds.get_unchecked(i) * other_abunds.get_unchecked(j);
}
break;
}
Ordering::Greater => break,
}
}
}
let norm_a = (a_sq as f64).sqrt();
let norm_b = (b_sq as f64).sqrt();
if norm_a == 0. || norm_b == 0. {
return Ok(0.0);
}
let prod = f64::min(prod as f64 / (norm_a * norm_b), 1.);
let distance = 2. * prod.acos() / PI;
Ok(1. - distance)
}
pub fn similarity(
&self,
other: &KmerMinHash,
ignore_abundance: bool,
downsample: bool,
) -> Result<f64, Error> {
if downsample && self.max_hash != other.max_hash {
let (first, second) = if self.max_hash < other.max_hash {
(self, other)
} else {
(other, self)
};
let downsampled_mh = second.downsample_max_hash(first.max_hash)?;
first.similarity(&downsampled_mh, ignore_abundance, false)
} else if ignore_abundance || self.abunds.is_none() || other.abunds.is_none() {
self.jaccard(&other)
} else {
self.angular_similarity(&other)
}
}
pub fn dayhoff(&self) -> bool {
self.hash_function == HashFunctions::murmur64_dayhoff
}
pub fn hp(&self) -> bool {
self.hash_function == HashFunctions::murmur64_hp
}
pub fn mins(&self) -> Vec<u64> {
self.mins.clone()
}
pub fn iter_mins(&self) -> impl Iterator<Item = &u64> {
self.mins.iter()
}
pub fn abunds(&self) -> Option<Vec<u64>> {
self.abunds.clone()
}
// create a downsampled copy of self
pub fn downsample_max_hash(&self, max_hash: u64) -> Result<KmerMinHash, Error> {
let scaled = scaled_for_max_hash(max_hash);
let mut new_mh = KmerMinHash::new(
scaled,
self.ksize,
self.hash_function,
self.seed,
self.abunds.is_some(),
self.num,
);
if self.abunds.is_some() {
new_mh.add_many_with_abund(&self.to_vec_abunds())?;
} else {
new_mh.add_many(&self.mins)?;
}
Ok(new_mh)
}
pub fn to_vec_abunds(&self) -> Vec<(u64, u64)> {
if let Some(abunds) = &self.abunds {
self.mins
.iter()
.cloned()
.zip(abunds.iter().cloned())
.collect()
} else {
self.mins
.iter()
.cloned()
.zip(std::iter::repeat(1))
.collect()
}
}
pub fn as_hll(&self) -> HyperLogLog {
let mut hll = HyperLogLog::with_error_rate(0.01, self.ksize()).unwrap();
for h in &self.mins {
hll.add_hash(*h)
}
hll
}
}
impl SigsTrait for KmerMinHash {
fn size(&self) -> usize {
self.mins.len()
}
fn to_vec(&self) -> Vec<u64> {
self.mins.clone()
}
fn ksize(&self) -> usize {
self.ksize as usize
}
fn seed(&self) -> u64 {
self.seed
}
fn hash_function(&self) -> HashFunctions {
self.hash_function
}
fn add_hash(&mut self, hash: u64) {
self.add_hash_with_abundance(hash, 1);
}
fn check_compatible(&self, other: &KmerMinHash) -> Result<(), Error> {
/*
if self.num != other.num {
return Err(Error::MismatchNum {
n1: self.num,
n2: other.num,
}
.into());
}
*/
if self.ksize != other.ksize {
return Err(Error::MismatchKSizes);
}
if self.hash_function != other.hash_function {
// TODO: fix this error
return Err(Error::MismatchDNAProt);
}
if self.max_hash != other.max_hash {
return Err(Error::MismatchScaled);
}
if self.seed != other.seed {
return Err(Error::MismatchSeed);
}
Ok(())
}
}
struct Intersection<T, I: Iterator<Item = T>> {
iter: Peekable<I>,
other: Peekable<I>,
}
impl<T, I: Iterator<Item = T>> Intersection<T, I> {
pub fn new(left: I, right: I) -> Self {
Intersection {
iter: left.peekable(),
other: right.peekable(),
}
}
}
impl<T: Ord, I: Iterator<Item = T>> Iterator for Intersection<T, I> {
type Item = T;
fn next(&mut self) -> Option<T> {
loop {
let res = match (self.iter.peek(), self.other.peek()) {
(Some(ref left_key), Some(ref right_key)) => left_key.cmp(right_key),
_ => return None,
};
match res {
Ordering::Less => {
self.iter.next();
}
Ordering::Greater => {
self.other.next();
}
Ordering::Equal => {
self.other.next();
return self.iter.next();
}
}
}
}
}
//#############
// A MinHash implementation for low scaled or large cardinalities
#[cfg_attr(all(target_arch = "wasm32", target_vendor = "unknown"), wasm_bindgen)]
#[derive(Debug, TypedBuilder)]
pub struct KmerMinHashBTree {
num: u32,
ksize: u32,
#[builder(setter(into), default = HashFunctions::murmur64_DNA)]
hash_function: HashFunctions,
#[builder(default = 42u64)]
seed: u64,
#[builder(default = u64::max_value())]
max_hash: u64,
#[builder(default)]
mins: BTreeSet<u64>,
#[builder(default)]
abunds: Option<BTreeMap<u64, u64>>,
#[builder(default = 0u64)]
current_max: u64,
#[builder(default)]
md5sum: Mutex<Option<String>>,
}
impl PartialEq for KmerMinHashBTree {
fn eq(&self, other: &KmerMinHashBTree) -> bool {
// TODO: check all other fields?
self.md5sum() == other.md5sum()
}
}
impl Clone for KmerMinHashBTree {
fn clone(&self) -> Self {
KmerMinHashBTree {
num: self.num,
ksize: self.ksize,
hash_function: self.hash_function,
seed: self.seed,
max_hash: self.max_hash,
mins: self.mins.clone(),
abunds: self.abunds.clone(),
current_max: self.current_max,
md5sum: Mutex::new(Some(self.md5sum())),
}
}
}
impl Default for KmerMinHashBTree {
fn default() -> KmerMinHashBTree {
KmerMinHashBTree {
num: 1000,
ksize: 21,
hash_function: HashFunctions::murmur64_DNA,
seed: 42,
max_hash: 0,
mins: Default::default(),
abunds: None,
current_max: 0,
md5sum: Mutex::new(None),
}
}
}
impl Serialize for KmerMinHashBTree {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let n_fields = match &self.abunds {
Some(_) => 8,
_ => 7,
};
let mut partial = serializer.serialize_struct("KmerMinHashBTree", n_fields)?;
partial.serialize_field("num", &self.num)?;
partial.serialize_field("ksize", &self.ksize)?;
partial.serialize_field("seed", &self.seed)?;
partial.serialize_field("max_hash", &self.max_hash)?;
partial.serialize_field("mins", &self.mins)?;
partial.serialize_field("md5sum", &self.md5sum())?;
if let Some(abunds) = &self.abunds {
let abs: Vec<u64> = abunds.values().cloned().collect();
partial.serialize_field("abundances", &abs)?;
}
partial.serialize_field("molecule", &self.hash_function.to_string())?;
partial.end()
}
}
impl<'de> Deserialize<'de> for KmerMinHashBTree {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct TempSig {
num: u32,
ksize: u32,
seed: u64,
max_hash: u64,
md5sum: String,
mins: Vec<u64>,
abundances: Option<Vec<u64>>,
molecule: String,
}
let tmpsig = TempSig::deserialize(deserializer)?;
let num = if tmpsig.max_hash != 0 { 0 } else { tmpsig.num };
let hash_function = match tmpsig.molecule.to_lowercase().as_ref() {
"protein" => HashFunctions::murmur64_protein,
"dayhoff" => HashFunctions::murmur64_dayhoff,
"hp" => HashFunctions::murmur64_hp,
"dna" => HashFunctions::murmur64_DNA,
_ => unimplemented!(), // TODO: throw error here
};
let current_max;
// This shouldn't be necessary, but at some point we
// created signatures with unordered mins =(