use tab_hash::{Tab32Simple, Tab64Simple};
use rand_core::RngCore;
use crate::hash_utils::{tab32_from_rng, tab64_from_rng, to_unit};
use crate::rng_utils::MtRng;
use std::cell::RefCell;
pub type Dart = (u64, f64);
#[derive(Clone)]
pub struct RedGreenIndex {
base: Vec<f64>,
cap: Vec<f64>,
d: usize,
m_total: f64,
prob: Vec<f64>, alias: Vec<u32>, }
impl RedGreenIndex {
pub fn from_caps(m_per_dim: &[f64]) -> Self {
let d = m_per_dim.len();
let mut base = Vec::with_capacity(d);
let mut acc = 0.0f64;
for &mi in m_per_dim {
debug_assert!(mi >= 0.0, "caps must be non-negative");
base.push(acc);
acc += mi;
}
let m_total = acc;
let cap = m_per_dim.to_vec();
let mut prob = vec![0.0f64; d];
let mut alias = vec![0u32; d];
if d == 0 || m_total == 0.0 {
return Self { base, cap, d, m_total, prob, alias };
}
let mut q: Vec<f64> = cap
.iter()
.map(|&mi| (mi / m_total) * (d as f64))
.collect();
let mut small = Vec::<usize>::new();
let mut large = Vec::<usize>::new();
for (i, &qi) in q.iter().enumerate() {
if qi < 1.0 { small.push(i); } else { large.push(i); }
}
while let (Some(s), Some(l)) = (small.pop(), large.pop()) {
prob[s] = q[s]; alias[s] = l as u32;
q[l] = (q[l] + q[s]) - 1.0;
if q[l] < 1.0 {
small.push(l);
} else {
large.push(l);
}
}
for i in small.into_iter().chain(large.into_iter()) {
prob[i] = 1.0;
alias[i] = i as u32;
}
Self { base, cap, d, m_total, prob, alias }
}
#[inline]
pub fn d(&self) -> usize { self.d }
#[inline]
pub fn m_total(&self) -> f64 { self.m_total }
#[inline]
pub fn base_of(&self, i: usize) -> f64 {
unsafe { *self.base.get_unchecked(i) }
}
#[inline]
pub fn cap_of(&self, i: usize) -> f64 {
unsafe { *self.cap.get_unchecked(i) }
}
#[inline]
pub fn sample_interval_and_offset(&self, t_u: &Tab64Simple, key: u64) -> (usize, f64) {
debug_assert!(self.d > 0);
let mut u0 = to_unit(t_u.hash(key));
if u0 >= 1.0 {
u0 = f64::from_bits(0x3fefffffffffffff); }
let mut col = (u0 * (self.d as f64)) as usize;
if col >= self.d {
col = self.d - 1;
}
let mut u1 = to_unit(t_u.hash(key ^ 0x9e37_79b9_7f4a_7c15));
if u1 >= 1.0 {
u1 = f64::from_bits(0x3fefffffffffffff);
}
let i = if u1 < unsafe { *self.prob.get_unchecked(col) } {
col
} else {
unsafe { *self.alias.get_unchecked(col) as usize }
};
let mut u2 = to_unit(t_u.hash(key ^ 0xbf58_476d_1ce4_e5b9));
if u2 >= 1.0 {
u2 = f64::from_bits(0x3fefffffffffffff);
}
let off = self.cap_of(i) * u2;
(i, off)
}
}
#[derive(Default)]
struct DenseScratch {
w: Vec<f64>,
touched: Vec<usize>,
}
impl DenseScratch {
#[inline]
fn ensure_len(&mut self, d: usize) {
if self.w.len() < d {
self.w.resize(d, 0.0);
}
}
#[inline]
fn fill_from_sparse_and_mass(&mut self, d: usize, x: &[(u64, f64)]) -> f64 {
self.ensure_len(d);
self.touched.clear();
let mut mass = 0.0f64;
for &(i_u64, xi) in x {
let idx = i_u64 as usize;
debug_assert!(idx < d);
if xi <= 0.0 {
continue;
}
let old = self.w[idx];
if old == 0.0 {
self.touched.push(idx);
self.w[idx] = xi;
mass += xi;
} else {
self.w[idx] = xi;
mass += xi - old;
}
}
mass
}
#[inline]
fn clear_touched(&mut self) {
for &idx in &self.touched {
self.w[idx] = 0.0;
}
self.touched.clear();
}
}
thread_local! {
static ERS_SCRATCH: RefCell<DenseScratch> = RefCell::new(DenseScratch::default());
}
pub struct ErsWmh {
index: RedGreenIndex,
t_u: Tab64Simple, t_id: Tab64Simple, t_rot: Tab32Simple, k: usize,
}
impl ErsWmh {
pub fn new_mt(rng: &mut MtRng, caps: &[f64], k: u64) -> Self {
let index = RedGreenIndex::from_caps(caps);
let t_u = tab64_from_rng(rng);
let t_id = tab64_from_rng(rng);
let t_rot = tab32_from_rng(rng);
Self { index, t_u, t_id, t_rot, k: k as usize }
}
#[inline]
fn is_green_offset(&self, w_dense: &[f64], i: usize, off: f64) -> bool {
let xi = unsafe { *w_dense.get_unchecked(i) };
off <= xi
}
pub fn sketch(&self, x: &[(u64, f64)], max_attempts: Option<u64>) -> Vec<Dart> {
const L_DEFAULT: u32 = 1024;
let l_per_hash: u32 = max_attempts.map(|v| v as u32).unwrap_or(L_DEFAULT);
let d = self.index.d();
let m = self.index.m_total();
let mut buckets: Vec<Option<(u64 /*id*/, u32 /*time*/)>> = vec![None; self.k];
let mut out: Option<Vec<Dart>> = None;
ERS_SCRATCH.with(|cell| {
let mut scratch = cell.borrow_mut();
let mass = scratch.fill_from_sparse_and_mass(d, x);
if m == 0.0 || mass == 0.0 || d == 0 {
let mut fallback = Vec::with_capacity(self.k);
for j in 0..self.k {
let fake = (self.t_rot.hash(j as u32) as u64) << 32 | (j as u64);
fallback.push((fake, f64::INFINITY));
}
scratch.clear_touched();
out = Some(fallback);
return;
}
let w = &scratch.w;
for j in 0..self.k {
for t in 1..=l_per_hash {
let key = ((j as u64) << 32) ^ (t as u64);
let (i, off) = self.index.sample_interval_and_offset(&self.t_u, key);
if self.is_green_offset(w, i, off) {
let r = self.index.base_of(i) + off;
let id = self.t_id.hash(r.to_bits());
buckets[j] = Some((id, t));
break;
}
}
}
if buckets.iter().all(|b| b.is_none()) {
let mut fallback = Vec::with_capacity(self.k);
for j in 0..self.k {
let fake = (self.t_rot.hash(j as u32) as u64) << 32 | (j as u64);
fallback.push((fake, f64::INFINITY));
}
scratch.clear_touched();
out = Some(fallback);
return;
}
for j in 0..self.k {
if buckets[j].is_none() {
let offset =
(self.t_rot.hash(j as u32) as usize % (self.k.saturating_sub(1)).max(1)) + 1;
let mut idx = (j + offset) % self.k;
for _ in 0..(self.k - 1) {
if let Some(val) = buckets[idx] {
buckets[j] = Some(val);
break;
}
idx += 1;
if idx == self.k {
idx = 0;
}
}
if buckets[j].is_none() {
let fake = (self.t_rot.hash(j as u32) as u64) << 32 | (j as u64);
buckets[j] = Some((fake, u32::MAX));
}
}
}
let mut result = Vec::with_capacity(self.k);
for j in 0..self.k {
let (id, t) = buckets[j].unwrap();
result.push((id, t as f64));
}
scratch.clear_touched();
out = Some(result);
});
out.expect("ERS_SCRATCH closure must set out")
}
#[inline]
pub fn sketch_early_stop(&self, x: &[(u64, f64)]) -> Vec<Dart> {
self.sketch(x, None)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rng_utils::{mt_from_seed, MtRng};
fn generate_weighted_set(d: usize, l0: u64, l1: f64, rng: &mut MtRng) -> Vec<(u64, f64)> {
use std::collections::HashSet;
let mut elements = HashSet::with_capacity(l0 as usize);
while elements.len() < l0 as usize {
let id = (rng.next_u64() as usize) % d;
elements.insert(id as u64);
}
fn uniform01(rng: &mut MtRng) -> f64 {
mt19937::gen_res53(rng)
}
let mut z: Vec<f64> = (0..(l0 - 1)).map(|_| uniform01(rng)).collect();
z.push(1.0);
z.sort_by(|a, b| a.partial_cmp(b).unwrap());
let mut prev = 0.0;
let mut j = 0usize;
let mut out: Vec<(u64, f64)> = Vec::with_capacity(l0 as usize);
for idx in elements {
let w = l1 * (z[j] - prev);
out.push((idx, w.max(0.0)));
prev = z[j];
j += 1;
}
out.sort_by_key(|p| p.0);
out
}
fn generate_similar_weighted_set(
d: usize,
x: &[(u64, f64)],
relative_overlap: f64,
rng: &mut MtRng,
) -> Vec<(u64, f64)> {
let free_id: u64 = loop {
let cand = (rng.next_u64() as usize) % d;
if x.binary_search_by_key(&(cand as u64), |p| p.0).is_err() {
break cand as u64;
}
};
let mut excess = 0.0;
let mut y = Vec::with_capacity(x.len() + 1);
for &(id, w) in x {
let w_scaled = w * relative_overlap;
excess += w - w_scaled;
y.push((id, w_scaled.max(0.0)));
}
if excess > 0.0 {
y.push((free_id, excess));
}
y.sort_by_key(|p| p.0);
y
}
fn caps_from_sets(d: usize, sets: &[&[(u64, f64)]]) -> Vec<f64> {
let mut m = vec![0.0f64; d];
for s in sets {
for &(id, w) in *s {
if w > 0.0 {
let idx = id as usize;
if w > m[idx] {
m[idx] = w;
}
}
}
}
m
}
#[test]
fn ers_early_stop_fills_all_buckets() {
let mut rng = mt_from_seed(1337);
let d = 200_000usize;
let k = 4096;
let x = generate_weighted_set(d, 50_000, 10_000.0, &mut rng);
let m = caps_from_sets(d, &[&x]);
let ers = ErsWmh::new_mt(&mut rng, &m, k as u64);
let l: u64 = 512;
let sk = ers.sketch(&x, Some(l));
assert_eq!(sk.len(), k);
}
#[test]
fn ers_approximates_weighted_jaccard() {
use crate::similarity::jaccard_similarity;
let mut rng = mt_from_seed(8675309);
let d = 200_000usize;
let k = 4096;
let l: u64 = 1024;
let l0 = 50_000u64;
let l1 = 10_000.0;
let x = generate_weighted_set(d, l0, l1, &mut rng);
let targets = [
0.99, 0.96, 0.93, 0.9, 0.85, 0.8, 0.75, 0.7, 0.65, 0.6, 0.55, 0.5, 0.4, 0.3, 0.2, 0.1,
0.05, 0.01,
];
for &rel in &targets {
let y = generate_similar_weighted_set(d, &x, rel, &mut rng);
let j_true = jaccard_similarity(&x, &y);
println!("true weighted Jaccard: {:?}", j_true);
let m_per_dim = caps_from_sets(d, &[&x, &y]);
let ers = ErsWmh::new_mt(&mut rng, &m_per_dim, k as u64);
let sk_x = ers.sketch(&x, Some(l));
let sk_y = ers.sketch(&y, Some(l));
let hits = sk_x.iter().zip(&sk_y).filter(|(a, b)| a.0 == b.0).count();
let j_est = hits as f64 / k as f64;
println!("estimated weighted Jaccard: {:?}", j_est);
let sd = (j_true * (1.0 - j_true) / (k as f64)).sqrt();
let tol = (3.2 * sd).max(1.25 / (k as f64).sqrt());
let err = (j_true - j_est).abs();
assert!(
err <= tol,
"rel={rel:.3}, true={j_true:.6}, est={j_est:.6}, err={err:.6}, tol={tol:.6}"
);
}
}
}