rig/embeddings/
distance.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
pub trait VectorDistance {
    /// Get dot product of two embedding vectors
    fn dot_product(&self, other: &Self) -> f64;

    /// Get cosine similarity of two embedding vectors.
    /// If `normalized` is true, the dot product is returned.
    fn cosine_similarity(&self, other: &Self, normalized: bool) -> f64;

    /// Get angular distance of two embedding vectors.
    fn angular_distance(&self, other: &Self, normalized: bool) -> f64;

    /// Get euclidean distance of two embedding vectors.
    fn euclidean_distance(&self, other: &Self) -> f64;

    /// Get manhattan distance of two embedding vectors.
    fn manhattan_distance(&self, other: &Self) -> f64;

    /// Get chebyshev distance of two embedding vectors.
    fn chebyshev_distance(&self, other: &Self) -> f64;
}

#[cfg(not(feature = "rayon"))]
impl VectorDistance for crate::embeddings::Embedding {
    fn dot_product(&self, other: &Self) -> f64 {
        self.vec
            .iter()
            .zip(other.vec.iter())
            .map(|(x, y)| x * y)
            .sum()
    }

    fn cosine_similarity(&self, other: &Self, normalized: bool) -> f64 {
        let dot_product = self.dot_product(other);

        if normalized {
            dot_product
        } else {
            let magnitude1: f64 = self.vec.iter().map(|x| x.powi(2)).sum::<f64>().sqrt();
            let magnitude2: f64 = other.vec.iter().map(|x| x.powi(2)).sum::<f64>().sqrt();

            dot_product / (magnitude1 * magnitude2)
        }
    }

    fn angular_distance(&self, other: &Self, normalized: bool) -> f64 {
        let cosine_sim = self.cosine_similarity(other, normalized);
        cosine_sim.acos() / std::f64::consts::PI
    }

    fn euclidean_distance(&self, other: &Self) -> f64 {
        self.vec
            .iter()
            .zip(other.vec.iter())
            .map(|(x, y)| (x - y).powi(2))
            .sum::<f64>()
            .sqrt()
    }

    fn manhattan_distance(&self, other: &Self) -> f64 {
        self.vec
            .iter()
            .zip(other.vec.iter())
            .map(|(x, y)| (x - y).abs())
            .sum()
    }

    fn chebyshev_distance(&self, other: &Self) -> f64 {
        self.vec
            .iter()
            .zip(other.vec.iter())
            .map(|(x, y)| (x - y).abs())
            .fold(0.0, f64::max)
    }
}

#[cfg(feature = "rayon")]
mod rayon {
    use crate::embeddings::{distance::VectorDistance, Embedding};
    use rayon::prelude::*;

    impl VectorDistance for Embedding {
        fn dot_product(&self, other: &Self) -> f64 {
            self.vec
                .par_iter()
                .zip(other.vec.par_iter())
                .map(|(x, y)| x * y)
                .sum()
        }

        fn cosine_similarity(&self, other: &Self, normalized: bool) -> f64 {
            let dot_product = self.dot_product(other);

            if normalized {
                dot_product
            } else {
                let magnitude1: f64 = self.vec.par_iter().map(|x| x.powi(2)).sum::<f64>().sqrt();
                let magnitude2: f64 = other.vec.par_iter().map(|x| x.powi(2)).sum::<f64>().sqrt();

                dot_product / (magnitude1 * magnitude2)
            }
        }

        fn angular_distance(&self, other: &Self, normalized: bool) -> f64 {
            let cosine_sim = self.cosine_similarity(other, normalized);
            cosine_sim.acos() / std::f64::consts::PI
        }

        fn euclidean_distance(&self, other: &Self) -> f64 {
            self.vec
                .par_iter()
                .zip(other.vec.par_iter())
                .map(|(x, y)| (x - y).powi(2))
                .sum::<f64>()
                .sqrt()
        }

        fn manhattan_distance(&self, other: &Self) -> f64 {
            self.vec
                .par_iter()
                .zip(other.vec.par_iter())
                .map(|(x, y)| (x - y).abs())
                .sum()
        }

        fn chebyshev_distance(&self, other: &Self) -> f64 {
            self.vec
                .iter()
                .zip(other.vec.iter())
                .map(|(x, y)| (x - y).abs())
                .fold(0.0, f64::max)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::VectorDistance;
    use crate::embeddings::Embedding;

    fn embeddings() -> (Embedding, Embedding) {
        let embedding_1 = Embedding {
            document: "test".to_string(),
            vec: vec![1.0, 2.0, 3.0],
        };

        let embedding_2 = Embedding {
            document: "test".to_string(),
            vec: vec![1.0, 5.0, 7.0],
        };

        (embedding_1, embedding_2)
    }

    #[test]
    fn test_dot_product() {
        let (embedding_1, embedding_2) = embeddings();

        assert_eq!(embedding_1.dot_product(&embedding_2), 32.0)
    }

    #[test]
    fn test_cosine_similarity() {
        let (embedding_1, embedding_2) = embeddings();

        assert_eq!(
            embedding_1.cosine_similarity(&embedding_2, false),
            0.9875414397573881
        )
    }

    #[test]
    fn test_angular_distance() {
        let (embedding_1, embedding_2) = embeddings();

        assert_eq!(
            embedding_1.angular_distance(&embedding_2, false),
            0.0502980301830343
        )
    }

    #[test]
    fn test_euclidean_distance() {
        let (embedding_1, embedding_2) = embeddings();

        assert_eq!(embedding_1.euclidean_distance(&embedding_2), 5.0)
    }

    #[test]
    fn test_manhattan_distance() {
        let (embedding_1, embedding_2) = embeddings();

        assert_eq!(embedding_1.manhattan_distance(&embedding_2), 7.0)
    }

    #[test]
    fn test_chebyshev_distance() {
        let (embedding_1, embedding_2) = embeddings();

        assert_eq!(embedding_1.chebyshev_distance(&embedding_2), 4.0)
    }
}