Skip to main content

reserving_kernels/
ptf_regression.rs

1//! Barnett & Zehnwirth (2000) Probabilistic Trend Family (PTF) log-linear
2//! regression reserving kernel.
3//!
4//! Implements:
5//!
6//! * G. Barnett & B. Zehnwirth, *"Best Estimates for Reserves"*, *PCAS*,
7//!   Vol. LXXXVII (2000), pp. 245–321.
8//!
9//! ## Model Specification
10//!
11//! For strictly positive incremental claims `Y_{i,j}` (origin `i = 0..n-1`,
12//! development `j = 0..n-1`, calendar period `t = i + j`), optionally divided
13//! by exposure `E_i`:
14//!
15//! `ln(Y_{i,j} / E_i) = alpha_i + sum_{k=1}^j gamma_k + sum_{t=1}^{i+j} iota_t + eps_{i,j}`
16//!
17//! with `eps_{i,j} ~ N(0, sigma^2 / w_{i,j})`.
18//!
19//! Because `t = i + j`, saturating all three directions simultaneously creates
20//! an age–period–cohort collinearity. PTF parameterizes each direction via
21//! parsimonious piecewise-linear trends with explicit knots (solved via
22//! Householder QR weighted least squares):
23//!
24//! * **Accident direction (`AccidentSpec`)**: constant intercept `alpha`,
25//!   piecewise-linear accident trend with knots, or per-origin levels
26//!   `alpha_0..alpha_{n-1}`.
27//! * **Development direction (`DevelopmentSpec`)**: piecewise-linear
28//!   development slopes `gamma` with knots, or full per-lag increments
29//!   `gamma_1..gamma_{n-1}`.
30//! * **Calendar direction (`CalendarSpec`)**: zero calendar trend, constant
31//!   calendar inflation `iota * (i + j)`, piecewise-linear inflation regimes
32//!   with knots `kappa_m` (`sum_m delta_m * max(0, i + j - kappa_m)`), or
33//!   inflation change-points only (identifiable even alongside saturated
34//!   per-origin `alpha_i` and per-lag `gamma_k`).
35//!
36//! ## Forecasting & Analytical MSEP
37//!
38//! Future incremental cells `(i, j)` (`i + j >= n`) are projected on the
39//! log scale as `eta_hat_{i,j} = x_{i,j}^T beta_hat + ln(E_i)` with parameter
40//! covariance `Cov(eta_hat_a, eta_hat_b) = sigma^2 * x_a^T (X^T W X)^{-1} x_b`,
41//! log-normal bias correction, and exact analytical log-normal reserve MSEP
42//! including full cross-cell parameter covariance.
43
44use crate::linalg::{quad_form, weighted_least_squares_qr};
45use crate::triangle::cumulative_to_incremental;
46use crate::types::TriangleView;
47use crate::validate::{ValidationError, validate_positive_finite_slice, validate_triangle};
48
49/// Accident-year direction specification for PTF regression.
50#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
51pub enum AccidentSpec {
52    /// Single constant level `alpha` shared across origins (allows full
53    /// identification of a baseline calendar inflation rate `iota`).
54    Constant,
55    /// Piecewise-linear accident trend with slope change knots (e.g. `&[]` for
56    /// linear accident trend, `&[4]` for slope change at origin 4).
57    PiecewiseLinear {
58        /// Interior knot origin indices `k` (`1 <= k < n - 1`).
59        knots: Vec<usize>,
60    },
61    /// Separate level `alpha_i` for every origin `i = 0..n-1`.
62    PerOrigin,
63}
64
65/// Development-period direction specification for PTF regression.
66#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
67pub enum DevelopmentSpec {
68    /// Separate development step `gamma_k` for every lag `k = 1..n-1`.
69    PerPeriod,
70    /// Piecewise-linear development trend with slope change knots at lags `k`.
71    PiecewiseLinear {
72        /// Interior knot development lag indices `k` (`1 <= k < n - 1`).
73        knots: Vec<usize>,
74    },
75}
76
77/// Calendar-year inflation direction specification for PTF regression.
78#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
79pub enum CalendarSpec {
80    /// No calendar-year inflation term (`iota_t = 0`).
81    None,
82    /// Constant calendar inflation rate `iota` across all calendar periods `t = i + j`.
83    ConstantRate,
84    /// Piecewise-linear calendar inflation with baseline rate `iota_0` plus
85    /// rate shifts `delta_m` after calendar knot periods `knots`
86    /// (`iota_0 * t + sum_m delta_m * max(0, t - knot_m)`).
87    PiecewiseLinear {
88        /// Calendar-period knots `t_m` (`1 <= t_m < n - 1`) where inflation rate shifts.
89        knots: Vec<usize>,
90    },
91    /// Calendar inflation regime shifts only (`sum_m delta_m * max(0, t - knot_m)`),
92    /// omitting the baseline linear slope so it remains uniquely identifiable
93    /// even when both `AccidentSpec::PerOrigin` and `DevelopmentSpec::PerPeriod`
94    /// are active.
95    ChangePointsOnly {
96        /// Calendar-period knots `t_m` (`1 <= t_m < n - 1`).
97        knots: Vec<usize>,
98    },
99}
100
101/// Log-normal bias-correction convention when transforming log-scale
102/// predictions `eta_hat` back to dollar incremental expectations.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
104pub enum LogNormalMeanMode {
105    /// Plug-in log-normal mean: `exp(eta_hat + 0.5 * sigma^2)`.
106    #[default]
107    ProcessVariance,
108    /// Full predictive log-normal mean: `exp(eta_hat + 0.5 * (sigma^2 + v_est))`.
109    FullPredictive,
110}
111
112/// Configuration for [`fit_ptf`].
113#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
114pub struct PtfOptions {
115    /// Accident-year trend parameterization.
116    pub accident: AccidentSpec,
117    /// Development-period trend parameterization.
118    pub development: DevelopmentSpec,
119    /// Calendar-year inflation trend parameterization.
120    pub calendar: CalendarSpec,
121    /// Optional positive exposure vector `E_i` (length `n`) used as log offset.
122    pub exposure: Option<Vec<f64>>,
123    /// Optional per-development-period observation weights `w_j > 0` (length `n`)
124    /// for heteroscedastic weighted OLS (Barnett & Zehnwirth 2000, §5).
125    pub dev_weights: Option<Vec<f64>>,
126    /// Future calendar inflation assumption beyond the last observed diagonal
127    /// (`t >= n`): when `Some(r)`, overrides future calendar slope beyond `t = n - 1`
128    /// with constant rate `r`; when `None`, continues the final estimated
129    /// calendar-year inflation regime.
130    pub future_calendar_rate: Option<f64>,
131    /// Log-normal mean bias-correction convention.
132    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    /// Set the accident-year trend specification.
151    pub fn with_accident(mut self, accident: AccidentSpec) -> Self {
152        self.accident = accident;
153        self
154    }
155
156    /// Set the development-period trend specification.
157    pub fn with_development(mut self, development: DevelopmentSpec) -> Self {
158        self.development = development;
159        self
160    }
161
162    /// Set the calendar-year inflation specification.
163    pub fn with_calendar(mut self, calendar: CalendarSpec) -> Self {
164        self.calendar = calendar;
165        self
166    }
167
168    /// Supply a positive exposure vector `E_i` used as a `ln(E_i)` offset.
169    pub fn with_exposure(mut self, exposure: impl Into<Vec<f64>>) -> Self {
170        self.exposure = Some(exposure.into());
171        self
172    }
173
174    /// Supply per-development-period observation weights `w_j > 0`.
175    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    /// Override the future calendar inflation rate beyond the last observed diagonal.
181    pub const fn with_future_calendar_rate(mut self, rate: f64) -> Self {
182        self.future_calendar_rate = Some(rate);
183        self
184    }
185
186    /// Set the log-normal mean bias-correction convention.
187    pub const fn with_mean_mode(mut self, mean_mode: LogNormalMeanMode) -> Self {
188        self.mean_mode = mean_mode;
189        self
190    }
191}
192
193/// Output from Barnett & Zehnwirth (2000) PTF log-linear regression reserving.
194#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
195pub struct PtfResult {
196    /// Human-readable names of the fitted regression parameters (length `p`).
197    pub param_names: Vec<String>,
198    /// Estimated regression parameter vector `beta_hat` (length `p`).
199    pub coefficients: Vec<f64>,
200    /// Parameter standard errors `sqrt(diag(Cov(beta_hat)))` (length `p`).
201    pub coefficient_se: Vec<f64>,
202    /// Full `p × p` parameter covariance matrix `sigma^2 * (X^T W X)^{-1}` (row-major).
203    pub coefficient_covariance: Vec<f64>,
204    /// Implied incremental calendar-year inflation rates `iota_t` for `t = 1..n-1`
205    /// (on the log scale; annual percentage rate is `exp(iota_t) - 1`).
206    pub calendar_inflation_rates: Vec<f64>,
207    /// Residual variance `sigma^2 = weighted_rss / (N - p)`.
208    pub sigma_sq: f64,
209    /// Residual standard error `sigma = sqrt(sigma_sq)`.
210    pub sigma: f64,
211    /// Number of observed positive incremental cells `N`.
212    pub n_observed: usize,
213    /// Number of fitted parameters `p`.
214    pub n_params: usize,
215    /// Residual degrees of freedom `N - p`.
216    pub degrees_of_freedom: usize,
217    /// Weighted coefficient of determination `R^2`.
218    pub r_squared: f64,
219    /// Akaike Information Criterion (`N * ln(weighted_rss / N) + 2 * p`, Gaussian log-scale).
220    pub aic: f64,
221    /// Bayesian Information Criterion (`N * ln(weighted_rss / N) + p * ln(N)`).
222    pub bic: f64,
223    /// Full `n × n` fitted/projected incremental expectations (row-major).
224    pub fitted_incremental: Vec<f64>,
225    /// Projected reserves by origin (length `n`).
226    pub reserves: Vec<f64>,
227    /// Projected ultimates by origin (`latest_cumulative + reserves[i]`, length `n`).
228    pub ultimates: Vec<f64>,
229    /// Analytical prediction standard error by origin (length `n`).
230    pub standard_error: Vec<f64>,
231    /// Total projected reserve across origins.
232    pub total_reserve: f64,
233    /// Analytical aggregate prediction MSEP (including cross-cell parameter covariance).
234    pub total_msep: f64,
235    /// Analytical aggregate prediction standard error `sqrt(total_msep)`.
236    pub total_standard_error: f64,
237    /// Aggregate coefficient of variation (`total_standard_error / total_reserve`).
238    pub total_cv: f64,
239}
240
241/// Fit the Barnett & Zehnwirth (2000) Probabilistic Trend Family (PTF) model
242/// to a cumulative loss triangle.
243pub 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        if !fcr.is_finite() {
269            return Err(ValidationError::NotFinite);
270        }
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    // Assemble observed rows for all strictly positive observed incremental cells.
283    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    // Weighted residual sum of squares and R^2.
318    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    // Extract implied incremental calendar-year inflation rates iota_t for t = 1..n-1.
355    let calendar_inflation_rates = schema.calendar_rates(&sol.beta, n);
356
357    // Compute fitted incremental values across full n × n grid and forecast future cells
358    // using a single reusable row buffer and flat future design matrix.
359    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    // Per-origin and aggregate reserves + exact analytical log-normal MSEP.
396    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    // Precompute Cov * x_b into a flat n_fut × p buffer so pairwise covariances run in O(N_fut^2 * p).
403    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    /// Populate design row `out` for cell `(i, j)`. Returns any deterministic
575    /// future calendar offset (when `future_calendar_rate` overrides `t > n - 1`).
576    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        // Accident direction.
587        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        // Development direction: sum_{k=1}^j gamma_k or piecewise linear in j.
605        match &self.development {
606            DevelopmentSpec::PerPeriod => {
607                // Parameter gamma_k represents incremental change from k-1 to k,
608                // so cumulative sum_{k=1}^j gamma_k places 1.0 in columns 1..=j.
609                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        // Calendar direction: t = i + j.
624        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            // Incremental calendar trend from t-1 to t.
659            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        // Synthetic 8x8 incremental triangle with known development curve and a
719        // sharp calendar-year inflation shock at calendar year t = 4:
720        //   iota_t = 0.04 for t <= 4, jumping to 0.14 (+0.10 shock) for t > 4.
721        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}