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