aboutsummaryrefslogtreecommitdiff
path: root/src/embedders/vecmetric.rs
blob: 2ebd170d680226e723b5ed8ae44fa71e953381af (plain)
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
use super::MetricElem;
use bincode::{Decode, Encode};

pub trait VecMetric: MetricElem + From<Vec<f32>> {}

#[derive(Decode, Encode)]
pub struct AngularDistance(pub Vec<f32>);
#[derive(Decode, Encode)]
pub struct CosineDistance(pub Vec<f32>);
#[derive(Decode, Encode)]
pub struct EuclidianDistance(pub Vec<f32>);
#[derive(Decode, Encode)]
pub struct ManhattenDistance(pub Vec<f32>);

impl VecMetric for AngularDistance {}
impl VecMetric for CosineDistance {}
impl VecMetric for EuclidianDistance {}
impl VecMetric for ManhattenDistance {}
#[rustfmt::skip] impl From<Vec<f32>> for AngularDistance { fn from(value: Vec<f32>) -> Self { Self(value) } }
#[rustfmt::skip] impl From<Vec<f32>> for CosineDistance { fn from(value: Vec<f32>) -> Self { Self(value) } }
#[rustfmt::skip] impl From<Vec<f32>> for EuclidianDistance { fn from(value: Vec<f32>) -> Self { Self(value) } }
#[rustfmt::skip] impl From<Vec<f32>> for ManhattenDistance { fn from(value: Vec<f32>) -> Self { Self(value) } }

impl MetricElem for AngularDistance {
    fn dist(&self, other: &Self) -> f64 {
        let x = self
            .0
            .iter()
            .zip(other.0.iter())
            .map(|(a, b)| *a * *b)
            .sum::<f32>();
        let mag_a = self.0.iter().map(|x| x.powi(2)).sum::<f32>();
        let mag_b = other.0.iter().map(|x| x.powi(2)).sum::<f32>();
        let cossim = x / (mag_a * mag_b).sqrt();
        // clamp is require because floating point errors
        cossim.clamp(-1., 1.).acos() as f64
    }
}
impl MetricElem for CosineDistance {
    fn dist(&self, other: &Self) -> f64 {
        self.0
            .iter()
            .zip(other.0.iter())
            .map(|(a, b)| (*a - *b) * (*b - *a))
            .sum::<f32>()
            .sqrt() as f64
    }
}
impl MetricElem for EuclidianDistance {
    fn dist(&self, other: &Self) -> f64 {
        self.0
            .iter()
            .zip(other.0.iter())
            .map(|(a, b)| (a - b).powf(2.))
            .sum::<f32>()
            .sqrt() as f64
    }
}
impl MetricElem for ManhattenDistance {
    fn dist(&self, other: &Self) -> f64 {
        self.0
            .iter()
            .zip(other.0.iter())
            .map(|(a, b)| (a - b).abs())
            .sum::<f32>() as f64
    }
}