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
#![deny(warnings)]

#[cfg(feature = "cffi")]
#[macro_use]
mod macros;

#[cfg(feature = "cffi")]
mod c_ffi;

mod annoy_index_search_result;

mod lib_impl;
mod pqentry;

#[cfg(feature = "cffi")]
pub use crate::c_ffi::*;

use crate::lib_impl::MmapExtensions;

use memmap::{Mmap, MmapOptions};
use std::f32;
use std::fs;
use std::fs::File;
use std::vec::Vec;

use crate::annoy_index_search_result::AnnoyIndexSearchResult;
use crate::pqentry::PriorityQueueEntry;

const INT32_SIZE: i32 = 4;
const FLOAT32_SIZE: i32 = 4;

#[derive(PartialEq)]
pub enum IndexType {
    Angular = 0,
    Euclidean = 1,
}

pub struct AnnoyIndex {
    pub dimension: i32,
    pub index_type: IndexType,
    index_type_offset: i32,
    k_node_header_style: i32,
    min_leaf_size: i32,
    node_size: i64,
    mmap: Mmap,
    roots: Vec<i64>,
}

pub trait AnnoyIndexSearchApi {
    fn get_item_vector(&self, item_index: i64) -> Vec<f32>;
    fn get_nearest(
        &self,
        query_vector: &[f32],
        n_results: usize,
        search_k: i32,
        should_include_distance: bool,
    ) -> Vec<AnnoyIndexSearchResult>;
}

impl AnnoyIndex {
    pub fn load(dimension: i32, index_file_path: &str, index_type: IndexType) -> AnnoyIndex {
        let index_type_offset: i32 = if index_type == IndexType::Angular {
            4
        } else {
            8
        };
        let k_node_header_style: i32 = if index_type == IndexType::Angular {
            12
        } else {
            16
        };
        let min_leaf_size = dimension + 2;
        let node_size = k_node_header_style as i64 + FLOAT32_SIZE as i64 * dimension as i64;
        let file = File::open(index_file_path).expect("fail to open file");
        let file_metadata = fs::metadata(index_file_path).expect("failed to load file");
        let file_size = file_metadata.len();
        let mmap = unsafe {
            MmapOptions::new()
                .map(&file)
                .expect("failed to map the file")
        };

        let mut roots: Vec<i64> = Vec::new();
        let mut m: i32 = -1;
        let mut i = file_size as i64 - node_size as i64;
        while i >= 0 {
            let k = mmap.read_i32(i as usize);
            if m == -1 || k == m {
                roots.push(i);
                m = k;
            } else {
                break;
            }

            i -= node_size as i64;
        }

        // hacky fix: since the last root precedes the copy of all roots, delete it
        if roots.len() > 1
            && get_l_child_offset(&mmap, *roots.first().unwrap(), node_size, index_type_offset)
                == get_r_child_offset(&mmap, *roots.last().unwrap(), node_size, index_type_offset)
        {
            let last_index = roots.len() - 1;
            roots.remove(last_index);
        }

        let index = AnnoyIndex {
            dimension: dimension,
            index_type: index_type,
            index_type_offset: index_type_offset,
            k_node_header_style: k_node_header_style,
            min_leaf_size: min_leaf_size,
            node_size: node_size,
            mmap: mmap,
            roots: roots,
        };

        return index;
    }
}

fn get_l_child_offset(
    mmap: &Mmap,
    top_node_offset: i64,
    node_size: i64,
    index_type_offset: i32,
) -> i64 {
    let child_offset = top_node_offset as usize + index_type_offset as usize;
    let child = mmap.read_i32(child_offset) as i64;
    return node_size * child;
}

fn get_r_child_offset(
    mmap: &Mmap,
    top_node_offset: i64,
    node_size: i64,
    index_type_offset: i32,
) -> i64 {
    let child_offset = top_node_offset as usize + index_type_offset as usize + 4;
    let child = mmap.read_i32(child_offset) as i64;
    return node_size * child;
}

fn get_node_vector(index: &AnnoyIndex, node_offset: i64) -> Vec<f32> {
    let mut vec: Vec<f32> = Vec::with_capacity(index.dimension as usize);
    for i in 0..index.dimension as usize {
        let idx =
            node_offset as usize + index.k_node_header_style as usize + i * (FLOAT32_SIZE as usize);
        let value = index.mmap.read_f32(idx);
        vec.push(value);
    }

    return vec;
}

impl AnnoyIndexSearchApi for AnnoyIndex {
    fn get_item_vector(&self, item_index: i64) -> Vec<f32> {
        let node_offset = item_index * self.node_size;
        return get_node_vector(self, node_offset);
    }

