1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
pub use packed_simd::{f32x16, f32x2, f32x4, f32x8, u128x2, u128x4};
#[cfg(feature = "serde-impl")]
use serde::{Deserialize, Serialize};

/// This is the primary trait used by the HNSW. This is also implemented for [`FloatingDistance`].
/// If your features have a floating point distance, please implement the distance using [`FloatingDistance`].
/// Implementing [`FloatingDistance`] implements [`Distance`] so long as you satisfy its conditions.
pub trait Distance {
    /// This must compute the distance between two `Self` as a `u32`.
    fn distance(lhs: &Self, rhs: &Self) -> u32;
}

/// Implement this trait when your features have a floating point distance between them. You will take no performance
/// penalty for doing so. Please ensure your distance satisfies the conditions on `floating_distance`.
pub trait FloatingDistance {
    /// This must compute the distance between two `Self` as a `f32`.
    /// The output must not be negative, infinity, or NaN. Subnormal numbers and zero are allowed.
    fn floating_distance(lhs: &Self, rhs: &Self) -> f32;
}

/// This impl requires the float to not be negative, infinite, or NaN.
/// The tradeoff is that it performs equally as well as unsigned integer distance.
impl<T> Distance for T
where
    T: FloatingDistance,
{
    fn distance(lhs: &Self, rhs: &Self) -> u32 {
        T::floating_distance(lhs, rhs).to_bits()
    }
}

/// Treats each bit contained in this struct as its own dimension and distance is computed as hamming distance.
#[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq)]
#[cfg_attr(feature = "serde-impl", derive(Serialize, Deserialize))]
pub struct Hamming<T>(pub T);

impl Distance for Hamming<&[u8]> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        // TODO: This generates pretty sub-optimal code.
        lhs.iter()
            .zip(rhs)
            .map(|(&lhs, &rhs)| (lhs ^ rhs).count_ones())
            .sum::<u32>()
    }
}

impl Distance for Hamming<Vec<u8>> {
    fn distance(Self(lhs): &Self, Self(rhs): &Self) -> u32 {
        // TODO: This generates pretty sub-optimal code.
        lhs.iter()
            .zip(rhs)
            .map(|(&lhs, &rhs)| (lhs ^ rhs).count_ones())
            .sum::<u32>()
    }
}

impl Distance for Hamming<u8> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones()
    }
}

impl Distance for Hamming<u16> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones()
    }
}

impl Distance for Hamming<u32> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones()
    }
}

impl Distance for Hamming<u64> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones()
    }
}

impl Distance for Hamming<u128> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones()
    }
}

impl Distance for Hamming<u128x2> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones().wrapping_sum() as u32
    }
}

impl Distance for Hamming<u128x4> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        (lhs ^ rhs).count_ones().wrapping_sum() as u32
    }
}

impl Distance for Hamming<[u128x4; 1]> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        lhs.iter()
            .zip(&rhs)
            .map(|(&lhs, &rhs)| (lhs ^ rhs).count_ones().wrapping_sum() as u32)
            .sum::<u32>()
    }
}

impl Distance for Hamming<[u128x4; 2]> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        lhs.iter()
            .zip(&rhs)
            .map(|(&lhs, &rhs)| (lhs ^ rhs).count_ones().wrapping_sum() as u32)
            .sum::<u32>()
    }
}

impl Distance for Hamming<[u128x4; 4]> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        lhs.iter()
            .zip(&rhs)
            .map(|(&lhs, &rhs)| (lhs ^ rhs).count_ones().wrapping_sum() as u32)
            .sum::<u32>()
    }
}

impl Distance for Hamming<[u128x4; 8]> {
    fn distance(&Self(lhs): &Self, &Self(rhs): &Self) -> u32 {
        lhs.iter()
            .zip(&rhs)
            .map(|(&lhs, &rhs)| (lhs ^ rhs).count_ones().wrapping_sum() as u32)
            .sum::<u32>()
    }
}

/// Any list, vector, etc of floats wrapped in `Euclidean` is to be treated as having euclidean distance.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde-impl", derive(Serialize, Deserialize))]
pub struct Euclidean<T>(pub T);

impl FloatingDistance for Euclidean<&[f32]> {
    fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
        assert_eq!(lhs.len(), rhs.len());
        lhs.iter()
            .zip(rhs)
            .map(|(a, b)| (a - b).powi(2))
            .sum::<f32>()
    }
}

impl FloatingDistance for Euclidean<Vec<f32>> {
    fn floating_distance(Euclidean(lhs): &Self, Euclidean(rhs): &Self) -> f32 {
        assert_eq!(lhs.len(), rhs.len());
        lhs.iter()
            .zip(rhs)
            .map(|(&a, &b)| (a - b).powi(2))
            .sum::<f32>()
    }
}

impl FloatingDistance for Euclidean<f32> {
    fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
        (lhs - rhs).abs()
    }
}

impl FloatingDistance for Euclidean<f32x2> {
    fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
        let diff = lhs - rhs;
        (diff * diff).sum()
    }
}

impl FloatingDistance for Euclidean<f32x4> {
    fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
        let diff = lhs - rhs;
        (diff * diff).sum()
    }
}

impl FloatingDistance for Euclidean<f32x8> {
    fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
        let diff = lhs - rhs;
        (diff * diff).sum()
    }
}

impl FloatingDistance for Euclidean<f32x16> {
    fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
        let diff = lhs - rhs;
        (diff * diff).sum()
    }
}

macro_rules! euclidean_array_impl {
    ($x:expr) => {
        impl FloatingDistance for Euclidean<[f32x16; $x]> {
            fn floating_distance(&Euclidean(lhs): &Self, &Euclidean(rhs): &Self) -> f32 {
                lhs.iter()
                    .zip(rhs.iter())
                    .map(|(&a, &b)| {
                        let diff = a - b;
                        (diff * diff).sum()
                    })
                    .sum::<f32>()
            }
        }
    };
}

euclidean_array_impl!(1);
euclidean_array_impl!(2);
euclidean_array_impl!(3);
euclidean_array_impl!(4);
euclidean_array_impl!(5);
euclidean_array_impl!(6);
euclidean_array_impl!(7);
euclidean_array_impl!(8);
euclidean_array_impl!(9);
euclidean_array_impl!(10);
euclidean_array_impl!(11);
euclidean_array_impl!(12);
euclidean_array_impl!(13);
euclidean_array_impl!(14);
euclidean_array_impl!(15);
euclidean_array_impl!(16);
euclidean_array_impl!(32);
euclidean_array_impl!(64);
euclidean_array_impl!(128);
euclidean_array_impl!(256);