abd-clam 0.25.3

Clustering, Learning and Approximation with Manifolds
Documentation
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
//! CLAM-Accelerated K-nearest-neighbor Entropy-scaling Search.

use core::ops::Index;

use std::path::Path;

pub mod knn;
pub mod rnn;
mod search;
mod sharded;
mod singular;

use distances::Number;
use rayon::prelude::*;
use search::Search;
use sharded::RandomlySharded;
use singular::SingleShard;

use crate::{Dataset, Instance, PartitionCriteria, Tree};

/// CAKES search.
pub enum Cakes<I: Instance, U: Number, D: Dataset<I, U>> {
    /// Search with a single shard.
    SingleShard(SingleShard<I, U, D>),
    /// Search with multiple shards.
    RandomlySharded(RandomlySharded<I, U, D>),
}

impl<I: Instance, U: Number, D: Dataset<I, U>> Cakes<I, U, D> {
    /// Creates a new CAKES instance with a single shard dataset.
    ///
    /// # Arguments
    ///
    /// * `data` - The dataset to search.
    /// * `seed` - The seed to use for the random number generator.
    /// * `criteria` - The criteria to use for partitioning the tree.
    pub fn new(data: D, seed: Option<u64>, criteria: &PartitionCriteria<U>) -> Self {
        Self::SingleShard(SingleShard::new(data, seed, criteria))
    }

    /// Saves the Cakes structure to the given path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to save the Cakes structure to.
    ///
    /// # Errors
    ///
    /// * If the `path` does not exist.
    /// * If the `path` is not a valid directory.
    pub fn save(&self, path: &Path) -> Result<(), String> {
        match self {
            Self::SingleShard(ss) => ss.save(path),
            Self::RandomlySharded(rs) => rs.save(path),
        }
    }

    /// Loads the Cakes structure from the given path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to load the Cakes structure from.
    /// * `metric` - The metric to use for the search.
    /// * `is_expensive` - Whether the metric is expensive to compute.
    ///
    /// # Returns
    ///
    /// The Cakes structure.
    ///
    /// # Errors
    ///
    /// * If the `path` does not exist.
    /// * If the `path` is not a valid directory.
    /// * If the `path` does not contain a valid Cakes structure.
    pub fn load(path: &Path, metric: fn(&I, &I) -> U, is_expensive: bool) -> Result<Self, String> {
        if !path.exists() {
            return Err(format!("Path '{}' does not exist.", path.display()));
        }

        if !path.is_dir() {
            return Err(format!("Path '{}' is not a directory.", path.display()));
        }

        // Check if there is a subdirectory for `sample_shard`.
        let sample_shard_path = path.join("sample_shard");
        if sample_shard_path.exists() {
            let rs = RandomlySharded::load(path, metric, is_expensive)?;
            Ok(Self::RandomlySharded(rs))
        } else {
            let ss = SingleShard::load(path, metric, is_expensive)?;
            Ok(Self::SingleShard(ss))
        }
    }

    /// Returns the references to the tree(s) of the dataset.
    pub fn trees(&self) -> Vec<&Tree<I, U, D>> {
        match self {
            Self::SingleShard(ss) => vec![ss.tree()],
            Self::RandomlySharded(rs) => rs.shards().into_iter().map(SingleShard::tree).collect(),
        }
    }

    /// Returns the references to the shard(s) of the dataset.
    pub fn shards(&self) -> Vec<&D> {
        match self {
            Self::SingleShard(ss) => vec![ss.data()],
            Self::RandomlySharded(rs) => rs.shards().into_iter().map(SingleShard::data).collect(),
        }
    }

    /// Creates a new CAKES instance with a randomly sharded dataset.
    ///
    /// # Arguments
    ///
    /// * `shards` - The shards of the dataset to search.
    /// * `seed` - The seed to use for the random number generator.
    /// * `criteria` - The criteria to use for partitioning the tree.
    #[must_use]
    pub fn new_randomly_sharded(shards: Vec<D>, seed: Option<u64>, criteria: &PartitionCriteria<U>) -> Self {
        let shards = shards
            .into_iter()
            .map(|d| SingleShard::new(d, seed, criteria))
            .collect::<Vec<_>>();
        Self::RandomlySharded(RandomlySharded::new(shards))
    }

    /// Returns the number of shards in the dataset.
    pub fn num_shards(&self) -> usize {
        match self {
            Self::SingleShard(_) => 1,
            Self::RandomlySharded(rs) => rs.num_shards(),
        }
    }

