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 {
262        0.0
263    } else {
264        dot / denom
265    }
266}
267
268/// Compute Euclidean (L2) distance between two vectors.
269#[inline]
270pub fn l2_distance(a: &[f32], b: &[f32]) -> f32 {
271    debug_assert_eq!(a.len(), b.len());
272
273    let mut sum = 0.0f32;
274
275    let chunks = a.len() / 4;
276    let remainder = a.len() % 4;
277
278    for i in 0..chunks {
279        let base = i * 4;
280        let d0 = a[base] - b[base];
281        let d1 = a[base + 1] - b[base + 1];
282        let d2 = a[base + 2] - b[base + 2];
283        let d3 = a[base + 3] - b[base + 3];
284        sum += d0 * d0 + d1 * d1 + d2 * d2 + d3 * d3;
285    }
286
287    let start = chunks * 4;
288    for i in 0..remainder {
289        let idx = start + i;
290        let d = a[idx] - b[idx];
291        sum += d * d;
292    }
293
294    if !sum.is_finite() {
295        return f32::INFINITY;
296    }
297
298    sum.sqrt()
299}
300
301/// Compute dot product between two vectors.
302#[inline]
303pub fn dot_product(a: &[f32], b: &[f32]) -> f32 {
304    debug_assert_eq!(a.len(), b.len());
305
306    let mut sum = 0.0f32;
307
308    let chunks = a.len() / 4;
309    let remainder = a.len() % 4;
310
311    for i in 0..chunks {
312        let base = i * 4;
313        sum += a[base] * b[base]
314            + a[base + 1] * b[base + 1]
315            + a[base + 2] * b[base + 2]
316            + a[base + 3] * b[base + 3];
317    }
318
319    let start = chunks * 4;
320    for i in 0..remainder {
321        let idx = start + i;
322        sum += a[idx] * b[idx];
323    }
324
325    sum
326}
327
328/// Compute Manhattan (L1) distance between two vectors.
329#[inline]
330fn manhattan_distance(a: &[f32], b: &[f32]) -> f32 {
331    let mut sum = 0.0f32;
332
333    for (x, y) in a.iter().zip(b.iter()) {
334        sum += (x - y).abs();
335    }
336
337    sum
338}
339
340// ============================================================================
341// Scalar reference implementations (for equivalence tests)
342// ============================================================================
343
344#[cfg(test)]
345#[inline]
346fn cosine_similarity_scalar(a: &[f32], b: &[f32]) -> f32 {
347    let dot: f32 = a.iter().zip(b).map(|(x, y)| x * y).sum();
348    let norm_a: f32 = a.iter().map(|x| x * x).sum::<f32>().sqrt();
349    let norm_b: f32 = b.iter().map(|x| x * x).sum::<f32>().sqrt();
350    let denom = norm_a * norm_b;
351    if denom == 0.0 {
352        0.0
353    } else {
354        dot / denom
355    }
356}
357
358#[cfg(test)]
359#[inline]
360fn l2_distance_scalar(a: &[f32], b: &[f32]) -> f32 {
361    let sum: f32 = a
362        .iter()
363        .zip(b)
364        .map(|(x, y)| {
365            let d = x - y;
366            d * d
367        })
368        .sum();
369    if !sum.is_finite() {
370        return f32::INFINITY;
371    }
372    sum.sqrt()
373}
374
375#[cfg(test)]
376#[inline]
377fn dot_product_scalar(a: &[f32], b: &[f32]) -> f32 {
378    a.iter().zip(b).map(|(x, y)| x * y).sum()
379}
380
381// ============================================================================
382// HNSW Distance Adapter
383// ============================================================================
384
385use anndists::dist::distances::{DistCosine, DistDot, DistL1, DistL2};
386use anndists::dist::Distance;
387
388/// Trait for creating HNSW distance instances.
389pub trait HnswDistance: Clone + Send + Sync + 'static {
390    /// Create the HNSW distance function type.
391    type Dist: Distance<f32> + Clone + Send + Sync + Default;
392
393    /// Create a new instance of the distance function.
394    fn create() -> Self::Dist;
395}
396
397/// Cosine distance adapter for HNSW.
398#[derive(Clone)]
399pub struct CosineDistance;
400
401impl HnswDistance for CosineDistance {
402    type Dist = DistCosine;
403    fn create() -> Self::Dist {
404        DistCosine {}
405    }
406}
407
408/// Euclidean distance adapter for HNSW.
409#[derive(Clone)]
410pub struct EuclideanDistance;
411
412impl HnswDistance for EuclideanDistance {
413    type Dist = DistL2;
414    fn create() -> Self::Dist {
415        DistL2 {}
416    }
417}
418
419/// Dot product distance adapter for HNSW.
420#[derive(Clone)]
421pub struct DotProductDistance;
422
423impl HnswDistance for DotProductDistance {
424    type Dist = DistDot;
425    fn create() -> Self::Dist {
426        DistDot {}
427    }
428}
429
430/// Manhattan distance adapter for HNSW.
431#[derive(Clone)]
432pub struct ManhattanDistance;
433
434impl HnswDistance for ManhattanDistance {
435    type Dist = DistL1;
436    fn create() -> Self::Dist {
437        DistL1 {}
438    }
439}
440
441/// pgvector distance operator for supported metrics.
442pub fn distance_operator(metric: DistanceMetric) -> Option<&'static str> {
443    match metric {
444        DistanceMetric::Cosine => Some("<=>"),
445        DistanceMetric::Euclidean => Some("<->"),
446        DistanceMetric::DotProduct => Some("<#>"),
447        DistanceMetric::Manhattan => None,
448    }
449}
450
451// ============================================================================
452// Tests
453// ============================================================================
454
455#[cfg(test)]
456mod tests {
457    use super::*;
458    use crate::error::Error;
459
460    const EPS: f32 = 1e-4;
461
462    fn approx_eq(a: f32, b: f32) -> bool {
463        (a - b).abs() < EPS
464    }
465
466    // ------------------------------------------------------------------------
467    // DistanceMetric: serde, Display, Clone, Debug
468    // ------------------------------------------------------------------------
469
470    #[cfg(feature = "serde")]
471    #[test]
472    fn metric_serde_roundtrip_cosine() {
473        let metric = DistanceMetric::Cosine;
474        let json = serde_json::to_string(&metric).unwrap();
475        let decoded: DistanceMetric = serde_json::from_str(&json).unwrap();
476        assert_eq!(decoded, metric);
477    }
478
479    #[cfg(feature = "serde")]
480    #[test]
481    fn metric_serde_roundtrip_euclidean() {
482        let metric = DistanceMetric::Euclidean;
483        let json = serde_json::to_string(&metric).unwrap();
484        let decoded: DistanceMetric = serde_json::from_str(&json).unwrap();
485        assert_eq!(decoded, DistanceMetric::Euclidean);
486    }
487
488    #[cfg(feature = "serde")]
489    #[test]
490    fn metric_serde_roundtrip_dot_product() {
491        let metric = DistanceMetric::DotProduct;
492        let json = serde_json::to_string(&metric).unwrap();
493        let decoded: DistanceMetric = serde_json::from_str(&json).unwrap();
494        assert_eq!(decoded, DistanceMetric::DotProduct);
495    }
496
497    #[test]
498    fn metric_debug_clone() {
499        let metric = DistanceMetric::Cosine;
500        let cloned = metric;
501        assert_eq!(format!("{metric:?}"), format!("{cloned:?}"));
502        assert_eq!(cloned, metric);
503    }
504
505    #[test]
506    fn metric_display_name() {
507        assert_eq!(DistanceMetric::Cosine.to_string(), "cosine");
508        assert_eq!(DistanceMetric::Euclidean.to_string(), "euclidean");
509        assert_eq!(format!("{}", DistanceMetric::DotProduct), "dot_product");
510    }
511
512    #[test]
513    fn metric_formula_display() {
514        assert_eq!(
515            DistanceFormula(DistanceMetric::Cosine).to_string(),
516            "1 - (a·b) / (||a|| · ||b||)"
517        );
518        assert_eq!(
519            DistanceFormula(DistanceMetric::Euclidean).to_string(),
520            "√(Σ(aᵢ - bᵢ)²)"
521        );
522        assert_eq!(
523            DistanceFormula(DistanceMetric::DotProduct).to_string(),
524            "-(a·b)"
525        );
526        assert_eq!(
527            DistanceFormula(DistanceMetric::Manhattan).to_string(),
528            "Σ|aᵢ - bᵢ|"
529        );
530    }
531
532    #[test]
533    fn test_metric_from_str() {
534        assert_eq!(
535            "cosine".parse::<DistanceMetric>().unwrap(),
536            DistanceMetric::Cosine
537        );
538        assert_eq!(
539            "l2".parse::<DistanceMetric>().unwrap(),
540            DistanceMetric::Euclidean
541        );
542        assert_eq!(
543            "dot".parse::<DistanceMetric>().unwrap(),
544            DistanceMetric::DotProduct
545        );
546        assert!("unknown".parse::<DistanceMetric>().is_err());
547    }
548
549    #[test]
550    fn test_default_metric_is_cosine() {
551        assert_eq!(DistanceMetric::default(), DistanceMetric::Cosine);
552    }
553
554    #[test]
555    fn test_metric_kind_flags() {
556        assert!(DistanceMetric::Cosine.is_similarity_based());
557        assert!(DistanceMetric::DotProduct.is_similarity_based());
558        assert!(!DistanceMetric::Euclidean.is_similarity_based());
559        assert!(DistanceMetric::Manhattan.is_distance_based());
560    }
561
562    // ------------------------------------------------------------------------
563    // cosine_similarity
564    // ------------------------------------------------------------------------
565
566    #[test]
567    fn cosine_unit_vectors_identical() {
568        let a = [1.0f32, 0.0, 0.0];
569        let b = [1.0, 0.0, 0.0];
570        assert!(approx_eq(cosine_similarity(&a, &b), 1.0));
571    }
572
573    #[test]
574    fn cosine_orthogonal_vectors() {
575        let a = [1.0f32, 0.0, 0.0];
576        let b = [0.0, 1.0, 0.0];
577        assert!(cosine_similarity(&a, &b).abs() < EPS);
578    }
579
580    #[test]
581    fn cosine_opposite_vectors() {
582        let a = [1.0f32, 0.0, 0.0];
583        let b = [-1.0, 0.0, 0.0];
584        assert!(approx_eq(cosine_similarity(&a, &b), -1.0));
585    }
586
587    #[test]
588    fn cosine_zero_vectors() {
589        let a = [0.0f32, 0.0, 0.0];
590        let b = [0.0, 0.0, 0.0];
591        assert!(cosine_similarity(&a, &b).abs() < EPS);
592    }
593
594    #[test]
595    fn cosine_one_zero_vector() {
596        let a = [0.0f32, 0.0];
597        let b = [1.0, 1.0];
598        assert!(cosine_similarity(&a, &b).abs() < EPS);
599    }
600
601    #[test]
602    fn cosine_parallel_large_scale() {
603        let a = [1_000.0f32, 2_000.0, 3_000.0];
604        let b = [2_000.0, 4_000.0, 6_000.0];
605        let sim = cosine_similarity(&a, &b);
606        assert!(approx_eq(sim, 1.0));
607        assert!((-1.0..=1.0).contains(&sim));
608    }
609
610    // ------------------------------------------------------------------------
611    // l2_distance
612    // ------------------------------------------------------------------------
613
614    #[test]
615    fn l2_identical_vectors_zero() {
616        let a = [1.0f32, 2.0, 3.0];
617        let b = [1.0, 2.0, 3.0];
618        assert!(l2_distance(&a, &b).abs() < EPS);
619    }
620
621    #[test]
622    fn l2_unit_distance() {
623        let a = [0.0f32, 0.0, 0.0];
624        let b = [1.0, 0.0, 0.0];
625        assert!(approx_eq(l2_distance(&a, &b), 1.0));
626    }
627
628    #[test]
629    fn l2_large_distance() {
630        let a = [0.0f32, 0.0];
631        let b = [3.0, 4.0];
632        assert!(approx_eq(l2_distance(&a, &b), 5.0));
633    }
634
635    #[test]
636    fn l2_overflow_returns_infinity() {
637        let a = [f32::MAX, 0.0];
638        let b = [0.0, 0.0];
639        assert!(l2_distance(&a, &b).is_infinite());
640    }
641
642    // ------------------------------------------------------------------------
643    // dot_product
644    // ------------------------------------------------------------------------
645
646    #[test]
647    fn dot_product_positive() {
648        let a = [1.0f32, 2.0, 3.0];
649        let b = [4.0, 5.0, 6.0];
650        assert!(approx_eq(dot_product(&a, &b), 32.0));
651    }
652
653    #[test]
654    fn dot_product_negative() {
655        let a = [1.0f32, 0.0];
656        let b = [-1.0, 0.0];
657        assert!(approx_eq(dot_product(&a, &b), -1.0));
658    }
659
660    #[test]
661    fn dot_product_zero_vectors() {
662        let a = [0.0f32, 0.0];
663        let b = [0.0, 0.0];
664        assert!(dot_product(&a, &b).abs() < EPS);
665    }
666
667    #[test]
668    fn dot_product_magnitude_scaling() {
669        let a = [2.0f32, 0.0];
670        let b = [3.0f32, 0.0];
671        assert!(approx_eq(dot_product(&a, &b), 6.0));
672        let unit_a = [1.0f32, 0.0];
673        let unit_b = [1.0f32, 0.0];
674        assert!(approx_eq(dot_product(&unit_a, &unit_b), 1.0));
675    }
676
677    // ------------------------------------------------------------------------
678    // validate_dimensions
679    // ------------------------------------------------------------------------
680
681    #[test]
682    fn validate_dimensions_matching() {
683        let v = [1.0f32, 2.0, 3.0];
684        assert!(validate_dimensions(&v, 3).is_ok());
685    }
686
687    #[test]
688    fn validate_dimensions_mismatch() {
689        let v = [1.0f32, 2.0];
690        let err = validate_dimensions(&v, 3).unwrap_err();
691        assert!(matches!(
692            err,
693            Error::DimensionMismatch {
694                expected: 3,
695                actual: 2
696            }
697        ));
698    }
699
700    #[test]
701    fn validate_dimensions_empty_vector() {
702        let v: [f32; 0] = [];
703        let err = validate_dimensions(&v, 0).unwrap_err();
704        assert!(matches!(err, Error::InvalidVector(_)));
705    }
706
707    #[test]
708    fn validate_dimensions_nan() {
709        let v = [1.0f32, f32::NAN];
710        let err = validate_dimensions(&v, 2).unwrap_err();
711        assert!(matches!(err, Error::InvalidVector(_)));
712    }
713
714    #[test]
715    fn validate_dimensions_inf() {
716        let v = [1.0f32, f32::INFINITY];
717        let err = validate_dimensions(&v, 2).unwrap_err();
718        assert!(matches!(err, Error::InvalidVector(_)));
719    }
720
721    #[test]
722    fn validate_dimension_pair_matching() {
723        let a = [1.0f32, 2.0];
724        let b = [3.0, 4.0];
725        assert!(validate_dimension_pair(&a, &b).is_ok());
726    }
727
728    #[test]
729    fn validate_dimension_pair_mismatch() {
730        let a = [1.0f32];
731        let b = [1.0, 2.0];
732        let err = validate_dimension_pair(&a, &b).unwrap_err();
733        assert!(matches!(
734            err,
735            Error::DimensionMismatch {
736                expected: 1,
737                actual: 2
738            }
739        ));
740    }
741
742    // ------------------------------------------------------------------------
743    // normalize_vector
744    // ------------------------------------------------------------------------
745
746    #[test]
747    fn normalize_vector_unit_norm() {
748        let mut v = [3.0f32, 4.0];
749        normalize_vector(&mut v).unwrap();
750        let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
751        assert!(approx_eq(norm, 1.0));
752        assert!(approx_eq(v[0], 0.6));
753        assert!(approx_eq(v[1], 0.8));
754    }
755
756    #[test]
757    fn normalize_vector_zero_error() {
758        let mut v = [0.0f32, 0.0];
759        let err = normalize_vector(&mut v).unwrap_err();
760        assert!(matches!(err, Error::InvalidVector(_)));
761    }
762
763    #[test]
764    fn normalize_vector_negative_components() {
765        let mut v = [-3.0f32, 4.0];
766        normalize_vector(&mut v).unwrap();
767        assert!(approx_eq(v[0], -0.6));
768        assert!(approx_eq(v[1], 0.8));
769    }
770
771    // ------------------------------------------------------------------------
772    // Scalar vs optimized equivalence
773    // ------------------------------------------------------------------------
774
775    #[test]
776    fn scalar_cosine_matches_optimized() {
777        let a: Vec<f32> = (0..65).map(|i| (i as f32 * 0.1).sin()).collect();
778        let b: Vec<f32> = (0..65).map(|i| (i as f32 * 0.2).cos()).collect();
779        let opt = cosine_similarity(&a, &b);
780        let scalar = cosine_similarity_scalar(&a, &b);
781        assert!(approx_eq(opt, scalar));
782    }
783
784    #[test]
785    fn scalar_l2_matches_optimized() {
786        let a: Vec<f32> = (0..65).map(|i| i as f32).collect();
787        let b: Vec<f32> = (0..65).map(|i| (i as f32) + 0.5).collect();
788        assert!(approx_eq(l2_distance(&a, &b), l2_distance_scalar(&a, &b)));
789    }
790
791    #[test]
792    fn scalar_dot_matches_optimized() {
793        let a: Vec<f32> = (0..65).map(|i| i as f32 * 0.01).collect();
794        let b: Vec<f32> = (0..65).map(|i| (65 - i) as f32 * 0.01).collect();
795        assert!(approx_eq(dot_product(&a, &b), dot_product_scalar(&a, &b)));
796    }
797
798    // ------------------------------------------------------------------------
799    // Error variant display (distance-related paths)
800    // ------------------------------------------------------------------------
801
802    #[test]
803    fn error_dimension_mismatch_display() {
804        let err = Error::DimensionMismatch {
805            expected: 384,
806            actual: 128,
807        };
808        assert_eq!(err.to_string(), "Dimension mismatch: expected 384, got 128");
809    }
810
811    #[test]
812    fn error_invalid_vector_display() {
813        let err = Error::InvalidVector("contains NaN".into());
814        assert_eq!(err.to_string(), "Invalid vector: contains NaN");
815    }
816
817    #[test]
818    fn error_numerical_instability_display() {
819        let err = Error::NumericalInstability("norm overflow".into());
820        assert_eq!(err.to_string(), "Numerical instability: norm overflow");
821    }
822
823    // ------------------------------------------------------------------------
824    // DistanceMetric integration (existing coverage)
825    // ------------------------------------------------------------------------
826
827    #[test]
828    fn test_cosine_identical() {
829        let a = vec![1.0, 0.0, 0.0];
830        let b = vec![1.0, 0.0, 0.0];
831        assert!(approx_eq(DistanceMetric::Cosine.similarity(&a, &b), 1.0));
832    }
833
834    #[test]
835    fn test_cosine_orthogonal() {
836        let a = vec![1.0, 0.0, 0.0];
837        let b = vec![0.0, 1.0, 0.0];
838        assert!(DistanceMetric::Cosine.similarity(&a, &b).abs() < EPS);
839    }
840
841    #[test]
842    fn test_euclidean_identical() {
843        let a = vec![1.0, 2.0, 3.0];
844        let b = vec![1.0, 2.0, 3.0];
845        assert!(DistanceMetric::Euclidean.distance(&a, &b).abs() < EPS);
846    }
847
848    #[test]
849    fn test_manhattan_distance() {
850        let a = vec![0.0, 0.0, 0.0];
851        let b = vec![1.0, 2.0, 3.0];
852        assert!(approx_eq(DistanceMetric::Manhattan.distance(&a, &b), 6.0));
853    }
854
855    #[test]
856    fn test_dot_product_metric() {
857        let a = vec![1.0, 2.0, 3.0];
858        let b = vec![4.0, 5.0, 6.0];
859        assert!(approx_eq(
860            DistanceMetric::DotProduct.similarity(&a, &b),
861            32.0
862        ));
863    }
864
865    #[test]
866    fn test_single_dimension_vectors() {
867        let a = vec![3.0];
868        let b = vec![4.0];
869        assert!(approx_eq(DistanceMetric::Euclidean.distance(&a, &b), 1.0));
870        assert!(approx_eq(
871            DistanceMetric::DotProduct.similarity(&a, &b),
872            12.0
873        ));
874    }
875
876    #[test]
877    fn test_large_vectors_unrolled_paths() {
878        let n = 128;
879        let a: Vec<f32> = (0..n).map(|i| i as f32 * 0.01).collect();
880        let b = a.clone();
881        assert!(DistanceMetric::Euclidean.distance(&a, &b).abs() < EPS);
882        assert!(approx_eq(DistanceMetric::Cosine.similarity(&a, &b), 1.0));
883    }
884
885    #[test]
886    fn test_euclidean_and_manhattan_similarity_transform() {
887        let a = vec![0.0, 0.0];
888        let b = vec![3.0, 4.0];
889        let euclid_sim = DistanceMetric::Euclidean.similarity(&a, &b);
890        assert!(approx_eq(euclid_sim, 1.0 / 6.0));
891        let manhattan_sim = DistanceMetric::Manhattan.similarity(&a, &b);
892        assert!(approx_eq(manhattan_sim, 1.0 / 8.0));
893    }
894
895    #[test]
896    fn test_hnsw_distance_adapters() {
897        use anndists::dist::Distance;
898
899        let a = vec![1.0f32, 0.0, 0.0];
900        let b = vec![0.0f32, 1.0, 0.0];
901        let same = vec![1.0f32, 0.0, 0.0];
902
903        let cosine = CosineDistance::create();
904        assert!(approx_eq(cosine.eval(&a, &b), 1.0));
905        assert!(cosine.eval(&same, &a).abs() < EPS);
906
907        let l2 = EuclideanDistance::create();
908        assert!(approx_eq(l2.eval(&a, &b), std::f32::consts::SQRT_2));
909        assert!(l2.eval(&same, &a).abs() < EPS);
910
911        let dot = DotProductDistance::create();
912        assert!(approx_eq(dot.eval(&a, &b), 1.0));
913        assert!(dot.eval(&same, &a).abs() < EPS);
914
915        let l1 = ManhattanDistance::create();
916        assert!(approx_eq(l1.eval(&a, &b), 2.0));
917        assert!(l1.eval(&same, &a).abs() < EPS);
918    }
919    #[test]
920    fn distance_operator_maps_pgvector_tokens() {
921        assert_eq!(distance_operator(DistanceMetric::Euclidean), Some("<->"));
922        assert_eq!(distance_operator(DistanceMetric::DotProduct), Some("<#>"));
923        assert_eq!(distance_operator(DistanceMetric::Cosine), Some("<=>"));
924        assert_eq!(distance_operator(DistanceMetric::Manhattan), None);
925    }
926
927    #[test]
928    fn distance_metric_serde_roundtrip() {
929        for metric in [
930            DistanceMetric::Cosine,
931            DistanceMetric::Euclidean,
932            DistanceMetric::DotProduct,
933            DistanceMetric::Manhattan,
934        ] {
935            let json = serde_json::to_string(&metric).expect("serialize");
936            let restored: DistanceMetric = serde_json::from_str(&json).expect("deserialize");
937            assert_eq!(restored, metric);
938        }
939    }
940}