Skip to main content

caroli_disorder/
rng.rs

1//! Reproducible random streams.
2//!
3//! caroli draws all its randomness from xoshiro256** (Blackman & Vigna, 2018), a small, fast
4//! generator with a fixed definition, so that a seed gives the same disorder on every platform
5//! and version. [`Xoshiro256::gfortran`] reproduces the stream of gfortran ≥ 9 after
6//! `random_seed(put = [seed, seed, …])`, the seeding used by the thesis codes: their disorder
7//! configurations can be rebuilt exactly.
8
9/// xoshiro256** generator.
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Xoshiro256 {
12    s: [u64; 4],
13}
14
15/// Keys gfortran XORs into a user seed (`scramble_seed`, libgfortran/intrinsics/random.c).
16const GFORTRAN_KEYS: [u64; 4] =
17    [0xbd0c5b6e50c2df49, 0xd46061cd46e1df38, 0xbb4f4d4ed6103544, 0x114a583d0756ad39];
18
19fn splitmix64(state: &mut u64) -> u64 {
20    *state = state.wrapping_add(0x9e3779b97f4a7c15);
21    let mut z = *state;
22    z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
23    z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
24    z ^ (z >> 31)
25}
26
27impl Xoshiro256 {
28    /// Generator seeded from a 64-bit value (state filled by splitmix64, as recommended by the
29    /// authors of xoshiro).
30    pub fn seed_from_u64(seed: u64) -> Self {
31        let mut sm = seed;
32        Self { s: [splitmix64(&mut sm), splitmix64(&mut sm), splitmix64(&mut sm), splitmix64(&mut sm)] }
33    }
34
35    /// Generator in the state gfortran ≥ 9 reaches after `random_seed(put = put)` (`put` has
36    /// 8 elements; the thesis codes fill it with one value, see [`Self::gfortran`]).
37    pub fn gfortran_put(put: [i32; 8]) -> Self {
38        // gfortran copies put(8), put(7), …, put(1) into consecutive 32-bit words of the state,
39        // then XORs the four 64-bit words with fixed keys.
40        let w = |k: usize| put[k] as u32 as u64;
41        let raw = [w(7) | w(6) << 32, w(5) | w(4) << 32, w(3) | w(2) << 32, w(1) | w(0) << 32];
42        Self { s: std::array::from_fn(|i| raw[i] ^ GFORTRAN_KEYS[i]) }
43    }
44
45    /// Generator in the state of the thesis routine `random_set(seed)`, i.e. gfortran's
46    /// `random_seed(put = [seed, seed, …])`.
47    pub fn gfortran(seed: i32) -> Self {
48        Self::gfortran_put([seed; 8])
49    }
50
51    /// Next 64 random bits.
52    pub fn next_u64(&mut self) -> u64 {
53        let s = &mut self.s;
54        let result = s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
55        let t = s[1] << 17;
56        s[2] ^= s[0];
57        s[3] ^= s[1];
58        s[1] ^= s[2];
59        s[0] ^= s[3];
60        s[2] ^= t;
61        s[3] = s[3].rotate_left(45);
62        result
63    }
64
65    /// Uniform number in `[0, 1)` with 53 random bits (identical to gfortran's
66    /// `random_number` for `real(8)`).
67    pub fn uniform(&mut self) -> f64 {
68        (self.next_u64() >> 11) as f64 * (1.0 / (1u64 << 53) as f64)
69    }
70
71    /// `n` uniform numbers (like `random_number` on an array of size `n`).
72    pub fn uniforms(&mut self, n: usize) -> Vec<f64> {
73        (0..n).map(|_| self.uniform()).collect()
74    }
75
76    /// Integer uniform in `lo..=hi`, drawn as `lo + ⌊(hi − lo + 1) u⌋` (thesis
77    /// `random_integer`).
78    pub fn integer(&mut self, lo: usize, hi: usize) -> usize {
79        lo + ((hi - lo + 1) as f64 * self.uniform()) as usize
80    }
81}
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86
87    /// Values printed by gfortran 16 (`random_seed(put = …)` then `random_number`).
88    #[test]
89    #[allow(clippy::excessive_precision)]
90    fn reproduces_gfortran() {
91        let mut r = Xoshiro256::gfortran(12345);
92        let expected = [
93            4.65636743897908767e-01,
94            1.00833111555351462e-01,
95            8.41914420882911130e-01,
96            7.73831493534653414e-01,
97            1.80372332904081167e-01,
98            8.44873831312145440e-01,
99        ];
100        for e in expected {
101            assert_eq!(r.uniform(), e);
102        }
103        assert_eq!(Xoshiro256::gfortran(1237).uniform(), 4.72208155982870581e-01);
104        assert_eq!(Xoshiro256::gfortran_put([1, 2, 3, 4, 5, 6, 7, 8]).uniform(), 4.71070899360821249e-01);
105    }
106
107    #[test]
108    fn seeds_differ() {
109        let a = Xoshiro256::seed_from_u64(1).uniforms(4);
110        let b = Xoshiro256::seed_from_u64(2).uniforms(4);
111        assert_ne!(a, b);
112        assert!(a.iter().all(|x| (0.0..1.0).contains(x)));
113    }
114}