Skip to main content

evolutionary_planning/
rng.rs

1//! The seeded pseudo-random generator [`SplitMix64`] and the sampling helpers every algorithm
2//! uses: uniform floats, unbiased integers, standard normals and shuffles.
3//!
4//! An own generator rather than a dependency, so that a seed reproduces a run across releases
5//! of this crate regardless of other crates' versions (see `docs/design.md`). It implements
6//! `rand_core`'s generator trait, which only fixes the interface, not the sequence. Every
7//! algorithm takes any `rand_core::Rng`, so callers can use another generator.
8
9use core::convert::Infallible;
10
11use rand_core::Rng;
12
13/// The `SplitMix64` generator (Steele, Lea and Flood 2014).
14///
15/// Fast, with a full `2^64` period and good equidistribution for sampling. Not
16/// cryptographically secure, which evolutionary search does not need.
17///
18/// ```
19/// use evolutionary_planning::{SplitMix64, unit_f64};
20///
21/// let mut rng = SplitMix64::new(7);
22/// assert!((0.0..1.0).contains(&unit_f64(&mut rng)));
23/// ```
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct SplitMix64 {
26    /// The generator state, advanced by a fixed odd increment per draw.
27    state: u64,
28}
29
30impl SplitMix64 {
31    /// Creates a generator from a seed. Every seed, including `0`, is valid.
32    #[must_use]
33    pub const fn new(seed: u64) -> Self {
34        Self { state: seed }
35    }
36
37    /// Returns the next 64 random bits.
38    fn next_word(&mut self) -> u64 {
39        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
40        let mut z = self.state;
41        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
42        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
43
44        z ^ (z >> 31)
45    }
46
47    /// Derives an independent generator for stream `stream`, for example one per restart or
48    /// per decision, without consuming randomness from `self`.
49    #[must_use]
50    pub fn fork(&self, stream: u64) -> Self {
51        let mixed = Self::new(self.state ^ stream.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_word();
52
53        Self::new(mixed)
54    }
55}
56
57impl rand_core::TryRng for SplitMix64 {
58    type Error = Infallible;
59
60    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
61        Ok((self.next_word() >> 32) as u32)
62    }
63
64    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
65        Ok(self.next_word())
66    }
67
68    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
69        rand_core::utils::fill_bytes_via_next_word(dst, || self.try_next_u64())
70    }
71}
72
73/// Returns a uniform sample from `[0, 1)` with 53 random bits drawn from `rng`.
74///
75/// ```
76/// use evolutionary_planning::{SplitMix64, unit_f64};
77///
78/// let mut rng = SplitMix64::new(1);
79/// let u = unit_f64(&mut rng);
80/// assert!(u >= 0.0 && u < 1.0);
81/// ```
82pub fn unit_f64<R: Rng + ?Sized>(rng: &mut R) -> f64 {
83    /// `2^-53`, the spacing of the 53-bit grid on `[0, 1)`.
84    const SCALE: f64 = 1.0 / 9_007_199_254_740_992.0;
85
86    #[expect(
87        clippy::cast_precision_loss,
88        reason = "the value has at most 53 bits, which f64 represents exactly"
89    )]
90    let bits = (rng.next_u64() >> 11) as f64;
91
92    bits * SCALE
93}
94
95/// Returns a uniform sample from `[low, high)`; `low` itself if the interval is empty.
96pub fn uniform<R: Rng + ?Sized>(rng: &mut R, low: f64, high: f64) -> f64 {
97    if high <= low {
98        return low;
99    }
100
101    let x = low + (high - low) * unit_f64(rng);
102
103    // Rounding can land exactly on `high`; keep the interval half-open.
104    if x >= high { low } else { x }
105}
106
107/// Returns `true` with probability `p` (clamped to `[0, 1]`).
108pub fn chance<R: Rng + ?Sized>(rng: &mut R, p: f64) -> bool {
109    if p >= 1.0 {
110        return true;
111    }
112
113    unit_f64(rng) < p
114}
115
116/// Returns a uniform integer from `0..n` with Lemire's unbiased multiply-and-reject method.
117///
118/// # Panics
119///
120/// Panics if `n == 0`.
121///
122/// ```
123/// use evolutionary_planning::{SplitMix64, below};
124///
125/// let mut rng = SplitMix64::new(3);
126/// assert!(below(&mut rng, 10) < 10);
127/// ```
128pub fn below<R: Rng + ?Sized>(rng: &mut R, n: usize) -> usize {
129    assert!(n > 0, "below(0) has no valid result");
130
131    let n = n as u64;
132    let mut product = u128::from(rng.next_u64()) * u128::from(n);
133
134    #[expect(
135        clippy::cast_possible_truncation,
136        reason = "the low half of a 128-bit product"
137    )]
138    let mut low = product as u64;
139    if low < n {
140        let threshold = n.wrapping_neg() % n;
141        while low < threshold {
142            product = u128::from(rng.next_u64()) * u128::from(n);
143
144            #[expect(
145                clippy::cast_possible_truncation,
146                reason = "the low half of a 128-bit product"
147            )]
148            {
149                low = product as u64;
150            }
151        }
152    }
153
154    #[expect(
155        clippy::cast_possible_truncation,
156        reason = "the high half is below n, a usize"
157    )]
158    let index = (product >> 64) as usize;
159
160    index
161}
162
163/// Returns a standard normal sample `N(0, 1)` with Marsaglia's polar method.
164///
165/// The second sample of each polar pair is discarded so the function needs no state; the
166/// cost is one extra `ln` and `sqrt` per sample, small against any objective evaluation.
167pub fn standard_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
168    loop {
169        let u = 2.0 * unit_f64(rng) - 1.0;
170        let v = 2.0 * unit_f64(rng) - 1.0;
171        let s = u * u + v * v;
172        if s > 0.0 && s < 1.0 {
173            return u * libm::sqrt(-2.0 * libm::log(s) / s);
174        }
175    }
176}
177
178/// Shuffles `items` uniformly in place (Fisher-Yates).
179pub fn shuffle<T, R: Rng + ?Sized>(rng: &mut R, items: &mut [T]) {
180    for i in (1..items.len()).rev() {
181        let j = below(rng, i + 1);
182        items.swap(i, j);
183    }
184}
185
186/// Returns two distinct uniform indices from `0..n`, the first strictly below the second.
187///
188/// # Panics
189///
190/// Panics if `n < 2`.
191pub fn two_sorted_indices<R: Rng + ?Sized>(rng: &mut R, n: usize) -> (usize, usize) {
192    assert!(n >= 2, "two distinct indices need n >= 2");
193
194    let a = below(rng, n);
195    let mut b = below(rng, n - 1);
196    if b >= a {
197        b += 1;
198    }
199
200    (a.min(b), a.max(b))
201}
202
203/// Returns `count` distinct indices from `0..n` that are all different from `exclude`, in
204/// random order (partial Fisher-Yates over a scratch vector).
205///
206/// # Panics
207///
208/// Panics if fewer than `count` indices are available.
209pub fn distinct_indices<R: Rng + ?Sized>(
210    rng: &mut R,
211    n: usize,
212    count: usize,
213    exclude: Option<usize>,
214) -> alloc::vec::Vec<usize> {
215    let mut pool: alloc::vec::Vec<usize> = (0..n).filter(|&i| Some(i) != exclude).collect();
216    assert!(pool.len() >= count, "not enough distinct indices");
217
218    for i in 0..count {
219        let j = i + below(rng, pool.len() - i);
220        pool.swap(i, j);
221    }
222
223    pool.truncate(count);
224    pool
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    /// The first outputs for seed 0 match the reference implementation.
232    #[test]
233    fn matches_reference_sequence() {
234        let mut rng = SplitMix64::new(0);
235
236        assert_eq!(rng.next_u64(), 0xE220_A839_7B1D_CDAF);
237        assert_eq!(rng.next_u64(), 0x6E78_9E6A_A1B9_65F4);
238    }
239
240    /// `below` covers its range and never leaves it.
241    #[test]
242    fn below_covers_range() {
243        let mut rng = SplitMix64::new(5);
244        let mut seen = [false; 7];
245        for _ in 0..1000 {
246            seen[below(&mut rng, 7)] = true;
247        }
248
249        assert!(seen.iter().all(|&s| s));
250    }
251
252    /// The normal samples have roughly zero mean and unit variance.
253    #[test]
254    fn normal_moments() {
255        let mut rng = SplitMix64::new(11);
256        let n = 20_000;
257        let samples: alloc::vec::Vec<f64> = (0..n).map(|_| standard_normal(&mut rng)).collect();
258        let mean = samples.iter().sum::<f64>() / f64::from(n);
259        let var = samples.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / f64::from(n);
260
261        assert!(mean.abs() < 0.03, "mean {mean}");
262        assert!((var - 1.0).abs() < 0.05, "variance {var}");
263    }
264
265    /// Shuffling keeps the multiset, two indices are distinct and sorted.
266    #[test]
267    fn shuffle_and_pairs() {
268        let mut rng = SplitMix64::new(2);
269        let mut items: alloc::vec::Vec<u32> = (0..50).collect();
270        shuffle(&mut rng, &mut items);
271        let mut sorted = items.clone();
272        sorted.sort_unstable();
273
274        assert_eq!(sorted, (0..50).collect::<alloc::vec::Vec<_>>());
275        for _ in 0..100 {
276            let (a, b) = two_sorted_indices(&mut rng, 3);
277            assert!(a < b && b < 3);
278        }
279
280        let picked = distinct_indices(&mut rng, 6, 5, Some(2));
281        assert_eq!(picked.len(), 5);
282        assert!(!picked.contains(&2));
283    }
284
285    /// Forked streams differ from each other and are reproducible.
286    #[test]
287    fn forks_are_distinct() {
288        let base = SplitMix64::new(9);
289
290        assert_ne!(base.fork(0), base.fork(1));
291        assert_eq!(base.fork(3), base.fork(3));
292    }
293}