Skip to main content

lib_jsl_random/
sampling.rs

1//! Random variate generation from a given density or mass function, after the methods of UNU.RAN
2//! that `scipy.stats.sampling` wraps: the alias method and guide-table inversion for discrete
3//! distributions, transformed density rejection for log-concave densities, Hermite-interpolated
4//! numerical inversion of a distribution function, and the ratio-of-uniforms method.
5//!
6//! Distributions are given by closures (the density, its derivative, the distribution function).
7//! The generators draw from any [`UniformGenerator`]. They are exact (rejection methods) or exact
8//! to a stated resolution (inversion), and do not reproduce SciPy's numbers for the same seed:
9//! their uniform streams differ.
10//!
11//! See the book entry [Random variate generation](https://jwkunz.github.io/lib_jsl/book/random/variate-generation.html).
12
13use crate::quasi_random::SobolSequence;
14use crate::uniform_generator::UniformGenerator;
15use lib_jsl_core::ErrorsJSL;
16
17fn bad(msg: &'static str) -> ErrorsJSL {
18    ErrorsJSL::InvalidInputRange(msg)
19}
20
21fn check_pmf(pmf: &[f64]) -> Result<f64, ErrorsJSL> {
22    if pmf.is_empty() || pmf.iter().any(|&p| !p.is_finite() || p < 0.0) {
23        return Err(bad("the probabilities must be finite and non-negative, and there must be at least one"));
24    }
25    let total: f64 = pmf.iter().sum();
26    if total <= 0.0 {
27        return Err(bad("the probabilities sum to zero"));
28    }
29    Ok(total)
30}
31
32// ANCHOR: alias
33/// Walker's alias method (SciPy's `DiscreteAliasUrn`, Vose's construction): after `O(n)` set-up,
34/// each variate costs one uniform and one comparison. Each of `n` equally likely columns holds its
35/// own outcome with some probability and an *alias* otherwise.
36#[derive(Clone, Debug)]
37pub struct DiscreteAliasUrn {
38    probability: Vec<f64>,
39    alias: Vec<usize>,
40}
41
42impl DiscreteAliasUrn {
43    /// From (unnormalised) probabilities `pmf[k]` of the outcomes `0..n`.
44    pub fn new(pmf: &[f64]) -> Result<Self, ErrorsJSL> {
45        let total = check_pmf(pmf)?;
46        let n = pmf.len();
47        let mut scaled: Vec<f64> = pmf.iter().map(|p| p * n as f64 / total).collect();
48        let (mut small, mut large): (Vec<usize>, Vec<usize>) = (Vec::new(), Vec::new());
49        for (i, &s) in scaled.iter().enumerate() {
50            if s < 1.0 { small.push(i) } else { large.push(i) }
51        }
52        let (mut probability, mut alias) = (vec![1.0; n], (0..n).collect::<Vec<_>>());
53        while let (Some(&s), Some(&l)) = (small.last(), large.last()) {
54            small.pop();
55            probability[s] = scaled[s];
56            alias[s] = l;
57            scaled[l] -= 1.0 - scaled[s];
58            if scaled[l] < 1.0 {
59                large.pop();
60                small.push(l);
61            }
62        }
63        // What is left (by rounding) has probability one.
64        Ok(DiscreteAliasUrn { probability, alias })
65    }
66
67    /// One variate.
68    pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> usize {
69        let x = rng.next_f64() * self.probability.len() as f64;
70        let k = (x as usize).min(self.probability.len() - 1);
71        if x - (k as f64) < self.probability[k] { k } else { self.alias[k] }
72    }
73
74    /// `n` variates.
75    pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<usize> {
76        (0..n).map(|_| self.rvs_one(rng)).collect()
77    }
78}
79// ANCHOR_END: alias
80
81/// Inversion by guide table (SciPy's `DiscreteGuideTable`): the cumulative probabilities are
82/// searched from a table that says where to start for each of `guide_factor × n` equal slices of
83/// `[0, 1)`, so the expected search length is a small constant.
84#[derive(Clone, Debug)]
85pub struct DiscreteGuideTable {
86    cdf: Vec<f64>,
87    guide: Vec<usize>,
88}
89
90impl DiscreteGuideTable {
91    /// `guide_factor` is SciPy's default of 1.
92    pub fn new(pmf: &[f64], guide_factor: f64) -> Result<Self, ErrorsJSL> {
93        let total = check_pmf(pmf)?;
94        let n = pmf.len();
95        let mut cdf = Vec::with_capacity(n);
96        let mut acc = 0.0;
97        for p in pmf {
98            acc += p / total;
99            cdf.push(acc);
100        }
101        *cdf.last_mut().expect("non-empty") = 1.0;
102        let slices = ((guide_factor.max(0.1) * n as f64).ceil() as usize).max(1);
103        let mut guide = Vec::with_capacity(slices);
104        let mut k = 0;
105        for s in 0..slices {
106            let u = s as f64 / slices as f64;
107            while cdf[k] < u {
108                k += 1;
109            }
110            guide.push(k);
111        }
112        Ok(DiscreteGuideTable { cdf, guide })
113    }
114
115    /// The outcome for the uniform value `u ∈ [0, 1)`: the first `k` with `cdf[k] > u`.
116    pub fn ppf(&self, u: f64) -> usize {
117        let mut k = self.guide[((u * self.guide.len() as f64) as usize).min(self.guide.len() - 1)];
118        while k + 1 < self.cdf.len() && self.cdf[k] <= u {
119            k += 1;
120        }
121        k
122    }
123
124    pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> usize {
125        self.ppf(rng.next_f64())
126    }
127
128    pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<usize> {
129        (0..n).map(|_| self.rvs_one(rng)).collect()
130    }
131
132    /// `n` variates by inversion of the first points of the (unscrambled, one-dimensional) Sobol
133    /// sequence, a quasi-Monte Carlo sample (SciPy's `qrvs`). The sequence starts at 0, which
134    /// is skipped.
135    pub fn qrvs_sobol(&self, n: usize) -> Vec<usize> {
136        let mut sobol = SobolSequence::new(1).expect("one dimension");
137        sobol.next_point();
138        (0..n).map(|_| self.ppf(sobol.next_point()[0])).collect()
139    }
140}
141
142// ANCHOR: tdr
143/// Transformed density rejection with the logarithm as the transformation (SciPy's
144/// `TransformedDensityRejection`; Gilks and Wild's adaptive rejection sampling, Hörmann's
145/// formulation) for a log-concave density `f` on `(a, b)`.
146///
147/// The tangents of `log f` at a set of construction points bound `log f` above by a concave
148/// piecewise-linear function; its exponential is a *hat* made of exponential pieces, which can be
149/// sampled by inversion. A point `x` from the hat is accepted if `u · hat(x) ≤ f(x)`. Every
150/// rejected point is added as a new construction point, so the hat tightens where it matters; the
151/// variates stay exact whatever the number of points.
152pub struct TransformedDensityRejection<'a> {
153    pdf: Box<dyn Fn(f64) -> f64 + 'a>,
154    dpdf: Box<dyn Fn(f64) -> f64 + 'a>,
155    domain: (f64, f64),
156    /// Construction points, their `log f`, and the slopes of `log f` there.
157    x: Vec<f64>,
158    logf: Vec<f64>,
159    slope: Vec<f64>,
160    /// The hat's pieces: `[lo, hi, point index, integral]`, left to right.
161    pieces: Vec<(f64, f64, usize, f64)>,
162    /// The areas of the pieces up to and including each, for the search.
163    cumulative: Vec<f64>,
164    total: f64,
165    max_points: usize,
166}
167
168impl<'a> TransformedDensityRejection<'a> {
169    /// `pdf` and its derivative `dpdf` on the interval `domain` (ends may be infinite);
170    /// `center` is a point near the mode where the construction starts (SciPy's `mode` or
171    /// `center`). The density need not be normalised.
172    pub fn new(pdf: impl Fn(f64) -> f64 + 'a, dpdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64) -> Result<Self, ErrorsJSL> {
173        if !matches!(domain.0.partial_cmp(&domain.1), Some(std::cmp::Ordering::Less)) || !(domain.0..=domain.1).contains(&center) {
174            return Err(bad("the domain must be a non-empty interval containing the centre"));
175        }
176        let mut t = TransformedDensityRejection { pdf: Box::new(pdf), dpdf: Box::new(dpdf), domain, x: Vec::new(), logf: Vec::new(), slope: Vec::new(), pieces: Vec::new(), cumulative: Vec::new(), total: 0.0, max_points: 100 };
177        // The starting points: the centre, then outward until the slope of log f has the sign
178        // that makes the tails of the hat integrable (positive on the left, negative on the right).
179        let centre = if t.finite_positive(center) { center } else { return Err(bad("the density must be positive at the centre")) };
180        t.insert(centre)?;
181        let spread = if domain.0.is_finite() && domain.1.is_finite() { (domain.1 - domain.0) / 8.0 } else { 1.0 };
182        let mut step = spread;
183        if !domain.0.is_finite() || t.slope[0] <= 0.0 {
184            let mut x = centre;
185            for _ in 0..200 {
186                x = (x - step).max(domain.0);
187                if t.finite_positive(x) {
188                    t.insert(x)?;
189                    if t.slope[t.x.iter().position(|&v| v == x).expect("inserted")] > 0.0 || x <= domain.0 {
190                        break;
191                    }
192                } else {
193                    step *= 0.5;
194                    x += step * 2.0;
195                }
196                step *= 2.0;
197            }
198        }
199        step = spread;
200        if !domain.1.is_finite() || *t.slope.last().expect("a point") >= 0.0 {
201            let mut x = centre;
202            for _ in 0..200 {
203                x = (x + step).min(domain.1);
204                if t.finite_positive(x) {
205                    t.insert(x)?;
206                    if t.slope[t.x.iter().position(|&v| v == x).expect("inserted")] < 0.0 || x >= domain.1 {
207                        break;
208                    }
209                } else {
210                    step *= 0.5;
211                    x -= step * 2.0;
212                }
213                step *= 2.0;
214            }
215        }
216        // A few points beyond the first ones in each tail, where a density that is not
217        // log-concave usually shows it, then a few more between for a reasonable first hat.
218        let (first, last) = (t.x[0], *t.x.last().expect("points"));
219        for k in 1..=3 {
220            let reach = spread * 2f64.powi(k);
221            for x in [first - reach, last + reach] {
222                if x > domain.0 && x < domain.1 && t.finite_positive(x) {
223                    t.insert(x)?;
224                }
225            }
226        }
227        let (lo, hi) = (t.x[0], *t.x.last().expect("points"));
228        for k in 1..8 {
229            let x = lo + (hi - lo) * k as f64 / 8.0;
230            if t.finite_positive(x) && !t.x.contains(&x) {
231                t.insert(x)?;
232            }
233        }
234        // Log-concavity, as far as the construction points can tell: the slopes of log f must not
235        // increase from left to right.
236        if t.slope.windows(2).any(|w| w[1] > w[0] + 1e-9 * (1.0 + w[0].abs())) {
237            return Err(bad("the density is not log-concave (the slope of log f increases between construction points)"));
238        }
239        t.rebuild()?;
240        Ok(t)
241    }
242
243    fn finite_positive(&self, x: f64) -> bool {
244        let f = (self.pdf)(x);
245        f.is_finite() && f > 0.0
246    }
247
248    /// Adds a construction point, keeping the points sorted.
249    fn insert(&mut self, x: f64) -> Result<(), ErrorsJSL> {
250        let f = (self.pdf)(x);
251        if !(f.is_finite() && f > 0.0) {
252            return Err(bad("the density must be positive and finite at the construction points"));
253        }
254        let s = (self.dpdf)(x) / f;
255        if !s.is_finite() {
256            return Err(bad("the derivative of the density must be finite"));
257        }
258        let k = self.x.partition_point(|&v| v < x);
259        if self.x.get(k) == Some(&x) {
260            return Ok(());
261        }
262        let tol = |v: f64| 1e-9 * (1.0 + v.abs());
263        if (k > 0 && s > self.slope[k - 1] + tol(s)) || (k < self.x.len() && s < self.slope[k] - tol(s)) {
264            return Err(bad("the density is not log-concave"));
265        }
266        self.x.insert(k, x);
267        self.logf.insert(k, f.ln());
268        self.slope.insert(k, s);
269        Ok(())
270    }
271
272    /// The hat's pieces and total area from the construction points.
273    fn rebuild(&mut self) -> Result<(), ErrorsJSL> {
274        let n = self.x.len();
275        let mut pieces = Vec::with_capacity(n + 1);
276        let mut total = 0.0;
277        let area = |a: f64, lo: f64, hi: f64, s: f64, x0: f64, logf0: f64| -> f64 {
278            // ∫ exp(logf0 + s (x − x0)) dx over [lo, hi], with infinite ends handled by the sign of s.
279            let _ = a;
280            let at = |x: f64| logf0 + s * (x - x0);
281            if s == 0.0 {
282                at(0.0).exp() * 0.0 + logf0.exp() * (hi - lo)
283            } else if hi.is_infinite() {
284                at(lo).exp() / -s
285            } else if lo.is_infinite() {
286                at(hi).exp() / s
287            } else if s > 0.0 {
288                at(hi).exp() * (1.0 - (-s * (hi - lo)).exp()) / s
289            } else {
290                at(lo).exp() * (1.0 - (s * (hi - lo)).exp()) / -s
291            }
292        };
293        // Left tail.
294        if self.x[0] > self.domain.0 {
295            if self.slope[0] <= 0.0 && self.domain.0.is_infinite() {
296                return Err(bad("the density is not log-concave or its left tail is too heavy: the slope of log f is not positive on the left"));
297            }
298            let a = area(0.0, self.domain.0, self.x[0], self.slope[0], self.x[0], self.logf[0]);
299            pieces.push((self.domain.0, self.x[0], 0, a));
300            total += a;
301        }
302        for i in 0..n {
303            let (hi_x, next) = if i + 1 < n { (self.x[i + 1], Some(i + 1)) } else { (self.domain.1, None) };
304            match next {
305                Some(j) => {
306                    // Between the points the hat follows the lower of the two tangents.
307                    let (s0, s1) = (self.slope[i], self.slope[j]);
308                    let (t0, t1) = (self.logf[i] - s0 * self.x[i], self.logf[j] - s1 * self.x[j]);
309                    let xi = if (s0 - s1).abs() < 1e-300 { 0.5 * (self.x[i] + self.x[j]) } else { ((t1 - t0) / (s0 - s1)).clamp(self.x[i], self.x[j]) };
310                    let a1 = area(0.0, self.x[i], xi, s0, self.x[i], self.logf[i]);
311                    let a2 = area(0.0, xi, self.x[j], s1, self.x[j], self.logf[j]);
312                    pieces.push((self.x[i], xi, i, a1));
313                    pieces.push((xi, self.x[j], j, a2));
314                    total += a1 + a2;
315                }
316                None => {
317                    if self.x[i] < self.domain.1 {
318                        if self.slope[i] >= 0.0 && self.domain.1.is_infinite() {
319                            return Err(bad("the density is not log-concave or its right tail is too heavy: the slope of log f is not negative on the right"));
320                        }
321                        let a = area(0.0, self.x[i], hi_x, self.slope[i], self.x[i], self.logf[i]);
322                        pieces.push((self.x[i], hi_x, i, a));
323                        total += a;
324                    }
325                }
326            }
327        }
328        if !(total.is_finite() && total > 0.0) {
329            return Err(bad("the hat has no finite area"));
330        }
331        let mut acc = 0.0;
332        self.cumulative = pieces.iter().map(|p| { acc += p.3; acc }).collect();
333        self.pieces = pieces;
334        self.total = total;
335        Ok(())
336    }
337
338    /// The hat at `x`: `exp(logf_i + s_i (x − x_i))` for the tangent `i` of the piece holding `x`.
339    fn hat(&self, piece: usize, x: f64) -> f64 {
340        let (_, _, i, _) = self.pieces[piece];
341        (self.logf[i] + self.slope[i] * (x - self.x[i])).exp()
342    }
343
344    /// The area under the hat divided by the area under the density that it bounds: the expected
345    /// number of trials per variate is this ratio (`f` need only be proportional to the density,
346    /// so it is `total / ∫f`, estimated here by the ratio of the hat to its own squeeze: 1 if the
347    /// density is exactly exponential pieces). For a normalised density it is `total`.
348    pub fn hat_area(&self) -> f64 {
349        self.total
350    }
351
352    /// The number of construction points.
353    pub fn n_points(&self) -> usize {
354        self.x.len()
355    }
356
357    /// One variate. Rejected points tighten the hat while there is room (at most 200 points).
358    pub fn rvs_one<G: UniformGenerator>(&mut self, rng: &mut G) -> f64 {
359        loop {
360            // Choose a piece, then invert its exponential CDF.
361            let mut u = rng.next_f64() * self.total;
362            let piece = self.cumulative.partition_point(|&c| c <= u).min(self.pieces.len() - 1);
363            u -= if piece == 0 { 0.0 } else { self.cumulative[piece - 1] };
364            let (lo, hi, i, area) = self.pieces[piece];
365            let s = self.slope[i];
366            let v = (u / area).clamp(0.0, 1.0);
367            let x = if s == 0.0 {
368                lo + v * (hi - lo)
369            } else if hi.is_infinite() {
370                // Density ∝ exp(s (x − lo)) with s < 0: x = lo + ln(1 − v)/s.
371                lo + (1.0 - v).ln() / s
372            } else if lo.is_infinite() {
373                hi + (v.ln()) / s
374            } else {
375                // x = lo + ln(1 + v (e^{s (hi − lo)} − 1)) / s, written to avoid overflow.
376                let w = s * (hi - lo);
377                if s > 0.0 {
378                    hi + (v + (1.0 - v) * (-w).exp()).ln() / s
379                } else {
380                    lo + (1.0 + v * w.exp_m1()).ln() / s
381                }
382            };
383            let x = x.clamp(self.domain.0, self.domain.1);
384            let h = self.hat(piece, x);
385            let f = (self.pdf)(x);
386            if rng.next_f64() * h <= f {
387                return x;
388            }
389            if self.x.len() < self.max_points && f > 0.0 && f.is_finite() && self.insert(x).is_ok() {
390                let _ = self.rebuild();
391            }
392        }
393    }
394
395    pub fn rvs<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<f64> {
396        (0..n).map(|_| self.rvs_one(rng)).collect()
397    }
398}
399// ANCHOR_END: tdr
400
401/// The ratio-of-uniforms method (SciPy's `rvs_ratio_uniforms`): if `(u, v)` is uniform on the
402/// region `0 < u ≤ √f(v/u + c)`, then `v/u + c` has density proportional to `f`. Points are
403/// drawn from the rectangle `[0, umax] × [vmin, vmax]` that contains the region and kept if they
404/// fall inside it; `c` shifts the centre (SciPy's `c`).
405pub fn rvs_ratio_uniforms<G: UniformGenerator>(pdf: impl Fn(f64) -> f64, umax: f64, vmin: f64, vmax: f64, c: f64, n: usize, rng: &mut G) -> Result<Vec<f64>, ErrorsJSL> {
406    if !(umax > 0.0 && vmax > vmin) {
407        return Err(bad("the bounding rectangle must have positive width and height"));
408    }
409    let mut out = Vec::with_capacity(n);
410    let mut trials = 0u64;
411    while out.len() < n {
412        trials += 1;
413        if trials > 1000 * n as u64 + 100_000 {
414            return Err(bad("the bounding rectangle is far too large for the density: too many rejections"));
415        }
416        let u = rng.next_f64() * umax;
417        let v = vmin + rng.next_f64() * (vmax - vmin);
418        if u > 0.0 && u * u <= pdf(v / u + c) {
419            out.push(v / u + c);
420        }
421    }
422    Ok(out)
423}
424
425// ANCHOR: hinv
426/// Numerical inversion of a distribution function by cubic Hermite interpolation of its inverse
427/// (SciPy's `NumericalInverseHermite`; Hörmann and Leydold's HINV). The interval `(a, b)` is
428/// split until, on every piece, the cubic that matches `x` and `dx/du = 1/f(x)` at both ends
429/// inverts `F` to within `u_resolution`: `|F(x̂(u)) − u| ≤ ε` at the middle of the piece. The
430/// pieces are then a table, and a variate or a quantile costs a search and a cubic.
431pub struct NumericalInverseHermite<'a> {
432    cdf: Box<dyn Fn(f64) -> f64 + 'a>,
433    /// Knots: `x`, `F(x)`, and `dx/du`.
434    x: Vec<f64>,
435    u: Vec<f64>,
436    d: Vec<f64>,
437}
438
439impl<'a> NumericalInverseHermite<'a> {
440    /// `cdf` and `pdf` on `domain` (infinite ends are cut where the tail probability is below
441    /// `u_resolution / 10`); `center` is a point inside the distribution (SciPy's `center`).
442    pub fn new(cdf: impl Fn(f64) -> f64 + 'a, pdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64, u_resolution: f64) -> Result<Self, ErrorsJSL> {
443        if !matches!(domain.0.partial_cmp(&domain.1), Some(std::cmp::Ordering::Less)) || !(1e-15..=1e-3).contains(&u_resolution) {
444            return Err(bad("the domain must be a non-empty interval and the resolution between 1e-15 and 1e-3"));
445        }
446        let tail = 0.1 * u_resolution;
447        // Cut the tails.
448        let left = if domain.0.is_finite() {
449            domain.0
450        } else {
451            let (mut x, mut step) = (center, 1.0);
452            while cdf(x) > tail {
453                x -= step;
454                step *= 2.0;
455                if !x.is_finite() || step > 1e300 {
456                    return Err(bad("the left tail does not decay"));
457                }
458            }
459            x
460        };
461        let right = if domain.1.is_finite() {
462            domain.1
463        } else {
464            let (mut x, mut step) = (center, 1.0);
465            while 1.0 - cdf(x) > tail {
466                x += step;
467                step *= 2.0;
468                if !x.is_finite() || step > 1e300 {
469                    return Err(bad("the right tail does not decay"));
470                }
471            }
472            x
473        };
474        let density = |x: f64| pdf(x).max(f64::MIN_POSITIVE);
475        let (f_left, f_right) = (cdf(left), cdf(right));
476        // A first split into equal pieces in x, then recursive halving.
477        let mut knots: Vec<(f64, f64)> = vec![(left, f_left)];
478        let n0 = 20;
479        for k in 1..=n0 {
480            let x = left + (right - left) * k as f64 / n0 as f64;
481            knots.push((x, if k == n0 { f_right } else { cdf(x) }));
482        }
483        let mut done: Vec<(f64, f64)> = vec![knots[0]];
484        // Stack of intervals still to check, processed left to right.
485        let mut stack: Vec<((f64, f64), (f64, f64))> = (0..n0).rev().map(|k| (knots[k], knots[k + 1])).collect();
486        let mut guard = 0usize;
487        while let Some((a, b)) = stack.pop() {
488            guard += 1;
489            if guard > 2_000_000 {
490                return Err(bad("the interpolation does not converge: is the density continuous?"));
491            }
492            let (da, db) = (1.0 / density(a.0), 1.0 / density(b.0));
493            let h = b.1 - a.1;
494            let ok = if h <= 0.0 || b.0 - a.0 < 1e-14 * (1.0 + b.0.abs()) {
495                true
496            } else {
497                // Hermite value at the middle of the u-interval.
498                let t = 0.5;
499                let (h00, h10, h01, h11) = (2.0 * t * t * t - 3.0 * t * t + 1.0, t * t * t - 2.0 * t * t + t, -2.0 * t * t * t + 3.0 * t * t, t * t * t - t * t);
500                let xm = h00 * a.0 + h10 * h * da + h01 * b.0 + h11 * h * db;
501                let um = a.1 + t * h;
502                xm.is_finite() && xm >= a.0 && xm <= b.0 && (cdf(xm) - um).abs() <= 0.5 * u_resolution
503            };
504            if ok {
505                done.push(b);
506            } else {
507                let xm = 0.5 * (a.0 + b.0);
508                let m = (xm, cdf(xm));
509                stack.push((m, b));
510                stack.push((a, m));
511            }
512        }
513        let n = done.len();
514        let (x, u): (Vec<f64>, Vec<f64>) = done.into_iter().unzip();
515        let d: Vec<f64> = x.iter().map(|&xi| 1.0 / density(xi)).collect();
516        debug_assert_eq!(x.len(), n);
517        Ok(NumericalInverseHermite { cdf: Box::new(cdf), x, u, d })
518    }
519
520    /// The number of intervals of the table.
521    pub fn n_intervals(&self) -> usize {
522        self.x.len() - 1
523    }
524
525    /// The quantile function: `x` with `F(x) = u`, `0 ≤ u ≤ 1` (SciPy's `ppf`).
526    pub fn ppf(&self, u: f64) -> f64 {
527        if !(0.0..=1.0).contains(&u) {
528            return f64::NAN;
529        }
530        let u = u.clamp(self.u[0], *self.u.last().expect("knots"));
531        let k = self.u.partition_point(|&v| v <= u).saturating_sub(1).min(self.x.len() - 2);
532        let h = self.u[k + 1] - self.u[k];
533        if h <= 0.0 {
534            return self.x[k];
535        }
536        let t = (u - self.u[k]) / h;
537        let (h00, h10, h01, h11) = (2.0 * t * t * t - 3.0 * t * t + 1.0, t * t * t - 2.0 * t * t + t, -2.0 * t * t * t + 3.0 * t * t, t * t * t - t * t);
538        h00 * self.x[k] + h10 * h * self.d[k] + h01 * self.x[k + 1] + h11 * h * self.d[k + 1]
539    }
540
541    pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> f64 {
542        self.ppf(rng.next_f64())
543    }
544
545    pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<f64> {
546        (0..n).map(|_| self.rvs_one(rng)).collect()
547    }
548
549    /// `n` variates by inversion of the first points of the (unscrambled, one-dimensional) Sobol
550    /// sequence (SciPy's `qrvs`); their empirical distribution function converges to `F` like
551    /// `(log n)/n`, not `n^{-1/2}`. The sequence starts at 0, which is skipped.
552    pub fn qrvs_sobol(&self, n: usize) -> Vec<f64> {
553        let mut sobol = SobolSequence::new(1).expect("one dimension");
554        sobol.next_point();
555        (0..n).map(|_| self.ppf(sobol.next_point()[0])).collect()
556    }
557
558    /// The largest `|F(ppf(u)) − u|` over `n` equally spaced values of `u` (SciPy's `u_error`,
559    /// which uses random ones).
560    pub fn u_error(&self, n: usize) -> f64 {
561        (0..n).map(|k| (k as f64 + 0.5) / n as f64).map(|u| ((self.cdf)(self.ppf(u)) - u).abs()).fold(0.0, f64::max)
562    }
563}
564// ANCHOR_END: hinv
565
566// ANCHOR: srou
567/// The simple ratio-of-uniforms method (SciPy's `SimpleRatioUniforms`; Leydold's SROU) for a
568/// unimodal density with a known mode: the region `0 < u ≤ √f(x)`, `v = (x − mode) u`, lies inside
569/// the rectangle `[0, √f(mode)] × [v₋, v₊]` with `v₊ = sup_{x>mode} (x − mode) √f(x)` and `v₋ =
570/// inf_{x<mode} (x − mode) √f(x)`. The two suprema are found numerically at construction (a scan
571/// over geometrically spaced points, then golden-section refinement), so the density need not be
572/// normalised and no derivative is needed.
573pub struct SimpleRatioUniforms<'a> {
574    pdf: Box<dyn Fn(f64) -> f64 + 'a>,
575    mode: f64,
576    umax: f64,
577    vmin: f64,
578    vmax: f64,
579    domain: (f64, f64),
580    trials: u64,
581    accepted: u64,
582}
583
584/// The largest of `g(mode + sign·d)` over `d` in `(0, dmax]`, by a geometric scan and a golden
585/// search around the best scan point.
586fn scan_maximum(g: impl Fn(f64) -> f64, dmax: f64) -> f64 {
587    let mut best = (0.0f64, 0.0f64);
588    let mut d = dmax.min(1e12);
589    let hi = d;
590    let ratio = 1.05f64;
591    let mut points = Vec::new();
592    while d > hi * 1e-18 {
593        points.push(d);
594        d /= ratio;
595    }
596    if dmax.is_finite() && dmax < 1e12 {
597        // A finite end: also a uniform scan.
598        for k in 1..=2000 {
599            points.push(dmax * k as f64 / 2000.0);
600        }
601    }
602    for &d in &points {
603        let v = g(d);
604        if v.is_finite() && v > best.1 {
605            best = (d, v);
606        }
607    }
608    // Refine in the bracket of the best point.
609    let (mut lo, mut up) = (best.0 / ratio.powi(2), (best.0 * ratio.powi(2)).min(dmax));
610    for _ in 0..80 {
611        let (m1, m2) = (lo + (up - lo) * 0.381966, lo + (up - lo) * 0.618034);
612        if g(m1) < g(m2) {
613            lo = m1;
614        } else {
615            up = m2;
616        }
617    }
618    best.1.max(g(0.5 * (lo + up)))
619}
620
621impl<'a> SimpleRatioUniforms<'a> {
622    /// `pdf` (up to a constant) on `domain`, with its `mode`.
623    pub fn new(pdf: impl Fn(f64) -> f64 + 'a, mode: f64, domain: (f64, f64)) -> Result<Self, ErrorsJSL> {
624        if domain.0.is_nan() || domain.1.is_nan() || domain.0 > mode || mode > domain.1 || domain.0 >= domain.1 {
625            return Err(bad("the mode must lie inside the domain"));
626        }
627        let fm = pdf(mode);
628        if !(fm.is_finite() && fm > 0.0) {
629            return Err(bad("the density at the mode must be positive and finite"));
630        }
631        let up = |d: f64| d * pdf(mode + d).max(0.0).sqrt();
632        let down = |d: f64| d * pdf(mode - d).max(0.0).sqrt();
633        let vmax = if domain.1 > mode { scan_maximum(up, domain.1 - mode) } else { 0.0 };
634        let vmin = if domain.0 < mode { -scan_maximum(down, mode - domain.0) } else { 0.0 };
635        // A little room for the numerical search.
636        let (vmax, vmin) = (vmax * (1.0 + 1e-6), vmin * (1.0 + 1e-6));
637        if vmax.is_nan() || vmin.is_nan() || vmax <= vmin {
638            return Err(bad("the bounding rectangle is degenerate"));
639        }
640        Ok(SimpleRatioUniforms { pdf: Box::new(pdf), mode, umax: fm.sqrt() * (1.0 + 1e-12), vmin, vmax, domain, trials: 0, accepted: 0 })
641    }
642
643    /// The bounding rectangle `(umax, vmin, vmax)`.
644    pub fn bounds(&self) -> (f64, f64, f64) {
645        (self.umax, self.vmin, self.vmax)
646    }
647
648    /// The fraction of the points drawn so far that were kept.
649    pub fn acceptance_rate(&self) -> f64 {
650        if self.trials == 0 { f64::NAN } else { self.accepted as f64 / self.trials as f64 }
651    }
652
653    pub fn rvs_one<G: UniformGenerator>(&mut self, rng: &mut G) -> f64 {
654        loop {
655            self.trials += 1;
656            let u = rng.next_f64() * self.umax;
657            let v = self.vmin + rng.next_f64() * (self.vmax - self.vmin);
658            if u <= 0.0 {
659                continue;
660            }
661            let x = self.mode + v / u;
662            if x >= self.domain.0 && x <= self.domain.1 && u * u <= (self.pdf)(x) {
663                self.accepted += 1;
664                return x;
665            }
666        }
667    }
668
669    pub fn rvs<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<f64> {
670        (0..n).map(|_| self.rvs_one(rng)).collect()
671    }
672}
673// ANCHOR_END: srou
674
675/// Gauss-Legendre nodes and weights on `(−1, 1)`, by Newton's method on the Legendre polynomial.
676fn gauss_legendre(n: usize) -> (Vec<f64>, Vec<f64>) {
677    let (mut x, mut w) = (vec![0.0; n], vec![0.0; n]);
678    for i in 0..n.div_ceil(2) {
679        let mut z = (std::f64::consts::PI * (i as f64 + 0.75) / (n as f64 + 0.5)).cos();
680        let mut dp = 1.0;
681        for _ in 0..100 {
682            let (mut p0, mut p1) = (1.0, z);
683            for k in 2..=n {
684                let p2 = ((2 * k - 1) as f64 * z * p1 - (k - 1) as f64 * p0) / k as f64;
685                p0 = p1;
686                p1 = p2;
687            }
688            dp = n as f64 * (z * p1 - p0) / (z * z - 1.0);
689            let dz = p1 / dp;
690            z -= dz;
691            if dz.abs() < 1e-16 {
692                break;
693            }
694        }
695        x[i] = -z;
696        x[n - 1 - i] = z;
697        w[i] = 2.0 / ((1.0 - z * z) * dp * dp);
698        w[n - 1 - i] = w[i];
699    }
700    (x, w)
701}
702
703/// `∫ f` over `[a, b]` by adaptive 12-point Gauss-Legendre: an interval is accepted when its two
704/// halves agree with the whole to a relative `1e-14`, or after twelve levels of halving.
705fn integrate(f: &dyn Fn(f64) -> f64, rule: &(Vec<f64>, Vec<f64>), a: f64, b: f64) -> f64 {
706    fn panel(f: &dyn Fn(f64) -> f64, rule: &(Vec<f64>, Vec<f64>), a: f64, b: f64) -> f64 {
707        let (c, h) = (0.5 * (a + b), 0.5 * (b - a));
708        h * rule.0.iter().zip(&rule.1).map(|(&x, &w)| w * f(c + h * x)).sum::<f64>()
709    }
710    fn go(f: &dyn Fn(f64) -> f64, rule: &(Vec<f64>, Vec<f64>), a: f64, b: f64, whole: f64, depth: u32) -> f64 {
711        let m = 0.5 * (a + b);
712        let (l, r) = (panel(f, rule, a, m), panel(f, rule, m, b));
713        if depth == 0 || (l + r - whole).abs() <= 1e-14 * (l + r).abs().max(1e-300) {
714            l + r
715        } else {
716            go(f, rule, a, m, l, depth - 1) + go(f, rule, m, b, r, depth - 1)
717        }
718    }
719    if a == b {
720        return 0.0;
721    }
722    go(f, rule, a, b, panel(f, rule, a, b), 12)
723}
724
725// ANCHOR: pinv
726/// Numerical inversion of a distribution function from the density alone, by polynomial
727/// interpolation of its inverse (SciPy's `NumericalInversePolynomial`; Derflinger, Hörmann and
728/// Leydold's PINV). The interval is split until, on every piece, the polynomial of degree `order`
729/// through `order + 1` Chebyshev-Lobatto points of the piece, as a function of the probability
730/// mass, inverts the integral of the density to within `u_resolution` of the whole mass at
731/// three interior test points. The masses are integrals of the density (adaptive Gauss-Legendre),
732/// so the density needs neither normalising nor a distribution function.
733pub struct NumericalInversePolynomial<'a> {
734    pdf: Box<dyn Fn(f64) -> f64 + 'a>,
735    rule: (Vec<f64>, Vec<f64>),
736    order: usize,
737    /// Interval ends in `x`, and the cumulative probability at each.
738    x: Vec<f64>,
739    u: Vec<f64>,
740    /// Per interval: the nodes `s_j` (probability within the interval, in [0, 1]) and the Newton
741    /// coefficients of `x(s)`, `order + 1` each.
742    nodes: Vec<f64>,
743    coef: Vec<f64>,
744    area: f64,
745}
746
747/// A piece of the table: its ends, its mass, the nodes in probability and the Newton coefficients.
748type Piece = (f64, f64, f64, Vec<f64>, Vec<f64>);
749
750/// Newton divided differences of `y` at the nodes `s`, in place.
751fn divided_differences(s: &[f64], y: &mut [f64]) {
752    let n = s.len();
753    for j in 1..n {
754        for i in (j..n).rev() {
755            y[i] = (y[i] - y[i - 1]) / (s[i] - s[i - j]);
756        }
757    }
758}
759
760fn newton_eval(s: &[f64], c: &[f64], t: f64) -> f64 {
761    let mut v = c[c.len() - 1];
762    for j in (0..c.len() - 1).rev() {
763        v = v * (t - s[j]) + c[j];
764    }
765    v
766}
767
768impl<'a> NumericalInversePolynomial<'a> {
769    /// `pdf` (up to a constant) on `domain`; `order` is the degree of the polynomials (3 to 17,
770    /// SciPy's default is 5); infinite ends are cut where the mass of what is left is below
771    /// `u_resolution / 10` of the total. `center` is a point where the density is positive.
772    pub fn new(pdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64, order: usize, u_resolution: f64) -> Result<Self, ErrorsJSL> {
773        if !matches!(domain.0.partial_cmp(&domain.1), Some(std::cmp::Ordering::Less)) || !(1e-15..=1e-5).contains(&u_resolution) || !(1..=17).contains(&order) {
774            return Err(bad("the domain must be a non-empty interval, the resolution between 1e-15 and 1e-5 and the order between 1 and 17"));
775        }
776        let rule = gauss_legendre(12);
777        let pdfb: Box<dyn Fn(f64) -> f64 + 'a> = Box::new(pdf);
778        let f = |x: f64| pdfb(x).max(0.0);
779        // The effective domain.
780        let (mut lo, mut hi) = (domain.0.max(center - 1.0), domain.1.min(center + 1.0));
781        if lo >= hi {
782            lo = domain.0.max(center - 1.0).min(center);
783            hi = domain.1.min(center + 1.0).max(center);
784        }
785        let mut total = integrate(&f, &rule, lo, hi);
786        let mut grow = 1.0;
787        while total <= 0.0 && (lo > domain.0 || hi < domain.1) && grow < 1e30 {
788            grow *= 4.0;
789            lo = domain.0.max(center - grow);
790            hi = domain.1.min(center + grow);
791            total = integrate(&f, &rule, lo, hi);
792        }
793        if !(total > 0.0 && total.is_finite()) {
794            return Err(bad("the density has no mass near the centre"));
795        }
796        let tail = 0.1 * u_resolution;
797        let mut step = (hi - lo).max(1.0);
798        while hi < domain.1 {
799            let next = if domain.1.is_finite() { (hi + step).min(domain.1) } else { hi + step };
800            let m = integrate(&f, &rule, hi, next);
801            total += m;
802            hi = next;
803            if m <= tail * total {
804                break;
805            }
806            step *= 2.0;
807            if !hi.is_finite() || step > 1e300 {
808                return Err(bad("the right tail does not decay"));
809            }
810        }
811        step = (hi - lo).max(1.0) * 0.5;
812        while lo > domain.0 {
813            let next = if domain.0.is_finite() { (lo - step).max(domain.0) } else { lo - step };
814            let m = integrate(&f, &rule, next, lo);
815            total += m;
816            lo = next;
817            if m <= tail * total {
818                break;
819            }
820            step *= 2.0;
821            if !lo.is_finite() || step > 1e300 {
822                return Err(bad("the left tail does not decay"));
823            }
824        }
825        // Splitting.
826        let cheb = |k: usize| -> Vec<f64> { (0..=k).map(|j| 0.5 * (1.0 - (std::f64::consts::PI * j as f64 / k as f64).cos())).collect() };
827        let unit = cheb(order);
828        let mut stack: Vec<(f64, f64)> = {
829            let n0 = 16;
830            (0..n0).rev().map(|k| (lo + (hi - lo) * k as f64 / n0 as f64, lo + (hi - lo) * (k + 1) as f64 / n0 as f64)).collect()
831        };
832        let mut pieces: Vec<Piece> = Vec::new();
833        let mut guard = 0usize;
834        while let Some((a, b)) = stack.pop() {
835            guard += 1;
836            if guard > 400_000 {
837                return Err(bad("the interpolation does not converge: is the density continuous?"));
838            }
839            let xs: Vec<f64> = unit.iter().map(|&t| a + (b - a) * t).collect();
840            let mut cum = vec![0.0; xs.len()];
841            for j in 1..xs.len() {
842                cum[j] = cum[j - 1] + integrate(&f, &rule, xs[j - 1], xs[j]);
843            }
844            let mass = cum[order];
845            if mass <= 1e-3 * tail * total {
846                // Negligible mass: a straight line.
847                pieces.push((a, b, mass, vec![0.0, 1.0], vec![a, b - a]));
848                continue;
849            }
850            let s: Vec<f64> = cum.iter().map(|&c| c / mass).collect();
851            let mut c = xs.clone();
852            if s.windows(2).any(|w| w[1].is_nan() || w[1] <= w[0]) {
853                if b - a < 1e-13 * (1.0 + b.abs()) {
854                    pieces.push((a, b, mass, vec![0.0, 1.0], vec![a, b - a]));
855                } else {
856                    let m = 0.5 * (a + b);
857                    stack.push((m, b));
858                    stack.push((a, m));
859                }
860                continue;
861            }
862            divided_differences(&s, &mut c);
863            let mut ok = b - a < 1e-13 * (1.0 + b.abs());
864            if !ok {
865                ok = true;
866                for &t in &[0.17, 0.5, 0.83] {
867                    let xh = newton_eval(&s, &c, t);
868                    if !(xh >= a && xh <= b) {
869                        ok = false;
870                        break;
871                    }
872                    let err = (integrate(&f, &rule, a, xh) - t * mass).abs();
873                    if err > 0.5 * u_resolution * total {
874                        ok = false;
875                        break;
876                    }
877                }
878            }
879            if ok {
880                pieces.push((a, b, mass, s, c));
881            } else {
882                let m = 0.5 * (a + b);
883                stack.push((m, b));
884                stack.push((a, m));
885            }
886        }
887        let area: f64 = pieces.iter().map(|p| p.2).sum();
888        let (mut x, mut u, mut nodes, mut coef) = (vec![pieces[0].0], vec![0.0], Vec::new(), Vec::new());
889        let mut acc = 0.0;
890        for (_, b, mass, s, c) in pieces {
891            acc += mass;
892            x.push(b);
893            u.push(acc / area);
894            // Pad to a fixed width so the intervals index uniformly.
895            let w = order + 1;
896            let mut sp = s.clone();
897            let mut cp = c.clone();
898            sp.resize(w, 0.0);
899            cp.resize(w, 0.0);
900            nodes.extend(sp);
901            coef.extend(cp);
902        }
903        *u.last_mut().expect("pieces") = 1.0;
904        Ok(NumericalInversePolynomial { pdf: pdfb, rule, order, x, u, nodes, coef, area })
905    }
906
907    /// The number of intervals.
908    pub fn n_intervals(&self) -> usize {
909        self.x.len() - 1
910    }
911
912    /// The integral of the density over the domain (the normalising constant).
913    pub fn area(&self) -> f64 {
914        self.area
915    }
916
917    /// The quantile function: `x` with `F(x) = u`.
918    pub fn ppf(&self, u: f64) -> f64 {
919        if !(0.0..=1.0).contains(&u) {
920            return f64::NAN;
921        }
922        let k = self.u.partition_point(|&v| v <= u).saturating_sub(1).min(self.x.len() - 2);
923        let h = self.u[k + 1] - self.u[k];
924        let t = if h > 0.0 { ((u - self.u[k]) / h).clamp(0.0, 1.0) } else { 0.0 };
925        let w = self.order + 1;
926        // Pieces with a straight line carry two nodes and zero padding after them.
927        let (s, c) = (&self.nodes[k * w..(k + 1) * w], &self.coef[k * w..(k + 1) * w]);
928        let used = if s[1] == 1.0 && s[2..].iter().all(|&v| v == 0.0) && c[2..].iter().all(|&v| v == 0.0) { 2 } else { w };
929        newton_eval(&s[..used], &c[..used], t).clamp(self.x[k], self.x[k + 1])
930    }
931
932    /// The distribution function, by integrating the density from the start of the interval.
933    pub fn cdf(&self, x: f64) -> f64 {
934        if x <= self.x[0] {
935            return 0.0;
936        }
937        if x >= *self.x.last().expect("knots") {
938            return 1.0;
939        }
940        let k = self.x.partition_point(|&v| v <= x).saturating_sub(1).min(self.x.len() - 2);
941        let f = |t: f64| (self.pdf)(t).max(0.0);
942        (self.u[k] + integrate(&f, &self.rule, self.x[k], x) / self.area).clamp(0.0, 1.0)
943    }
944
945    pub fn rvs_one<G: UniformGenerator>(&self, rng: &mut G) -> f64 {
946        self.ppf(rng.next_f64())
947    }
948
949    pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<f64> {
950        (0..n).map(|_| self.rvs_one(rng)).collect()
951    }
952
953    /// `n` variates by inversion of the (unscrambled, one-dimensional) Sobol sequence.
954    pub fn qrvs_sobol(&self, n: usize) -> Vec<f64> {
955        let mut sobol = SobolSequence::new(1).expect("one dimension");
956        sobol.next_point();
957        (0..n).map(|_| self.ppf(sobol.next_point()[0])).collect()
958    }
959
960    /// The largest `|F(ppf(u)) − u|` over `n` equally spaced values of `u`.
961    pub fn u_error(&self, n: usize) -> f64 {
962        (0..n).map(|k| (k as f64 + 0.5) / n as f64).map(|u| (self.cdf(self.ppf(u)) - u).abs()).fold(0.0, f64::max)
963    }
964}
965// ANCHOR_END: pinv
966
967// ANCHOR: fgi
968/// Fast numerical inversion of a standard density with a location and a scale (SciPy's
969/// `FastGeneratorInversion`, which wraps the library's distributions and picks the method that
970/// suits each; here the density is given, and the method is polynomial inversion of order 5 at
971/// resolution `1e-12`): `X = loc + scale · Z`, `Z` with the given density.
972pub struct FastGeneratorInversion<'a> {
973    inner: NumericalInversePolynomial<'a>,
974    loc: f64,
975    scale: f64,
976}
977
978impl<'a> FastGeneratorInversion<'a> {
979    pub fn new(pdf: impl Fn(f64) -> f64 + 'a, domain: (f64, f64), center: f64, loc: f64, scale: f64) -> Result<Self, ErrorsJSL> {
980        if !(scale > 0.0 && scale.is_finite() && loc.is_finite()) {
981            return Err(bad("the scale must be positive and finite, the location finite"));
982        }
983        Ok(FastGeneratorInversion { inner: NumericalInversePolynomial::new(pdf, domain, center, 5, 1e-12)?, loc, scale })
984    }
985
986    /// The support of `X`.
987    pub fn support(&self) -> (f64, f64) {
988        (self.loc + self.scale * self.inner.x[0], self.loc + self.scale * self.inner.x[self.inner.x.len() - 1])
989    }
990
991    pub fn ppf(&self, u: f64) -> f64 {
992        self.loc + self.scale * self.inner.ppf(u)
993    }
994
995    pub fn cdf(&self, x: f64) -> f64 {
996        self.inner.cdf((x - self.loc) / self.scale)
997    }
998
999    pub fn rvs<G: UniformGenerator>(&self, n: usize, rng: &mut G) -> Vec<f64> {
1000        (0..n).map(|_| self.ppf(rng.next_f64())).collect()
1001    }
1002
1003    pub fn qrvs_sobol(&self, n: usize) -> Vec<f64> {
1004        self.inner.qrvs_sobol(n).into_iter().map(|z| self.loc + self.scale * z).collect()
1005    }
1006
1007    pub fn u_error(&self, n: usize) -> f64 {
1008        self.inner.u_error(n)
1009    }
1010}
1011// ANCHOR_END: fgi
1012
1013
1014// ANCHOR: mvrou
1015/// A density of a vector argument.
1016type VectorDensity<'a> = Box<dyn Fn(&[f64]) -> f64 + 'a>;
1017
1018/// The multivariate ratio-of-uniforms method (Wakefield, Gelfand and Smith 1991; the idea of UNU.RAN's
1019/// `VNROU`) for a unimodal density `f` on `ℝᵈ` known up to a constant, with its mode `m`: if `(u, v)`
1020/// is uniform on `{(u, v): 0 < u ≤ f(m + v/u)^{1/(d+1)}}`, then `m + v/u` has density `∝ f`. The region
1021/// lies in the box `[0, f(m)^{1/(d+1)}] × ∏ᵢ [vᵢ⁻, vᵢ⁺]` with `vᵢ⁺ = sup (xᵢ − mᵢ) f(x)^{1/(d+1)}` and
1022/// `vᵢ⁻ = inf`, found at construction by a derivative-free search from several starting points, with a
1023/// 1 % margin, or given. Points of the box are drawn and kept if they fall in the region. The method is exact when the box
1024/// contains the region, and its acceptance rate falls with `d` (about 27 % for the normal density at
1025/// `d = 3`, 7 % at `d = 5`).
1026pub struct MultivariateRatioUniforms<'a> {
1027    pdf: VectorDensity<'a>,
1028    mode: Vec<f64>,
1029    umax: f64,
1030    vmin: Vec<f64>,
1031    vmax: Vec<f64>,
1032    trials: u64,
1033    accepted: u64,
1034}
1035
1036/// The largest value of `g` found by a compass-and-random-direction search with an adaptive step,
1037/// from `x0`.
1038fn search_maximum(g: &dyn Fn(&[f64]) -> f64, x0: Vec<f64>, step0: f64) -> f64 {
1039    let d = x0.len();
1040    let (mut x, mut step) = (x0, step0);
1041    let mut fx = g(&x);
1042    let mut state = 0x2545_F491_4F6C_DD1Du64;
1043    let mut dirs: Vec<Vec<f64>> = (0..d)
1044        .flat_map(|i| {
1045            let mut e = vec![0.0; d];
1046            e[i] = 1.0;
1047            let m: Vec<f64> = e.iter().map(|t| -t).collect();
1048            [e, m]
1049        })
1050        .collect();
1051    for _ in 0..4000 {
1052        // Random directions join the coordinate ones, so that ridges not aligned with the axes are followed.
1053        dirs.truncate(2 * d);
1054        for _ in 0..2 * d {
1055            let mut v: Vec<f64> = (0..d)
1056                .map(|_| {
1057                    state ^= state << 13;
1058                    state ^= state >> 7;
1059                    state ^= state << 17;
1060                    (state >> 11) as f64 / (1u64 << 53) as f64 - 0.5
1061                })
1062                .collect();
1063            let n = v.iter().map(|t| t * t).sum::<f64>().sqrt().max(1e-300);
1064            v.iter_mut().for_each(|t| *t /= n);
1065            dirs.push(v);
1066        }
1067        let mut improved = false;
1068        for dir in &dirs {
1069            let y: Vec<f64> = x.iter().zip(dir).map(|(a, b)| a + step * b).collect();
1070            let fy = g(&y);
1071            if fy > fx {
1072                x = y;
1073                fx = fy;
1074                improved = true;
1075            }
1076        }
1077        step *= if improved { 1.4 } else { 0.5 };
1078        if step < 1e-11 * (1.0 + x.iter().fold(0.0f64, |m, t| m.max(t.abs()))) {
1079            break;
1080        }
1081    }
1082    fx
1083}
1084
1085impl<'a> MultivariateRatioUniforms<'a> {
1086    /// `pdf` (up to a constant) with its `mode`; the box is found numerically.
1087    pub fn new(pdf: impl Fn(&[f64]) -> f64 + 'a, mode: &[f64]) -> Result<Self, ErrorsJSL> {
1088        let d = mode.len();
1089        let fm = pdf(mode);
1090        if d == 0 || !(fm.is_finite() && fm > 0.0) {
1091            return Err(bad("the density at the mode must be positive and finite, and the dimension positive"));
1092        }
1093        let r = 1.0 / (d as f64 + 1.0);
1094        let (mut vmin, mut vmax) = (vec![0.0; d], vec![0.0; d]);
1095        for i in 0..d {
1096            for (sign, out) in [(1.0, &mut vmax[i]), (-1.0, &mut vmin[i])] {
1097                let g = |x: &[f64]| {
1098                    let f = pdf(x);
1099                    if f.is_finite() && f > 0.0 { sign * (x[i] - mode[i]) * f.powf(r) } else { 0.0 }
1100                };
1101                let mut best = 0.0f64;
1102                for dist in [0.5, 1.5, 4.0, 12.0] {
1103                    let mut x0 = mode.to_vec();
1104                    x0[i] += sign * dist;
1105                    best = best.max(search_maximum(&g, x0, 0.5 * dist));
1106                }
1107                *out = sign * best * 1.01;
1108            }
1109        }
1110        Self::with_bounds(pdf, mode, vmin, vmax)
1111    }
1112
1113    /// With the box given: `vmin[i] ≤ 0 ≤ vmax[i]` must contain `(xᵢ − mᵢ) f(x)^{1/(d+1)}` for every `x`.
1114    pub fn with_bounds(pdf: impl Fn(&[f64]) -> f64 + 'a, mode: &[f64], vmin: Vec<f64>, vmax: Vec<f64>) -> Result<Self, ErrorsJSL> {
1115        let d = mode.len();
1116        if vmin.len() != d || vmax.len() != d || vmin.iter().zip(&vmax).any(|(a, b)| a.is_nan() || b.is_nan() || a >= b) {
1117            return Err(bad("the bounds must have the dimension of the mode, with vmin < vmax"));
1118        }
1119        let fm = pdf(mode);
1120        if !(fm.is_finite() && fm > 0.0) {
1121            return Err(bad("the density at the mode must be positive and finite"));
1122        }
1123        let umax = fm.powf(1.0 / (d as f64 + 1.0)) * (1.0 + 1e-12);
1124        Ok(MultivariateRatioUniforms { pdf: Box::new(pdf), mode: mode.to_vec(), umax, vmin, vmax, trials: 0, accepted: 0 })
1125    }
1126
1127    /// The box `(umax, vmin, vmax)`.
1128    pub fn bounds(&self) -> (f64, &[f64], &[f64]) {
1129        (self.umax, &self.vmin, &self.vmax)
1130    }
1131
1132    /// The fraction of the points drawn so far that were kept.
1133    pub fn acceptance_rate(&self) -> f64 {
1134        if self.trials == 0 { f64::NAN } else { self.accepted as f64 / self.trials as f64 }
1135    }
1136
1137    pub fn rvs_one<G: UniformGenerator>(&mut self, rng: &mut G) -> Vec<f64> {
1138        let d = self.mode.len();
1139        let power = d as f64 + 1.0;
1140        loop {
1141            self.trials += 1;
1142            let u = rng.next_f64() * self.umax;
1143            if u <= 0.0 {
1144                continue;
1145            }
1146            let x: Vec<f64> = (0..d).map(|i| self.mode[i] + (self.vmin[i] + rng.next_f64() * (self.vmax[i] - self.vmin[i])) / u).collect();
1147            if u.powf(power) <= (self.pdf)(&x) {
1148                self.accepted += 1;
1149                return x;
1150            }
1151        }
1152    }
1153
1154    pub fn rvs<G: UniformGenerator>(&mut self, n: usize, rng: &mut G) -> Vec<Vec<f64>> {
1155        (0..n).map(|_| self.rvs_one(rng)).collect()
1156    }
1157}
1158// ANCHOR_END: mvrou
1159
1160
1161#[cfg(test)]
1162mod tests {
1163    use super::*;
1164    use crate::uniform_generator::UniformRNG;
1165
1166    /// The Kolmogorov-Smirnov distance of a sample from a distribution function.
1167    fn ks(mut sample: Vec<f64>, cdf: impl Fn(f64) -> f64) -> f64 {
1168        sample.sort_by(f64::total_cmp);
1169        let n = sample.len() as f64;
1170        sample.iter().enumerate().map(|(i, &x)| {
1171            let f = cdf(x);
1172            (f - i as f64 / n).abs().max((f - (i + 1) as f64 / n).abs())
1173        }).fold(0.0, f64::max)
1174    }
1175
1176    fn erf(x: f64) -> f64 {
1177        // Abramowitz and Stegun 7.1.26 is not accurate enough; use a series/continued fraction.
1178        let t = 1.0 / (1.0 + 0.5 * x.abs());
1179        let y = 1.0 - t * (-x * x - 1.26551223 + t * (1.00002368 + t * (0.37409196 + t * (0.09678418 + t * (-0.18628806 + t * (0.27886807 + t * (-1.13520398 + t * (1.48851587 + t * (-0.82215223 + t * 0.17087277))))))))).exp();
1180        if x >= 0.0 { y } else { -y }
1181    }
1182
1183    fn normal_cdf(x: f64) -> f64 {
1184        0.5 * (1.0 + erf(x / std::f64::consts::SQRT_2))
1185    }
1186
1187    #[test]
1188    fn alias_and_guide_table_reproduce_the_probabilities() {
1189        let pmf = [0.1, 0.0, 0.25, 0.05, 0.4, 0.2];
1190        let mut rng = UniformRNG::from_seed(1);
1191        let n = 200_000;
1192        for sample in [DiscreteAliasUrn::new(&pmf).unwrap().rvs(n, &mut rng), DiscreteGuideTable::new(&pmf, 1.0).unwrap().rvs(n, &mut rng)] {
1193            let mut counts = [0usize; 6];
1194            sample.iter().for_each(|&k| counts[k] += 1);
1195            assert_eq!(counts[1], 0, "a zero probability is never drawn");
1196            for (c, p) in counts.iter().zip(&pmf) {
1197                assert!((*c as f64 / n as f64 - p).abs() < 4.0 * (p * (1.0 - p) / n as f64).sqrt() + 1e-4, "{counts:?}");
1198            }
1199        }
1200        assert!(DiscreteAliasUrn::new(&[]).is_err() && DiscreteAliasUrn::new(&[0.0, 0.0]).is_err() && DiscreteAliasUrn::new(&[-1.0, 2.0]).is_err());
1201        // The guide table's inversion: ppf is the first k with cdf > u.
1202        let g = DiscreteGuideTable::new(&pmf, 2.0).unwrap();
1203        assert_eq!((g.ppf(0.0), g.ppf(0.0999), g.ppf(0.1), g.ppf(0.999999)), (0, 0, 2, 5));
1204    }
1205
1206    #[test]
1207    fn transformed_density_rejection_samples_log_concave_densities() {
1208        let mut rng = UniformRNG::from_seed(2);
1209        let n = 100_000;
1210        // The standard normal, unnormalised.
1211        let mut t = TransformedDensityRejection::new(|x| (-0.5 * x * x).exp(), |x| -x * (-0.5 * x * x).exp(), (f64::NEG_INFINITY, f64::INFINITY), 0.0).unwrap();
1212        let sample = t.rvs(n, &mut rng);
1213        assert!(ks(sample, normal_cdf) < 0.006, "normal");
1214        // Gamma(3): x² e^{−x}/2 on (0, ∞).
1215        let mut t = TransformedDensityRejection::new(|x| x * x * (-x).exp(), |x| (2.0 * x - x * x) * (-x).exp(), (0.0, f64::INFINITY), 2.0).unwrap();
1216        let gamma3 = |x: f64| 1.0 - (-x).exp() * (1.0 + x + 0.5 * x * x);
1217        assert!(ks(t.rvs(n, &mut rng), gamma3) < 0.006, "gamma");
1218        // Beta(2, 3) on a finite interval: 12 x (1 − x)².
1219        let mut t = TransformedDensityRejection::new(|x| x * (1.0 - x) * (1.0 - x), |x| (1.0 - x) * (1.0 - 3.0 * x), (0.0, 1.0), 0.3).unwrap();
1220        let beta23 = |x: f64| 6.0 * x * x - 8.0 * x * x * x + 3.0 * x.powi(4);
1221        assert!(ks(t.rvs(n, &mut rng), beta23) < 0.006, "beta");
1222        // The hat gets tighter as it is used.
1223        assert!(t.n_points() >= 8);
1224        // A density that is not log-concave in the tail is refused rather than sampled wrongly.
1225        assert!(TransformedDensityRejection::new(|x| 1.0 / (1.0 + x * x), |x| -2.0 * x / (1.0 + x * x).powi(2), (f64::NEG_INFINITY, f64::INFINITY), 0.0).is_err());
1226        assert!(TransformedDensityRejection::new(|x| x, |_| 1.0, (1.0, 0.0), 0.5).is_err());
1227    }
1228
1229    #[test]
1230    fn hermite_inversion_reaches_its_resolution() {
1231        let pdf = |x: f64| (-0.5 * x * x).exp() / (2.0 * std::f64::consts::PI).sqrt();
1232        let h = NumericalInverseHermite::new(normal_cdf, pdf, (f64::NEG_INFINITY, f64::INFINITY), 0.0, 1e-8).unwrap();
1233        // normal_cdf here is accurate to about 1e-7, so test against the exact median and
1234        // symmetry, and the u-error against that cdf.
1235        assert!(h.ppf(0.5).abs() < 1e-7);
1236        assert!((h.ppf(0.1) + h.ppf(0.9)).abs() < 1e-7);
1237        assert!(h.u_error(10_000) < 1e-7);
1238        let mut rng = UniformRNG::from_seed(3);
1239        assert!(ks(h.rvs(50_000, &mut rng), normal_cdf) < 0.007);
1240        assert!(h.n_intervals() > 20);
1241        // A finite domain: the triangular density 2x on (0, 1) has the exact inverse √u.
1242        let t = NumericalInverseHermite::new(|x| x * x, |x| 2.0 * x, (0.0, 1.0), 0.5, 1e-10).unwrap();
1243        for u in [0.01, 0.25, 0.5, 0.9, 0.999] {
1244            assert!((t.ppf(u) - u.sqrt()).abs() < 1e-9, "{u}");
1245        }
1246        assert!(t.ppf(1.5).is_nan());
1247        // Quasi-Monte Carlo variates fit far better than random ones of the same number.
1248        assert!(ks(h.qrvs_sobol(4096), normal_cdf) < 5e-4);
1249        let g = DiscreteGuideTable::new(&[0.2, 0.3, 0.5], 1.0).unwrap();
1250        let counts = g.qrvs_sobol(1024).iter().fold([0usize; 3], |mut c, &k| { c[k] += 1; c });
1251        assert!((counts[0] as f64 - 204.8).abs() < 3.0 && (counts[1] as f64 - 307.2).abs() < 3.0, "{counts:?}");
1252    }
1253
1254
1255    #[test]
1256    fn ratio_of_uniforms_samples_the_normal() {
1257        let mut rng = UniformRNG::from_seed(4);
1258        // f(x) = exp(−x²/2): u ≤ 1, |v| ≤ √(2/e).
1259        let b = (2.0 / std::f64::consts::E).sqrt();
1260        let s = rvs_ratio_uniforms(|x| (-0.5 * x * x).exp(), 1.0, -b, b, 0.0, 50_000, &mut rng).unwrap();
1261        assert!(ks(s, normal_cdf) < 0.008);
1262        assert!(rvs_ratio_uniforms(|x| x, 0.0, 0.0, 1.0, 0.0, 10, &mut rng).is_err());
1263    }
1264
1265    #[test]
1266    fn simple_ratio_uniforms_samples_unimodal_densities() {
1267        let mut rng = UniformRNG::from_seed(7);
1268        let n = 100_000;
1269        // The normal, unnormalised, with its mode at 1 (shifted).
1270        let mut g = SimpleRatioUniforms::new(|x| (-0.5 * (x - 1.0) * (x - 1.0)).exp(), 1.0, (f64::NEG_INFINITY, f64::INFINITY)).unwrap();
1271        let (umax, vmin, vmax) = g.bounds();
1272        // sup d·exp(−d²/4) = √2 e^{−1/2}, at d = √2.
1273        let exact = 2f64.sqrt() * (-0.5f64).exp();
1274        assert!((umax - 1.0).abs() < 1e-9 && (vmax - exact).abs() < 1e-5 && (vmin + exact).abs() < 1e-5, "{vmin} {vmax}");
1275        assert!(vmin < 0.0 && vmax > 0.0);
1276        let sample = g.rvs(n, &mut rng);
1277        assert!(ks(sample, |x| normal_cdf(x - 1.0)) < 0.006);
1278        // Exponential: the mode is the left end of the domain.
1279        let mut g = SimpleRatioUniforms::new(|x| (-x).exp(), 0.0, (0.0, f64::INFINITY)).unwrap();
1280        assert!(ks(g.rvs(n, &mut rng), |x| 1.0 - (-x).exp()) < 0.006);
1281        // Beta(2, 3) on [0, 1], with the mode 1/3.
1282        let mut g = SimpleRatioUniforms::new(|x| x * (1.0 - x) * (1.0 - x), 1.0 / 3.0, (0.0, 1.0)).unwrap();
1283        assert!(ks(g.rvs(n, &mut rng), |x| 6.0 * x * x - 8.0 * x * x * x + 3.0 * x.powi(4)) < 0.006);
1284        assert!(SimpleRatioUniforms::new(|x| x, 5.0, (0.0, 1.0)).is_err());
1285    }
1286
1287    #[test]
1288    fn polynomial_inversion_needs_only_the_density() {
1289        let mut rng = UniformRNG::from_seed(8);
1290        // The normal density, unnormalised.
1291        let g = NumericalInversePolynomial::new(|x| (-0.5 * x * x).exp(), (f64::NEG_INFINITY, f64::INFINITY), 0.0, 5, 1e-12).unwrap();
1292        assert!((g.area() - (2.0 * std::f64::consts::PI).sqrt()).abs() < 1e-9);
1293        assert!(g.u_error(2000) < 5e-12, "u-error {}", g.u_error(2000));
1294        assert!((g.ppf(0.5)).abs() < 1e-9 && (g.ppf(0.975) - 1.959963984540054).abs() < 1e-8);
1295        assert!(ks(g.rvs(100_000, &mut rng), normal_cdf) < 0.006);
1296        // A skewed one on a half line, and a finite one with a singular-looking end (Beta(0.5, 2)).
1297        let gamma = NumericalInversePolynomial::new(|x| x.powf(1.5) * (-x).exp(), (0.0, f64::INFINITY), 2.0, 5, 1e-12).unwrap();
1298        assert!(gamma.u_error(2000) < 5e-12);
1299        let beta = NumericalInversePolynomial::new(|x| x.powf(-0.5) * (1.0 - x), (0.0, 1.0), 0.3, 5, 1e-10).unwrap();
1300        assert!(beta.u_error(2000) < 5e-10, "beta {}", beta.u_error(2000));
1301        assert!(NumericalInversePolynomial::new(|x| x, (1.0, 0.0), 0.5, 5, 1e-12).is_err());
1302        assert!(NumericalInversePolynomial::new(|x| x, (0.0, 1.0), 0.5, 5, 0.1).is_err());
1303    }
1304
1305    #[test]
1306    fn fast_generator_inversion_applies_location_and_scale() {
1307        let g = FastGeneratorInversion::new(|x| (-0.5 * x * x).exp(), (f64::NEG_INFINITY, f64::INFINITY), 0.0, 3.0, 2.0).unwrap();
1308        assert!((g.ppf(0.5) - 3.0).abs() < 1e-8);
1309        // (the test's normal_cdf is good to about 1e-7)
1310        assert!((g.cdf(5.0) - 0.8413447460685429).abs() < 1e-12);
1311        let mut rng = UniformRNG::from_seed(9);
1312        assert!(ks(g.rvs(50_000, &mut rng), |x| normal_cdf((x - 3.0) / 2.0)) < 0.008);
1313        assert!(g.support().0 < -10.0 && g.support().1 > 16.0);
1314        assert!(FastGeneratorInversion::new(|x| x, (0.0, 1.0), 0.5, 0.0, -1.0).is_err());
1315    }
1316
1317    #[test]
1318    fn multivariate_ratio_of_uniforms_samples_unimodal_densities() {
1319        let mut rng = UniformRNG::from_seed(11);
1320        let n = 60_000;
1321        // A correlated normal in 3-D: covariance [[2, .6, 0], [.6, 1, .3], [0, .3, .5]], mean (1, −1, 0.5).
1322        let cov = [[2.0, 0.6, 0.0], [0.6, 1.0, 0.3], [0.0, 0.3, 0.5]];
1323        let mean = [1.0, -1.0, 0.5];
1324        // Its inverse by cofactors.
1325        let det = 2.0 * (0.5 - 0.09) - 0.6 * (0.3 - 0.0);
1326        let inv = [[(1.0 * 0.5 - 0.09) / det, -(0.6 * 0.5 - 0.0) / det, (0.6 * 0.3 - 0.0) / det], [-(0.6 * 0.5) / det, 2.0 * 0.5 / det, -(2.0 * 0.3) / det], [(0.6 * 0.3) / det, -(2.0 * 0.3) / det, (2.0 * 1.0 - 0.36) / det]];
1327        let pdf = |x: &[f64]| {
1328            let d: Vec<f64> = (0..3).map(|i| x[i] - mean[i]).collect();
1329            let q: f64 = (0..3).map(|i| (0..3).map(|j| d[i] * inv[i][j] * d[j]).sum::<f64>()).sum();
1330            (-0.5 * q).exp()
1331        };
1332        let mut g = MultivariateRatioUniforms::new(pdf, &mean).unwrap();
1333        let sample = g.rvs(n, &mut rng);
1334        let m: Vec<f64> = (0..3).map(|i| sample.iter().map(|x| x[i]).sum::<f64>() / n as f64).collect();
1335        for i in 0..3 {
1336            assert!((m[i] - mean[i]).abs() < 0.03, "mean {i}: {}", m[i]);
1337            for j in 0..3 {
1338                let c = sample.iter().map(|x| (x[i] - m[i]) * (x[j] - m[j])).sum::<f64>() / n as f64;
1339                assert!((c - cov[i][j]).abs() < 0.04, "cov {i}{j}: {c}");
1340            }
1341        }
1342        // Each marginal is normal: Kolmogorov-Smirnov.
1343        for i in 0..3 {
1344            let s = sample.iter().map(|x| (x[i] - mean[i]) / cov[i][i].sqrt()).collect::<Vec<_>>();
1345            assert!(ks(s, normal_cdf) < 0.009, "marginal {i}");
1346        }
1347        assert!((0.1..0.5).contains(&g.acceptance_rate()), "{}", g.acceptance_rate());
1348        // A non-normal density in the plane: f(x, y) = exp(−|x| − y²/2) (a Laplace times a normal).
1349        let mut h = MultivariateRatioUniforms::new(|x: &[f64]| (-x[0].abs() - 0.5 * x[1] * x[1]).exp(), &[0.0, 0.0]).unwrap();
1350        let s = h.rvs(n, &mut rng);
1351        assert!(ks(s.iter().map(|x| x[0]).collect(), |t| if t < 0.0 { 0.5 * t.exp() } else { 1.0 - 0.5 * (-t).exp() }) < 0.009);
1352        assert!(ks(s.iter().map(|x| x[1]).collect(), normal_cdf) < 0.009);
1353        assert!(MultivariateRatioUniforms::new(|_: &[f64]| 0.0, &[0.0]).is_err());
1354        assert!(MultivariateRatioUniforms::with_bounds(|_: &[f64]| 1.0, &[0.0], vec![1.0], vec![0.0]).is_err());
1355    }
1356}