    fn get_nearest(
        &self,
        query_vector: &[f32],
        n_results: usize,
        search_k: i32,
        should_include_distance: bool,
    ) -> Vec<AnnoyIndexSearchResult> {
        let mut search_k_mut = search_k;
        if search_k <= 0 {
            search_k_mut = n_results as i32 * (self.roots.len() as i32);
        }

        let mut pq =
            Vec::<PriorityQueueEntry>::with_capacity(self.roots.len() * (FLOAT32_SIZE as usize));
        for r in &self.roots {
            pq.push(PriorityQueueEntry::new(std::f32::MAX, *r));
        }

        let mut nearest_neighbors = std::collections::HashSet::<i64>::new();
        while nearest_neighbors.len() < search_k_mut as usize && !pq.is_empty() {
            pq.sort_by(|a, b| b.margin.partial_cmp(&a.margin).unwrap());
            let top = pq.remove(0);
            let top_node_offset = top.node_offset;
            let n_descendants = self.mmap.read_i32(top_node_offset as usize);
            let v = get_node_vector(self, top_node_offset);
            if n_descendants == 1 {
                if is_zero_vec(&v) {
                    continue;
                }

                nearest_neighbors.insert(top_node_offset / self.node_size);
            } else if n_descendants <= self.min_leaf_size {
                for i in 0..n_descendants as usize {
                    let j = self
                        .mmap
                        .read_i32(top_node_offset as usize + i * INT32_SIZE as usize)
                        as i64;
                    if is_zero_vec(&get_node_vector(self, j)) {
                        continue;
                    }

                    nearest_neighbors.insert(j);
                }
            } else {
                let margin = if self.index_type == IndexType::Angular {
                    cosine_margin_no_norm(v.as_slice(), query_vector)
                } else {
                    euclidean_margin(
                        v.as_slice(),
                        query_vector,
                        get_node_bias(self, top_node_offset),
                    )
                };
                let l_child = get_l_child_offset(
                    &self.mmap,
                    top_node_offset,
                    self.node_size,
                    self.index_type_offset,
                );
                let r_child = get_r_child_offset(
                    &self.mmap,
                    top_node_offset,
                    self.node_size,
                    self.index_type_offset,
                );
                pq.push(PriorityQueueEntry {
                    margin: top.margin.min(-margin),
                    node_offset: l_child,
                });
                pq.push(PriorityQueueEntry {
                    margin: top.margin.min(margin),
                    node_offset: r_child,
                });
            }
        }

        let mut sorted_nns: Vec<PriorityQueueEntry> = Vec::new();
        for nn in nearest_neighbors {
            let v = self.get_item_vector(nn);
            if !is_zero_vec(&v) {
                let param1 = v.as_slice();
                let param2 = query_vector;
                sorted_nns.push(PriorityQueueEntry {
                    margin: if self.index_type == IndexType::Angular {
                        cosine_distance(param1, param2)
                    } else {
                        euclidean_distance(param1, param2)
                    },
                    node_offset: nn,
                });
            }
        }

        sorted_nns.sort_by(|a, b| a.margin.partial_cmp(&b.margin).unwrap());

        let mut results: Vec<AnnoyIndexSearchResult> = Vec::with_capacity(n_results);
        for i in 0..n_results.min(sorted_nns.len()) {
            let nn = &sorted_nns[i];
            results.push(AnnoyIndexSearchResult {
                id: nn.node_offset,
                distance: if should_include_distance {
                    nn.margin.sqrt()
                } else {
                    0.0
                },
            });
        }

        return results;
    }
}

fn is_zero_vec(v: &Vec<f32>) -> bool {
    for item in v {
        if *item != 0.0 {
            return false;
        }
    }

    return true;
}

fn cosine_margin_no_norm(u: &[f32], v: &[f32]) -> f32 {
    let mut d: f32 = 0.0;
    for i in 0..u.len() {
        d += u[i] * v[i];
    }

    return d;
}

fn euclidean_margin(u: &[f32], v: &[f32], bias: f32) -> f32 {
    let mut d: f32 = bias;
    for i in 0..u.len() {
        d += u[i] * v[i];
    }

    return d;
}

fn cosine_distance(u: &[f32], v: &[f32]) -> f32 {
    // want to calculate (a/|a| - b/|b|)^2
    // = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b|
    // = 2 - 2cos
    let mut pp: f32 = 0.0;
    let mut qq: f32 = 0.0;
    let mut pq: f32 = 0.0;

    for i in 0..u.len() {
        let _u = u[i];
        let _v = v[i];
        pp += _u.powi(2);
        qq += _v.powi(2);
        pq += _u * _v;
    }

    let ppqq = pp * qq;
    return if ppqq > 0.0 {
        2.0 - 2.0 * pq / ppqq.sqrt()
    } else {
        2.0
    };
}

fn euclidean_distance(u: &[f32], v: &[f32]) -> f32 {
    let mut diff: Vec<f32> = Vec::with_capacity(u.len());
    for i in 0..u.len() {
        diff[i] = u[i] - v[i];
    }

    let mut n: f32 = 0.0;
    for item in diff {
        n += item.powi(2);
    }

    return n.sqrt();
}

fn get_node_bias(index: &AnnoyIndex, node_offset: i64) -> f32 {
    return index.mmap.read_f32(node_offset as usize + 4);
}