-
Notifications
You must be signed in to change notification settings - Fork 80
/
bigsi.rs
228 lines (185 loc) · 6.3 KB
/
bigsi.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
use std::collections::HashMap;
use std::path::Path;
use failure::{Error, Fail};
use fixedbitset::FixedBitSet;
use typed_builder::TypedBuilder;
use crate::index::{Comparable, Index};
use crate::signature::{Signature, SigsTrait};
use crate::sketch::nodegraph::Nodegraph;
use crate::sketch::Sketch;
use crate::HashIntoType;
#[derive(Clone, TypedBuilder)]
pub struct BIGSI<L> {
matrix: Vec<FixedBitSet>,
ksize: usize,
datasets: Vec<L>,
//#[builder(setter(skip))]
//storage: Rc<dyn Storage>,
}
#[derive(Debug, Fail)]
pub enum BIGSIError {
#[fail(display = "BIGSI doesn't support this method")]
MethodDisabled,
}
impl<L> BIGSI<L> {
pub fn new(bf_size: usize, ksize: usize) -> BIGSI<L> {
let mut matrix = Vec::with_capacity(bf_size);
for _ in 0..bf_size {
// TODO: figure initial capacity for each row
matrix.push(FixedBitSet::with_capacity(100));
}
BIGSI {
matrix,
ksize,
datasets: Vec::new(),
}
}
}
impl BIGSI<Signature> {
pub fn add(&mut self, dataset: Signature) {
let mut ng = Nodegraph::new(&[self.matrix.len()], self.ksize);
// TODO: select correct minhash
if let Sketch::MinHash(mh) = &dataset.signatures[0] {
for h in &mh.mins {
ng.count(*h);
}
} else {
// TODO: what if it is not a mh?
unimplemented!()
}
self.datasets.push(dataset);
let col = self.datasets.len() - 1;
for pos in ng.bs[0].ones() {
let bs = &mut self.matrix[pos];
if bs.len() == col {
bs.grow(col + col / 2);
}
bs.insert(col);
}
}
pub fn query(&self, hash: HashIntoType) -> impl Iterator<Item = usize> + '_ {
let pos = hash as usize % self.matrix.len();
let bs = &self.matrix[pos];
bs.ones()
}
pub fn query_datasets(&self, hash: HashIntoType) -> impl Iterator<Item = Signature> + '_ {
self.query(hash).map(move |pos| self.datasets[pos].clone())
}
}
impl Index for BIGSI<Signature> {
type Item = Signature;
fn find<F>(
&self,
_search_fn: F,
_sig: &Self::Item,
_threshold: f64,
) -> Result<Vec<&Self::Item>, Error>
where
F: Fn(&dyn Comparable<Self::Item>, &Self::Item, f64) -> bool,
{
// TODO: is there a better way than making this a runtime check?
//Err(BIGSIError::MethodDisabled.into())
unimplemented!();
}
fn search(
&self,
sig: &Self::Item,
threshold: f64,
containment: bool,
) -> Result<Vec<&Self::Item>, Error> {
let mut results = Vec::new();
//TODO: still assuming one mh in the signature!
if let Sketch::MinHash(hashes) = &sig.signatures[0] {
let mut counter: HashMap<usize, usize> = HashMap::with_capacity(hashes.size());
for hash in &hashes.mins {
self.query(*hash)
.map(|dataset_idx| {
let idx = counter.entry(dataset_idx).or_insert(0);
*idx += 1;
})
.count();
}
for (idx, count) in counter {
let match_sig = &self.datasets[idx];
//TODO: still assuming one mh in the signature!
let match_mh = match_sig.signatures[0].size();
let score = if containment {
count as f64 / hashes.size() as f64
} else {
count as f64 / (hashes.size() + match_mh - count) as f64
};
if score >= threshold {
results.push(match_sig)
}
}
Ok(results)
} else {
// TODO: what if it is not a minhash?
unimplemented!()
}
}
fn insert(&mut self, node: &Self::Item) -> Result<(), Error> {
self.add(node.clone());
Ok(())
}
fn save<P: AsRef<Path>>(&self, _path: P) -> Result<(), Error> {
unimplemented!()
}
fn load<P: AsRef<Path>>(_path: P) -> Result<(), Error> {
unimplemented!()
}
fn datasets(&self) -> Vec<Self::Item> {
unimplemented!()
}
}
#[cfg(test)]
mod test {
use std::fs::File;
use std::io::BufReader;
use std::path::PathBuf;
use std::rc::Rc;
use lazy_init::Lazy;
use super::BIGSI;
use crate::index::storage::ReadData;
use crate::index::Dataset;
use crate::index::{Index, MHBT};
use crate::signature::Signature;
#[test]
fn bigsi_sbt_oracle() {
let mut filename = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
filename.push("tests/test-data/v5.sbt.json");
let sbt = MHBT::from_path(filename).expect("Loading error");
let mut bigsi = BIGSI::new(10000, 10);
let datasets = sbt.datasets();
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, 31, Some("DNA".into()), None).unwrap();
let sig_data = sigs[0].clone();
let data = Lazy::new();
data.get_or_create(|| sig_data);
let leaf = Dataset::builder()
.data(Rc::new(data))
.filename("")
.name("")
.metadata("")
.storage(None)
.build();
for l in &datasets {
let data = l.data().unwrap();
bigsi.insert(data).expect("insertion error!");
}
let results_sbt = sbt.search(&leaf, 0.5, false).unwrap();
assert_eq!(results_sbt.len(), 1);
let data = (*leaf.data).get().unwrap();
let results_bigsi = bigsi.search(&data, 0.5, false).unwrap();
assert_eq!(results_bigsi.len(), 1);
assert_eq!(results_sbt.len(), results_bigsi.len());
let results_sbt = sbt.search(&leaf, 0.1, false).unwrap();
assert_eq!(results_sbt.len(), 2);
let data = (*leaf.data).get().unwrap();
let results_bigsi = bigsi.search(&data, 0.1, false).unwrap();
assert_eq!(results_bigsi.len(), 2);
assert_eq!(results_sbt.len(), results_bigsi.len());
}
}