1use crate::linalg::{quad_form, weighted_least_squares_qr};
45use crate::preprocessing::triangle::cumulative_to_incremental;
46use crate::types::TriangleView;
47use crate::validate::{ValidationError, validate_positive_finite_slice, validate_triangle};
48
49#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
51pub enum AccidentSpec {
52 Constant,
55 PiecewiseLinear {
58 knots: Vec<usize>,
60 },
61 PerOrigin,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
67pub enum DevelopmentSpec {
68 PerPeriod,
70 PiecewiseLinear {
72 knots: Vec<usize>,
74 },
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub enum CalendarSpec {
80 None,
82 ConstantRate,
84 PiecewiseLinear {
88 knots: Vec<usize>,
90 },
91 ChangePointsOnly {
96 knots: Vec<usize>,
98 },
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
104pub enum LogNormalMeanMode {
105 #[default]
107 ProcessVariance,
108 FullPredictive,
110}
111
112#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
114pub struct PtfOptions {
115 pub accident: AccidentSpec,
117 pub development: DevelopmentSpec,
119 pub calendar: CalendarSpec,
121 pub exposure: Option<Vec<f64>>,
123 pub dev_weights: Option<Vec<f64>>,
126 pub future_calendar_rate: Option<f64>,
131 pub mean_mode: LogNormalMeanMode,
133}
134
135impl Default for PtfOptions {
136 fn default() -> Self {
137 Self {
138 accident: AccidentSpec::Constant,
139 development: DevelopmentSpec::PerPeriod,
140 calendar: CalendarSpec::ConstantRate,
141 exposure: None,
142 dev_weights: None,
143 future_calendar_rate: None,
144 mean_mode: LogNormalMeanMode::ProcessVariance,
145 }
146 }
147}
148
149impl PtfOptions {
150 pub fn with_accident(mut self, accident: AccidentSpec) -> Self {
152 self.accident = accident;
153 self
154 }
155
156 pub fn with_development(mut self, development: DevelopmentSpec) -> Self {
158 self.development = development;
159 self
160 }
161
162 pub fn with_calendar(mut self, calendar: CalendarSpec) -> Self {
164 self.calendar = calendar;
165 self
166 }
167
168 pub fn with_exposure(mut self, exposure: impl Into<Vec<f64>>) -> Self {
170 self.exposure = Some(exposure.into());
171 self
172 }
173
174 pub fn with_dev_weights(mut self, dev_weights: impl Into<Vec<f64>>) -> Self {
176 self.dev_weights = Some(dev_weights.into());
177 self
178 }
179
180 pub const fn with_future_calendar_rate(mut self, rate: f64) -> Self {
182 self.future_calendar_rate = Some(rate);
183 self
184 }
185
186 pub const fn with_mean_mode(mut self, mean_mode: LogNormalMeanMode) -> Self {
188 self.mean_mode = mean_mode;
189 self
190 }
191}
192
193#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
195pub struct PtfResult {
196 pub param_names: Vec<String>,
198 pub coefficients: Vec<f64>,
200 pub coefficient_se: Vec<f64>,
202 pub coefficient_covariance: Vec<f64>,
204 pub calendar_inflation_rates: Vec<f64>,
207 pub sigma_sq: f64,
209 pub sigma: f64,
211 pub n_observed: usize,
213 pub n_params: usize,
215 pub degrees_of_freedom: usize,
217 pub r_squared: f64,
219 pub aic: f64,
221 pub bic: f64,
223 pub fitted_incremental: Vec<f64>,
225 pub reserves: Vec<f64>,
227 pub ultimates: Vec<f64>,
229 pub standard_error: Vec<f64>,
231 pub total_reserve: f64,
233 pub total_msep: f64,
235 pub total_standard_error: f64,
237 pub total_cv: f64,
239}
240
241pub fn fit_ptf(
244 triangle: &TriangleView<'_>,
245 options: &PtfOptions,
246) -> Result<PtfResult, ValidationError> {
247 validate_triangle(triangle)?;
248 let n = triangle.n_origins;
249 if n < 3 {
250 return Err(ValidationError::InvalidParameter(
251 "PTF regression requires at least a 3x3 triangle",
252 ));
253 }
254
255 if let Some(exp) = &options.exposure {
256 if exp.len() != n {
257 return Err(ValidationError::ShapeMismatch);
258 }
259 validate_positive_finite_slice(exp, "exposure")?;
260 }
261 if let Some(dw) = &options.dev_weights {
262 if dw.len() != n {
263 return Err(ValidationError::ShapeMismatch);
264 }
265 validate_positive_finite_slice(dw, "dev_weights")?;
266 }
267 if let Some(fcr) = options.future_calendar_rate
268 && !fcr.is_finite()
269 {
270 return Err(ValidationError::NotFinite);
271 }
272
273 let inc = cumulative_to_incremental(triangle);
274 let schema = PtfDesignSchema::build(
275 n,
276 &options.accident,
277 &options.development,
278 &options.calendar,
279 )?;
280 let p = schema.param_names.len();
281
282 let max_obs = n * (n + 1) / 2;
284 let mut obs_cells: Vec<(usize, usize)> = Vec::with_capacity(max_obs);
285 let mut x_flat: Vec<f64> = Vec::with_capacity(max_obs * p);
286 let mut y_vec: Vec<f64> = Vec::with_capacity(max_obs);
287 let mut w_vec: Vec<f64> = Vec::with_capacity(max_obs);
288 let mut row_buf = vec![0.0; p];
289
290 for i in 0..n {
291 let log_exp = options.exposure.as_ref().map_or(0.0, |e| e[i].ln());
292 for j in 0..(n - i) {
293 let val = inc[i * n + j];
294 if !(val > 0.0) || !val.is_finite() {
295 return Err(ValidationError::InvalidParameter(
296 "PTF log-linear regression requires strictly positive observed incremental losses",
297 ));
298 }
299 schema.fill_row(i, j, None, &mut row_buf);
300 x_flat.extend_from_slice(&row_buf);
301 y_vec.push(val.ln() - log_exp);
302 w_vec.push(options.dev_weights.as_ref().map_or(1.0, |w| w[j]));
303 obs_cells.push((i, j));
304 }
305 }
306
307 let n_obs = obs_cells.len();
308 if n_obs <= p {
309 return Err(ValidationError::InvalidParameter(
310 "PTF model has non-positive residual degrees of freedom",
311 ));
312 }
313 let dof = n_obs - p;
314
315 let sol = weighted_least_squares_qr(&x_flat, &y_vec, &w_vec, n_obs, p)?;
316
317 let w_sum: f64 = w_vec.iter().sum();
319 let y_bar = y_vec
320 .iter()
321 .zip(w_vec.iter())
322 .map(|(&y, &w)| w * y)
323 .sum::<f64>()
324 / w_sum;
325
326 let mut rss = 0.0;
327 let mut tss = 0.0;
328 for (row_idx, &y_val) in y_vec.iter().enumerate() {
329 let mut eta = 0.0;
330 for col in 0..p {
331 eta += x_flat[row_idx * p + col] * sol.beta[col];
332 }
333 let resid = y_val - eta;
334 rss += w_vec[row_idx] * resid * resid;
335 let dy = y_val - y_bar;
336 tss += w_vec[row_idx] * dy * dy;
337 }
338
339 let sigma_sq = (rss / dof as f64).max(0.0);
340 let sigma = sigma_sq.sqrt();
341 let r_squared = if tss > 0.0 {
342 (1.0 - rss / tss).clamp(0.0, 1.0)
343 } else {
344 1.0
345 };
346 let rss_floor = (rss / n_obs as f64).max(1e-30);
347 let sum_ln_w: f64 = w_vec.iter().map(|w| w.ln()).sum();
348 let aic = n_obs as f64 * rss_floor.ln() - sum_ln_w + 2.0 * p as f64;
349 let bic = n_obs as f64 * rss_floor.ln() - sum_ln_w + (p as f64) * (n_obs as f64).ln();
350
351 let cov: Vec<f64> = sol.xtwx_inv.iter().map(|&v| sigma_sq * v).collect();
352 let coefficient_se: Vec<f64> = (0..p).map(|k| cov[k * p + k].max(0.0).sqrt()).collect();
353
354 let calendar_inflation_rates = schema.calendar_rates(&sol.beta, n);
356
357 let n_fut_cap = n * (n - 1) / 2;
360 let mut fitted_incremental = vec![0.0; n * n];
361 let mut future_meta: Vec<(usize, f64, f64, f64)> = Vec::with_capacity(n_fut_cap);
362 let mut future_x: Vec<f64> = Vec::with_capacity(n_fut_cap * p);
363 let mut latest_cum = vec![0.0; n];
364 let mut x_cell = vec![0.0; p];
365
366 for i in 0..n {
367 let log_exp = options.exposure.as_ref().map_or(0.0, |e| e[i].ln());
368 latest_cum[i] = triangle.get(i, n - 1 - i);
369 for j in 0..n {
370 let w_j = options.dev_weights.as_ref().map_or(1.0, |w| w[j]);
371 let extra_cal = schema.fill_row(i, j, options.future_calendar_rate, &mut x_cell);
372 let mut eta = log_exp + extra_cal;
373 for col in 0..p {
374 eta += x_cell[col] * sol.beta[col];
375 }
376 let v_proc = sigma_sq / w_j;
377 let v_est = quad_form(&x_cell, &cov, p).max(0.0);
378 let mean_var = match options.mean_mode {
379 LogNormalMeanMode::ProcessVariance => v_proc,
380 LogNormalMeanMode::FullPredictive => v_proc + v_est,
381 };
382 let mu = (eta + 0.5 * mean_var).exp();
383 if !mu.is_finite() {
384 return Err(ValidationError::NotFinite);
385 }
386 fitted_incremental[i * n + j] = mu;
387
388 if i + j >= n {
389 future_meta.push((i, mu, v_proc, v_est));
390 future_x.extend_from_slice(&x_cell);
391 }
392 }
393 }
394
395 let mut reserves = vec![0.0; n];
397 let mut origin_msep = vec![0.0; n];
398 for &(i, mu, _vp, _ve) in &future_meta {
399 reserves[i] += mu;
400 }
401
402 let n_fut = future_meta.len();
404 let mut cov_x = vec![0.0; n_fut * p];
405 for b in 0..n_fut {
406 let xb = &future_x[b * p..(b + 1) * p];
407 let dst = &mut cov_x[b * p..(b + 1) * p];
408 for r in 0..p {
409 let cov_row = &cov[r * p..(r + 1) * p];
410 let mut acc = 0.0;
411 for (&cr, &xc) in cov_row.iter().zip(xb.iter()) {
412 acc += cr * xc;
413 }
414 dst[r] = acc;
415 }
416 }
417
418 let mut total_msep = 0.0;
419 for a in 0..n_fut {
420 let (ia, mu_a, vp_a, v_est_a) = future_meta[a];
421 let xa = &future_x[a * p..(a + 1) * p];
422 let var_a = mu_a * mu_a * (vp_a + v_est_a).exp_m1();
423 if !var_a.is_finite() {
424 return Err(ValidationError::NotFinite);
425 }
426 origin_msep[ia] += var_a;
427 total_msep += var_a;
428
429 for b in (a + 1)..n_fut {
430 let (ib, mu_b, _vp_b, _ve_b) = future_meta[b];
431 let cvb = &cov_x[b * p..(b + 1) * p];
432 let mut cov_eta = 0.0;
433 for (&xar, &cvbr) in xa.iter().zip(cvb.iter()) {
434 cov_eta += xar * cvbr;
435 }
436 let cov_y = mu_a * mu_b * cov_eta.exp_m1();
437 if !cov_y.is_finite() {
438 return Err(ValidationError::NotFinite);
439 }
440 total_msep += 2.0 * cov_y;
441 if ia == ib {
442 origin_msep[ia] += 2.0 * cov_y;
443 }
444 }
445 }
446
447 if !total_msep.is_finite() {
448 return Err(ValidationError::NotFinite);
449 }
450
451 let ultimates: Vec<f64> = latest_cum
452 .iter()
453 .zip(reserves.iter())
454 .map(|(&l, &r)| l + r)
455 .collect();
456 let standard_error: Vec<f64> = origin_msep.iter().map(|v| v.max(0.0).sqrt()).collect();
457 let total_reserve: f64 = reserves.iter().sum();
458 let total_msep = total_msep.max(0.0);
459 let total_standard_error = total_msep.sqrt();
460 let total_cv = if total_reserve > 0.0 {
461 total_standard_error / total_reserve
462 } else {
463 0.0
464 };
465
466 Ok(PtfResult {
467 param_names: schema.param_names,
468 coefficients: sol.beta,
469 coefficient_se,
470 coefficient_covariance: cov,
471 calendar_inflation_rates,
472 sigma_sq,
473 sigma,
474 n_observed: n_obs,
475 n_params: p,
476 degrees_of_freedom: dof,
477 r_squared,
478 aic,
479 bic,
480 fitted_incremental,
481 reserves,
482 ultimates,
483 standard_error,
484 total_reserve,
485 total_msep,
486 total_standard_error,
487 total_cv,
488 })
489}
490
491struct PtfDesignSchema {
492 n: usize,
493 accident: AccidentSpec,
494 development: DevelopmentSpec,
495 calendar: CalendarSpec,
496 param_names: Vec<String>,
497 dev_offset: usize,
498 cal_offset: usize,
499}
500
501impl PtfDesignSchema {
502 fn build(
503 n: usize,
504 accident: &AccidentSpec,
505 development: &DevelopmentSpec,
506 calendar: &CalendarSpec,
507 ) -> Result<Self, ValidationError> {
508 let mut names = vec!["intercept".to_string()];
509
510 match accident {
511 AccidentSpec::Constant => {}
512 AccidentSpec::PiecewiseLinear { knots } => {
513 validate_knots(knots, n - 1, "accident knots")?;
514 names.push("alpha_slope_0".to_string());
515 for &k in knots {
516 names.push(format!("alpha_knot_{k}"));
517 }
518 }
519 AccidentSpec::PerOrigin => {
520 for i in 1..n {
521 names.push(format!("alpha_{i}"));
522 }
523 }
524 }
525
526 let dev_offset = names.len();
527 match development {
528 DevelopmentSpec::PerPeriod => {
529 for j in 1..n {
530 names.push(format!("gamma_{j}"));
531 }
532 }
533 DevelopmentSpec::PiecewiseLinear { knots } => {
534 validate_knots(knots, n - 1, "development knots")?;
535 names.push("gamma_slope_0".to_string());
536 for &k in knots {
537 names.push(format!("gamma_knot_{k}"));
538 }
539 }
540 }
541
542 let cal_offset = names.len();
543 match calendar {
544 CalendarSpec::None => {}
545 CalendarSpec::ConstantRate => {
546 names.push("iota_0".to_string());
547 }
548 CalendarSpec::PiecewiseLinear { knots } => {
549 validate_knots(knots, n - 1, "calendar knots")?;
550 names.push("iota_0".to_string());
551 for &k in knots {
552 names.push(format!("iota_knot_{k}"));
553 }
554 }
555 CalendarSpec::ChangePointsOnly { knots } => {
556 validate_knots(knots, n - 1, "calendar change-point knots")?;
557 for &k in knots {
558 names.push(format!("iota_knot_{k}"));
559 }
560 }
561 }
562
563 Ok(Self {
564 n,
565 accident: accident.clone(),
566 development: development.clone(),
567 calendar: calendar.clone(),
568 param_names: names,
569 dev_offset,
570 cal_offset,
571 })
572 }
573
574 fn fill_row(
577 &self,
578 i: usize,
579 j: usize,
580 future_calendar_rate: Option<f64>,
581 out: &mut [f64],
582 ) -> f64 {
583 out.fill(0.0);
584 out[0] = 1.0;
585
586 match &self.accident {
588 AccidentSpec::Constant => {}
589 AccidentSpec::PiecewiseLinear { knots } => {
590 out[1] = i as f64;
591 for (m, &k) in knots.iter().enumerate() {
592 if i > k {
593 out[2 + m] = (i - k) as f64;
594 }
595 }
596 }
597 AccidentSpec::PerOrigin => {
598 if i > 0 {
599 out[i] = 1.0;
600 }
601 }
602 }
603
604 match &self.development {
606 DevelopmentSpec::PerPeriod => {
607 for k in 1..=j {
610 out[self.dev_offset + (k - 1)] = 1.0;
611 }
612 }
613 DevelopmentSpec::PiecewiseLinear { knots } => {
614 out[self.dev_offset] = j as f64;
615 for (m, &k) in knots.iter().enumerate() {
616 if j > k {
617 out[self.dev_offset + 1 + m] = (j - k) as f64;
618 }
619 }
620 }
621 }
622
623 let t = i + j;
625 let last_obs_t = self.n - 1;
626 let (t_model, extra_offset) = match future_calendar_rate {
627 Some(rate) if t > last_obs_t => (last_obs_t, rate * (t - last_obs_t) as f64),
628 _ => (t, 0.0),
629 };
630
631 match &self.calendar {
632 CalendarSpec::None => {}
633 CalendarSpec::ConstantRate => {
634 out[self.cal_offset] = t_model as f64;
635 }
636 CalendarSpec::PiecewiseLinear { knots } => {
637 out[self.cal_offset] = t_model as f64;
638 for (m, &k) in knots.iter().enumerate() {
639 if t_model > k {
640 out[self.cal_offset + 1 + m] = (t_model - k) as f64;
641 }
642 }
643 }
644 CalendarSpec::ChangePointsOnly { knots } => {
645 for (m, &k) in knots.iter().enumerate() {
646 if t_model > k {
647 out[self.cal_offset + m] = (t_model - k) as f64;
648 }
649 }
650 }
651 }
652 extra_offset
653 }
654
655 fn calendar_rates(&self, beta: &[f64], n: usize) -> Vec<f64> {
656 let mut rates = vec![0.0; n.saturating_sub(1)];
657 for t in 1..n {
658 let rate = match &self.calendar {
660 CalendarSpec::None => 0.0,
661 CalendarSpec::ConstantRate => beta[self.cal_offset],
662 CalendarSpec::PiecewiseLinear { knots } => {
663 let mut r = beta[self.cal_offset];
664 for (m, &k) in knots.iter().enumerate() {
665 if t > k {
666 r += beta[self.cal_offset + 1 + m];
667 }
668 }
669 r
670 }
671 CalendarSpec::ChangePointsOnly { knots } => {
672 let mut r = 0.0;
673 for (m, &k) in knots.iter().enumerate() {
674 if t > k {
675 r += beta[self.cal_offset + m];
676 }
677 }
678 r
679 }
680 };
681 rates[t - 1] = rate;
682 }
683 rates
684 }
685}
686
687fn validate_knots(
688 knots: &[usize],
689 max_exclusive: usize,
690 _ctx: &str,
691) -> Result<(), ValidationError> {
692 let mut prev = 0usize;
693 for &k in knots {
694 if k == 0 || k >= max_exclusive {
695 return Err(ValidationError::InvalidParameter(
696 "PTF knot index must lie strictly inside (0, n - 1)",
697 ));
698 }
699 if k <= prev {
700 return Err(ValidationError::InvalidParameter(
701 "PTF knots must be strictly increasing",
702 ));
703 }
704 prev = k;
705 }
706 Ok(())
707}
708
709#[cfg(test)]
710mod tests {
711 use super::*;
712 use crate::types::Triangle;
713
714 const NAN: f64 = f64::NAN;
715
716 #[test]
717 fn ptf_recovers_exact_inflation_shock_parameters_and_future_reserves() {
718 let n = 8usize;
722 let alpha0 = 10.0_f64;
723 let dev_cum = [0.0, 0.35, 0.15, -0.25, -0.70, -1.20, -1.75, -2.30];
724 let iota_pre = 0.04_f64;
725 let iota_shift = 0.10_f64;
726 let knot = 4usize;
727
728 let mut cum_data = vec![NAN; n * n];
729 let mut true_reserve = 0.0;
730 for i in 0..n {
731 let mut running = 0.0;
732 for j in 0..n {
733 let t = i + j;
734 let cal = iota_pre * t as f64 + iota_shift * t.saturating_sub(knot) as f64;
735 let inc = (alpha0 + dev_cum[j] + cal).exp();
736 if i + j < n {
737 running += inc;
738 cum_data[i * n + j] = running;
739 } else {
740 true_reserve += inc;
741 }
742 }
743 }
744 let tri = Triangle::new(n, n, cum_data);
745 let opts = PtfOptions {
746 accident: AccidentSpec::Constant,
747 development: DevelopmentSpec::PerPeriod,
748 calendar: CalendarSpec::PiecewiseLinear { knots: vec![knot] },
749 ..PtfOptions::default()
750 };
751 let res = fit_ptf(&tri.view(), &opts).expect("ptf");
752
753 assert!(res.sigma < 1e-10, "sigma={}", res.sigma);
754 assert!((res.calendar_inflation_rates[0] - iota_pre).abs() < 1e-10);
755 assert!((res.calendar_inflation_rates[knot - 1] - iota_pre).abs() < 1e-10);
756 assert!((res.calendar_inflation_rates[knot] - (iota_pre + iota_shift)).abs() < 1e-10);
757 assert!(
758 (res.total_reserve - true_reserve).abs() / true_reserve < 1e-9,
759 "got {} expected {}",
760 res.total_reserve,
761 true_reserve
762 );
763 }
764}