1use 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
51pub(crate) use crate::linalg::cholesky_lower;
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
60pub struct BootstrapConfig {
61 pub iterations: usize,
63 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
81pub enum ResidualAdjustment {
82 #[default]
85 DegreesOfFreedom,
86 HatMatrixLeverage,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
94pub enum ProcessDistribution {
95 #[default]
98 Gamma,
99 OverDispersedPoisson,
101 None,
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
107pub struct OdpBootstrapOptions {
108 pub iterations: usize,
110 pub seed: u64,
112 pub residual_adjustment: ResidualAdjustment,
114 pub process_distribution: ProcessDistribution,
116 pub center_residuals: bool,
119 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 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 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 pub const fn with_iterations(mut self, iterations: usize) -> Self {
159 self.iterations = iterations;
160 self
161 }
162
163 pub const fn with_seed(mut self, seed: u64) -> Self {
165 self.seed = seed;
166 self
167 }
168
169 pub const fn with_residual_adjustment(mut self, adjustment: ResidualAdjustment) -> Self {
171 self.residual_adjustment = adjustment;
172 self
173 }
174
175 pub const fn with_process_distribution(mut self, dist: ProcessDistribution) -> Self {
177 self.process_distribution = dist;
178 self
179 }
180
181 pub const fn with_centered_residuals(mut self, center: bool) -> Self {
183 self.center_residuals = center;
184 self
185 }
186
187 pub const fn with_policy(mut self, policy: MonotonicityPolicy) -> Self {
189 self.monotonicity_policy = policy;
190 self
191 }
192}
193
194pub type BootstrapSummary = ReserveDistributionSummary;
196
197#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
199pub struct BootstrapResult {
200 pub base_total_reserve: f64,
202 pub simulated_totals: Vec<f64>,
204 pub summary: BootstrapSummary,
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
210pub struct OdpCellResidual {
211 pub origin: usize,
213 pub dev: usize,
215 pub observed_incremental: f64,
217 pub fitted_incremental: f64,
219 pub raw_pearson_residual: f64,
221 pub leverage: f64,
223 pub saturated: bool,
225}
226
227#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
229pub struct OdpFit {
230 pub n_origins: usize,
232 pub n_devs: usize,
234 pub ldfs: Vec<f64>,
236 pub tail: f64,
238 pub fitted_cumulative: Vec<f64>,
241 pub fitted_incremental: Vec<f64>,
243 pub observed_incremental: Vec<f64>,
245 pub residuals: Vec<OdpCellResidual>,
247 pub n_observed: usize,
249 pub rank: usize,
251 pub degrees_of_freedom: usize,
253 pub dispersion: f64,
255 pub origin_reserves: Vec<f64>,
257 pub total_reserve: f64,
259 pub analytic_origin_process_se: Vec<f64>,
261 pub analytic_origin_param_se: Vec<f64>,
263 pub analytic_origin_prediction_error: Vec<f64>,
265 pub analytic_total_process_se: f64,
267 pub analytic_total_param_se: f64,
269 pub analytic_total_prediction_error: f64,
271}
272
273#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
276pub struct OdpBootstrapResult {
277 pub fit: OdpFit,
279 pub options: OdpBootstrapOptions,
281 pub base_total_reserve: f64,
283 pub simulated_totals: Vec<f64>,
285 pub simulated_by_origin: Vec<Vec<f64>>,
287 pub origin_summaries: Vec<ReserveDistributionSummary>,
289 pub summary: ReserveDistributionSummary,
291 pub failed_iterations: usize,
294 pub residual_pool_mean_before_centering: f64,
296}
297
298#[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#[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#[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#[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#[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 #[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 #[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 #[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 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 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 #[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 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 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
703pub(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 #[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
904pub(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
926struct 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
946fn 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 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 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 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 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 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 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 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 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 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 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
1207fn 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 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 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
1393pub 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 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 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
1504pub(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
1540pub(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#[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#[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 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 while origin + 1 < m {
1692 let len_a = n - origin; let len_b = len_a - 1; 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#[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 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#[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 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#[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 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 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
2002pub(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
2029pub fn bootstrap_odp(
2031 triangle: &TriangleView<'_>,
2032 tail: f64,
2033 options: OdpBootstrapOptions,
2034) -> Result<OdpBootstrapResult, ValidationError> {
2035 if options.iterations == 0 {
2036 return Err(ValidationError::ShapeMismatch);
2037 }
2038
2039 let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2040 let (pool, pool_mean) =
2041 build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2042
2043 let mut rng = DeterministicRng::from_seed(options.seed);
2044 let mut sampler = FastIndexSampler::new(pool.len());
2045 let n = fit.n_origins;
2046 let mut simulated_totals = Vec::with_capacity(options.iterations);
2047 let mut simulated_by_origin: Vec<Vec<f64>> = (0..n)
2048 .map(|_| Vec::with_capacity(options.iterations))
2049 .collect();
2050 let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2051 let mut failed_iterations = 0usize;
2052
2053 for _ in 0..options.iterations {
2054 let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2055 if !outcome.valid {
2056 failed_iterations += 1;
2057 continue;
2058 }
2059 if let Some(total) = project_origin_reserves(
2060 fit.tail,
2061 fit.dispersion,
2062 outcome.all_ldfs_ge_one,
2063 options.process_distribution,
2064 &mut rng,
2065 &mut scratch,
2066 ) {
2067 simulated_totals.push(total);
2068 for (origin_vec, &r) in simulated_by_origin
2069 .iter_mut()
2070 .zip(scratch.origin_reserves.iter())
2071 {
2072 origin_vec.push(r);
2073 }
2074 } else {
2075 failed_iterations += 1;
2076 }
2077 }
2078
2079 if simulated_totals.is_empty() {
2080 return Err(ValidationError::NotFinite);
2081 }
2082
2083 let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2086 let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2087 let mut origin_summaries = Vec::with_capacity(n);
2088 for series in &simulated_by_origin {
2089 origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2090 }
2091
2092 Ok(OdpBootstrapResult {
2093 base_total_reserve: fit.total_reserve,
2094 fit,
2095 options,
2096 simulated_totals,
2097 simulated_by_origin,
2098 origin_summaries,
2099 summary,
2100 failed_iterations,
2101 residual_pool_mean_before_centering: pool_mean,
2102 })
2103}
2104
2105pub fn bootstrap(
2113 triangle: &TriangleView<'_>,
2114 tail: f64,
2115 config: BootstrapConfig,
2116) -> Result<BootstrapResult, ValidationError> {
2117 if config.iterations == 0 {
2118 return Err(ValidationError::ShapeMismatch);
2119 }
2120
2121 let options = OdpBootstrapOptions::england_verrall(config.iterations, config.seed);
2122 let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2123 let (pool, _) =
2124 build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2125
2126 let mut rng = DeterministicRng::from_seed(options.seed);
2127 let mut sampler = FastIndexSampler::new(pool.len());
2128 let n = fit.n_origins;
2129 let phi = fit.dispersion;
2130 let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2131 let inv_phi = scratch.inv_phi;
2132 let tail_inc = fit.tail - 1.0;
2133 let mut simulated_totals = Vec::with_capacity(config.iterations);
2134
2135 for _ in 0..config.iterations {
2136 let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2137 if !outcome.valid {
2138 continue;
2139 }
2140 let mut ok = true;
2141 let total = if outcome.all_ldfs_ge_one {
2142 let mut cdf = fit.tail;
2143 let l0 = scratch.latest_pseudo[0];
2144 if !l0.is_finite() {
2145 ok = false;
2146 }
2147 let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2148 l0 * tail_inc
2149 } else {
2150 0.0
2151 };
2152 let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2153 -l0 * tail_inc
2154 } else {
2155 0.0
2156 };
2157 for origin in 1..n {
2158 cdf *= scratch.pseudo_ldfs[n - 1 - origin];
2159 let li = scratch.latest_pseudo[origin];
2160 if !li.is_finite() {
2161 ok = false;
2162 break;
2163 }
2164 let expected = li * (cdf - 1.0);
2165 if expected >= 0.0 {
2166 pos_sum += expected;
2167 } else {
2168 neg_sum -= expected;
2169 }
2170 }
2171 if ok {
2172 let p_draw = if pos_sum > 0.0 {
2173 sample_positive_process(
2174 pos_sum,
2175 phi,
2176 inv_phi,
2177 options.process_distribution,
2178 &mut rng,
2179 )
2180 } else {
2181 0.0
2182 };
2183 let n_draw = if neg_sum > 0.0 {
2184 sample_positive_process(
2185 neg_sum,
2186 phi,
2187 inv_phi,
2188 options.process_distribution,
2189 &mut rng,
2190 )
2191 } else {
2192 0.0
2193 };
2194 p_draw - n_draw
2195 } else {
2196 f64::NAN
2197 }
2198 } else {
2199 let mut pos_factor = tail_inc;
2200 let mut neg_factor = 0.0;
2201 let l0 = scratch.latest_pseudo[0];
2202 if !l0.is_finite() {
2203 ok = false;
2204 }
2205 let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2206 l0 * tail_inc
2207 } else {
2208 0.0
2209 };
2210 let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2211 -l0 * tail_inc
2212 } else {
2213 0.0
2214 };
2215 for origin in 1..n {
2216 let f = scratch.pseudo_ldfs[n - 1 - origin];
2217 let step = f - 1.0;
2218 if step >= 0.0 {
2219 pos_factor = step + f * pos_factor;
2220 neg_factor *= f;
2221 } else {
2222 pos_factor *= f;
2223 neg_factor = (-step) + f * neg_factor;
2224 }
2225 let li = scratch.latest_pseudo[origin];
2226 if !li.is_finite() {
2227 ok = false;
2228 break;
2229 }
2230 if li >= 0.0 {
2231 pos_sum += li * pos_factor;
2232 neg_sum += li * neg_factor;
2233 } else {
2234 pos_sum += -li * neg_factor;
2235 neg_sum += -li * pos_factor;
2236 }
2237 }
2238 if ok {
2239 let p_draw = if pos_sum > 0.0 {
2240 sample_positive_process(
2241 pos_sum,
2242 phi,
2243 inv_phi,
2244 options.process_distribution,
2245 &mut rng,
2246 )
2247 } else {
2248 0.0
2249 };
2250 let n_draw = if neg_sum > 0.0 {
2251 sample_positive_process(
2252 neg_sum,
2253 phi,
2254 inv_phi,
2255 options.process_distribution,
2256 &mut rng,
2257 )
2258 } else {
2259 0.0
2260 };
2261 p_draw - n_draw
2262 } else {
2263 f64::NAN
2264 }
2265 };
2266 if ok && total.is_finite() {
2267 simulated_totals.push(total);
2268 }
2269 }
2270
2271 if simulated_totals.is_empty() {
2272 return Err(ValidationError::NotFinite);
2273 }
2274
2275 let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2276 let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2277 Ok(BootstrapResult {
2278 base_total_reserve: fit.total_reserve,
2279 simulated_totals,
2280 summary,
2281 })
2282}
2283
2284pub fn bootstrap_summary(
2286 triangle: &TriangleView<'_>,
2287 tail: f64,
2288 config: BootstrapConfig,
2289) -> Result<BootstrapSummary, ValidationError> {
2290 Ok(bootstrap(triangle, tail, config)?.summary)
2291}
2292
2293#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
2297pub struct OdpCdrBootstrapResult {
2298 pub base_total_reserve: f64,
2300 pub base_origin_reserves: Vec<f64>,
2302 pub simulated_total_cdr: Vec<f64>,
2305 pub simulated_cdr_by_origin: Vec<Vec<f64>>,
2307 pub summary: BootstrapSummary,
2309 pub origin_summaries: Vec<BootstrapSummary>,
2311 pub failed_iterations: usize,
2313}
2314
2315pub fn bootstrap_odp_cdr(
2328 triangle: &TriangleView<'_>,
2329 tail: f64,
2330 options: OdpBootstrapOptions,
2331) -> Result<OdpCdrBootstrapResult, ValidationError> {
2332 if options.iterations == 0 {
2333 return Err(ValidationError::ShapeMismatch);
2334 }
2335
2336 let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2337 let (pool, _) =
2338 build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2339
2340 let n = fit.n_origins;
2341 let m = n.saturating_sub(1);
2342 let mut rng = DeterministicRng::from_seed(options.seed);
2343 let mut sampler = FastIndexSampler::new(pool.len());
2344
2345 let mut simulated_total_cdr = Vec::with_capacity(options.iterations);
2346 let mut simulated_cdr_by_origin: Vec<Vec<f64>> = (0..n)
2347 .map(|_| Vec::with_capacity(options.iterations))
2348 .collect();
2349 let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2350 let inv_phi = scratch.inv_phi;
2351 let mut ext_ldfs = vec![1.0; m];
2352 let mut ext_cdfs = vec![tail; n];
2353 let mut next_pay = vec![0.0; n];
2354 let mut next_cum_diag = vec![0.0; n];
2355 let mut failed_iterations = 0usize;
2356
2357 let mut obs_den = vec![0.0; m];
2360 let mut obs_num = vec![0.0; m];
2361 for i in 0..m {
2362 let row = &triangle.data[i * n..i * n + (n - i)];
2363 for k in 0..(n - 1 - i) {
2364 let c0 = row[k];
2365 let c1 = row[k + 1];
2366 if c0.is_finite() && c1.is_finite() {
2367 obs_den[k] += c0;
2368 obs_num[k] += c1;
2369 }
2370 }
2371 }
2372 let obs_diag: Vec<f64> = (0..n).map(|i| triangle.get(i, n - 1 - i)).collect();
2373 let r1_origin0 = obs_diag[0] * (tail - 1.0);
2374
2375 for _ in 0..options.iterations {
2376 let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2378 if !outcome.valid {
2379 failed_iterations += 1;
2380 continue;
2381 }
2382
2383 let mut valid_ext = true;
2385 for i in 1..n {
2386 let k = n - 1 - i; let c_prev = obs_diag[i];
2388 let expected_inc = c_prev * (scratch.pseudo_ldfs[k] - 1.0);
2389 let sim_inc = sample_process_increment_fast(
2390 expected_inc,
2391 fit.dispersion,
2392 inv_phi,
2393 options.process_distribution,
2394 &mut rng,
2395 );
2396 let c_next = c_prev + sim_inc;
2397 next_pay[i] = sim_inc;
2398 next_cum_diag[i] = c_next;
2399
2400 let den = obs_den[k] + c_prev;
2401 let num = obs_num[k] + c_next;
2402 if !den.is_finite() || den <= 0.0 || !num.is_finite() || num <= 0.0 {
2403 valid_ext = false;
2404 break;
2405 }
2406 ext_ldfs[k] = num / den;
2407 }
2408 if !valid_ext {
2409 failed_iterations += 1;
2410 continue;
2411 }
2412
2413 ext_cdfs[m] = tail;
2415 for k in (0..m).rev() {
2416 ext_cdfs[k] = ext_ldfs[k] * ext_cdfs[k + 1];
2417 }
2418
2419 let cdr0 = fit.origin_reserves[0] - r1_origin0;
2421 if !cdr0.is_finite() {
2422 failed_iterations += 1;
2423 continue;
2424 }
2425 scratch.origin_reserves[0] = cdr0;
2426 let mut total_cdr = cdr0;
2427 let mut ok = true;
2428 for i in 1..n {
2429 let j_next = n - i;
2430 let c_next = next_cum_diag[i];
2431 let r1 = c_next * (ext_cdfs[j_next] - 1.0);
2432 let cdr_i = fit.origin_reserves[i] - (next_pay[i] + r1);
2433 if !cdr_i.is_finite() {
2434 ok = false;
2435 break;
2436 }
2437 scratch.origin_reserves[i] = cdr_i;
2438 total_cdr += cdr_i;
2439 }
2440 if !ok || !total_cdr.is_finite() {
2441 failed_iterations += 1;
2442 continue;
2443 }
2444 simulated_total_cdr.push(total_cdr);
2445 for (origin_vec, &r) in simulated_cdr_by_origin
2446 .iter_mut()
2447 .zip(scratch.origin_reserves.iter())
2448 {
2449 origin_vec.push(r);
2450 }
2451 }
2452
2453 if simulated_total_cdr.is_empty() {
2454 return Err(ValidationError::NotFinite);
2455 }
2456
2457 let mut summary_buf = Vec::with_capacity(simulated_total_cdr.len());
2458 let summary = summarize_with_scratch(&simulated_total_cdr, &mut summary_buf, true)?;
2459 let mut origin_summaries = Vec::with_capacity(n);
2460 for series in &simulated_cdr_by_origin {
2461 origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2462 }
2463
2464 Ok(OdpCdrBootstrapResult {
2465 base_total_reserve: fit.total_reserve,
2466 base_origin_reserves: fit.origin_reserves,
2467 simulated_total_cdr,
2468 simulated_cdr_by_origin,
2469 summary,
2470 origin_summaries,
2471 failed_iterations,
2472 })
2473}
2474
2475#[cfg(test)]
2476mod tests {
2477 use super::*;
2478 use crate::chain_ladder::ChainLadderEngine;
2479 use crate::datasets::genins;
2480 use crate::ldf::DevelopmentFactorEngine;
2481 use crate::types::Triangle;
2482
2483 fn triangle_4x4() -> Triangle {
2484 #[rustfmt::skip]
2485 let data = vec![
2486 1000.0, 1500.0, 1700.0, 1800.0,
2487 1200.0, 1800.0, 2000.0, f64::NAN,
2488 1500.0, 2100.0, f64::NAN, f64::NAN,
2489 1800.0, f64::NAN, f64::NAN, f64::NAN,
2490 ];
2491 Triangle::new(4, 4, data)
2492 }
2493
2494 #[test]
2495 fn bootstrap_is_deterministic_for_same_seed() {
2496 let triangle = triangle_4x4();
2497 let config = BootstrapConfig {
2498 iterations: 50,
2499 seed: 42,
2500 };
2501
2502 let first = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2503 let second = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2504
2505 assert_eq!(first.simulated_totals, second.simulated_totals);
2506 assert_eq!(first.summary, second.summary);
2507 }
2508
2509 #[test]
2510 fn bootstrap_returns_ordered_quantiles() {
2511 let triangle = triangle_4x4();
2512 let summary = bootstrap_summary(
2513 &triangle.view(),
2514 1.0,
2515 BootstrapConfig {
2516 iterations: 100,
2517 seed: 7,
2518 },
2519 )
2520 .expect("summary");
2521
2522 assert!(summary.mean >= 0.0);
2523 assert!(summary.std_dev >= 0.0);
2524 assert!(summary.p50 <= summary.p75);
2525 assert!(summary.p75 <= summary.p90);
2526 assert!(summary.p90 <= summary.p95);
2527 assert!(summary.p95 <= summary.p99);
2528 }
2529
2530 #[test]
2531 fn bootstrap_rejects_zero_iterations() {
2532 let triangle = triangle_4x4();
2533 assert_eq!(
2534 bootstrap(
2535 &triangle.view(),
2536 1.0,
2537 BootstrapConfig {
2538 iterations: 0,
2539 seed: 1
2540 }
2541 ),
2542 Err(ValidationError::ShapeMismatch)
2543 );
2544 }
2545
2546 #[test]
2547 fn bootstrap_base_reserve_matches_chain_ladder() {
2548 let triangle = triangle_4x4();
2549 let result = bootstrap(
2550 &triangle.view(),
2551 1.0,
2552 BootstrapConfig {
2553 iterations: 10,
2554 seed: 9,
2555 },
2556 )
2557 .expect("bootstrap");
2558
2559 let factors =
2560 DevelopmentFactorEngine::volume_weighted(&triangle.view(), 1.0).expect("factors");
2561 let projection =
2562 ChainLadderEngine::project(&triangle.view(), &factors).expect("projection");
2563 assert!((result.base_total_reserve - projection.total_reserve).abs() < 1e-9);
2564 }
2565
2566 #[test]
2567 fn odp_fit_leverages_sum_to_rank_and_saturate_corners() {
2568 let triangle = triangle_4x4();
2569 let fit = fit_odp(&triangle.view(), 1.0, MonotonicityPolicy::Strict).expect("fit");
2570
2571 assert_eq!(fit.n_observed, 10);
2572 assert_eq!(fit.rank, 7);
2573 assert_eq!(fit.degrees_of_freedom, 3);
2574 let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2575 assert!((h_sum - 7.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2576 let saturated_corners: Vec<(usize, usize)> = fit
2577 .residuals
2578 .iter()
2579 .filter(|r| r.saturated)
2580 .map(|r| (r.origin, r.dev))
2581 .collect();
2582 assert_eq!(saturated_corners, vec![(0, 3), (3, 0)]);
2583 }
2584
2585 #[test]
2586 fn odp_fit_tridiagonal_matches_general_solver_to_machine_precision() {
2587 let tri = genins();
2588 let fit = fit_odp(&tri.view(), 1.05, MonotonicityPolicy::Strict).expect("fast fit");
2589 let general = solve_odp_general(
2590 fit.n_origins,
2591 fit.tail,
2592 &fit.fitted_cumulative,
2593 &fit.fitted_incremental,
2594 &fit.observed_incremental,
2595 )
2596 .expect("general fit");
2597
2598 assert_eq!(fit.residuals.len(), general.residuals.len());
2599 for (a, b) in fit.residuals.iter().zip(general.residuals.iter()) {
2600 assert_eq!((a.origin, a.dev), (b.origin, b.dev));
2601 assert!((a.leverage - b.leverage).abs() < 1e-12);
2602 assert!((a.raw_pearson_residual - b.raw_pearson_residual).abs() < 1e-12);
2603 }
2604 for i in 0..fit.n_origins {
2605 let tol = 1e-10 * (1.0 + general.analytic_origin_prediction_error[i]);
2606 assert!(
2607 (fit.analytic_origin_param_se[i] - general.analytic_origin_param_se[i]).abs() < tol
2608 );
2609 assert!(
2610 (fit.analytic_origin_prediction_error[i]
2611 - general.analytic_origin_prediction_error[i])
2612 .abs()
2613 < tol
2614 );
2615 }
2616 assert!(
2617 (fit.analytic_total_param_se - general.analytic_total_param_se).abs()
2618 < 1e-10 * general.analytic_total_param_se
2619 );
2620 }
2621
2622 #[test]
2623 fn odp_fit_handles_flat_ldf_via_general_fallback() {
2624 #[rustfmt::skip]
2626 let tri = Triangle::new(4, 4, vec![
2627 1000.0, 1500.0, 1700.0, 1700.0,
2628 1200.0, 1800.0, 2000.0, f64::NAN,
2629 1500.0, 2100.0, f64::NAN, f64::NAN,
2630 1800.0, f64::NAN, f64::NAN, f64::NAN,
2631 ]);
2632 let fit = fit_odp(&tri.view(), 1.0, MonotonicityPolicy::Strict).expect("fallback fit");
2633 assert_eq!(fit.n_observed, 9);
2634 assert_eq!(fit.rank, 6);
2635 assert_eq!(fit.degrees_of_freedom, 3);
2636 let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2637 assert!((h_sum - 6.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2638 }
2639
2640 #[test]
2641 fn ziggurat_normal_and_fast_index_samplers_match_theoretical_distributions() {
2642 let mut rng = DeterministicRng::from_seed(1234567);
2643 let n = 200_000usize;
2644 let mut sum = 0.0;
2645 let mut s2 = 0.0;
2646 let mut s3 = 0.0;
2647 let mut s4 = 0.0;
2648 let mut tail_hits = 0usize;
2649 for _ in 0..n {
2650 let z = rng.next_standard_normal();
2651 sum += z;
2652 let z2 = z * z;
2653 s2 += z2;
2654 s3 += z2 * z;
2655 s4 += z2 * z2;
2656 if z.abs() >= ZIG_NORM_R {
2657 tail_hits += 1;
2658 }
2659 }
2660 let nf = n as f64;
2661 let mean = sum / nf;
2662 let var = s2 / nf - mean * mean;
2663 let skew = s3 / nf;
2664 let kurt = s4 / nf;
2665 assert!(mean.abs() < 0.01, "mean={mean}");
2666 assert!((var - 1.0).abs() < 0.015, "var={var}");
2667 assert!(skew.abs() < 0.03, "skew={skew}");
2668 assert!((kurt - 3.0).abs() < 0.08, "kurt={kurt}");
2669 assert!((20..=100).contains(&tail_hits), "tail_hits={tail_hits}");
2671
2672 let mut counts53 = [0usize; 53];
2674 let mut s53 = FastIndexSampler::new(53);
2675 for _ in 0..53_000 {
2676 counts53[s53.next(&mut rng)] += 1;
2677 }
2678 let chi2: f64 = counts53
2679 .iter()
2680 .map(|&c| {
2681 let d = c as f64 - 1000.0;
2682 d * d / 1000.0
2683 })
2684 .sum();
2685 assert!(chi2 < 100.0, "chi2(df=52)={chi2}");
2686
2687 let mut s1500 = FastIndexSampler::new(1500);
2688 for _ in 0..5_000 {
2689 assert!(s1500.next(&mut rng) < 1500);
2690 }
2691 }
2692
2693 #[test]
2694 fn gamma_and_poisson_samplers_match_theoretical_moments() {
2695 let mut rng = DeterministicRng::from_seed(42069);
2696 let n = 40_000usize;
2697
2698 for &(shape, scale) in &[(0.4, 2.5), (3.5, 10.0), (25.0, 50.0)] {
2699 let samples: Vec<f64> = (0..n).map(|_| rng.sample_gamma(shape, scale)).collect();
2700 let mean = samples.iter().sum::<f64>() / n as f64;
2701 let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2702 let expected_mean = shape * scale;
2703 let expected_var = shape * scale * scale;
2704 assert!(
2705 (mean - expected_mean).abs() / expected_mean < 0.03,
2706 "gamma({shape},{scale}) mean={mean} expected={expected_mean}"
2707 );
2708 assert!(
2709 (var - expected_var).abs() / expected_var < 0.08,
2710 "gamma({shape},{scale}) var={var} expected={expected_var}"
2711 );
2712 }
2713
2714 for &lambda in &[0.7, 9.5, 10.0, 12.0, 20.0, 45.0, 300.0] {
2715 let samples: Vec<f64> = (0..n).map(|_| rng.sample_poisson(lambda)).collect();
2716 let mean = samples.iter().sum::<f64>() / n as f64;
2717 let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2718 assert!(
2719 (mean - lambda).abs() / lambda < 0.03,
2720 "poisson({lambda}) mean={mean}"
2721 );
2722 assert!(
2723 (var - lambda).abs() / lambda < 0.06,
2724 "poisson({lambda}) var={var}"
2725 );
2726 }
2727 }
2728}