Skip to main content

lib_jsl_random/
quasi_random.rs

1//! Low-discrepancy (quasi-random) sequences: Sobol and Halton.
2//!
3//! Quasi-random points fill the unit cube far more evenly than pseudo-random ones, so averages
4//! over them converge like `(log N)^d / N` instead of `N^{−1/2}`. They are deterministic; for
5//! error estimates, apply independent random shifts (randomized quasi-Monte Carlo).
6//!
7//! See the book entry [Quasi-random sequences](https://jwkunz.github.io/lib_jsl/book/random/quasi-random.html).
8
9use crate::uniform_generator::UniformGenerator;
10use lib_jsl_core::ErrorsJSL;
11
12use std::sync::OnceLock;
13
14/// Joe and Kuo's `new-joe-kuo-6.21201` table for dimensions 2 to 21201, `(degree s, interior
15/// coefficients a, m_1..m_s)`, decoded once from the compact varint file written by
16/// `crates/random/data/make_sobol_directions.py`.
17fn joe_kuo() -> &'static [(u32, u32, Vec<u64>)] {
18    static TABLE: OnceLock<Vec<(u32, u32, Vec<u64>)>> = OnceLock::new();
19    TABLE.get_or_init(|| {
20        let bytes: &[u8] = include_bytes!("../data/sobol_directions.bin");
21        let mut pos = 0;
22        let mut next = || {
23            let (mut v, mut shift) = (0u64, 0);
24            loop {
25                let b = bytes[pos];
26                pos += 1;
27                v |= ((b & 0x7F) as u64) << shift;
28                if b & 0x80 == 0 {
29                    return v;
30                }
31                shift += 7;
32            }
33        };
34        let mut table = Vec::with_capacity(SobolSequence::MAX_DIMENSION - 1);
35        for _ in 1..SobolSequence::MAX_DIMENSION {
36            let s = next() as u32;
37            let a = next() as u32;
38            let m = (0..s).map(|_| next()).collect();
39            table.push((s, a, m));
40        }
41        table
42    })
43}
44
45const BITS: usize = 64;
46
47/// The Sobol sequence in up to 21201 dimensions (Joe-Kuo direction numbers), generated in Gray-code
48/// order (Antonov and Saleev), one XOR per coordinate per point. The first point is the origin;
49/// every block of `2^k` consecutive points starting at a multiple of `2^k` is a `(t, k, d)`-net.
50#[derive(Debug, Clone)]
51pub struct SobolSequence {
52    directions: Vec<[u64; BITS]>,
53    state: Vec<u64>,
54    index: u64,
55}
56
57impl SobolSequence {
58    /// The largest supported dimension.
59    pub const MAX_DIMENSION: usize = 21201;
60
61    pub fn new(dimension: usize) -> Result<Self, ErrorsJSL> {
62        if dimension == 0 || dimension > Self::MAX_DIMENSION {
63            return Err(ErrorsJSL::InvalidInputRange("The Sobol dimension must be between 1 and 21201."));
64        }
65        let mut directions = Vec::with_capacity(dimension);
66        let mut first = [0u64; BITS];
67        for (i, v) in first.iter_mut().enumerate() {
68            *v = 1u64 << (BITS - 1 - i);
69        }
70        directions.push(first);
71        for (s, a, m) in joe_kuo().iter().take(dimension - 1) {
72            let (s, a) = (*s, *a);
73            let s = s as usize;
74            let mut v = [0u64; BITS];
75            for i in 0..s {
76                v[i] = m[i] << (BITS - 1 - i);
77            }
78            for i in s..BITS {
79                let mut value = v[i - s] ^ (v[i - s] >> s);
80                for k in 1..s {
81                    if (a >> (s - 1 - k)) & 1 == 1 {
82                        value ^= v[i - k];
83                    }
84                }
85                v[i] = value;
86            }
87            directions.push(v);
88        }
89        Ok(SobolSequence { directions, state: vec![0; dimension], index: 0 })
90    }
91
92    // ANCHOR: sobol_scramble
93    /// A scrambled Sobol sequence (SciPy's default, `Sobol(d, scramble=True)`): Matoušek's linear
94    /// matrix scrambling of each coordinate's direction numbers by a random lower triangular
95    /// binary matrix with unit diagonal, then a random digital shift (XOR). The points remain a
96    /// `(t, m, d)`-net in every block of `2^m`, but are no longer biased towards the origin, and
97    /// independent scramblings give independent, unbiased estimates.
98    pub fn scrambled<G: UniformGenerator>(dimension: usize, rng: &mut G) -> Result<Self, ErrorsJSL> {
99        let mut seq = Self::new(dimension)?;
100        for (v, x) in seq.directions.iter_mut().zip(seq.state.iter_mut()) {
101            // Row i of L acts on digit i (bit 63 − i); entries below the diagonal are random.
102            let rows: Vec<u64> = (0..BITS).map(|i| {
103                let below = if i == 0 { 0 } else { rng.next_u64() & !((1u64 << (BITS - i)) - 1) };
104                below | (1u64 << (BITS - 1 - i))
105            }).collect();
106            for d in v.iter_mut() {
107                *d = rows.iter().enumerate().fold(0u64, |acc, (i, r)| acc | (((r & *d).count_ones() as u64 & 1) << (BITS - 1 - i)));
108            }
109            *x = rng.next_u64();
110        }
111        Ok(seq)
112    }
113    // ANCHOR_END: sobol_scramble
114
115    pub fn dimension(&self) -> usize {
116        self.directions.len()
117    }
118
119    // ANCHOR: sobol_next
120    /// The next point in `[0, 1)^d`.
121    pub fn next_point(&mut self) -> Vec<f64> {
122        let point = self.state.iter().map(|&x| (x >> 11) as f64 * (1.0 / (1u64 << 53) as f64)).collect();
123        // Advance: flip the direction number at the lowest zero bit of the current index.
124        let bit = self.index.trailing_ones() as usize;
125        for (x, v) in self.state.iter_mut().zip(&self.directions) {
126            *x ^= v[bit.min(BITS - 1)];
127        }
128        self.index += 1;
129        point
130    }
131    // ANCHOR_END: sobol_next
132
133    /// Skips `count` points.
134    pub fn skip(&mut self, count: u64) {
135        for _ in 0..count {
136            self.next_point();
137        }
138    }
139}
140
141const PRIMES: [u64; 100] = [
142    2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
143    149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293,
144    307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
145    467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
146];
147
148// ANCHOR: radical_inverse
149/// The van der Corput radical inverse of `n` in base `b`: the base-b digits of `n` mirrored about
150/// the radix point.
151pub fn radical_inverse(mut n: u64, base: u64) -> f64 {
152    let inv = 1.0 / base as f64;
153    let (mut value, mut scale) = (0.0, inv);
154    while n > 0 {
155        value += (n % base) as f64 * scale;
156        n /= base;
157        scale *= inv;
158    }
159    value
160}
161// ANCHOR_END: radical_inverse
162
163/// The Halton sequence: coordinate `k` is the radical inverse in the k-th prime base. Simple and
164/// extensible to any number of points; uniformity degrades in high dimensions (large bases), where
165/// Sobol is preferable. Supports up to 100 dimensions. Starts at index 1 (skipping the origin).
166#[derive(Debug, Clone)]
167pub struct HaltonSequence {
168    dimension: usize,
169    index: u64,
170    /// For a scrambled sequence, one random permutation of the digits per coordinate and digit
171    /// position.
172    permutations: Option<Vec<Vec<Vec<u64>>>>,
173}
174
175impl HaltonSequence {
176    pub fn new(dimension: usize) -> Result<Self, ErrorsJSL> {
177        if dimension == 0 || dimension > PRIMES.len() {
178            return Err(ErrorsJSL::InvalidInputRange("The Halton dimension must be between 1 and 100."));
179        }
180        Ok(HaltonSequence { dimension, index: 1, permutations: None })
181    }
182
183    // ANCHOR: halton_scramble
184    /// A scrambled Halton sequence (SciPy's `Halton(d, scramble=True)`): in coordinate `k`, digit
185    /// position `j` of every index is mapped through one random permutation `π_{k,j}` of the
186    /// digits `0..b`, over as many positions as a double resolves. Unlike the plain sequence it
187    /// starts at index 0, and the permutations break up the correlations between large bases.
188    pub fn scrambled<G: UniformGenerator>(dimension: usize, rng: &mut G) -> Result<Self, ErrorsJSL> {
189        let mut seq = Self::new(dimension)?;
190        seq.index = 0;
191        let perms = PRIMES[..dimension]
192            .iter()
193            .map(|&b| {
194                let digits = (54.0 / (b as f64).log2()).ceil() as usize;
195                (0..digits)
196                    .map(|_| {
197                        let mut p: Vec<u64> = (0..b).collect();
198                        for i in (1..b as usize).rev() {
199                            let j = (rng.next_u64() % (i as u64 + 1)) as usize;
200                            p.swap(i, j);
201                        }
202                        p
203                    })
204                    .collect()
205            })
206            .collect();
207        seq.permutations = Some(perms);
208        Ok(seq)
209    }
210    // ANCHOR_END: halton_scramble
211
212    pub fn dimension(&self) -> usize {
213        self.dimension
214    }
215
216    pub fn next_point(&mut self) -> Vec<f64> {
217        let point = match &self.permutations {
218            None => PRIMES[..self.dimension].iter().map(|&p| radical_inverse(self.index, p)).collect(),
219            Some(perms) => PRIMES[..self.dimension]
220                .iter()
221                .zip(perms)
222                .map(|(&b, pk)| {
223                    let (mut n, mut scale, mut x) = (self.index, 1.0 / b as f64, 0.0);
224                    for pj in pk {
225                        x += pj[(n % b) as usize] as f64 * scale;
226                        n /= b;
227                        scale /= b as f64;
228                    }
229                    x.min(1.0 - f64::EPSILON / 2.0)
230                })
231                .collect(),
232        };
233        self.index += 1;
234        point
235    }
236
237    pub fn skip(&mut self, count: u64) {
238        self.index += count;
239    }
240}
241
242/// Applies a Cranley-Patterson rotation `x ← (x + u) mod 1` with a uniform random shift `u` per
243/// coordinate. Independent shifts give unbiased, independent replicates of a quasi-Monte Carlo
244/// estimate, whose spread estimates its error.
245pub fn random_shift<G: UniformGenerator>(points: &mut [Vec<f64>], rng: &mut G) {
246    let Some(d) = points.first().map(|p| p.len()) else { return };
247    let shift: Vec<f64> = (0..d).map(|_| rng.next_f64()).collect();
248    for p in points.iter_mut() {
249        for (x, u) in p.iter_mut().zip(&shift) {
250            *x = (*x + u).fract();
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::uniform_generator::UniformRNG;
259
260    /// Whether x^s + a₁x^{s−1} + … + a_{s−1}x + 1 is primitive over GF(2): the order of x modulo
261    /// it must be exactly 2^s − 1.
262    fn is_primitive(s: u32, a: u32) -> bool {
263        let poly = (1u64 << s) | ((a as u64) << 1) | 1;
264        let period = (1u64 << s) - 1;
265        let mut x = 1u64;
266        for k in 1..=period {
267            x <<= 1;
268            if x >> s & 1 == 1 {
269                x ^= poly;
270            }
271            if x == 1 {
272                return k == period;
273            }
274        }
275        false
276    }
277
278    #[test]
279    fn direction_number_table_is_valid() {
280        let mut seen = std::collections::HashSet::new();
281        assert_eq!(joe_kuo().len(), SobolSequence::MAX_DIMENSION - 1);
282        for (k, (s, a, m)) in joe_kuo().iter().enumerate() {
283            let (s, a) = (*s, *a);
284            // Primitivity is checked by brute force for the polynomials of degree up to 13
285            // (the first 1111 or so dimensions); the rest would take minutes.
286            if s <= 13 {
287                assert!(is_primitive(s, a), "polynomial ({s}, {a}) of dimension {} is not primitive", k + 2);
288            }
289            assert!(seen.insert((s, a)), "duplicate polynomial");
290            assert_eq!(m.len(), s as usize);
291            for (i, &mi) in m.iter().enumerate() {
292                assert!(mi % 2 == 1 && mi < 1 << (i + 1), "m_{} = {mi}", i + 1);
293            }
294        }
295    }
296
297    #[test]
298    fn sobol_points_form_nets() {
299        // Every coordinate of the full 21201-dimensional sequence is stratified.
300        let mut full = SobolSequence::new(SobolSequence::MAX_DIMENSION).unwrap();
301        let points: Vec<Vec<f64>> = (0..64).map(|_| full.next_point()).collect();
302        for d in (0..SobolSequence::MAX_DIMENSION).step_by(97).chain([SobolSequence::MAX_DIMENSION - 1]) {
303            let mut cells: Vec<u64> = points.iter().map(|p| (p[d] * 64.0) as u64).collect();
304            cells.sort_unstable();
305            assert!(cells.iter().enumerate().all(|(i, &c)| c == i as u64), "dimension {d}");
306        }
307        let low = 1111;
308        let mut sobol = SobolSequence::new(low).unwrap();
309        let points: Vec<Vec<f64>> = (0..1024).map(|_| sobol.next_point()).collect();
310        assert!(points[0].iter().all(|&x| x == 0.0) && points[1].iter().all(|&x| x == 0.5));
311        // Every 1D projection of the first 2^k points is exactly the grid {i / 2^k}.
312        for d in 0..low {
313            let mut cells: Vec<u64> = points[..256].iter().map(|p| (p[d] * 256.0) as u64).collect();
314            cells.sort_unstable();
315            assert!(cells.iter().enumerate().all(|(i, &c)| c == i as u64), "dimension {d}");
316        }
317        // The first two dimensions form a (0, 10, 2)-net: each of the 2^10 elementary boxes of
318        // any shape 2^{−i} × 2^{−(10−i)} holds exactly one point.
319        for i in 0..=10 {
320            let mut count = vec![0; 1024];
321            for p in &points {
322                let (bx, by) = ((p[0] * (1 << i) as f64) as usize, (p[1] * (1 << (10 - i)) as f64) as usize);
323                count[bx * (1 << (10 - i)) + by] += 1;
324            }
325            assert!(count.iter().all(|&c| c == 1), "shape {i}");
326        }
327        assert!(SobolSequence::new(0).is_err() && SobolSequence::new(21202).is_err());
328    }
329
330    #[test]
331    fn halton_matches_radical_inverses_and_shifts_stay_in_the_cube() {
332        assert_eq!(radical_inverse(6, 2), 0.375); // 110₂ → 0.011₂
333        assert!((radical_inverse(7, 3) - (1.0 / 3.0 + 2.0 / 9.0)).abs() < 1e-15); // 21₃ → 0.12₃
334        let mut h = HaltonSequence::new(3).unwrap();
335        assert_eq!(h.next_point(), vec![0.5, 1.0 / 3.0, 0.2]);
336        h.skip(2);
337        assert_eq!(h.next_point()[0], 0.125);
338        // Star discrepancy proxy: the mean of x·y·z over 4096 points is close to 1/8.
339        let mut h = HaltonSequence::new(3).unwrap();
340        let mut pts: Vec<Vec<f64>> = (0..4096).map(|_| h.next_point()).collect();
341        let mean: f64 = pts.iter().map(|p| p[0] * p[1] * p[2]).sum::<f64>() / 4096.0;
342        assert!((mean - 0.125).abs() < 1e-3);
343        random_shift(&mut pts, &mut UniformRNG::from_seed(4));
344        assert!(pts.iter().flatten().all(|&x| (0.0..1.0).contains(&x)));
345        assert!(HaltonSequence::new(101).is_err());
346    }
347}