use std::collections::HashSet;
use crate::search::{HitList, Search, Stop, collect_all};
use crate::value::Value;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NeighbourTable {
pub sample: usize,
pub seed: u64,
pub counts: Vec<u64>,
}
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,
}
}
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
}
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)
}
fn below(&mut self, bound: u64) -> u64 {
((u128::from(self.next()) * u128::from(bound)) >> 64) as u64
}
}