    /// Returns the cardinalities of the shards in the dataset.
    pub fn shard_cardinalities(&self) -> Vec<usize> {
        match self {
            Self::SingleShard(ss) => ss.shard_cardinalities(),
            Self::RandomlySharded(rs) => rs.shard_cardinalities(),
        }
    }

    /// Returns the tuned RNN algorithm.
    pub fn tuned_rnn_algorithm(&self) -> rnn::Algorithm {
        match self {
            Self::SingleShard(ss) => ss.tuned_rnn_algorithm(),
            Self::RandomlySharded(rs) => rs.tuned_rnn_algorithm(),
        }
    }

    /// Performs RNN search on a batch of queries with the given algorithm.
    ///
    /// # Arguments
    ///
    /// * `queries` - The queries to search.
    /// * `radius` - The search radius.
    /// * `algo` - The algorithm to use.
    ///
    /// # Returns
    ///
    /// A vector of vectors of tuples containing the index of the instance and
    /// the distance to the query.
    pub fn batch_rnn_search(&self, queries: &[&I], radius: U, algo: rnn::Algorithm) -> Vec<Vec<(usize, U)>> {
        queries.par_iter().map(|q| self.rnn_search(q, radius, algo)).collect()
    }

    /// Performs an RNN search with the given algorithm.
    ///
    /// # Arguments
    ///
    /// * `query` - The query instance.
    /// * `radius` - The search radius.
    /// * `algo` - The algorithm to use.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the index of the instance and the distance
    /// to the query.
    pub fn rnn_search(&self, query: &I, radius: U, algo: rnn::Algorithm) -> Vec<(usize, U)> {
        match self {
            Self::SingleShard(ss) => ss.rnn_search(query, radius, algo),
            Self::RandomlySharded(rs) => rs.rnn_search(query, radius, algo),
        }
    }

    /// Performs Linear RNN search on a batch of queries.
    ///
    /// # Arguments
    ///
    /// * `queries` - The queries to search.
    /// * `radius` - The search radius.
    ///
    /// # Returns
    ///
    /// A vector of vectors of tuples containing the index of the instance and
    /// the distance to the query.
    pub fn batch_linear_rnn_search(&self, queries: &[&I], radius: U) -> Vec<Vec<(usize, U)>> {
        queries.par_iter().map(|q| self.linear_rnn_search(q, radius)).collect()
    }

    /// Performs a linear RNN search.
    ///
    /// # Arguments
    ///
    /// * `query` - The query instance.
    /// * `radius` - The search radius.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the index of the instance and the distance
    /// to the query.
    pub fn linear_rnn_search(&self, query: &I, radius: U) -> Vec<(usize, U)> {
        match self {
            Self::SingleShard(ss) => ss.linear_rnn_search(query, radius),
            Self::RandomlySharded(rs) => rs.linear_rnn_search(query, radius),
        }
    }

    /// Returns the tuned KNN algorithm.
    pub fn tuned_knn_algorithm(&self) -> knn::Algorithm {
        match self {
            Self::SingleShard(ss) => ss.tuned_knn_algorithm(),
            Self::RandomlySharded(rs) => rs.tuned_knn_algorithm(),
        }
    }

    /// Performs KNN search on a batch of queries with the given algorithm.
    ///
    /// # Arguments
    ///
    /// * `queries` - The queries to search.
    /// * `k` - The number of nearest neighbors to return.
    /// * `algo` - The algorithm to use.
    ///
    /// # Returns
    ///
    /// A vector of vectors of tuples containing the index of the instance and
    /// the distance to the query.
    pub fn batch_knn_search(&self, queries: &[&I], k: usize, algo: knn::Algorithm) -> Vec<Vec<(usize, U)>> {
        queries.par_iter().map(|q| self.knn_search(q, k, algo)).collect()
    }

    /// Performs a KNN search with the given algorithm.
    ///
    /// # Arguments
    ///
    /// * `query` - The query instance.
    /// * `k` - The number of nearest neighbors to return.
    /// * `algo` - The algorithm to use.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the index of the instance and the distance to the query.
    pub fn knn_search(&self, query: &I, k: usize, algo: knn::Algorithm) -> Vec<(usize, U)> {
        match self {
            Self::SingleShard(ss) => ss.knn_search(query, k, algo),
            Self::RandomlySharded(rs) => rs.knn_search(query, k, algo),
        }
    }

    /// Automatically finds the best RNN algorithm to use.
    ///
    /// # Arguments
    ///
    /// * `radius` - The search radius.
    /// * `tuning_depth` - The number of instances to use for tuning.
    pub fn auto_tune_rnn(&mut self, radius: U, tuning_depth: usize) {
        match self {
            Self::SingleShard(ss) => ss.auto_tune_rnn(radius, tuning_depth),
            Self::RandomlySharded(rs) => rs.auto_tune_rnn(radius, tuning_depth),
        }
    }

