use crate::linalg::{quad_form, weighted_least_squares_qr};
use crate::preprocessing::triangle::cumulative_to_incremental;
use crate::types::TriangleView;
use crate::validate::{ValidationError, validate_positive_finite_slice, validate_triangle};
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum AccidentSpec {
Constant,
PiecewiseLinear {
knots: Vec<usize>,
},
PerOrigin,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum DevelopmentSpec {
PerPeriod,
PiecewiseLinear {
knots: Vec<usize>,
},
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum CalendarSpec {
None,
ConstantRate,
PiecewiseLinear {
knots: Vec<usize>,
},
ChangePointsOnly {
knots: Vec<usize>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum LogNormalMeanMode {
#[default]
ProcessVariance,
FullPredictive,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PtfOptions {
pub accident: AccidentSpec,
pub development: DevelopmentSpec,
pub calendar: CalendarSpec,
pub exposure: Option<Vec<f64>>,
pub dev_weights: Option<Vec<f64>>,
pub future_calendar_rate: Option<f64>,
pub mean_mode: LogNormalMeanMode,
}
impl Default for PtfOptions {
fn default() -> Self {
Self {
accident: AccidentSpec::Constant,
development: DevelopmentSpec::PerPeriod,
calendar: CalendarSpec::ConstantRate,
exposure: None,
dev_weights: None,
future_calendar_rate: None,
mean_mode: LogNormalMeanMode::ProcessVariance,
}
}
}
impl PtfOptions {
pub fn with_accident(mut self, accident: AccidentSpec) -> Self {
self.accident = accident;
self
}
pub fn with_development(mut self, development: DevelopmentSpec) -> Self {
self.development = development;
self
}
pub fn with_calendar(mut self, calendar: CalendarSpec) -> Self {
self.calendar = calendar;
self
}
pub fn with_exposure(mut self, exposure: impl Into<Vec<f64>>) -> Self {
self.exposure = Some(exposure.into());
self
}
pub fn with_dev_weights(mut self, dev_weights: impl Into<Vec<f64>>) -> Self {
self.dev_weights = Some(dev_weights.into());
self
}
pub const fn with_future_calendar_rate(mut self, rate: f64) -> Self {
self.future_calendar_rate = Some(rate);
self
}
pub const fn with_mean_mode(mut self, mean_mode: LogNormalMeanMode) -> Self {
self.mean_mode = mean_mode;
self
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PtfResult {
pub param_names: Vec<String>,
pub coefficients: Vec<f64>,
pub coefficient_se: Vec<f64>,
pub coefficient_covariance: Vec<f64>,
pub calendar_inflation_rates: Vec<f64>,
pub sigma_sq: f64,
pub sigma: f64,
pub n_observed: usize,
pub n_params: usize,
pub degrees_of_freedom: usize,
pub r_squared: f64,
pub aic: f64,
pub bic: f64,
pub fitted_incremental: Vec<f64>,
pub reserves: Vec<f64>,
pub ultimates: Vec<f64>,
pub standard_error: Vec<f64>,
pub total_reserve: f64,
pub total_msep: f64,
pub total_standard_error: f64,
pub total_cv: f64,
}
pub fn fit_ptf(
triangle: &TriangleView<'_>,
options: &PtfOptions,
) -> Result<PtfResult, ValidationError> {
validate_triangle(triangle)?;
let n = triangle.n_origins;
if n < 3 {
return Err(ValidationError::InvalidParameter(
"PTF regression requires at least a 3x3 triangle",
));
}
if let Some(exp) = &options.exposure {
if exp.len() != n {
return Err(ValidationError::ShapeMismatch);
}
validate_positive_finite_slice(exp, "exposure")?;
}
if let Some(dw) = &options.dev_weights {
if dw.len() != n {
return Err(ValidationError::ShapeMismatch);
}
validate_positive_finite_slice(dw, "dev_weights")?;
}
if let Some(fcr) = options.future_calendar_rate
&& !fcr.is_finite()
{
return Err(ValidationError::NotFinite);
}
let inc = cumulative_to_incremental(triangle);
let schema = PtfDesignSchema::build(
n,
&options.accident,
&options.development,
&options.calendar,
)?;
let p = schema.param_names.len();
let max_obs = n * (n + 1) / 2;
let mut obs_cells: Vec<(usize, usize)> = Vec::with_capacity(max_obs);
let mut x_flat: Vec<f64> = Vec::with_capacity(max_obs * p);
let mut y_vec: Vec<f64> = Vec::with_capacity(max_obs);
let mut w_vec: Vec<f64> = Vec::with_capacity(max_obs);
let mut row_buf = vec![0.0; p];
for i in 0..n {
let log_exp = options.exposure.as_ref().map_or(0.0, |e| e[i].ln());
for j in 0..(n - i) {
let val = inc[i * n + j];
if !(val > 0.0) || !val.is_finite() {
return Err(ValidationError::InvalidParameter(
"PTF log-linear regression requires strictly positive observed incremental losses",
));
}
schema.fill_row(i, j, None, &mut row_buf);
x_flat.extend_from_slice(&row_buf);
y_vec.push(val.ln() - log_exp);
w_vec.push(options.dev_weights.as_ref().map_or(1.0, |w| w[j]));
obs_cells.push((i, j));
}
}
let n_obs = obs_cells.len();
if n_obs <= p {
return Err(ValidationError::InvalidParameter(
"PTF model has non-positive residual degrees of freedom",
));
}
let dof = n_obs - p;
let sol = weighted_least_squares_qr(&x_flat, &y_vec, &w_vec, n_obs, p)?;
let w_sum: f64 = w_vec.iter().sum();
let y_bar = y_vec
.iter()
.zip(w_vec.iter())
.map(|(&y, &w)| w * y)
.sum::<f64>()
/ w_sum;
let mut rss = 0.0;
let mut tss = 0.0;
for (row_idx, &y_val) in y_vec.iter().enumerate() {
let mut eta = 0.0;
for col in 0..p {
eta += x_flat[row_idx * p + col] * sol.beta[col];
}
let resid = y_val - eta;
rss += w_vec[row_idx] * resid * resid;
let dy = y_val - y_bar;
tss += w_vec[row_idx] * dy * dy;
}
let sigma_sq = (rss / dof as f64).max(0.0);
let sigma = sigma_sq.sqrt();
let r_squared = if tss > 0.0 {
(1.0 - rss / tss).clamp(0.0, 1.0)
} else {
1.0
};
let rss_floor = (rss / n_obs as f64).max(1e-30);
let sum_ln_w: f64 = w_vec.iter().map(|w| w.ln()).sum();
let aic = n_obs as f64 * rss_floor.ln() - sum_ln_w + 2.0 * p as f64;
let bic = n_obs as f64 * rss_floor.ln() - sum_ln_w + (p as f64) * (n_obs as f64).ln();
let cov: Vec<f64> = sol.xtwx_inv.iter().map(|&v| sigma_sq * v).collect();
let coefficient_se: Vec<f64> = (0..p).map(|k| cov[k * p + k].max(0.0).sqrt()).collect();
let calendar_inflation_rates = schema.calendar_rates(&sol.beta, n);
let n_fut_cap = n * (n - 1) / 2;
let mut fitted_incremental = vec![0.0; n * n];
let mut future_meta: Vec<(usize, f64, f64, f64)> = Vec::with_capacity(n_fut_cap);
let mut future_x: Vec<f64> = Vec::with_capacity(n_fut_cap * p);
let mut latest_cum = vec![0.0; n];
let mut x_cell = vec![0.0; p];
for i in 0..n {
let log_exp = options.exposure.as_ref().map_or(0.0, |e| e[i].ln());
latest_cum[i] = triangle.get(i, n - 1 - i);
for j in 0..n {
let w_j = options.dev_weights.as_ref().map_or(1.0, |w| w[j]);
let extra_cal = schema.fill_row(i, j, options.future_calendar_rate, &mut x_cell);
let mut eta = log_exp + extra_cal;
for col in 0..p {
eta += x_cell[col] * sol.beta[col];
}
let v_proc = sigma_sq / w_j;
let v_est = quad_form(&x_cell, &cov, p).max(0.0);
let mean_var = match options.mean_mode {
LogNormalMeanMode::ProcessVariance => v_proc,
LogNormalMeanMode::FullPredictive => v_proc + v_est,
};
let mu = (eta + 0.5 * mean_var).exp();
if !mu.is_finite() {
return Err(ValidationError::NotFinite);
}
fitted_incremental[i * n + j] = mu;
if i + j >= n {
future_meta.push((i, mu, v_proc, v_est));
future_x.extend_from_slice(&x_cell);
}
}
}
let mut reserves = vec![0.0; n];
let mut origin_msep = vec![0.0; n];
for &(i, mu, _vp, _ve) in &future_meta {
reserves[i] += mu;
}
let n_fut = future_meta.len();
let mut cov_x = vec![0.0; n_fut * p];
for b in 0..n_fut {
let xb = &future_x[b * p..(b + 1) * p];
let dst = &mut cov_x[b * p..(b + 1) * p];
for r in 0..p {
let cov_row = &cov[r * p..(r + 1) * p];
let mut acc = 0.0;
for (&cr, &xc) in cov_row.iter().zip(xb.iter()) {
acc += cr * xc;
}
dst[r] = acc;
}
}
let mut total_msep = 0.0;
for a in 0..n_fut {
let (ia, mu_a, vp_a, v_est_a) = future_meta[a];
let xa = &future_x[a * p..(a + 1) * p];
let var_a = mu_a * mu_a * (vp_a + v_est_a).exp_m1();
if !var_a.is_finite() {
return Err(ValidationError::NotFinite);
}
origin_msep[ia] += var_a;
total_msep += var_a;
for b in (a + 1)..n_fut {
let (ib, mu_b, _vp_b, _ve_b) = future_meta[b];
let cvb = &cov_x[b * p..(b + 1) * p];
let mut cov_eta = 0.0;
for (&xar, &cvbr) in xa.iter().zip(cvb.iter()) {
cov_eta += xar * cvbr;
}
let cov_y = mu_a * mu_b * cov_eta.exp_m1();
if !cov_y.is_finite() {
return Err(ValidationError::NotFinite);
}
total_msep += 2.0 * cov_y;
if ia == ib {
origin_msep[ia] += 2.0 * cov_y;
}
}
}
if !total_msep.is_finite() {
return Err(ValidationError::NotFinite);
}
let ultimates: Vec<f64> = latest_cum
.iter()
.zip(reserves.iter())
.map(|(&l, &r)| l + r)
.collect();
let standard_error: Vec<f64> = origin_msep.iter().map(|v| v.max(0.0).sqrt()).collect();
let total_reserve: f64 = reserves.iter().sum();
let total_msep = total_msep.max(0.0);
let total_standard_error = total_msep.sqrt();
let total_cv = if total_reserve > 0.0 {
total_standard_error / total_reserve
} else {
0.0
};
Ok(PtfResult {
param_names: schema.param_names,
coefficients: sol.beta,
coefficient_se,
coefficient_covariance: cov,
calendar_inflation_rates,
sigma_sq,
sigma,
n_observed: n_obs,
n_params: p,
degrees_of_freedom: dof,
r_squared,
aic,
bic,
fitted_incremental,
reserves,
ultimates,
standard_error,
total_reserve,
total_msep,
total_standard_error,
total_cv,
})
}
struct PtfDesignSchema {
n: usize,
accident: AccidentSpec,
development: DevelopmentSpec,
calendar: CalendarSpec,
param_names: Vec<String>,
dev_offset: usize,
cal_offset: usize,
}
impl PtfDesignSchema {
fn build(
n: usize,
accident: &AccidentSpec,
development: &DevelopmentSpec,
calendar: &CalendarSpec,
) -> Result<Self, ValidationError> {
let mut names = vec!["intercept".to_string()];
match accident {
AccidentSpec::Constant => {}
AccidentSpec::PiecewiseLinear { knots } => {
validate_knots(knots, n - 1, "accident knots")?;
names.push("alpha_slope_0".to_string());
for &k in knots {
names.push(format!("alpha_knot_{k}"));
}
}
AccidentSpec::PerOrigin => {
for i in 1..n {
names.push(format!("alpha_{i}"));
}
}
}
let dev_offset = names.len();
match development {
DevelopmentSpec::PerPeriod => {
for j in 1..n {
names.push(format!("gamma_{j}"));
}
}
DevelopmentSpec::PiecewiseLinear { knots } => {
validate_knots(knots, n - 1, "development knots")?;
names.push("gamma_slope_0".to_string());
for &k in knots {
names.push(format!("gamma_knot_{k}"));
}
}
}
let cal_offset = names.len();
match calendar {
CalendarSpec::None => {}
CalendarSpec::ConstantRate => {
names.push("iota_0".to_string());
}
CalendarSpec::PiecewiseLinear { knots } => {
validate_knots(knots, n - 1, "calendar knots")?;
names.push("iota_0".to_string());
for &k in knots {
names.push(format!("iota_knot_{k}"));
}
}
CalendarSpec::ChangePointsOnly { knots } => {
validate_knots(knots, n - 1, "calendar change-point knots")?;
for &k in knots {
names.push(format!("iota_knot_{k}"));
}
}
}
Ok(Self {
n,
accident: accident.clone(),
development: development.clone(),
calendar: calendar.clone(),
param_names: names,
dev_offset,
cal_offset,
})
}
fn fill_row(
&self,
i: usize,
j: usize,
future_calendar_rate: Option<f64>,
out: &mut [f64],
) -> f64 {
out.fill(0.0);
out[0] = 1.0;
match &self.accident {
AccidentSpec::Constant => {}
AccidentSpec::PiecewiseLinear { knots } => {
out[1] = i as f64;
for (m, &k) in knots.iter().enumerate() {
if i > k {
out[2 + m] = (i - k) as f64;
}
}
}
AccidentSpec::PerOrigin => {
if i > 0 {
out[i] = 1.0;
}
}
}
match &self.development {
DevelopmentSpec::PerPeriod => {
for k in 1..=j {
out[self.dev_offset + (k - 1)] = 1.0;
}
}
DevelopmentSpec::PiecewiseLinear { knots } => {
out[self.dev_offset] = j as f64;
for (m, &k) in knots.iter().enumerate() {
if j > k {
out[self.dev_offset + 1 + m] = (j - k) as f64;
}
}
}
}
let t = i + j;
let last_obs_t = self.n - 1;
let (t_model, extra_offset) = match future_calendar_rate {
Some(rate) if t > last_obs_t => (last_obs_t, rate * (t - last_obs_t) as f64),
_ => (t, 0.0),
};
match &self.calendar {
CalendarSpec::None => {}
CalendarSpec::ConstantRate => {
out[self.cal_offset] = t_model as f64;
}
CalendarSpec::PiecewiseLinear { knots } => {
out[self.cal_offset] = t_model as f64;
for (m, &k) in knots.iter().enumerate() {
if t_model > k {
out[self.cal_offset + 1 + m] = (t_model - k) as f64;
}
}
}
CalendarSpec::ChangePointsOnly { knots } => {
for (m, &k) in knots.iter().enumerate() {
if t_model > k {
out[self.cal_offset + m] = (t_model - k) as f64;
}
}
}
}
extra_offset
}
fn calendar_rates(&self, beta: &[f64], n: usize) -> Vec<f64> {
let mut rates = vec![0.0; n.saturating_sub(1)];
for t in 1..n {
let rate = match &self.calendar {
CalendarSpec::None => 0.0,
CalendarSpec::ConstantRate => beta[self.cal_offset],
CalendarSpec::PiecewiseLinear { knots } => {
let mut r = beta[self.cal_offset];
for (m, &k) in knots.iter().enumerate() {
if t > k {
r += beta[self.cal_offset + 1 + m];
}
}
r
}
CalendarSpec::ChangePointsOnly { knots } => {
let mut r = 0.0;
for (m, &k) in knots.iter().enumerate() {
if t > k {
r += beta[self.cal_offset + m];
}
}
r
}
};
rates[t - 1] = rate;
}
rates
}
}
fn validate_knots(
knots: &[usize],
max_exclusive: usize,
_ctx: &str,
) -> Result<(), ValidationError> {
let mut prev = 0usize;
for &k in knots {
if k == 0 || k >= max_exclusive {
return Err(ValidationError::InvalidParameter(
"PTF knot index must lie strictly inside (0, n - 1)",
));
}
if k <= prev {
return Err(ValidationError::InvalidParameter(
"PTF knots must be strictly increasing",
));
}
prev = k;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::Triangle;
const NAN: f64 = f64::NAN;
#[test]
fn ptf_recovers_exact_inflation_shock_parameters_and_future_reserves() {
let n = 8usize;
let alpha0 = 10.0_f64;
let dev_cum = [0.0, 0.35, 0.15, -0.25, -0.70, -1.20, -1.75, -2.30];
let iota_pre = 0.04_f64;
let iota_shift = 0.10_f64;
let knot = 4usize;
let mut cum_data = vec![NAN; n * n];
let mut true_reserve = 0.0;
for i in 0..n {
let mut running = 0.0;
for j in 0..n {
let t = i + j;
let cal = iota_pre * t as f64 + iota_shift * t.saturating_sub(knot) as f64;
let inc = (alpha0 + dev_cum[j] + cal).exp();
if i + j < n {
running += inc;
cum_data[i * n + j] = running;
} else {
true_reserve += inc;
}
}
}
let tri = Triangle::new(n, n, cum_data);
let opts = PtfOptions {
accident: AccidentSpec::Constant,
development: DevelopmentSpec::PerPeriod,
calendar: CalendarSpec::PiecewiseLinear { knots: vec![knot] },
..PtfOptions::default()
};
let res = fit_ptf(&tri.view(), &opts).expect("ptf");
assert!(res.sigma < 1e-10, "sigma={}", res.sigma);
assert!((res.calendar_inflation_rates[0] - iota_pre).abs() < 1e-10);
assert!((res.calendar_inflation_rates[knot - 1] - iota_pre).abs() < 1e-10);
assert!((res.calendar_inflation_rates[knot] - (iota_pre + iota_shift)).abs() < 1e-10);
assert!(
(res.total_reserve - true_reserve).abs() / true_reserve < 1e-9,
"got {} expected {}",
res.total_reserve,
true_reserve
);
}
}