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