Skip to main content

diskann_vector/
traits.rs

1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6/// An overloadable, 2-argument distance function with a parameterized return type.
7///
8/// Pure distance functions depend only on the values of the argument and the type of the
9/// return value.
10pub trait PureDistanceFunction<Left, Right, To = f32> {
11    fn evaluate(x: Left, y: Right) -> To;
12}
13
14/// An overloadable, 2-argument distance function with a parameterized return type.
15///
16/// Unlike `PureDistanceFunction`, this takes a functor as the receiver. This allows
17/// distance functors to contain auxiliary state required to do their job
18/// (for example, access to some shared quantization tables).
19pub trait DistanceFunction<Left, Right, To = f32> {
20    /// Perform a distance computation between the left-hand and right-hand arguments.
21    fn evaluate_similarity(&self, x: Left, y: Right) -> To;
22}
23
24/// A mutable version of [`DistanceFunction`] that allows mutation of `Self`.
25///
26/// This trait is useful for computing distances where the distance functor holds
27/// mutable state (e.g., a buffer to accumulate per-vector scores).
28pub trait DistanceFunctionMut<Left, Right, To = ()> {
29    /// Compute distances between the left and right arguments.
30    fn evaluate(&mut self, left: Left, right: Right) -> To;
31}
32
33/// A distance function where one argument is static and interned within `Self`.
34///
35/// The method `self.evaluate_similarity` can then be invoked for arbitrarily many values of
36/// `changing`.
37///
38/// The main idea behind this trait is to enable distance functions where some amount of
39/// preprocessing on a query can be used to accelerate distance computations.
40pub trait PreprocessedDistanceFunction<Changing, To = f32> {
41    fn evaluate_similarity(&self, changing: Changing) -> To;
42}
43
44/// Evaluate a norm of the argument `x` and return the result as the requested type.
45///
46/// Note that while this has a similar signature to `PreprocessedDistanceFunction`, the
47/// semantics of this trait are different. Implementations are expected to be light-weight
48/// types that implement some kind of reduction on on `x`.
49pub trait Norm<T, To = f32> {
50    fn evaluate(&self, x: T) -> To;
51}