Skip to main content

reserving_kernels/subannual/
grid.rs

1//! Asymmetric grid geometry, valuation age mapping, stub average claim age,
2//! and calendar-diagonal alignment.
3//!
4//! Implements:
5//!
6//! * **Asymmetric Age Grid (`asymmetric_age_grid`)** — Friedland (2010),
7//!   *Estimating Unpaid Claims Using Basic Techniques*, Ch. 7: maps
8//!   `(origin_idx, dev_idx)` on rectangular grids (annual origin × semiannual,
9//!   quarterly, or monthly development; stride ratios 2:1, 4:1, 12:1, or general
10//!   positive ratios) to exact valuation ages in months, supporting interim
11//!   valuations with a partial stub latest origin.
12//! * **Stub Average Age (`stub_average_age`)** — Clark (2003), *"LDF
13//!   Curve-Fitting and Stochastic Reserving"*, CAS Fall Forum; Bloom (2015),
14//!   *"Interpolation and Extrapolation of Loss Development Factors for Interim
15//!   Valuations"*: computes the effective average claim age for complete or
16//!   incomplete/stub origin periods under uniform or custom exposure profiles.
17//! * **Calendar Diagonal Alignment (`calendar_diagonal_index`)** — Shapland
18//!   (2016), *Using the ODP Bootstrap Model: A Practitioner's Guide*, CAS
19//!   Monograph No. 4: maps cells on non-square grids to their true calendar
20//!   valuation diagonals so calendar-effect diagnostics and ODP bootstrap
21//!   residuals align across asymmetric triangles.
22
23use serde::Deserialize;
24
25use crate::validate::ValidationError;
26
27/// Deserialize a `Vec<f64>` where JSON `null` values map back to `f64::NAN`
28/// (enabling lossless `serde_json` roundtrips for grids containing `NaN` sentinels).
29fn deserialize_vec_f64_null_as_nan<'de, D>(deserializer: D) -> Result<Vec<f64>, D::Error>
30where
31    D: serde::Deserializer<'de>,
32{
33    let opts: Vec<Option<f64>> = Vec::deserialize(deserializer)?;
34    Ok(opts.into_iter().map(|v| v.unwrap_or(f64::NAN)).collect())
35}
36
37/// Exact age and observation geometry for an asymmetric (rectangular) loss
38/// development triangle.
39#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
40pub struct AsymmetricAgeGrid {
41    /// Number of origin (accident / policy) periods.
42    pub n_origins: usize,
43    /// Number of development columns.
44    pub n_devs: usize,
45    /// Length of a full origin period in months (e.g., `12.0` for annual).
46    pub origin_months: f64,
47    /// Step between consecutive development columns in months (e.g., `6.0`, `3.0`, `1.0`).
48    pub dev_months: f64,
49    /// Stride ratio `origin_months / dev_months` (e.g., `2.0`, `4.0`, `12.0`).
50    pub stride_ratio: f64,
51    /// Valuation age (in months from origin start) of each development column
52    /// (length `n_devs`).
53    pub dev_ages_months: Vec<f64>,
54    /// Start month of each origin period relative to origin 0 (`i * origin_months`).
55    pub origin_start_months: Vec<f64>,
56    /// Earned exposure duration in months for each origin period at the
57    /// valuation date (`origin_months` for full origins, `< origin_months` for
58    /// a partial stub origin).
59    pub origin_durations_months: Vec<f64>,
60    /// Valuation date in months measured from the start of origin 0.
61    pub valuation_month: f64,
62    /// Number of observed development columns for each origin row (length `n_origins`).
63    pub observed_counts: Vec<usize>,
64    /// Row-major (`n_origins * n_devs`) exact valuation age in months from
65    /// origin start for each cell (`NaN` for unobserved cells).
66    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
67    pub cell_ages_months: Vec<f64>,
68    /// Row-major (`n_origins * n_devs`) effective average claim age in months
69    /// (accounting for uniform exposure over the origin's earned duration; `NaN`
70    /// for unobserved cells).
71    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
72    pub cell_average_ages_months: Vec<f64>,
73}
74
75impl AsymmetricAgeGrid {
76    /// Valuation age in months at `(origin, dev)`, or `NaN` if unobserved.
77    #[inline]
78    pub fn cell_age(&self, origin: usize, dev: usize) -> f64 {
79        self.cell_ages_months[origin * self.n_devs + dev]
80    }
81
82    /// Effective average claim age in months at `(origin, dev)`, or `NaN` if unobserved.
83    #[inline]
84    pub fn cell_average_age(&self, origin: usize, dev: usize) -> f64 {
85        self.cell_average_ages_months[origin * self.n_devs + dev]
86    }
87
88    /// `true` iff cell `(origin, dev)` is observed at the grid's valuation date.
89    #[inline]
90    pub fn is_observed(&self, origin: usize, dev: usize) -> bool {
91        origin < self.n_origins && dev < self.observed_counts[origin]
92    }
93
94    /// Latest observed development column index for each origin (`observed_counts[i] - 1`).
95    pub fn latest_dev_indices(&self) -> Vec<usize> {
96        self.observed_counts
97            .iter()
98            .map(|&c| c.saturating_sub(1))
99            .collect()
100    }
101
102    /// Exact valuation age in months of the latest observed cell for each origin.
103    pub fn latest_ages_months(&self) -> Vec<f64> {
104        (0..self.n_origins)
105            .map(|i| {
106                let c = self.observed_counts[i];
107                if c == 0 {
108                    f64::NAN
109                } else {
110                    self.cell_ages_months[i * self.n_devs + (c - 1)]
111                }
112            })
113            .collect()
114    }
115
116    /// Earned exposure fraction `origin_durations_months[i] / origin_months` for each origin.
117    pub fn exposure_fractions(&self) -> Vec<f64> {
118        self.origin_durations_months
119            .iter()
120            .map(|&d| d / self.origin_months)
121            .collect()
122    }
123}
124
125/// Build an [`AsymmetricAgeGrid`] mapping `(origin_idx, dev_idx)` on non-square
126/// grids to exact valuation ages and effective average claim ages in months
127/// (Friedland 2010).
128///
129/// # Parameters
130/// * `n_origins` — number of origin periods (`>= 1`).
131/// * `n_devs` — number of development columns (`>= 1`).
132/// * `origin_months` — full length of one origin period in months (e.g., `12.0`).
133/// * `dev_months` — step between adjacent development columns in months (e.g., `6.0`, `3.0`, `1.0`).
134/// * `first_dev_age_months` — valuation age in months of column `0` (typically `dev_months`).
135/// * `stub_months` — optional duration in months of the most recent origin at the
136///   valuation date (`0 < stub_months <= origin_months`). When `None`, the most
137///   recent origin is valued at `origin_months` (or `first_dev_age_months` if
138///   `n_origins == 1` and `n_devs == 1`). When `Some(s)`, the valuation date is
139///   set to `(n_origins - 1) * origin_months + s`, creating an interim valuation
140///   where origin `n_origins - 1` is an `s`-month stub.
141pub fn asymmetric_age_grid(
142    n_origins: usize,
143    n_devs: usize,
144    origin_months: f64,
145    dev_months: f64,
146    first_dev_age_months: f64,
147    stub_months: Option<f64>,
148) -> Result<AsymmetricAgeGrid, ValidationError> {
149    if n_origins == 0 || n_devs == 0 {
150        return Err(ValidationError::ShapeMismatch);
151    }
152    if !origin_months.is_finite() || !dev_months.is_finite() || !first_dev_age_months.is_finite() {
153        return Err(ValidationError::NotFinite);
154    }
155    if origin_months <= 0.0 || dev_months <= 0.0 || first_dev_age_months <= 0.0 {
156        return Err(ValidationError::InvalidParameter(
157            "origin_months, dev_months, and first_dev_age_months must be positive",
158        ));
159    }
160    let latest_duration = match stub_months {
161        Some(s) => {
162            if !s.is_finite() {
163                return Err(ValidationError::NotFinite);
164            }
165            if s <= 0.0 || s > origin_months + 1e-9 {
166                return Err(ValidationError::InvalidParameter(
167                    "stub_months must be in (0, origin_months]",
168                ));
169            }
170            s.min(origin_months)
171        }
172        None => origin_months,
173    };
174
175    let stride_ratio = origin_months / dev_months;
176    let dev_ages_months: Vec<f64> = (0..n_devs)
177        .map(|j| first_dev_age_months + (j as f64) * dev_months)
178        .collect();
179    let origin_start_months: Vec<f64> =
180        (0..n_origins).map(|i| (i as f64) * origin_months).collect();
181    let valuation_month = ((n_origins - 1) as f64) * origin_months + latest_duration;
182
183    let mut origin_durations_months = Vec::with_capacity(n_origins);
184    let mut observed_counts = Vec::with_capacity(n_origins);
185    let mut cell_ages_months = vec![f64::NAN; n_origins * n_devs];
186    let mut cell_average_ages_months = vec![f64::NAN; n_origins * n_devs];
187
188    let tol = 1e-9 * origin_months.max(dev_months).max(1.0);
189    for i in 0..n_origins {
190        let max_age_i = valuation_month - origin_start_months[i];
191        let dur_i = max_age_i.min(origin_months).max(0.0);
192        origin_durations_months.push(dur_i);
193
194        let mut count = 0usize;
195        for j in 0..n_devs {
196            let age = dev_ages_months[j];
197            if age <= max_age_i + tol {
198                cell_ages_months[i * n_devs + j] = age;
199                cell_average_ages_months[i * n_devs + j] = stub_average_age(age, dur_i)?;
200                count += 1;
201            }
202        }
203        observed_counts.push(count);
204    }
205
206    Ok(AsymmetricAgeGrid {
207        n_origins,
208        n_devs,
209        origin_months,
210        dev_months,
211        stride_ratio,
212        dev_ages_months,
213        origin_start_months,
214        origin_durations_months,
215        valuation_month,
216        observed_counts,
217        cell_ages_months,
218        cell_average_ages_months,
219    })
220}
221
222/// Compute the effective average claim age (in months) for a complete or
223/// incomplete/stub origin period under uniform exposure (Clark 2003; Bloom 2015).
224///
225/// For an origin period with earned exposure over `[0, d]` where
226/// `d = min(valuation_age_months, origin_duration_months)`, the average accident
227/// date under uniform exposure is `d / 2`, giving an effective average claim age
228/// of:
229///
230/// ```text
231/// avg_age = valuation_age_months - 0.5 * min(valuation_age_months, origin_duration_months)
232/// ```
233///
234/// Examples:
235/// * A 6-month stub valued at 6 months (`valuation_age = 6`, `origin_duration = 6` or `12`)
236///   has average claim age `3.0` months.
237/// * A full 12-month accident year valued at 12 months has average claim age `6.0` months.
238/// * A full 12-month accident year valued at 18 months (interim 6m valuation) has
239///   average claim age `12.0` months.
240pub fn stub_average_age(
241    valuation_age_months: f64,
242    origin_duration_months: f64,
243) -> Result<f64, ValidationError> {
244    if !valuation_age_months.is_finite() || !origin_duration_months.is_finite() {
245        return Err(ValidationError::NotFinite);
246    }
247    if valuation_age_months <= 0.0 || origin_duration_months <= 0.0 {
248        return Err(ValidationError::InvalidParameter(
249            "valuation_age_months and origin_duration_months must be positive",
250        ));
251    }
252    let effective_duration = valuation_age_months.min(origin_duration_months);
253    Ok(valuation_age_months - 0.5 * effective_duration)
254}
255
256/// Compute the effective average claim age (in months) under a non-uniform
257/// piecewise-constant sub-period exposure profile (e.g., seasonal monthly weights).
258///
259/// `exposure_weights` gives non-negative exposure weights over consecutive equal
260/// slices of width `slice_months` starting at month `0`. Only exposure earned up
261/// to `valuation_age_months` contributes (partial last slice is pro-rated linearly).
262pub fn stub_average_age_weighted(
263    valuation_age_months: f64,
264    slice_months: f64,
265    exposure_weights: &[f64],
266) -> Result<f64, ValidationError> {
267    if !valuation_age_months.is_finite() || !slice_months.is_finite() {
268        return Err(ValidationError::NotFinite);
269    }
270    if valuation_age_months <= 0.0 || slice_months <= 0.0 {
271        return Err(ValidationError::InvalidParameter(
272            "valuation_age_months and slice_months must be positive",
273        ));
274    }
275    if exposure_weights.is_empty() {
276        return Err(ValidationError::ShapeMismatch);
277    }
278
279    let mut weighted_accident_time = 0.0;
280    let mut total_weight = 0.0;
281    for (k, &w) in exposure_weights.iter().enumerate() {
282        if !w.is_finite() {
283            return Err(ValidationError::NotFinite);
284        }
285        if w < 0.0 {
286            return Err(ValidationError::Negative);
287        }
288        let t_start = (k as f64) * slice_months;
289        if t_start >= valuation_age_months {
290            break;
291        }
292        let t_end = ((k + 1) as f64 * slice_months).min(valuation_age_months);
293        let frac = (t_end - t_start) / slice_months;
294        let eff_w = w * frac;
295        let mid_t = f64::midpoint(t_start, t_end);
296        weighted_accident_time += eff_w * mid_t;
297        total_weight += eff_w;
298    }
299
300    if total_weight <= 0.0 {
301        return Err(ValidationError::DivideByZero("exposure_weights"));
302    }
303    let avg_accident_time = weighted_accident_time / total_weight;
304    Ok(valuation_age_months - avg_accident_time)
305}
306
307/// Calendar-diagonal metadata for a single observed cell `(origin, dev)`.
308#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
309pub struct CalendarDiagonalCell {
310    /// Origin period index.
311    pub origin: usize,
312    /// Development column index.
313    pub dev: usize,
314    /// Exact calendar valuation time in months from origin 0 start.
315    pub calendar_month: f64,
316    /// Chronological diagonal bucket index (`0..n_diagonals`).
317    pub diagonal_index: usize,
318    /// Calendar major-period (e.g., calendar year) index `floor((calendar_month - eps) / origin_months)`.
319    pub calendar_period_index: usize,
320}
321
322/// Complete calendar-diagonal mapping across an asymmetric triangle (Shapland 2016).
323#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
324pub struct CalendarDiagonalMap {
325    /// Number of origin periods.
326    pub n_origins: usize,
327    /// Number of development columns.
328    pub n_devs: usize,
329    /// Distinct sorted calendar valuation months for each diagonal bucket.
330    pub diagonal_months: Vec<f64>,
331    /// Row-major (`n_origins * n_devs`) diagonal bucket index (`None` for unobserved cells).
332    pub cell_diagonal: Vec<Option<usize>>,
333    /// Row-major (`n_origins * n_devs`) exact calendar valuation month (`NaN` for unobserved cells).
334    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
335    pub cell_calendar_months: Vec<f64>,
336    /// Cells grouped by chronological diagonal bucket (`diagonals[d]` lists all
337    /// observed cells valued at `diagonal_months[d]`).
338    pub diagonals: Vec<Vec<CalendarDiagonalCell>>,
339}
340
341impl CalendarDiagonalMap {
342    /// Number of distinct observed calendar diagonals.
343    #[inline]
344    pub fn n_diagonals(&self) -> usize {
345        self.diagonal_months.len()
346    }
347
348    /// Diagonal bucket index for cell `(origin, dev)`, if observed.
349    #[inline]
350    pub fn diagonal_of(&self, origin: usize, dev: usize) -> Option<usize> {
351        self.cell_diagonal[origin * self.n_devs + dev]
352    }
353}
354
355/// Align calendar-year / valuation-period diagonals across an asymmetric
356/// [`AsymmetricAgeGrid`] (Shapland 2016).
357///
358/// Unlike square triangles where calendar diagonals follow `origin + dev`, an
359/// asymmetric grid with stride ratio `s = origin_months / dev_months` aligns
360/// cells with equal `origin_start_months[i] + dev_ages_months[j]` (e.g., on an
361/// annual × semiannual grid, `(0, 2)` and `(1, 0)` share calendar month `18.0`).
362pub fn calendar_diagonal_index(
363    grid: &AsymmetricAgeGrid,
364) -> Result<CalendarDiagonalMap, ValidationError> {
365    if grid.n_origins == 0 || grid.n_devs == 0 {
366        return Err(ValidationError::ShapeMismatch);
367    }
368    let tol = 1e-6 * grid.dev_months.max(1.0);
369
370    // Collect all observed (origin, dev, calendar_month) triples.
371    let mut observed: Vec<(usize, usize, f64)> = Vec::new();
372    for i in 0..grid.n_origins {
373        let count = grid.observed_counts[i].min(grid.n_devs);
374        for j in 0..count {
375            let age = grid.cell_ages_months[i * grid.n_devs + j];
376            if age.is_finite() {
377                let cal_m = grid.origin_start_months[i] + age;
378                observed.push((i, j, cal_m));
379            }
380        }
381    }
382
383    // Extract distinct sorted calendar valuation months within tolerance.
384    let mut sorted_months: Vec<f64> = observed.iter().map(|&(_, _, m)| m).collect();
385    sorted_months.sort_by(f64::total_cmp);
386    let mut diagonal_months: Vec<f64> = Vec::new();
387    for m in sorted_months {
388        match diagonal_months.last() {
389            Some(&prev) if (m - prev).abs() <= tol => {}
390            _ => diagonal_months.push(m),
391        }
392    }
393
394    let n_diag = diagonal_months.len();
395    let mut cell_diagonal = vec![None; grid.n_origins * grid.n_devs];
396    let mut cell_calendar_months = vec![f64::NAN; grid.n_origins * grid.n_devs];
397    let mut diagonals: Vec<Vec<CalendarDiagonalCell>> = vec![Vec::new(); n_diag];
398
399    for (origin, dev, cal_m) in observed {
400        // Find matching diagonal bucket.
401        let diag_idx = diagonal_months
402            .iter()
403            .position(|&dm| (dm - cal_m).abs() <= tol)
404            .expect("calendar month must match a bucket");
405        let cal_period = ((cal_m - 1e-9).max(0.0) / grid.origin_months).floor() as usize;
406
407        let flat = origin * grid.n_devs + dev;
408        cell_diagonal[flat] = Some(diag_idx);
409        cell_calendar_months[flat] = cal_m;
410        diagonals[diag_idx].push(CalendarDiagonalCell {
411            origin,
412            dev,
413            calendar_month: cal_m,
414            diagonal_index: diag_idx,
415            calendar_period_index: cal_period,
416        });
417    }
418
419    Ok(CalendarDiagonalMap {
420        n_origins: grid.n_origins,
421        n_devs: grid.n_devs,
422        diagonal_months,
423        cell_diagonal,
424        cell_calendar_months,
425        diagonals,
426    })
427}
428
429/// Summary of mean residuals grouped by true calendar diagonal on an asymmetric grid.
430#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
431pub struct AsymmetricCalendarDiagnostics {
432    /// Calendar valuation month for each diagonal bucket.
433    pub diagonal_months: Vec<f64>,
434    /// Mean residual on each calendar diagonal (`NaN` if no finite residuals on that diagonal).
435    #[serde(deserialize_with = "deserialize_vec_f64_null_as_nan")]
436    pub diagonal_means: Vec<f64>,
437    /// Count of finite residuals on each calendar diagonal.
438    pub diagonal_counts: Vec<usize>,
439    /// Diagonal bucket index with the largest absolute mean residual.
440    pub strongest_diagonal: Option<usize>,
441    /// Root-mean-square diagonal bias across populated diagonals.
442    pub rms_diagonal_bias: f64,
443}
444
445/// Aggregate a row-major residual grid (`n_origins * n_devs`, `NaN` for excluded/unobserved)
446/// along the true asymmetric calendar diagonals from [`calendar_diagonal_index`].
447pub fn diagnose_asymmetric_calendar_effects(
448    map: &CalendarDiagonalMap,
449    residuals: &[f64],
450) -> Result<AsymmetricCalendarDiagnostics, ValidationError> {
451    if residuals.len() != map.n_origins * map.n_devs {
452        return Err(ValidationError::ShapeMismatch);
453    }
454    let n_diag = map.n_diagonals();
455    let mut diagonal_means = Vec::with_capacity(n_diag);
456    let mut diagonal_counts = Vec::with_capacity(n_diag);
457
458    for bucket in &map.diagonals {
459        let mut sum = 0.0;
460        let mut cnt = 0usize;
461        for cell in bucket {
462            let r = residuals[cell.origin * map.n_devs + cell.dev];
463            if r.is_finite() {
464                sum += r;
465                cnt += 1;
466            }
467        }
468        diagonal_counts.push(cnt);
469        diagonal_means.push(if cnt > 0 { sum / cnt as f64 } else { f64::NAN });
470    }
471
472    let strongest_diagonal = diagonal_means
473        .iter()
474        .enumerate()
475        .filter(|(_, v)| v.is_finite())
476        .max_by(|(_, a), (_, b)| a.abs().total_cmp(&b.abs()))
477        .map(|(idx, _)| idx);
478
479    let mut sq_sum = 0.0;
480    let mut finite_cnt = 0usize;
481    for &m in &diagonal_means {
482        if m.is_finite() {
483            sq_sum += m * m;
484            finite_cnt += 1;
485        }
486    }
487    let rms_diagonal_bias = if finite_cnt > 0 {
488        (sq_sum / finite_cnt as f64).sqrt()
489    } else {
490        0.0
491    };
492
493    Ok(AsymmetricCalendarDiagnostics {
494        diagonal_months: map.diagonal_months.clone(),
495        diagonal_means,
496        diagonal_counts,
497        strongest_diagonal,
498        rms_diagonal_bias,
499    })
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505
506    #[test]
507    fn annual_by_semiannual_grid_with_6m_stub() {
508        // 4 annual origins × 8 semiannual devs, valued at 6 months into AY 3 (month 42).
509        let grid = asymmetric_age_grid(4, 8, 12.0, 6.0, 6.0, Some(6.0)).expect("grid");
510        assert!((grid.stride_ratio - 2.0).abs() < 1e-12);
511        assert_eq!(grid.observed_counts, vec![7, 5, 3, 1]);
512        assert!((grid.valuation_month - 42.0).abs() < 1e-12);
513        // Latest origin is a 6m stub -> age 6m, avg claim age 3m.
514        assert!((grid.cell_age(3, 0) - 6.0).abs() < 1e-12);
515        assert!((grid.cell_average_age(3, 0) - 3.0).abs() < 1e-12);
516        // AY 2 at latest valuation (18m) -> full 12m origin -> avg claim age 12m.
517        assert!((grid.cell_age(2, 2) - 18.0).abs() < 1e-12);
518        assert!((grid.cell_average_age(2, 2) - 12.0).abs() < 1e-12);
519    }
520
521    #[test]
522    fn calendar_diagonals_align_stride_2_to_1() {
523        let grid = asymmetric_age_grid(3, 6, 12.0, 6.0, 6.0, None).expect("grid");
524        let map = calendar_diagonal_index(&grid).expect("cal map");
525        // AY 0 at 18m (dev 2) and AY 1 at 6m (dev 0) are both valued at calendar month 18.
526        assert_eq!(map.diagonal_of(0, 2), map.diagonal_of(1, 0));
527        // AY 0 at 30m (dev 4), AY 1 at 18m (dev 2), AY 2 at 6m (dev 0) share month 30.
528        assert_eq!(map.diagonal_of(0, 4), map.diagonal_of(1, 2));
529        assert_eq!(map.diagonal_of(1, 2), map.diagonal_of(2, 0));
530    }
531
532    #[test]
533    fn stub_average_age_uniform_and_weighted() {
534        assert!((stub_average_age(6.0, 6.0).unwrap() - 3.0).abs() < 1e-12);
535        assert!((stub_average_age(6.0, 12.0).unwrap() - 3.0).abs() < 1e-12);
536        assert!((stub_average_age(12.0, 12.0).unwrap() - 6.0).abs() < 1e-12);
537        assert!((stub_average_age(18.0, 12.0).unwrap() - 12.0).abs() < 1e-12);
538
539        // Uniform weights across 6 monthly slices should match uniform stub_average_age(6, 6) = 3.0.
540        let w = [1.0; 6];
541        let avg = stub_average_age_weighted(6.0, 1.0, &w).unwrap();
542        assert!((avg - 3.0).abs() < 1e-12);
543    }
544}