1use crate::deterministic::ldf::{
14 LdfSelectionMethod, cdfs_from_ldfs, volume_weighted_ldfs_observed_counts,
15};
16use crate::preprocessing::ragged::{
17 ex_hi_lo_observed_counts, simple_average_observed_counts,
18 volume_weighted_last_n_observed_counts,
19};
20use crate::subannual::grid::AsymmetricAgeGrid;
21use crate::validate::{
22 MonotonicityPolicy, ValidationError, validate_nonnegative_finite_slice,
23 validate_positive_finite_slice, validate_tail,
24};
25
26#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
28pub struct AsymmetricChainLadderProjection {
29 pub ldfs: Vec<f64>,
31 pub cdfs: Vec<f64>,
33 pub tail: f64,
35 pub latest: Vec<f64>,
37 pub latest_dev_indices: Vec<usize>,
39 pub latest_ages_months: Vec<f64>,
41 pub origin_cdfs: Vec<f64>,
43 pub ultimates: Vec<f64>,
45 pub ibnr: Vec<f64>,
47 pub total_latest: f64,
49 pub total_ultimate: f64,
51 pub total_ibnr: f64,
53}
54
55pub(crate) fn validate_asymmetric_cumulative(
57 cum: &[f64],
58 grid: &AsymmetricAgeGrid,
59 policy: MonotonicityPolicy,
60) -> Result<(), ValidationError> {
61 if grid.n_origins == 0 || grid.n_devs < 2 {
62 return Err(ValidationError::ShapeMismatch);
63 }
64 if cum.len() != grid.n_origins * grid.n_devs || grid.observed_counts.len() != grid.n_origins {
65 return Err(ValidationError::ShapeMismatch);
66 }
67 for i in 0..grid.n_origins {
68 let cnt = grid.observed_counts[i];
69 if cnt == 0 || cnt > grid.n_devs {
70 return Err(ValidationError::ShapeMismatch);
71 }
72 let mut prev = None;
73 for j in 0..cnt {
74 let v = cum[i * grid.n_devs + j];
75 if !v.is_finite() {
76 return Err(ValidationError::NotFinite);
77 }
78 if v < 0.0 {
79 return Err(ValidationError::Negative);
80 }
81 if policy == MonotonicityPolicy::Strict
82 && let Some(p) = prev
83 && v < p
84 {
85 return Err(ValidationError::NonMonotoneCumulative {
86 origin: i,
87 dev: j,
88 previous: p,
89 value: v,
90 });
91 }
92 prev = Some(v);
93 }
94 }
95 Ok(())
96}
97
98fn median_observed_counts(cum: &[f64], n_o: usize, n_d: usize, counts: &[usize], out: &mut [f64]) {
100 let n_links = n_d.saturating_sub(1);
101 let mut buf = Vec::with_capacity(n_o);
102 for j in 0..n_links {
103 buf.clear();
104 for i in 0..n_o {
105 if counts[i] <= j + 1 {
106 continue;
107 }
108 let x = cum[i * n_d + j];
109 let y = cum[i * n_d + j + 1];
110 if x > 0.0 && x.is_finite() && y.is_finite() {
111 buf.push(y / x);
112 }
113 }
114 if buf.is_empty() {
115 out[j] = f64::NAN;
116 } else {
117 buf.sort_by(f64::total_cmp);
118 let mid = buf.len() / 2;
119 out[j] = if buf.len() % 2 == 1 {
120 buf[mid]
121 } else {
122 f64::midpoint(buf[mid - 1], buf[mid])
123 };
124 }
125 }
126}
127
128pub fn asymmetric_chain_ladder(
136 cum: &[f64],
137 grid: &AsymmetricAgeGrid,
138 method: LdfSelectionMethod,
139 tail: f64,
140 policy: MonotonicityPolicy,
141) -> Result<AsymmetricChainLadderProjection, ValidationError> {
142 validate_asymmetric_cumulative(cum, grid, policy)?;
143 validate_tail(tail)?;
144
145 let n_o = grid.n_origins;
146 let n_d = grid.n_devs;
147 let n_links = n_d - 1;
148 let counts = &grid.observed_counts;
149 let max_obs = counts.iter().copied().max().unwrap_or(0);
150 if max_obs < 2 {
151 return Err(ValidationError::InvalidParameter(
152 "asymmetric_chain_ladder requires at least one origin with >= 2 observed cells",
153 ));
154 }
155
156 let mut ldfs = vec![1.0; n_links];
157 match method {
158 LdfSelectionMethod::VolumeWeighted => {
159 volume_weighted_ldfs_observed_counts(cum, n_o, n_d, counts, &mut ldfs);
160 }
161 LdfSelectionMethod::SimpleAverage => {
162 simple_average_observed_counts(cum, n_o, n_d, counts, None, &mut ldfs);
163 }
164 LdfSelectionMethod::ExHiLo => {
165 ex_hi_lo_observed_counts(cum, n_o, n_d, counts, &mut ldfs);
166 }
167 LdfSelectionMethod::Median => {
168 median_observed_counts(cum, n_o, n_d, counts, &mut ldfs);
169 }
170 LdfSelectionMethod::LastNVolumeWeighted { last_n } => {
171 if last_n == 0 {
172 return Err(ValidationError::InvalidParameter("last_n must be >= 1"));
173 }
174 volume_weighted_last_n_observed_counts(cum, n_o, n_d, counts, last_n, &mut ldfs);
175 }
176 LdfSelectionMethod::LastNSimpleAverage { last_n } => {
177 if last_n == 0 {
178 return Err(ValidationError::InvalidParameter("last_n must be >= 1"));
179 }
180 simple_average_observed_counts(cum, n_o, n_d, counts, Some(last_n), &mut ldfs);
181 }
182 LdfSelectionMethod::Selected => {
183 return Err(ValidationError::InvalidParameter(
184 "Selected method requires explicit LDFs; use a computed LdfSelectionMethod",
185 ));
186 }
187 }
188
189 for j in (max_obs - 1)..n_links {
192 if !ldfs[j].is_finite() {
193 ldfs[j] = 1.0;
194 }
195 }
196 validate_positive_finite_slice(&ldfs, "asymmetric LDF")?;
197
198 let mut cdfs = vec![0.0; n_d];
199 cdfs_from_ldfs(&ldfs, tail, &mut cdfs);
200
201 let mut latest = Vec::with_capacity(n_o);
202 let mut latest_dev_indices = Vec::with_capacity(n_o);
203 let mut latest_ages_months = Vec::with_capacity(n_o);
204 let mut origin_cdfs = Vec::with_capacity(n_o);
205 let mut ultimates = Vec::with_capacity(n_o);
206 let mut ibnr = Vec::with_capacity(n_o);
207
208 for i in 0..n_o {
209 let d_i = counts[i] - 1;
210 let lat = cum[i * n_d + d_i];
211 let cdf = cdfs[d_i];
212 let ult = lat * cdf;
213 latest.push(lat);
214 latest_dev_indices.push(d_i);
215 latest_ages_months.push(grid.cell_age(i, d_i));
216 origin_cdfs.push(cdf);
217 ultimates.push(ult);
218 ibnr.push(ult - lat);
219 }
220
221 let total_latest = latest.iter().sum();
222 let total_ultimate = ultimates.iter().sum();
223 let total_ibnr = ibnr.iter().sum();
224
225 Ok(AsymmetricChainLadderProjection {
226 ldfs,
227 cdfs,
228 tail,
229 latest,
230 latest_dev_indices,
231 latest_ages_months,
232 origin_cdfs,
233 ultimates,
234 ibnr,
235 total_latest,
236 total_ultimate,
237 total_ibnr,
238 })
239}
240
241#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
244pub struct InterimBfProjection {
245 pub latest: Vec<f64>,
247 pub cdfs: Vec<f64>,
249 pub exposure_fractions: Vec<f64>,
251 pub earned_expected_ultimate: Vec<f64>,
253 pub pct_reported: Vec<f64>,
255 pub ibnr: Vec<f64>,
257 pub ultimates: Vec<f64>,
259 pub total_latest: f64,
261 pub total_ibnr: f64,
263 pub total_ultimate: f64,
265}
266
267pub fn interim_bf(
274 latest: &[f64],
275 cdfs_at_origin: &[f64],
276 full_period_expected_ultimate: &[f64],
277 exposure_fractions: &[f64],
278) -> Result<InterimBfProjection, ValidationError> {
279 let n = latest.len();
280 if n == 0
281 || cdfs_at_origin.len() != n
282 || full_period_expected_ultimate.len() != n
283 || exposure_fractions.len() != n
284 {
285 return Err(ValidationError::ShapeMismatch);
286 }
287 validate_nonnegative_finite_slice(latest)?;
288 validate_positive_finite_slice(cdfs_at_origin, "origin CDF")?;
289 validate_nonnegative_finite_slice(full_period_expected_ultimate)?;
290 validate_positive_finite_slice(exposure_fractions, "exposure_fractions")?;
291 if exposure_fractions.iter().any(|&e| e > 1.0 + 1e-9) {
292 return Err(ValidationError::InvalidParameter(
293 "exposure_fractions must lie in (0, 1]",
294 ));
295 }
296
297 let mut earned_expected_ultimate = Vec::with_capacity(n);
298 let mut pct_reported = Vec::with_capacity(n);
299 let mut ibnr = Vec::with_capacity(n);
300 let mut ultimates = Vec::with_capacity(n);
301
302 for i in 0..n {
303 let earned_exp = full_period_expected_ultimate[i] * exposure_fractions[i];
304 let p = 1.0 / cdfs_at_origin[i];
305 let r = earned_exp * (1.0 - p);
306 let u = latest[i] + r;
307 earned_expected_ultimate.push(earned_exp);
308 pct_reported.push(p);
309 ibnr.push(r);
310 ultimates.push(u);
311 }
312
313 Ok(InterimBfProjection {
314 latest: latest.to_vec(),
315 cdfs: cdfs_at_origin.to_vec(),
316 exposure_fractions: exposure_fractions.to_vec(),
317 earned_expected_ultimate,
318 pct_reported,
319 ibnr: ibnr.clone(),
320 ultimates: ultimates.clone(),
321 total_latest: latest.iter().sum(),
322 total_ibnr: ibnr.iter().sum(),
323 total_ultimate: ultimates.iter().sum(),
324 })
325}
326
327#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
330pub struct InterimCapeCodProjection {
331 pub latest: Vec<f64>,
333 pub cdfs: Vec<f64>,
335 pub exposure_fractions: Vec<f64>,
337 pub earned_premium: Vec<f64>,
339 pub used_up_premium: Vec<f64>,
341 pub elr: f64,
343 pub ibnr: Vec<f64>,
345 pub ultimates: Vec<f64>,
347 pub total_latest: f64,
349 pub total_ibnr: f64,
351 pub total_ultimate: f64,
353}
354
355pub fn interim_cape_cod(
360 latest: &[f64],
361 cdfs_at_origin: &[f64],
362 full_period_premium: &[f64],
363 exposure_fractions: &[f64],
364) -> Result<InterimCapeCodProjection, ValidationError> {
365 let n = latest.len();
366 if n == 0
367 || cdfs_at_origin.len() != n
368 || full_period_premium.len() != n
369 || exposure_fractions.len() != n
370 {
371 return Err(ValidationError::ShapeMismatch);
372 }
373 validate_nonnegative_finite_slice(latest)?;
374 validate_positive_finite_slice(cdfs_at_origin, "origin CDF")?;
375 validate_positive_finite_slice(full_period_premium, "premium")?;
376 validate_positive_finite_slice(exposure_fractions, "exposure_fractions")?;
377 if exposure_fractions.iter().any(|&e| e > 1.0 + 1e-9) {
378 return Err(ValidationError::InvalidParameter(
379 "exposure_fractions must lie in (0, 1]",
380 ));
381 }
382
383 let mut earned_premium = Vec::with_capacity(n);
384 let mut used_up_premium = Vec::with_capacity(n);
385 for i in 0..n {
386 let ep = full_period_premium[i] * exposure_fractions[i];
387 let uup = ep / cdfs_at_origin[i];
388 earned_premium.push(ep);
389 used_up_premium.push(uup);
390 }
391
392 let total_latest: f64 = latest.iter().sum();
393 let total_uup: f64 = used_up_premium.iter().sum();
394 if !(total_uup > 0.0) || !total_uup.is_finite() {
395 return Err(ValidationError::DivideByZero("used-up premium"));
396 }
397 let elr = total_latest / total_uup;
398
399 let mut ibnr = Vec::with_capacity(n);
400 let mut ultimates = Vec::with_capacity(n);
401 for i in 0..n {
402 let r = earned_premium[i] * elr * (1.0 - 1.0 / cdfs_at_origin[i]);
403 let u = latest[i] + r;
404 ibnr.push(r);
405 ultimates.push(u);
406 }
407
408 Ok(InterimCapeCodProjection {
409 latest: latest.to_vec(),
410 cdfs: cdfs_at_origin.to_vec(),
411 exposure_fractions: exposure_fractions.to_vec(),
412 earned_premium,
413 used_up_premium,
414 elr,
415 ibnr: ibnr.clone(),
416 ultimates: ultimates.clone(),
417 total_latest,
418 total_ibnr: ibnr.iter().sum(),
419 total_ultimate: ultimates.iter().sum(),
420 })
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426 use crate::subannual::grid::asymmetric_age_grid;
427
428 #[test]
429 fn asymmetric_cl_recovers_exact_synthetic_pattern() {
430 let grid = asymmetric_age_grid(4, 6, 12.0, 6.0, 6.0, None).unwrap();
432 assert_eq!(grid.observed_counts, vec![6, 6, 4, 2]);
433 let true_ldfs = [1.5, 1.3, 1.15, 1.08, 1.03];
434 let base_first = [100.0, 120.0, 140.0, 160.0];
435 let mut cum = vec![f64::NAN; 4 * 6];
436 for i in 0..4 {
437 let mut val = base_first[i];
438 for j in 0..grid.observed_counts[i] {
439 if j > 0 {
440 val *= true_ldfs[j - 1];
441 }
442 cum[i * 6 + j] = val;
443 }
444 }
445
446 let res = asymmetric_chain_ladder(
447 &cum,
448 &grid,
449 LdfSelectionMethod::VolumeWeighted,
450 1.0,
451 MonotonicityPolicy::Strict,
452 )
453 .unwrap();
454 for (got, expected) in res.ldfs.iter().zip(true_ldfs.iter()) {
455 assert!((got - expected).abs() < 1e-12);
456 }
457 assert!(res.total_ibnr > 0.0);
458 }
459
460 #[test]
461 fn interim_bf_and_cape_cod_pro_rate_stub_row() {
462 let latest = [1000.0, 800.0, 300.0];
463 let cdfs = [1.0, 1.25, 2.0];
464 let full_exp = [1000.0, 1000.0, 1000.0];
465 let fracs = [1.0, 1.0, 0.5];
466
467 let bf = interim_bf(&latest, &cdfs, &full_exp, &fracs).unwrap();
468 assert!((bf.earned_expected_ultimate[2] - 500.0).abs() < 1e-12);
470 assert!((bf.ibnr[2] - 250.0).abs() < 1e-12);
471 assert!((bf.ultimates[2] - 550.0).abs() < 1e-12);
472
473 let cc = interim_cape_cod(&latest, &cdfs, &full_exp, &fracs).unwrap();
474 assert!((cc.elr - (2100.0 / 2050.0)).abs() < 1e-12);
477 assert!((cc.ibnr[2] - 500.0 * cc.elr * 0.5).abs() < 1e-12);
478 }
479}