pub struct Rng(u64);
impl Rng {
pub fn new(seed: u64) -> Self {
Self(seed.max(1))
}
pub fn next_u64(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
pub fn gaussian(&mut self) -> f32 {
let u1 = ((self.next_u64() >> 11) + 1) as f64 / (1u64 << 53) as f64;
let u2 = (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64;
((-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()) as f32
}
}
pub fn normalize(v: Vec<f32>) -> Vec<f32> {
let n = v.iter().map(|x| x * x).sum::<f32>().sqrt();
if n == 0.0 {
return v;
}
v.into_iter().map(|x| x / n).collect()
}
pub fn clustered(seed: u64, n: usize, dims: usize, clusters: usize, spread: f32) -> Vec<Vec<f32>> {
assert!(clusters > 0 && dims > 0, "clusters and dims must be positive");
let mut rng = Rng::new(seed);
let centres: Vec<Vec<f32>> = (0..clusters).map(|_| normalize((0..dims).map(|_| rng.gaussian()).collect())).collect();
(0..n)
.map(|_| {
let c = ¢res[(rng.next_u64() % clusters as u64) as usize];
normalize(c.iter().map(|x| x + spread * rng.gaussian()).collect())
})
.collect()
}