Skip to main content

ares_vector/
distance.rs

1//! Distance metrics for vector similarity.
2//!
3//! Provides various distance/similarity metrics used for comparing vectors.
4
5use crate::error::{Error, Result};
6use std::fmt;
7
8/// Distance metric for vector similarity calculations.
9///
10/// The choice of distance metric significantly affects search results:
11///
12/// - **Cosine**: Best for normalized embeddings (most LLM embeddings).
13/// - **Euclidean**: Best for raw feature vectors where magnitude matters.
14/// - **DotProduct**: Best for vectors that are already normalized.
15/// - **Manhattan**: Robust to outliers, good for sparse vectors.
16#[derive(
17    Debug, Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize,
18)]
19pub enum DistanceMetric {
20    /// Cosine similarity (1 - cosine_distance).
21    ///
22    /// Measures the angle between vectors, ignoring magnitude.
23    /// Range: [-1, 1], where 1 means identical direction.
24    ///
25    /// Best for: Text embeddings, semantic similarity.
26    #[default]
27    Cosine,
28
29    /// Euclidean (L2) distance.
30    ///
31    /// Measures the straight-line distance between vectors.
32    /// Range: [0, ∞), where 0 means identical vectors.
33    ///
34    /// Best for: Image features, geographic coordinates.
35    Euclidean,
36
37    /// Dot product (inner product).
38    ///
39    /// Measures alignment of vectors including magnitude.
40    /// Range: (-∞, ∞), where higher is more similar.
41    ///
42    /// Best for: Pre-normalized vectors, recommendation systems.
43    DotProduct,
44
45    /// Manhattan (L1) distance.
46    ///
47    /// Sum of absolute differences across dimensions.
48    /// Range: [0, ∞), where 0 means identical vectors.
49    ///
50    /// Best for: Sparse vectors, grid-based navigation.
51    Manhattan,
52}
53
54impl DistanceMetric {
55    /// Mathematical formula for this metric's distance computation.
56    pub fn formula(&self) -> &'static str {
57        match self {
58            DistanceMetric::Cosine => "1 - (a·b) / (||a|| · ||b||)",
59            DistanceMetric::Euclidean => "√(Σ(aᵢ - bᵢ)²)",
60            DistanceMetric::DotProduct => "-(a·b)",
61            DistanceMetric::Manhattan => "Σ|aᵢ - bᵢ|",
62        }
63    }
64
65    /// Compute the similarity score between two vectors.
66    ///
67    /// Returns a score where **higher is more similar** for all metrics.
68    /// For distance-based metrics (Euclidean, Manhattan), this returns
69    /// a transformed score in [0, 1] range.
70    ///
71    /// # Panics
72    ///
73    /// Panics if vectors have different lengths.
74    #[inline]
75    pub fn similarity(&self, a: &[f32], b: &[f32]) -> f32 {
76        debug_assert_eq!(a.len(), b.len(), "Vector dimensions must match");
77
78        match self {
79            DistanceMetric::Cosine => cosine_similarity(a, b),
80            DistanceMetric::Euclidean => {
81                let dist = l2_distance(a, b);
82                // Transform to similarity: 1 / (1 + dist)
83                1.0 / (1.0 + dist)
84            }
85            DistanceMetric::DotProduct => dot_product(a, b),
86            DistanceMetric::Manhattan => {
87                let dist = manhattan_distance(a, b);
88                // Transform to similarity: 1 / (1 + dist)
89                1.0 / (1.0 + dist)
90            }
91        }
92    }
93
94    /// Compute the raw distance between two vectors.
95    ///
96    /// Returns a distance where **lower means more similar**.
97    /// For similarity-based metrics (Cosine, DotProduct), this returns
98    /// a transformed distance.
99    #[inline]
100    pub fn distance(&self, a: &[f32], b: &[f32]) -> f32 {
101        debug_assert_eq!(a.len(), b.len(), "Vector dimensions must match");
102
103        match self {
104            DistanceMetric::Cosine => 1.0 - cosine_similarity(a, b),
105            DistanceMetric::Euclidean => l2_distance(a, b),
106            DistanceMetric::DotProduct => -dot_product(a, b), // Negate for distance
107            DistanceMetric::Manhattan => manhattan_distance(a, b),
108        }
109    }
110
111    /// Returns true if this metric is similarity-based (higher = more similar).
112    pub fn is_similarity_based(&self) -> bool {
113        matches!(self, DistanceMetric::Cosine | DistanceMetric::DotProduct)
114    }
115
116    /// Returns true if this metric is distance-based (lower = more similar).
117    pub fn is_distance_based(&self) -> bool {
118        matches!(self, DistanceMetric::Euclidean | DistanceMetric::Manhattan)
119    }
120
121    /// Get the name of this distance metric.
122    pub fn name(&self) -> &'static str {
123        match self {
124            DistanceMetric::Cosine => "cosine",
125            DistanceMetric::Euclidean => "euclidean",
126            DistanceMetric::DotProduct => "dot_product",
127            DistanceMetric::Manhattan => "manhattan",
128        }
129    }
130}
131
132impl fmt::Display for DistanceMetric {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(f, "{}", self.name())
135    }
136}
137
138/// Display wrapper that renders the mathematical formula for a metric.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub struct DistanceFormula(pub DistanceMetric);
141
142impl fmt::Display for DistanceFormula {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        write!(f, "{}", self.0.formula())
145    }
146}
147
148impl std::str::FromStr for DistanceMetric {
149    type Err = String;
150
151    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
152        match s.to_lowercase().as_str() {
153            "cosine" | "cos" => Ok(DistanceMetric::Cosine),
154            "euclidean" | "l2" | "euclid" => Ok(DistanceMetric::Euclidean),
155            "dot" | "dot_product" | "dotproduct" | "inner" => Ok(DistanceMetric::DotProduct),
156            "manhattan" | "l1" | "taxicab" => Ok(DistanceMetric::Manhattan),
157            _ => Err(format!("Unknown distance metric: {s}")),
158        }
159    }
160}
161
162// ============================================================================
163// Pure vector helpers
164// ============================================================================
165
166/// Validate that `vector` has `expected` dimensions and finite values.
167pub fn validate_dimensions(vector: &[f32], expected: usize) -> Result<()> {
168    if vector.len() != expected {
169        return Err(Error::DimensionMismatch {
170            expected,
171            actual: vector.len(),
172        });
173    }
174    if expected == 0 {
175        return Err(Error::InvalidVector("Dimensions must be > 0".into()));
176    }
177    if vector.iter().any(|v| !v.is_finite()) {
178        return Err(Error::InvalidVector(
179            "Vector contains NaN or Inf".to_string(),
180        ));
181    }
182    Ok(())
183}
184
185/// Validate that two vectors share the same dimension and contain finite values.
186pub fn validate_dimension_pair(a: &[f32], b: &[f32]) -> Result<()> {
187    if a.len() != b.len() {
188        return Err(Error::DimensionMismatch {
189            expected: a.len(),
190            actual: b.len(),
191        });
192    }
193    validate_dimensions(a, a.len())
194}
195
196/// L2-normalize `vector` in place.
197pub fn normalize_vector(vector: &mut [f32]) -> Result<()> {
198    validate_dimensions(vector, vector.len())?;
199
200    let norm_sq: f32 = vector.iter().map(|x| x * x).sum();
201    if !norm_sq.is_finite() {
202        return Err(Error::NumericalInstability(
203            "Norm squared overflow".to_string(),
204        ));
205    }
206
207    let norm = norm_sq.sqrt();
208    if norm == 0.0 {
209        return Err(Error::InvalidVector("Cannot normalize zero vector".into()));
210    }
211    if !norm.is_finite() {
212        return Err(Error::NumericalInstability("Norm overflow".to_string()));
213    }
214
215    for x in vector.iter_mut() {
216        *x /= norm;
217    }
218    Ok(())
219}
220
221/// Compute cosine similarity between two vectors.
222///
223/// Returns a value in [-1, 1] where 1 means identical direction.
224/// Zero-norm vectors yield 0.0.
225#[inline]
226pub fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
227    debug_assert_eq!(a.len(), b.len());
228
229    let mut dot = 0.0f32;
230    let mut norm_a = 0.0f32;
231    let mut norm_b = 0.0f32;
232
233    let chunks = a.len() / 4;
234    let remainder = a.len() % 4;
235
236    for i in 0..chunks {
237        let base = i * 4;
238        dot += a[base] * b[base]
239            + a[base + 1] * b[base + 1]
240            + a[base + 2] * b[base + 2]
241            + a[base + 3] * b[base + 3];
242        norm_a += a[base] * a[base]
243            + a[base + 1] * a[base + 1]
244            + a[base + 2] * a[base + 2]
245            + a[base + 3] * a[base + 3];
246        norm_b += b[base] * b[base]
247            + b[base + 1] * b[base + 1]
248            + b[base + 2] * b[base + 2]
249            + b[base + 3] * b[base + 3];
250    }
251
252    let start = chunks * 4;
253    for i in 0..remainder {
254        let idx = start + i;
255        dot += a[idx] * b[idx];
256        norm_a += a[idx] * a[idx];
257        norm_b += b[idx] * b[idx];
258    }
259
260    let denom = (norm_a * norm_b).sqrt();
261    if denom == 0.0 { 0.0 } else { dot / denom }
262}
263
264/// Compute Euclidean (L2) distance between two vectors.
265#[inline]
266pub fn l2_distance(a: &[f32], b: &[f32]) -> f32 {
267    debug_assert_eq!(a.len(), b.len());
268
269    let mut sum = 0.0f32;
270
271    let chunks = a.len() / 4;
272    let remainder = a.len() % 4;
273
274    for i in 0..chunks {
275        let base = i * 4;
276        let d0 = a[base] - b[base];
277        let d1 = a[base + 1] - b[base + 1];
278        let d2 = a[base + 2] - b[base + 2];
279        let d3 = a[base + 3] - b[base + 3];
280        sum += d0 * d0 + d1 * d1 + d2 * d2 + d3 * d3;
281    }
282
283    let start = chunks * 4;
284    for i in 0..remainder {
285        let idx = start + i;
286        let d = a[idx] - b[idx];
287        sum += d * d;
288    }
289
290    if !sum.is_finite() {
291        return f32::INFINITY;
292    }
293
294    sum.sqrt()
295}
296
297/// Compute dot product between two vectors.
298#[inline]
299pub fn dot_product(a: &[f32], b: &[f32]) -> f32 {
300    debug_assert_eq!(a.len(), b.len());
301
302    let mut sum = 0.0f32;
303
304    let chunks = a.len() / 4;
305    let remainder = a.len() % 4;
306
307    for i in 0..chunks {
308        let base = i * 4;
309        sum += a[base] * b[base]
310            + a[base + 1] * b[base + 1]
311            + a[base + 2] * b[base + 2]
312            + a[base + 3] * b[base + 3];
313    }
314
315    let start = chunks * 4;
316    for i in 0..remainder {
317        let idx = start + i;
318        sum += a[idx] * b[idx];
319    }
320
321    sum
322}
323
324/// Compute Manhattan (L1) distance between two vectors.
325#[inline]
326fn manhattan_distance(a: &[f32], b: &[f32]) -> f32 {
327    let mut sum = 0.0f32;
328
329    for (x, y) in a.iter().zip(b.iter()) {
330        sum += (x - y).abs();
331    }
332
333    sum
334}
335
336// ============================================================================
337// Scalar reference implementations (for equivalence tests)
338// ============================================================================
339
340#[cfg(test)]
341#[inline]
342fn cosine_similarity_scalar(a: &[f32], b: &[f32]) -> f32 {
343    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
344    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
345    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
346    let denom = norm_a * norm_b;
347    if denom == 0.0 { 0.0 } else { dot / denom }
348}
349
350#[cfg(test)]
351#[inline]
352fn l2_distance_scalar(a: &[f32], b: &[f32]) -> f32 {
353    let sum: f32 = a
354        .iter()
355        .zip(b)
356        .map(|(x, y)| {
357            let d = x - y;
358            d * d
359        })
360        .sum();
361    if !sum.is_finite() {
362        return f32::INFINITY;
363    }
364    sum.sqrt()
365}
366
367#[cfg(test)]
368#[inline]
369fn dot_product_scalar(a: &[f32], b: &[f32]) -> f32 {
370    a.iter().zip(b).map(|(x, y)| x * y).sum()
371}
372
373// ============================================================================
374// HNSW Distance Adapter
375// ============================================================================
376
377use anndists::dist::Distance;
378use anndists::dist::distances::{DistCosine, DistDot, DistL1, DistL2};
379
380/// Trait for creating HNSW distance instances.
381pub trait HnswDistance: Clone + Send + Sync + 'static {
382    /// Create the HNSW distance function type.
383    type Dist: Distance<f32> + Clone + Send + Sync + Default;
384
385    /// Create a new instance of the distance function.
386    fn create() -> Self::Dist;
387}
388
389/// Cosine distance adapter for HNSW.
390#[derive(Clone)]
391pub struct CosineDistance;
392
393impl HnswDistance for CosineDistance {
394    type Dist = DistCosine;
395    fn create() -> Self::Dist {
396        DistCosine {}
397    }
398}
399
400/// Euclidean distance adapter for HNSW.
401#[derive(Clone)]
402pub struct EuclideanDistance;
403
404impl HnswDistance for EuclideanDistance {
405    type Dist = DistL2;
406    fn create() -> Self::Dist {
407        DistL2 {}
408    }
409}
410
411/// Dot product distance adapter for HNSW.
412#[derive(Clone)]
413pub struct DotProductDistance;
414
415impl HnswDistance for DotProductDistance {
416    type Dist = DistDot;
417    fn create() -> Self::Dist {
418        DistDot {}
419    }
420}
421
422/// Manhattan distance adapter for HNSW.
423#[derive(Clone)]
424pub struct ManhattanDistance;
425
426impl HnswDistance for ManhattanDistance {
427    type Dist = DistL1;
428    fn create() -> Self::Dist {
429        DistL1 {}
430    }
431}
432
433/// pgvector distance operator for supported metrics.
434pub fn distance_operator(metric: DistanceMetric) -> Option<&'static str> {
435    match metric {
436        DistanceMetric::Cosine => Some("<=>"),
437        DistanceMetric::Euclidean => Some("<->"),
438        DistanceMetric::DotProduct => Some("<#>"),
439        DistanceMetric::Manhattan => None,
440    }
441}
442
443// ============================================================================
444// Tests
445// ============================================================================
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450    use crate::error::Error;
451
452    const EPS: f32 = 1e-4;
453
454    fn approx_eq(a: f32, b: f32) -> bool {
455        (a - b).abs() < EPS
456    }
457
458    // ------------------------------------------------------------------------
459    // DistanceMetric: serde, Display, Clone, Debug
460    // ------------------------------------------------------------------------
461
462    #[cfg(feature = "serde")]
463    #[test]
464    fn metric_serde_roundtrip_cosine() {
465        let metric = DistanceMetric::Cosine;
466        let json = serde_json::to_string(&metric).unwrap();
467        let decoded: DistanceMetric = serde_json::from_str(&json).unwrap();
468        assert_eq!(decoded, metric);
469    }
470
471    #[cfg(feature = "serde")]
472    #[test]
473    fn metric_serde_roundtrip_euclidean() {
474        let metric = DistanceMetric::Euclidean;
475        let json = serde_json::to_string(&metric).unwrap();
476        let decoded: DistanceMetric = serde_json::from_str(&json).unwrap();
477        assert_eq!(decoded, DistanceMetric::Euclidean);
478    }
479
480    #[cfg(feature = "serde")]
481    #[test]
482    fn metric_serde_roundtrip_dot_product() {
483        let metric = DistanceMetric::DotProduct;
484        let json = serde_json::to_string(&metric).unwrap();
485        let decoded: DistanceMetric = serde_json::from_str(&json).unwrap();
486        assert_eq!(decoded, DistanceMetric::DotProduct);
487    }
488
489    #[test]
490    fn metric_debug_clone() {
491        let metric = DistanceMetric::Cosine;
492        let cloned = metric;
493        assert_eq!(format!("{metric:?}"), format!("{cloned:?}"));
494        assert_eq!(cloned, metric);
495    }
496
497    #[test]
498    fn metric_display_name() {
499        assert_eq!(DistanceMetric::Cosine.to_string(), "cosine");
500        assert_eq!(DistanceMetric::Euclidean.to_string(), "euclidean");
501        assert_eq!(format!("{}", DistanceMetric::DotProduct), "dot_product");
502    }
503
504    #[test]
505    fn metric_formula_display() {
506        assert_eq!(
507            DistanceFormula(DistanceMetric::Cosine).to_string(),
508            "1 - (a·b) / (||a|| · ||b||)"
509        );
510        assert_eq!(
511            DistanceFormula(DistanceMetric::Euclidean).to_string(),
512            "√(Σ(aᵢ - bᵢ)²)"
513        );
514        assert_eq!(
515            DistanceFormula(DistanceMetric::DotProduct).to_string(),
516            "-(a·b)"
517        );
518        assert_eq!(
519            DistanceFormula(DistanceMetric::Manhattan).to_string(),
520            "Σ|aᵢ - bᵢ|"
521        );
522    }
523
524    #[test]
525    fn test_metric_from_str() {
526        assert_eq!(
527            "cosine".parse::<DistanceMetric>().unwrap(),
528            DistanceMetric::Cosine
529        );
530        assert_eq!(
531            "l2".parse::<DistanceMetric>().unwrap(),
532            DistanceMetric::Euclidean
533        );
534        assert_eq!(
535            "dot".parse::<DistanceMetric>().unwrap(),
536            DistanceMetric::DotProduct
537        );
538        assert!("unknown".parse::<DistanceMetric>().is_err());
539    }
540
541    #[test]
542    fn test_default_metric_is_cosine() {
543        assert_eq!(DistanceMetric::default(), DistanceMetric::Cosine);
544    }
545
546    #[test]
547    fn test_metric_kind_flags() {
548        assert!(DistanceMetric::Cosine.is_similarity_based());
549        assert!(DistanceMetric::DotProduct.is_similarity_based());
550        assert!(!DistanceMetric::Euclidean.is_similarity_based());
551        assert!(DistanceMetric::Manhattan.is_distance_based());
552    }
553
554    // ------------------------------------------------------------------------
555    // cosine_similarity
556    // ------------------------------------------------------------------------
557
558    #[test]
559    fn cosine_unit_vectors_identical() {
560        let a = [1.0f32, 0.0, 0.0];
561        let b = [1.0, 0.0, 0.0];
562        assert!(approx_eq(cosine_similarity(&a, &b), 1.0));
563    }
564
565    #[test]
566    fn cosine_orthogonal_vectors() {
567        let a = [1.0f32, 0.0, 0.0];
568        let b = [0.0, 1.0, 0.0];
569        assert!(cosine_similarity(&a, &b).abs() < EPS);
570    }
571
572    #[test]
573    fn cosine_opposite_vectors() {
574        let a = [1.0f32, 0.0, 0.0];
575        let b = [-1.0, 0.0, 0.0];
576        assert!(approx_eq(cosine_similarity(&a, &b), -1.0));
577    }
578
579    #[test]
580    fn cosine_zero_vectors() {
581        let a = [0.0f32, 0.0, 0.0];
582        let b = [0.0, 0.0, 0.0];
583        assert!(cosine_similarity(&a, &b).abs() < EPS);
584    }
585
586    #[test]
587    fn cosine_one_zero_vector() {
588        let a = [0.0f32, 0.0];
589        let b = [1.0, 1.0];
590        assert!(cosine_similarity(&a, &b).abs() < EPS);
591    }
592
593    #[test]
594    fn cosine_parallel_large_scale() {
595        let a = [1_000.0f32, 2_000.0, 3_000.0];
596        let b = [2_000.0, 4_000.0, 6_000.0];
597        let sim = cosine_similarity(&a, &b);
598        assert!(approx_eq(sim, 1.0));
599        assert!((-1.0..=1.0).contains(&sim));
600    }
601
602    // ------------------------------------------------------------------------
603    // l2_distance
604    // ------------------------------------------------------------------------
605
606    #[test]
607    fn l2_identical_vectors_zero() {
608        let a = [1.0f32, 2.0, 3.0];
609        let b = [1.0, 2.0, 3.0];
610        assert!(l2_distance(&a, &b).abs() < EPS);
611    }
612
613    #[test]
614    fn l2_unit_distance() {
615        let a = [0.0f32, 0.0, 0.0];
616        let b = [1.0, 0.0, 0.0];
617        assert!(approx_eq(l2_distance(&a, &b), 1.0));
618    }
619
620    #[test]
621    fn l2_large_distance() {
622        let a = [0.0f32, 0.0];
623        let b = [3.0, 4.0];
624        assert!(approx_eq(l2_distance(&a, &b), 5.0));
625    }
626
627    #[test]
628    fn l2_overflow_returns_infinity() {
629        let a = [f32::MAX, 0.0];
630        let b = [0.0, 0.0];
631        assert!(l2_distance(&a, &b).is_infinite());
632    }
633
634    // ------------------------------------------------------------------------
635    // dot_product
636    // ------------------------------------------------------------------------
637
638    #[test]
639    fn dot_product_positive() {
640        let a = [1.0f32, 2.0, 3.0];
641        let b = [4.0, 5.0, 6.0];
642        assert!(approx_eq(dot_product(&a, &b), 32.0));
643    }
644
645    #[test]
646    fn dot_product_negative() {
647        let a = [1.0f32, 0.0];
648        let b = [-1.0, 0.0];
649        assert!(approx_eq(dot_product(&a, &b), -1.0));
650    }
651
652    #[test]
653    fn dot_product_zero_vectors() {
654        let a = [0.0f32, 0.0];
655        let b = [0.0, 0.0];
656        assert!(dot_product(&a, &b).abs() < EPS);
657    }
658
659    #[test]
660    fn dot_product_magnitude_scaling() {
661        let a = [2.0f32, 0.0];
662        let b = [3.0f32, 0.0];
663        assert!(approx_eq(dot_product(&a, &b), 6.0));
664        let unit_a = [1.0f32, 0.0];
665        let unit_b = [1.0f32, 0.0];
666        assert!(approx_eq(dot_product(&unit_a, &unit_b), 1.0));
667    }
668
669    // ------------------------------------------------------------------------
670    // validate_dimensions
671    // ------------------------------------------------------------------------
672
673    #[test]
674    fn validate_dimensions_matching() {
675        let v = [1.0f32, 2.0, 3.0];
676        assert!(validate_dimensions(&v, 3).is_ok());
677    }
678
679    #[test]
680    fn validate_dimensions_mismatch() {
681        let v = [1.0f32, 2.0];
682        let err = validate_dimensions(&v, 3).unwrap_err();
683        assert!(matches!(
684            err,
685            Error::DimensionMismatch {
686                expected: 3,
687                actual: 2
688            }
689        ));
690    }
691
692    #[test]
693    fn validate_dimensions_empty_vector() {
694        let v: [f32; 0] = [];
695        let err = validate_dimensions(&v, 0).unwrap_err();
696        assert!(matches!(err, Error::InvalidVector(_)));
697    }
698
699    #[test]
700    fn validate_dimensions_nan() {
701        let v = [1.0f32, f32::NAN];
702        let err = validate_dimensions(&v, 2).unwrap_err();
703        assert!(matches!(err, Error::InvalidVector(_)));
704    }
705
706    #[test]
707    fn validate_dimensions_inf() {
708        let v = [1.0f32, f32::INFINITY];
709        let err = validate_dimensions(&v, 2).unwrap_err();
710        assert!(matches!(err, Error::InvalidVector(_)));
711    }
712
713    #[test]
714    fn validate_dimension_pair_matching() {
715        let a = [1.0f32, 2.0];
716        let b = [3.0, 4.0];
717        assert!(validate_dimension_pair(&a, &b).is_ok());
718    }
719
720    #[test]
721    fn validate_dimension_pair_mismatch() {
722        let a = [1.0f32];
723        let b = [1.0, 2.0];
724        let err = validate_dimension_pair(&a, &b).unwrap_err();
725        assert!(matches!(
726            err,
727            Error::DimensionMismatch {
728                expected: 1,
729                actual: 2
730            }
731        ));
732    }
733
734    // ------------------------------------------------------------------------
735    // normalize_vector
736    // ------------------------------------------------------------------------
737
738    #[test]
739    fn normalize_vector_unit_norm() {
740        let mut v = [3.0f32, 4.0];
741        normalize_vector(&mut v).unwrap();
742        let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
743        assert!(approx_eq(norm, 1.0));
744        assert!(approx_eq(v[0], 0.6));
745        assert!(approx_eq(v[1], 0.8));
746    }
747
748    #[test]
749    fn normalize_vector_zero_error() {
750        let mut v = [0.0f32, 0.0];
751        let err = normalize_vector(&mut v).unwrap_err();
752        assert!(matches!(err, Error::InvalidVector(_)));
753    }
754
755    #[test]
756    fn normalize_vector_negative_components() {
757        let mut v = [-3.0f32, 4.0];
758        normalize_vector(&mut v).unwrap();
759        assert!(approx_eq(v[0], -0.6));
760        assert!(approx_eq(v[1], 0.8));
761    }
762
763    // ------------------------------------------------------------------------
764    // Scalar vs optimized equivalence
765    // ------------------------------------------------------------------------
766
767    #[test]
768    fn scalar_cosine_matches_optimized() {
769        let a: Vec<f32> = (0..65).map(|i| (i as f32 * 0.1).sin()).collect();
770        let b: Vec<f32> = (0..65).map(|i| (i as f32 * 0.2).cos()).collect();
771        let opt = cosine_similarity(&a, &b);
772        let scalar = cosine_similarity_scalar(&a, &b);
773        assert!(approx_eq(opt, scalar));
774    }
775
776    #[test]
777    fn scalar_l2_matches_optimized() {
778        let a: Vec<f32> = (0..65).map(|i| i as f32).collect();
779        let b: Vec<f32> = (0..65).map(|i| (i as f32) + 0.5).collect();
780        assert!(approx_eq(l2_distance(&a, &b), l2_distance_scalar(&a, &b)));
781    }
782
783    #[test]
784    fn scalar_dot_matches_optimized() {
785        let a: Vec<f32> = (0..65).map(|i| i as f32 * 0.01).collect();
786        let b: Vec<f32> = (0..65).map(|i| (65 - i) as f32 * 0.01).collect();
787        assert!(approx_eq(dot_product(&a, &b), dot_product_scalar(&a, &b)));
788    }
789
790    // ------------------------------------------------------------------------
791    // Error variant display (distance-related paths)
792    // ------------------------------------------------------------------------
793
794    #[test]
795    fn error_dimension_mismatch_display() {
796        let err = Error::DimensionMismatch {
797            expected: 384,
798            actual: 128,
799        };
800        assert_eq!(err.to_string(), "Dimension mismatch: expected 384, got 128");
801    }
802
803    #[test]
804    fn error_invalid_vector_display() {
805        let err = Error::InvalidVector("contains NaN".into());
806        assert_eq!(err.to_string(), "Invalid vector: contains NaN");
807    }
808
809    #[test]
810    fn error_numerical_instability_display() {
811        let err = Error::NumericalInstability("norm overflow".into());
812        assert_eq!(err.to_string(), "Numerical instability: norm overflow");
813    }
814
815    // ------------------------------------------------------------------------
816    // DistanceMetric integration (existing coverage)
817    // ------------------------------------------------------------------------
818
819    #[test]
820    fn test_cosine_identical() {
821        let a = vec![1.0, 0.0, 0.0];
822        let b = vec![1.0, 0.0, 0.0];
823        assert!(approx_eq(DistanceMetric::Cosine.similarity(&a, &b), 1.0));
824    }
825
826    #[test]
827    fn test_cosine_orthogonal() {
828        let a = vec![1.0, 0.0, 0.0];
829        let b = vec![0.0, 1.0, 0.0];
830        assert!(DistanceMetric::Cosine.similarity(&a, &b).abs() < EPS);
831    }
832
833    #[test]
834    fn test_euclidean_identical() {
835        let a = vec![1.0, 2.0, 3.0];
836        let b = vec![1.0, 2.0, 3.0];
837        assert!(DistanceMetric::Euclidean.distance(&a, &b).abs() < EPS);
838    }
839
840    #[test]
841    fn test_manhattan_distance() {
842        let a = vec![0.0, 0.0, 0.0];
843        let b = vec![1.0, 2.0, 3.0];
844        assert!(approx_eq(DistanceMetric::Manhattan.distance(&a, &b), 6.0));
845    }
846
847    #[test]
848    fn test_dot_product_metric() {
849        let a = vec![1.0, 2.0, 3.0];
850        let b = vec![4.0, 5.0, 6.0];
851        assert!(approx_eq(
852            DistanceMetric::DotProduct.similarity(&a, &b),
853            32.0
854        ));
855    }
856
857    #[test]
858    fn test_single_dimension_vectors() {
859        let a = vec![3.0];
860        let b = vec![4.0];
861        assert!(approx_eq(DistanceMetric::Euclidean.distance(&a, &b), 1.0));
862        assert!(approx_eq(
863            DistanceMetric::DotProduct.similarity(&a, &b),
864            12.0
865        ));
866    }
867
868    #[test]
869    fn test_large_vectors_unrolled_paths() {
870        let n = 128;
871        let a: Vec<f32> = (0..n).map(|i| i as f32 * 0.01).collect();
872        let b = a.clone();
873        assert!(DistanceMetric::Euclidean.distance(&a, &b).abs() < EPS);
874        assert!(approx_eq(DistanceMetric::Cosine.similarity(&a, &b), 1.0));
875    }
876
877    #[test]
878    fn test_euclidean_and_manhattan_similarity_transform() {
879        let a = vec![0.0, 0.0];
880        let b = vec![3.0, 4.0];
881        let euclid_sim = DistanceMetric::Euclidean.similarity(&a, &b);
882        assert!(approx_eq(euclid_sim, 1.0 / 6.0));
883        let manhattan_sim = DistanceMetric::Manhattan.similarity(&a, &b);
884        assert!(approx_eq(manhattan_sim, 1.0 / 8.0));
885    }
886
887    #[test]
888    fn test_hnsw_distance_adapters() {
889        use anndists::dist::Distance;
890
891        let a = vec![1.0f32, 0.0, 0.0];
892        let b = vec![0.0f32, 1.0, 0.0];
893        let same = vec![1.0f32, 0.0, 0.0];
894
895        let cosine = CosineDistance::create();
896        assert!(approx_eq(cosine.eval(&a, &b), 1.0));
897        assert!(cosine.eval(&same, &a).abs() < EPS);
898
899        let l2 = EuclideanDistance::create();
900        assert!(approx_eq(l2.eval(&a, &b), std::f32::consts::SQRT_2));
901        assert!(l2.eval(&same, &a).abs() < EPS);
902
903        let dot = DotProductDistance::create();
904        assert!(approx_eq(dot.eval(&a, &b), 1.0));
905        assert!(dot.eval(&same, &a).abs() < EPS);
906
907        let l1 = ManhattanDistance::create();
908        assert!(approx_eq(l1.eval(&a, &b), 2.0));
909        assert!(l1.eval(&same, &a).abs() < EPS);
910    }
911    #[test]
912    fn distance_operator_maps_pgvector_tokens() {
913        assert_eq!(distance_operator(DistanceMetric::Euclidean), Some("<->"));
914        assert_eq!(distance_operator(DistanceMetric::DotProduct), Some("<#>"));
915        assert_eq!(distance_operator(DistanceMetric::Cosine), Some("<=>"));
916        assert_eq!(distance_operator(DistanceMetric::Manhattan), None);
917    }
918
919    #[test]
920    fn distance_metric_serde_roundtrip() {
921        for metric in [
922            DistanceMetric::Cosine,
923            DistanceMetric::Euclidean,
924            DistanceMetric::DotProduct,
925            DistanceMetric::Manhattan,
926        ] {
927            let json = serde_json::to_string(&metric).expect("serialize");
928            let restored: DistanceMetric = serde_json::from_str(&json).expect("deserialize");
929            assert_eq!(restored, metric);
930        }
931    }
932}