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 = u128::from(self.next_u64()) * u128::from(bound);
574        let mut low = prod as u64;
575        if low < bound {
576            let threshold = bound.wrapping_neg() % bound;
577            while low < threshold {
578                prod = u128::from(self.next_u64()) * u128::from(bound);
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 u32::try_from(bound).is_ok() {
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 u32::try_from(self.bound).is_ok() {
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 (out_chunks, out_rem) = out.as_chunks_mut::<4>();
800            let (sm_chunks, sm_rem) = sqrt_mu.as_chunks::<4>();
801            for (oc, sc) in out_chunks.iter_mut().zip(sm_chunks.iter()) {
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            if !out_rem.is_empty() {
844                let mut w = rng.next_u64();
845                for (dst, &sm) in out_rem.iter_mut().zip(sm_rem.iter()) {
846                    let p = ((w & 0xFFFF) as u32) * bound;
847                    w >>= 16;
848                    let idx = if (p & 0xFFFF) >= threshold {
849                        (p >> 16) as usize
850                    } else {
851                        Self::sample_16_slow(rng, bound, threshold)
852                    };
853                    *dst = pool[idx] * sm;
854                }
855            }
856            return;
857        }
858        if u32::try_from(self.bound).is_ok() {
859            let bound = self.bound as u64;
860            let threshold = self.threshold;
861            let (out_chunks, out_rem) = out.as_chunks_mut::<2>();
862            let (sm_chunks, sm_rem) = sqrt_mu.as_chunks::<2>();
863            for (oc, sc) in out_chunks.iter_mut().zip(sm_chunks.iter()) {
864                let w = rng.next_u64();
865                let p0 = (w & 0xFFFF_FFFF) * bound;
866                let p1 = (w >> 32) * bound;
867                let l0 = p0 as u32;
868                let l1 = p1 as u32;
869                if l0.min(l1) >= threshold {
870                    oc[0] = pool[(p0 >> 32) as usize] * sc[0];
871                    oc[1] = pool[(p1 >> 32) as usize] * sc[1];
872                } else {
873                    let i0 = if l0 >= threshold {
874                        (p0 >> 32) as usize
875                    } else {
876                        Self::sample_32_slow(rng, bound, threshold)
877                    };
878                    let i1 = if l1 >= threshold {
879                        (p1 >> 32) as usize
880                    } else {
881                        Self::sample_32_slow(rng, bound, threshold)
882                    };
883                    oc[0] = pool[i0] * sc[0];
884                    oc[1] = pool[i1] * sc[1];
885                }
886            }
887            if let (Some(dst), Some(&sm)) = (out_rem.first_mut(), sm_rem.first()) {
888                let p = (rng.next_u64() >> 32) * bound;
889                let idx = if (p as u32) >= threshold {
890                    (p >> 32) as usize
891                } else {
892                    Self::sample_32_slow(rng, bound, threshold)
893                };
894                *dst = pool[idx] * sm;
895            }
896            return;
897        }
898        for (dst, &sm) in out.iter_mut().zip(sqrt_mu.iter()) {
899            *dst = pool[rng.next_index(self.bound)] * sm;
900        }
901    }
902}
903
904/// Lanczos approximation to `ln Γ(z)` for `z > 0` (accuracy ~1e-14).
905pub(crate) fn ln_gamma(z: f64) -> f64 {
906    const COEFFS: [f64; 9] = [
907        0.999_999_999_999_809_9,
908        676.520_368_121_885_1,
909        -1_259.139_216_722_402_8,
910        771.323_428_777_653_1,
911        -176.615_029_162_140_6,
912        12.507_343_278_686_905,
913        -0.138_571_095_265_720_12,
914        9.984_369_578_019_572e-6,
915        1.505_632_735_149_311_6e-7,
916    ];
917    let x = z - 1.0;
918    let mut sum = COEFFS[0];
919    for (idx, &coeff) in COEFFS.iter().enumerate().skip(1) {
920        sum += coeff / (x + idx as f64);
921    }
922    let t = x + 7.5;
923    0.5 * TAU.ln() + (x + 0.5) * t.ln() - t + sum.ln()
924}
925
926// ===========================================================================
927// ODP GLM Fit (Exact O(n^2) Tridiagonal Green's Function + O(n^3) Fallback)
928// ===========================================================================
929
930struct OdpSolvedDiagnostics {
931    residuals: Vec<OdpCellResidual>,
932    n_observed: usize,
933    rank: usize,
934    degrees_of_freedom: usize,
935    dispersion: f64,
936    origin_reserves: Vec<f64>,
937    total_reserve: f64,
938    analytic_origin_process_se: Vec<f64>,
939    analytic_origin_param_se: Vec<f64>,
940    analytic_origin_prediction_error: Vec<f64>,
941    analytic_total_process_se: f64,
942    analytic_total_param_se: f64,
943    analytic_total_prediction_error: f64,
944}
945
946/// Exact `O(n^2)` time, `O(n)` auxiliary-space solver for full strictly-positive
947/// right triangles (`μ_{i,j} = α_i · β_j > 0` for all `i + j < n`).
948///
949/// In cumulative development coordinates `T_k = sum_{j=1}^k β_j v_j` (`T_0 = 0`),
950/// the Schur complement of `X^T W X` reduces to an `(n - 1) × (n - 1)` symmetric
951/// positive-definite tridiagonal matrix `K`. Its bidiagonal `L D L^T` factorization
952/// takes `O(n)` time, its Green's function yields every hat-matrix leverage `h_{i,j}`
953/// in `O(1)` (`O(n^2)` total), and every analytic ODP parameter variance collapses to
954/// a 2-term closed form (`O(n)` total across all origins plus portfolio total).
955///
956/// Returns `None` if any cell has non-positive fitted mass or ill-conditioned pivot,
957/// signaling the caller to fall back to the general `O(n^3)` SPD-inverse path.
958fn try_solve_odp_tridiagonal(
959    n: usize,
960    ldfs: &[f64],
961    tail: f64,
962    latest: &[f64],
963    fitted_cumulative: &[f64],
964    fitted_incremental: &[f64],
965    observed_incremental: &[f64],
966) -> Option<OdpSolvedDiagnostics> {
967    let m = n - 1;
968    if latest.iter().any(|&v| !(v > 0.0) || !v.is_finite())
969        || ldfs.iter().any(|&f| !(f > 1.0) || !f.is_finite())
970    {
971        return None;
972    }
973
974    // Rank-1 factorization μ_{i,j} = α_i · β_j with sum_j β_j = 1.
975    let mut cdfs_to_last = vec![0.0; n];
976    cdfs_from_ldfs(ldfs, 1.0, &mut cdfs_to_last);
977    let mut b_cum = vec![0.0; n];
978    let mut beta = vec![0.0; n];
979    for j in 0..n {
980        let inv_cdf = 1.0 / cdfs_to_last[j];
981        if !inv_cdf.is_finite() || !(inv_cdf > 0.0) {
982            return None;
983        }
984        b_cum[j] = inv_cdf;
985        beta[j] = if j == 0 {
986            inv_cdf
987        } else {
988            inv_cdf - b_cum[j - 1]
989        };
990        if !(beta[j] > 0.0) || !beta[j].is_finite() {
991            return None;
992        }
993    }
994
995    let mut alpha = vec![0.0; n];
996    for i in 0..n {
997        let a = fitted_cumulative[i * n + m];
998        if !(a > 0.0) || !a.is_finite() {
999            return None;
1000        }
1001        alpha[i] = a;
1002    }
1003
1004    // A[k] = sum_{i=0}^{n-1-k} α_i.
1005    let mut a_sum = vec![0.0; n];
1006    let mut acc = 0.0;
1007    for k in (0..n).rev() {
1008        acc += alpha[m - k];
1009        a_sum[k] = acc;
1010    }
1011
1012    // Assemble symmetric tridiagonal K of dimension m = n - 1 (indices 0..m correspond to k = 1..n).
1013    let mut d = vec![0.0; m];
1014    let mut e = vec![0.0; m.saturating_sub(1)];
1015    for k in 1..n {
1016        let idx = k - 1;
1017        if k < m {
1018            let off = a_sum[k + 1] / beta[k + 1];
1019            d[idx] = a_sum[k] / beta[k] + off - alpha[m - k] / b_cum[k];
1020            e[idx] = -off;
1021        } else {
1022            d[idx] = a_sum[k] / beta[k] - alpha[0] / b_cum[k];
1023        }
1024    }
1025
1026    // Forward L D L^T sweep in O(n): L_{idx+1, idx} = -gamma[idx].
1027    let mut d_tilde = vec![0.0; m];
1028    let mut gamma = vec![0.0; m.saturating_sub(1)];
1029    if !d[0].is_finite() || d[0] <= 0.0 {
1030        return None;
1031    }
1032    d_tilde[0] = d[0];
1033    for idx in 0..(m - 1) {
1034        let g = -e[idx] / d_tilde[idx];
1035        let next_dt = d[idx + 1] + e[idx] * g;
1036        if !g.is_finite() || !next_dt.is_finite() || next_dt <= 1e-14 * d[idx + 1].abs().max(1e-30)
1037        {
1038            return None;
1039        }
1040        gamma[idx] = g;
1041        d_tilde[idx + 1] = next_dt;
1042    }
1043
1044    // Backward diagonal recurrence for G = K^{-1} in O(n) (sum of positive squares).
1045    let mut g_diag = vec![0.0; m];
1046    g_diag[m - 1] = 1.0 / d_tilde[m - 1];
1047    for idx in (0..(m - 1)).rev() {
1048        g_diag[idx] = 1.0 / d_tilde[idx] + gamma[idx] * gamma[idx] * g_diag[idx + 1];
1049    }
1050
1051    // Precompute w_j^T G w_j for j = 1..n in O(n).
1052    let mut w_g_w = vec![0.0; n];
1053    w_g_w[1] = g_diag[0] / (beta[1] * beta[1]);
1054    for j in 2..n {
1055        let g_jm1_j = gamma[j - 2] * g_diag[j - 1];
1056        w_g_w[j] = (g_diag[j - 1] - 2.0 * g_jm1_j + g_diag[j - 2]) / (beta[j] * beta[j]);
1057    }
1058
1059    // Compute all N = n(n+1)/2 residuals & exact leverages in row-major order in O(n^2).
1060    let n_observed = n * (n + 1) / 2;
1061    let rank = 2 * n - 1;
1062    let degrees_of_freedom = n_observed - rank;
1063    let mut residuals = Vec::with_capacity(n_observed);
1064    let mut pearson_sq_sum = 0.0;
1065    let mut g_row = vec![0.0; n];
1066
1067    for origin in 0..n {
1068        let ki = m - origin;
1069        if ki >= 1 {
1070            g_row[ki] = g_diag[ki - 1];
1071            for j in (1..ki).rev() {
1072                g_row[j] = gamma[j - 1] * g_row[j + 1];
1073            }
1074        }
1075        let inv_b_ki = 1.0 / b_cum[ki];
1076        let base_phi = inv_b_ki / alpha[origin];
1077        let z_g_z = if ki >= 1 {
1078            g_diag[ki - 1] * inv_b_ki * inv_b_ki
1079        } else {
1080            0.0
1081        };
1082        let row_off = origin * n;
1083
1084        for dev in 0..=ki {
1085            let obs = observed_incremental[row_off + dev];
1086            let mu = fitted_incremental[row_off + dev];
1087            if !(mu > 0.0) || !mu.is_finite() {
1088                return None;
1089            }
1090            let raw_residual = (obs - mu) / mu.sqrt();
1091            pearson_sq_sum += raw_residual * raw_residual;
1092
1093            let y_g_y = if dev == 0 {
1094                z_g_z
1095            } else if dev == 1 {
1096                let w_g_z = -g_row[1] * inv_b_ki / beta[1];
1097                w_g_w[1] + 2.0 * w_g_z + z_g_z
1098            } else {
1099                let w_g_z = -(g_row[dev] - g_row[dev - 1]) * inv_b_ki / beta[dev];
1100                w_g_w[dev] + 2.0 * w_g_z + z_g_z
1101            };
1102            let leverage = (mu * (base_phi + y_g_y)).clamp(0.0, 1.0);
1103            let saturated = (1.0 - leverage) <= 1e-10;
1104
1105            residuals.push(OdpCellResidual {
1106                origin,
1107                dev,
1108                observed_incremental: obs,
1109                fitted_incremental: mu,
1110                raw_pearson_residual: raw_residual,
1111                leverage,
1112                saturated,
1113            });
1114        }
1115    }
1116
1117    let dispersion = pearson_sq_sum / degrees_of_freedom as f64;
1118
1119    // Precompute column G[k, m-1] for k = 0..m in O(n).
1120    let mut g_last = vec![0.0; m];
1121    g_last[m - 1] = g_diag[m - 1];
1122    for idx in (0..(m - 1)).rev() {
1123        g_last[idx] = gamma[idx] * g_last[idx + 1];
1124    }
1125
1126    // Closed-form O(n) origin reserves & analytic prediction errors.
1127    let mut origin_reserves = vec![0.0; n];
1128    let mut analytic_origin_process_se = vec![0.0; n];
1129    let mut analytic_origin_param_se = vec![0.0; n];
1130    let mut analytic_origin_prediction_error = vec![0.0; n];
1131    let mut pre_tail_total_reserve = 0.0;
1132    let mut r_diag_sum = 0.0;
1133    let g_mm = g_diag[m - 1];
1134
1135    for origin in 0..n {
1136        let ki = m - origin;
1137        let ai = alpha[origin];
1138        let r_pre_tail = if origin == 0 {
1139            0.0
1140        } else {
1141            ai * (1.0 - b_cum[ki])
1142        };
1143        pre_tail_total_reserve += r_pre_tail;
1144        let tail_increment = ai * (tail - 1.0);
1145        origin_reserves[origin] = r_pre_tail + tail_increment;
1146
1147        let param_quad = if origin == 0 {
1148            0.0
1149        } else if origin < m {
1150            let inv_b = 1.0 / b_cum[ki];
1151            let diag_term = (r_pre_tail * r_pre_tail) * inv_b / ai;
1152            r_diag_sum += diag_term;
1153            diag_term
1154                + ai * ai * (g_diag[ki - 1] * inv_b * inv_b - 2.0 * g_last[ki - 1] * inv_b + g_mm)
1155        } else {
1156            let diag_term = (r_pre_tail * r_pre_tail) / (ai * b_cum[0]);
1157            r_diag_sum += diag_term;
1158            diag_term + ai * ai * g_mm
1159        };
1160        let param_var = (dispersion * param_quad).max(0.0);
1161        let proc_var = (dispersion * r_pre_tail).max(0.0);
1162        analytic_origin_process_se[origin] = proc_var.sqrt();
1163        analytic_origin_param_se[origin] = param_var.sqrt();
1164        analytic_origin_prediction_error[origin] = (proc_var + param_var).sqrt();
1165    }
1166
1167    // Portfolio total parameter variance via one O(n) forward pass: y^T K^{-1} y = z^T D_tilde^{-1} z.
1168    let mut total_quad = r_diag_sum;
1169    let mut z_prev = 0.0;
1170    for idx in 0..m {
1171        let k = idx + 1;
1172        let y_k = if k < m {
1173            -alpha[m - k] / b_cum[k]
1174        } else {
1175            a_sum[0] - alpha[0]
1176        };
1177        let z_k = if idx == 0 {
1178            y_k
1179        } else {
1180            y_k + gamma[idx - 1] * z_prev
1181        };
1182        total_quad += (z_k * z_k) / d_tilde[idx];
1183        z_prev = z_k;
1184    }
1185
1186    let total_reserve: f64 = origin_reserves.iter().sum();
1187    let total_param_var = (dispersion * total_quad).max(0.0);
1188    let total_proc_var = (dispersion * pre_tail_total_reserve).max(0.0);
1189
1190    Some(OdpSolvedDiagnostics {
1191        residuals,
1192        n_observed,
1193        rank,
1194        degrees_of_freedom,
1195        dispersion,
1196        origin_reserves,
1197        total_reserve,
1198        analytic_origin_process_se,
1199        analytic_origin_param_se,
1200        analytic_origin_prediction_error,
1201        analytic_total_process_se: total_proc_var.sqrt(),
1202        analytic_total_param_se: total_param_var.sqrt(),
1203        analytic_total_prediction_error: (total_proc_var + total_param_var).sqrt(),
1204    })
1205}
1206
1207/// General `O(n^3)` fallback for triangles with zero-mass fitted cells (e.g., an
1208/// LDF equal to `1.0` or a zero origin row). Uses `invert_spd` once in `O(p^3)`
1209/// and computes each hat-matrix leverage in `O(1)` via 3-sparse lookups (`O(N)`
1210/// total rather than `O(N p^2)`).
1211fn solve_odp_general(
1212    n: usize,
1213    tail: f64,
1214    fitted_cumulative: &[f64],
1215    fitted_incremental: &[f64],
1216    observed_incremental: &[f64],
1217) -> Result<OdpSolvedDiagnostics, ValidationError> {
1218    let mut active_origins = vec![false; n];
1219    let mut active_devs = vec![false; n];
1220    let mut active_cells: Vec<(usize, usize)> = Vec::with_capacity(n * (n + 1) / 2);
1221    for origin in 0..n {
1222        for dev in 0..(n - origin) {
1223            let mu = fitted_incremental[origin * n + dev];
1224            if mu.is_finite() && mu > 0.0 {
1225                active_origins[origin] = true;
1226                active_devs[dev] = true;
1227                active_cells.push((origin, dev));
1228            }
1229        }
1230    }
1231
1232    let mut origin_col = vec![None; n];
1233    let mut dev_col = vec![None; n];
1234    let mut param_count = 1usize;
1235    let mut first_origin_skipped = false;
1236    for origin in 0..n {
1237        if active_origins[origin] {
1238            if first_origin_skipped {
1239                origin_col[origin] = Some(param_count);
1240                param_count += 1;
1241            } else {
1242                first_origin_skipped = true;
1243            }
1244        }
1245    }
1246    let mut first_dev_skipped = false;
1247    for dev in 0..n {
1248        if active_devs[dev] {
1249            if first_dev_skipped {
1250                dev_col[dev] = Some(param_count);
1251                param_count += 1;
1252            } else {
1253                first_dev_skipped = true;
1254            }
1255        }
1256    }
1257
1258    let n_observed = active_cells.len();
1259    if n_observed <= param_count {
1260        return Err(ValidationError::InvalidParameter(
1261            "ODP model has non-positive residual degrees of freedom",
1262        ));
1263    }
1264    let degrees_of_freedom = n_observed - param_count;
1265
1266    // Assemble Fisher information matrix M = X^T W X in O(N).
1267    let mut info = vec![0.0; param_count * param_count];
1268    for &(origin, dev) in &active_cells {
1269        let w = fitted_incremental[origin * n + dev];
1270        let mut cols = [0usize; 3];
1271        let mut ncols = 1usize;
1272        if let Some(c) = origin_col[origin] {
1273            cols[ncols] = c;
1274            ncols += 1;
1275        }
1276        if let Some(c) = dev_col[dev] {
1277            cols[ncols] = c;
1278            ncols += 1;
1279        }
1280        for a in 0..ncols {
1281            for b in 0..ncols {
1282                info[cols[a] * param_count + cols[b]] += w;
1283            }
1284        }
1285    }
1286
1287    let chol = cholesky_lower(&info, param_count)?;
1288    let info_inv = invert_spd(&info, param_count)?;
1289
1290    // Exact hat-matrix leverages in O(1) per cell via 3-sparse quadratic form x^T M^{-1} x.
1291    let mut residuals = Vec::with_capacity(n_observed);
1292    let mut pearson_sq_sum = 0.0;
1293    for &(origin, dev) in &active_cells {
1294        let obs = observed_incremental[origin * n + dev];
1295        let mu = fitted_incremental[origin * n + dev];
1296        let raw_residual = (obs - mu) / mu.sqrt();
1297        pearson_sq_sum += raw_residual * raw_residual;
1298
1299        let mut cols = [0usize; 3];
1300        let mut ncols = 1usize;
1301        if let Some(c) = origin_col[origin] {
1302            cols[ncols] = c;
1303            ncols += 1;
1304        }
1305        if let Some(c) = dev_col[dev] {
1306            cols[ncols] = c;
1307            ncols += 1;
1308        }
1309        let mut qf = 0.0;
1310        for a in 0..ncols {
1311            let ca = cols[a];
1312            qf += info_inv[ca * param_count + ca];
1313            for b in (a + 1)..ncols {
1314                qf += 2.0 * info_inv[ca * param_count + cols[b]];
1315            }
1316        }
1317        let leverage = (mu * qf).clamp(0.0, 1.0);
1318        let saturated = (1.0 - leverage) <= 1e-10;
1319
1320        residuals.push(OdpCellResidual {
1321            origin,
1322            dev,
1323            observed_incremental: obs,
1324            fitted_incremental: mu,
1325            raw_pearson_residual: raw_residual,
1326            leverage,
1327            saturated,
1328        });
1329    }
1330
1331    let dispersion = pearson_sq_sum / degrees_of_freedom as f64;
1332
1333    let mut origin_reserves = vec![0.0; n];
1334    let mut analytic_origin_process_se = vec![0.0; n];
1335    let mut analytic_origin_param_se = vec![0.0; n];
1336    let mut analytic_origin_prediction_error = vec![0.0; n];
1337    let mut g_total = vec![0.0; param_count];
1338    let mut g_origin = vec![0.0; param_count];
1339    let mut y_buf = vec![0.0; param_count];
1340    let mut pre_tail_total_reserve = 0.0;
1341
1342    for origin in 0..n {
1343        g_origin.fill(0.0);
1344        let mut r_pre_tail = 0.0;
1345        for dev in (n - origin)..n {
1346            let mu = fitted_incremental[origin * n + dev];
1347            r_pre_tail += mu;
1348            g_origin[0] += mu;
1349            g_total[0] += mu;
1350            if let Some(c) = origin_col[origin] {
1351                g_origin[c] += mu;
1352                g_total[c] += mu;
1353            }
1354            if let Some(c) = dev_col[dev] {
1355                g_origin[c] += mu;
1356                g_total[c] += mu;
1357            }
1358        }
1359        pre_tail_total_reserve += r_pre_tail;
1360        let tail_increment = fitted_cumulative[origin * n + (n - 1)] * (tail - 1.0);
1361        origin_reserves[origin] = r_pre_tail + tail_increment;
1362
1363        solve_lower_into(&chol, param_count, &g_origin, &mut y_buf);
1364        let param_var = (dispersion * y_buf.iter().map(|v| v * v).sum::<f64>()).max(0.0);
1365        let proc_var = (dispersion * r_pre_tail).max(0.0);
1366        analytic_origin_process_se[origin] = proc_var.sqrt();
1367        analytic_origin_param_se[origin] = param_var.sqrt();
1368        analytic_origin_prediction_error[origin] = (proc_var + param_var).sqrt();
1369    }
1370
1371    let total_reserve: f64 = origin_reserves.iter().sum();
1372    solve_lower_into(&chol, param_count, &g_total, &mut y_buf);
1373    let total_param_var = (dispersion * y_buf.iter().map(|v| v * v).sum::<f64>()).max(0.0);
1374    let total_proc_var = (dispersion * pre_tail_total_reserve).max(0.0);
1375
1376    Ok(OdpSolvedDiagnostics {
1377        residuals,
1378        n_observed,
1379        rank: param_count,
1380        degrees_of_freedom,
1381        dispersion,
1382        origin_reserves,
1383        total_reserve,
1384        analytic_origin_process_se,
1385        analytic_origin_param_se,
1386        analytic_origin_prediction_error,
1387        analytic_total_process_se: total_proc_var.sqrt(),
1388        analytic_total_param_se: total_param_var.sqrt(),
1389        analytic_total_prediction_error: (total_proc_var + total_param_var).sqrt(),
1390    })
1391}
1392
1393/// Fit the Over-Dispersed Poisson GLM (`log μ_{i,j} = c + α_i + β_j`) to a
1394/// cumulative loss triangle.
1395///
1396/// Produces fitted expectations, unscaled Pearson residuals, exact GLM hat-
1397/// matrix diagonal leverages `h_{ii}`, Pearson dispersion `φ`, and England &
1398/// Verrall (1999, 2002) analytic prediction errors.
1399pub fn fit_odp(
1400    triangle: &TriangleView<'_>,
1401    tail: f64,
1402    policy: MonotonicityPolicy,
1403) -> Result<OdpFit, ValidationError> {
1404    validate_triangle(triangle)?;
1405    if policy == MonotonicityPolicy::Strict {
1406        validate_monotone_cumulative(triangle)?;
1407    }
1408    validate_tail(tail)?;
1409
1410    let n = triangle.n_origins;
1411    if n < 3 {
1412        return Err(ValidationError::InvalidParameter(
1413            "ODP model requires at least a 3x3 triangle for positive degrees of freedom",
1414        ));
1415    }
1416
1417    // Single-pass volume-weighted LDFs without duplicating triangle validation.
1418    let mut ldfs = vec![0.0; n - 1];
1419    volume_weighted_ldfs(triangle.data, n, n, &mut ldfs);
1420    for &f in &ldfs {
1421        if !f.is_finite() {
1422            return Err(ValidationError::NotFinite);
1423        }
1424        if f <= 0.0 {
1425            return Err(ValidationError::DivideByZero("development denominator"));
1426        }
1427        if f < 1.0 {
1428            return Err(ValidationError::InvalidParameter(
1429                "ODP GLM requires non-negative fitted expectations (all volume-weighted LDFs >= 1.0)",
1430            ));
1431        }
1432    }
1433
1434    let observed_incremental = cumulative_to_incremental(triangle);
1435    let latest = latest_diagonal(triangle);
1436
1437    // Exact ODP GLM MLE via backward + forward chain-ladder recursion in O(n^2).
1438    let mut fitted_cumulative = vec![0.0; n * n];
1439    for origin in 0..n {
1440        let d = n - 1 - origin;
1441        let row_off = origin * n;
1442        fitted_cumulative[row_off + d] = latest[origin];
1443        for dev in (0..d).rev() {
1444            fitted_cumulative[row_off + dev] = fitted_cumulative[row_off + dev + 1] / ldfs[dev];
1445        }
1446        for dev in (d + 1)..n {
1447            fitted_cumulative[row_off + dev] = fitted_cumulative[row_off + dev - 1] * ldfs[dev - 1];
1448        }
1449    }
1450
1451    let mut fitted_incremental = vec![0.0; n * n];
1452    for origin in 0..n {
1453        let row_off = origin * n;
1454        fitted_incremental[row_off] = fitted_cumulative[row_off];
1455        for dev in 1..n {
1456            fitted_incremental[row_off + dev] =
1457                fitted_cumulative[row_off + dev] - fitted_cumulative[row_off + dev - 1];
1458        }
1459    }
1460
1461    let solved = match try_solve_odp_tridiagonal(
1462        n,
1463        &ldfs,
1464        tail,
1465        &latest,
1466        &fitted_cumulative,
1467        &fitted_incremental,
1468        &observed_incremental,
1469    ) {
1470        Some(fast) => fast,
1471        None => solve_odp_general(
1472            n,
1473            tail,
1474            &fitted_cumulative,
1475            &fitted_incremental,
1476            &observed_incremental,
1477        )?,
1478    };
1479
1480    Ok(OdpFit {
1481        n_origins: n,
1482        n_devs: n,
1483        ldfs,
1484        tail,
1485        fitted_cumulative,
1486        fitted_incremental,
1487        observed_incremental,
1488        residuals: solved.residuals,
1489        n_observed: solved.n_observed,
1490        rank: solved.rank,
1491        degrees_of_freedom: solved.degrees_of_freedom,
1492        dispersion: solved.dispersion,
1493        origin_reserves: solved.origin_reserves,
1494        total_reserve: solved.total_reserve,
1495        analytic_origin_process_se: solved.analytic_origin_process_se,
1496        analytic_origin_param_se: solved.analytic_origin_param_se,
1497        analytic_origin_prediction_error: solved.analytic_origin_prediction_error,
1498        analytic_total_process_se: solved.analytic_total_process_se,
1499        analytic_total_param_se: solved.analytic_total_param_se,
1500        analytic_total_prediction_error: solved.analytic_total_prediction_error,
1501    })
1502}
1503
1504/// Build the adjusted residual pool for resampling along with its pre-centering mean.
1505pub(crate) fn build_adjusted_residual_pool(
1506    fit: &OdpFit,
1507    adjustment: ResidualAdjustment,
1508    center: bool,
1509) -> Result<(Vec<f64>, f64), ValidationError> {
1510    let mut pool = Vec::with_capacity(fit.residuals.len());
1511    match adjustment {
1512        ResidualAdjustment::DegreesOfFreedom => {
1513            let scale = (fit.n_observed as f64 / fit.degrees_of_freedom as f64).sqrt();
1514            for cell in &fit.residuals {
1515                pool.push(cell.raw_pearson_residual * scale);
1516            }
1517        }
1518        ResidualAdjustment::HatMatrixLeverage => {
1519            for cell in &fit.residuals {
1520                if !cell.saturated {
1521                    pool.push(cell.raw_pearson_residual / (1.0 - cell.leverage).sqrt());
1522                }
1523            }
1524        }
1525    }
1526    if pool.is_empty() {
1527        return Err(ValidationError::InvalidParameter(
1528            "no eligible residuals available for ODP bootstrap resampling",
1529        ));
1530    }
1531    let pool_mean = pool.iter().sum::<f64>() / pool.len() as f64;
1532    if center {
1533        for r in &mut pool {
1534            *r -= pool_mean;
1535        }
1536    }
1537    Ok((pool, pool_mean))
1538}
1539
1540/// Compact reusable scratch buffers for zero-allocation, single-pass ODP
1541/// bootstrap iterations.
1542///
1543/// Packs only the `N = n(n+1)/2` upper-triangle `sqrt(mu)` values (half the
1544/// memory of an `n × n` grid), precomputes baseline column denominators and
1545/// latest-diagonal sums so the hot loop accumulates only zero-mean FMA deltas,
1546/// and eliminates the `col_num` array via `col_num[k] = col_den[k+1] + latest_pseudo[m-1-k]`.
1547pub(crate) struct OdpBootstrapScratch {
1548    n: usize,
1549    all_observed_positive: bool,
1550    inv_phi: f64,
1551    packed_sqrt_mu: Vec<f64>,
1552    cell_deltas: Vec<f64>,
1553    base_col_den: Vec<f64>,
1554    base_latest: Vec<f64>,
1555    delta_col_den: Vec<f64>,
1556    latest_pseudo: Vec<f64>,
1557    pseudo_ldfs: Vec<f64>,
1558    origin_reserves: Vec<f64>,
1559}
1560
1561impl OdpBootstrapScratch {
1562    pub(crate) fn for_fit(fit: &OdpFit) -> Self {
1563        let n = fit.n_origins;
1564        let m = n.saturating_sub(1);
1565        let upper_len = n * (n + 1) / 2;
1566        let mut packed_sqrt_mu = Vec::with_capacity(upper_len);
1567        let mut base_col_den = vec![0.0; m];
1568        let mut base_latest = vec![0.0; n];
1569
1570        for origin in 0..n {
1571            let row_off = origin * n;
1572            let last_dev = n - 1 - origin;
1573            for dev in 0..=last_dev {
1574                let mu = fit.fitted_incremental[row_off + dev];
1575                packed_sqrt_mu.push(if mu > 0.0 { mu.sqrt() } else { 0.0 });
1576                if dev < last_dev {
1577                    base_col_den[dev] += fit.fitted_cumulative[row_off + dev];
1578                }
1579            }
1580            base_latest[origin] = fit.fitted_cumulative[row_off + last_dev];
1581        }
1582
1583        let inv_phi = if fit.dispersion > 0.0 && fit.dispersion.is_finite() {
1584            1.0 / fit.dispersion
1585        } else {
1586            0.0
1587        };
1588
1589        Self {
1590            n,
1591            all_observed_positive: fit.n_observed == upper_len,
1592            inv_phi,
1593            packed_sqrt_mu,
1594            cell_deltas: vec![0.0; upper_len],
1595            base_col_den,
1596            base_latest,
1597            delta_col_den: vec![0.0; m],
1598            latest_pseudo: vec![0.0; n],
1599            pseudo_ldfs: vec![0.0; m],
1600            origin_reserves: vec![0.0; n],
1601        }
1602    }
1603}
1604
1605#[derive(Clone, Copy)]
1606struct RefitOutcome {
1607    valid: bool,
1608    all_ldfs_ge_one: bool,
1609}
1610
1611/// Complete volume-weighted LDF computation from `delta_col_den` + `latest_pseudo`
1612/// in a single right-to-left `O(n)` pass using `col_num[k] = col_den[k+1] + latest_pseudo[m-1-k]`.
1613#[inline]
1614fn finalize_pseudo_ldfs(scratch: &mut OdpBootstrapScratch) -> RefitOutcome {
1615    let m = scratch.n.saturating_sub(1);
1616    let mut all_ge_one = true;
1617    let mut next_den = 0.0;
1618    for k in (0..m).rev() {
1619        let den = scratch.base_col_den[k] + scratch.delta_col_den[k];
1620        if !(den > 0.0) || !den.is_finite() {
1621            return RefitOutcome {
1622                valid: false,
1623                all_ldfs_ge_one: false,
1624            };
1625        }
1626        let num = next_den + scratch.latest_pseudo[m - 1 - k];
1627        let f = num / den;
1628        if !f.is_finite() || f <= 0.0 {
1629            return RefitOutcome {
1630                valid: false,
1631                all_ldfs_ge_one: false,
1632            };
1633        }
1634        if f < 1.0 {
1635            all_ge_one = false;
1636        }
1637        scratch.pseudo_ldfs[k] = f;
1638        next_den = den;
1639    }
1640    RefitOutcome {
1641        valid: true,
1642        all_ldfs_ge_one: all_ge_one,
1643    }
1644}
1645
1646/// Accumulate zero-mean cell perturbations `cell_deltas[0..N]` into
1647/// `delta_col_den[0..m]` and `latest_pseudo[0..n]` using paired origin rows
1648/// (breaking the serial `running += d` FP latency chain into 2 parallel pipes
1649/// and halving `delta_den` store traffic), then finalize volume-weighted LDFs.
1650#[inline]
1651fn accumulate_cell_deltas_and_refit(scratch: &mut OdpBootstrapScratch) -> RefitOutcome {
1652    let n = scratch.n;
1653    let m = n.saturating_sub(1);
1654    let deltas = &scratch.cell_deltas;
1655    let delta_den = &mut scratch.delta_col_den;
1656    let latest_out = &mut scratch.latest_pseudo;
1657    let base_latest = &scratch.base_latest;
1658
1659    // Pair origins (0, 1) to overwrite delta_den[0..m] directly (no fill(0.0)).
1660    // Note: fit_odp guarantees n >= 3 so m >= 2.
1661    let mut row_start = 0usize;
1662    let mut origin = 0usize;
1663    if m >= 2 {
1664        let r0 = &deltas[0..n];
1665        let r1 = &deltas[n..2 * n - 1];
1666        row_start = 2 * n - 1;
1667        let mut run0 = 0.0;
1668        let mut run1 = 0.0;
1669        for (den_slot, (&d0, &d1)) in delta_den[..m - 1]
1670            .iter_mut()
1671            .zip(r0[..m - 1].iter().zip(r1[..m - 1].iter()))
1672        {
1673            run0 += d0;
1674            run1 += d1;
1675            *den_slot = run0 + run1;
1676        }
1677        run0 += r0[m - 1];
1678        delta_den[m - 1] = run0;
1679        latest_out[0] = base_latest[0] + run0 + r0[m];
1680        latest_out[1] = base_latest[1] + run1 + r1[m - 1];
1681        origin = 2;
1682    } else if m == 1 {
1683        let d0 = deltas[0];
1684        delta_den[0] = d0;
1685        latest_out[0] = base_latest[0] + d0 + deltas[1];
1686        row_start = 2;
1687        origin = 1;
1688    }
1689
1690    // Remaining origin pairs (origin, origin + 1) while origin + 1 < m.
1691    while origin + 1 < m {
1692        let len_a = n - origin; // last_dev_a + 1 = m - origin + 1
1693        let len_b = len_a - 1; // last_dev_b + 1 = m - origin
1694        let ra = &deltas[row_start..row_start + len_a];
1695        let rb = &deltas[row_start + len_a..row_start + len_a + len_b];
1696        row_start += len_a + len_b;
1697
1698        let last_a = len_a - 1;
1699        let last_b = len_b - 1;
1700        let mut run_a = 0.0;
1701        let mut run_b = 0.0;
1702        for (den_slot, (&da, &db)) in delta_den[..last_b]
1703            .iter_mut()
1704            .zip(ra[..last_b].iter().zip(rb[..last_b].iter()))
1705        {
1706            run_a += da;
1707            run_b += db;
1708            *den_slot += run_a + run_b;
1709        }
1710        run_a += ra[last_b];
1711        delta_den[last_b] += run_a;
1712        latest_out[origin] = base_latest[origin] + run_a + ra[last_a];
1713        latest_out[origin + 1] = base_latest[origin + 1] + run_b + rb[last_b];
1714        origin += 2;
1715    }
1716
1717    if origin < m {
1718        let last_dev = m - origin;
1719        let row = &deltas[row_start..=(row_start + last_dev)];
1720        row_start += last_dev + 1;
1721        let mut running = 0.0;
1722        for (den_slot, &d) in delta_den[..last_dev].iter_mut().zip(&row[..last_dev]) {
1723            running += d;
1724            *den_slot += running;
1725        }
1726        latest_out[origin] = base_latest[origin] + running + row[last_dev];
1727    }
1728    latest_out[m] = base_latest[m] + deltas[row_start];
1729
1730    finalize_pseudo_ldfs(scratch)
1731}
1732
1733/// Fused 4-wide batched resampling (`pool[idx] * sqrt_mu`) + bounds-check-free
1734/// delta accumulation + LDF refit.
1735#[inline]
1736fn refit_pseudo_ldfs_from_pool(
1737    pool: &[f64],
1738    sampler: &mut FastIndexSampler,
1739    rng: &mut DeterministicRng,
1740    scratch: &mut OdpBootstrapScratch,
1741) -> RefitOutcome {
1742    if scratch.all_observed_positive {
1743        sampler.fill_weighted_deltas(pool, &scratch.packed_sqrt_mu, rng, &mut scratch.cell_deltas);
1744        return accumulate_cell_deltas_and_refit(scratch);
1745    }
1746
1747    // General path when some observed cells have zero fitted mass (`sm == 0.0`).
1748    for (dst, &sm) in scratch
1749        .cell_deltas
1750        .iter_mut()
1751        .zip(scratch.packed_sqrt_mu.iter())
1752    {
1753        *dst = if sm > 0.0 {
1754            pool[sampler.next(rng)] * sm
1755        } else {
1756            0.0
1757        };
1758    }
1759    accumulate_cell_deltas_and_refit(scratch)
1760}
1761
1762/// Fused single-pass pseudo-triangle delta accumulation + LDF refit from an
1763/// externally supplied residual slice (used by synchronized multi-line bootstrap).
1764#[inline]
1765fn refit_pseudo_ldfs_from_slice(
1766    sampled_residuals: &[f64],
1767    scratch: &mut OdpBootstrapScratch,
1768) -> RefitOutcome {
1769    if scratch.all_observed_positive {
1770        for ((dst, &r), &sm) in scratch
1771            .cell_deltas
1772            .iter_mut()
1773            .zip(sampled_residuals.iter())
1774            .zip(scratch.packed_sqrt_mu.iter())
1775        {
1776            *dst = r * sm;
1777        }
1778        return accumulate_cell_deltas_and_refit(scratch);
1779    }
1780
1781    let mut r_idx = 0usize;
1782    for (dst, &sm) in scratch
1783        .cell_deltas
1784        .iter_mut()
1785        .zip(scratch.packed_sqrt_mu.iter())
1786    {
1787        if sm > 0.0 {
1788            *dst = sampled_residuals[r_idx] * sm;
1789            r_idx += 1;
1790        } else {
1791            *dst = 0.0;
1792        }
1793    }
1794    accumulate_cell_deltas_and_refit(scratch)
1795}
1796
1797#[inline]
1798fn sample_positive_process(
1799    mag: f64,
1800    phi: f64,
1801    inv_phi: f64,
1802    dist: ProcessDistribution,
1803    rng: &mut DeterministicRng,
1804) -> f64 {
1805    if !(phi > 0.0) || !(mag > 0.0) || !mag.is_finite() {
1806        return mag;
1807    }
1808    match dist {
1809        ProcessDistribution::Gamma => rng.sample_gamma(mag * inv_phi, phi),
1810        ProcessDistribution::OverDispersedPoisson => phi * rng.sample_poisson(mag * inv_phi),
1811        ProcessDistribution::None => mag,
1812    }
1813}
1814
1815#[inline]
1816fn sample_process_increment_fast(
1817    future_mu: f64,
1818    phi: f64,
1819    inv_phi: f64,
1820    dist: ProcessDistribution,
1821    rng: &mut DeterministicRng,
1822) -> f64 {
1823    if !(phi > 0.0) || future_mu == 0.0 || !future_mu.is_finite() {
1824        return future_mu;
1825    }
1826    // Per Shapland (2016) §3.5.3, preserve process variance on negative pseudo-
1827    // incremental expectations by reflecting the draw: -Sample(|mu|, phi).
1828    let sign = if future_mu < 0.0 { -1.0 } else { 1.0 };
1829    let mag = future_mu.abs();
1830    let draw = match dist {
1831        ProcessDistribution::Gamma => rng.sample_gamma(mag * inv_phi, phi),
1832        ProcessDistribution::OverDispersedPoisson => phi * rng.sample_poisson(mag * inv_phi),
1833        ProcessDistribution::None => mag,
1834    };
1835    sign * draw
1836}
1837
1838/// Project per-origin reserves and sample exact process variance in `O(n)`.
1839///
1840/// Exploits the reproductive additivity of Gamma(`shape_j`, `φ`) and
1841/// `φ · Poisson(λ_j)` under common dispersion `φ` so each open origin requires
1842/// 1 draw (2 when negative pseudo-LDFs create both positive and negative future
1843/// increments) instead of `O(n)` cell-level draws (`O(n^2)` total).
1844///
1845/// Writes `scratch.origin_reserves[0..n]` and returns `Some(total_reserve)`.
1846#[inline]
1847fn project_origin_reserves(
1848    tail: f64,
1849    phi: f64,
1850    all_ldfs_ge_one: bool,
1851    process_distribution: ProcessDistribution,
1852    rng: &mut DeterministicRng,
1853    scratch: &mut OdpBootstrapScratch,
1854) -> Option<f64> {
1855    let n = scratch.n;
1856    let inv_phi = scratch.inv_phi;
1857    let tail_inc = tail - 1.0;
1858
1859    if all_ldfs_ge_one || process_distribution == ProcessDistribution::None {
1860        // Walking origin = 0..n traverses latest_dev = n-1 down to 0, so a single
1861        // register `cdf` compounds pseudo-LDFs right-to-left with zero arrays.
1862        let mut cdf = tail;
1863        let l0 = scratch.latest_pseudo[0];
1864        if !l0.is_finite() {
1865            return None;
1866        }
1867        let r0 = if tail_inc > 0.0 {
1868            sample_process_increment_fast(l0 * tail_inc, phi, inv_phi, process_distribution, rng)
1869        } else {
1870            0.0
1871        };
1872        if !r0.is_finite() {
1873            return None;
1874        }
1875        scratch.origin_reserves[0] = r0;
1876        let mut total = r0;
1877
1878        match process_distribution {
1879            ProcessDistribution::Gamma if phi > 0.0 => {
1880                for origin in 1..n {
1881                    cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1882                    let latest_i = scratch.latest_pseudo[origin];
1883                    let expected_res = latest_i * (cdf - 1.0);
1884                    let res_i = if expected_res > 0.0 && expected_res.is_finite() {
1885                        let shape = expected_res * inv_phi;
1886                        if shape >= 1.0 {
1887                            rng.sample_gamma_ge1(shape) * phi
1888                        } else {
1889                            rng.sample_gamma(shape, phi)
1890                        }
1891                    } else if expected_res < 0.0 && expected_res.is_finite() {
1892                        -rng.sample_gamma(-expected_res * inv_phi, phi)
1893                    } else if expected_res == 0.0 {
1894                        0.0
1895                    } else {
1896                        return None;
1897                    };
1898                    scratch.origin_reserves[origin] = res_i;
1899                    total += res_i;
1900                }
1901            }
1902            ProcessDistribution::OverDispersedPoisson if phi > 0.0 => {
1903                for origin in 1..n {
1904                    cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1905                    let latest_i = scratch.latest_pseudo[origin];
1906                    if !latest_i.is_finite() {
1907                        return None;
1908                    }
1909                    let expected_res = latest_i * (cdf - 1.0);
1910                    let res_i = sample_process_increment_fast(
1911                        expected_res,
1912                        phi,
1913                        inv_phi,
1914                        ProcessDistribution::OverDispersedPoisson,
1915                        rng,
1916                    );
1917                    if !res_i.is_finite() {
1918                        return None;
1919                    }
1920                    scratch.origin_reserves[origin] = res_i;
1921                    total += res_i;
1922                }
1923            }
1924            _ => {
1925                for origin in 1..n {
1926                    cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1927                    let latest_i = scratch.latest_pseudo[origin];
1928                    let expected_res = latest_i * (cdf - 1.0);
1929                    if !expected_res.is_finite() {
1930                        return None;
1931                    }
1932                    scratch.origin_reserves[origin] = expected_res;
1933                    total += expected_res;
1934                }
1935            }
1936        }
1937        return total.is_finite().then_some(total);
1938    }
1939
1940    // General path when any pseudo-LDF < 1.0: track exact positive and negative
1941    // suffix increment factors in two registers (exact equivalence to Shapland
1942    // cell-by-cell reflection because every valid pseudo-LDF > 0 preserves signs).
1943    let mut pos_factor = tail_inc;
1944    let mut neg_factor = 0.0;
1945
1946    let l0 = scratch.latest_pseudo[0];
1947    if !l0.is_finite() {
1948        return None;
1949    }
1950    let r0 = if tail_inc > 0.0 {
1951        sample_process_increment_fast(l0 * tail_inc, phi, inv_phi, process_distribution, rng)
1952    } else {
1953        0.0
1954    };
1955    if !r0.is_finite() {
1956        return None;
1957    }
1958    scratch.origin_reserves[0] = r0;
1959    let mut total = r0;
1960
1961    for origin in 1..n {
1962        let f = scratch.pseudo_ldfs[n - 1 - origin];
1963        let step = f - 1.0;
1964        if step >= 0.0 {
1965            pos_factor = step + f * pos_factor;
1966            neg_factor *= f;
1967        } else {
1968            pos_factor *= f;
1969            neg_factor = (-step) + f * neg_factor;
1970        }
1971
1972        let latest_i = scratch.latest_pseudo[origin];
1973        if !latest_i.is_finite() {
1974            return None;
1975        }
1976        let (pos_mu, neg_mu) = if latest_i >= 0.0 {
1977            (latest_i * pos_factor, latest_i * neg_factor)
1978        } else {
1979            (-latest_i * neg_factor, -latest_i * pos_factor)
1980        };
1981        let pos_draw = if pos_mu > 0.0 {
1982            sample_positive_process(pos_mu, phi, inv_phi, process_distribution, rng)
1983        } else {
1984            0.0
1985        };
1986        let neg_draw = if neg_mu > 0.0 {
1987            sample_positive_process(neg_mu, phi, inv_phi, process_distribution, rng)
1988        } else {
1989            0.0
1990        };
1991        let res_i = pos_draw - neg_draw;
1992        if !res_i.is_finite() {
1993            return None;
1994        }
1995        scratch.origin_reserves[origin] = res_i;
1996        total += res_i;
1997    }
1998
1999    total.is_finite().then_some(total)
2000}
2001
2002/// Execute one ODP bootstrap iteration into reusable `scratch` buffers using an
2003/// externally supplied residual slice (used by synchronized multi-line bootstrap).
2004///
2005/// Returns `Some(&scratch.origin_reserves)` on valid refit or `None` if the
2006/// pseudo-triangle has a degenerate non-positive column sum.
2007pub(crate) fn run_odp_iteration_with_scratch<'a>(
2008    fit: &OdpFit,
2009    sampled_residuals: &[f64],
2010    process_distribution: ProcessDistribution,
2011    rng: &mut DeterministicRng,
2012    scratch: &'a mut OdpBootstrapScratch,
2013) -> Option<&'a [f64]> {
2014    let outcome = refit_pseudo_ldfs_from_slice(sampled_residuals, scratch);
2015    if !outcome.valid {
2016        return None;
2017    }
2018    project_origin_reserves(
2019        fit.tail,
2020        fit.dispersion,
2021        outcome.all_ldfs_ge_one,
2022        process_distribution,
2023        rng,
2024        scratch,
2025    )?;
2026    Some(&scratch.origin_reserves)
2027}
2028
2029/// Run the full England & Verrall (1999, 2002) / Shapland (2016) ODP bootstrap.
2030///
2031/// # Example
2032/// ```rust
2033/// use reserving_kernels::datasets::genins;
2034/// use reserving_kernels::prelude::*;
2035///
2036/// let tri = genins();
2037/// let opts = OdpBootstrapOptions {
2038///     iterations: 200,
2039///     seed: 42,
2040///     ..OdpBootstrapOptions::default()
2041/// };
2042/// let boot = bootstrap_odp(&tri.view(), 1.0, opts)?;
2043/// assert_eq!(boot.simulated_totals.len(), 200);
2044/// assert!(boot.base_total_reserve > 0.0);
2045/// # Ok::<(), ValidationError>(())
2046/// ```
2047pub fn bootstrap_odp(
2048    triangle: &TriangleView<'_>,
2049    tail: f64,
2050    options: OdpBootstrapOptions,
2051) -> Result<OdpBootstrapResult, ValidationError> {
2052    if options.iterations == 0 {
2053        return Err(ValidationError::ShapeMismatch);
2054    }
2055
2056    let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2057    let (pool, pool_mean) =
2058        build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2059
2060    let mut rng = DeterministicRng::from_seed(options.seed);
2061    let mut sampler = FastIndexSampler::new(pool.len());
2062    let n = fit.n_origins;
2063    let mut simulated_totals = Vec::with_capacity(options.iterations);
2064    let mut simulated_by_origin: Vec<Vec<f64>> = (0..n)
2065        .map(|_| Vec::with_capacity(options.iterations))
2066        .collect();
2067    let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2068    let mut failed_iterations = 0usize;
2069
2070    for _ in 0..options.iterations {
2071        let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2072        if !outcome.valid {
2073            failed_iterations += 1;
2074            continue;
2075        }
2076        if let Some(total) = project_origin_reserves(
2077            fit.tail,
2078            fit.dispersion,
2079            outcome.all_ldfs_ge_one,
2080            options.process_distribution,
2081            &mut rng,
2082            &mut scratch,
2083        ) {
2084            simulated_totals.push(total);
2085            for (origin_vec, &r) in simulated_by_origin
2086                .iter_mut()
2087                .zip(scratch.origin_reserves.iter())
2088            {
2089                origin_vec.push(r);
2090            }
2091        } else {
2092            failed_iterations += 1;
2093        }
2094    }
2095
2096    if simulated_totals.is_empty() {
2097        return Err(ValidationError::NotFinite);
2098    }
2099
2100    // Reuse a single scratch buffer across portfolio + all n origin summaries
2101    // and skip redundant finiteness scans (every pushed value is verified finite).
2102    let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2103    let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2104    let mut origin_summaries = Vec::with_capacity(n);
2105    for series in &simulated_by_origin {
2106        origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2107    }
2108
2109    Ok(OdpBootstrapResult {
2110        base_total_reserve: fit.total_reserve,
2111        fit,
2112        options,
2113        simulated_totals,
2114        simulated_by_origin,
2115        origin_summaries,
2116        summary,
2117        failed_iterations,
2118        residual_pool_mean_before_centering: pool_mean,
2119    })
2120}
2121
2122/// Run a deterministic ODP bootstrap using the classic England & Verrall
2123/// (1999, 2002) specification (`DegreesOfFreedom` scaling + Gamma process variance).
2124///
2125/// Because this compact entry point only returns portfolio totals, it skips
2126/// allocating per-origin simulation series (`O(B)` space instead of `O(n B)`),
2127/// skips `n` per-origin summaries, and collapses process variance to 1–2 exact
2128/// Gamma draws per iteration.
2129pub fn bootstrap(
2130    triangle: &TriangleView<'_>,
2131    tail: f64,
2132    config: BootstrapConfig,
2133) -> Result<BootstrapResult, ValidationError> {
2134    if config.iterations == 0 {
2135        return Err(ValidationError::ShapeMismatch);
2136    }
2137
2138    let options = OdpBootstrapOptions::england_verrall(config.iterations, config.seed);
2139    let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2140    let (pool, _) =
2141        build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2142
2143    let mut rng = DeterministicRng::from_seed(options.seed);
2144    let mut sampler = FastIndexSampler::new(pool.len());
2145    let n = fit.n_origins;
2146    let phi = fit.dispersion;
2147    let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2148    let inv_phi = scratch.inv_phi;
2149    let tail_inc = fit.tail - 1.0;
2150    let mut simulated_totals = Vec::with_capacity(config.iterations);
2151
2152    for _ in 0..config.iterations {
2153        let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2154        if !outcome.valid {
2155            continue;
2156        }
2157        let mut ok = true;
2158        let total = if outcome.all_ldfs_ge_one {
2159            let mut cdf = fit.tail;
2160            let l0 = scratch.latest_pseudo[0];
2161            if !l0.is_finite() {
2162                ok = false;
2163            }
2164            let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2165                l0 * tail_inc
2166            } else {
2167                0.0
2168            };
2169            let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2170                -l0 * tail_inc
2171            } else {
2172                0.0
2173            };
2174            for origin in 1..n {
2175                cdf *= scratch.pseudo_ldfs[n - 1 - origin];
2176                let li = scratch.latest_pseudo[origin];
2177                if !li.is_finite() {
2178                    ok = false;
2179                    break;
2180                }
2181                let expected = li * (cdf - 1.0);
2182                if expected >= 0.0 {
2183                    pos_sum += expected;
2184                } else {
2185                    neg_sum -= expected;
2186                }
2187            }
2188            if ok {
2189                let p_draw = if pos_sum > 0.0 {
2190                    sample_positive_process(
2191                        pos_sum,
2192                        phi,
2193                        inv_phi,
2194                        options.process_distribution,
2195                        &mut rng,
2196                    )
2197                } else {
2198                    0.0
2199                };
2200                let n_draw = if neg_sum > 0.0 {
2201                    sample_positive_process(
2202                        neg_sum,
2203                        phi,
2204                        inv_phi,
2205                        options.process_distribution,
2206                        &mut rng,
2207                    )
2208                } else {
2209                    0.0
2210                };
2211                p_draw - n_draw
2212            } else {
2213                f64::NAN
2214            }
2215        } else {
2216            let mut pos_factor = tail_inc;
2217            let mut neg_factor = 0.0;
2218            let l0 = scratch.latest_pseudo[0];
2219            if !l0.is_finite() {
2220                ok = false;
2221            }
2222            let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2223                l0 * tail_inc
2224            } else {
2225                0.0
2226            };
2227            let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2228                -l0 * tail_inc
2229            } else {
2230                0.0
2231            };
2232            for origin in 1..n {
2233                let f = scratch.pseudo_ldfs[n - 1 - origin];
2234                let step = f - 1.0;
2235                if step >= 0.0 {
2236                    pos_factor = step + f * pos_factor;
2237                    neg_factor *= f;
2238                } else {
2239                    pos_factor *= f;
2240                    neg_factor = (-step) + f * neg_factor;
2241                }
2242                let li = scratch.latest_pseudo[origin];
2243                if !li.is_finite() {
2244                    ok = false;
2245                    break;
2246                }
2247                if li >= 0.0 {
2248                    pos_sum += li * pos_factor;
2249                    neg_sum += li * neg_factor;
2250                } else {
2251                    pos_sum += -li * neg_factor;
2252                    neg_sum += -li * pos_factor;
2253                }
2254            }
2255            if ok {
2256                let p_draw = if pos_sum > 0.0 {
2257                    sample_positive_process(
2258                        pos_sum,
2259                        phi,
2260                        inv_phi,
2261                        options.process_distribution,
2262                        &mut rng,
2263                    )
2264                } else {
2265                    0.0
2266                };
2267                let n_draw = if neg_sum > 0.0 {
2268                    sample_positive_process(
2269                        neg_sum,
2270                        phi,
2271                        inv_phi,
2272                        options.process_distribution,
2273                        &mut rng,
2274                    )
2275                } else {
2276                    0.0
2277                };
2278                p_draw - n_draw
2279            } else {
2280                f64::NAN
2281            }
2282        };
2283        if ok && total.is_finite() {
2284            simulated_totals.push(total);
2285        }
2286    }
2287
2288    if simulated_totals.is_empty() {
2289        return Err(ValidationError::NotFinite);
2290    }
2291
2292    let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2293    let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2294    Ok(BootstrapResult {
2295        base_total_reserve: fit.total_reserve,
2296        simulated_totals,
2297        summary,
2298    })
2299}
2300
2301/// Reserve-only convenience wrapper around [`bootstrap`].
2302pub fn bootstrap_summary(
2303    triangle: &TriangleView<'_>,
2304    tail: f64,
2305    config: BootstrapConfig,
2306) -> Result<BootstrapSummary, ValidationError> {
2307    Ok(bootstrap(triangle, tail, config)?.summary)
2308}
2309
2310/// Output of the 1-year Solvency II Claims Development Result (CDR)
2311/// re-reserving ODP bootstrap (England & Verrall / Merz & Wüthrich;
2312/// mirrors `mages/ChainLadder`'s `CDR(BootChainLadder)`).
2313#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
2314pub struct OdpCdrBootstrapResult {
2315    /// Initial deterministic reserve $R^{(0)}$ summed across origins.
2316    pub base_total_reserve: f64,
2317    /// Initial deterministic reserve $R_i^{(0)}$ per origin.
2318    pub base_origin_reserves: Vec<f64>,
2319    /// Simulated total 1-year CDR samples: $R^{(0)} - (Y_{\text{next}} + R^{(1)})$.
2320    /// Negative values represent adverse 1-year development.
2321    pub simulated_total_cdr: Vec<f64>,
2322    /// Simulated 1-year CDR samples per origin (`n_origins` vectors).
2323    pub simulated_cdr_by_origin: Vec<Vec<f64>>,
2324    /// Empirical summary statistics of total 1-year CDR.
2325    pub summary: BootstrapSummary,
2326    /// Empirical summary statistics of 1-year CDR per origin.
2327    pub origin_summaries: Vec<BootstrapSummary>,
2328    /// Count of skipped iterations due to degenerate pseudo-triangles.
2329    pub failed_iterations: usize,
2330}
2331
2332/// Run a 1-year Solvency II Claims Development Result (CDR) re-reserving
2333/// bootstrap on top of the ODP bootstrap model.
2334///
2335/// For each simulation $b$:
2336/// 1. Resample scaled Pearson residuals and refit pseudo-LDFs $\hat{f}_k^{(b)}$.
2337/// 2. Simulate the next calendar-year incremental payments $Y_{i, n-i}^{(b)}$
2338///    (with process variance from `options.process_distribution`) for each open
2339///    origin $i \ge 1$.
2340/// 3. Append the simulated diagonal $C_{i, n-i}^{(b)} = C_{i, n-1-i} + Y_{i, n-i}^{(b)}$
2341///    to the observed triangle, re-estimate volume-weighted chain-ladder LDFs
2342///    on the extended 1-year-later triangle, and compute the updated reserve $R_i^{(1,b)}$.
2343/// 4. Record $\text{CDR}_i^{(b)}(1) = R_i^{(0)} - (Y_{i, n-i}^{(b)} + R_i^{(1,b)})$.
2344pub fn bootstrap_odp_cdr(
2345    triangle: &TriangleView<'_>,
2346    tail: f64,
2347    options: OdpBootstrapOptions,
2348) -> Result<OdpCdrBootstrapResult, ValidationError> {
2349    if options.iterations == 0 {
2350        return Err(ValidationError::ShapeMismatch);
2351    }
2352
2353    let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2354    let (pool, _) =
2355        build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2356
2357    let n = fit.n_origins;
2358    let m = n.saturating_sub(1);
2359    let mut rng = DeterministicRng::from_seed(options.seed);
2360    let mut sampler = FastIndexSampler::new(pool.len());
2361
2362    let mut simulated_total_cdr = Vec::with_capacity(options.iterations);
2363    let mut simulated_cdr_by_origin: Vec<Vec<f64>> = (0..n)
2364        .map(|_| Vec::with_capacity(options.iterations))
2365        .collect();
2366    let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2367    let inv_phi = scratch.inv_phi;
2368    let mut ext_ldfs = vec![1.0; m];
2369    let mut ext_cdfs = vec![tail; n];
2370    let mut next_pay = vec![0.0; n];
2371    let mut next_cum_diag = vec![0.0; n];
2372    let mut failed_iterations = 0usize;
2373
2374    // Precompute observed column sums once: each 1-year CDR draw only appends a
2375    // single simulated diagonal cell (i = n - 1 - k, j = k + 1) to link k.
2376    let mut obs_den = vec![0.0; m];
2377    let mut obs_num = vec![0.0; m];
2378    for i in 0..m {
2379        let row = &triangle.data[i * n..i * n + (n - i)];
2380        for k in 0..(n - 1 - i) {
2381            let c0 = row[k];
2382            let c1 = row[k + 1];
2383            if c0.is_finite() && c1.is_finite() {
2384                obs_den[k] += c0;
2385                obs_num[k] += c1;
2386            }
2387        }
2388    }
2389    let obs_diag: Vec<f64> = (0..n).map(|i| triangle.get(i, n - 1 - i)).collect();
2390    let r1_origin0 = obs_diag[0] * (tail - 1.0);
2391
2392    for _ in 0..options.iterations {
2393        // 1. Fused single-pass resampling + delta accumulation + LDF refit.
2394        let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2395        if !outcome.valid {
2396            failed_iterations += 1;
2397            continue;
2398        }
2399
2400        // 2. Simulate next calendar diagonal (i + j == n) and update extended LDFs in O(n).
2401        let mut valid_ext = true;
2402        for i in 1..n {
2403            let k = n - 1 - i; // link k -> k + 1 (j_next = k + 1 = n - i)
2404            let c_prev = obs_diag[i];
2405            let expected_inc = c_prev * (scratch.pseudo_ldfs[k] - 1.0);
2406            let sim_inc = sample_process_increment_fast(
2407                expected_inc,
2408                fit.dispersion,
2409                inv_phi,
2410                options.process_distribution,
2411                &mut rng,
2412            );
2413            let c_next = c_prev + sim_inc;
2414            next_pay[i] = sim_inc;
2415            next_cum_diag[i] = c_next;
2416
2417            let den = obs_den[k] + c_prev;
2418            let num = obs_num[k] + c_next;
2419            if !den.is_finite() || den <= 0.0 || !num.is_finite() || num <= 0.0 {
2420                valid_ext = false;
2421                break;
2422            }
2423            ext_ldfs[k] = num / den;
2424        }
2425        if !valid_ext {
2426            failed_iterations += 1;
2427            continue;
2428        }
2429
2430        // 3. Compound extended CDFs right-to-left in O(n).
2431        ext_cdfs[m] = tail;
2432        for k in (0..m).rev() {
2433            ext_cdfs[k] = ext_ldfs[k] * ext_cdfs[k + 1];
2434        }
2435
2436        // 4. Compute updated reserve R^{(1)} and 1-year CDR = R^{(0)} - (Y_next + R^{(1)}) in O(n).
2437        let cdr0 = fit.origin_reserves[0] - r1_origin0;
2438        if !cdr0.is_finite() {
2439            failed_iterations += 1;
2440            continue;
2441        }
2442        scratch.origin_reserves[0] = cdr0;
2443        let mut total_cdr = cdr0;
2444        let mut ok = true;
2445        for i in 1..n {
2446            let j_next = n - i;
2447            let c_next = next_cum_diag[i];
2448            let r1 = c_next * (ext_cdfs[j_next] - 1.0);
2449            let cdr_i = fit.origin_reserves[i] - (next_pay[i] + r1);
2450            if !cdr_i.is_finite() {
2451                ok = false;
2452                break;
2453            }
2454            scratch.origin_reserves[i] = cdr_i;
2455            total_cdr += cdr_i;
2456        }
2457        if !ok || !total_cdr.is_finite() {
2458            failed_iterations += 1;
2459            continue;
2460        }
2461        simulated_total_cdr.push(total_cdr);
2462        for (origin_vec, &r) in simulated_cdr_by_origin
2463            .iter_mut()
2464            .zip(scratch.origin_reserves.iter())
2465        {
2466            origin_vec.push(r);
2467        }
2468    }
2469
2470    if simulated_total_cdr.is_empty() {
2471        return Err(ValidationError::NotFinite);
2472    }
2473
2474    let mut summary_buf = Vec::with_capacity(simulated_total_cdr.len());
2475    let summary = summarize_with_scratch(&simulated_total_cdr, &mut summary_buf, true)?;
2476    let mut origin_summaries = Vec::with_capacity(n);
2477    for series in &simulated_cdr_by_origin {
2478        origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2479    }
2480
2481    Ok(OdpCdrBootstrapResult {
2482        base_total_reserve: fit.total_reserve,
2483        base_origin_reserves: fit.origin_reserves,
2484        simulated_total_cdr,
2485        simulated_cdr_by_origin,
2486        summary,
2487        origin_summaries,
2488        failed_iterations,
2489    })
2490}
2491
2492#[cfg(test)]
2493mod tests {
2494    use super::*;
2495    use crate::chain_ladder::ChainLadderEngine;
2496    use crate::datasets::genins;
2497    use crate::ldf::DevelopmentFactorEngine;
2498    use crate::types::Triangle;
2499
2500    fn triangle_4x4() -> Triangle {
2501        #[rustfmt::skip]
2502        let data = vec![
2503            1000.0, 1500.0, 1700.0, 1800.0,
2504            1200.0, 1800.0, 2000.0, f64::NAN,
2505            1500.0, 2100.0, f64::NAN, f64::NAN,
2506            1800.0, f64::NAN, f64::NAN, f64::NAN,
2507        ];
2508        Triangle::new(4, 4, data)
2509    }
2510
2511    #[test]
2512    fn bootstrap_is_deterministic_for_same_seed() {
2513        let triangle = triangle_4x4();
2514        let config = BootstrapConfig {
2515            iterations: 50,
2516            seed: 42,
2517        };
2518
2519        let first = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2520        let second = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2521
2522        assert_eq!(first.simulated_totals, second.simulated_totals);
2523        assert_eq!(first.summary, second.summary);
2524    }
2525
2526    #[test]
2527    fn bootstrap_returns_ordered_quantiles() {
2528        let triangle = triangle_4x4();
2529        let summary = bootstrap_summary(
2530            &triangle.view(),
2531            1.0,
2532            BootstrapConfig {
2533                iterations: 100,
2534                seed: 7,
2535            },
2536        )
2537        .expect("summary");
2538
2539        assert!(summary.mean >= 0.0);
2540        assert!(summary.std_dev >= 0.0);
2541        assert!(summary.p50 <= summary.p75);
2542        assert!(summary.p75 <= summary.p90);
2543        assert!(summary.p90 <= summary.p95);
2544        assert!(summary.p95 <= summary.p99);
2545    }
2546
2547    #[test]
2548    fn bootstrap_rejects_zero_iterations() {
2549        let triangle = triangle_4x4();
2550        assert_eq!(
2551            bootstrap(
2552                &triangle.view(),
2553                1.0,
2554                BootstrapConfig {
2555                    iterations: 0,
2556                    seed: 1
2557                }
2558            ),
2559            Err(ValidationError::ShapeMismatch)
2560        );
2561    }
2562
2563    #[test]
2564    fn bootstrap_base_reserve_matches_chain_ladder() {
2565        let triangle = triangle_4x4();
2566        let result = bootstrap(
2567            &triangle.view(),
2568            1.0,
2569            BootstrapConfig {
2570                iterations: 10,
2571                seed: 9,
2572            },
2573        )
2574        .expect("bootstrap");
2575
2576        let factors =
2577            DevelopmentFactorEngine::volume_weighted(&triangle.view(), 1.0).expect("factors");
2578        let projection =
2579            ChainLadderEngine::project(&triangle.view(), &factors).expect("projection");
2580        assert!((result.base_total_reserve - projection.total_reserve).abs() < 1e-9);
2581    }
2582
2583    #[test]
2584    fn odp_fit_leverages_sum_to_rank_and_saturate_corners() {
2585        let triangle = triangle_4x4();
2586        let fit = fit_odp(&triangle.view(), 1.0, MonotonicityPolicy::Strict).expect("fit");
2587
2588        assert_eq!(fit.n_observed, 10);
2589        assert_eq!(fit.rank, 7);
2590        assert_eq!(fit.degrees_of_freedom, 3);
2591        let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2592        assert!((h_sum - 7.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2593        let saturated_corners: Vec<(usize, usize)> = fit
2594            .residuals
2595            .iter()
2596            .filter(|r| r.saturated)
2597            .map(|r| (r.origin, r.dev))
2598            .collect();
2599        assert_eq!(saturated_corners, vec![(0, 3), (3, 0)]);
2600    }
2601
2602    #[test]
2603    fn odp_fit_tridiagonal_matches_general_solver_to_machine_precision() {
2604        let tri = genins();
2605        let fit = fit_odp(&tri.view(), 1.05, MonotonicityPolicy::Strict).expect("fast fit");
2606        let general = solve_odp_general(
2607            fit.n_origins,
2608            fit.tail,
2609            &fit.fitted_cumulative,
2610            &fit.fitted_incremental,
2611            &fit.observed_incremental,
2612        )
2613        .expect("general fit");
2614
2615        assert_eq!(fit.residuals.len(), general.residuals.len());
2616        for (a, b) in fit.residuals.iter().zip(general.residuals.iter()) {
2617            assert_eq!((a.origin, a.dev), (b.origin, b.dev));
2618            assert!((a.leverage - b.leverage).abs() < 1e-12);
2619            assert!((a.raw_pearson_residual - b.raw_pearson_residual).abs() < 1e-12);
2620        }
2621        for i in 0..fit.n_origins {
2622            let tol = 1e-10 * (1.0 + general.analytic_origin_prediction_error[i]);
2623            assert!(
2624                (fit.analytic_origin_param_se[i] - general.analytic_origin_param_se[i]).abs() < tol
2625            );
2626            assert!(
2627                (fit.analytic_origin_prediction_error[i]
2628                    - general.analytic_origin_prediction_error[i])
2629                    .abs()
2630                    < tol
2631            );
2632        }
2633        assert!(
2634            (fit.analytic_total_param_se - general.analytic_total_param_se).abs()
2635                < 1e-10 * general.analytic_total_param_se
2636        );
2637    }
2638
2639    #[test]
2640    fn odp_fit_handles_flat_ldf_via_general_fallback() {
2641        // Last development link has LDF == 1.0 (zero incremental fitted mass in col 3).
2642        #[rustfmt::skip]
2643        let tri = Triangle::new(4, 4, vec![
2644            1000.0, 1500.0, 1700.0, 1700.0,
2645            1200.0, 1800.0, 2000.0, f64::NAN,
2646            1500.0, 2100.0, f64::NAN, f64::NAN,
2647            1800.0, f64::NAN, f64::NAN, f64::NAN,
2648        ]);
2649        let fit = fit_odp(&tri.view(), 1.0, MonotonicityPolicy::Strict).expect("fallback fit");
2650        assert_eq!(fit.n_observed, 9);
2651        assert_eq!(fit.rank, 6);
2652        assert_eq!(fit.degrees_of_freedom, 3);
2653        let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2654        assert!((h_sum - 6.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2655    }
2656
2657    #[test]
2658    fn ziggurat_normal_and_fast_index_samplers_match_theoretical_distributions() {
2659        let mut rng = DeterministicRng::from_seed(1234567);
2660        let n = 200_000usize;
2661        let mut sum = 0.0;
2662        let mut s2 = 0.0;
2663        let mut s3 = 0.0;
2664        let mut s4 = 0.0;
2665        let mut tail_hits = 0usize;
2666        for _ in 0..n {
2667            let z = rng.next_standard_normal();
2668            sum += z;
2669            let z2 = z * z;
2670            s2 += z2;
2671            s3 += z2 * z;
2672            s4 += z2 * z2;
2673            if z.abs() >= ZIG_NORM_R {
2674                tail_hits += 1;
2675            }
2676        }
2677        let nf = n as f64;
2678        let mean = sum / nf;
2679        let var = s2 / nf - mean * mean;
2680        let skew = s3 / nf;
2681        let kurt = s4 / nf;
2682        assert!(mean.abs() < 0.01, "mean={mean}");
2683        assert!((var - 1.0).abs() < 0.015, "var={var}");
2684        assert!(skew.abs() < 0.03, "skew={skew}");
2685        assert!((kurt - 3.0).abs() < 0.08, "kurt={kurt}");
2686        // P(|Z| >= 3.654153) ≈ 2.58e-4 => ~52 hits in 200k.
2687        assert!((20..=100).contains(&tail_hits), "tail_hits={tail_hits}");
2688
2689        // FastIndexSampler uniformity on bound = 53 (16-bit Lemire) and 1500 (32-bit Lemire).
2690        let mut counts53 = [0usize; 53];
2691        let mut s53 = FastIndexSampler::new(53);
2692        for _ in 0..53_000 {
2693            counts53[s53.next(&mut rng)] += 1;
2694        }
2695        let chi2: f64 = counts53
2696            .iter()
2697            .map(|&c| {
2698                let d = c as f64 - 1000.0;
2699                d * d / 1000.0
2700            })
2701            .sum();
2702        assert!(chi2 < 100.0, "chi2(df=52)={chi2}");
2703
2704        let mut s1500 = FastIndexSampler::new(1500);
2705        for _ in 0..5_000 {
2706            assert!(s1500.next(&mut rng) < 1500);
2707        }
2708    }
2709
2710    #[test]
2711    fn gamma_and_poisson_samplers_match_theoretical_moments() {
2712        let mut rng = DeterministicRng::from_seed(42069);
2713        let n = 40_000usize;
2714
2715        for &(shape, scale) in &[(0.4, 2.5), (3.5, 10.0), (25.0, 50.0)] {
2716            let samples: Vec<f64> = (0..n).map(|_| rng.sample_gamma(shape, scale)).collect();
2717            let mean = samples.iter().sum::<f64>() / n as f64;
2718            let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2719            let expected_mean = shape * scale;
2720            let expected_var = shape * scale * scale;
2721            assert!(
2722                (mean - expected_mean).abs() / expected_mean < 0.03,
2723                "gamma({shape},{scale}) mean={mean} expected={expected_mean}"
2724            );
2725            assert!(
2726                (var - expected_var).abs() / expected_var < 0.08,
2727                "gamma({shape},{scale}) var={var} expected={expected_var}"
2728            );
2729        }
2730
2731        for &lambda in &[0.7, 9.5, 10.0, 12.0, 20.0, 45.0, 300.0] {
2732            let samples: Vec<f64> = (0..n).map(|_| rng.sample_poisson(lambda)).collect();
2733            let mean = samples.iter().sum::<f64>() / n as f64;
2734            let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2735            assert!(
2736                (mean - lambda).abs() / lambda < 0.03,
2737                "poisson({lambda}) mean={mean}"
2738            );
2739            assert!(
2740                (var - lambda).abs() / lambda < 0.06,
2741                "poisson({lambda}) var={var}"
2742            );
2743        }
2744    }
2745}