1use std::f64::consts::TAU;
40
41use crate::capital::reserve_distribution::{ReserveDistributionSummary, summarize_with_scratch};
42use crate::deterministic::ldf::{cdfs_from_ldfs, volume_weighted_ldfs};
43use crate::linalg::{invert_spd, solve_lower_into};
44use crate::preprocessing::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)]
229#[non_exhaustive]
230pub struct OdpFit {
231 pub n_origins: usize,
233 pub n_devs: usize,
235 pub ldfs: Vec<f64>,
237 pub tail: f64,
239 pub fitted_cumulative: Vec<f64>,
242 pub fitted_incremental: Vec<f64>,
244 pub observed_incremental: Vec<f64>,
246 pub residuals: Vec<OdpCellResidual>,
248 pub n_observed: usize,
250 pub rank: usize,
252 pub degrees_of_freedom: usize,
254 pub dispersion: f64,
256 pub origin_reserves: Vec<f64>,
258 pub total_reserve: f64,
260 pub analytic_origin_process_se: Vec<f64>,
262 pub analytic_origin_param_se: Vec<f64>,
264 pub analytic_origin_prediction_error: Vec<f64>,
266 pub analytic_total_process_se: f64,
268 pub analytic_total_param_se: f64,
270 pub analytic_total_prediction_error: f64,
272}
273
274#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
277#[non_exhaustive]
278pub struct OdpBootstrapResult {
279 pub fit: OdpFit,
281 pub options: OdpBootstrapOptions,
283 pub base_total_reserve: f64,
285 pub simulated_totals: Vec<f64>,
287 pub simulated_by_origin: Vec<Vec<f64>>,
289 pub origin_summaries: Vec<ReserveDistributionSummary>,
291 pub summary: ReserveDistributionSummary,
293 pub failed_iterations: usize,
296 pub residual_pool_mean_before_centering: f64,
298}
299
300#[allow(clippy::excessive_precision)]
306const ZIG_NORM_R: f64 = 3.65415288536100924e+00;
307#[allow(clippy::excessive_precision)]
308const ZIG_NORM_INV_R: f64 = 2.73661237329758222e-01;
309
310#[allow(clippy::excessive_precision)]
312#[rustfmt::skip]
313const ZIG_NORM_W: [f64; 256] = [
314 1.73672541216026340e-15, 1.62276986753129703e-15, 1.53178727416111455e-15, 1.47448486035975978e-15,
315 1.43199898696613284e-15, 1.39794366727752419e-15, 1.36936068351285195e-15, 1.34463009250111733e-15,
316 1.32276557701953283e-15, 1.30312066346899871e-15, 1.28524793190961128e-15, 1.26882448142550120e-15,
317 1.25360939266025688e-15, 1.23941797891632531e-15, 1.22610544174505652e-15, 1.21355608186668990e-15,
318 1.20167593925438206e-15, 1.19038762992828923e-15, 1.17962663529558048e-15, 1.16933857869109619e-15,
319 1.15947718914491932e-15, 1.15000275378397944e-15, 1.14088092425827821e-15, 1.13208178401648483e-15,
320 1.12357911071108373e-15, 1.11534978658531569e-15, 1.10737332249357560e-15, 1.09963147017856302e-15,
321 1.09210790381495648e-15, 1.08478795644034286e-15, 1.07765840026681103e-15, 1.07070726236329957e-15,
322 1.06392366906768027e-15, 1.05729771390098922e-15, 1.05082034483551986e-15, 1.04448326760004725e-15,
323 1.03827886235154011e-15, 1.03220011154864585e-15, 1.02624053726135694e-15, 1.02039414646831276e-15,
324 1.01465538314670881e-15, 1.00901908616374609e-15, 1.00348045214361829e-15, 9.98035002618364886e-16,
325 9.92678554880797846e-16, 9.87407196048067304e-16, 9.82217259919054503e-16, 9.77105306270721081e-16,
326 9.72068102290162982e-16, 9.67102605882305622e-16, 9.62205950629484033e-16, 9.57375432209745160e-16,
327 9.52608496106628067e-16, 9.47902726465174022e-16, 9.43255835967670851e-16, 9.38665656618666373e-16,
328 9.34130131342526710e-16, 9.29647306308641870e-16, 9.25215323909569530e-16, 9.20832416326230957e-16,
329 9.16496899621913729e-16, 9.12207168313484807e-16, 9.07961690374007196e-16, 9.03759002626012147e-16,
330 8.99597706489110330e-16, 8.95476464049507169e-16, 8.91393994422409008e-16, 8.87349070381313749e-16,
331 8.83340515230841091e-16, 8.79367199902104669e-16, 8.75428040251717888e-16, 8.71521994547370097e-16,
332 8.67648061124558555e-16, 8.63805276200526185e-16, 8.59992711832766756e-16, 8.56209474010623629e-16,
333 8.52454700869559916e-16, 8.48727561018615789e-16, 8.45027251972409973e-16, 8.41352998679803121e-16,
334 8.37704052142022459e-16, 8.34079688113663175e-16, 8.30479205880537668e-16, 8.26901927108847298e-16,
335 8.23347194760605338e-16, 8.19814372070653583e-16, 8.16302841580988043e-16, 8.12812004228450472e-16,
336 8.09341278482150286e-16, 8.05890099527265881e-16, 8.02457918492126209e-16, 7.99044201715713301e-16,
337 7.95648430052936913e-16, 7.92270098215227480e-16, 7.88908714144175817e-16, 7.85563798416108701e-16,
338 7.82234883675641479e-16, 7.78921514096385636e-16, 7.75623244867117738e-16, 7.72339641701830249e-16,
339 7.69070280372192306e-16, 7.65814746261049029e-16, 7.62572633935675970e-16, 7.59343546739589345e-16,
340 7.56127096401792568e-16, 7.52922902662406231e-16, 7.49730592913698329e-16, 7.46549801855589297e-16,
341 7.43380171164765187e-16, 7.40221349176580262e-16, 7.37072990578983395e-16, 7.33934756117740870e-16,
342 7.30806312312274682e-16, 7.27687331181469666e-16, 7.24577489978839093e-16, 7.21476470936471065e-16,
343 7.18383961017206680e-16, 7.15299651674530694e-16, 7.12223238619678278e-16, 7.09154421595487736e-16,
344 7.06092904156548511e-16, 7.03038393455215375e-16, 6.99990600033076791e-16, 6.96949237617483333e-16,
345 6.93914022922757200e-16, 6.90884675455717296e-16, 6.87860917325166761e-16, 6.84842473055004125e-16,
346 6.81829069400625700e-16, 6.78820435168298322e-16, 6.75816301037190453e-16, 6.72816399383753509e-16,
347 6.69820464108156184e-16, 6.66828230462474985e-16, 6.63839434880350960e-16, 6.60853814807826269e-16,
348 6.57871108535074527e-16, 6.54891055028741935e-16, 6.51913393764616367e-16, 6.48937864560340148e-16,
349 6.45964207407883707e-16, 6.42992162305490100e-16, 6.40021469088802966e-16, 6.37051867260881988e-16,
350 6.34083095820806494e-16, 6.31114893090560917e-16, 6.28146996539890023e-16, 6.25179142608800574e-16,
351 6.22211066527379383e-16, 6.19242502132585295e-16, 6.16273181681660223e-16, 6.13302835661791692e-16,
352 6.10331192595644535e-16, 6.07357978842361158e-16, 6.04382918393613093e-16, 6.01405732664266896e-16,
353 5.98426140277203304e-16, 5.95443856841806472e-16, 5.92458594725613986e-16, 5.89470062818587669e-16,
354 5.86477966289437117e-16, 5.83482006333389797e-16, 5.80481879910769157e-16, 5.77477279475697074e-16,
355 5.74467892694196679e-16, 5.71453402150920989e-16, 5.68433485043682002e-16, 5.65407812864896635e-16,
356 5.62376051069004938e-16, 5.59337858724846799e-16, 5.56292888151909609e-16, 5.53240784539278853e-16,
357 5.50181185546034217e-16, 5.47113720881736705e-16, 5.44038011865547399e-16, 5.40953670962399925e-16,
358 5.37860301294524071e-16, 5.34757496126473645e-16, 5.31644838321662347e-16, 5.28521899768238889e-16,
359 5.25388240771946115e-16, 5.22243409413404864e-16, 5.19086940867035028e-16, 5.15918356678574433e-16,
360 5.12737163997880354e-16, 5.09542854763389919e-16, 5.06334904834272739e-16, 5.03112773065932658e-16,
361 4.99875900324091668e-16, 4.96623708432218620e-16, 4.93355599046542278e-16, 4.90070952452300263e-16,
362 4.86769126274221756e-16, 4.83449454093501688e-16, 4.80111243962702438e-16, 4.76753776809086152e-16,
363 4.73376304715833357e-16, 4.69978049069420384e-16, 4.66558198560088404e-16, 4.63115907020817356e-16,
364 4.59650291088495059e-16, 4.56160427669004794e-16, 4.52645351185714954e-16, 4.49104050588288485e-16,
365 4.45535466095792352e-16, 4.41938485644707683e-16, 4.38311941008546798e-16, 4.34654603551288730e-16,
366 4.30965179571630542e-16, 4.27242305188998743e-16, 4.23484540715208218e-16, 4.19690364447408414e-16,
367 4.15858165808281775e-16, 4.11986237748075556e-16, 4.08072768309605617e-16, 4.04115831241434458e-16,
368 4.00113375525468080e-16, 3.96063213662565057e-16, 3.91963008532578115e-16, 3.87810258612503849e-16,
369 3.83602281296774122e-16, 3.79336194015496967e-16, 3.75008892787479409e-16, 3.70617027772362203e-16,
370 3.66156975296536877e-16, 3.61624805715984870e-16, 3.57016246339536469e-16, 3.52326638460021892e-16,
371 3.47550887317299159e-16, 3.42683403531195187e-16, 3.37718034173533949e-16, 3.32647981168418826e-16,
372 3.27465704079399184e-16, 3.22162803505500827e-16, 3.16729880185819877e-16, 3.11156363389217596e-16,
373 3.05430300071926326e-16, 2.99538093367823101e-16, 2.93464174847290854e-16, 2.87190589041141424e-16,
374 2.80696460024850205e-16, 2.73957296851426679e-16, 2.66944074736485216e-16, 2.59621997725283540e-16,
375 2.51948798292744913e-16, 2.43872345574290521e-16, 2.35327189140461874e-16, 2.26229403922184264e-16,
376 2.16468605768957550e-16, 2.05895006284824550e-16, 1.94297201531359847e-16, 1.81361208101194749e-16,
377 1.66587336315867911e-16, 1.49097409624961075e-16, 1.27087048348114564e-16, 9.55866035145697372e-17,
378];
379
380#[allow(clippy::excessive_precision)]
382#[rustfmt::skip]
383const ZIG_NORM_X_INNER: [f64; 256] = [
384 3.65415288536100924e+00, 3.44927829856143164e+00, 3.32024473383982599e+00, 3.22457505204780182e+00,
385 3.14788928951800129e+00, 3.08352613200214387e+00, 3.02783779176959378e+00, 2.97860327988184359e+00,
386 2.93436686720888806e+00, 2.89412105361341299e+00, 2.85713873087322501e+00, 2.82287739682644334e+00,
387 2.79092117400192796e+00, 2.76094400527998696e+00, 2.73268535904401189e+00, 2.70593365612306291e+00,
388 2.68051464328574562e+00, 2.65628303757674411e+00, 2.63311639363158312e+00, 2.61091051848882438e+00,
389 2.58957598670828704e+00, 2.56903545268184441e+00, 2.54922155032478370e+00, 2.53007523215985497e+00,
390 2.51154444162669499e+00, 2.49358304127104757e+00, 2.47614993967052355e+00, 2.45920837433470574e+00,
391 2.44272531820036498e+00, 2.42667098493714750e+00, 2.41101841390111993e+00, 2.39574311978192789e+00,
392 2.38082279517208617e+00, 2.36623705671729168e+00, 2.35196722737914543e+00, 2.33799614879652928e+00,
393 2.32430801887113292e+00, 2.31088825060137237e+00, 2.29772334890286434e+00, 2.28480080272449282e+00,
394 2.27210899022838264e+00, 2.25963709517378808e+00, 2.24737503294739005e+00, 2.23531338492992182e+00,
395 2.22344334009251110e+00, 2.21175664288416174e+00, 2.20024554661127691e+00, 2.18890277162636160e+00,
396 2.17772146774029363e+00, 2.16669518035430908e+00, 2.15581781987673793e+00, 2.14508363404788938e+00,
397 2.13448718284601746e+00, 2.12402331568952407e+00, 2.11368715068665391e+00, 2.10347405571487789e+00,
398 2.09337963113879244e+00, 2.08339969399830505e+00, 2.07353026351874359e+00, 2.06376754781173277e+00,
399 2.05410793165065275e+00, 2.04454796521753224e+00, 2.03508435372961971e+00, 2.02571394786385506e+00,
400 2.01643373490620492e+00, 2.00724083056052960e+00, 1.99813247135842031e+00, 1.98910600761743894e+00,
401 1.98015889690047753e+00, 1.97128869793366013e+00, 1.96249306494436371e+00, 1.95376974238464762e+00,
402 1.94511656000867905e+00, 1.93653142827569535e+00, 1.92801233405266648e+00, 1.91955733659318883e+00,
403 1.91116456377125399e+00, 1.90283220855042989e+00, 1.89455852567070537e+00, 1.88634182853678345e+00,
404 1.87818048629299650e+00, 1.87007292107126744e+00, 1.86201760539967487e+00, 1.85401305976020270e+00,
405 1.84605785028518632e+00, 1.83815058658280739e+00, 1.83028991968275778e+00, 1.82247454009388643e+00,
406 1.81470317596628328e+00, 1.80697459135082172e+00, 1.79928758454972093e+00, 1.79164098655216342e+00,
407 1.78403365954944237e+00, 1.77646449552452368e+00, 1.76893241491126929e+00, 1.76143636531891112e+00,
408 1.75397532031767245e+00, 1.74654827828172321e+00, 1.73915426128591255e+00, 1.73179231405296408e+00,
409 1.72446150294804568e+00, 1.71716091501782397e+00, 1.70988965707130269e+00, 1.70264685479992406e+00,
410 1.69543165193456247e+00, 1.68824320943719641e+00, 1.68108070472517479e+00, 1.67394333092612602e+00,
411 1.66683029616166634e+00, 1.65974082285818336e+00, 1.65267414708305682e+00, 1.64562951790478329e+00,
412 1.63860619677554875e+00, 1.63160345693487452e+00, 1.62462058283303579e+00, 1.61765686957301646e+00,
413 1.61071162236983101e+00, 1.60378415602609548e+00, 1.59687379442278909e+00, 1.58997987002419161e+00,
414 1.58310172339603006e+00, 1.57623870273590727e+00, 1.56939016341512461e+00, 1.56255546753104557e+00,
415 1.55573398346917724e+00, 1.54892508547417429e+00, 1.54212815322900276e+00, 1.53534257144151498e+00,
416 1.52856772943771313e+00, 1.52180302076099894e+00, 1.51504784277671556e+00, 1.50830159628131244e+00,
417 1.50156368511546479e+00, 1.49483351578049461e+00, 1.48811049705744858e+00, 1.48139403962818839e+00,
418 1.47468355569785659e+00, 1.46797845861808085e+00, 1.46127816251027665e+00, 1.45458208188841143e+00,
419 1.44788963128057735e+00, 1.44120022484872523e+00, 1.43451327600589340e+00, 1.42782819703025732e+00,
420 1.42114439867531028e+00, 1.41446128977547247e+00, 1.40777827684640022e+00, 1.40109476367925234e+00,
421 1.39441015092814236e+00, 1.38772383568997748e+00, 1.38103521107585681e+00, 1.37434366577316758e+00,
422 1.36764858359747765e+00, 1.36094934303328441e+00, 1.35424531676263626e+00, 1.34753587118058848e+00,
423 1.34082036589640530e+00, 1.33409815321936143e+00, 1.32736857762792715e+00, 1.32063097522105766e+00,
424 1.31388467315022184e+00, 1.30712898903073249e+00, 1.30036323033083856e+00, 1.29358669373694912e+00,
425 1.28679866449324498e+00, 1.27999841571381934e+00, 1.27318520766535781e+00, 1.26635828701823083e+00,
426 1.25951688606371559e+00, 1.25266022189489856e+00, 1.24578749554862855e+00, 1.23889789110568871e+00,
427 1.23199057474613749e+00, 1.22506469375653237e+00, 1.21811937548548310e+00, 1.21115372624370066e+00,
428 1.20416683014438308e+00, 1.19715774787944307e+00, 1.19012551542669365e+00, 1.18306914268268848e+00,
429 1.17598761201545376e+00, 1.16887987673083482e+00, 1.16174485944561323e+00, 1.15458145035992943e+00,
430 1.14738850542085080e+00, 1.14016484436815313e+00, 1.13290924865253562e+00, 1.12562045921553522e+00,
431 1.11829717411934682e+00, 1.11093804601357782e+00, 1.10354167942464176e+00, 1.09610662785202351e+00,
432 1.08863139065398196e+00, 1.08111440970340600e+00, 1.07355406579243851e+00, 1.06594867476212474e+00,
433 1.05829648333067716e+00, 1.05059566459093201e+00, 1.04284431314415116e+00, 1.03504043983344318e+00,
434 1.02718196603564804e+00, 1.01926671746548658e+00, 1.01129241743999820e+00, 1.00325667954467534e+00,
435 9.95156999635093409e-01, 9.86990747099065091e-01, 9.78755155294227297e-01, 9.70447311064227103e-01,
436 9.62064143223043233e-01, 9.53602409881088686e-01, 9.45058684468168098e-01, 9.36429340286577871e-01,
437 9.27710533402002824e-01, 9.18898183649593303e-01, 9.09987953496721236e-01, 9.00975224461224689e-01,
438 8.91855070732944566e-01, 8.82622229585168672e-01, 8.73271068088864011e-01, 8.63795545553312061e-01,
439 8.54189171008167158e-01, 8.44444954909157275e-01, 8.34555354086385592e-01, 8.24512208752295694e-01,
440 8.14306670135218735e-01, 8.03929116989974824e-01, 7.93369058840627028e-01, 7.82615023307236868e-01,
441 7.71654424224571978e-01, 7.60473406430111964e-01, 7.49056662017819397e-01, 7.37387211434299639e-01,
442 7.25446140910003923e-01, 7.13212285190980122e-01, 7.00661841106819505e-01, 6.87767892795793090e-01,
443 6.74499822837298479e-01, 6.60822574244424588e-01, 6.46695714894998885e-01, 6.32072236386066355e-01,
444 6.16896990007756774e-01, 6.01104617755998327e-01, 5.84616766106385355e-01, 5.67338257053825123e-01,
445 5.49151702327171809e-01, 5.29909720661565165e-01, 5.09423329602099240e-01, 4.87443966139244012e-01,
446 4.63634336790890889e-01, 4.37518402207881185e-01, 4.08389134612001825e-01, 3.75121332878393110e-01,
447 3.35737519214440450e-01, 2.86174591792092481e-01, 2.15241895984913806e-01, 0.00000000000000000e+00,
448];
449
450#[allow(clippy::excessive_precision)]
452#[rustfmt::skip]
453const ZIG_NORM_F: [f64; 257] = [
454 1.26028593049859559e-03, 1.26028593049859559e-03, 2.60907274610215883e-03, 4.03797259336302443e-03,
455 5.52240329925098895e-03, 7.05087547137321635e-03, 8.61658276939871945e-03, 1.02149714397014556e-02,
456 1.18427578579078704e-02, 1.34974506017398587e-02, 1.51770883079353023e-02, 1.68800831525431419e-02,
457 1.86051212757246155e-02, 2.03510962300444860e-02, 2.21170627073088294e-02, 2.39022033057958438e-02,
458 2.57058040085488548e-02, 2.75272356696030368e-02, 2.93659397581332651e-02, 3.12214171919201963e-02,
459 3.30932194585784670e-02, 3.49809414617160280e-02, 3.68842156885672290e-02, 3.88027074045260573e-02,
460 4.07361106559408701e-02, 4.26841449164743689e-02, 4.46465522512943802e-02, 4.66230949019302982e-02,
461 4.86135532158684519e-02, 5.06177238609476915e-02, 5.26354182767921064e-02, 5.46664613248888376e-02,
462 5.67106901062028185e-02, 5.87679529209336748e-02, 6.08381083495397740e-02, 6.29210244377580302e-02,
463 6.50165779712427588e-02, 6.71246538277883997e-02, 6.92451443970066721e-02, 7.13779490588902776e-02,
464 7.35229737139811712e-02, 7.56801303589269697e-02, 7.78493367020959420e-02, 8.00305158146629447e-02,
465 8.22235958132027517e-02, 8.44285095703532634e-02, 8.66451944505578497e-02, 8.88735920682756780e-02,
466 9.11136480663735232e-02, 9.33653119126907488e-02, 9.56285367130087077e-02, 9.79032790388621732e-02,
467 1.00189498768809698e-01, 1.02487158941934969e-01, 1.04796225622486777e-01, 1.07116667774683511e-01,
468 1.09448457146811506e-01, 1.11791568163837868e-01, 1.14145977827838210e-01, 1.16511665625610661e-01,
469 1.18888613442909824e-01, 1.21276805484790057e-01, 1.23676228201596392e-01, 1.26086870220185693e-01,
470 1.28508722279999349e-01, 1.30941777173644136e-01, 1.33386029691668934e-01, 1.35841476571253533e-01,
471 1.38308116448550511e-01, 1.40785949814444478e-01, 1.43274978973513212e-01, 1.45775208005993834e-01,
472 1.48286642732574331e-01, 1.50809290681845481e-01, 1.53343161060262634e-01, 1.55888264724479003e-01,
473 1.58444614155924091e-01, 1.61012223437510871e-01, 1.63591108232365501e-01, 1.66181285764481851e-01,
474 1.68782774801211288e-01, 1.71395595637505727e-01, 1.74019770081838526e-01, 1.76655321443734747e-01,
475 1.79302274522847416e-01, 1.81960655599522320e-01, 1.84630492426799020e-01, 1.87311814223800027e-01,
476 1.90004651670464736e-01, 1.92709036903588898e-01, 1.95425003514134027e-01, 1.98152586545774861e-01,
477 2.00891822494656314e-01, 2.03642749310334603e-01, 2.06405406397880464e-01, 2.09179834621124744e-01,
478 2.11966076307029905e-01, 2.14764175251173306e-01, 2.17574176724330853e-01, 2.20396127480151666e-01,
479 2.23230075763917152e-01, 2.26076071322379890e-01, 2.28934165414679924e-01, 2.31804410824338281e-01,
480 2.34686861872329566e-01, 2.37581574431237619e-01, 2.40488605940500061e-01, 2.43408015422749785e-01,
481 2.46339863501263301e-01, 2.49284212418527912e-01, 2.52241126055941567e-01, 2.55210669954661351e-01,
482 2.58192911337618569e-01, 2.61187919132720492e-01, 2.64195763997260413e-01, 2.67216518343560749e-01,
483 2.70250256365874852e-01, 2.73297054068576517e-01, 2.76356989295667710e-01, 2.79430141761637385e-01,
484 2.82516593083707079e-01, 2.85616426815501201e-01, 2.88729728482182368e-01, 2.91856585617094655e-01,
485 2.94997087799961311e-01, 2.98151326696684982e-01, 3.01319396100802550e-01, 3.04501391976649438e-01,
486 3.07697412504291501e-01, 3.10907558126285954e-01, 3.14131931596336678e-01, 3.17370638029913055e-01,
487 3.20623784956904856e-01, 3.23891482376390594e-01, 3.27173842813600846e-01, 3.30470981379162920e-01,
488 3.33783015830717733e-01, 3.37110066637005379e-01, 3.40452257044521145e-01, 3.43809713146850049e-01,
489 3.47182563956792922e-01, 3.50570941481405329e-01, 3.53974980800076000e-01, 3.57394820145779668e-01,
490 3.60830600989647143e-01, 3.64282468129003112e-01, 3.67750569779031644e-01, 3.71235057668238555e-01,
491 3.74736087137890195e-01, 3.78253817245618240e-01, 3.81788410873392714e-01, 3.85340034840076340e-01,
492 3.88908860018787828e-01, 3.92495061459314676e-01, 3.96098818515831508e-01, 3.99720314980196334e-01,
493 4.03359739221113622e-01, 4.07017284329472484e-01, 4.10693148270187325e-01, 4.14387534040890237e-01,
494 4.18100649837847282e-01, 4.21832709229495006e-01, 4.25583931338021082e-01, 4.29354541029440595e-01,
495 4.33144769112651373e-01, 4.36954852547984607e-01, 4.40785034665803044e-01, 4.44635565395738397e-01,
496 4.48506701507202010e-01, 4.52398706861847522e-01, 4.56311852678715379e-01, 4.60246417812841757e-01,
497 4.64202689048173189e-01, 4.68180961405692431e-01, 4.72181538467728978e-01, 4.76204732719504698e-01,
498 4.80250865909045588e-01, 4.84320269426682048e-01, 4.88413284705456752e-01, 4.92530263643867261e-01,
499 4.96671569052488437e-01, 5.00837575126147461e-01, 5.05028667943466902e-01, 5.09245245995746609e-01,
500 5.13487720747325516e-01, 5.17756517229754909e-01, 5.22052074672320399e-01, 5.26374847171682925e-01,
501 5.30725304403660503e-01, 5.35103932380456060e-01, 5.39511234256950467e-01, 5.43947731190024597e-01,
502 5.48413963255264147e-01, 5.52910490425830625e-01, 5.57437893618764280e-01, 5.61996775814522675e-01,
503 5.66587763256162669e-01, 5.71211506735251451e-01, 5.75868682972351942e-01, 5.80559996100789122e-01,
504 5.85286179263369566e-01, 5.90047996332824121e-01, 5.94846243767985561e-01, 5.99681752619123487e-01,
505 6.04555390697466000e-01, 6.09468064925771658e-01, 6.14420723888912002e-01, 6.19414360605832437e-01,
506 6.24450015547024617e-01, 6.29528779924834803e-01, 6.34651799287621721e-01, 6.39820277453054698e-01,
507 6.45035480820820406e-01, 6.50298743110814814e-01, 6.55611470579695377e-01, 6.60975147776661220e-01,
508 6.66391343908748102e-01, 6.71861719897079990e-01, 6.77388036218771306e-01, 6.82972161644992526e-01,
509 6.88616083004669477e-01, 6.94321916126114380e-01, 7.00091918136509284e-01, 7.05928501332751868e-01,
510 7.11834248878245979e-01, 7.17811932630719518e-01, 7.23864533468627669e-01, 7.29995264561473678e-01,
511 7.36207598126860097e-01, 7.42505296340148502e-01, 7.48892447219154267e-01, 7.55373506507093451e-01,
512 7.61953346836792611e-01, 7.68637315798483489e-01, 7.75431304981184399e-01, 7.82341832654799618e-01,
513 7.89376143566021704e-01, 7.96542330422956080e-01, 8.03849483170961387e-01, 8.11307874312653277e-01,
514 8.18929191603699369e-01, 8.26726833946218376e-01, 8.34716292986880326e-01, 8.42915653112200958e-01,
515 8.51346258458674621e-01, 8.60033621196328091e-01, 8.69008688036853494e-01, 8.78309655808913736e-01,
516 8.87984660755829602e-01, 8.98095921898339533e-01, 9.08726440052126772e-01, 9.19991505039342683e-01,
517 9.32060075959225798e-01, 9.45198953442294543e-01, 9.59879091800100892e-01, 9.77101701267664491e-01,
518 1.00000000000000000e+00,
519];
520
521#[derive(Debug, Clone)]
530pub(crate) struct DeterministicRng {
531 s: [u64; 4],
532}
533
534impl DeterministicRng {
535 pub(crate) fn from_seed(seed: u64) -> Self {
536 let mut sm = seed;
537 let mut next_sm = || {
538 sm = sm.wrapping_add(0x9e3779b97f4a7c15);
539 let mut z = sm;
540 z = (z ^ (z >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
541 z = (z ^ (z >> 27)).wrapping_mul(0x94d049bb133111eb);
542 z ^ (z >> 31)
543 };
544 let mut s = [next_sm(), next_sm(), next_sm(), next_sm()];
545 if s == [0; 4] {
546 s[0] = 1;
547 }
548 Self { s }
549 }
550
551 #[inline]
552 pub(crate) fn next_u64(&mut self) -> u64 {
553 let result = self.s[1].wrapping_mul(5).rotate_left(7).wrapping_mul(9);
554 let t = self.s[1] << 17;
555 self.s[2] ^= self.s[0];
556 self.s[3] ^= self.s[1];
557 self.s[1] ^= self.s[2];
558 self.s[0] ^= self.s[3];
559 self.s[2] ^= t;
560 self.s[3] = self.s[3].rotate_left(45);
561 result
562 }
563
564 #[inline]
566 pub(crate) fn next_open01(&mut self) -> f64 {
567 ((self.next_u64() >> 11) as f64 + 0.5) * (1.0 / 9_007_199_254_740_992.0)
568 }
569
570 #[inline]
572 pub(crate) fn next_index(&mut self, upper: usize) -> usize {
573 debug_assert!(upper > 0);
574 let bound = upper as u64;
575 let mut prod = u128::from(self.next_u64()) * u128::from(bound);
576 let mut low = prod as u64;
577 if low < bound {
578 let threshold = bound.wrapping_neg() % bound;
579 while low < threshold {
580 prod = u128::from(self.next_u64()) * u128::from(bound);
581 low = prod as u64;
582 }
583 }
584 (prod >> 64) as usize
585 }
586
587 #[inline]
590 pub(crate) fn next_standard_normal(&mut self) -> f64 {
591 loop {
592 let bits = self.next_u64();
593 let i = (bits & 0xFF) as usize;
594 let j = ((bits as i64) >> 12) as f64 + 0.5;
597 let x = j * ZIG_NORM_W[i];
598 if x.abs() < ZIG_NORM_X_INNER[i] {
599 return x;
600 }
601 if i == 0 {
602 return self.sample_normal_tail(j >= 0.0);
603 }
604 let u = self.next_open01();
605 if ZIG_NORM_F[i] + u * (ZIG_NORM_F[i + 1] - ZIG_NORM_F[i]) < (-0.5 * x * x).exp() {
606 return x;
607 }
608 }
609 }
610
611 #[cold]
612 fn sample_normal_tail(&mut self, positive: bool) -> f64 {
613 loop {
615 let tx = -self.next_open01().ln() * ZIG_NORM_INV_R;
616 let ty = -self.next_open01().ln();
617 if ty + ty >= tx * tx {
618 let mag = ZIG_NORM_R + tx;
619 return if positive { mag } else { -mag };
620 }
621 }
622 }
623
624 #[inline]
626 pub(crate) fn sample_gamma(&mut self, shape: f64, scale: f64) -> f64 {
627 if !(shape > 0.0) || !(scale > 0.0) || !shape.is_finite() || !scale.is_finite() {
628 return 0.0;
629 }
630 if shape < 1.0 {
631 let g = self.sample_gamma_ge1(shape + 1.0);
632 let u = self.next_open01();
633 return g * u.powf(1.0 / shape) * scale;
634 }
635 self.sample_gamma_ge1(shape) * scale
636 }
637
638 #[inline]
639 fn sample_gamma_ge1(&mut self, shape: f64) -> f64 {
640 let d = shape - (1.0 / 3.0);
641 let c = (1.0 / 3.0) / d.sqrt();
642 loop {
643 let z = self.next_standard_normal();
644 let v_root = 1.0 + c * z;
645 if v_root <= 0.0 {
646 continue;
647 }
648 let v = v_root * v_root * v_root;
649 let u = self.next_open01();
650 let z2 = z * z;
651 if u < 1.0 - 0.0331 * (z2 * z2) {
652 return d * v;
653 }
654 if u.ln() < 0.5 * z2 + d * (1.0 - v + v.ln()) {
655 return d * v;
656 }
657 }
658 }
659
660 pub(crate) fn sample_poisson(&mut self, lambda: f64) -> f64 {
662 if !(lambda > 0.0) || !lambda.is_finite() {
663 return 0.0;
664 }
665 if lambda < 10.0 {
666 let limit = (-lambda).exp();
667 let mut k = 0u64;
668 let mut p = 1.0;
669 loop {
670 k += 1;
671 p *= self.next_open01();
672 if p <= limit {
673 return (k - 1) as f64;
674 }
675 }
676 }
677 let s = lambda.sqrt();
680 let b = 0.931 + 2.53 * s;
681 let a = -0.059 + 0.02483 * b;
682 let inv_alpha = 1.1239 + 1.1328 / (b - 3.4);
683 let v_r = 0.9277 - 3.6224 / (b - 2.0);
684 let ln_lambda = lambda.ln();
685 loop {
686 let u = self.next_open01() - 0.5;
687 let v = self.next_open01();
688 let us = 0.5 - u.abs();
689 let k = ((2.0 * a / us + b) * u + lambda + 0.43).floor();
690 if us >= 0.07 && v <= v_r {
691 return k;
692 }
693 if k < 0.0 || (us < 0.013 && v > us) {
694 continue;
695 }
696 let lhs = (v * inv_alpha / (a / (us * us) + b)).ln();
697 let rhs = -lambda + k * ln_lambda - ln_gamma(k + 1.0);
698 if lhs <= rhs {
699 return k;
700 }
701 }
702 }
703}
704
705pub(crate) struct FastIndexSampler {
714 bound: usize,
715 threshold: u32,
716}
717
718impl FastIndexSampler {
719 #[inline]
720 pub(crate) fn new(bound: usize) -> Self {
721 debug_assert!(bound > 0);
722 let threshold = if bound <= 1024 {
723 65_536u32 % (bound as u32)
724 } else if u32::try_from(bound).is_ok() {
725 let b = bound as u32;
726 b.wrapping_neg() % b
727 } else {
728 0
729 };
730 Self { bound, threshold }
731 }
732
733 #[cold]
734 fn sample_16_slow(rng: &mut DeterministicRng, bound: u32, threshold: u32) -> usize {
735 loop {
736 let mut w = rng.next_u64();
737 for _ in 0..4 {
738 let prod = ((w & 0xFFFF) as u32) * bound;
739 if (prod & 0xFFFF) >= threshold {
740 return (prod >> 16) as usize;
741 }
742 w >>= 16;
743 }
744 }
745 }
746
747 #[cold]
748 fn sample_32_slow(rng: &mut DeterministicRng, bound: u64, threshold: u32) -> usize {
749 loop {
750 let w = rng.next_u64();
751 let p0 = (w & 0xFFFF_FFFF) * bound;
752 if (p0 as u32) >= threshold {
753 return (p0 >> 32) as usize;
754 }
755 let p1 = (w >> 32) * bound;
756 if (p1 as u32) >= threshold {
757 return (p1 >> 32) as usize;
758 }
759 }
760 }
761
762 #[inline]
763 pub(crate) fn next(&mut self, rng: &mut DeterministicRng) -> usize {
764 if self.bound <= 1 {
765 return 0;
766 }
767 if u32::try_from(self.bound).is_ok() {
768 let bound = self.bound as u64;
769 let threshold = self.threshold;
770 let prod = (rng.next_u64() >> 32) * bound;
771 if (prod as u32) >= threshold {
772 return (prod >> 32) as usize;
773 }
774 return Self::sample_32_slow(rng, bound, threshold);
775 }
776 rng.next_index(self.bound)
777 }
778
779 #[inline]
783 pub(crate) fn fill_weighted_deltas(
784 &self,
785 pool: &[f64],
786 sqrt_mu: &[f64],
787 rng: &mut DeterministicRng,
788 out: &mut [f64],
789 ) {
790 debug_assert_eq!(out.len(), sqrt_mu.len());
791 if self.bound <= 1 {
792 let r0 = pool[0];
793 for (dst, &sm) in out.iter_mut().zip(sqrt_mu.iter()) {
794 *dst = r0 * sm;
795 }
796 return;
797 }
798 if self.bound <= 1024 {
799 let bound = self.bound as u32;
800 let threshold = self.threshold;
801 let (out_chunks, out_rem) = out.as_chunks_mut::<4>();
802 let (sm_chunks, sm_rem) = sqrt_mu.as_chunks::<4>();
803 for (oc, sc) in out_chunks.iter_mut().zip(sm_chunks.iter()) {
804 let w = rng.next_u64();
805 let p0 = ((w & 0xFFFF) as u32) * bound;
806 let p1 = (((w >> 16) & 0xFFFF) as u32) * bound;
807 let p2 = (((w >> 32) & 0xFFFF) as u32) * bound;
808 let p3 = ((w >> 48) as u32) * bound;
809 let l0 = p0 & 0xFFFF;
810 let l1 = p1 & 0xFFFF;
811 let l2 = p2 & 0xFFFF;
812 let l3 = p3 & 0xFFFF;
813 if l0.min(l1).min(l2).min(l3) >= threshold {
814 oc[0] = pool[(p0 >> 16) as usize] * sc[0];
815 oc[1] = pool[(p1 >> 16) as usize] * sc[1];
816 oc[2] = pool[(p2 >> 16) as usize] * sc[2];
817 oc[3] = pool[(p3 >> 16) as usize] * sc[3];
818 } else {
819 let i0 = if l0 >= threshold {
820 (p0 >> 16) as usize
821 } else {
822 Self::sample_16_slow(rng, bound, threshold)
823 };
824 let i1 = if l1 >= threshold {
825 (p1 >> 16) as usize
826 } else {
827 Self::sample_16_slow(rng, bound, threshold)
828 };
829 let i2 = if l2 >= threshold {
830 (p2 >> 16) as usize
831 } else {
832 Self::sample_16_slow(rng, bound, threshold)
833 };
834 let i3 = if l3 >= threshold {
835 (p3 >> 16) as usize
836 } else {
837 Self::sample_16_slow(rng, bound, threshold)
838 };
839 oc[0] = pool[i0] * sc[0];
840 oc[1] = pool[i1] * sc[1];
841 oc[2] = pool[i2] * sc[2];
842 oc[3] = pool[i3] * sc[3];
843 }
844 }
845 if !out_rem.is_empty() {
846 let mut w = rng.next_u64();
847 for (dst, &sm) in out_rem.iter_mut().zip(sm_rem.iter()) {
848 let p = ((w & 0xFFFF) as u32) * bound;
849 w >>= 16;
850 let idx = if (p & 0xFFFF) >= threshold {
851 (p >> 16) as usize
852 } else {
853 Self::sample_16_slow(rng, bound, threshold)
854 };
855 *dst = pool[idx] * sm;
856 }
857 }
858 return;
859 }
860 if u32::try_from(self.bound).is_ok() {
861 let bound = self.bound as u64;
862 let threshold = self.threshold;
863 let (out_chunks, out_rem) = out.as_chunks_mut::<2>();
864 let (sm_chunks, sm_rem) = sqrt_mu.as_chunks::<2>();
865 for (oc, sc) in out_chunks.iter_mut().zip(sm_chunks.iter()) {
866 let w = rng.next_u64();
867 let p0 = (w & 0xFFFF_FFFF) * bound;
868 let p1 = (w >> 32) * bound;
869 let l0 = p0 as u32;
870 let l1 = p1 as u32;
871 if l0.min(l1) >= threshold {
872 oc[0] = pool[(p0 >> 32) as usize] * sc[0];
873 oc[1] = pool[(p1 >> 32) as usize] * sc[1];
874 } else {
875 let i0 = if l0 >= threshold {
876 (p0 >> 32) as usize
877 } else {
878 Self::sample_32_slow(rng, bound, threshold)
879 };
880 let i1 = if l1 >= threshold {
881 (p1 >> 32) as usize
882 } else {
883 Self::sample_32_slow(rng, bound, threshold)
884 };
885 oc[0] = pool[i0] * sc[0];
886 oc[1] = pool[i1] * sc[1];
887 }
888 }
889 if let (Some(dst), Some(&sm)) = (out_rem.first_mut(), sm_rem.first()) {
890 let p = (rng.next_u64() >> 32) * bound;
891 let idx = if (p as u32) >= threshold {
892 (p >> 32) as usize
893 } else {
894 Self::sample_32_slow(rng, bound, threshold)
895 };
896 *dst = pool[idx] * sm;
897 }
898 return;
899 }
900 for (dst, &sm) in out.iter_mut().zip(sqrt_mu.iter()) {
901 *dst = pool[rng.next_index(self.bound)] * sm;
902 }
903 }
904}
905
906pub(crate) fn ln_gamma(z: f64) -> f64 {
908 const COEFFS: [f64; 9] = [
909 0.999_999_999_999_809_9,
910 676.520_368_121_885_1,
911 -1_259.139_216_722_402_8,
912 771.323_428_777_653_1,
913 -176.615_029_162_140_6,
914 12.507_343_278_686_905,
915 -0.138_571_095_265_720_12,
916 9.984_369_578_019_572e-6,
917 1.505_632_735_149_311_6e-7,
918 ];
919 let x = z - 1.0;
920 let mut sum = COEFFS[0];
921 for (idx, &coeff) in COEFFS.iter().enumerate().skip(1) {
922 sum += coeff / (x + idx as f64);
923 }
924 let t = x + 7.5;
925 0.5 * TAU.ln() + (x + 0.5) * t.ln() - t + sum.ln()
926}
927
928struct OdpSolvedDiagnostics {
933 residuals: Vec<OdpCellResidual>,
934 n_observed: usize,
935 rank: usize,
936 degrees_of_freedom: usize,
937 dispersion: f64,
938 origin_reserves: Vec<f64>,
939 total_reserve: f64,
940 analytic_origin_process_se: Vec<f64>,
941 analytic_origin_param_se: Vec<f64>,
942 analytic_origin_prediction_error: Vec<f64>,
943 analytic_total_process_se: f64,
944 analytic_total_param_se: f64,
945 analytic_total_prediction_error: f64,
946}
947
948fn try_solve_odp_tridiagonal(
961 n: usize,
962 ldfs: &[f64],
963 tail: f64,
964 latest: &[f64],
965 fitted_cumulative: &[f64],
966 fitted_incremental: &[f64],
967 observed_incremental: &[f64],
968) -> Option<OdpSolvedDiagnostics> {
969 let m = n - 1;
970 if latest.iter().any(|&v| !(v > 0.0) || !v.is_finite())
971 || ldfs.iter().any(|&f| !(f > 1.0) || !f.is_finite())
972 {
973 return None;
974 }
975
976 let mut cdfs_to_last = vec![0.0; n];
978 cdfs_from_ldfs(ldfs, 1.0, &mut cdfs_to_last);
979 let mut b_cum = vec![0.0; n];
980 let mut beta = vec![0.0; n];
981 for j in 0..n {
982 let inv_cdf = 1.0 / cdfs_to_last[j];
983 if !inv_cdf.is_finite() || !(inv_cdf > 0.0) {
984 return None;
985 }
986 b_cum[j] = inv_cdf;
987 beta[j] = if j == 0 {
988 inv_cdf
989 } else {
990 inv_cdf - b_cum[j - 1]
991 };
992 if !(beta[j] > 0.0) || !beta[j].is_finite() {
993 return None;
994 }
995 }
996
997 let mut alpha = vec![0.0; n];
998 for i in 0..n {
999 let a = fitted_cumulative[i * n + m];
1000 if !(a > 0.0) || !a.is_finite() {
1001 return None;
1002 }
1003 alpha[i] = a;
1004 }
1005
1006 let mut a_sum = vec![0.0; n];
1008 let mut acc = 0.0;
1009 for k in (0..n).rev() {
1010 acc += alpha[m - k];
1011 a_sum[k] = acc;
1012 }
1013
1014 let mut d = vec![0.0; m];
1016 let mut e = vec![0.0; m.saturating_sub(1)];
1017 for k in 1..n {
1018 let idx = k - 1;
1019 if k < m {
1020 let off = a_sum[k + 1] / beta[k + 1];
1021 d[idx] = a_sum[k] / beta[k] + off - alpha[m - k] / b_cum[k];
1022 e[idx] = -off;
1023 } else {
1024 d[idx] = a_sum[k] / beta[k] - alpha[0] / b_cum[k];
1025 }
1026 }
1027
1028 let mut d_tilde = vec![0.0; m];
1030 let mut gamma = vec![0.0; m.saturating_sub(1)];
1031 if !d[0].is_finite() || d[0] <= 0.0 {
1032 return None;
1033 }
1034 d_tilde[0] = d[0];
1035 for idx in 0..(m - 1) {
1036 let g = -e[idx] / d_tilde[idx];
1037 let next_dt = d[idx + 1] + e[idx] * g;
1038 if !g.is_finite() || !next_dt.is_finite() || next_dt <= 1e-14 * d[idx + 1].abs().max(1e-30)
1039 {
1040 return None;
1041 }
1042 gamma[idx] = g;
1043 d_tilde[idx + 1] = next_dt;
1044 }
1045
1046 let mut g_diag = vec![0.0; m];
1048 g_diag[m - 1] = 1.0 / d_tilde[m - 1];
1049 for idx in (0..(m - 1)).rev() {
1050 g_diag[idx] = 1.0 / d_tilde[idx] + gamma[idx] * gamma[idx] * g_diag[idx + 1];
1051 }
1052
1053 let mut w_g_w = vec![0.0; n];
1055 w_g_w[1] = g_diag[0] / (beta[1] * beta[1]);
1056 for j in 2..n {
1057 let g_jm1_j = gamma[j - 2] * g_diag[j - 1];
1058 w_g_w[j] = (g_diag[j - 1] - 2.0 * g_jm1_j + g_diag[j - 2]) / (beta[j] * beta[j]);
1059 }
1060
1061 let n_observed = n * (n + 1) / 2;
1063 let rank = 2 * n - 1;
1064 let degrees_of_freedom = n_observed - rank;
1065 let mut residuals = Vec::with_capacity(n_observed);
1066 let mut pearson_sq_sum = 0.0;
1067 let mut g_row = vec![0.0; n];
1068
1069 for origin in 0..n {
1070 let ki = m - origin;
1071 if ki >= 1 {
1072 g_row[ki] = g_diag[ki - 1];
1073 for j in (1..ki).rev() {
1074 g_row[j] = gamma[j - 1] * g_row[j + 1];
1075 }
1076 }
1077 let inv_b_ki = 1.0 / b_cum[ki];
1078 let base_phi = inv_b_ki / alpha[origin];
1079 let z_g_z = if ki >= 1 {
1080 g_diag[ki - 1] * inv_b_ki * inv_b_ki
1081 } else {
1082 0.0
1083 };
1084 let row_off = origin * n;
1085
1086 for dev in 0..=ki {
1087 let obs = observed_incremental[row_off + dev];
1088 let mu = fitted_incremental[row_off + dev];
1089 if !(mu > 0.0) || !mu.is_finite() {
1090 return None;
1091 }
1092 let raw_residual = (obs - mu) / mu.sqrt();
1093 pearson_sq_sum += raw_residual * raw_residual;
1094
1095 let y_g_y = if dev == 0 {
1096 z_g_z
1097 } else if dev == 1 {
1098 let w_g_z = -g_row[1] * inv_b_ki / beta[1];
1099 w_g_w[1] + 2.0 * w_g_z + z_g_z
1100 } else {
1101 let w_g_z = -(g_row[dev] - g_row[dev - 1]) * inv_b_ki / beta[dev];
1102 w_g_w[dev] + 2.0 * w_g_z + z_g_z
1103 };
1104 let leverage = (mu * (base_phi + y_g_y)).clamp(0.0, 1.0);
1105 let saturated = (1.0 - leverage) <= 1e-10;
1106
1107 residuals.push(OdpCellResidual {
1108 origin,
1109 dev,
1110 observed_incremental: obs,
1111 fitted_incremental: mu,
1112 raw_pearson_residual: raw_residual,
1113 leverage,
1114 saturated,
1115 });
1116 }
1117 }
1118
1119 let dispersion = pearson_sq_sum / degrees_of_freedom as f64;
1120
1121 let mut g_last = vec![0.0; m];
1123 g_last[m - 1] = g_diag[m - 1];
1124 for idx in (0..(m - 1)).rev() {
1125 g_last[idx] = gamma[idx] * g_last[idx + 1];
1126 }
1127
1128 let mut origin_reserves = vec![0.0; n];
1130 let mut analytic_origin_process_se = vec![0.0; n];
1131 let mut analytic_origin_param_se = vec![0.0; n];
1132 let mut analytic_origin_prediction_error = vec![0.0; n];
1133 let mut pre_tail_total_reserve = 0.0;
1134 let mut r_diag_sum = 0.0;
1135 let g_mm = g_diag[m - 1];
1136
1137 for origin in 0..n {
1138 let ki = m - origin;
1139 let ai = alpha[origin];
1140 let r_pre_tail = if origin == 0 {
1141 0.0
1142 } else {
1143 ai * (1.0 - b_cum[ki])
1144 };
1145 pre_tail_total_reserve += r_pre_tail;
1146 let tail_increment = ai * (tail - 1.0);
1147 origin_reserves[origin] = r_pre_tail + tail_increment;
1148
1149 let param_quad = if origin == 0 {
1150 0.0
1151 } else if origin < m {
1152 let inv_b = 1.0 / b_cum[ki];
1153 let diag_term = (r_pre_tail * r_pre_tail) * inv_b / ai;
1154 r_diag_sum += diag_term;
1155 diag_term
1156 + ai * ai * (g_diag[ki - 1] * inv_b * inv_b - 2.0 * g_last[ki - 1] * inv_b + g_mm)
1157 } else {
1158 let diag_term = (r_pre_tail * r_pre_tail) / (ai * b_cum[0]);
1159 r_diag_sum += diag_term;
1160 diag_term + ai * ai * g_mm
1161 };
1162 let param_var = (dispersion * param_quad).max(0.0);
1163 let proc_var = (dispersion * r_pre_tail).max(0.0);
1164 analytic_origin_process_se[origin] = proc_var.sqrt();
1165 analytic_origin_param_se[origin] = param_var.sqrt();
1166 analytic_origin_prediction_error[origin] = (proc_var + param_var).sqrt();
1167 }
1168
1169 let mut total_quad = r_diag_sum;
1171 let mut z_prev = 0.0;
1172 for idx in 0..m {
1173 let k = idx + 1;
1174 let y_k = if k < m {
1175 -alpha[m - k] / b_cum[k]
1176 } else {
1177 a_sum[0] - alpha[0]
1178 };
1179 let z_k = if idx == 0 {
1180 y_k
1181 } else {
1182 y_k + gamma[idx - 1] * z_prev
1183 };
1184 total_quad += (z_k * z_k) / d_tilde[idx];
1185 z_prev = z_k;
1186 }
1187
1188 let total_reserve: f64 = origin_reserves.iter().sum();
1189 let total_param_var = (dispersion * total_quad).max(0.0);
1190 let total_proc_var = (dispersion * pre_tail_total_reserve).max(0.0);
1191
1192 Some(OdpSolvedDiagnostics {
1193 residuals,
1194 n_observed,
1195 rank,
1196 degrees_of_freedom,
1197 dispersion,
1198 origin_reserves,
1199 total_reserve,
1200 analytic_origin_process_se,
1201 analytic_origin_param_se,
1202 analytic_origin_prediction_error,
1203 analytic_total_process_se: total_proc_var.sqrt(),
1204 analytic_total_param_se: total_param_var.sqrt(),
1205 analytic_total_prediction_error: (total_proc_var + total_param_var).sqrt(),
1206 })
1207}
1208
1209fn solve_odp_general(
1214 n: usize,
1215 tail: f64,
1216 fitted_cumulative: &[f64],
1217 fitted_incremental: &[f64],
1218 observed_incremental: &[f64],
1219) -> Result<OdpSolvedDiagnostics, ValidationError> {
1220 let mut active_origins = vec![false; n];
1221 let mut active_devs = vec![false; n];
1222 let mut active_cells: Vec<(usize, usize)> = Vec::with_capacity(n * (n + 1) / 2);
1223 for origin in 0..n {
1224 for dev in 0..(n - origin) {
1225 let mu = fitted_incremental[origin * n + dev];
1226 if mu.is_finite() && mu > 0.0 {
1227 active_origins[origin] = true;
1228 active_devs[dev] = true;
1229 active_cells.push((origin, dev));
1230 }
1231 }
1232 }
1233
1234 let mut origin_col = vec![None; n];
1235 let mut dev_col = vec![None; n];
1236 let mut param_count = 1usize;
1237 let mut first_origin_skipped = false;
1238 for origin in 0..n {
1239 if active_origins[origin] {
1240 if first_origin_skipped {
1241 origin_col[origin] = Some(param_count);
1242 param_count += 1;
1243 } else {
1244 first_origin_skipped = true;
1245 }
1246 }
1247 }
1248 let mut first_dev_skipped = false;
1249 for dev in 0..n {
1250 if active_devs[dev] {
1251 if first_dev_skipped {
1252 dev_col[dev] = Some(param_count);
1253 param_count += 1;
1254 } else {
1255 first_dev_skipped = true;
1256 }
1257 }
1258 }
1259
1260 let n_observed = active_cells.len();
1261 if n_observed <= param_count {
1262 return Err(ValidationError::InvalidParameter(
1263 "ODP model has non-positive residual degrees of freedom",
1264 ));
1265 }
1266 let degrees_of_freedom = n_observed - param_count;
1267
1268 let mut info = vec![0.0; param_count * param_count];
1270 for &(origin, dev) in &active_cells {
1271 let w = fitted_incremental[origin * n + dev];
1272 let mut cols = [0usize; 3];
1273 let mut ncols = 1usize;
1274 if let Some(c) = origin_col[origin] {
1275 cols[ncols] = c;
1276 ncols += 1;
1277 }
1278 if let Some(c) = dev_col[dev] {
1279 cols[ncols] = c;
1280 ncols += 1;
1281 }
1282 for a in 0..ncols {
1283 for b in 0..ncols {
1284 info[cols[a] * param_count + cols[b]] += w;
1285 }
1286 }
1287 }
1288
1289 let chol = cholesky_lower(&info, param_count)?;
1290 let info_inv = invert_spd(&info, param_count)?;
1291
1292 let mut residuals = Vec::with_capacity(n_observed);
1294 let mut pearson_sq_sum = 0.0;
1295 for &(origin, dev) in &active_cells {
1296 let obs = observed_incremental[origin * n + dev];
1297 let mu = fitted_incremental[origin * n + dev];
1298 let raw_residual = (obs - mu) / mu.sqrt();
1299 pearson_sq_sum += raw_residual * raw_residual;
1300
1301 let mut cols = [0usize; 3];
1302 let mut ncols = 1usize;
1303 if let Some(c) = origin_col[origin] {
1304 cols[ncols] = c;
1305 ncols += 1;
1306 }
1307 if let Some(c) = dev_col[dev] {
1308 cols[ncols] = c;
1309 ncols += 1;
1310 }
1311 let mut qf = 0.0;
1312 for a in 0..ncols {
1313 let ca = cols[a];
1314 qf += info_inv[ca * param_count + ca];
1315 for b in (a + 1)..ncols {
1316 qf += 2.0 * info_inv[ca * param_count + cols[b]];
1317 }
1318 }
1319 let leverage = (mu * qf).clamp(0.0, 1.0);
1320 let saturated = (1.0 - leverage) <= 1e-10;
1321
1322 residuals.push(OdpCellResidual {
1323 origin,
1324 dev,
1325 observed_incremental: obs,
1326 fitted_incremental: mu,
1327 raw_pearson_residual: raw_residual,
1328 leverage,
1329 saturated,
1330 });
1331 }
1332
1333 let dispersion = pearson_sq_sum / degrees_of_freedom as f64;
1334
1335 let mut origin_reserves = vec![0.0; n];
1336 let mut analytic_origin_process_se = vec![0.0; n];
1337 let mut analytic_origin_param_se = vec![0.0; n];
1338 let mut analytic_origin_prediction_error = vec![0.0; n];
1339 let mut g_total = vec![0.0; param_count];
1340 let mut g_origin = vec![0.0; param_count];
1341 let mut y_buf = vec![0.0; param_count];
1342 let mut pre_tail_total_reserve = 0.0;
1343
1344 for origin in 0..n {
1345 g_origin.fill(0.0);
1346 let mut r_pre_tail = 0.0;
1347 for dev in (n - origin)..n {
1348 let mu = fitted_incremental[origin * n + dev];
1349 r_pre_tail += mu;
1350 g_origin[0] += mu;
1351 g_total[0] += mu;
1352 if let Some(c) = origin_col[origin] {
1353 g_origin[c] += mu;
1354 g_total[c] += mu;
1355 }
1356 if let Some(c) = dev_col[dev] {
1357 g_origin[c] += mu;
1358 g_total[c] += mu;
1359 }
1360 }
1361 pre_tail_total_reserve += r_pre_tail;
1362 let tail_increment = fitted_cumulative[origin * n + (n - 1)] * (tail - 1.0);
1363 origin_reserves[origin] = r_pre_tail + tail_increment;
1364
1365 solve_lower_into(&chol, param_count, &g_origin, &mut y_buf);
1366 let param_var = (dispersion * y_buf.iter().map(|v| v * v).sum::<f64>()).max(0.0);
1367 let proc_var = (dispersion * r_pre_tail).max(0.0);
1368 analytic_origin_process_se[origin] = proc_var.sqrt();
1369 analytic_origin_param_se[origin] = param_var.sqrt();
1370 analytic_origin_prediction_error[origin] = (proc_var + param_var).sqrt();
1371 }
1372
1373 let total_reserve: f64 = origin_reserves.iter().sum();
1374 solve_lower_into(&chol, param_count, &g_total, &mut y_buf);
1375 let total_param_var = (dispersion * y_buf.iter().map(|v| v * v).sum::<f64>()).max(0.0);
1376 let total_proc_var = (dispersion * pre_tail_total_reserve).max(0.0);
1377
1378 Ok(OdpSolvedDiagnostics {
1379 residuals,
1380 n_observed,
1381 rank: param_count,
1382 degrees_of_freedom,
1383 dispersion,
1384 origin_reserves,
1385 total_reserve,
1386 analytic_origin_process_se,
1387 analytic_origin_param_se,
1388 analytic_origin_prediction_error,
1389 analytic_total_process_se: total_proc_var.sqrt(),
1390 analytic_total_param_se: total_param_var.sqrt(),
1391 analytic_total_prediction_error: (total_proc_var + total_param_var).sqrt(),
1392 })
1393}
1394
1395pub fn fit_odp(
1402 triangle: &TriangleView<'_>,
1403 tail: f64,
1404 policy: MonotonicityPolicy,
1405) -> Result<OdpFit, ValidationError> {
1406 validate_triangle(triangle)?;
1407 if policy == MonotonicityPolicy::Strict {
1408 validate_monotone_cumulative(triangle)?;
1409 }
1410 validate_tail(tail)?;
1411
1412 let n = triangle.n_origins;
1413 if n < 3 {
1414 return Err(ValidationError::InvalidParameter(
1415 "ODP model requires at least a 3x3 triangle for positive degrees of freedom",
1416 ));
1417 }
1418
1419 let mut ldfs = vec![0.0; n - 1];
1421 volume_weighted_ldfs(triangle.data, n, n, &mut ldfs);
1422 for &f in &ldfs {
1423 if !f.is_finite() {
1424 return Err(ValidationError::NotFinite);
1425 }
1426 if f <= 0.0 {
1427 return Err(ValidationError::DivideByZero("development denominator"));
1428 }
1429 if f < 1.0 {
1430 return Err(ValidationError::InvalidParameter(
1431 "ODP GLM requires non-negative fitted expectations (all volume-weighted LDFs >= 1.0)",
1432 ));
1433 }
1434 }
1435
1436 let observed_incremental = cumulative_to_incremental(triangle);
1437 let latest = latest_diagonal(triangle);
1438
1439 let mut fitted_cumulative = vec![0.0; n * n];
1441 for origin in 0..n {
1442 let d = n - 1 - origin;
1443 let row_off = origin * n;
1444 fitted_cumulative[row_off + d] = latest[origin];
1445 for dev in (0..d).rev() {
1446 fitted_cumulative[row_off + dev] = fitted_cumulative[row_off + dev + 1] / ldfs[dev];
1447 }
1448 for dev in (d + 1)..n {
1449 fitted_cumulative[row_off + dev] = fitted_cumulative[row_off + dev - 1] * ldfs[dev - 1];
1450 }
1451 }
1452
1453 let mut fitted_incremental = vec![0.0; n * n];
1454 for origin in 0..n {
1455 let row_off = origin * n;
1456 fitted_incremental[row_off] = fitted_cumulative[row_off];
1457 for dev in 1..n {
1458 fitted_incremental[row_off + dev] =
1459 fitted_cumulative[row_off + dev] - fitted_cumulative[row_off + dev - 1];
1460 }
1461 }
1462
1463 let solved = match try_solve_odp_tridiagonal(
1464 n,
1465 &ldfs,
1466 tail,
1467 &latest,
1468 &fitted_cumulative,
1469 &fitted_incremental,
1470 &observed_incremental,
1471 ) {
1472 Some(fast) => fast,
1473 None => solve_odp_general(
1474 n,
1475 tail,
1476 &fitted_cumulative,
1477 &fitted_incremental,
1478 &observed_incremental,
1479 )?,
1480 };
1481
1482 Ok(OdpFit {
1483 n_origins: n,
1484 n_devs: n,
1485 ldfs,
1486 tail,
1487 fitted_cumulative,
1488 fitted_incremental,
1489 observed_incremental,
1490 residuals: solved.residuals,
1491 n_observed: solved.n_observed,
1492 rank: solved.rank,
1493 degrees_of_freedom: solved.degrees_of_freedom,
1494 dispersion: solved.dispersion,
1495 origin_reserves: solved.origin_reserves,
1496 total_reserve: solved.total_reserve,
1497 analytic_origin_process_se: solved.analytic_origin_process_se,
1498 analytic_origin_param_se: solved.analytic_origin_param_se,
1499 analytic_origin_prediction_error: solved.analytic_origin_prediction_error,
1500 analytic_total_process_se: solved.analytic_total_process_se,
1501 analytic_total_param_se: solved.analytic_total_param_se,
1502 analytic_total_prediction_error: solved.analytic_total_prediction_error,
1503 })
1504}
1505
1506pub(crate) fn build_adjusted_residual_pool(
1508 fit: &OdpFit,
1509 adjustment: ResidualAdjustment,
1510 center: bool,
1511) -> Result<(Vec<f64>, f64), ValidationError> {
1512 let mut pool = Vec::with_capacity(fit.residuals.len());
1513 match adjustment {
1514 ResidualAdjustment::DegreesOfFreedom => {
1515 let scale = (fit.n_observed as f64 / fit.degrees_of_freedom as f64).sqrt();
1516 for cell in &fit.residuals {
1517 pool.push(cell.raw_pearson_residual * scale);
1518 }
1519 }
1520 ResidualAdjustment::HatMatrixLeverage => {
1521 for cell in &fit.residuals {
1522 if !cell.saturated {
1523 pool.push(cell.raw_pearson_residual / (1.0 - cell.leverage).sqrt());
1524 }
1525 }
1526 }
1527 }
1528 if pool.is_empty() {
1529 return Err(ValidationError::InvalidParameter(
1530 "no eligible residuals available for ODP bootstrap resampling",
1531 ));
1532 }
1533 let pool_mean = pool.iter().sum::<f64>() / pool.len() as f64;
1534 if center {
1535 for r in &mut pool {
1536 *r -= pool_mean;
1537 }
1538 }
1539 Ok((pool, pool_mean))
1540}
1541
1542pub(crate) struct OdpBootstrapScratch {
1550 n: usize,
1551 all_observed_positive: bool,
1552 pub(crate) inv_phi: f64,
1553 packed_sqrt_mu: Vec<f64>,
1554 cell_deltas: Vec<f64>,
1555 base_col_den: Vec<f64>,
1556 base_latest: Vec<f64>,
1557 delta_col_den: Vec<f64>,
1558 latest_pseudo: Vec<f64>,
1559 pub(crate) pseudo_ldfs: Vec<f64>,
1560 origin_reserves: Vec<f64>,
1561}
1562
1563impl OdpBootstrapScratch {
1564 pub(crate) fn for_fit(fit: &OdpFit) -> Self {
1565 let n = fit.n_origins;
1566 let m = n.saturating_sub(1);
1567 let upper_len = n * (n + 1) / 2;
1568 let mut packed_sqrt_mu = Vec::with_capacity(upper_len);
1569 let mut base_col_den = vec![0.0; m];
1570 let mut base_latest = vec![0.0; n];
1571
1572 for origin in 0..n {
1573 let row_off = origin * n;
1574 let last_dev = n - 1 - origin;
1575 for dev in 0..=last_dev {
1576 let mu = fit.fitted_incremental[row_off + dev];
1577 packed_sqrt_mu.push(if mu > 0.0 { mu.sqrt() } else { 0.0 });
1578 if dev < last_dev {
1579 base_col_den[dev] += fit.fitted_cumulative[row_off + dev];
1580 }
1581 }
1582 base_latest[origin] = fit.fitted_cumulative[row_off + last_dev];
1583 }
1584
1585 let inv_phi = if fit.dispersion > 0.0 && fit.dispersion.is_finite() {
1586 1.0 / fit.dispersion
1587 } else {
1588 0.0
1589 };
1590
1591 Self {
1592 n,
1593 all_observed_positive: fit.n_observed == upper_len,
1594 inv_phi,
1595 packed_sqrt_mu,
1596 cell_deltas: vec![0.0; upper_len],
1597 base_col_den,
1598 base_latest,
1599 delta_col_den: vec![0.0; m],
1600 latest_pseudo: vec![0.0; n],
1601 pseudo_ldfs: vec![0.0; m],
1602 origin_reserves: vec![0.0; n],
1603 }
1604 }
1605}
1606
1607#[derive(Clone, Copy)]
1608pub(crate) struct RefitOutcome {
1609 pub(crate) valid: bool,
1610 all_ldfs_ge_one: bool,
1611}
1612
1613#[inline]
1616fn finalize_pseudo_ldfs(scratch: &mut OdpBootstrapScratch) -> RefitOutcome {
1617 let m = scratch.n.saturating_sub(1);
1618 let mut all_ge_one = true;
1619 let mut next_den = 0.0;
1620 for k in (0..m).rev() {
1621 let den = scratch.base_col_den[k] + scratch.delta_col_den[k];
1622 if !(den > 0.0) || !den.is_finite() {
1623 return RefitOutcome {
1624 valid: false,
1625 all_ldfs_ge_one: false,
1626 };
1627 }
1628 let num = next_den + scratch.latest_pseudo[m - 1 - k];
1629 let f = num / den;
1630 if !f.is_finite() || f <= 0.0 {
1631 return RefitOutcome {
1632 valid: false,
1633 all_ldfs_ge_one: false,
1634 };
1635 }
1636 if f < 1.0 {
1637 all_ge_one = false;
1638 }
1639 scratch.pseudo_ldfs[k] = f;
1640 next_den = den;
1641 }
1642 RefitOutcome {
1643 valid: true,
1644 all_ldfs_ge_one: all_ge_one,
1645 }
1646}
1647
1648#[inline]
1653fn accumulate_cell_deltas_and_refit(scratch: &mut OdpBootstrapScratch) -> RefitOutcome {
1654 let n = scratch.n;
1655 let m = n.saturating_sub(1);
1656 let deltas = &scratch.cell_deltas;
1657 let delta_den = &mut scratch.delta_col_den;
1658 let latest_out = &mut scratch.latest_pseudo;
1659 let base_latest = &scratch.base_latest;
1660
1661 let mut row_start = 0usize;
1664 let mut origin = 0usize;
1665 if m >= 2 {
1666 let r0 = &deltas[0..n];
1667 let r1 = &deltas[n..2 * n - 1];
1668 row_start = 2 * n - 1;
1669 let mut run0 = 0.0;
1670 let mut run1 = 0.0;
1671 for (den_slot, (&d0, &d1)) in delta_den[..m - 1]
1672 .iter_mut()
1673 .zip(r0[..m - 1].iter().zip(r1[..m - 1].iter()))
1674 {
1675 run0 += d0;
1676 run1 += d1;
1677 *den_slot = run0 + run1;
1678 }
1679 run0 += r0[m - 1];
1680 delta_den[m - 1] = run0;
1681 latest_out[0] = base_latest[0] + run0 + r0[m];
1682 latest_out[1] = base_latest[1] + run1 + r1[m - 1];
1683 origin = 2;
1684 } else if m == 1 {
1685 let d0 = deltas[0];
1686 delta_den[0] = d0;
1687 latest_out[0] = base_latest[0] + d0 + deltas[1];
1688 row_start = 2;
1689 origin = 1;
1690 }
1691
1692 while origin + 1 < m {
1694 let len_a = n - origin; let len_b = len_a - 1; let ra = &deltas[row_start..row_start + len_a];
1697 let rb = &deltas[row_start + len_a..row_start + len_a + len_b];
1698 row_start += len_a + len_b;
1699
1700 let last_a = len_a - 1;
1701 let last_b = len_b - 1;
1702 let mut run_a = 0.0;
1703 let mut run_b = 0.0;
1704 for (den_slot, (&da, &db)) in delta_den[..last_b]
1705 .iter_mut()
1706 .zip(ra[..last_b].iter().zip(rb[..last_b].iter()))
1707 {
1708 run_a += da;
1709 run_b += db;
1710 *den_slot += run_a + run_b;
1711 }
1712 run_a += ra[last_b];
1713 delta_den[last_b] += run_a;
1714 latest_out[origin] = base_latest[origin] + run_a + ra[last_a];
1715 latest_out[origin + 1] = base_latest[origin + 1] + run_b + rb[last_b];
1716 origin += 2;
1717 }
1718
1719 if origin < m {
1720 let last_dev = m - origin;
1721 let row = &deltas[row_start..=(row_start + last_dev)];
1722 row_start += last_dev + 1;
1723 let mut running = 0.0;
1724 for (den_slot, &d) in delta_den[..last_dev].iter_mut().zip(&row[..last_dev]) {
1725 running += d;
1726 *den_slot += running;
1727 }
1728 latest_out[origin] = base_latest[origin] + running + row[last_dev];
1729 }
1730 latest_out[m] = base_latest[m] + deltas[row_start];
1731
1732 finalize_pseudo_ldfs(scratch)
1733}
1734
1735#[inline]
1738pub(crate) fn refit_pseudo_ldfs_from_pool(
1739 pool: &[f64],
1740 sampler: &mut FastIndexSampler,
1741 rng: &mut DeterministicRng,
1742 scratch: &mut OdpBootstrapScratch,
1743) -> RefitOutcome {
1744 if scratch.all_observed_positive {
1745 sampler.fill_weighted_deltas(pool, &scratch.packed_sqrt_mu, rng, &mut scratch.cell_deltas);
1746 return accumulate_cell_deltas_and_refit(scratch);
1747 }
1748
1749 for (dst, &sm) in scratch
1751 .cell_deltas
1752 .iter_mut()
1753 .zip(scratch.packed_sqrt_mu.iter())
1754 {
1755 *dst = if sm > 0.0 {
1756 pool[sampler.next(rng)] * sm
1757 } else {
1758 0.0
1759 };
1760 }
1761 accumulate_cell_deltas_and_refit(scratch)
1762}
1763
1764#[inline]
1767fn refit_pseudo_ldfs_from_slice(
1768 sampled_residuals: &[f64],
1769 scratch: &mut OdpBootstrapScratch,
1770) -> RefitOutcome {
1771 if scratch.all_observed_positive {
1772 for ((dst, &r), &sm) in scratch
1773 .cell_deltas
1774 .iter_mut()
1775 .zip(sampled_residuals.iter())
1776 .zip(scratch.packed_sqrt_mu.iter())
1777 {
1778 *dst = r * sm;
1779 }
1780 return accumulate_cell_deltas_and_refit(scratch);
1781 }
1782
1783 let mut r_idx = 0usize;
1784 for (dst, &sm) in scratch
1785 .cell_deltas
1786 .iter_mut()
1787 .zip(scratch.packed_sqrt_mu.iter())
1788 {
1789 if sm > 0.0 {
1790 *dst = sampled_residuals[r_idx] * sm;
1791 r_idx += 1;
1792 } else {
1793 *dst = 0.0;
1794 }
1795 }
1796 accumulate_cell_deltas_and_refit(scratch)
1797}
1798
1799#[inline]
1800fn sample_positive_process(
1801 mag: f64,
1802 phi: f64,
1803 inv_phi: f64,
1804 dist: ProcessDistribution,
1805 rng: &mut DeterministicRng,
1806) -> f64 {
1807 if !(phi > 0.0) || !(mag > 0.0) || !mag.is_finite() {
1808 return mag;
1809 }
1810 match dist {
1811 ProcessDistribution::Gamma => rng.sample_gamma(mag * inv_phi, phi),
1812 ProcessDistribution::OverDispersedPoisson => phi * rng.sample_poisson(mag * inv_phi),
1813 ProcessDistribution::None => mag,
1814 }
1815}
1816
1817#[inline]
1818pub(crate) fn sample_process_increment_fast(
1819 future_mu: f64,
1820 phi: f64,
1821 inv_phi: f64,
1822 dist: ProcessDistribution,
1823 rng: &mut DeterministicRng,
1824) -> f64 {
1825 if !(phi > 0.0) || future_mu == 0.0 || !future_mu.is_finite() {
1826 return future_mu;
1827 }
1828 let sign = if future_mu < 0.0 { -1.0 } else { 1.0 };
1831 let mag = future_mu.abs();
1832 let draw = match dist {
1833 ProcessDistribution::Gamma => rng.sample_gamma(mag * inv_phi, phi),
1834 ProcessDistribution::OverDispersedPoisson => phi * rng.sample_poisson(mag * inv_phi),
1835 ProcessDistribution::None => mag,
1836 };
1837 sign * draw
1838}
1839
1840#[inline]
1849fn project_origin_reserves(
1850 tail: f64,
1851 phi: f64,
1852 all_ldfs_ge_one: bool,
1853 process_distribution: ProcessDistribution,
1854 rng: &mut DeterministicRng,
1855 scratch: &mut OdpBootstrapScratch,
1856) -> Option<f64> {
1857 let n = scratch.n;
1858 let inv_phi = scratch.inv_phi;
1859 let tail_inc = tail - 1.0;
1860
1861 if all_ldfs_ge_one || process_distribution == ProcessDistribution::None {
1862 let mut cdf = tail;
1865 let l0 = scratch.latest_pseudo[0];
1866 if !l0.is_finite() {
1867 return None;
1868 }
1869 let r0 = if tail_inc > 0.0 {
1870 sample_process_increment_fast(l0 * tail_inc, phi, inv_phi, process_distribution, rng)
1871 } else {
1872 0.0
1873 };
1874 if !r0.is_finite() {
1875 return None;
1876 }
1877 scratch.origin_reserves[0] = r0;
1878 let mut total = r0;
1879
1880 match process_distribution {
1881 ProcessDistribution::Gamma if phi > 0.0 => {
1882 for origin in 1..n {
1883 cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1884 let latest_i = scratch.latest_pseudo[origin];
1885 let expected_res = latest_i * (cdf - 1.0);
1886 let res_i = if expected_res > 0.0 && expected_res.is_finite() {
1887 let shape = expected_res * inv_phi;
1888 if shape >= 1.0 {
1889 rng.sample_gamma_ge1(shape) * phi
1890 } else {
1891 rng.sample_gamma(shape, phi)
1892 }
1893 } else if expected_res < 0.0 && expected_res.is_finite() {
1894 -rng.sample_gamma(-expected_res * inv_phi, phi)
1895 } else if expected_res == 0.0 {
1896 0.0
1897 } else {
1898 return None;
1899 };
1900 scratch.origin_reserves[origin] = res_i;
1901 total += res_i;
1902 }
1903 }
1904 ProcessDistribution::OverDispersedPoisson if phi > 0.0 => {
1905 for origin in 1..n {
1906 cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1907 let latest_i = scratch.latest_pseudo[origin];
1908 if !latest_i.is_finite() {
1909 return None;
1910 }
1911 let expected_res = latest_i * (cdf - 1.0);
1912 let res_i = sample_process_increment_fast(
1913 expected_res,
1914 phi,
1915 inv_phi,
1916 ProcessDistribution::OverDispersedPoisson,
1917 rng,
1918 );
1919 if !res_i.is_finite() {
1920 return None;
1921 }
1922 scratch.origin_reserves[origin] = res_i;
1923 total += res_i;
1924 }
1925 }
1926 _ => {
1927 for origin in 1..n {
1928 cdf *= scratch.pseudo_ldfs[n - 1 - origin];
1929 let latest_i = scratch.latest_pseudo[origin];
1930 let expected_res = latest_i * (cdf - 1.0);
1931 if !expected_res.is_finite() {
1932 return None;
1933 }
1934 scratch.origin_reserves[origin] = expected_res;
1935 total += expected_res;
1936 }
1937 }
1938 }
1939 return total.is_finite().then_some(total);
1940 }
1941
1942 let mut pos_factor = tail_inc;
1946 let mut neg_factor = 0.0;
1947
1948 let l0 = scratch.latest_pseudo[0];
1949 if !l0.is_finite() {
1950 return None;
1951 }
1952 let r0 = if tail_inc > 0.0 {
1953 sample_process_increment_fast(l0 * tail_inc, phi, inv_phi, process_distribution, rng)
1954 } else {
1955 0.0
1956 };
1957 if !r0.is_finite() {
1958 return None;
1959 }
1960 scratch.origin_reserves[0] = r0;
1961 let mut total = r0;
1962
1963 for origin in 1..n {
1964 let f = scratch.pseudo_ldfs[n - 1 - origin];
1965 let step = f - 1.0;
1966 if step >= 0.0 {
1967 pos_factor = step + f * pos_factor;
1968 neg_factor *= f;
1969 } else {
1970 pos_factor *= f;
1971 neg_factor = (-step) + f * neg_factor;
1972 }
1973
1974 let latest_i = scratch.latest_pseudo[origin];
1975 if !latest_i.is_finite() {
1976 return None;
1977 }
1978 let (pos_mu, neg_mu) = if latest_i >= 0.0 {
1979 (latest_i * pos_factor, latest_i * neg_factor)
1980 } else {
1981 (-latest_i * neg_factor, -latest_i * pos_factor)
1982 };
1983 let pos_draw = if pos_mu > 0.0 {
1984 sample_positive_process(pos_mu, phi, inv_phi, process_distribution, rng)
1985 } else {
1986 0.0
1987 };
1988 let neg_draw = if neg_mu > 0.0 {
1989 sample_positive_process(neg_mu, phi, inv_phi, process_distribution, rng)
1990 } else {
1991 0.0
1992 };
1993 let res_i = pos_draw - neg_draw;
1994 if !res_i.is_finite() {
1995 return None;
1996 }
1997 scratch.origin_reserves[origin] = res_i;
1998 total += res_i;
1999 }
2000
2001 total.is_finite().then_some(total)
2002}
2003
2004pub(crate) fn run_odp_iteration_with_scratch<'a>(
2010 fit: &OdpFit,
2011 sampled_residuals: &[f64],
2012 process_distribution: ProcessDistribution,
2013 rng: &mut DeterministicRng,
2014 scratch: &'a mut OdpBootstrapScratch,
2015) -> Option<&'a [f64]> {
2016 let outcome = refit_pseudo_ldfs_from_slice(sampled_residuals, scratch);
2017 if !outcome.valid {
2018 return None;
2019 }
2020 project_origin_reserves(
2021 fit.tail,
2022 fit.dispersion,
2023 outcome.all_ldfs_ge_one,
2024 process_distribution,
2025 rng,
2026 scratch,
2027 )?;
2028 Some(&scratch.origin_reserves)
2029}
2030
2031pub fn bootstrap_odp(
2050 triangle: &TriangleView<'_>,
2051 tail: f64,
2052 options: OdpBootstrapOptions,
2053) -> Result<OdpBootstrapResult, ValidationError> {
2054 if options.iterations == 0 {
2055 return Err(ValidationError::InvalidIterations);
2056 }
2057
2058 let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2059 let (pool, pool_mean) =
2060 build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2061
2062 let mut rng = DeterministicRng::from_seed(options.seed);
2063 let mut sampler = FastIndexSampler::new(pool.len());
2064 let n = fit.n_origins;
2065 let mut simulated_totals = Vec::with_capacity(options.iterations);
2066 let mut simulated_by_origin: Vec<Vec<f64>> = (0..n)
2067 .map(|_| Vec::with_capacity(options.iterations))
2068 .collect();
2069 let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2070 let mut failed_iterations = 0usize;
2071
2072 for _ in 0..options.iterations {
2073 let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2074 if !outcome.valid {
2075 failed_iterations += 1;
2076 continue;
2077 }
2078 if let Some(total) = project_origin_reserves(
2079 fit.tail,
2080 fit.dispersion,
2081 outcome.all_ldfs_ge_one,
2082 options.process_distribution,
2083 &mut rng,
2084 &mut scratch,
2085 ) {
2086 simulated_totals.push(total);
2087 for (origin_vec, &r) in simulated_by_origin
2088 .iter_mut()
2089 .zip(scratch.origin_reserves.iter())
2090 {
2091 origin_vec.push(r);
2092 }
2093 } else {
2094 failed_iterations += 1;
2095 }
2096 }
2097
2098 if simulated_totals.is_empty() {
2099 return Err(ValidationError::NotFinite);
2100 }
2101
2102 let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2105 let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2106 let mut origin_summaries = Vec::with_capacity(n);
2107 for series in &simulated_by_origin {
2108 origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2109 }
2110
2111 Ok(OdpBootstrapResult {
2112 base_total_reserve: fit.total_reserve,
2113 fit,
2114 options,
2115 simulated_totals,
2116 simulated_by_origin,
2117 origin_summaries,
2118 summary,
2119 failed_iterations,
2120 residual_pool_mean_before_centering: pool_mean,
2121 })
2122}
2123
2124pub fn bootstrap(
2132 triangle: &TriangleView<'_>,
2133 tail: f64,
2134 config: BootstrapConfig,
2135) -> Result<BootstrapResult, ValidationError> {
2136 if config.iterations == 0 {
2137 return Err(ValidationError::ShapeMismatch);
2138 }
2139
2140 let options = OdpBootstrapOptions::england_verrall(config.iterations, config.seed);
2141 let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2142 let (pool, _) =
2143 build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2144
2145 let mut rng = DeterministicRng::from_seed(options.seed);
2146 let mut sampler = FastIndexSampler::new(pool.len());
2147 let n = fit.n_origins;
2148 let phi = fit.dispersion;
2149 let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2150 let inv_phi = scratch.inv_phi;
2151 let tail_inc = fit.tail - 1.0;
2152 let mut simulated_totals = Vec::with_capacity(config.iterations);
2153
2154 for _ in 0..config.iterations {
2155 let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2156 if !outcome.valid {
2157 continue;
2158 }
2159 let mut ok = true;
2160 let total = if outcome.all_ldfs_ge_one {
2161 let mut cdf = fit.tail;
2162 let l0 = scratch.latest_pseudo[0];
2163 if !l0.is_finite() {
2164 ok = false;
2165 }
2166 let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2167 l0 * tail_inc
2168 } else {
2169 0.0
2170 };
2171 let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2172 -l0 * tail_inc
2173 } else {
2174 0.0
2175 };
2176 for origin in 1..n {
2177 cdf *= scratch.pseudo_ldfs[n - 1 - origin];
2178 let li = scratch.latest_pseudo[origin];
2179 if !li.is_finite() {
2180 ok = false;
2181 break;
2182 }
2183 let expected = li * (cdf - 1.0);
2184 if expected >= 0.0 {
2185 pos_sum += expected;
2186 } else {
2187 neg_sum -= expected;
2188 }
2189 }
2190 if ok {
2191 let p_draw = if pos_sum > 0.0 {
2192 sample_positive_process(
2193 pos_sum,
2194 phi,
2195 inv_phi,
2196 options.process_distribution,
2197 &mut rng,
2198 )
2199 } else {
2200 0.0
2201 };
2202 let n_draw = if neg_sum > 0.0 {
2203 sample_positive_process(
2204 neg_sum,
2205 phi,
2206 inv_phi,
2207 options.process_distribution,
2208 &mut rng,
2209 )
2210 } else {
2211 0.0
2212 };
2213 p_draw - n_draw
2214 } else {
2215 f64::NAN
2216 }
2217 } else {
2218 let mut pos_factor = tail_inc;
2219 let mut neg_factor = 0.0;
2220 let l0 = scratch.latest_pseudo[0];
2221 if !l0.is_finite() {
2222 ok = false;
2223 }
2224 let mut pos_sum = if tail_inc > 0.0 && l0 > 0.0 {
2225 l0 * tail_inc
2226 } else {
2227 0.0
2228 };
2229 let mut neg_sum = if tail_inc > 0.0 && l0 < 0.0 {
2230 -l0 * tail_inc
2231 } else {
2232 0.0
2233 };
2234 for origin in 1..n {
2235 let f = scratch.pseudo_ldfs[n - 1 - origin];
2236 let step = f - 1.0;
2237 if step >= 0.0 {
2238 pos_factor = step + f * pos_factor;
2239 neg_factor *= f;
2240 } else {
2241 pos_factor *= f;
2242 neg_factor = (-step) + f * neg_factor;
2243 }
2244 let li = scratch.latest_pseudo[origin];
2245 if !li.is_finite() {
2246 ok = false;
2247 break;
2248 }
2249 if li >= 0.0 {
2250 pos_sum += li * pos_factor;
2251 neg_sum += li * neg_factor;
2252 } else {
2253 pos_sum += -li * neg_factor;
2254 neg_sum += -li * pos_factor;
2255 }
2256 }
2257 if ok {
2258 let p_draw = if pos_sum > 0.0 {
2259 sample_positive_process(
2260 pos_sum,
2261 phi,
2262 inv_phi,
2263 options.process_distribution,
2264 &mut rng,
2265 )
2266 } else {
2267 0.0
2268 };
2269 let n_draw = if neg_sum > 0.0 {
2270 sample_positive_process(
2271 neg_sum,
2272 phi,
2273 inv_phi,
2274 options.process_distribution,
2275 &mut rng,
2276 )
2277 } else {
2278 0.0
2279 };
2280 p_draw - n_draw
2281 } else {
2282 f64::NAN
2283 }
2284 };
2285 if ok && total.is_finite() {
2286 simulated_totals.push(total);
2287 }
2288 }
2289
2290 if simulated_totals.is_empty() {
2291 return Err(ValidationError::NotFinite);
2292 }
2293
2294 let mut summary_buf = Vec::with_capacity(simulated_totals.len());
2295 let summary = summarize_with_scratch(&simulated_totals, &mut summary_buf, true)?;
2296 Ok(BootstrapResult {
2297 base_total_reserve: fit.total_reserve,
2298 simulated_totals,
2299 summary,
2300 })
2301}
2302
2303pub fn bootstrap_summary(
2305 triangle: &TriangleView<'_>,
2306 tail: f64,
2307 config: BootstrapConfig,
2308) -> Result<BootstrapSummary, ValidationError> {
2309 Ok(bootstrap(triangle, tail, config)?.summary)
2310}
2311
2312#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
2316pub struct OdpCdrBootstrapResult {
2317 pub base_total_reserve: f64,
2319 pub base_origin_reserves: Vec<f64>,
2321 pub simulated_total_cdr: Vec<f64>,
2324 pub simulated_cdr_by_origin: Vec<Vec<f64>>,
2326 pub summary: BootstrapSummary,
2328 pub origin_summaries: Vec<BootstrapSummary>,
2330 pub failed_iterations: usize,
2332}
2333
2334pub fn bootstrap_odp_cdr(
2347 triangle: &TriangleView<'_>,
2348 tail: f64,
2349 options: OdpBootstrapOptions,
2350) -> Result<OdpCdrBootstrapResult, ValidationError> {
2351 if options.iterations == 0 {
2352 return Err(ValidationError::InvalidIterations);
2353 }
2354
2355 let fit = fit_odp(triangle, tail, options.monotonicity_policy)?;
2356 let (pool, _) =
2357 build_adjusted_residual_pool(&fit, options.residual_adjustment, options.center_residuals)?;
2358
2359 let n = fit.n_origins;
2360 let m = n.saturating_sub(1);
2361 let mut rng = DeterministicRng::from_seed(options.seed);
2362 let mut sampler = FastIndexSampler::new(pool.len());
2363
2364 let mut simulated_total_cdr = Vec::with_capacity(options.iterations);
2365 let mut simulated_cdr_by_origin: Vec<Vec<f64>> = (0..n)
2366 .map(|_| Vec::with_capacity(options.iterations))
2367 .collect();
2368 let mut scratch = OdpBootstrapScratch::for_fit(&fit);
2369 let inv_phi = scratch.inv_phi;
2370 let mut ext_ldfs = vec![1.0; m];
2371 let mut ext_cdfs = vec![tail; n];
2372 let mut next_pay = vec![0.0; n];
2373 let mut next_cum_diag = vec![0.0; n];
2374 let mut failed_iterations = 0usize;
2375
2376 let mut obs_den = vec![0.0; m];
2379 let mut obs_num = vec![0.0; m];
2380 for i in 0..m {
2381 let row = &triangle.data[i * n..i * n + (n - i)];
2382 for k in 0..(n - 1 - i) {
2383 let c0 = row[k];
2384 let c1 = row[k + 1];
2385 if c0.is_finite() && c1.is_finite() {
2386 obs_den[k] += c0;
2387 obs_num[k] += c1;
2388 }
2389 }
2390 }
2391 let obs_diag: Vec<f64> = (0..n).map(|i| triangle.get(i, n - 1 - i)).collect();
2392 let r1_origin0 = obs_diag[0] * (tail - 1.0);
2393
2394 for _ in 0..options.iterations {
2395 let outcome = refit_pseudo_ldfs_from_pool(&pool, &mut sampler, &mut rng, &mut scratch);
2397 if !outcome.valid {
2398 failed_iterations += 1;
2399 continue;
2400 }
2401
2402 let mut valid_ext = true;
2404 for i in 1..n {
2405 let k = n - 1 - i; let c_prev = obs_diag[i];
2407 let expected_inc = c_prev * (scratch.pseudo_ldfs[k] - 1.0);
2408 let sim_inc = sample_process_increment_fast(
2409 expected_inc,
2410 fit.dispersion,
2411 inv_phi,
2412 options.process_distribution,
2413 &mut rng,
2414 );
2415 let c_next = c_prev + sim_inc;
2416 next_pay[i] = sim_inc;
2417 next_cum_diag[i] = c_next;
2418
2419 let den = obs_den[k] + c_prev;
2420 let num = obs_num[k] + c_next;
2421 if !den.is_finite() || den <= 0.0 || !num.is_finite() || num <= 0.0 {
2422 valid_ext = false;
2423 break;
2424 }
2425 ext_ldfs[k] = num / den;
2426 }
2427 if !valid_ext {
2428 failed_iterations += 1;
2429 continue;
2430 }
2431
2432 ext_cdfs[m] = tail;
2434 for k in (0..m).rev() {
2435 ext_cdfs[k] = ext_ldfs[k] * ext_cdfs[k + 1];
2436 }
2437
2438 let cdr0 = fit.origin_reserves[0] - r1_origin0;
2440 if !cdr0.is_finite() {
2441 failed_iterations += 1;
2442 continue;
2443 }
2444 scratch.origin_reserves[0] = cdr0;
2445 let mut total_cdr = cdr0;
2446 let mut ok = true;
2447 for i in 1..n {
2448 let j_next = n - i;
2449 let c_next = next_cum_diag[i];
2450 let r1 = c_next * (ext_cdfs[j_next] - 1.0);
2451 let cdr_i = fit.origin_reserves[i] - (next_pay[i] + r1);
2452 if !cdr_i.is_finite() {
2453 ok = false;
2454 break;
2455 }
2456 scratch.origin_reserves[i] = cdr_i;
2457 total_cdr += cdr_i;
2458 }
2459 if !ok || !total_cdr.is_finite() {
2460 failed_iterations += 1;
2461 continue;
2462 }
2463 simulated_total_cdr.push(total_cdr);
2464 for (origin_vec, &r) in simulated_cdr_by_origin
2465 .iter_mut()
2466 .zip(scratch.origin_reserves.iter())
2467 {
2468 origin_vec.push(r);
2469 }
2470 }
2471
2472 if simulated_total_cdr.is_empty() {
2473 return Err(ValidationError::NotFinite);
2474 }
2475
2476 let mut summary_buf = Vec::with_capacity(simulated_total_cdr.len());
2477 let summary = summarize_with_scratch(&simulated_total_cdr, &mut summary_buf, true)?;
2478 let mut origin_summaries = Vec::with_capacity(n);
2479 for series in &simulated_cdr_by_origin {
2480 origin_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
2481 }
2482
2483 Ok(OdpCdrBootstrapResult {
2484 base_total_reserve: fit.total_reserve,
2485 base_origin_reserves: fit.origin_reserves,
2486 simulated_total_cdr,
2487 simulated_cdr_by_origin,
2488 summary,
2489 origin_summaries,
2490 failed_iterations,
2491 })
2492}
2493
2494#[cfg(test)]
2495mod tests {
2496 use super::*;
2497 use crate::datasets::genins;
2498 use crate::deterministic::chain_ladder::ChainLadderEngine;
2499 use crate::deterministic::ldf::DevelopmentFactorEngine;
2500 use crate::types::Triangle;
2501
2502 fn triangle_4x4() -> Triangle {
2503 #[rustfmt::skip]
2504 let data = vec![
2505 1000.0, 1500.0, 1700.0, 1800.0,
2506 1200.0, 1800.0, 2000.0, f64::NAN,
2507 1500.0, 2100.0, f64::NAN, f64::NAN,
2508 1800.0, f64::NAN, f64::NAN, f64::NAN,
2509 ];
2510 Triangle::new(4, 4, data)
2511 }
2512
2513 #[test]
2514 fn bootstrap_is_deterministic_for_same_seed() {
2515 let triangle = triangle_4x4();
2516 let config = BootstrapConfig {
2517 iterations: 50,
2518 seed: 42,
2519 };
2520
2521 let first = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2522 let second = bootstrap(&triangle.view(), 1.0, config).expect("bootstrap");
2523
2524 assert_eq!(first.simulated_totals, second.simulated_totals);
2525 assert_eq!(first.summary, second.summary);
2526 }
2527
2528 #[test]
2529 fn bootstrap_returns_ordered_quantiles() {
2530 let triangle = triangle_4x4();
2531 let summary = bootstrap_summary(
2532 &triangle.view(),
2533 1.0,
2534 BootstrapConfig {
2535 iterations: 100,
2536 seed: 7,
2537 },
2538 )
2539 .expect("summary");
2540
2541 assert!(summary.mean >= 0.0);
2542 assert!(summary.std_dev >= 0.0);
2543 assert!(summary.p50 <= summary.p75);
2544 assert!(summary.p75 <= summary.p90);
2545 assert!(summary.p90 <= summary.p95);
2546 assert!(summary.p95 <= summary.p99);
2547 }
2548
2549 #[test]
2550 fn bootstrap_rejects_zero_iterations() {
2551 let triangle = triangle_4x4();
2552 assert_eq!(
2553 bootstrap(
2554 &triangle.view(),
2555 1.0,
2556 BootstrapConfig {
2557 iterations: 0,
2558 seed: 1
2559 }
2560 ),
2561 Err(ValidationError::ShapeMismatch)
2562 );
2563 }
2564
2565 #[test]
2566 fn bootstrap_base_reserve_matches_chain_ladder() {
2567 let triangle = triangle_4x4();
2568 let result = bootstrap(
2569 &triangle.view(),
2570 1.0,
2571 BootstrapConfig {
2572 iterations: 10,
2573 seed: 9,
2574 },
2575 )
2576 .expect("bootstrap");
2577
2578 let factors =
2579 DevelopmentFactorEngine::volume_weighted(&triangle.view(), 1.0).expect("factors");
2580 let projection =
2581 ChainLadderEngine::project(&triangle.view(), &factors).expect("projection");
2582 assert!((result.base_total_reserve - projection.total_reserve).abs() < 1e-9);
2583 }
2584
2585 #[test]
2586 fn odp_fit_leverages_sum_to_rank_and_saturate_corners() {
2587 let triangle = triangle_4x4();
2588 let fit = fit_odp(&triangle.view(), 1.0, MonotonicityPolicy::Strict).expect("fit");
2589
2590 assert_eq!(fit.n_observed, 10);
2591 assert_eq!(fit.rank, 7);
2592 assert_eq!(fit.degrees_of_freedom, 3);
2593 let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2594 assert!((h_sum - 7.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2595 let saturated_corners: Vec<(usize, usize)> = fit
2596 .residuals
2597 .iter()
2598 .filter(|r| r.saturated)
2599 .map(|r| (r.origin, r.dev))
2600 .collect();
2601 assert_eq!(saturated_corners, vec![(0, 3), (3, 0)]);
2602 }
2603
2604 #[test]
2605 fn odp_fit_tridiagonal_matches_general_solver_to_machine_precision() {
2606 let tri = genins();
2607 let fit = fit_odp(&tri.view(), 1.05, MonotonicityPolicy::Strict).expect("fast fit");
2608 let general = solve_odp_general(
2609 fit.n_origins,
2610 fit.tail,
2611 &fit.fitted_cumulative,
2612 &fit.fitted_incremental,
2613 &fit.observed_incremental,
2614 )
2615 .expect("general fit");
2616
2617 assert_eq!(fit.residuals.len(), general.residuals.len());
2618 for (a, b) in fit.residuals.iter().zip(general.residuals.iter()) {
2619 assert_eq!((a.origin, a.dev), (b.origin, b.dev));
2620 assert!((a.leverage - b.leverage).abs() < 1e-12);
2621 assert!((a.raw_pearson_residual - b.raw_pearson_residual).abs() < 1e-12);
2622 }
2623 for i in 0..fit.n_origins {
2624 let tol = 1e-10 * (1.0 + general.analytic_origin_prediction_error[i]);
2625 assert!(
2626 (fit.analytic_origin_param_se[i] - general.analytic_origin_param_se[i]).abs() < tol
2627 );
2628 assert!(
2629 (fit.analytic_origin_prediction_error[i]
2630 - general.analytic_origin_prediction_error[i])
2631 .abs()
2632 < tol
2633 );
2634 }
2635 assert!(
2636 (fit.analytic_total_param_se - general.analytic_total_param_se).abs()
2637 < 1e-10 * general.analytic_total_param_se
2638 );
2639 }
2640
2641 #[test]
2642 fn odp_fit_handles_flat_ldf_via_general_fallback() {
2643 #[rustfmt::skip]
2645 let tri = Triangle::new(4, 4, vec![
2646 1000.0, 1500.0, 1700.0, 1700.0,
2647 1200.0, 1800.0, 2000.0, f64::NAN,
2648 1500.0, 2100.0, f64::NAN, f64::NAN,
2649 1800.0, f64::NAN, f64::NAN, f64::NAN,
2650 ]);
2651 let fit = fit_odp(&tri.view(), 1.0, MonotonicityPolicy::Strict).expect("fallback fit");
2652 assert_eq!(fit.n_observed, 9);
2653 assert_eq!(fit.rank, 6);
2654 assert_eq!(fit.degrees_of_freedom, 3);
2655 let h_sum: f64 = fit.residuals.iter().map(|r| r.leverage).sum();
2656 assert!((h_sum - 6.0).abs() < 1e-10, "sum(h_ii)={h_sum}");
2657 }
2658
2659 #[test]
2660 fn ziggurat_normal_and_fast_index_samplers_match_theoretical_distributions() {
2661 let mut rng = DeterministicRng::from_seed(1234567);
2662 let n = 200_000usize;
2663 let mut sum = 0.0;
2664 let mut s2 = 0.0;
2665 let mut s3 = 0.0;
2666 let mut s4 = 0.0;
2667 let mut tail_hits = 0usize;
2668 for _ in 0..n {
2669 let z = rng.next_standard_normal();
2670 sum += z;
2671 let z2 = z * z;
2672 s2 += z2;
2673 s3 += z2 * z;
2674 s4 += z2 * z2;
2675 if z.abs() >= ZIG_NORM_R {
2676 tail_hits += 1;
2677 }
2678 }
2679 let nf = n as f64;
2680 let mean = sum / nf;
2681 let var = s2 / nf - mean * mean;
2682 let skew = s3 / nf;
2683 let kurt = s4 / nf;
2684 assert!(mean.abs() < 0.01, "mean={mean}");
2685 assert!((var - 1.0).abs() < 0.015, "var={var}");
2686 assert!(skew.abs() < 0.03, "skew={skew}");
2687 assert!((kurt - 3.0).abs() < 0.08, "kurt={kurt}");
2688 assert!((20..=100).contains(&tail_hits), "tail_hits={tail_hits}");
2690
2691 let mut counts53 = [0usize; 53];
2693 let mut s53 = FastIndexSampler::new(53);
2694 for _ in 0..53_000 {
2695 counts53[s53.next(&mut rng)] += 1;
2696 }
2697 let chi2: f64 = counts53
2698 .iter()
2699 .map(|&c| {
2700 let d = c as f64 - 1000.0;
2701 d * d / 1000.0
2702 })
2703 .sum();
2704 assert!(chi2 < 100.0, "chi2(df=52)={chi2}");
2705
2706 let mut s1500 = FastIndexSampler::new(1500);
2707 for _ in 0..5_000 {
2708 assert!(s1500.next(&mut rng) < 1500);
2709 }
2710 }
2711
2712 #[test]
2713 fn gamma_and_poisson_samplers_match_theoretical_moments() {
2714 let mut rng = DeterministicRng::from_seed(42069);
2715 let n = 40_000usize;
2716
2717 for &(shape, scale) in &[(0.4, 2.5), (3.5, 10.0), (25.0, 50.0)] {
2718 let samples: Vec<f64> = (0..n).map(|_| rng.sample_gamma(shape, scale)).collect();
2719 let mean = samples.iter().sum::<f64>() / n as f64;
2720 let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2721 let expected_mean = shape * scale;
2722 let expected_var = shape * scale * scale;
2723 assert!(
2724 (mean - expected_mean).abs() / expected_mean < 0.03,
2725 "gamma({shape},{scale}) mean={mean} expected={expected_mean}"
2726 );
2727 assert!(
2728 (var - expected_var).abs() / expected_var < 0.08,
2729 "gamma({shape},{scale}) var={var} expected={expected_var}"
2730 );
2731 }
2732
2733 for &lambda in &[0.7, 9.5, 10.0, 12.0, 20.0, 45.0, 300.0] {
2734 let samples: Vec<f64> = (0..n).map(|_| rng.sample_poisson(lambda)).collect();
2735 let mean = samples.iter().sum::<f64>() / n as f64;
2736 let var = samples.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (n - 1) as f64;
2737 assert!(
2738 (mean - lambda).abs() / lambda < 0.03,
2739 "poisson({lambda}) mean={mean}"
2740 );
2741 assert!(
2742 (var - lambda).abs() / lambda < 0.06,
2743 "poisson({lambda}) var={var}"
2744 );
2745 }
2746 }
2747}