aboutsummaryrefslogtreecommitdiff
path: root/src/embedders/vecmetric.rs
blob: 474a6d0b53a775b356baa85e3fd6188266a9608c (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
use super::MetricElem;
use serde::{Deserialize, Serialize};

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

#[derive(Deserialize, Serialize)]
pub struct CosineSimilarity(pub Vec<f32>);
#[derive(Deserialize, Serialize)]
pub struct EuclidianDistance(pub Vec<f32>);
#[derive(Deserialize, Serialize)]
pub struct ManhattenDistance(pub Vec<f32>);

impl VecMetric for CosineSimilarity {}
impl VecMetric for EuclidianDistance {}
impl VecMetric for ManhattenDistance {}
#[rustfmt::skip] impl From<Vec<f32>> for CosineSimilarity { 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 CosineSimilarity {
    fn dist(&self, _other: &Self) -> f64 {
        todo!()
    }
}
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
    }
}