Skip to main content

stochastic_search/
rng.rs

1//! The seeded pseudo-random generator behind LRTDP's successor sampling and the POMDP
2//! planners' simulations.
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.
7
8use core::convert::Infallible;
9
10use rand_core::Rng;
11
12/// The `SplitMix64` generator (Steele, Lea and Flood 2014).
13///
14/// Fast, with a full `2^64` period and good equidistribution for sampling. Not
15/// cryptographically secure, which sampling does not need. Public so that callers of
16/// [`update_belief`](crate::update_belief()) and of [`Pomdp::step`](crate::Pomdp::step) can
17/// use the same reproducible sequence as the planners; it implements `rand_core`'s
18/// generator traits.
19///
20/// ```
21/// use stochastic_search::{SplitMix64, unit_interval};
22///
23/// let mut rng = SplitMix64::new(7);
24/// assert!((0.0..1.0).contains(&unit_interval(&mut rng)));
25/// ```
26#[derive(Debug, Clone)]
27pub struct SplitMix64 {
28    /// The generator state, advanced by a fixed odd increment per draw.
29    state: u64,
30}
31
32impl SplitMix64 {
33    /// Creates a generator from a seed. Every seed, including `0`, is valid.
34    #[must_use]
35    pub const fn new(seed: u64) -> Self {
36        Self { state: seed }
37    }
38
39    /// Returns the next 64 random bits.
40    pub(crate) fn next_u64(&mut self) -> u64 {
41        self.state = self.state.wrapping_add(0x9E37_79B9_7F4A_7C15);
42        let mut z = self.state;
43        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
44        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
45
46        z ^ (z >> 31)
47    }
48
49    /// Returns a uniform sample from `[0, 1)` with 53 random bits.
50    pub(crate) fn next_unit(&mut self) -> f64 {
51        unit_interval(self)
52    }
53}
54
55impl rand_core::TryRng for SplitMix64 {
56    type Error = Infallible;
57
58    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
59        Ok((self.next_u64() >> 32) as u32)
60    }
61
62    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
63        Ok(self.next_u64())
64    }
65
66    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
67        rand_core::utils::fill_bytes_via_next_word(dst, || self.try_next_u64())
68    }
69}
70
71/// Returns a uniform sample from `[0, 1)` with 53 random bits drawn from `rng`.
72///
73/// `rand_core` has no floating-point helpers, and a generative
74/// [`Pomdp`](crate::Pomdp) usually needs one; this is the conversion the crate uses itself.
75///
76/// # Example
77///
78/// ```
79/// use stochastic_search::unit_interval;
80///
81/// # struct Counter(u64);
82/// # impl rand_core::TryRng for Counter {
83/// #     type Error = core::convert::Infallible;
84/// #     fn try_next_u32(&mut self) -> Result<u32, Self::Error> { Ok(0) }
85/// #     fn try_next_u64(&mut self) -> Result<u64, Self::Error> { self.0 += 1 << 62; Ok(self.0) }
86/// #     fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<(), Self::Error> { Ok(()) }
87/// # }
88/// let mut rng = Counter(0);
89/// assert_eq!(unit_interval(&mut rng), 0.25);
90/// ```
91pub fn unit_interval<R: Rng + ?Sized>(rng: &mut R) -> f64 {
92    /// `2^-53`, the spacing of the 53-bit grid on `[0, 1)`.
93    const SCALE: f64 = 1.0 / 9_007_199_254_740_992.0;
94
95    #[expect(
96        clippy::cast_precision_loss,
97        reason = "the value has at most 53 bits, which f64 represents exactly"
98    )]
99    let bits = (rng.next_u64() >> 11) as f64;
100
101    bits * SCALE
102}
103
104/// Derives the seed of an independent stream from `seed` and two stream coordinates, by
105/// running each coordinate through `SplitMix64`'s output mix in turn.
106pub(crate) fn derive_seed(seed: u64, a: u64, b: u64) -> u64 {
107    let first = SplitMix64::new(seed ^ a.wrapping_mul(0xD1B5_4A32_D192_ED03)).next_u64();
108
109    SplitMix64::new(first ^ b.wrapping_mul(0xA24B_AED4_963E_E407)).next_u64()
110}
111
112#[cfg(test)]
113mod tests {
114    use super::SplitMix64;
115
116    /// The first outputs for seed 0 match the reference implementation.
117    #[test]
118    fn matches_reference_sequence() {
119        let mut rng = SplitMix64::new(0);
120
121        assert_eq!(rng.next_u64(), 0xE220_A839_7B1D_CDAF);
122        assert_eq!(rng.next_u64(), 0x6E78_9E6A_A1B9_65F4);
123    }
124
125    /// Unit samples stay in `[0, 1)`.
126    #[test]
127    fn unit_samples_are_in_range() {
128        let mut rng = SplitMix64::new(42);
129
130        for _ in 0..1000 {
131            let u = rng.next_unit();
132            assert!((0.0..1.0).contains(&u));
133        }
134    }
135
136    /// Derived streams differ per coordinate and repeat for equal ones.
137    #[test]
138    fn derived_seeds_are_distinct_and_stable() {
139        use super::derive_seed;
140
141        let seeds = [
142            derive_seed(1, 0, 0),
143            derive_seed(1, 1, 0),
144            derive_seed(1, 0, 1),
145            derive_seed(2, 0, 0),
146        ];
147        for (i, a) in seeds.iter().enumerate() {
148            for b in &seeds[i + 1..] {
149                assert_ne!(a, b);
150            }
151        }
152
153        assert_eq!(derive_seed(1, 1, 0), seeds[1]);
154    }
155}