File size: 6,845 Bytes
8ef2d83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//! # Proximity
//!
//! Trait and implementations for measuring how related two points are.
//!
//! This is one of the five primitives of ARMS:
//! `Proximity: fn(a, b) -> f32` - How related?
//!
//! Proximity functions are pluggable - use whichever fits your use case.

use super::Point;

/// Trait for measuring proximity between points
///
/// Higher values typically mean more similar/related.
/// The exact semantics depend on the implementation.
pub trait Proximity: Send + Sync {
    /// Compute proximity between two points
    ///
    /// Both points must have the same dimensionality.
    fn proximity(&self, a: &Point, b: &Point) -> f32;

    /// Name of this proximity function (for debugging/config)
    fn name(&self) -> &'static str;
}

// ============================================================================
// IMPLEMENTATIONS
// ============================================================================

/// Cosine similarity
///
/// Measures the cosine of the angle between two vectors.
/// Returns a value in [-1, 1] where 1 means identical direction.
///
/// Best for: Normalized vectors, semantic similarity.
#[derive(Clone, Copy, Debug, Default)]
pub struct Cosine;

impl Proximity for Cosine {
    fn proximity(&self, a: &Point, b: &Point) -> f32 {
        assert_eq!(
            a.dimensionality(),
            b.dimensionality(),
            "Points must have same dimensionality"
        );

        let dot: f32 = a
            .dims()
            .iter()
            .zip(b.dims().iter())
            .map(|(x, y)| x * y)
            .sum();

        let mag_a = a.magnitude();
        let mag_b = b.magnitude();

        if mag_a == 0.0 || mag_b == 0.0 {
            return 0.0;
        }

        dot / (mag_a * mag_b)
    }

    fn name(&self) -> &'static str {
        "cosine"
    }
}

/// Euclidean distance
///
/// The straight-line distance between two points.
/// Returns a value in [0, ∞) where 0 means identical.
///
/// Note: This returns DISTANCE, not similarity.
/// Lower values = more similar.
#[derive(Clone, Copy, Debug, Default)]
pub struct Euclidean;

impl Proximity for Euclidean {
    fn proximity(&self, a: &Point, b: &Point) -> f32 {
        assert_eq!(
            a.dimensionality(),
            b.dimensionality(),
            "Points must have same dimensionality"
        );

        let dist_sq: f32 = a
            .dims()
            .iter()
            .zip(b.dims().iter())
            .map(|(x, y)| (x - y).powi(2))
            .sum();

        dist_sq.sqrt()
    }

    fn name(&self) -> &'static str {
        "euclidean"
    }
}

/// Squared Euclidean distance
///
/// Same ordering as Euclidean but faster (no sqrt).
/// Use when you only need to compare distances, not absolute values.
#[derive(Clone, Copy, Debug, Default)]
pub struct EuclideanSquared;

impl Proximity for EuclideanSquared {
    fn proximity(&self, a: &Point, b: &Point) -> f32 {
        assert_eq!(
            a.dimensionality(),
            b.dimensionality(),
            "Points must have same dimensionality"
        );

        a.dims()
            .iter()
            .zip(b.dims().iter())
            .map(|(x, y)| (x - y).powi(2))
            .sum()
    }

    fn name(&self) -> &'static str {
        "euclidean_squared"
    }
}

/// Dot product
///
/// The raw dot product without normalization.
/// Returns a value that depends on magnitudes.
///
/// Best for: When magnitude matters, not just direction.
#[derive(Clone, Copy, Debug, Default)]
pub struct DotProduct;

impl Proximity for DotProduct {
    fn proximity(&self, a: &Point, b: &Point) -> f32 {
        assert_eq!(
            a.dimensionality(),
            b.dimensionality(),
            "Points must have same dimensionality"
        );

        a.dims()
            .iter()
            .zip(b.dims().iter())
            .map(|(x, y)| x * y)
            .sum()
    }

    fn name(&self) -> &'static str {
        "dot_product"
    }
}

/// Manhattan (L1) distance
///
/// Sum of absolute differences along each dimension.
/// Returns a value in [0, ∞) where 0 means identical.
#[derive(Clone, Copy, Debug, Default)]
pub struct Manhattan;

impl Proximity for Manhattan {
    fn proximity(&self, a: &Point, b: &Point) -> f32 {
        assert_eq!(
            a.dimensionality(),
            b.dimensionality(),
            "Points must have same dimensionality"
        );

        a.dims()
            .iter()
            .zip(b.dims().iter())
            .map(|(x, y)| (x - y).abs())
            .sum()
    }

    fn name(&self) -> &'static str {
        "manhattan"
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_cosine_identical() {
        let a = Point::new(vec![1.0, 0.0, 0.0]);
        let b = Point::new(vec![1.0, 0.0, 0.0]);
        let cos = Cosine.proximity(&a, &b);
        assert!((cos - 1.0).abs() < 0.0001);
    }

    #[test]
    fn test_cosine_opposite() {
        let a = Point::new(vec![1.0, 0.0, 0.0]);
        let b = Point::new(vec![-1.0, 0.0, 0.0]);
        let cos = Cosine.proximity(&a, &b);
        assert!((cos - (-1.0)).abs() < 0.0001);
    }

    #[test]
    fn test_cosine_orthogonal() {
        let a = Point::new(vec![1.0, 0.0, 0.0]);
        let b = Point::new(vec![0.0, 1.0, 0.0]);
        let cos = Cosine.proximity(&a, &b);
        assert!(cos.abs() < 0.0001);
    }

    #[test]
    fn test_euclidean() {
        let a = Point::new(vec![0.0, 0.0]);
        let b = Point::new(vec![3.0, 4.0]);
        let dist = Euclidean.proximity(&a, &b);
        assert!((dist - 5.0).abs() < 0.0001);
    }

    #[test]
    fn test_euclidean_squared() {
        let a = Point::new(vec![0.0, 0.0]);
        let b = Point::new(vec![3.0, 4.0]);
        let dist_sq = EuclideanSquared.proximity(&a, &b);
        assert!((dist_sq - 25.0).abs() < 0.0001);
    }

    #[test]
    fn test_dot_product() {
        let a = Point::new(vec![1.0, 2.0, 3.0]);
        let b = Point::new(vec![4.0, 5.0, 6.0]);
        let dot = DotProduct.proximity(&a, &b);
        // 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32
        assert!((dot - 32.0).abs() < 0.0001);
    }

    #[test]
    fn test_manhattan() {
        let a = Point::new(vec![0.0, 0.0]);
        let b = Point::new(vec![3.0, 4.0]);
        let dist = Manhattan.proximity(&a, &b);
        assert!((dist - 7.0).abs() < 0.0001);
    }

    #[test]
    fn test_proximity_names() {
        assert_eq!(Cosine.name(), "cosine");
        assert_eq!(Euclidean.name(), "euclidean");
        assert_eq!(DotProduct.name(), "dot_product");
        assert_eq!(Manhattan.name(), "manhattan");
    }

    #[test]
    #[should_panic(expected = "same dimensionality")]
    fn test_dimension_mismatch_panics() {
        let a = Point::new(vec![1.0, 2.0]);
        let b = Point::new(vec![1.0, 2.0, 3.0]);
        Cosine.proximity(&a, &b);
    }
}