Skip to main content

reserving_kernels/
bootstrap_odp.rs

1//! Over-Dispersed Poisson (ODP) GLM and residual bootstrap reserving kernel.
2//!
3//! Implements the classical ODP reserving and bootstrap framework from:
4//!
5//! * England & Verrall (1999), *Analytic and Bootstrap Estimates of Prediction
6//!   Errors in Claims Reserving*, Insurance: Mathematics and Economics,
7//!   Vol. 25, No. 3, pp. 281–293.
8//! * England & Verrall (2002), *Stochastic Claims Reserving in General
9//!   Insurance*, British Actuarial Journal, Vol. 8, No. 3, pp. 443–518.
10//! * Shapland (2016), *Using the ODP Bootstrap Model: A Practitioner's Guide*,
11//!   CAS Monograph No. 4.
12//!
13//! ## Model Specification
14//!
15//! For incremental payments `q_{i,j}` with `E[q_{i,j}] = μ_{i,j}` and
16//! `Var(q_{i,j}) = φ · μ_{i,j}`, the log-linear ODP GLM
17//! `log(μ_{i,j}) = c + α_i + β_j` produces fitted expectations identical to
18//! volume-weighted chain ladder via backwards recursion from the observed
19//! latest diagonal.
20//!
21//! Two mutually exclusive residual adjustments are supported:
22//!
23//! * [`ResidualAdjustment::DegreesOfFreedom`] — England & Verrall (1999, 2002)
24//!   global degrees-of-freedom scaling `r_adj = sqrt(N / (N - p)) * r`.
25//! * [`ResidualAdjustment::HatMatrixLeverage`] — Shapland (2016, CAS Monograph
26//!   4, §3.4) leverage scaling `r_H = r / sqrt(1 - h_{ii})` computed from the
27//!   exact GLM hat matrix `H = W^{1/2} X (X^T W X)^{-1} X^T W^{1/2}`, excluding
28//!   structurally saturated corner cells (`1 - h_{ii} ≈ 0`).
29//!
30//! Process variance in future cells is sampled using either a moment-matched
31//! Gamma distribution (`shape = μ* / φ`, `scale = φ`) or a scaled
32//! Over-Dispersed Poisson (`φ · Poisson(μ* / φ)`), driven by a deterministic
33//! SplitMix64-seeded Xoshiro256** PRNG with a 256-strip Ziggurat normal sampler.
34//! Because both Gamma and scaled Poisson are exact additive families under
35//! common dispersion `φ`, per-origin future reserves are sampled directly in
36//! `O(n)` per iteration while preserving exact distributional equivalence
37//! (including Shapland reflection for negative pseudo-increments).
38
39use std::f64::consts::TAU;
40
41use crate::ldf::{cdfs_from_ldfs, volume_weighted_ldfs};
42use crate::linalg::{invert_spd, solve_lower_into};
43use crate::reserve_distribution::{ReserveDistributionSummary, summarize_with_scratch};
44use crate::triangle::{cumulative_to_incremental, latest_diagonal};
45use crate::types::TriangleView;
46use crate::validate::{
47    MonotonicityPolicy, ValidationError, validate_monotone_cumulative, validate_tail,
48    validate_triangle,
49};
50
51// Re-export the crate's Cholesky helper for `crate::dependence`.
52pub(crate) use crate::linalg::cholesky_lower;
53
54// ===========================================================================
55// Public Configuration & Result Types
56// ===========================================================================
57
58/// Compact bootstrap configuration for the legacy [`bootstrap`] entry point.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
60pub struct BootstrapConfig {
61    /// Number of bootstrap iterations.
62    pub iterations: usize,
63    /// Deterministic seed for reproducible resampling.
64    pub seed: u64,
65}
66
67impl Default for BootstrapConfig {
68    fn default() -> Self {
69        Self {
70            iterations: 1000,
71            seed: 0xC0DE5EED,
72        }
73    }
74}
75
76/// Residual degrees-of-freedom / leverage adjustment convention.
77///
78/// The two conventions are mutually exclusive (Shapland 2016, §3.4): do not
79/// apply both simultaneously.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
81pub enum ResidualAdjustment {
82    /// England & Verrall (1999, 2002): multiply Pearson residuals by
83    /// `sqrt(N / (N - p))` over all `N` active observed cells.
84    #[default]
85    DegreesOfFreedom,
86    /// Shapland (2016, CAS Monograph 4, §3.4): divide non-saturated Pearson
87    /// residuals by `sqrt(1 - h_{ii})` and exclude structurally saturated
88    /// corner cells (`1 - h_{ii} <= 1e-10`) from the resampling pool.
89    HatMatrixLeverage,
90}
91
92/// Future incremental process-variance distribution for ODP bootstrap draws.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
94pub enum ProcessDistribution {
95    /// Moment-matched Gamma: `Gamma(shape = μ* / φ, scale = φ)` with mean `μ*`
96    /// and variance `φ · μ*` (England & Verrall 2002; Shapland 2016 §3.5).
97    #[default]
98    Gamma,
99    /// Scaled Poisson: `φ · Poisson(μ* / φ)` with mean `μ*` and variance `φ · μ*`.
100    OverDispersedPoisson,
101    /// Omit process variance (parameter estimation uncertainty only).
102    None,
103}
104
105/// Full configuration for [`bootstrap_odp`].
106#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
107pub struct OdpBootstrapOptions {
108    /// Number of bootstrap iterations.
109    pub iterations: usize,
110    /// Deterministic PRNG seed.
111    pub seed: u64,
112    /// Residual scaling convention (degrees of freedom vs. hat-matrix leverage).
113    pub residual_adjustment: ResidualAdjustment,
114    /// Process-variance distribution for future cells.
115    pub process_distribution: ProcessDistribution,
116    /// Whether to center the eligible adjusted residual pool to zero mean
117    /// before resampling (Shapland 2016, §3.4.3).
118    pub center_residuals: bool,
119    /// Monotonicity policy for triangle validation.
120    pub monotonicity_policy: MonotonicityPolicy,
121}
122
123impl Default for OdpBootstrapOptions {
124    fn default() -> Self {
125        Self::england_verrall(1000, 42069)
126    }
127}
128
129impl OdpBootstrapOptions {
130    /// Classic England & Verrall (1999, 2002) specification: global
131    /// `sqrt(N / (N - p))` residual scaling, Gamma process variance, uncentered.
132    pub const fn england_verrall(iterations: usize, seed: u64) -> Self {
133        Self {
134            iterations,
135            seed,
136            residual_adjustment: ResidualAdjustment::DegreesOfFreedom,
137            process_distribution: ProcessDistribution::Gamma,
138            center_residuals: false,
139            monotonicity_policy: MonotonicityPolicy::Strict,
140        }
141    }
142
143    /// Shapland (2016, CAS Monograph 4) practitioner specification: exact
144    /// hat-matrix leverage `1 / sqrt(1 - h_{ii})`, centered eligible pool,
145    /// Gamma process variance.
146    pub const fn shapland(iterations: usize, seed: u64) -> Self {
147        Self {
148            iterations,
149            seed,
150            residual_adjustment: ResidualAdjustment::HatMatrixLeverage,
151            process_distribution: ProcessDistribution::Gamma,
152            center_residuals: true,
153            monotonicity_policy: MonotonicityPolicy::Strict,
154        }
155    }
156
157    /// Set the number of bootstrap iterations.
158    pub const fn with_iterations(mut self, iterations: usize) -> Self {
159        self.iterations = iterations;
160        self
161    }
162
163    /// Set the deterministic PRNG seed.
164    pub const fn with_seed(mut self, seed: u64) -> Self {
165        self.seed = seed;
166        self
167    }
168
169    /// Set the residual adjustment convention (`DegreesOfFreedom` vs. `HatMatrixLeverage`).
170    pub const fn with_residual_adjustment(mut self, adjustment: ResidualAdjustment) -> Self {
171        self.residual_adjustment = adjustment;
172        self
173    }
174
175    /// Set the future process-variance distribution (`Gamma`, `OverDispersedPoisson`, or `None`).
176    pub const fn with_process_distribution(mut self, dist: ProcessDistribution) -> Self {
177        self.process_distribution = dist;
178        self
179    }
180
181    /// Enable or disable centering the eligible adjusted residual pool before resampling.
182    pub const fn with_centered_residuals(mut self, center: bool) -> Self {
183        self.center_residuals = center;
184        self
185    }
186
187    /// Set the triangle monotonicity policy.
188    pub const fn with_policy(mut self, policy: MonotonicityPolicy) -> Self {
189        self.monotonicity_policy = policy;
190        self
191    }
192}
193
194/// Bootstrap reserve summary shared with the generic reserve-distribution layer.
195pub type BootstrapSummary = ReserveDistributionSummary;
196
197/// Compact bootstrap output returned by [`bootstrap`].
198#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
199pub struct BootstrapResult {
200    /// Original chain-ladder / ODP total reserve.
201    pub base_total_reserve: f64,
202    /// Simulated reserve totals by iteration.
203    pub simulated_totals: Vec<f64>,
204    /// Summary percentiles and moments.
205    pub summary: BootstrapSummary,
206}
207
208/// Cell-level residual and hat-matrix leverage record from [`fit_odp`].
209#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
210pub struct OdpCellResidual {
211    /// Origin row index.
212    pub origin: usize,
213    /// Development column index.
214    pub dev: usize,
215    /// Observed incremental payment `q_{i,j}`.
216    pub observed_incremental: f64,
217    /// ODP GLM / chain-ladder fitted incremental expectation `μ_{i,j}`.
218    pub fitted_incremental: f64,
219    /// Unscaled Pearson residual `(q_{i,j} - μ_{i,j}) / sqrt(μ_{i,j})`.
220    pub raw_pearson_residual: f64,
221    /// Diagonal entry `h_{ii}` of the GLM hat matrix `H`.
222    pub leverage: f64,
223    /// `true` when `1 - h_{ii} <= 1e-10` (structurally saturated corner cell).
224    pub saturated: bool,
225}
226
227/// Immutable ODP GLM fit, dispersion, leverages, and analytic prediction errors.
228#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
229pub struct OdpFit {
230    /// Number of origin rows.
231    pub n_origins: usize,
232    /// Number of development columns.
233    pub n_devs: usize,
234    /// Volume-weighted chain-ladder LDFs (length `n - 1`).
235    pub ldfs: Vec<f64>,
236    /// Multiplicative tail factor (`>= 1.0`).
237    pub tail: f64,
238    /// Full `n × n` fitted cumulative grid (row-major; observed region by
239    /// backward recursion, future region by chain-ladder projection).
240    pub fitted_cumulative: Vec<f64>,
241    /// Full `n × n` fitted incremental grid (row-major).
242    pub fitted_incremental: Vec<f64>,
243    /// Observed `n × n` incremental grid (`NaN` in unobserved lower-right).
244    pub observed_incremental: Vec<f64>,
245    /// Residual and leverage diagnostics for every active observed cell.
246    pub residuals: Vec<OdpCellResidual>,
247    /// Count of active observed cells entering the ODP fit (`N`).
248    pub n_observed: usize,
249    /// Effective parameter rank of the ODP design matrix (`p = 2n - 1` for full triangles).
250    pub rank: usize,
251    /// Residual degrees of freedom (`N - p`).
252    pub degrees_of_freedom: usize,
253    /// Pearson dispersion parameter `φ = sum(r^2) / (N - p)`.
254    pub dispersion: f64,
255    /// Point-estimate reserves by origin (including tail when `tail > 1`).
256    pub origin_reserves: Vec<f64>,
257    /// Aggregate point-estimate reserve.
258    pub total_reserve: f64,
259    /// Analytic ODP process standard error by origin (pre-tail).
260    pub analytic_origin_process_se: Vec<f64>,
261    /// Analytic ODP parameter estimation standard error by origin (pre-tail).
262    pub analytic_origin_param_se: Vec<f64>,
263    /// Analytic ODP total prediction error by origin (England & Verrall 1999, Table 2).
264    pub analytic_origin_prediction_error: Vec<f64>,
265    /// Analytic ODP aggregate process standard error `sqrt(φ · R)`.
266    pub analytic_total_process_se: f64,
267    /// Analytic ODP aggregate parameter estimation standard error.
268    pub analytic_total_param_se: f64,
269    /// Analytic ODP aggregate prediction error (England & Verrall 1999, 2002).
270    pub analytic_total_prediction_error: f64,
271}
272
273/// Full ODP bootstrap output with fit diagnostics, per-origin distributions,
274/// and explicit failure accounting.
275#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
276pub struct OdpBootstrapResult {
277    /// Underlying ODP GLM fit and analytic prediction errors.
278    pub fit: OdpFit,
279    /// Options used to generate this simulation.
280    pub options: OdpBootstrapOptions,
281    /// Base chain-ladder / ODP total reserve.
282    pub base_total_reserve: f64,
283    /// Simulated aggregate reserves for successful iterations.
284    pub simulated_totals: Vec<f64>,
285    /// Simulated reserves per origin: `simulated_by_origin[origin][iter]`.
286    pub simulated_by_origin: Vec<Vec<f64>>,
287    /// Distribution summary for each origin year.
288    pub origin_summaries: Vec<ReserveDistributionSummary>,
289    /// Distribution summary for the aggregate portfolio reserve.
290    pub summary: ReserveDistributionSummary,
291    /// Number of bootstrap draws rejected due to degenerate pseudo-triangles
292    /// (non-positive column sums or non-finite refits). Never silently clipped.
293    pub failed_iterations: usize,
294    /// Arithmetic mean of the adjusted residual pool prior to optional centering.
295    pub residual_pool_mean_before_centering: f64,
296}
297
298// ===========================================================================
299// 256-Strip Ziggurat Tables for Standard Normal N(0, 1)
300// (Marsaglia & Tsang 2000; Doornik 2005; exact equal-area strips to ~2e-15)
301// ===========================================================================
302
303#[allow(clippy::excessive_precision)]
304const ZIG_NORM_R: f64 = 3.65415288536100924e+00;
305#[allow(clippy::excessive_precision)]
306const ZIG_NORM_INV_R: f64 = 2.73661237329758222e-01;
307
308/// Pre-scaled strip half-widths `x[i] * 2^-51` for exact symmetric 52-bit shifts.
309#[allow(clippy::excessive_precision)]
310#[rustfmt::skip]
311const ZIG_NORM_W: [f64; 256] = [
312    1.73672541216026340e-15, 1.62276986753129703e-15, 1.53178727416111455e-15, 1.47448486035975978e-15,
313    1.43199898696613284e-15, 1.39794366727752419e-15, 1.36936068351285195e-15, 1.34463009250111733e-15,
314    1.32276557701953283e-15, 1.30312066346899871e-15, 1.28524793190961128e-15, 1.26882448142550120e-15,
315    1.25360939266025688e-15, 1.23941797891632531e-15, 1.22610544174505652e-15, 1.21355608186668990e-15,
316    1.20167593925438206e-15, 1.19038762992828923e-15, 1.17962663529558048e-15, 1.16933857869109619e-15,
317    1.15947718914491932e-15, 1.15000275378397944e-15, 1.14088092425827821e-15, 1.13208178401648483e-15,
318    1.12357911071108373e-15, 1.11534978658531569e-15, 1.10737332249357560e-15, 1.09963147017856302e-15,
319    1.09210790381495648e-15, 1.08478795644034286e-15, 1.07765840026681103e-15, 1.07070726236329957e-15,
320    1.06392366906768027e-15, 1.05729771390098922e-15, 1.05082034483551986e-15, 1.04448326760004725e-15,
321    1.03827886235154011e-15, 1.03220011154864585e-15, 1.02624053726135694e-15, 1.02039414646831276e-15,
322    1.01465538314670881e-15, 1.00901908616374609e-15, 1.00348045214361829e-15, 9.98035002618364886e-16,
323    9.92678554880797846e-16, 9.87407196048067304e-16, 9.82217259919054503e-16, 9.77105306270721081e-16,
324    9.72068102290162982e-16, 9.67102605882305622e-16, 9.62205950629484033e-16, 9.57375432209745160e-16,
325    9.52608496106628067e-16, 9.47902726465174022e-16, 9.43255835967670851e-16, 9.38665656618666373e-16,
326    9.34130131342526710e-16, 9.29647306308641870e-16, 9.25215323909569530e-16, 9.20832416326230957e-16,
327    9.16496899621913729e-16, 9.12207168313484807e-16, 9.07961690374007196e-16, 9.03759002626012147e-16,
328    8.99597706489110330e-16, 8.95476464049507169e-16, 8.91393994422409008e-16, 8.87349070381313749e-16,
329    8.83340515230841091e-16, 8.79367199902104669e-16, 8.75428040251717888e-16, 8.71521994547370097e-16,
330    8.67648061124558555e-16, 8.63805276200526185e-16, 8.59992711832766756e-16, 8.56209474010623629e-16,
331    8.52454700869559916e-16, 8.48727561018615789e-16, 8.45027251972409973e-16, 8.41352998679803121e-16,
332    8.37704052142022459e-16, 8.34079688113663175e-16, 8.30479205880537668e-16, 8.26901927108847298e-16,
333    8.23347194760605338e-16, 8.19814372070653583e-16, 8.16302841580988043e-16, 8.12812004228450472e-16,
334    8.09341278482150286e-16, 8.05890099527265881e-16, 8.02457918492126209e-16, 7.99044201715713301e-16,
335    7.95648430052936913e-16, 7.92270098215227480e-16, 7.88908714144175817e-16, 7.85563798416108701e-16,
336    7.82234883675641479e-16, 7.78921514096385636e-16, 7.75623244867117738e-16, 7.72339641701830249e-16,
337    7.69070280372192306e-16, 7.65814746261049029e-16, 7.62572633935675970e-16, 7.59343546739589345e-16,
338    7.56127096401792568e-16, 7.52922902662406231e-16, 7.49730592913698329e-16, 7.46549801855589297e-16,
339    7.43380171164765187e-16, 7.40221349176580262e-16, 7.37072990578983395e-16, 7.33934756117740870e-16,
340    7.30806312312274682e-16, 7.27687331181469666e-16, 7.24577489978839093e-16, 7.21476470936471065e-16,
341    7.18383961017206680e-16, 7.15299651674530694e-16, 7.12223238619678278e-16, 7.09154421595487736e-16,
342    7.06092904156548511e-16, 7.03038393455215375e-16, 6.99990600033076791e-16, 6.96949237617483333e-16,
343    6.93914022922757200e-16, 6.90884675455717296e-16, 6.87860917325166761e-16, 6.84842473055004125e-16,
344    6.81829069400625700e-16, 6.78820435168298322e-16, 6.75816301037190453e-16, 6.72816399383753509e-16,
345    6.69820464108156184e-16, 6.66828230462474985e-16, 6.63839434880350960e-16, 6.60853814807826269e-16,
346    6.57871108535074527e-16, 6.54891055028741935e-16, 6.51913393764616367e-16, 6.48937864560340148e-16,
347    6.45964207407883707e-16, 6.42992162305490100e-16, 6.40021469088802966e-16, 6.37051867260881988e-16,
348    6.34083095820806494e-16, 6.31114893090560917e-16, 6.28146996539890023e-16, 6.25179142608800574e-16,
349    6.22211066527379383e-16, 6.19242502132585295e-16, 6.16273181681660223e-16, 6.13302835661791692e-16,
350    6.10331192595644535e-16, 6.07357978842361158e-16, 6.04382918393613093e-16, 6.01405732664266896e-16,
351    5.98426140277203304e-16, 5.95443856841806472e-16, 5.92458594725613986e-16, 5.89470062818587669e-16,
352    5.86477966289437117e-16, 5.83482006333389797e-16, 5.80481879910769157e-16, 5.77477279475697074e-16,
353    5.74467892694196679e-16, 5.71453402150920989e-16, 5.68433485043682002e-16, 5.65407812864896635e-16,
354    5.62376051069004938e-16, 5.59337858724846799e-16, 5.56292888151909609e-16, 5.53240784539278853e-16,
355    5.50181185546034217e-16, 5.47113720881736705e-16, 5.44038011865547399e-16, 5.40953670962399925e-16,
356    5.37860301294524071e-16, 5.34757496126473645e-16, 5.31644838321662347e-16, 5.28521899768238889e-16,
357    5.25388240771946115e-16, 5.22243409413404864e-16, 5.19086940867035028e-16, 5.15918356678574433e-16,
358    5.12737163997880354e-16, 5.09542854763389919e-16, 5.06334904834272739e-16, 5.03112773065932658e-16,
359    4.99875900324091668e-16, 4.96623708432218620e-16, 4.93355599046542278e-16, 4.90070952452300263e-16,
360    4.86769126274221756e-16, 4.83449454093501688e-16, 4.80111243962702438e-16, 4.76753776809086152e-16,
361    4.73376304715833357e-16, 4.69978049069420384e-16, 4.66558198560088404e-16, 4.63115907020817356e-16,
362    4.59650291088495059e-16, 4.56160427669004794e-16, 4.52645351185714954e-16, 4.49104050588288485e-16,
363    4.45535466095792352e-16, 4.41938485644707683e-16, 4.38311941008546798e-16, 4.34654603551288730e-16,
364    4.30965179571630542e-16, 4.27242305188998743e-16, 4.23484540715208218e-16, 4.19690364447408414e-16,
365    4.15858165808281775e-16, 4.11986237748075556e-16, 4.08072768309605617e-16, 4.04115831241434458e-16,
366    4.00113375525468080e-16, 3.96063213662565057e-16, 3.91963008532578115e-16, 3.87810258612503849e-16,
367    3.83602281296774122e-16, 3.79336194015496967e-16, 3.75008892787479409e-16, 3.70617027772362203e-16,
368    3.66156975296536877e-16, 3.61624805715984870e-16, 3.57016246339536469e-16, 3.52326638460021892e-16,
369    3.47550887317299159e-16, 3.42683403531195187e-16, 3.37718034173533949e-16, 3.32647981168418826e-16,
370    3.27465704079399184e-16, 3.22162803505500827e-16, 3.16729880185819877e-16, 3.11156363389217596e-16,
371    3.05430300071926326e-16, 2.99538093367823101e-16, 2.93464174847290854e-16, 2.87190589041141424e-16,
372    2.80696460024850205e-16, 2.73957296851426679e-16, 2.66944074736485216e-16, 2.59621997725283540e-16,
373    2.51948798292744913e-16, 2.43872345574290521e-16, 2.35327189140461874e-16, 2.26229403922184264e-16,
374    2.16468605768957550e-16, 2.05895006284824550e-16, 1.94297201531359847e-16, 1.81361208101194749e-16,
375    1.66587336315867911e-16, 1.49097409624961075e-16, 1.27087048348114564e-16, 9.55866035145697372e-17,
376];
377
378/// Inner acceptance thresholds `x[i + 1]` for strip `i` (`x[256] = 0.0`).
379#[allow(clippy::excessive_precision)]
380#[rustfmt::skip]
381const ZIG_NORM_X_INNER: [f64; 256] = [
382    3.65415288536100924e+00, 3.44927829856143164e+00, 3.32024473383982599e+00, 3.22457505204780182e+00,
383    3.14788928951800129e+00, 3.08352613200214387e+00, 3.02783779176959378e+00, 2.97860327988184359e+00,
384    2.93436686720888806e+00, 2.89412105361341299e+00, 2.85713873087322501e+00, 2.82287739682644334e+00,
385    2.79092117400192796e+00, 2.76094400527998696e+00, 2.73268535904401189e+00, 2.70593365612306291e+00,
386    2.68051464328574562e+00, 2.65628303757674411e+00, 2.63311639363158312e+00, 2.61091051848882438e+00,
387    2.58957598670828704e+00, 2.56903545268184441e+00, 2.54922155032478370e+00, 2.53007523215985497e+00,
388    2.51154444162669499e+00, 2.49358304127104757e+00, 2.47614993967052355e+00, 2.45920837433470574e+00,
389    2.44272531820036498e+00, 2.42667098493714750e+00, 2.41101841390111993e+00, 2.39574311978192789e+00,
390    2.38082279517208617e+00, 2.36623705671729168e+00, 2.35196722737914543e+00, 2.33799614879652928e+00,
391    2.32430801887113292e+00, 2.31088825060137237e+00, 2.29772334890286434e+00, 2.28480080272449282e+00,
392    2.27210899022838264e+00, 2.25963709517378808e+00, 2.24737503294739005e+00, 2.23531338492992182e+00,
393    2.22344334009251110e+00, 2.21175664288416174e+00, 2.20024554661127691e+00, 2.18890277162636160e+00,
394    2.17772146774029363e+00, 2.16669518035430908e+00, 2.15581781987673793e+00, 2.14508363404788938e+00,
395    2.13448718284601746e+00, 2.12402331568952407e+00, 2.11368715068665391e+00, 2.10347405571487789e+00,
396    2.09337963113879244e+00, 2.08339969399830505e+00, 2.07353026351874359e+00, 2.06376754781173277e+00,
397    2.05410793165065275e+00, 2.04454796521753224e+00, 2.03508435372961971e+00, 2.02571394786385506e+00,
398    2.01643373490620492e+00, 2.00724083056052960e+00, 1.99813247135842031e+00, 1.98910600761743894e+00,
399    1.98015889690047753e+00, 1.97128869793366013e+00, 1.96249306494436371e+00, 1.95376974238464762e+00,
400    1.94511656000867905e+00, 1.93653142827569535e+00, 1.92801233405266648e+00, 1.91955733659318883e+00,
401    1.91116456377125399e+00, 1.90283220855042989e+00, 1.89455852567070537e+00, 1.88634182853678345e+00,
402    1.87818048629299650e+00, 1.87007292107126744e+00, 1.86201760539967487e+00, 1.85401305976020270e+00,
403    1.84605785028518632e+00, 1.83815058658280739e+00, 1.83028991968275778e+00, 1.82247454009388643e+00,
404    1.81470317596628328e+00, 1.80697459135082172e+00, 1.79928758454972093e+00, 1.79164098655216342e+00,
405    1.78403365954944237e+00, 1.77646449552452368e+00, 1.76893241491126929e+00, 1.76143636531891112e+00,
406    1.75397532031767245e+00, 1.74654827828172321e+00, 1.73915426128591255e+00, 1.73179231405296408e+00,
407    1.72446150294804568e+00, 1.71716091501782397e+00, 1.70988965707130269e+00, 1.70264685479992406e+00,
408    1.69543165193456247e+00, 1.68824320943719641e+00, 1.68108070472517479e+00, 1.67394333092612602e+00,
409    1.66683029616166634e+00, 1.65974082285818336e+00, 1.65267414708305682e+00, 1.64562951790478329e+00,
410    1.63860619677554875e+00, 1.63160345693487452e+00, 1.62462058283303579e+00, 1.61765686957301646e+00,
411    1.61071162236983101e+00, 1.60378415602609548e+00, 1.59687379442278909e+00, 1.58997987002419161e+00,
412    1.58310172339603006e+00, 1.57623870273590727e+00, 1.56939016341512461e+00, 1.56255546753104557e+00,
413    1.55573398346917724e+00, 1.54892508547417429e+00, 1.54212815322900276e+00, 1.53534257144151498e+00,
414    1.52856772943771313e+00, 1.52180302076099894e+00, 1.51504784277671556e+00, 1.50830159628131244e+00,
415    1.50156368511546479e+00, 1.49483351578049461e+00, 1.48811049705744858e+00, 1.48139403962818839e+00,
416    1.47468355569785659e+00, 1.46797845861808085e+00, 1.46127816251027665e+00, 1.45458208188841143e+00,
417    1.44788963128057735e+00, 1.44120022484872523e+00, 1.43451327600589340e+00, 1.42782819703025732e+00,
418    1.42114439867531028e+00, 1.41446128977547247e+00, 1.40777827684640022e+00, 1.40109476367925234e+00,
419    1.39441015092814236e+00, 1.38772383568997748e+00, 1.38103521107585681e+00, 1.37434366577316758e+00,
420    1.36764858359747765e+00, 1.36094934303328441e+00, 1.35424531676263626e+00, 1.34753587118058848e+00,
421    1.34082036589640530e+00, 1.33409815321936143e+00, 1.32736857762792715e+00, 1.32063097522105766e+00,
422    1.31388467315022184e+00, 1.30712898903073249e+00, 1.30036323033083856e+00, 1.29358669373694912e+00,
423    1.28679866449324498e+00, 1.27999841571381934e+00, 1.27318520766535781e+00, 1.26635828701823083e+00,
424    1.25951688606371559e+00, 1.25266022189489856e+00, 1.24578749554862855e+00, 1.23889789110568871e+00,
425    1.23199057474613749e+00, 1.22506469375653237e+00, 1.21811937548548310e+00, 1.21115372624370066e+00,
426    1.20416683014438308e+00, 1.19715774787944307e+00, 1.19012551542669365e+00, 1.18306914268268848e+00,
427    1.17598761201545376e+00, 1.16887987673083482e+00, 1.16174485944561323e+00, 1.15458145035992943e+00,
428    1.14738850542085080e+00, 1.14016484436815313e+00, 1.13290924865253562e+00, 1.12562045921553522e+00,
429    1.11829717411934682e+00, 1.11093804601357782e+00, 1.10354167942464176e+00, 1.09610662785202351e+00,
430    1.08863139065398196e+00, 1.08111440970340600e+00, 1.07355406579243851e+00, 1.06594867476212474e+00,
431    1.05829648333067716e+00, 1.05059566459093201e+00, 1.04284431314415116e+00, 1.03504043983344318e+00,
432    1.02718196603564804e+00, 1.01926671746548658e+00, 1.01129241743999820e+00, 1.00325667954467534e+00,
433    9.95156999635093409e-01, 9.86990747099065091e-01, 9.78755155294227297e-01, 9.70447311064227103e-01,
434    9.62064143223043233e-01, 9.53602409881088686e-01, 9.45058684468168098e-01, 9.36429340286577871e-01,
435    9.27710533402002824e-01, 9.18898183649593303e-01, 9.09987953496721236e-01, 9.00975224461224689e-01,
436    8.91855070732944566e-01, 8.82622229585168672e-01, 8.73271068088864011e-01, 8.63795545553312061e-01,
437    8.54189171008167158e-01, 8.44444954909157275e-01, 8.34555354086385592e-01, 8.24512208752295694e-01,
438    8.14306670135218735e-01, 8.03929116989974824e-01, 7.93369058840627028e-01, 7.82615023307236868e-01,
439    7.71654424224571978e-01, 7.60473406430111964e-01, 7.49056662017819397e-01, 7.37387211434299639e-01,
440    7.25446140910003923e-01, 7.13212285190980122e-01, 7.00661841106819505e-01, 6.87767892795793090e-01,
441    6.74499822837298479e-01, 6.60822574244424588e-01, 6.46695714894998885e-01, 6.32072236386066355e-01,
442    6.16896990007756774e-01, 6.01104617755998327e-01, 5.84616766106385355e-01, 5.67338257053825123e-01,
443    5.49151702327171809e-01, 5.29909720661565165e-01, 5.09423329602099240e-01, 4.87443966139244012e-01,
444    4.63634336790890889e-01, 4.37518402207881185e-01, 4.08389134612001825e-01, 3.75121332878393110e-01,
445    3.35737519214440450e-01, 2.86174591792092481e-01, 2.15241895984913806e-01, 0.00000000000000000e+00,
446];
447
448/// Density values `f[i] = exp(-0.5 * x[i]^2)` for wedge checks (`f[256] = 1.0`).
449#[allow(clippy::excessive_precision)]
450#[rustfmt::skip]
451const ZIG_NORM_F: [f64; 257] = [
452    1.26028593049859559e-03, 1.26028593049859559e-03, 2.60907274610215883e-03, 4.03797259336302443e-03,
453    5.52240329925098895e-03, 7.05087547137321635e-03, 8.61658276939871945e-03, 1.02149714397014556e-02,
454    1.18427578579078704e-02, 1.34974506017398587e-02, 1.51770883079353023e-02, 1.68800831525431419e-02,
455    1.86051212757246155e-02, 2.03510962300444860e-02, 2.21170627073088294e-02, 2.39022033057958438e-02,
456    2.57058040085488548e-02, 2.75272356696030368e-02, 2.93659397581332651e-02, 3.12214171919201963e-02,
457    3.30932194585784670e-02, 3.49809414617160280e-02, 3.68842156885672290e-02, 3.88027074045260573e-02,
458    4.07361106559408701e-02, 4.26841449164743689e-02, 4.46465522512943802e-02, 4.66230949019302982e-02,
459    4.86135532158684519e-02, 5.06177238609476915e-02, 5.26354182767921064e-02, 5.46664613248888376e-02,
460    5.67106901062028185e-02, 5.87679529209336748e-02, 6.08381083495397740e-02, 6.29210244377580302e-02,
461    6.50165779712427588e-02, 6.71246538277883997e-02, 6.92451443970066721e-02, 7.13779490588902776e-02,
462    7.35229737139811712e-02, 7.56801303589269697e-02, 7.78493367020959420e-02, 8.00305158146629447e-02,
463    8.22235958132027517e-02, 8.44285095703532634e-02, 8.66451944505578497e-02, 8.88735920682756780e-02,
464    9.11136480663735232e-02, 9.33653119126907488e-02, 9.56285367130087077e-02, 9.79032790388621732e-02,
465    1.00189498768809698e-01, 1.02487158941934969e-01, 1.04796225622486777e-01, 1.07116667774683511e-01,
466    1.09448457146811506e-01, 1.11791568163837868e-01, 1.14145977827838210e-01, 1.16511665625610661e-01,
467    1.18888613442909824e-01, 1.21276805484790057e-01, 1.23676228201596392e-01, 1.26086870220185693e-01,
468    1.28508722279999349e-01, 1.30941777173644136e-01, 1.33386029691668934e-01, 1.35841476571253533e-01,
469    1.38308116448550511e-01, 1.40785949814444478e-01, 1.43274978973513212e-01, 1.45775208005993834e-01,
470    1.48286642732574331e-01, 1.50809290681845481e-01, 1.53343161060262634e-01, 1.55888264724479003e-01,
471    1.58444614155924091e-01, 1.61012223437510871e-01, 1.63591108232365501e-01, 1.66181285764481851e-01,
472    1.68782774801211288e-01, 1.71395595637505727e-01, 1.74019770081838526e-01, 1.76655321443734747e-01,
473    1.79302274522847416e-01, 1.81960655599522320e-01, 1.84630492426799020e-01, 1.87311814223800027e-01,
474    1.90004651670464736e-01, 1.92709036903588898e-01, 1.95425003514134027e-01, 1.98152586545774861e-01,
475    2.00891822494656314e-01, 2.03642749310334603e-01, 2.06405406397880464e-01, 2.09179834621124744e-01,
476    2.11966076307029905e-01, 2.14764175251173306e-01, 2.17574176724330853e-01, 2.20396127480151666e-01,
477    2.23230075763917152e-01, 2.26076071322379890e-01, 2.28934165414679924e-01, 2.31804410824338281e-01,
478    2.34686861872329566e-01, 2.37581574431237619e-01, 2.40488605940500061e-01, 2.43408015422749785e-01,
479    2.46339863501263301e-01, 2.49284212418527912e-01, 2.52241126055941567e-01, 2.55210669954661351e-01,
480    2.58192911337618569e-01, 2.61187919132720492e-01, 2.64195763997260413e-01, 2.67216518343560749e-01,
481    2.70250256365874852e-01, 2.73297054068576517e-01, 2.76356989295667710e-01, 2.79430141761637385e-01,
482    2.82516593083707079e-01, 2.85616426815501201e-01, 2.88729728482182368e-01, 2.91856585617094655e-01,
483    2.94997087799961311e-01, 2.98151326696684982e-01, 3.01319396100802550e-01, 3.04501391976649438e-01,
484    3.07697412504291501e-01, 3.10907558126285954e-01, 3.14131931596336678e-01, 3.17370638029913055e-01,
485    3.20623784956904856e-01, 3.23891482376390594e-01, 3.27173842813600846e-01, 3.30470981379162920e-01,
486    3.33783015830717733e-01, 3.37110066637005379e-01, 3.40452257044521145e-01, 3.43809713146850049e-01,
487    3.47182563956792922e-01, 3.50570941481405329e-01, 3.53974980800076000e-01, 3.57394820145779668e-01,
488    3.60830600989647143e-01, 3.64282468129003112e-01, 3.67750569779031644e-01, 3.71235057668238555e-01,
489    3.74736087137890195e-01, 3.78253817245618240e-01, 3.81788410873392714e-01, 3.85340034840076340e-01,
490    3.88908860018787828e-01, 3.92495061459314676e-01, 3.96098818515831508e-01, 3.99720314980196334e-01,
491    4.03359739221113622e-01, 4.07017284329472484e-01, 4.10693148270187325e-01, 4.14387534040890237e-01,
492    4.18100649837847282e-01, 4.21832709229495006e-01, 4.25583931338021082e-01, 4.29354541029440595e-01,
493    4.33144769112651373e-01, 4.36954852547984607e-01, 4.40785034665803044e-01, 4.44635565395738397e-01,
494    4.48506701507202010e-01, 4.52398706861847522e-01, 4.56311852678715379e-01, 4.60246417812841757e-01,
495    4.64202689048173189e-01, 4.68180961405692431e-01, 4.72181538467728978e-01, 4.76204732719504698e-01,
496    4.80250865909045588e-01, 4.84320269426682048e-01, 4.88413284705456752e-01, 4.92530263643867261e-01,
497    4.96671569052488437e-01, 5.00837575126147461e-01, 5.05028667943466902e-01, 5.09245245995746609e-01,
498    5.13487720747325516e-01, 5.17756517229754909e-01, 5.22052074672320399e-01, 5.26374847171682925e-01,
499    5.30725304403660503e-01, 5.35103932380456060e-01, 5.39511234256950467e-01, 5.43947731190024597e-01,
500    5.48413963255264147e-01, 5.52910490425830625e-01, 5.57437893618764280e-01, 5.61996775814522675e-01,
501    5.66587763256162669e-01, 5.71211506735251451e-01, 5.75868682972351942e-01, 5.80559996100789122e-01,
502    5.85286179263369566e-01, 5.90047996332824121e-01, 5.94846243767985561e-01, 5.99681752619123487e-01,
503    6.04555390697466000e-01, 6.09468064925771658e-01, 6.14420723888912002e-01, 6.19414360605832437e-01,
504    6.24450015547024617e-01, 6.29528779924834803e-01, 6.34651799287621721e-01, 6.39820277453054698e-01,
505    6.45035480820820406e-01, 6.50298743110814814e-01, 6.55611470579695377e-01, 6.60975147776661220e-01,
506    6.66391343908748102e-01, 6.71861719897079990e-01, 6.77388036218771306e-01, 6.82972161644992526e-01,
507    6.88616083004669477e-01, 6.94321916126114380e-01, 7.00091918136509284e-01, 7.05928501332751868e-01,
508    7.11834248878245979e-01, 7.17811932630719518e-01, 7.23864533468627669e-01, 7.29995264561473678e-01,
509    7.36207598126860097e-01, 7.42505296340148502e-01, 7.48892447219154267e-01, 7.55373506507093451e-01,
510    7.61953346836792611e-01, 7.68637315798483489e-01, 7.75431304981184399e-01, 7.82341832654799618e-01,
511    7.89376143566021704e-01, 7.96542330422956080e-01, 8.03849483170961387e-01, 8.11307874312653277e-01,
512    8.18929191603699369e-01, 8.26726833946218376e-01, 8.34716292986880326e-01, 8.42915653112200958e-01,
513    8.51346258458674621e-01, 8.60033621196328091e-01, 8.69008688036853494e-01, 8.78309655808913736e-01,
514    8.87984660755829602e-01, 8.98095921898339533e-01, 9.08726440052126772e-01, 9.19991505039342683e-01,
515    9.32060075959225798e-01, 9.45198953442294543e-01, 9.59879091800100892e-01, 9.77101701267664491e-01,
516    1.00000000000000000e+00,
517];
518
519// ===========================================================================
520// Deterministic PRNG & Exact Samplers (SplitMix64 + Xoshiro256** + Ziggurat)
521// ===========================================================================
522
523/// Deterministic SplitMix64-seeded Xoshiro256** PRNG with exact Ziggurat
524/// Normal, Marsaglia–Tsang Gamma, and Knuth/Hörmann PTRD Poisson samplers.
525/// Shared with [`crate::dependence`], [`crate::hertig`], [`crate::micro_reserving`],
526/// and [`crate::subannual::odp_asymmetric`].
527#[derive(Debug, Clone)]
528pub(crate) struct DeterministicRng {
529    s: [u64; 4],
530}
531
532impl DeterministicRng {
533    pub(crate) fn from_seed(seed: u64) -> Self {
534        let mut sm = seed;
535        let mut next_sm = || {
536            sm = sm.wrapping_add(0x9e3779b97f4a7c15);
537            let mut z = sm;
538            z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
539            z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
540            z ^ (z >> 31)
541        };
542        let mut s = [next_sm(), next_sm(), next_sm(), next_sm()];
543        if s == [0; 4] {
544            s[0] = 1;
545        }
546        Self { s }
547    }
548
549    #[inline]
550    pub(crate) fn next_u64(&mut self) -> u64 {
551        let result = self.s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
552        let t = self.s[1] << 17;
553        self.s[2] ^= self.s[0];
554        self.s[3] ^= self.s[1];
555        self.s[1] ^= self.s[2];
556        self.s[0] ^= self.s[3];
557        self.s[2] ^= t;
558        self.s[3] = self.s[3].rotate_left(45);
559        result
560    }
561
562    /// Uniform float strictly in `(0, 1)` (53-bit mantissa precision).
563    #[inline]
564    pub(crate) fn next_open01(&mut self) -> f64 {
565        ((self.next_u64() >> 11) as f64 + 0.5) * (1.0 / 9_007_199_254_740_992.0)
566    }
567
568    /// Unbiased uniform index in `0..upper` via Lemire's nearly-divisionless multiply-high.
569    #[inline]
570    pub(crate) fn next_index(&mut self, upper: usize) -> usize {
571        debug_assert!(upper > 0);
572        let bound = upper as u64;
573        let mut prod = (self.next_u64() as u128) * (bound as u128);
574        let mut low = prod as u64;
575        if low < bound {
576            let threshold = bound.wrapping_neg() % bound;
577            while low < threshold {
578                prod = (self.next_u64() as u128) * (bound as u128);
579                low = prod as u64;
580            }
581        }
582        (prod >> 64) as usize
583    }
584
585    /// Standard normal `N(0, 1)` via 256-strip Ziggurat (98.51% branch-light fast
586    /// path requiring 1 `next_u64` and zero transcendental functions).
587    #[inline]
588    pub(crate) fn next_standard_normal(&mut self) -> f64 {
589        loop {
590            let bits = self.next_u64();
591            let i = (bits & 0xFF) as usize;
592            // Signed 52-bit integer in [-2^51, 2^51 - 1] (disjoint from bits 0..8);
593            // adding 0.5 is exact in IEEE-754 f64 and symmetric around 0.0.
594            let j = ((bits as i64) >> 12) as f64 + 0.5;
595            let x = j * ZIG_NORM_W[i];
596            if x.abs() < ZIG_NORM_X_INNER[i] {
597                return x;
598            }
599            if i == 0 {
600                return self.sample_normal_tail(j >= 0.0);
601            }
602            let u = self.next_open01();
603            if ZIG_NORM_F[i] + u * (ZIG_NORM_F[i + 1] - ZIG_NORM_F[i]) < (-0.5 * x * x).exp() {
604                return x;
605            }
606        }
607    }
608
609    #[cold]
610    fn sample_normal_tail(&mut self, positive: bool) -> f64 {
611        // Marsaglia (1964) exact exponential tail for |Z| >= ZIG_NORM_R.
612        loop {
613            let tx = -self.next_open01().ln() * ZIG_NORM_INV_R;
614            let ty = -self.next_open01().ln();
615            if ty + ty >= tx * tx {
616                let mag = ZIG_NORM_R + tx;
617                return if positive { mag } else { -mag };
618            }
619        }
620    }
621
622    /// Exact Gamma(shape, scale) via Marsaglia & Tsang (2000).
623    #[inline]
624    pub(crate) fn sample_gamma(&mut self, shape: f64, scale: f64) -> f64 {
625        if !(shape > 0.0) || !(scale > 0.0) || !shape.is_finite() || !scale.is_finite() {
626            return 0.0;
627        }
628        if shape < 1.0 {
629            let g = self.sample_gamma_ge1(shape + 1.0);
630            let u = self.next_open01();
631            return g * u.powf(1.0 / shape) * scale;
632        }
633        self.sample_gamma_ge1(shape) * scale
634    }
635
636    #[inline]
637    fn sample_gamma_ge1(&mut self, shape: f64) -> f64 {
638        let d = shape - (1.0 / 3.0);
639        let c = (1.0 / 3.0) / d.sqrt();
640        loop {
641            let z = self.next_standard_normal();
642            let v_root = 1.0 + c * z;
643            if v_root <= 0.0 {
644                continue;
645            }
646            let v = v_root * v_root * v_root;
647            let u = self.next_open01();
648            let z2 = z * z;
649            if u < 1.0 - 0.0331 * (z2 * z2) {
650                return d * v;
651            }
652            if u.ln() < 0.5 * z2 + d * (1.0 - v + v.ln()) {
653                return d * v;
654            }
655        }
656    }
657
658    /// Exact Poisson(lambda) via Knuth (`lambda < 10`) and Hörmann PTRD (`lambda >= 10`).
659    pub(crate) fn sample_poisson(&mut self, lambda: f64) -> f64 {
660        if !(lambda > 0.0) || !lambda.is_finite() {
661            return 0.0;
662        }
663        if lambda < 10.0 {
664            let limit = (-lambda).exp();
665            let mut k = 0u64;
666            let mut p = 1.0;
667            loop {
668                k += 1;
669                p *= self.next_open01();
670                if p <= limit {
671                    return (k - 1) as f64;
672                }
673            }
674        }
675        // Hörmann (1993), Insurance: Mathematics and Economics 12(1), pp. 39–45.
676        // Exact for all lambda >= 10.
677        let s = lambda.sqrt();
678        let b = 0.931 + 2.53 * s;
679        let a = -0.059 + 0.02483 * b;
680        let inv_alpha = 1.1239 + 1.1328 / (b - 3.4);
681        let v_r = 0.9277 - 3.6224 / (b - 2.0);
682        let ln_lambda = lambda.ln();
683        loop {
684            let u = self.next_open01() - 0.5;
685            let v = self.next_open01();
686            let us = 0.5 - u.abs();
687            let k = ((2.0 * a / us + b) * u + lambda + 0.43).floor();
688            if us >= 0.07 && v <= v_r {
689                return k;
690            }
691            if k < 0.0 || (us < 0.013 && v > us) {
692                continue;
693            }
694            let lhs = (v * inv_alpha / (a / (us * us) + b)).ln();
695            let rhs = -lambda + k * ln_lambda - ln_gamma(k + 1.0);
696            if lhs <= rhs {
697                return k;
698            }
699        }
700    }
701}
702
703/// Branch-light batched unbiased index sampler with loop-invariant precomputed
704/// Lemire rejection threshold.
705///
706/// For `bound <= 1024` (triangles up to `45 × 45`), `fill_weighted_deltas`
707/// extracts 4 independent exact 16-bit Lemire indices per `next_u64()` with
708/// zero per-element refill branches and fuses the `pool[idx] * sqrt_mu[k]`
709/// product into a single pass. For larger pools (`bound <= u32::MAX`), it
710/// extracts 2 independent 32-bit Lemire indices per `next_u64()`.
711pub(crate) struct FastIndexSampler {
712    bound: usize,
713    threshold: u32,
714}
715
716impl FastIndexSampler {
717    #[inline]
718    pub(crate) fn new(bound: usize) -> Self {
719        debug_assert!(bound > 0);
720        let threshold = if bound <= 1024 {
721            65_536u32 % (bound as u32)
722        } else if bound <= u32::MAX as usize {
723            let b = bound as u32;
724            b.wrapping_neg() % b
725        } else {
726            0
727        };
728        Self { bound, threshold }
729    }
730
731    #[cold]
732    fn sample_16_slow(rng: &mut DeterministicRng, bound: u32, threshold: u32) -> usize {
733        loop {
734            let mut w = rng.next_u64();
735            for _ in 0..4 {
736                let prod = ((w & 0xFFFF) as u32) * bound;
737                if (prod & 0xFFFF) >= threshold {
738                    return (prod >> 16) as usize;
739                }
740                w >>= 16;
741            }
742        }
743    }
744
745    #[cold]
746    fn sample_32_slow(rng: &mut DeterministicRng, bound: u64, threshold: u32) -> usize {
747        loop {
748            let w = rng.next_u64();
749            let p0 = (w & 0xFFFF_FFFF) * bound;
750            if (p0 as u32) >= threshold {
751                return (p0 >> 32) as usize;
752            }
753            let p1 = (w >> 32) * bound;
754            if (p1 as u32) >= threshold {
755                return (p1 >> 32) as usize;
756            }
757        }
758    }
759
760    #[inline]
761    pub(crate) fn next(&mut self, rng: &mut DeterministicRng) -> usize {
762        if self.bound <= 1 {
763            return 0;
764        }
765        if self.bound <= u32::MAX as usize {
766            let bound = self.bound as u64;
767            let threshold = self.threshold;
768            let prod = (rng.next_u64() >> 32) * bound;
769            if (prod as u32) >= threshold {
770                return (prod >> 32) as usize;
771            }
772            return Self::sample_32_slow(rng, bound, threshold);
773        }
774        rng.next_index(self.bound)
775    }
776
777    /// Fill `out[k] = pool[idx_k] * sqrt_mu[k]` for every cell using 4-wide
778    /// 16-bit Lemire (1 `next_u64()` per 4 cells, 0 refill branches, parallel
779    /// multiplies) for `bound <= 1024`, or 2-wide 32-bit Lemire for larger pools.
780    #[inline]
781    pub(crate) fn fill_weighted_deltas(
782        &self,
783        pool: &[f64],
784        sqrt_mu: &[f64],
785        rng: &mut DeterministicRng,
786        out: &mut [f64],
787    ) {
788        debug_assert_eq!(out.len(), sqrt_mu.len());
789        if self.bound <= 1 {
790            let r0 = pool[0];
791            for (dst, &sm) in out.iter_mut().zip(sqrt_mu.iter()) {
792                *dst = r0 * sm;
793            }
794            return;
795        }
796        if self.bound <= 1024 {
797            let bound = self.bound as u32;
798            let threshold = self.threshold;
799            let mut out_chunks = out.chunks_exact_mut(4);
800            let mut sm_chunks = sqrt_mu.chunks_exact(4);
801            for (oc, sc) in (&mut out_chunks).zip(&mut sm_chunks) {
802                let w = rng.next_u64();
803                let p0 = ((w & 0xFFFF) as u32) * bound;
804                let p1 = (((w >> 16) & 0xFFFF) as u32) * bound;
805                let p2 = (((w >> 32) & 0xFFFF) as u32) * bound;
806                let p3 = ((w >> 48) as u32) * bound;
807                let l0 = p0 & 0xFFFF;
808                let l1 = p1 & 0xFFFF;
809                let l2 = p2 & 0xFFFF;
810                let l3 = p3 & 0xFFFF;
811                if l0.min(l1).min(l2).min(l3) >= threshold {
812                    oc[0] = pool[(p0 >> 16) as usize] * sc[0];
813                    oc[1] = pool[(p1 >> 16) as usize] * sc[1];
814                    oc[2] = pool[(p2 >> 16) as usize] * sc[2];
815                    oc[3] = pool[(p3 >> 16) as usize] * sc[3];
816                } else {
817                    let i0 = if l0 >= threshold {
818                        (p0 >> 16) as usize
819                    } else {
820                        Self::sample_16_slow(rng, bound, threshold)
821                    };
822                    let i1 = if l1 >= threshold {
823                        (p1 >> 16) as usize
824                    } else {
825                        Self::sample_16_slow(rng, bound, threshold)
826                    };
827                    let i2 = if l2 >= threshold {
828                        (p2 >> 16) as usize
829                    } else {
830                        Self::sample_16_slow(rng, bound, threshold)
831                    };
832                    let i3 = if l3 >= threshold {
833                        (p3 >> 16) as usize
834                    } else {
835                        Self::sample_16_slow(rng, bound, threshold)
836                    };
837                    oc[0] = pool[i0] * sc[0];
838                    oc[1] = pool[i1] * sc[1];
839                    oc[2] = pool[i2] * sc[2];
840                    oc[3] = pool[i3] * sc[3];
841                }
842            }
843            let out_rem = out_chunks.into_remainder();
844            let sm_rem = sm_chunks.remainder();
845            if !out_rem.is_empty() {
846                let mut w = rng.next_u64();
847                for (dst, &sm) in out_rem.iter_mut().zip(sm_rem.iter()) {
848                    let p = ((w & 0xFFFF) as u32) * bound;
849                    w >>= 16;
850                    let idx = if (p & 0xFFFF) >= threshold {
851                        (p >> 16) as usize
852                    } else {
853                        Self::sample_16_slow(rng, bound, threshold)
854                    };
855                    *dst = pool[idx] * sm;
856                }
857            }
858            return;
859        }
860        if self.bound <= u32::MAX as usize {
861            let bound = self.bound as u64;
862            let threshold = self.threshold;
863            let mut out_chunks = out.chunks_exact_mut(2);
864            let mut sm_chunks = sqrt_mu.chunks_exact(2);
865            for (oc, sc) in (&mut out_chunks).zip(&mut sm_chunks) {
866                let w = rng.next_u64();
867                let p0 = (w & 0xFFFF_FFFF) * bound;
868                let p1 = (w >> 32) * bound;
869                let l0 = p0 as u32;
870                let l1 = p1 as u32;
871                if l0.min(l1) >= threshold {
872                    oc[0] = pool[(p0 >> 32) as usize] * sc[0];
873                    oc[1] = pool[(p1 >> 32) as usize] * sc[1];
874                } else {
875                    let i0 = if l0 >= threshold {
876                        (p0 >> 32) as usize
877                    } else {
878                        Self::sample_32_slow(rng, bound, threshold)
879                    };
880                    let i1 = if l1 >= threshold {
881                        (p1 >> 32) as usize
882                    } else {
883                        Self::sample_32_slow(rng, bound, threshold)
884                    };
885                    oc[0] = pool[i0] * sc[0];
886                    oc[1] = pool[i1] * sc[1];
887                }
888            }
889            let out_rem = out_chunks.into_remainder();
890            let sm_rem = sm_chunks.remainder();
891            if let (Some(dst), Some(&sm)) = (out_rem.first_mut(), sm_rem.first()) {
892                let p = (rng.next_u64() >> 32) * bound;
893                let idx = if (p as u32) >= threshold {
894                    (p >> 32) as usize
895                } else {
896                    Self::sample_32_slow(rng, bound, threshold)
897                };
898                *dst = pool[idx] * sm;
899            }
900            return;
901        }
902        for (dst, &sm) in out.iter_mut().zip(sqrt_mu.iter()) {
903            *dst = pool[rng.next_index(self.bound)] * sm;
904        }
905    }
906}
907
908/// Lanczos approximation to `ln Γ(z)` for `z > 0` (accuracy ~1e-14).
909pub(crate) fn ln_gamma(z: f64) -> f64 {
910    const COEFFS: [f64; 9] = [
911        0.999_999_999_999_809_9,
912        676.520_368_121_885_1,
913        -1_259.139_216_722_402_8,
914        771.323_428_777_653_1,
915        -176.615_029_162_140_6,
916        12.507_343_278_686_905,
917        -0.138_571_095_265_720_12,
918        9.984_369_578_019_572e-6,
919        1.505_632_735_149_311_6e-7,
920    ];
921    let x = z - 1.0;
922    let mut sum = COEFFS[0];
923    for (idx, &coeff) in COEFFS.iter().enumerate().skip(1) {
924        sum += coeff / (x + idx as f64);
925    }
926    let t = x + 7.5;
927    0.5 * TAU.ln() + (x + 0.5) * t.ln() - t + sum.ln()
928}
929
930// ===========================================================================
931// ODP GLM Fit (Exact O(n^2) Tridiagonal Green's Function + O(n^3) Fallback)
932// ===========================================================================
933
934struct OdpSolvedDiagnostics {
935    residuals: Vec<OdpCellResidual>,
936    n_observed: usize,
937    rank: usize,
938    degrees_of_freedom: usize,
939    dispersion: f64,
940    origin_reserves: Vec<f64>,
941    total_reserve: f64,
942    analytic_origin_process_se: Vec<f64>,
943    analytic_origin_param_se: Vec<f64>,
944    analytic_origin_prediction_error: Vec<f64>,
945    analytic_total_process_se: f64,
946    analytic_total_param_se: f64,
947    analytic_total_prediction_error: f64,
948}
949
950/// Exact `O(n^2)` time, `O(n)` auxiliary-space solver for full strictly-positive
951/// right triangles (`μ_{i,j} = α_i · β_j > 0` for all `i + j < n`).
952///
953/// In cumulative development coordinates `T_k = sum_{j=1}^k β_j v_j` (`T_0 = 0`),
954/// the Schur complement of `X^T W X` reduces to an `(n - 1) × (n - 1)` symmetric
955/// positive-definite tridiagonal matrix `K`. Its bidiagonal `L D L^T` factorization
956/// takes `O(n)` time, its Green's function yields every hat-matrix leverage `h_{i,j}`
957/// in `O(1)` (`O(n^2)` total), and every analytic ODP parameter variance collapses to
958/// a 2-term closed form (`O(n)` total across all origins plus portfolio total).
959///
960/// Returns `None` if any cell has non-positive fitted mass or ill-conditioned pivot,
961/// signaling the caller to fall back to the general `O(n^3)` SPD-inverse path.
962fn try_solve_odp_tridiagonal(
963    n: usize,
964    ldfs: &[f64],
965    tail: f64,
966    latest: &[f64],
967    fitted_cumulative: &[f64],
968    fitted_incremental: &[f64],
969    observed_incremental: &[f64],
970) -> Option<OdpSolvedDiagnostics> {
971    let m = n - 1;
972    if latest.iter().any(|&v| !(v > 0.0) || !v.is_finite())
973        || ldfs.iter().any(|&f| !(f > 1.0) || !f.is_finite())
974    {
975        return None;
976    }
977
978    // Rank-1 factorization μ_{i,j} = α_i · β_j with sum_j β_j = 1.
979    let mut cdfs_to_last = vec![0.0; n];
980    cdfs_from_ldfs(ldfs, 1.0, &mut cdfs_to_last);
981    let mut b_cum = vec![0.0; n];
982    let mut beta = vec![0.0; n];
983    for j in 0..n {
984        let inv_cdf = 1.0 / cdfs_to_last[j];
985        if !inv_cdf.is_finite() || !(inv_cdf > 0.0) {
986            return None;
987        }
988        b_cum[j] = inv_cdf;
989        beta[j] = if j == 0 {
990            inv_cdf
991        } else {
992            inv_cdf - b_cum[j - 1]
993        };
994        if !(beta[j] > 0.0) || !beta[j].is_finite() {
995            return None;
996        }
997    }
998
999    let mut alpha = vec![0.0; n];
1000    for i in 0..n {
1001        let a = fitted_cumulative[i * n + m];
1002        if !(a > 0.0) || !a.is_finite() {
1003            return None;
1004        }
1005        alpha[i] = a;
1006    }
1007
1008    // A[k] = sum_{i=0}^{n-1-k} α_i.
1009    let mut a_sum = vec![0.0; n];
1010    let mut acc = 0.0;
1011    for k in (0..n).rev() {
1012        acc += alpha[m - k];
1013        a_sum[k] = acc;
1014    }
1015
1016    // Assemble symmetric tridiagonal K of dimension m = n - 1 (indices 0..m correspond to k = 1..n).
1017    let mut d = vec![0.0; m];
1018    let mut e = vec![0.0; m.saturating_sub(1)];
1019    for k in 1..n {
1020        let idx = k - 1;
1021        if k < m {
1022            let off = a_sum[k + 1] / beta[k + 1];
1023            d[idx] = a_sum[k] / beta[k] + off - alpha[m - k] / b_cum[k];
1024            e[idx] = -off;
1025        } else {
1026            d[idx] = a_sum[k] / beta[k] - alpha[0] / b_cum[k];
1027        }
1028    }
1029
1030    // Forward L D L^T sweep in O(n): L_{idx+1, idx} = -gamma[idx].
1031    let mut d_tilde = vec![0.0; m];
1032    let mut gamma = vec![0.0; m.saturating_sub(1)];
1033    if !d[0].is_finite() || d[0] <= 0.0 {
1034        return None;
1035    }
1036    d_tilde[0] = d[0];
1037    for idx in 0..(m - 1) {
1038        let g = -e[idx] / d_tilde[idx];
1039        let next_dt = d[idx + 1] + e[idx] * g;
1040        if !g.is_finite() || !next_dt.is_finite() || next_dt <= 1e-14 * d[idx + 1].abs().max(1e-30)
1041        {
1042            return None;
1043        }
1044        gamma[idx] = g;
1045        d_tilde[idx + 1] = next_dt;
1046    }
1047
1048    // Backward diagonal recurrence for G = K^{-1} in O(n) (sum of positive squares).
1049    let mut g_diag = vec![0.0; m];
1050    g_diag[m - 1] = 1.0 / d_tilde[m - 1];
1051    for idx in (0..(m - 1)).rev() {
1052        g_diag[idx] = 1.0 / d_tilde[idx] + gamma[idx] * gamma[idx] * g_diag[idx + 1];
1053    }
1054
1055    // Precompute w_j^T G w_j for j = 1..n in O(n).
1056    let mut w_g_w = vec![0.0; n];
1057    w_g_w[1] = g_diag[0] / (beta[1] * beta[1]);
1058    for j in 2..n {
1059        let g_jm1_j = gamma[j - 2] * g_diag[j - 1];
1060        w_g_w[j] = (g_diag[j - 1] - 2.0 * g_jm1_j + g_diag[j - 2]) / (beta[j] * beta[j]);
1061    }
1062
1063    // Compute all N = n(n+1)/2 residuals & exact leverages in row-major order in O(n^2).
1064    let n_observed = n * (n + 1) / 2;
1065    let rank = 2 * n - 1;
1066    let degrees_of_freedom = n_observed - rank;
1067    let mut residuals = Vec::with_capacity(n_observed);
1068    let mut pearson_sq_sum = 0.0;
1069    let mut g_row = vec![0.0; n];
1070
1071    for origin in 0..n {
1072        let ki = m - origin;
1073        if ki >= 1 {
1074            g_row[ki] = g_diag[ki - 1];
1075            for j in (1..ki).rev() {
1076                g_row[j] = gamma[j - 1] * g_row[j + 1];
1077            }
1078        }
1079        let inv_b_ki = 1.0 / b_cum[ki];
1080        let base_phi = inv_b_ki / alpha[origin];
1081        let z_g_z = if ki >= 1 {
1082            g_diag[ki - 1] * inv_b_ki * inv_b_ki
1083        } else {
1084            0.0
1085        };
1086        let row_off = origin * n;
1087
1088        for dev in 0..=ki {
1089            let obs = observed_incremental[row_off + dev];
1090            let mu = fitted_incremental[row_off + dev];
1091            if !(mu > 0.0) || !mu.is_finite() {
1092                return None;
1093            }
1094            let raw_residual = (obs - mu) / mu.sqrt();
1095            pearson_sq_sum += raw_residual * raw_residual;
1096
1097            let y_g_y = if dev == 0 {
1098                z_g_z
1099            } else if dev == 1 {
1100                let w_g_z = -g_row[1] * inv_b_ki / beta[1];
1101                w_g_w[1] + 2.0 * w_g_z + z_g_z
1102            } else {
1103                let w_g_z = -(g_row[dev] - g_row[dev - 1]) * inv_b_ki / beta[dev];
1104                w_g_w[dev] + 2.0 * w_g_z + z_g_z
1105            };
1106            let leverage = (mu * (base_phi + y_g_y)).clamp(0.0, 1.0);
1107            let saturated = (1.0 - leverage) <= 1e-10;
1108
1109            residuals.push(OdpCellResidual {
1110                origin,
1111                dev,
1112                observed_incremental: obs,
1113                fitted_incremental: mu,
1114                raw_pearson_residual: raw_residual,
1115                leverage,
1116                saturated,
1117            });
1118        }
1119    }
1120
1121    let dispersion = pearson_sq_sum / degrees_of_freedom as f64;
1122
1123    // Precompute column G[k, m-1] for k = 0..m in O(n).
1124    let mut g_last = vec![0.0; m];
1125    g_last[m - 1] = g_diag[m - 1];
1126    for idx in (0..(m - 1)).rev() {
1127        g_last[idx] = gamma[idx] * g_last[idx + 1];
1128    }
1129
1130    // Closed-form O(n) origin reserves & analytic prediction errors.
1131    let mut origin_reserves = vec![0.0; n];
1132    let mut analytic_origin_process_se = vec![0.0; n];
1133    let mut analytic_origin_param_se = vec![0.0; n];
1134    let mut analytic_origin_prediction_error = vec![0.0; n];
1135    let mut pre_tail_total_reserve = 0.0;
1136    let mut r_diag_sum = 0.0;
1137    let g_mm = g_diag[m - 1];
1138
1139    for origin in 0..n {
1140        let ki = m - origin;
1141        let ai = alpha[origin];
1142        let r_pre_tail = if origin == 0 {
1143            0.0
1144        } else {
1145            ai * (1.0 - b_cum[ki])
1146        };
1147        pre_tail_total_reserve += r_pre_tail;
1148        let tail_increment = ai * (tail - 1.0);
1149        origin_reserves[origin] = r_pre_tail + tail_increment;
1150
1151        let param_quad = if origin == 0 {
1152            0.0
1153        } else if origin < m {
1154            let inv_b = 1.0 / b_cum[ki];
1155            let diag_term = (r_pre_tail * r_pre_tail) * inv_b / ai;
1156            r_diag_sum += diag_term;
1157            diag_term
1158                + ai * ai * (g_diag[ki - 1] * inv_b * inv_b - 2.0 * g_last[ki - 1] * inv_b + g_mm)
1159        } else {
1160            let diag_term = (r_pre_tail * r_pre_tail) / (ai * b_cum[0]);
1161            r_diag_sum += diag_term;
1162            diag_term + ai * ai * g_mm
1163        };
1164        let param_var = (dispersion * param_quad).max(0.0);
1165        let proc_var = (dispersion * r_pre_tail).max(0.0);
1166        analytic_origin_process_se[origin] = proc_var.sqrt();
1167        analytic_origin_param_se[origin] = param_var.sqrt();
1168        analytic_origin_prediction_error[origin] = (proc_var + param_var).sqrt();
1169    }
1170
1171    // Portfolio total parameter variance via one O(n) forward pass: y^T K^{-1} y = z^T D_tilde^{-1} z.
1172    let mut total_quad = r_diag_sum;
1173    let mut z_prev = 0.0;
1174    for idx in 0..m {
1175        let k = idx + 1;
1176        let y_k = if k < m {
1177            -alpha[m - k] / b_cum[k]
1178        } else {
1179            a_sum[0] - alpha[0]
1180        };
1181        let z_k = if idx == 0 {
1182            y_k
1183        } else {
1184            y_k + gamma[idx - 1] * z_prev
1185        };
1186        total_quad += (z_k * z_k) / d_tilde[idx];
1187        z_prev = z_k;
1188    }
1189
1190    let total_reserve: f64 = origin_reserves.iter().sum();
1191    let total_param_var = (dispersion * total_quad).max(0.0);
1192    let total_proc_var = (dispersion * pre_tail_total_reserve).max(0.0);
1193
1194    Some(OdpSolvedDiagnostics {
1195        residuals,
1196        n_observed,
1197        rank,
1198        degrees_of_freedom,
1199        dispersion,
1200        origin_reserves,
1201        total_reserve,
1202        analytic_origin_process_se,
1203        analytic_origin_param_se,
1204        analytic_origin_prediction_error,
1205        analytic_total_process_se: total_proc_var.sqrt(),
1206        analytic_total_param_se: total_param_var.sqrt(),
1207        analytic_total_prediction_error: (total_proc_var + total_param_var).sqrt(),
1208    })
1209}
1210
1211/// General `O(n^3)` fallback for triangles with zero-mass fitted cells (e.g., an
1212/// LDF equal to `1.0` or a zero origin row). Uses `invert_spd` once in `O(p^3)`
1213/// and computes each hat-matrix leverage in `O(1)` via 3-sparse lookups (`O(N)`
1214/// total rather than `O(N p^2)`).
1215fn solve_odp_general(
1216    n: usize,
1217    tail: f64,
1218    fitted_cumulative: &[f64],
1219    fitted_incremental: &[f64],
1220    observed_incremental: &[f64],
1221) -> Result<OdpSolvedDiagnostics, ValidationError> {
1222    let mut active_origins = vec![false; n];
1223    let mut active_devs = vec![false; n];
1224    let mut active_cells: Vec<(usize, usize)> = Vec::with_capacity(n * (n + 1) / 2);
1225    for origin in 0..n {
1226        for dev in 0..(n - origin) {
1227            let mu = fitted_incremental[origin * n + dev];
1228            if mu.is_finite() && mu > 0.0 {
1229                active_origins[origin] = true;
1230                active_devs[dev] = true;
1231                active_cells.push((origin, dev));
1232            }
1233        }
1234    }
1235
1236    let mut origin_col = vec![None; n];
1237    let mut dev_col = vec![None; n];
1238    let mut param_count = 1usize;
1239    let mut first_origin_skipped = false;
1240    for origin in 0..n {
1241        if active_origins[origin] {
1242            if !first_origin_skipped {
1243                first_origin_skipped = true;
1244            } else {
1245                origin_col[origin] = Some(param_count);
1246                param_count += 1;
1247            }
1248        }
1249    }
1250    let mut first_dev_skipped = false;
1251    for dev in 0..n {
1252        if active_devs[dev] {
1253            if !first_dev_skipped {
1254                first_dev_skipped = true;
1255            } else {
1256                dev_col[dev] = Some(param_count);
1257                param_count += 1;
1258            }
1259        }
1260    }
1261
1262    let n_observed = active_cells.len();
1263    if n_observed <= param_count {
1264        return Err(ValidationError::InvalidParameter(
1265            "ODP model has non-positive residual degrees of freedom",
1266        ));
1267    }
1268    let degrees_of_freedom = n_observed - param_count;
1269
1270    // Assemble Fisher information matrix M = X^T W X in O(N).
1271    let mut info = vec![0.0; param_count * param_count];
1272    for &(origin, dev) in &active_cells {
1273        let w = fitted_incremental[origin * n + dev];
1274        let mut cols = [0usize; 3];
1275        let mut ncols = 1usize;
1276        if let Some(c) = origin_col[origin] {
1277            cols[ncols] = c;
1278            ncols += 1;
1279        }
1280        if let Some(c) = dev_col[dev] {
1281            cols[ncols] = c;
1282            ncols += 1;
1283        }
1284        for a in 0..ncols {
1285            for b in 0..ncols {
1286                info[cols[a] * param_count + cols[b]] += w;
1287            }
1288        }
1289    }
1290
1291    let chol = cholesky_lower(&info, param_count)?;
1292    let info_inv = invert_spd(&info, param_count)?;
1293
1294    // Exact hat-matrix leverages in O(1) per cell via 3-sparse quadratic form x^T M^{-1} x.
1295    let mut residuals = Vec::with_capacity(n_observed);
1296    let mut pearson_sq_sum = 0.0;
1297    for &(origin, dev) in &active_cells {
1298        let obs = observed_incremental[origin * n + dev];
1299        let mu = fitted_incremental[origin * n + dev];
1300        let raw_residual = (obs - mu) / mu.sqrt();
1301        pearson_sq_sum += raw_residual * raw_residual;
1302
1303        let mut cols = [0usize; 3];
1304        let mut ncols = 1usize;
1305        if let Some(c) = origin_col[origin] {
1306            cols[ncols] = c;
1307            ncols += 1;
1308        }
1309        if let Some(c) = dev_col[dev] {
1310            cols[ncols] = c;
1311            ncols += 1;
1312        }
1313        let mut qf = 0.0;
1314        for a in 0..ncols {
1315            let ca = cols[a];
1316            qf += info_inv[ca * param_count + ca];
1317            for b in (a + 1)..ncols {
1318                qf += 2.0 * info_inv[ca * param_count + cols[b]];
1319            }
1320        }
1321        let leverage = (mu * qf).clamp(0.0, 1.0);
1322        let saturated = (1.0 - leverage) <= 1e-10;
1323
1324        residuals.push(OdpCellResidual {
1325            origin,
1326            dev,
1327            observed_incremental: obs,
1328            fitted_incremental: mu,
1329            raw_pearson_residual: raw_residual,
1330            leverage,
1331            saturated,
1332        });
1333    }
1334
1335    let dispersion = pearson_sq_sum / degrees_of_freedom as f64;
1336
1337    let mut origin_reserves = vec![0.0; n];
1338    let mut analytic_origin_process_se = vec![0.0; n];
1339    let mut analytic_origin_param_se = vec![0.0; n];
1340    let mut analytic_origin_prediction_error = vec![0.0; n];
1341    let mut g_total = vec![0.0; param_count];
1342    let mut g_origin = vec![0.0; param_count];
1343    let mut y_buf = vec![0.0; param_count];
1344    let mut pre_tail_total_reserve = 0.0;
1345
1346    for origin in 0..n {
1347        g_origin.fill(0.0);
1348        let mut r_pre_tail = 0.0;
1349        for dev in (n - origin)..n {
1350            let mu = fitted_incremental[origin * n + dev];
1351            r_pre_tail += mu;
1352            g_origin[0] += mu;
1353            g_total[0] += mu;
1354            if let Some(c) = origin_col[origin] {
1355                g_origin[c] += mu;
1356                g_total[c] += mu;
1357            }
1358            if let Some(c) = dev_col[dev] {
1359                g_origin[c] += mu;
1360                g_total[c] += mu;
1361            }
1362        }
1363        pre_tail_total_reserve += r_pre_tail;
1364        let tail_increment = fitted_cumulative[origin * n + (n - 1)] * (tail - 1.0);
1365        origin_reserves[origin] = r_pre_tail + tail_increment;
1366
1367        solve_lower_into(&chol, param_count, &g_origin, &mut y_buf);
1368        let param_var = (dispersion * y_buf.iter().map(|v| v * v).sum::<f64>()).max(0.0);
1369        let proc_var = (dispersion * r_pre_tail).max(0.0);
1370        analytic_origin_process_se[origin] = proc_var.sqrt();
1371        analytic_origin_param_se[origin] = param_var.sqrt();
1372        analytic_origin_prediction_error[origin] = (proc_var + param_var).sqrt();
1373    }
1374
1375    let total_reserve: f64 = origin_reserves.iter().sum();
1376    solve_lower_into(&chol, param_count, &g_total, &mut y_buf);
1377    let total_param_var = (dispersion * y_buf.iter().map(|v| v * v).sum::<f64>()).max(0.0);
1378    let total_proc_var = (dispersion * pre_tail_total_reserve).max(0.0);
1379
1380    Ok(OdpSolvedDiagnostics {
1381        residuals,
1382        n_observed,
1383        rank: param_count,
1384        degrees_of_freedom,
1385        dispersion,
1386        origin_reserves,
1387        total_reserve,
1388        analytic_origin_process_se,
1389        analytic_origin_param_se,
1390        analytic_origin_prediction_error,
1391        analytic_total_process_se: total_proc_var.sqrt(),
1392        analytic_total_param_se: total_param_var.sqrt(),
1393        analytic_total_prediction_error: (total_proc_var + total_param_var).sqrt(),
1394    })
1395}
1396
1397/// Fit the Over-Dispersed Poisson GLM (`log μ_{i,j} = c + α_i + β_j`) to a
1398/// cumulative loss triangle.
1399///
1400/// Produces fitted expectations, unscaled Pearson residuals, exact GLM hat-
1401/// matrix diagonal leverages `h_{ii}`, Pearson dispersion `φ`, and England &
1402/// Verrall (1999, 2002) analytic prediction errors.
1403pub fn fit_odp(
1404    triangle: &TriangleView<'_>,
1405    tail: f64,
1406    policy: MonotonicityPolicy,
1407) -> Result<OdpFit, ValidationError> {
1408    validate_triangle(triangle)?;
1409    if policy == MonotonicityPolicy::Strict {
1410        validate_monotone_cumulative(triangle)?;
1411    }
1412    validate_tail(tail)?;
1413
1414    let n = triangle.n_origins;
1415    if n < 3 {
1416        return Err(ValidationError::InvalidParameter(
1417            "ODP model requires at least a 3x3 triangle for positive degrees of freedom",
1418        ));
1419    }
1420
1421    // Single-pass volume-weighted LDFs without duplicating triangle validation.
1422    let mut ldfs = vec![0.0; n - 1];
1423    volume_weighted_ldfs(triangle.data, n, n, &mut ldfs);
1424    for &f in &ldfs {
1425        if !f.is_finite() {
1426            return Err(ValidationError::NotFinite);
1427        }
1428        if f <= 0.0 {
1429            return Err(ValidationError::DivideByZero("development denominator"));
1430        }
1431        if f < 1.0 {
1432            return Err(ValidationError::InvalidParameter(
1433                "ODP GLM requires non-negative fitted expectations (all volume-weighted LDFs >= 1.0)",
1434            ));
1435        }
1436    }
1437
1438    let observed_incremental = cumulative_to_incremental(triangle);
1439    let latest = latest_diagonal(triangle);
1440
1441    // Exact ODP GLM MLE via backward + forward chain-ladder recursion in O(n^2).
1442    let mut fitted_cumulative = vec![0.0; n * n];
1443    for origin in 0..n {
1444        let d = n - 1 - origin;
1445        let row_off = origin * n;
1446        fitted_cumulative[row_off + d] = latest[origin];
1447        for dev in (0..d).rev() {
1448            fitted_cumulative[row_off + dev] = fitted_cumulative[row_off + dev + 1] / ldfs[dev];
1449        }
1450        for dev in (d + 1)..n {
1451            fitted_cumulative[row_off + dev] = fitted_cumulative[row_off + dev - 1] * ldfs[dev - 1];
1452        }
1453    }
1454
1455    let mut fitted_incremental = vec![0.0; n * n];
1456    for origin in 0..n {
1457        let row_off = origin * n;
1458        fitted_incremental[row_off] = fitted_cumulative[row_off];
1459        for dev in 1..n {
1460            fitted_incremental[row_off + dev] =
1461                fitted_cumulative[row_off + dev] - fitted_cumulative[row_off + dev - 1];
1462        }
1463    }
1464
1465    let solved = match try_solve_odp_tridiagonal(
1466        n,
1467        &ldfs,
1468        tail,
1469        &latest,
1470        &fitted_cumulative,
1471        &fitted_incremental,
1472        &observed_incremental,
1473    ) {
1474        Some(fast) => fast,
1475        None => solve_odp_general(
1476            n,
1477            tail,
1478            &fitted_cumulative,
1479            &fitted_incremental,
1480            &observed_incremental,
1481        )?,
1482    };
1483
1484    Ok(OdpFit {
1485        n_origins: n,
1486        n_devs: n,
1487        ldfs,
1488        tail,
1489        fitted_cumulative,
1490        fitted_incremental,
1491        observed_incremental,
1492        residuals: solved.residuals,
1493        n_observed: solved.n_observed,
1494        rank: solved.rank,
1495        degrees_of_freedom: solved.degrees_of_freedom,
1496        dispersion: solved.dispersion,
1497        origin_reserves: solved.origin_reserves,
1498        total_reserve: solved.total_reserve,
1499        analytic_origin_process_se: solved.analytic_origin_process_se,
1500        analytic_origin_param_se: solved.analytic_origin_param_se,
1501        analytic_origin_prediction_error: solved.analytic_origin_prediction_error,
1502        analytic_total_process_se: solved.analytic_total_process_se,
1503        analytic_total_param_se: solved.analytic_total_param_se,
1504        analytic_total_prediction_error: solved.analytic_total_prediction_error,
1505    })
1506}
1507
1508/// Build the adjusted residual pool for resampling along with its pre-centering mean.
1509pub(crate) fn build_adjusted_residual_pool(
1510    fit: &OdpFit,
1511    adjustment: ResidualAdjustment,
1512    center: bool,
1513) -> Result<(Vec<f64>, f64), ValidationError> {
1514    let mut pool = Vec::with_capacity(fit.residuals.len());
1515    match adjustment {
1516        ResidualAdjustment::DegreesOfFreedom => {
1517            let scale = (fit.n_observed as f64 / fit.degrees_of_freedom as f64).sqrt();
1518            for cell in &fit.residuals {
1519                pool.push(cell.raw_pearson_residual * scale);
1520            }
1521        }
1522        ResidualAdjustment::HatMatrixLeverage => {
1523            for cell in &fit.residuals {
1524                if !cell.saturated {
1525                    pool.push(cell.raw_pearson_residual / (1.0 - cell.leverage).sqrt());
1526                }
1527            }
1528        }
1529    }
1530    if pool.is_empty() {
1531        return Err(ValidationError::InvalidParameter(
1532            "no eligible residuals available for ODP bootstrap resampling",
1533        ));
1534    }
1535    let pool_mean = pool.iter().sum::<f64>() / pool.len() as f64;
1536    if center {
1537        for r in &mut pool {
1538            *r -= pool_mean;
1539        }
1540    }
1541    Ok((pool, pool_mean))
1542}
1543
1544/// Compact reusable scratch buffers for zero-allocation, single-pass ODP
1545/// bootstrap iterations.
1546///
1547/// Packs only the `N = n(n+1)/2` upper-triangle `sqrt(mu)` values (half the
1548/// memory of an `n × n` grid), precomputes baseline column denominators and
1549/// latest-diagonal sums so the hot loop accumulates only zero-mean FMA deltas,
1550/// and eliminates the `col_num` array via `col_num[k] = col_den[k+1] + latest_pseudo[m-1-k]`.
1551pub(crate) struct OdpBootstrapScratch {
1552    n: usize,
1553    all_observed_positive: bool,
1554    inv_phi: f64,
1555    packed_sqrt_mu: Vec<f64>,
1556    cell_deltas: Vec<f64>,
1557    base_col_den: Vec<f64>,
1558    base_latest: Vec<f64>,
1559    delta_col_den: Vec<f64>,
1560    latest_pseudo: Vec<f64>,
1561    pseudo_ldfs: Vec<f64>,
1562    origin_reserves: Vec<f64>,
1563}
1564
1565impl OdpBootstrapScratch {
1566    pub(crate) fn for_fit(fit: &OdpFit) -> Self {
1567        let n = fit.n_origins;
1568        let m = n.saturating_sub(1);
1569        let upper_len = n * (n + 1) / 2;
1570        let mut packed_sqrt_mu = Vec::with_capacity(upper_len);
1571        let mut base_col_den = vec![0.0; m];
1572        let mut base_latest = vec![0.0; n];
1573
1574        for origin in 0..n {
1575            let row_off = origin * n;
1576            let last_dev = n - 1 - origin;
1577            for dev in 0..=last_dev {
1578                let mu = fit.fitted_incremental[row_off + dev];
1579                packed_sqrt_mu.push(if mu > 0.0 { mu.sqrt() } else { 0.0 });
1580                if dev < last_dev {
1581                    base_col_den[dev] += fit.fitted_cumulative[row_off + dev];
1582                }
1583            }
1584            base_latest[origin] = fit.fitted_cumulative[row_off + last_dev];
1585        }
1586
1587        let inv_phi = if fit.dispersion > 0.0 && fit.dispersion.is_finite() {
1588            1.0 / fit.dispersion
1589        } else {
1590            0.0
1591        };
1592
1593        Self {
1594            n,
1595            all_observed_positive: fit.n_observed == upper_len,
1596            inv_phi,
1597            packed_sqrt_mu,
1598            cell_deltas: vec![0.0; upper_len],
1599            base_col_den,
1600            base_latest,
1601            delta_col_den: vec![0.0; m],
1602            latest_pseudo: vec![0.0; n],
1603            pseudo_ldfs: vec![0.0; m],
1604            origin_reserves: vec![0.0; n],
1605        }
1606    }
1607}
1608
1609#[derive(Clone, Copy)]
1610struct RefitOutcome {
1611    valid: bool,
1612    all_ldfs_ge_one: bool,
1613}
1614
1615/// Complete volume-weighted LDF computation from `delta_col_den` + `latest_pseudo`
1616/// in a single right-to-left `O(n)` pass using `col_num[k] = col_den[k+1] + latest_pseudo[m-1-k]`.
1617#[inline]
1618fn finalize_pseudo_ldfs(scratch: &mut OdpBootstrapScratch) -> RefitOutcome {
1619    let m = scratch.n.saturating_sub(1);
1620    let mut all_ge_one = true;
1621    let mut next_den = 0.0;
1622    for k in (0..m).rev() {
1623        let den = scratch.base_col_den[k] + scratch.delta_col_den[k];
1624        if !(den > 0.0) || !den.is_finite() {
1625            return RefitOutcome {
1626                valid: false,
1627                all_ldfs_ge_one: false,
1628            };
1629        }
1630        let num = next_den + scratch.latest_pseudo[m - 1 - k];
1631        let f = num / den;
1632        if !f.is_finite() || f <= 0.0 {
1633            return RefitOutcome {
1634                valid: false,
1635                all_ldfs_ge_one: false,
1636            };
1637        }
1638        if f < 1.0 {
1639            all_ge_one = false;
1640        }
1641        scratch.pseudo_ldfs[k] = f;
1642        next_den = den;
1643    }
1644    RefitOutcome {
1645        valid: true,
1646        all_ldfs_ge_one: all_ge_one,
1647    }
1648}
1649
1650/// Accumulate zero-mean cell perturbations `cell_deltas[0..N]` into
1651/// `delta_col_den[0..m]` and `latest_pseudo[0..n]` using paired origin rows
1652/// (breaking the serial `running += d` FP latency chain into 2 parallel pipes
1653/// and halving `delta_den` store traffic), then finalize volume-weighted LDFs.
1654#[inline]
1655fn accumulate_cell_deltas_and_refit(scratch: &mut OdpBootstrapScratch) -> RefitOutcome {
1656    let n = scratch.n;
1657    let m = n.saturating_sub(1);
1658    let deltas = &scratch.cell_deltas;
1659    let delta_den = &mut scratch.delta_col_den;
1660    let latest_out = &mut scratch.latest_pseudo;
1661    let base_latest = &scratch.base_latest;
1662
1663    // Pair origins (0, 1) to overwrite delta_den[0..m] directly (no fill(0.0)).
1664    // Note: fit_odp guarantees n >= 3 so m >= 2.
1665    let mut row_start = 0usize;
1666    let mut origin = 0usize;
1667    if m >= 2 {
1668        let r0 = &deltas[0..n];
1669        let r1 = &deltas[n..2 * n - 1];
1670        row_start = 2 * n - 1;
1671        let mut run0 = 0.0;
1672        let mut run1 = 0.0;
1673        for (den_slot, (&d0, &d1)) in delta_den[..m - 1]
1674            .iter_mut()
1675            .zip(r0[..m - 1].iter().zip(r1[..m - 1].iter()))
1676        {
1677            run0 += d0;
1678            run1 += d1;
1679            *den_slot = run0 + run1;
1680        }
1681        run0 += r0[m - 1];
1682        delta_den[m - 1] = run0;
1683        latest_out[0] = base_latest[0] + run0 + r0[m];
1684        latest_out[1] = base_latest[1] + run1 + r1[m - 1];
1685        origin = 2;
1686    } else if m == 1 {
1687        let d0 = deltas[0];
1688        delta_den[0] = d0;
1689        latest_out[0] = base_latest[0] + d0 + deltas[1];
1690        row_start = 2;
1691        origin = 1;
1692    }
1693
1694    // Remaining origin pairs (origin, origin + 1) while origin + 1 < m.
1695    while origin + 1 < m {
1696        let len_a = n - origin; // last_dev_a + 1 = m - origin + 1
1697        let len_b = len_a - 1; // last_dev_b + 1 = m - origin
1698        let ra = &deltas[row_start..row_start + len_a];
1699        let rb = &deltas[row_start + len_a..row_start + len_a + len_b];
1700        row_start += len_a + len_b;
1701
1702        let last_a = len_a - 1;
1703        let last_b = len_b - 1;
1704        let mut run_a = 0.0;
1705        let mut run_b = 0.0;
1706        for (den_slot, (&da, &db)) in delta_den[..last_b]
1707            .iter_mut()
1708            .zip(ra[..last_b].iter().zip(rb[..last_b].iter()))
1709        {
1710            run_a += da;
1711            run_b += db;
1712            *den_slot += run_a + run_b;
1713        }
1714        run_a += ra[last_b];
1715        delta_den[last_b] += run_a;
1716        latest_out[origin] = base_latest[origin] + run_a + ra[last_a];
1717        latest_out[origin + 1] = base_latest[origin + 1] + run_b + rb[last_b];
1718        origin += 2;
1719    }
1720
1721    if origin < m {
1722        let last_dev = m - origin;
1723        let row = &deltas[row_start..row_start + last_dev + 1];
1724        row_start += last_dev + 1;
1725        let mut running = 0.0;
1726        for (den_slot, &d) in delta_den[..last_dev].iter_mut().zip(&row[..last_dev]) {
1727            running += d;
1728            *den_slot += running;
1729        }
1730        latest_out[origin] = base_latest[origin] + running + row[last_dev];
1731    }
1732    latest_out[m] = base_latest[m] + deltas[row_start];
1733
1734    finalize_pseudo_ldfs(scratch)
1735}
1736
1737/// Fused 4-wide batched resampling (`pool[idx] * sqrt_mu`) + bounds-check-free
1738/// delta accumulation + LDF refit.
1739#[inline]
1740fn refit_pseudo_ldfs_from_pool(
1741    pool: &[f64],
1742    sampler: &mut FastIndexSampler,
1743    rng: &mut DeterministicRng,
1744    scratch: &mut OdpBootstrapScratch,
1745) -> RefitOutcome {
1746    if scratch.all_observed_positive {
1747        sampler.fill_weighted_deltas(pool, &scratch.packed_sqrt_mu, rng, &mut scratch.cell_deltas);
1748        return accumulate_cell_deltas_and_refit(scratch);
1749    }
1750
1751    // General path when some observed cells have zero fitted mass (`sm == 0.0`).
1752    for (dst, &sm) in scratch
1753        .cell_deltas
1754        .iter_mut()
1755        .zip(scratch.packed_sqrt_mu.iter())
1756    {
1757        *dst = if sm > 0.0 {
1758            pool[sampler.next(rng)] * sm
1759        } else {
1760            0.0
1761        };
1762    }
1763    accumulate_cell_deltas_and_refit(scratch)
1764}
1765
1766/// Fused single-pass pseudo-triangle delta accumulation + LDF refit from an
1767/// externally supplied residual slice (used by synchronized multi-line bootstrap).
1768#[inline]
1769fn refit_pseudo_ldfs_from_slice(
1770    sampled_residuals: &[f64],
1771    scratch: &mut OdpBootstrapScratch,
1772) -> RefitOutcome {
1773    if scratch.all_observed_positive {
1774        for ((dst, &r), &sm) in scratch
1775            .cell_deltas
1776            .iter_mut()
1777            .zip(sampled_residuals.iter())
1778            .zip(scratch.packed_sqrt_mu.iter())
1779        {
1780            *dst = r * sm;
1781        }
1782        return accumulate_cell_deltas_and_refit(scratch);
1783    }
1784
1785    let mut r_idx = 0usize;
1786    for (dst, &sm) in scratch
1787        .cell_deltas
1788        .iter_mut()
1789        .zip(scratch.packed_sqrt_mu.iter())
1790    {
1791        if sm > 0.0 {
1792            *dst = sampled_residuals[r_idx] * sm;
1793            r_idx += 1;
1794        } else {
1795            *dst = 0.0;
1796        }
1797    }
1798    accumulate_cell_deltas_and_refit(scratch)
1799}
1800
1801#[inline]
1802fn sample_positive_process(
1803    mag: f64,
1804    phi: f64,
1805    inv_phi: f64,
1806    dist: ProcessDistribution,
1807    rng: &mut DeterministicRng,
1808) -> f64 {
1809    if !(phi > 0.0) || !(mag > 0.0) || !mag.is_finite() {
1810        return mag;
1811    }
1812    match dist {
1813        ProcessDistribution::Gamma => rng.sample_gamma(mag * inv_phi, phi),
1814        ProcessDistribution::OverDispersedPoisson => phi * rng.sample_poisson(mag * inv_phi),
1815        ProcessDistribution::None => mag,
1816    }
1817}
1818
1819#[inline]
1820fn sample_process_increment_fast(
1821    future_mu: f64,
1822    phi: f64,
1823    inv_phi: f64,
1824    dist: ProcessDistribution,
1825    rng: &mut DeterministicRng,
1826) -> f64 {
1827    if !(phi > 0.0) || future_mu == 0.0 || !future_mu.is_finite() {
1828        return future_mu;
1829    }
1830    // Per Shapland (2016) §3.5.3, preserve process variance on negative pseudo-
1831    // incremental expectations by reflecting the draw: -Sample(|mu|, phi).
1832    let sign = if future_mu < 0.0 { -1.0 } else { 1.0 };
1833    let mag = future_mu.abs();
1834    let draw = match dist {
1835        ProcessDistribution::Gamma => rng.sample_gamma(mag * inv_phi, phi),
1836        ProcessDistribution::OverDispersedPoisson => phi * rng.sample_poisson(mag * inv_phi),
1837        ProcessDistribution::None => mag,
1838    };
1839    sign * draw
1840}
1841
1842/// Project per-origin reserves and sample exact process variance in `O(n)`.
1843///
1844/// Exploits the reproductive additivity of Gamma(`shape_j`, `φ`) and
1845/// `φ · Poisson(λ_j)` under common dispersion `φ` so each open origin requires
1846/// 1 draw (2 when negative pseudo-LDFs create both positive and negative future
1847/// increments) instead of `O(n)` cell-level draws (`O(n^2)` total).
1848///
1849/// Writes `scratch.origin_reserves[0..n]` and returns `Some(total_reserve)`.
1850#[inline]
1851fn project_origin_reserves(
1852    tail: f64,
1853    phi: f64,
1854    all_ldfs_ge_one: bool,
1855    process_distribution: ProcessDistribution,
1856    rng: &mut DeterministicRng,
1857    scratch: &mut OdpBootstrapScratch,
1858) -> Option<f64> {
1859    let n = scratch.n;
1860    let inv_phi = scratch.inv_phi;
1861    let tail_inc = tail - 1.0;
1862
1863    if all_ldfs_ge_one || process_distribution == ProcessDistribution::None {
1864        // Walking origin = 0..n traverses latest_dev = n-1 down to 0, so a single
1865        // register `cdf` compounds pseudo-LDFs right-to-left with zero arrays.
1866        let mut cdf = tail;
1867        let l0 = scratch.latest_pseudo[0];
1868        if !l0.is_finite() {
1869            return None;
1870        }
1871        let r0 = if tail_inc > 0.0 {
1872            sample_process_increment_fast(l0 * tail_inc, phi, inv_phi, process_distribution, rng)
1873        } else {
1874            0.0
1875        };
1876        if !r0.is_finite() {
1877            return None;
1878        }
1879        scratch.origin_reserves[0] = r0;
1880        let mut total = r0;
1881
1882        match process_distribution {
1883            ProcessDistribution::Gamma if phi > 0.0 => {
1884                for origin in 1..n {
1885                    cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1886                    let latest_i = scratch.latest_pseudo[origin];
1887                    let expected_res = latest_i * (cdf - 1.0);
1888                    let res_i = if expected_res > 0.0 && expected_res.is_finite() {
1889                        let shape = expected_res * inv_phi;
1890                        if shape >= 1.0 {
1891                            rng.sample_gamma_ge1(shape) * phi
1892                        } else {
1893                            rng.sample_gamma(shape, phi)
1894                        }
1895                    } else if expected_res < 0.0 && expected_res.is_finite() {
1896                        -rng.sample_gamma(-expected_res * inv_phi, phi)
1897                    } else if expected_res == 0.0 {
1898                        0.0
1899                    } else {
1900                        return None;
1901                    };
1902                    scratch.origin_reserves[origin] = res_i;
1903                    total += res_i;
1904                }
1905            }
1906            ProcessDistribution::OverDispersedPoisson if phi > 0.0 => {
1907                for origin in 1..n {
1908                    cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1909                    let latest_i = scratch.latest_pseudo[origin];
1910                    if !latest_i.is_finite() {
1911                        return None;
1912                    }
1913                    let expected_res = latest_i * (cdf - 1.0);
1914                    let res_i = sample_process_increment_fast(
1915                        expected_res,
1916                        phi,
1917                        inv_phi,
1918                        ProcessDistribution::OverDispersedPoisson,
1919                        rng,
1920                    );
1921                    if !res_i.is_finite() {
1922                        return None;
1923                    }
1924                    scratch.origin_reserves[origin] = res_i;
1925                    total += res_i;
1926                }
1927            }
1928            _ => {
1929                for origin in 1..n {
1930                    cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1931                    let latest_i = scratch.latest_pseudo[origin];
1932                    let expected_res = latest_i * (cdf - 1.0);
1933                    if !expected_res.is_finite() {
1934                        return None;
1935                    }
1936                    scratch.origin_reserves[origin] = expected_res;
1937                    total += expected_res;
1938                }
1939            }
1940        }
1941        return total.is_finite().then_some(total);
1942    }
1943
1944    // General path when any pseudo-LDF < 1.0: track exact positive and negative
1945    // suffix increment factors in two registers (exact equivalence to Shapland
1946    // cell-by-cell reflection because every valid pseudo-LDF > 0 preserves signs).
1947    let mut pos_factor = tail_inc;
1948    let mut neg_factor = 0.0;
1949
1950    let l0 = scratch.latest_pseudo[0];
1951    if !l0.is_finite() {
1952        return None;
1953    }
1954    let r0 = if tail_inc > 0.0 {
1955        sample_process_increment_fast(l0 * tail_inc, phi, inv_phi, process_distribution, rng)
1956    } else {
1957        0.0
1958    };
1959    if !r0.is_finite() {
1960        return None;
1961    }
1962    scratch.origin_reserves[0] = r0;
1963    let mut total = r0;
1964
1965    for origin in 1..n {
1966        let f = scratch.pseudo_ldfs[n - 1 - origin];
1967        let step = f - 1.0;
1968        if step >= 0.0 {
1969            pos_factor = step + f * pos_factor;
1970            neg_factor *= f;
1971        } else {
1972            pos_factor *= f;
1973            neg_factor = (-step) + f * neg_factor;
1974        }
1975
1976        let latest_i = scratch.latest_pseudo[origin];
1977        if !latest_i.is_finite() {
1978            return None;
1979        }
1980        let (pos_mu, neg_mu) = if latest_i >= 0.0 {
1981            (latest_i * pos_factor, latest_i * neg_factor)
1982        } else {
1983            (-latest_i * neg_factor, -latest_i * pos_factor)
1984        };
1985        let pos_draw = if pos_mu > 0.0 {
1986            sample_positive_process(pos_mu, phi, inv_phi, process_distribution, rng)
1987        } else {
1988            0.0
1989        };
1990        let neg_draw = if neg_mu > 0.0 {
1991            sample_positive_process(neg_mu, phi, inv_phi, process_distribution, rng)
1992        } else {
1993            0.0
1994        };
1995        let res_i = pos_draw - neg_draw;
1996        if !res_i.is_finite() {
1997            return None;
1998        }
1999        scratch.origin_reserves[origin] = res_i;
2000        total += res_i;
2001    }
2002
2003    total.is_finite().then_some(total)
2004}
2005
2006/// Execute one ODP bootstrap iteration into reusable `scratch` buffers using an
2007/// externally supplied residual slice (used by synchronized multi-line bootstrap).
2008///
2009/// Returns `Some(&scratch.origin_reserves)` on valid refit or `None` if the
2010/// pseudo-triangle has a degenerate non-positive column sum.
2011pub(crate) fn run_odp_iteration_with_scratch<'a>(
2012    fit: &OdpFit,
2013    sampled_residuals: &[f64],
2014    process_distribution: ProcessDistribution,
2015    rng: &mut DeterministicRng,
2016    scratch: &'a mut OdpBootstrapScratch,
2017) -> Option<&'a [f64]> {
2018    let outcome = refit_pseudo_ldfs_from_slice(sampled_residuals, scratch);
2019    if !outcome.valid {
2020        return None;
2021    }
2022    project_origin_reserves(
2023        fit.tail,
2024        fit.dispersion,
2025        outcome.all_ldfs_ge_one,
2026        process_distribution,
2027        rng,
2028        scratch,
2029    )?;
2030    Some(&scratch.origin_reserves)
2031}
2032
2033/// Run the full England & Verrall (1999, 2002) / Shapland (2016) ODP bootstrap.
2034pub fn bootstrap_odp(
2035    triangle: &TriangleView<'_>,
2036    tail: f64,
2037    options: OdpBootstrapOptions,
2038) -> Result<OdpBootstrapResult, ValidationError> {
2039    if options.iterations == 0 {
2040        return Err(ValidationError::ShapeMismatch);
2041    }
2042
2043    let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2044    let (pool, pool_mean) =
2045        build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2046
2047    let mut rng = DeterministicRng::from_seed(options.seed);
2048    let mut sampler = FastIndexSampler::new(pool.len());
2049    let n = fit.n_origins;
2050    let mut simulated_totals = Vec::with_capacity(options.iterations);
2051    let mut simulated_by_origin: Vec<Vec<f64>> = (0..n)
2052        .map(|_| Vec::with_capacity(options.iterations))
2053        .collect();
2054    let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2055    let mut failed_iterations = 0usize;
2056
2057    for _ in 0..options.iterations {
2058        let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2059        if !outcome.valid {
2060            failed_iterations += 1;
2061            continue;
2062        }
2063        if let Some(total) = project_origin_reserves(
2064            fit.tail,
2065            fit.dispersion,
2066            outcome.all_ldfs_ge_one,
2067            options.process_distribution,
2068            &mut rng,
2069            &mut scratch,
2070        ) {
2071            simulated_totals.push(total);
2072            for (origin_vec, &r) in simulated_by_origin
2073                .iter_mut()
2074                .zip(scratch.origin_reserves.iter())
2075            {
2076                origin_vec.push(r);
2077            }
2078        } else {
2079            failed_iterations += 1;
2080        }
2081    }
2082
2083    if simulated_totals.is_empty() {
2084        return Err(ValidationError::NotFinite);
2085    }
2086
2087    // Reuse a single scratch buffer across portfolio + all n origin summaries
2088    // and skip redundant finiteness scans (every pushed value is verified finite).
2089    let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2090    let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2091    let mut origin_summaries = Vec::with_capacity(n);
2092    for series in &simulated_by_origin {
2093        origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2094    }
2095
2096    Ok(OdpBootstrapResult {
2097        base_total_reserve: fit.total_reserve,
2098        fit,
2099        options,
2100        simulated_totals,
2101        simulated_by_origin,
2102        origin_summaries,
2103        summary,
2104        failed_iterations,
2105        residual_pool_mean_before_centering: pool_mean,
2106    })
2107}
2108
2109/// Run a deterministic ODP bootstrap using the classic England & Verrall
2110/// (1999, 2002) specification (`DegreesOfFreedom` scaling + Gamma process variance).
2111///
2112/// Because this compact entry point only returns portfolio totals, it skips
2113/// allocating per-origin simulation series (`O(B)` space instead of `O(n B)`),
2114/// skips `n` per-origin summaries, and collapses process variance to 1–2 exact
2115/// Gamma draws per iteration.
2116pub fn bootstrap(
2117    triangle: &TriangleView<'_>,
2118    tail: f64,
2119    config: BootstrapConfig,
2120) -> Result<BootstrapResult, ValidationError> {
2121    if config.iterations == 0 {
2122        return Err(ValidationError::ShapeMismatch);
2123    }
2124
2125    let options = OdpBootstrapOptions::england_verrall(config.iterations, config.seed);
2126    let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2127    let (pool, _) =
2128        build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2129
2130    let mut rng = DeterministicRng::from_seed(options.seed);
2131    let mut sampler = FastIndexSampler::new(pool.len());
2132    let n = fit.n_origins;
2133    let phi = fit.dispersion;
2134    let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2135    let inv_phi = scratch.inv_phi;
2136    let tail_inc = fit.tail - 1.0;
2137    let mut simulated_totals = Vec::with_capacity(config.iterations);
2138
2139    for _ in 0..config.iterations {
2140        let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2141        if !outcome.valid {
2142            continue;
2143        }
2144        let mut ok = true;
2145        let total = if outcome.all_ldfs_ge_one {
2146            let mut cdf = fit.tail;
2147            let l0 = scratch.latest_pseudo[0];
2148            if !l0.is_finite() {
2149                ok = false;
2150            }
2151            let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2152                l0 * tail_inc
2153            } else {
2154                0.0
2155            };
2156            let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2157                -l0 * tail_inc
2158            } else {
2159                0.0
2160            };
2161            for origin in 1..n {
2162                cdf *= scratch.pseudo_ldfs[n - 1 - origin];
2163                let li = scratch.latest_pseudo[origin];
2164                if !li.is_finite() {
2165                    ok = false;
2166                    break;
2167                }
2168                let expected = li * (cdf - 1.0);
2169                if expected >= 0.0 {
2170                    pos_sum += expected;
2171                } else {
2172                    neg_sum -= expected;
2173                }
2174            }
2175            if ok {
2176                let p_draw = if pos_sum > 0.0 {
2177                    sample_positive_process(
2178                        pos_sum,
2179                        phi,
2180                        inv_phi,
2181                        options.process_distribution,
2182                        &mut rng,
2183                    )
2184                } else {
2185                    0.0
2186                };
2187                let n_draw = if neg_sum > 0.0 {
2188                    sample_positive_process(
2189                        neg_sum,
2190                        phi,
2191                        inv_phi,
2192                        options.process_distribution,
2193                        &mut rng,
2194                    )
2195                } else {
2196                    0.0
2197                };
2198                p_draw - n_draw
2199            } else {
2200                f64::NAN
2201            }
2202        } else {
2203            let mut pos_factor = tail_inc;
2204            let mut neg_factor = 0.0;
2205            let l0 = scratch.latest_pseudo[0];
2206            if !l0.is_finite() {
2207                ok = false;
2208            }
2209            let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2210                l0 * tail_inc
2211            } else {
2212                0.0
2213            };
2214            let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2215                -l0 * tail_inc
2216            } else {
2217                0.0
2218            };
2219            for origin in 1..n {
2220                let f = scratch.pseudo_ldfs[n - 1 - origin];
2221                let step = f - 1.0;
2222                if step >= 0.0 {
2223                    pos_factor = step + f * pos_factor;
2224                    neg_factor *= f;
2225                } else {
2226                    pos_factor *= f;
2227                    neg_factor = (-step) + f * neg_factor;
2228                }
2229                let li = scratch.latest_pseudo[origin];
2230                if !li.is_finite() {
2231                    ok = false;
2232                    break;
2233                }
2234                if li >= 0.0 {
2235                    pos_sum += li * pos_factor;
2236                    neg_sum += li * neg_factor;
2237                } else {
2238                    pos_sum += -li * neg_factor;
2239                    neg_sum += -li * pos_factor;
2240                }
2241            }
2242            if ok {
2243                let p_draw = if pos_sum > 0.0 {
2244                    sample_positive_process(
2245                        pos_sum,
2246                        phi,
2247                        inv_phi,
2248                        options.process_distribution,
2249                        &mut rng,
2250                    )
2251                } else {
2252                    0.0
2253                };
2254                let n_draw = if neg_sum > 0.0 {
2255                    sample_positive_process(
2256                        neg_sum,
2257                        phi,
2258                        inv_phi,
2259                        options.process_distribution,
2260                        &mut rng,
2261                    )
2262                } else {
2263                    0.0
2264                };
2265                p_draw - n_draw
2266            } else {
2267                f64::NAN
2268            }
2269        };
2270        if ok && total.is_finite() {
2271            simulated_totals.push(total);
2272        }
2273    }
2274
2275    if simulated_totals.is_empty() {
2276        return Err(ValidationError::NotFinite);
2277    }
2278
2279    let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2280    let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2281    Ok(BootstrapResult {
2282        base_total_reserve: fit.total_reserve,
2283        simulated_totals,
2284        summary,
2285    })
2286}
2287
2288/// Reserve-only convenience wrapper around [`bootstrap`].
2289pub fn bootstrap_summary(
2290    triangle: &TriangleView<'_>,
2291    tail: f64,
2292    config: BootstrapConfig,
2293) -> Result<BootstrapSummary, ValidationError> {
2294    Ok(bootstrap(triangle, tail, config)?.summary)
2295}
2296
2297/// Output of the 1-year Solvency II Claims Development Result (CDR)
2298/// re-reserving ODP bootstrap (England & Verrall / Merz & Wüthrich;
2299/// mirrors `mages/ChainLadder`'s `CDR(BootChainLadder)`).
2300#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
2301pub struct OdpCdrBootstrapResult {
2302    /// Initial deterministic reserve $R^{(0)}$ summed across origins.
2303    pub base_total_reserve: f64,
2304    /// Initial deterministic reserve $R_i^{(0)}$ per origin.
2305    pub base_origin_reserves: Vec<f64>,
2306    /// Simulated total 1-year CDR samples: $R^{(0)} - (Y_{\text{next}} + R^{(1)})$.
2307    /// Negative values represent adverse 1-year development.
2308    pub simulated_total_cdr: Vec<f64>,
2309    /// Simulated 1-year CDR samples per origin (`n_origins` vectors).
2310    pub simulated_cdr_by_origin: Vec<Vec<f64>>,
2311    /// Empirical summary statistics of total 1-year CDR.
2312    pub summary: BootstrapSummary,
2313    /// Empirical summary statistics of 1-year CDR per origin.
2314    pub origin_summaries: Vec<BootstrapSummary>,
2315    /// Count of skipped iterations due to degenerate pseudo-triangles.
2316    pub failed_iterations: usize,
2317}
2318
2319/// Run a 1-year Solvency II Claims Development Result (CDR) re-reserving
2320/// bootstrap on top of the ODP bootstrap model.
2321///
2322/// For each simulation $b$:
2323/// 1. Resample scaled Pearson residuals and refit pseudo-LDFs $\hat{f}_k^{(b)}$.
2324/// 2. Simulate the next calendar-year incremental payments $Y_{i, n-i}^{(b)}$
2325///    (with process variance from `options.process_distribution`) for each open
2326///    origin $i \ge 1$.
2327/// 3. Append the simulated diagonal $C_{i, n-i}^{(b)} = C_{i, n-1-i} + Y_{i, n-i}^{(b)}$
2328///    to the observed triangle, re-estimate volume-weighted chain-ladder LDFs
2329///    on the extended 1-year-later triangle, and compute the updated reserve $R_i^{(1,b)}$.
2330/// 4. Record $\text{CDR}_i^{(b)}(1) = R_i^{(0)} - (Y_{i, n-i}^{(b)} + R_i^{(1,b)})$.
2331pub fn bootstrap_odp_cdr(
2332    triangle: &TriangleView<'_>,
2333    tail: f64,
2334    options: OdpBootstrapOptions,
2335) -> Result<OdpCdrBootstrapResult, ValidationError> {
2336    if options.iterations == 0 {
2337        return Err(ValidationError::ShapeMismatch);
2338    }
2339
2340    let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2341    let (pool, _) =
2342        build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2343
2344    let n = fit.n_origins;
2345    let m = n.saturating_sub(1);
2346    let mut rng = DeterministicRng::from_seed(options.seed);
2347    let mut sampler = FastIndexSampler::new(pool.len());
2348
2349    let mut simulated_total_cdr = Vec::with_capacity(options.iterations);
2350    let mut simulated_cdr_by_origin: Vec<Vec<f64>> = (0..n)
2351        .map(|_| Vec::with_capacity(options.iterations))
2352        .collect();
2353    let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2354    let inv_phi = scratch.inv_phi;
2355    let mut ext_ldfs = vec![1.0; m];
2356    let mut ext_cdfs = vec![tail; n];
2357    let mut next_pay = vec![0.0; n];
2358    let mut next_cum_diag = vec![0.0; n];
2359    let mut failed_iterations = 0usize;
2360
2361    // Precompute observed column sums once: each 1-year CDR draw only appends a
2362    // single simulated diagonal cell (i = n - 1 - k, j = k + 1) to link k.
2363    let mut obs_den = vec![0.0; m];
2364    let mut obs_num = vec![0.0; m];
2365    for i in 0..m {
2366        let row = &triangle.data[i * n..i * n + (n - i)];
2367        for k in 0..(n - 1 - i) {
2368            let c0 = row[k];
2369            let c1 = row[k + 1];
2370            if c0.is_finite() && c1.is_finite() {
2371                obs_den[k] += c0;
2372                obs_num[k] += c1;
2373            }
2374        }
2375    }
2376    let obs_diag: Vec<f64> = (0..n).map(|i| triangle.get(i, n - 1 - i)).collect();
2377    let r1_origin0 = obs_diag[0] * (tail - 1.0);
2378
2379    for _ in 0..options.iterations {
2380        // 1. Fused single-pass resampling + delta accumulation + LDF refit.
2381        let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2382        if !outcome.valid {
2383            failed_iterations += 1;
2384            continue;
2385        }
2386
2387        // 2. Simulate next calendar diagonal (i + j == n) and update extended LDFs in O(n).
2388        let mut valid_ext = true;
2389        for i in 1..n {
2390            let k = n - 1 - i; // link k -> k + 1 (j_next = k + 1 = n - i)
2391            let c_prev = obs_diag[i];
2392            let expected_inc = c_prev * (scratch.pseudo_ldfs[k] - 1.0);
2393            let sim_inc = sample_process_increment_fast(
2394                expected_inc,
2395                fit.dispersion,
2396                inv_phi,
2397                options.process_distribution,
2398                &mut rng,
2399            );
2400            let c_next = c_prev + sim_inc;
2401            next_pay[i] = sim_inc;
2402            next_cum_diag[i] = c_next;
2403
2404            let den = obs_den[k] + c_prev;
2405            let num = obs_num[k] + c_next;
2406            if !den.is_finite() || den <= 0.0 || !num.is_finite() || num <= 0.0 {
2407                valid_ext = false;
2408                break;
2409            }
2410            ext_ldfs[k] = num / den;
2411        }
2412        if !valid_ext {
2413            failed_iterations += 1;
2414            continue;
2415        }
2416
2417        // 3. Compound extended CDFs right-to-left in O(n).
2418        ext_cdfs[m] = tail;
2419        for k in (0..m).rev() {
2420            ext_cdfs[k] = ext_ldfs[k] * ext_cdfs[k + 1];
2421        }
2422
2423        // 4. Compute updated reserve R^{(1)} and 1-year CDR = R^{(0)} - (Y_next + R^{(1)}) in O(n).
2424        let cdr0 = fit.origin_reserves[0] - r1_origin0;
2425        if !cdr0.is_finite() {
2426            failed_iterations += 1;
2427            continue;
2428        }
2429        scratch.origin_reserves[0] = cdr0;
2430        let mut total_cdr = cdr0;
2431        let mut ok = true;
2432        for i in 1..n {
2433            let j_next = n - i;
2434            let c_next = next_cum_diag[i];
2435            let r1 = c_next * (ext_cdfs[j_next] - 1.0);
2436            let cdr_i = fit.origin_reserves[i] - (next_pay[i] + r1);
2437            if !cdr_i.is_finite() {
2438                ok = false;
2439                break;
2440            }
2441            scratch.origin_reserves[i] = cdr_i;
2442            total_cdr += cdr_i;
2443        }
2444        if !ok || !total_cdr.is_finite() {
2445            failed_iterations += 1;
2446            continue;
2447        }
2448        simulated_total_cdr.push(total_cdr);
2449        for (origin_vec, &r) in simulated_cdr_by_origin
2450            .iter_mut()
2451            .zip(scratch.origin_reserves.iter())
2452        {
2453            origin_vec.push(r);
2454        }
2455    }
2456
2457    if simulated_total_cdr.is_empty() {
2458        return Err(ValidationError::NotFinite);
2459    }
2460
2461    let mut summary_buf = Vec::with_capacity(simulated_total_cdr.len());
2462    let summary = summarize_with_scratch(&simulated_total_cdr, &mut summary_buf, true)?;
2463    let mut origin_summaries = Vec::with_capacity(n);
2464    for series in &simulated_cdr_by_origin {
2465        origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2466    }
2467
2468    Ok(OdpCdrBootstrapResult {
2469        base_total_reserve: fit.total_reserve,
2470        base_origin_reserves: fit.origin_reserves,
2471        simulated_total_cdr,
2472        simulated_cdr_by_origin,
2473        summary,
2474        origin_summaries,
2475        failed_iterations,
2476    })
2477}
2478
2479#[cfg(test)]
2480mod tests {
2481    use super::*;
2482    use crate::chain_ladder::ChainLadderEngine;
2483    use crate::datasets::genins;
2484    use crate::ldf::DevelopmentFactorEngine;
2485    use crate::types::Triangle;
2486
2487    fn triangle_4x4() -> Triangle {
2488        #[rustfmt::skip]
2489        let data = vec![
2490            1000.0, 1500.0, 1700.0, 1800.0,
2491            1200.0, 1800.0, 2000.0, f64::NAN,
2492            1500.0, 2100.0, f64::NAN, f64::NAN,
2493            1800.0, f64::NAN, f64::NAN, f64::NAN,
2494        ];
2495        Triangle::new(4, 4, data)
2496    }
2497
2498    #[test]
2499    fn bootstrap_is_deterministic_for_same_seed() {
2500        let triangle = triangle_4x4();
2501        let config = BootstrapConfig {
2502            iterations: 50,
2503            seed: 42,
2504        };
2505
2506        let first = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2507        let second = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2508
2509        assert_eq!(first.simulated_totals, second.simulated_totals);
2510        assert_eq!(first.summary, second.summary);
2511    }
2512
2513    #[test]
2514    fn bootstrap_returns_ordered_quantiles() {
2515        let triangle = triangle_4x4();
2516        let summary = bootstrap_summary(
2517            &triangle.view(),
2518            1.0,
2519            BootstrapConfig {
2520                iterations: 100,
2521                seed: 7,
2522            },
2523        )
2524        .expect("summary");
2525
2526        assert!(summary.mean >= 0.0);
2527        assert!(summary.std_dev >= 0.0);
2528        assert!(summary.p50 <= summary.p75);
2529        assert!(summary.p75 <= summary.p90);
2530        assert!(summary.p90 <= summary.p95);
2531        assert!(summary.p95 <= summary.p99);
2532    }
2533
2534    #[test]
2535    fn bootstrap_rejects_zero_iterations() {
2536        let triangle = triangle_4x4();
2537        assert_eq!(
2538            bootstrap(
2539                &triangle.view(),
2540                1.0,
2541                BootstrapConfig {
2542                    iterations: 0,
2543                    seed: 1
2544                }
2545            ),
2546            Err(ValidationError::ShapeMismatch)
2547        );
2548    }
2549
2550    #[test]
2551    fn bootstrap_base_reserve_matches_chain_ladder() {
2552        let triangle = triangle_4x4();
2553        let result = bootstrap(
2554            &triangle.view(),
2555            1.0,
2556            BootstrapConfig {
2557                iterations: 10,
2558                seed: 9,
2559            },
2560        )
2561        .expect("bootstrap");
2562
2563        let factors =
2564            DevelopmentFactorEngine::volume_weighted(&triangle.view(), 1.0).expect("factors");
2565        let projection =
2566            ChainLadderEngine::project(&triangle.view(), &factors).expect("projection");
2567        assert!((result.base_total_reserve - projection.total_reserve).abs() < 1e-9);
2568    }
2569
2570    #[test]
2571    fn odp_fit_leverages_sum_to_rank_and_saturate_corners() {
2572        let triangle = triangle_4x4();
2573        let fit = fit_odp(&triangle.view(), 1.0, MonotonicityPolicy::Strict).expect("fit");
2574
2575        assert_eq!(fit.n_observed, 10);
2576        assert_eq!(fit.rank, 7);
2577        assert_eq!(fit.degrees_of_freedom, 3);
2578        let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2579        assert!((h_sum - 7.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2580        let saturated_corners: Vec<(usize, usize)> = fit
2581            .residuals
2582            .iter()
2583            .filter(|r| r.saturated)
2584            .map(|r| (r.origin, r.dev))
2585            .collect();
2586        assert_eq!(saturated_corners, vec![(0, 3), (3, 0)]);
2587    }
2588
2589    #[test]
2590    fn odp_fit_tridiagonal_matches_general_solver_to_machine_precision() {
2591        let tri = genins();
2592        let fit = fit_odp(&tri.view(), 1.05, MonotonicityPolicy::Strict).expect("fast fit");
2593        let general = solve_odp_general(
2594            fit.n_origins,
2595            fit.tail,
2596            &fit.fitted_cumulative,
2597            &fit.fitted_incremental,
2598            &fit.observed_incremental,
2599        )
2600        .expect("general fit");
2601
2602        assert_eq!(fit.residuals.len(), general.residuals.len());
2603        for (a, b) in fit.residuals.iter().zip(general.residuals.iter()) {
2604            assert_eq!((a.origin, a.dev), (b.origin, b.dev));
2605            assert!((a.leverage - b.leverage).abs() < 1e-12);
2606            assert!((a.raw_pearson_residual - b.raw_pearson_residual).abs() < 1e-12);
2607        }
2608        for i in 0..fit.n_origins {
2609            let tol = 1e-10 * (1.0 + general.analytic_origin_prediction_error[i]);
2610            assert!(
2611                (fit.analytic_origin_param_se[i] - general.analytic_origin_param_se[i]).abs() < tol
2612            );
2613            assert!(
2614                (fit.analytic_origin_prediction_error[i]
2615                    - general.analytic_origin_prediction_error[i])
2616                    .abs()
2617                    < tol
2618            );
2619        }
2620        assert!(
2621            (fit.analytic_total_param_se - general.analytic_total_param_se).abs()
2622                < 1e-10 * general.analytic_total_param_se
2623        );
2624    }
2625
2626    #[test]
2627    fn odp_fit_handles_flat_ldf_via_general_fallback() {
2628        // Last development link has LDF == 1.0 (zero incremental fitted mass in col 3).
2629        #[rustfmt::skip]
2630        let tri = Triangle::new(4, 4, vec![
2631            1000.0, 1500.0, 1700.0, 1700.0,
2632            1200.0, 1800.0, 2000.0, f64::NAN,
2633            1500.0, 2100.0, f64::NAN, f64::NAN,
2634            1800.0, f64::NAN, f64::NAN, f64::NAN,
2635        ]);
2636        let fit = fit_odp(&tri.view(), 1.0, MonotonicityPolicy::Strict).expect("fallback fit");
2637        assert_eq!(fit.n_observed, 9);
2638        assert_eq!(fit.rank, 6);
2639        assert_eq!(fit.degrees_of_freedom, 3);
2640        let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2641        assert!((h_sum - 6.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2642    }
2643
2644    #[test]
2645    fn ziggurat_normal_and_fast_index_samplers_match_theoretical_distributions() {
2646        let mut rng = DeterministicRng::from_seed(1234567);
2647        let n = 200_000usize;
2648        let mut sum = 0.0;
2649        let mut s2 = 0.0;
2650        let mut s3 = 0.0;
2651        let mut s4 = 0.0;
2652        let mut tail_hits = 0usize;
2653        for _ in 0..n {
2654            let z = rng.next_standard_normal();
2655            sum += z;
2656            let z2 = z * z;
2657            s2 += z2;
2658            s3 += z2 * z;
2659            s4 += z2 * z2;
2660            if z.abs() >= ZIG_NORM_R {
2661                tail_hits += 1;
2662            }
2663        }
2664        let nf = n as f64;
2665        let mean = sum / nf;
2666        let var = s2 / nf - mean * mean;
2667        let skew = s3 / nf;
2668        let kurt = s4 / nf;
2669        assert!(mean.abs() < 0.01, "mean={mean}");
2670        assert!((var - 1.0).abs() < 0.015, "var={var}");
2671        assert!(skew.abs() < 0.03, "skew={skew}");
2672        assert!((kurt - 3.0).abs() < 0.08, "kurt={kurt}");
2673        // P(|Z| >= 3.654153) ≈ 2.58e-4 => ~52 hits in 200k.
2674        assert!((20..=100).contains(&tail_hits), "tail_hits={tail_hits}");
2675
2676        // FastIndexSampler uniformity on bound = 53 (16-bit Lemire) and 1500 (32-bit Lemire).
2677        let mut counts53 = [0usize; 53];
2678        let mut s53 = FastIndexSampler::new(53);
2679        for _ in 0..53_000 {
2680            counts53[s53.next(&mut rng)] += 1;
2681        }
2682        let chi2: f64 = counts53
2683            .iter()
2684            .map(|&c| {
2685                let d = c as f64 - 1000.0;
2686                d * d / 1000.0
2687            })
2688            .sum();
2689        assert!(chi2 < 100.0, "chi2(df=52)={chi2}");
2690
2691        let mut s1500 = FastIndexSampler::new(1500);
2692        for _ in 0..5_000 {
2693            assert!(s1500.next(&mut rng) < 1500);
2694        }
2695    }
2696
2697    #[test]
2698    fn gamma_and_poisson_samplers_match_theoretical_moments() {
2699        let mut rng = DeterministicRng::from_seed(42069);
2700        let n = 40_000usize;
2701
2702        for &(shape, scale) in &[(0.4, 2.5), (3.5, 10.0), (25.0, 50.0)] {
2703            let samples: Vec<f64> = (0..n).map(|_| rng.sample_gamma(shape, scale)).collect();
2704            let mean = samples.iter().sum::<f64>() / n as f64;
2705            let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2706            let expected_mean = shape * scale;
2707            let expected_var = shape * scale * scale;
2708            assert!(
2709                (mean - expected_mean).abs() / expected_mean < 0.03,
2710                "gamma({shape},{scale}) mean={mean} expected={expected_mean}"
2711            );
2712            assert!(
2713                (var - expected_var).abs() / expected_var < 0.08,
2714                "gamma({shape},{scale}) var={var} expected={expected_var}"
2715            );
2716        }
2717
2718        for &lambda in &[0.7, 9.5, 10.0, 12.0, 20.0, 45.0, 300.0] {
2719            let samples: Vec<f64> = (0..n).map(|_| rng.sample_poisson(lambda)).collect();
2720            let mean = samples.iter().sum::<f64>() / n as f64;
2721            let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2722            assert!(
2723                (mean - lambda).abs() / lambda < 0.03,
2724                "poisson({lambda}) mean={mean}"
2725            );
2726            assert!(
2727                (var - lambda).abs() / lambda < 0.06,
2728                "poisson({lambda}) var={var}"
2729            );
2730        }
2731    }
2732}