use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum DistanceMetric {
#[default]
Cosine,
Euclidean,
DotProduct,
Manhattan,
}
impl DistanceMetric {
#[inline]
pub fn similarity(&self, a: &[f32], b: &[f32]) -> f32 {
debug_assert_eq!(a.len(), b.len(), "Vector dimensions must match");
match self {
DistanceMetric::Cosine => cosine_similarity(a, b),
DistanceMetric::Euclidean => {
let dist = euclidean_distance(a, b);
1.0 / (1.0 + dist)
}
DistanceMetric::DotProduct => dot_product(a, b),
DistanceMetric::Manhattan => {
let dist = manhattan_distance(a, b);
1.0 / (1.0 + dist)
}
}
}
#[inline]
pub fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
debug_assert_eq!(a.len(), b.len(), "Vector dimensions must match");
match self {
DistanceMetric::Cosine => 1.0 - cosine_similarity(a, b),
DistanceMetric::Euclidean => euclidean_distance(a, b),
DistanceMetric::DotProduct => -dot_product(a, b), DistanceMetric::Manhattan => manhattan_distance(a, b),
}
}
pub fn is_similarity_based(&self) -> bool {
matches!(self, DistanceMetric::Cosine | DistanceMetric::DotProduct)
}
pub fn is_distance_based(&self) -> bool {
matches!(self, DistanceMetric::Euclidean | DistanceMetric::Manhattan)
}
pub fn name(&self) -> &'static str {
match self {
DistanceMetric::Cosine => "cosine",
DistanceMetric::Euclidean => "euclidean",
DistanceMetric::DotProduct => "dot_product",
DistanceMetric::Manhattan => "manhattan",
}
}
}
impl fmt::Display for DistanceMetric {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl std::str::FromStr for DistanceMetric {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"cosine" | "cos" => Ok(DistanceMetric::Cosine),
"euclidean" | "l2" | "euclid" => Ok(DistanceMetric::Euclidean),
"dot" | "dot_product" | "dotproduct" | "inner" => Ok(DistanceMetric::DotProduct),
"manhattan" | "l1" | "taxicab" => Ok(DistanceMetric::Manhattan),
_ => Err(format!("Unknown distance metric: {}", s)),
}
}
}
#[inline]
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
let mut dot = 0.0f32;
let mut norm_a = 0.0f32;
let mut norm_b = 0.0f32;
let chunks = a.len() / 4;
let remainder = a.len() % 4;
for i in 0..chunks {
let base = i * 4;
dot += a[base] * b[base]
+ a[base + 1] * b[base + 1]
+ a[base + 2] * b[base + 2]
+ a[base + 3] * b[base + 3];
norm_a += a[base] * a[base]
+ a[base + 1] * a[base + 1]
+ a[base + 2] * a[base + 2]
+ a[base + 3] * a[base + 3];
norm_b += b[base] * b[base]
+ b[base + 1] * b[base + 1]
+ b[base + 2] * b[base + 2]
+ b[base + 3] * b[base + 3];
}
let start = chunks * 4;
for i in 0..remainder {
let idx = start + i;
dot += a[idx] * b[idx];
norm_a += a[idx] * a[idx];
norm_b += b[idx] * b[idx];
}
let denom = (norm_a * norm_b).sqrt();
if denom == 0.0 {
0.0
} else {
dot / denom
}
}
#[inline]
fn euclidean_distance(a: &[f32], b: &[f32]) -> f32 {
let mut sum = 0.0f32;
let chunks = a.len() / 4;
let remainder = a.len() % 4;
for i in 0..chunks {
let base = i * 4;
let d0 = a[base] - b[base];
let d1 = a[base + 1] - b[base + 1];
let d2 = a[base + 2] - b[base + 2];
let d3 = a[base + 3] - b[base + 3];
sum += d0 * d0 + d1 * d1 + d2 * d2 + d3 * d3;
}
let start = chunks * 4;
for i in 0..remainder {
let idx = start + i;
let d = a[idx] - b[idx];
sum += d * d;
}
sum.sqrt()
}
#[inline]
fn dot_product(a: &[f32], b: &[f32]) -> f32 {
let mut sum = 0.0f32;
let chunks = a.len() / 4;
let remainder = a.len() % 4;
for i in 0..chunks {
let base = i * 4;
sum += a[base] * b[base]
+ a[base + 1] * b[base + 1]
+ a[base + 2] * b[base + 2]
+ a[base + 3] * b[base + 3];
}
let start = chunks * 4;
for i in 0..remainder {
let idx = start + i;
sum += a[idx] * b[idx];
}
sum
}
#[inline]
fn manhattan_distance(a: &[f32], b: &[f32]) -> f32 {
let mut sum = 0.0f32;
for (x, y) in a.iter().zip(b.iter()) {
sum += (x - y).abs();
}
sum
}
use anndists::dist::distances::{DistCosine, DistDot, DistL1, DistL2};
use anndists::dist::Distance;
pub trait HnswDistance: Clone + Send + Sync + 'static {
type Dist: Distance<f32> + Clone + Send + Sync + Default;
fn create() -> Self::Dist;
}
#[derive(Clone)]
pub struct CosineDistance;
impl HnswDistance for CosineDistance {
type Dist = DistCosine;
fn create() -> Self::Dist {
DistCosine {}
}
}
#[derive(Clone)]
pub struct EuclideanDistance;
impl HnswDistance for EuclideanDistance {
type Dist = DistL2;
fn create() -> Self::Dist {
DistL2 {}
}
}
#[derive(Clone)]
pub struct DotProductDistance;
impl HnswDistance for DotProductDistance {
type Dist = DistDot;
fn create() -> Self::Dist {
DistDot {}
}
}
#[derive(Clone)]
pub struct ManhattanDistance;
impl HnswDistance for ManhattanDistance {
type Dist = DistL1;
fn create() -> Self::Dist {
DistL1 {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cosine_identical() {
let a = vec![1.0, 0.0, 0.0];
let b = vec![1.0, 0.0, 0.0];
let sim = DistanceMetric::Cosine.similarity(&a, &b);
assert!((sim - 1.0).abs() < 0.0001);
}
#[test]
fn test_cosine_orthogonal() {
let a = vec![1.0, 0.0, 0.0];
let b = vec![0.0, 1.0, 0.0];
let sim = DistanceMetric::Cosine.similarity(&a, &b);
assert!(sim.abs() < 0.0001);
}
#[test]
fn test_cosine_opposite() {
let a = vec![1.0, 0.0, 0.0];
let b = vec![-1.0, 0.0, 0.0];
let sim = DistanceMetric::Cosine.similarity(&a, &b);
assert!((sim + 1.0).abs() < 0.0001);
}
#[test]
fn test_euclidean_identical() {
let a = vec![1.0, 2.0, 3.0];
let b = vec![1.0, 2.0, 3.0];
let dist = DistanceMetric::Euclidean.distance(&a, &b);
assert!(dist.abs() < 0.0001);
}
#[test]
fn test_euclidean_distance() {
let a = vec![0.0, 0.0, 0.0];
let b = vec![1.0, 0.0, 0.0];
let dist = DistanceMetric::Euclidean.distance(&a, &b);
assert!((dist - 1.0).abs() < 0.0001);
}
#[test]
fn test_manhattan_distance() {
let a = vec![0.0, 0.0, 0.0];
let b = vec![1.0, 2.0, 3.0];
let dist = DistanceMetric::Manhattan.distance(&a, &b);
assert!((dist - 6.0).abs() < 0.0001);
}
#[test]
fn test_dot_product() {
let a = vec![1.0, 2.0, 3.0];
let b = vec![4.0, 5.0, 6.0];
let sim = DistanceMetric::DotProduct.similarity(&a, &b);
assert!((sim - 32.0).abs() < 0.0001);
}
#[test]
fn test_metric_from_str() {
assert_eq!("cosine".parse::<DistanceMetric>().unwrap(), DistanceMetric::Cosine);
assert_eq!("l2".parse::<DistanceMetric>().unwrap(), DistanceMetric::Euclidean);
assert_eq!("dot".parse::<DistanceMetric>().unwrap(), DistanceMetric::DotProduct);
assert_eq!("manhattan".parse::<DistanceMetric>().unwrap(), DistanceMetric::Manhattan);
}
}