legit-hamming 0.1.1

Exact Hamming radius search over 64-bit and 256-bit hashes in memory: a scan or multi-index hashing, chosen per query, checked against one reference, and a search service over snapshots
Documentation
//! The measured neighbour table: how many records sit at each distance from a typical record.

use std::collections::HashSet;

use crate::search::{HitList, Search, Stop, collect_all};
use crate::value::Value;

/// How many other records sit at each distance from a sample of an index's own records.
///
/// Measured, never computed from a uniform model: real hashes aren't uniform, and on about 90
/// million real 64-bit perceptual hashes of one image collection a typical record had 1.03 others
/// at distance 0 and 12.8 at distance 8, where as many uniform values would have 0.02 at distance
/// 8. `counts[d] / sample` is how many records a typical record has at exactly distance `d`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NeighbourTable {
    /// How many records were sampled.
    pub sample: usize,
    /// The seed the sample was drawn with.
    pub seed: u64,
    /// For each distance from 0 to the bound, the count of other records at exactly that distance
    /// from a sampled record, summed over the sample. A record's own position isn't counted; a
    /// duplicate of its value, at another position, is counted at distance 0.
    pub counts: Vec<u64>,
}

/// Measure the [`NeighbourTable`] of `index` out to `max_distance`, from `sample` of its records
/// drawn at random without repeats, from `seed`, so the same seed draws the same sample. A sample
/// as large as the index takes every record.
///
/// It is one search of radius `max_distance` per sampled record, on whatever path the variant
/// searches with, 256 records at a time, split across up to `threads` threads as the variant's
/// [`plan`](Search::plan) says. Each match is added to
/// the table as the search finds it, so memory stays at a few thousand matches a sampled record
/// however many records sit within the bound; no match list is built.
///
/// # Panics
///
/// Panics if the variant panics on one of the threads.
pub fn neighbour_table<V: Value>(
    index: &(impl Search<V> + ?Sized),
    sample: usize,
    seed: u64,
    max_distance: u32,
    threads: usize,
) -> NeighbourTable {
    let positions = sample_positions(index.len(), sample, seed);
    let mut counts = vec![0u64; max_distance as usize + 1];
    for batch in positions.chunks(256) {
        let queries: Vec<V> = batch.iter().map(|&position| index.value(position)).collect();
        let planning = index.plan(&queries, max_distance, threads.max(1), &Stop::never());
        let (lists, _) = collect_all(
            index,
            &queries,
            max_distance,
            planning.threads,
            &Stop::never(),
            |query| {
                HitList::histogram(max_distance, u32::try_from(batch[query]).ok())
                    .with_plan(planning.plans.get(query).copied())
            },
        );
        for list in lists {
            for (count, add) in counts.iter_mut().zip(list.into_counts()) {
                *count += add;
            }
        }
    }
    NeighbourTable {
        sample: positions.len(),
        seed,
        counts,
    }
}

/// `sample` distinct positions below `length`, in rising order, by Floyd's algorithm.
fn sample_positions(length: usize, sample: usize, seed: u64) -> Vec<usize> {
    if sample >= length {
        return (0..length).collect();
    }
    let mut random = SplitMix64(seed);
    let mut chosen = HashSet::with_capacity(sample);
    for upper in length - sample..length {
        let pick = random.below(upper as u64 + 1) as usize;
        if !chosen.insert(pick) {
            chosen.insert(upper);
        }
    }
    let mut positions: Vec<usize> = chosen.into_iter().collect();
    positions.sort_unstable();
    positions
}

/// SplitMix64 (Steele, Lea and Flood, 2014): a small, fast generator, fixed here so a seed draws
/// the same sample in every version of the crate.
struct SplitMix64(u64);

impl SplitMix64 {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
        z ^ (z >> 31)
    }

    /// A number below `bound`, by multiplying and keeping the high half.
    fn below(&mut self, bound: u64) -> u64 {
        ((u128::from(self.next()) * u128::from(bound)) >> 64) as u64
    }
}