    /// Automatically finds the best KNN algorithm to use.
    ///
    /// # Arguments
    ///
    /// * `k` - The number of nearest neighbors to return.
    /// * `tuning_depth` - The number of instances to use for tuning.
    pub fn auto_tune_knn(&mut self, k: usize, tuning_depth: usize) {
        match self {
            Self::SingleShard(ss) => ss.auto_tune_knn(k, tuning_depth),
            Self::RandomlySharded(rs) => rs.auto_tune_knn(k, tuning_depth),
        }
    }

    /// Performs Linear KNN search on a batch of queries.
    ///
    /// # Arguments
    ///
    /// * `queries` - The queries to search.
    /// * `k` - The number of nearest neighbors to return.
    ///
    /// # Returns
    ///
    /// A vector of vectors of tuples containing the index of the instance and
    /// the distance to the query.
    pub fn batch_linear_knn_search(&self, queries: &[&I], k: usize) -> Vec<Vec<(usize, U)>> {
        queries.par_iter().map(|q| self.linear_knn_search(q, k)).collect()
    }

    /// Performs a linear KNN search.
    ///
    /// # Arguments
    ///
    /// * `query` - The query instance.
    /// * `k` - The number of nearest neighbors to return.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the index of the instance and the distance to the query.
    pub fn linear_knn_search(&self, query: &I, k: usize) -> Vec<(usize, U)> {
        match self {
            Self::SingleShard(ss) => ss.linear_knn_search(query, k),
            Self::RandomlySharded(rs) => rs.linear_knn_search(query, k),
        }
    }

    /// Performs RNN search on a batch of queries with the tuned algorithm.
    ///
    /// If the algorithm has not been tuned, this will use the default algorithm.
    ///
    /// # Arguments
    ///
    /// * `queries` - The queries to search.
    /// * `radius` - The search radius.
    ///
    /// # Returns
    ///
    /// A vector of vectors of tuples containing the index of the instance and
    /// the distance to the query.
    pub fn batch_tuned_rnn_search(&self, queries: &[&I], radius: U) -> Vec<Vec<(usize, U)>> {
        queries.par_iter().map(|q| self.tuned_rnn_search(q, radius)).collect()
    }

    /// Performs a RNN search with the tuned algorithm.
    ///
    /// If the algorithm has not been tuned, this will use the default algorithm.
    ///
    /// # Arguments
    ///
    /// * `query` - The query instance.
    /// * `radius` - The search radius.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the index of the instance and the distance to the query.
    pub fn tuned_rnn_search(&self, query: &I, radius: U) -> Vec<(usize, U)> {
        let algo = self.tuned_rnn_algorithm();
        self.rnn_search(query, radius, algo)
    }

    /// Performs KNN search on a batch of queries with the tuned algorithm.
    ///
    /// If the algorithm has not been tuned, this will use the default algorithm.
    ///
    /// # Arguments
    ///
    /// * `queries` - The queries to search.
    /// * `k` - The number of nearest neighbors to return.
    ///
    /// # Returns
    ///
    /// A vector of vectors of tuples containing the index of the instance and
    /// the distance to the query.
    pub fn batch_tuned_knn_search(&self, queries: &[&I], k: usize) -> Vec<Vec<(usize, U)>> {
        queries.par_iter().map(|q| self.tuned_knn_search(q, k)).collect()
    }

    /// Performs a KNN search with the tuned algorithm.
    ///
    /// If the algorithm has not been tuned, this will use the default algorithm.
    ///
    /// # Arguments
    ///
    /// * `query` - The query instance.
    /// * `k` - The number of nearest neighbors to return.
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the index of the instance and the distance to the query.
    pub fn tuned_knn_search(&self, query: &I, k: usize) -> Vec<(usize, U)> {
        let algo = self.tuned_knn_algorithm();
        self.knn_search(query, k, algo)
    }
}

impl<I, U, D> Index<usize> for Cakes<I, U, D>
where
    I: Instance,
    U: Number,
    D: Dataset<I, U>,
{
    type Output = I;

    fn index(&self, index: usize) -> &Self::Output {
        match self {
            Self::SingleShard(ss) => ss.data().index(index),
            Self::RandomlySharded(rs) => {
                let i = rs
                    .offsets()
                    .iter()
                    .enumerate()
                    .find(|(_, &o)| o > index)
                    .map_or_else(|| rs.num_shards() - 1, |(i, _)| i - 1);

                let index = index - rs.offsets()[i];
                rs.shards()[i].data().index(index)
            }
        }
    }
}