Skip to main content

autoagents_core/embeddings/
distance.rs

1/// Basic vector distance helpers.
2pub trait VectorDistance {
3    fn cosine_similarity(&self, other: &Self, normalize: bool) -> f32;
4}
5
6impl VectorDistance for [f32] {
7    fn cosine_similarity(&self, other: &Self, normalize: bool) -> f32 {
8        let dot = self
9            .iter()
10            .zip(other.iter())
11            .map(|(a, b)| a * b)
12            .sum::<f32>();
13
14        if !normalize {
15            return dot;
16        }
17
18        let norm_a = self.iter().map(|a| a * a).sum::<f32>().sqrt();
19        let norm_b = other.iter().map(|b| b * b).sum::<f32>().sqrt();
20
21        if norm_a == 0.0 || norm_b == 0.0 {
22            0.0
23        } else {
24            dot / (norm_a * norm_b)
25        }
26    }
27}
28
29impl VectorDistance for Vec<f32> {
30    fn cosine_similarity(&self, other: &Self, normalize: bool) -> f32 {
31        self.as_slice()
32            .cosine_similarity(other.as_slice(), normalize)
33    }
34}