Skip to main content

nodedb_vector/
distance.rs

1//! Distance metrics for vector similarity search.
2//!
3//! Re-exports shared scalar implementations from `nodedb-types`.
4//! No SIMD intrinsics — works on all targets (native, WASM, iOS, Android).
5
6pub use nodedb_types::vector_distance::*;
7
8#[cfg(test)]
9mod tests {
10    use super::*;
11
12    #[test]
13    fn l2_identical_is_zero() {
14        let v = [1.0, 2.0, 3.0];
15        assert_eq!(l2_squared(&v, &v), 0.0);
16    }
17
18    #[test]
19    fn l2_known_distance() {
20        let a = [0.0, 0.0];
21        let b = [3.0, 4.0];
22        assert_eq!(l2_squared(&a, &b), 25.0);
23    }
24
25    #[test]
26    fn cosine_identical_is_zero() {
27        let v = [1.0, 2.0, 3.0];
28        assert!(cosine_distance(&v, &v) < 1e-6);
29    }
30
31    #[test]
32    fn cosine_orthogonal_is_one() {
33        let a = [1.0, 0.0];
34        let b = [0.0, 1.0];
35        assert!((cosine_distance(&a, &b) - 1.0).abs() < 1e-6);
36    }
37
38    #[test]
39    fn neg_ip_basic() {
40        let a = [1.0, 2.0];
41        let b = [3.0, 4.0];
42        assert_eq!(neg_inner_product(&a, &b), -11.0);
43    }
44
45    #[test]
46    fn manhattan_basic() {
47        let a = [1.0, 2.0, 3.0];
48        let b = [4.0, 6.0, 3.0];
49        assert_eq!(manhattan(&a, &b), 7.0);
50    }
51
52    #[test]
53    fn chebyshev_basic() {
54        let a = [1.0, 2.0, 3.0];
55        let b = [4.0, 6.0, 3.0];
56        assert_eq!(chebyshev(&a, &b), 4.0);
57    }
58
59    #[test]
60    fn hamming_basic() {
61        let a = [1.0, 0.0, 1.0, 0.0];
62        let b = [1.0, 1.0, 0.0, 0.0];
63        assert_eq!(hamming_f32(&a, &b), 2.0);
64    }
65
66    #[test]
67    fn jaccard_basic() {
68        let a = [1.0, 0.0, 1.0, 0.0];
69        let b = [1.0, 1.0, 0.0, 0.0];
70        let j = jaccard(&a, &b);
71        assert!((j - (1.0 - 1.0 / 3.0)).abs() < 1e-6);
72    }
73
74    #[test]
75    fn pearson_identical_is_zero() {
76        let v = [1.0, 2.0, 3.0, 4.0, 5.0];
77        assert!(pearson(&v, &v) < 1e-6);
78    }
79
80    #[test]
81    fn pearson_opposite_is_high() {
82        let a = [1.0, 2.0, 3.0, 4.0, 5.0];
83        let b = [5.0, 4.0, 3.0, 2.0, 1.0];
84        assert!(pearson(&a, &b) > 1.5);
85    }
86}