Skip to main content

reserving_kernels/subannual/
interp.rs

1//! Sub-annual LDF and CDF interpolation kernels.
2//!
3//! Converts annual (or arbitrary strictly increasing) maturity anchor nodes
4//! `(anchor_ages, anchor_cdfs)` into smooth sub-annual CDFs, percent reported,
5//! and implied sub-period LDFs:
6//!
7//! * [`interp_linear_cdf`] — direct piecewise-linear CDF interpolation.
8//! * [`interp_linear_pct_reported`] — piecewise-linear percent-reported
9//!   (`1 / CDF`) interpolation, avoiding convexity bias.
10//! * [`interp_exponential`] — constant-rate geometric interpolation (Bloom 2015),
11//!   preserving exact multiplicative LDF parity.
12//! * [`interp_inverse_power`] — Sherman (1984) inverse power curve
13//!   `f(t) - 1 = a · t^{-b}` integrated over sub-annual intervals.
14//! * [`interp_swimon`] — Robbin (2018) smooth, monotonic, concavity-preserving
15//!   interpolation designed to eliminate sawtooth oscillations in expected IBNR runoff.
16//! * [`interp_spliced_weibull`] — Robbin (2018) piecewise Weibull curve spliced
17//!   across annual knots.
18//! * [`interp_ivf12`] — Robbin (2018) Interpolated Volume Factor (12-month basis)
19//!   method preserving exact 12-month factor parity with smooth emergence.
20
21use crate::validate::{ValidationError, validate_positive_finite_slice};
22
23/// Sub-annual CDF/LDF interpolation method selector.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
25pub enum SubannualInterpMethod {
26    /// Piecewise-linear interpolation of CDFs.
27    LinearCdf,
28    /// Piecewise-linear interpolation of percent reported (`1 / CDF`).
29    LinearPctReported,
30    /// Constant-rate geometric interpolation (`CDF(t) = CDF_0^(1-w) * CDF_1^w`).
31    Exponential,
32    /// Sherman (1984) inverse power curve `f(t) - 1 = a * t^{-b}`.
33    InversePower,
34    /// Robbin (2018) smooth monotonic interpolation (eliminates IBNR sawtooth).
35    Swimon,
36    /// Robbin (2018) piecewise Weibull spliced across annual knots.
37    SplicedWeibull,
38    /// Robbin (2018) Interpolated Volume Factor (12-month basis).
39    Ivf12,
40}
41
42/// Interpolated sub-annual development pattern evaluated at `target_ages`.
43#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
44pub struct InterpolatedPattern {
45    /// Interpolation method used.
46    pub method: SubannualInterpMethod,
47    /// Evaluation ages in months (same order as caller's `target_ages`).
48    pub ages_months: Vec<f64>,
49    /// Interpolated cumulative development factors `CDF(t)`.
50    pub cdfs: Vec<f64>,
51    /// Implied percent reported `1 / CDF(t)`.
52    pub pct_reported: Vec<f64>,
53    /// Implied step-to-step LDFs `CDF(t_k) / CDF(t_{k+1})` (length `target_ages.len() - 1`).
54    pub ldfs: Vec<f64>,
55}
56
57/// Result of Sherman (1984) inverse-power sub-annual interpolation, including
58/// the fitted curve parameters `f(t) - 1 = a · t^{-b}`.
59#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
60pub struct InversePowerInterpResult {
61    /// Evaluated sub-annual pattern (`cdfs`, `pct_reported`, `ldfs`).
62    pub pattern: InterpolatedPattern,
63    /// Scale parameter `a > 0` in `f(t) - 1 = a · t^{-b}`.
64    pub a: f64,
65    /// Decay exponent `b > 0` in `f(t) - 1 = a · t^{-b}`.
66    pub b: f64,
67    /// Coefficient of determination `R²` of the log-linear fit `ln(f_k - 1) = ln(a) - b ln(t_k)`.
68    pub r_squared: f64,
69}
70
71/// Dispatch to any of the 7 sub-annual interpolation kernels via [`SubannualInterpMethod`].
72pub fn interpolate_pattern(
73    method: SubannualInterpMethod,
74    anchor_ages: &[f64],
75    anchor_cdfs: &[f64],
76    target_ages: &[f64],
77) -> Result<InterpolatedPattern, ValidationError> {
78    match method {
79        SubannualInterpMethod::LinearCdf => {
80            interp_linear_cdf(anchor_ages, anchor_cdfs, target_ages)
81        }
82        SubannualInterpMethod::LinearPctReported => {
83            interp_linear_pct_reported(anchor_ages, anchor_cdfs, target_ages)
84        }
85        SubannualInterpMethod::Exponential => {
86            interp_exponential(anchor_ages, anchor_cdfs, target_ages)
87        }
88        SubannualInterpMethod::InversePower => {
89            Ok(interp_inverse_power(anchor_ages, anchor_cdfs, target_ages)?.pattern)
90        }
91        SubannualInterpMethod::Swimon => interp_swimon(anchor_ages, anchor_cdfs, target_ages),
92        SubannualInterpMethod::SplicedWeibull => {
93            interp_spliced_weibull(anchor_ages, anchor_cdfs, target_ages)
94        }
95        SubannualInterpMethod::Ivf12 => interp_ivf12(anchor_ages, anchor_cdfs, target_ages),
96    }
97}
98
99fn validate_anchors_and_targets(
100    anchor_ages: &[f64],
101    anchor_cdfs: &[f64],
102    target_ages: &[f64],
103) -> Result<(), ValidationError> {
104    if anchor_ages.len() < 2 || anchor_ages.len() != anchor_cdfs.len() || target_ages.is_empty() {
105        return Err(ValidationError::ShapeMismatch);
106    }
107    validate_positive_finite_slice(anchor_ages, "anchor_ages")?;
108    validate_positive_finite_slice(anchor_cdfs, "anchor_cdfs")?;
109    validate_positive_finite_slice(target_ages, "target_ages")?;
110    for k in 1..anchor_ages.len() {
111        if anchor_ages[k] <= anchor_ages[k - 1] {
112            return Err(ValidationError::InvalidParameter(
113                "anchor_ages must be strictly increasing",
114            ));
115        }
116    }
117    Ok(())
118}
119
120fn build_pattern(
121    method: SubannualInterpMethod,
122    target_ages: &[f64],
123    cdfs: Vec<f64>,
124) -> InterpolatedPattern {
125    let pct_reported: Vec<f64> = cdfs.iter().map(|&c| 1.0 / c).collect();
126    let mut ldfs = Vec::with_capacity(cdfs.len().saturating_sub(1));
127    for k in 0..cdfs.len().saturating_sub(1) {
128        ldfs.push(cdfs[k] / cdfs[k + 1]);
129    }
130    InterpolatedPattern {
131        method,
132        ages_months: target_ages.to_vec(),
133        cdfs,
134        pct_reported,
135        ldfs,
136    }
137}
138
139/// Find bracket index `k` such that `ages[k] <= t <= ages[k + 1]`.
140/// Assumes `ages[0] <= t <= ages[m - 1]`.
141#[inline]
142fn find_bracket(ages: &[f64], t: f64) -> usize {
143    let m = ages.len();
144    let pos = ages.partition_point(|&a| a < t);
145    if pos == 0 {
146        0
147    } else if pos >= m {
148        m - 2
149    } else if (ages[pos] - t).abs() <= 1e-12 * t.max(1.0) && pos + 1 < m {
150        pos
151    } else {
152        pos - 1
153    }
154}
155
156// ===========================================================================
157// 1. Linear CDF
158// ===========================================================================
159
160/// Linearly interpolate CDFs between adjacent anchor maturities:
161/// `CDF(t) = (1 - w) * CDF(t_k) + w * CDF(t_{k+1})`.
162///
163/// Requires `target_ages` within `[anchor_ages[0], anchor_ages[last]]`.
164pub fn interp_linear_cdf(
165    anchor_ages: &[f64],
166    anchor_cdfs: &[f64],
167    target_ages: &[f64],
168) -> Result<InterpolatedPattern, ValidationError> {
169    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
170    let t_min = anchor_ages[0];
171    let t_max = *anchor_ages.last().expect("len >= 2");
172    let tol = 1e-9 * t_max;
173
174    let mut cdfs = Vec::with_capacity(target_ages.len());
175    for &t in target_ages {
176        if t < t_min - tol || t > t_max + tol {
177            return Err(ValidationError::InvalidParameter(
178                "target age outside [anchor_ages[0], anchor_ages[last]] for linear CDF interpolation",
179            ));
180        }
181        let tc = t.clamp(t_min, t_max);
182        let k = find_bracket(anchor_ages, tc);
183        let w = (tc - anchor_ages[k]) / (anchor_ages[k + 1] - anchor_ages[k]);
184        let cdf = (1.0 - w) * anchor_cdfs[k] + w * anchor_cdfs[k + 1];
185        cdfs.push(cdf);
186    }
187    Ok(build_pattern(
188        SubannualInterpMethod::LinearCdf,
189        target_ages,
190        cdfs,
191    ))
192}
193
194// ===========================================================================
195// 2. Linear Percent Reported (1 / CDF)
196// ===========================================================================
197
198/// Linearly interpolate percent reported `p(t) = 1 / CDF(t)` between adjacent
199/// anchor nodes, then invert back to `CDF(t) = 1 / p(t)`.
200///
201/// Avoids the convexity bias of direct linear CDF interpolation. For ages in
202/// `(0, anchor_ages[0])`, interpolates linearly from the origin `(0, p(0) = 0)`.
203pub fn interp_linear_pct_reported(
204    anchor_ages: &[f64],
205    anchor_cdfs: &[f64],
206    target_ages: &[f64],
207) -> Result<InterpolatedPattern, ValidationError> {
208    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
209    let t_max = *anchor_ages.last().expect("len >= 2");
210    let tol = 1e-9 * t_max;
211
212    let mut cdfs = Vec::with_capacity(target_ages.len());
213    for &t in target_ages {
214        if t > t_max + tol {
215            return Err(ValidationError::InvalidParameter(
216                "target age exceeds maximum anchor age",
217            ));
218        }
219        let tc = t.min(t_max);
220        let p = if tc < anchor_ages[0] {
221            (tc / anchor_ages[0]) * (1.0 / anchor_cdfs[0])
222        } else {
223            let k = find_bracket(anchor_ages, tc);
224            let w = (tc - anchor_ages[k]) / (anchor_ages[k + 1] - anchor_ages[k]);
225            let p0 = 1.0 / anchor_cdfs[k];
226            let p1 = 1.0 / anchor_cdfs[k + 1];
227            (1.0 - w) * p0 + w * p1
228        };
229        if !(p > 0.0) || !p.is_finite() {
230            return Err(ValidationError::DivideByZero("percent reported"));
231        }
232        cdfs.push(1.0 / p);
233    }
234    Ok(build_pattern(
235        SubannualInterpMethod::LinearPctReported,
236        target_ages,
237        cdfs,
238    ))
239}
240
241// ===========================================================================
242// 3. Exponential / Geometric CDF (Bloom 2015)
243// ===========================================================================
244
245/// Constant-rate geometric CDF interpolation (Bloom 2015):
246/// `CDF(t) = CDF(t_k)^(1 - w) * CDF(t_{k+1})^w`.
247///
248/// Ensures that sub-period LDFs within each interval are constant and multiply
249/// cleanly back to the exact anchor-to-anchor LDF.
250pub fn interp_exponential(
251    anchor_ages: &[f64],
252    anchor_cdfs: &[f64],
253    target_ages: &[f64],
254) -> Result<InterpolatedPattern, ValidationError> {
255    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
256    let t_min = anchor_ages[0];
257    let t_max = *anchor_ages.last().expect("len >= 2");
258    let tol = 1e-9 * t_max;
259
260    let mut cdfs = Vec::with_capacity(target_ages.len());
261    for &t in target_ages {
262        if t < t_min - tol || t > t_max + tol {
263            return Err(ValidationError::InvalidParameter(
264                "target age outside [anchor_ages[0], anchor_ages[last]] for exponential interpolation",
265            ));
266        }
267        let tc = t.clamp(t_min, t_max);
268        let k = find_bracket(anchor_ages, tc);
269        let w = (tc - anchor_ages[k]) / (anchor_ages[k + 1] - anchor_ages[k]);
270        let ln_cdf = (1.0 - w) * anchor_cdfs[k].ln() + w * anchor_cdfs[k + 1].ln();
271        cdfs.push(ln_cdf.exp());
272    }
273    Ok(build_pattern(
274        SubannualInterpMethod::Exponential,
275        target_ages,
276        cdfs,
277    ))
278}
279
280// ===========================================================================
281// 4. Sherman (1984) Inverse Power Curve
282// ===========================================================================
283
284/// 8-point Gauss–Legendre quadrature nodes and weights on `[-1, 1]`.
285const GL8_NODES: [f64; 8] = [
286    -0.960_289_856_497_536_3,
287    -0.796_666_477_413_626_7,
288    -0.525_532_409_916_329,
289    -0.183_434_642_495_649_8,
290    0.183_434_642_495_649_8,
291    0.525_532_409_916_329,
292    0.796_666_477_413_626_7,
293    0.960_289_856_497_536_3,
294];
295const GL8_WEIGHTS: [f64; 8] = [
296    0.101_228_536_290_376_26,
297    0.222_381_034_453_374_47,
298    0.313_706_645_877_887_3,
299    0.362_683_783_378_362,
300    0.362_683_783_378_362,
301    0.313_706_645_877_887_3,
302    0.222_381_034_453_374_47,
303    0.101_228_536_290_376_26,
304];
305
306/// Integrate `ln(1 + a * u^{-b})` over `[lo, hi]` (`0 < lo <= hi`) via 8-point Gauss–Legendre.
307fn integrate_sherman_log_rate(lo: f64, hi: f64, a: f64, b: f64) -> f64 {
308    if hi <= lo {
309        return 0.0;
310    }
311    let mid = 0.5 * (lo + hi);
312    let half = 0.5 * (hi - lo);
313    let mut acc = 0.0;
314    for (&node, &weight) in GL8_NODES.iter().zip(GL8_WEIGHTS.iter()) {
315        let u = mid + half * node;
316        let val = (a * u.powf(-b)).ln_1p();
317        acc += weight * val;
318    }
319    half * acc
320}
321
322/// Fit Sherman (1984) inverse power curve `f(t) - 1 = a · t^{-b}` across annual
323/// nodes and evaluate smooth sub-annual LDFs and CDFs at arbitrary ages `t > 0`.
324///
325/// The continuous log-development rate `λ(u) ∝ ln(1 + a · u^{-b})` is integrated
326/// over each anchor interval `[t_k, t_{k+1}]` and normalized to preserve exact
327/// anchor CDFs at every knot (ensuring exact sub-annual product parity) while
328/// front-loading emergence realistically within each period. For target ages
329/// outside `[t_0, t_{m-1}]`, the fitted curve extrapolates smoothly via the
330/// unnormalized integral scaled by the adjacent anchor step width.
331pub fn interp_inverse_power(
332    anchor_ages: &[f64],
333    anchor_cdfs: &[f64],
334    target_ages: &[f64],
335) -> Result<InversePowerInterpResult, ValidationError> {
336    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
337
338    // Collect (ln t_k, ln(f_k - 1)) for annual links where f_k = CDF_k / CDF_{k+1} > 1.
339    let mut xs = Vec::new();
340    let mut ys = Vec::new();
341    for k in 0..(anchor_ages.len() - 1) {
342        let f_k = anchor_cdfs[k] / anchor_cdfs[k + 1];
343        if f_k > 1.0 + 1e-12 {
344            xs.push(anchor_ages[k].ln());
345            ys.push((f_k - 1.0).ln());
346        }
347    }
348    if xs.len() < 2 {
349        return Err(ValidationError::InvalidParameter(
350            "interp_inverse_power requires at least two anchor links with LDF > 1.0",
351        ));
352    }
353
354    let n = xs.len() as f64;
355    let x_bar = xs.iter().sum::<f64>() / n;
356    let y_bar = ys.iter().sum::<f64>() / n;
357    let mut sxx = 0.0;
358    let mut sxy = 0.0;
359    let mut syy = 0.0;
360    for (&x, &y) in xs.iter().zip(ys.iter()) {
361        let dx = x - x_bar;
362        let dy = y - y_bar;
363        sxx += dx * dx;
364        sxy += dx * dy;
365        syy += dy * dy;
366    }
367    if sxx <= 0.0 {
368        return Err(ValidationError::InvalidParameter(
369            "degenerate anchor ages in inverse power fit",
370        ));
371    }
372    let slope = sxy / sxx; // = -b
373    let intercept = y_bar - slope * x_bar; // = ln(a)
374    let b = -slope;
375    let a = intercept.exp();
376    if !(a > 0.0) || !a.is_finite() || !(b > 0.0) || !b.is_finite() {
377        return Err(ValidationError::InvalidParameter(
378            "inverse power fit requires decaying development factors (b > 0)",
379        ));
380    }
381    let r_squared = if syy > 0.0 {
382        ((sxy * sxy) / (sxx * syy)).clamp(0.0, 1.0)
383    } else {
384        1.0
385    };
386
387    let t_min = anchor_ages[0];
388    let t_max = *anchor_ages.last().expect("len >= 2");
389    let first_step = anchor_ages[1] - anchor_ages[0];
390    let last_step = anchor_ages[anchor_ages.len() - 1] - anchor_ages[anchor_ages.len() - 2];
391
392    let mut cdfs = Vec::with_capacity(target_ages.len());
393    for &t in target_ages {
394        let cdf = if t < t_min {
395            let integral = integrate_sherman_log_rate(t, t_min, a, b) / first_step;
396            anchor_cdfs[0] * integral.exp()
397        } else if t > t_max {
398            let integral = integrate_sherman_log_rate(t_max, t, a, b) / last_step;
399            (*anchor_cdfs.last().expect("non-empty") * (-integral).exp()).max(1.0)
400        } else {
401            let k = find_bracket(anchor_ages, t);
402            let t0 = anchor_ages[k];
403            let t1 = anchor_ages[k + 1];
404            let full = integrate_sherman_log_rate(t0, t1, a, b);
405            let w = if full > 0.0 {
406                (integrate_sherman_log_rate(t0, t, a, b) / full).clamp(0.0, 1.0)
407            } else {
408                (t - t0) / (t1 - t0)
409            };
410            ((1.0 - w) * anchor_cdfs[k].ln() + w * anchor_cdfs[k + 1].ln()).exp()
411        };
412        cdfs.push(cdf);
413    }
414
415    Ok(InversePowerInterpResult {
416        pattern: build_pattern(SubannualInterpMethod::InversePower, target_ages, cdfs),
417        a,
418        b,
419        r_squared,
420    })
421}
422
423// ===========================================================================
424// 5. SWIMON — Smooth Monotonic Interpolation (Robbin 2018)
425// ===========================================================================
426
427/// Evaluate cubic Hermite spline on `[x0, x1]` with values `(y0, y1)` and
428/// endpoint derivatives `(m0, m1)`.
429#[inline]
430fn eval_cubic_hermite(x0: f64, x1: f64, y0: f64, y1: f64, m0: f64, m1: f64, x: f64) -> f64 {
431    let h = x1 - x0;
432    let t = ((x - x0) / h).clamp(0.0, 1.0);
433    let t2 = t * t;
434    let t3 = t2 * t;
435    let h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
436    let h10 = t3 - 2.0 * t2 + t;
437    let h01 = -2.0 * t3 + 3.0 * t2;
438    let h11 = t3 - t2;
439    h00 * y0 + h10 * h * m0 + h01 * y1 + h11 * h * m1
440}
441
442/// Robbin (2018) SWIMON — Smooth, monotonic sub-annual interpolation designed
443/// to eliminate artificial sawtooth oscillations in expected IBNR runoff.
444///
445/// Interpolates percent reported `P(t) = 1 / CDF(t)` anchored at `(0, 0)` and
446/// every annual knot `(anchor_ages[k], 1 / anchor_cdfs[k])` using a `C¹`
447/// monotonic, concavity-preserving cubic Hermite spline:
448///
449/// * Exact preservation of all annual anchor CDFs.
450/// * Continuous first derivative `P'(t) >= 0` across every annual boundary (no
451///   kinks or sawtooth jumps in incremental emergence).
452/// * When the annual emergence increments are non-increasing (concave `P`),
453///   enforces `m_k >= s_k >= m_{k+1}` and the cubic concavity condition
454///   `m_k + 2 m_{k+1} <= 3 s_k <= 2 m_k + m_{k+1}` on every interval so that
455///   `P''(t) <= 0` everywhere and sub-annual IBNR runoff is strictly monotonic!
456pub fn interp_swimon(
457    anchor_ages: &[f64],
458    anchor_cdfs: &[f64],
459    target_ages: &[f64],
460) -> Result<InterpolatedPattern, ValidationError> {
461    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
462    let t_max = *anchor_ages.last().expect("len >= 2");
463    let tol = 1e-9 * t_max;
464
465    // Prepend origin knot (0.0, 0.0) so P(t) is smoothly defined on (0, t_max].
466    let n_knots = anchor_ages.len() + 1;
467    let mut xs = Vec::with_capacity(n_knots);
468    let mut ys = Vec::with_capacity(n_knots);
469    xs.push(0.0);
470    ys.push(0.0);
471    for (&a, &c) in anchor_ages.iter().zip(anchor_cdfs.iter()) {
472        xs.push(a);
473        ys.push(1.0 / c);
474    }
475
476    // Secant slopes s[k] = (y[k+1] - y[k]) / (x[k+1] - x[k]) for k = 0..n_knots-1.
477    let n_seg = n_knots - 1;
478    let mut h = Vec::with_capacity(n_seg);
479    let mut s = Vec::with_capacity(n_seg);
480    for k in 0..n_seg {
481        let hk = xs[k + 1] - xs[k];
482        h.push(hk);
483        s.push((ys[k + 1] - ys[k]) / hk);
484    }
485
486    // Step 1: Fritsch–Butland weighted harmonic-mean interior tangents for C¹ monotonicity.
487    let mut m = vec![0.0; n_knots];
488    for k in 1..n_seg {
489        if s[k - 1] * s[k] <= 0.0 {
490            m[k] = 0.0;
491        } else {
492            let w1 = 2.0 * h[k] + h[k - 1];
493            let w2 = h[k] + 2.0 * h[k - 1];
494            m[k] = (w1 + w2) / (w1 / s[k - 1] + w2 / s[k]);
495        }
496    }
497
498    // Endpoint tangents via non-centered 3-point formula, clamped for monotonicity/concavity.
499    m[0] = ((2.0 * h[0] + h[1]) * s[0] - h[0] * s[1]) / (h[0] + h[1]);
500    if m[0] * s[0] <= 0.0 {
501        m[0] = 0.0;
502    } else if s[0] > 0.0 && m[0] > 2.0 * s[0] {
503        m[0] = 2.0 * s[0];
504    }
505
506    let last = n_seg - 1;
507    m[n_knots - 1] =
508        ((2.0 * h[last] + h[last - 1]) * s[last] - h[last] * s[last - 1]) / (h[last] + h[last - 1]);
509    if m[n_knots - 1] * s[last] <= 0.0 {
510        m[n_knots - 1] = 0.0;
511    } else if s[last] > 0.0 && m[n_knots - 1] > 2.0 * s[last] {
512        m[n_knots - 1] = 2.0 * s[last];
513    }
514
515    // Step 2: Check if secants are non-increasing (concave emergence) and enforce
516    // exact cubic concavity P''(t) <= 0 on every segment:
517    //   P''(x_k) <= 0  <=>  2 m_k + m_{k+1} >= 3 s_k
518    //   P''(x_{k+1}) <= 0  <=>  m_k + 2 m_{k+1} <= 3 s_k
519    // Combined with m_k >= s_k >= m_{k+1} >= 0, this guarantees P'(t) is
520    // monotonically non-increasing across the entire domain (zero sawtooth!).
521    let is_concave_data = s.windows(2).all(|w| w[0] >= w[1] - 1e-12 && w[1] >= -1e-12);
522    if is_concave_data {
523        // Clamp interior tangents into [s[k], s[k-1]] first.
524        for k in 1..n_seg {
525            m[k] = m[k].clamp(s[k].max(0.0), s[k - 1].max(0.0));
526        }
527        m[0] = m[0].clamp(s[0].max(0.0), (2.0 * s[0]).max(0.0));
528        m[n_knots - 1] = m[n_knots - 1].clamp(0.0, s[last].max(0.0));
529
530        // Iterative projection onto the linear concavity inequalities (converges in a few sweeps).
531        for _ in 0..8 {
532            for k in 0..n_seg {
533                let sk = s[k].max(0.0);
534                // Enforce m[k] + 2 m[k+1] <= 3 s_k (reduce m[k+1] if needed, or raise m[k]).
535                if m[k] + 2.0 * m[k + 1] > 3.0 * sk {
536                    let target_m_next = 0.5 * (3.0 * sk - m[k]);
537                    let lo_next = if k + 1 < n_seg {
538                        s[k + 1].max(0.0)
539                    } else {
540                        0.0
541                    };
542                    m[k + 1] = target_m_next.clamp(lo_next, sk);
543                }
544                // Enforce 2 m[k] + m[k+1] >= 3 s_k (raise m[k] within [s_k, s_{k-1}]).
545                if 2.0 * m[k] + m[k + 1] < 3.0 * sk {
546                    let target_m_cur = 0.5 * (3.0 * sk - m[k + 1]);
547                    let hi_cur = if k > 0 { s[k - 1].max(0.0) } else { 2.0 * sk };
548                    m[k] = target_m_cur.clamp(sk, hi_cur);
549                }
550            }
551        }
552    } else {
553        // General Fritsch–Carlson monotonicity constraint (alpha^2 + beta^2 <= 9).
554        for k in 0..n_seg {
555            if s[k].abs() < 1e-15 {
556                m[k] = 0.0;
557                m[k + 1] = 0.0;
558            } else {
559                let alpha = m[k] / s[k];
560                let beta = m[k + 1] / s[k];
561                let r2 = alpha * alpha + beta * beta;
562                if r2 > 9.0 {
563                    let tau = 3.0 / r2.sqrt();
564                    m[k] = tau * alpha * s[k];
565                    m[k + 1] = tau * beta * s[k];
566                }
567            }
568        }
569    }
570
571    let mut cdfs = Vec::with_capacity(target_ages.len());
572    for &t in target_ages {
573        if t > t_max + tol {
574            return Err(ValidationError::InvalidParameter(
575                "target age exceeds maximum anchor age for SWIMON interpolation",
576            ));
577        }
578        let tc = t.min(t_max);
579        let k = find_bracket(&xs, tc);
580        let p = eval_cubic_hermite(xs[k], xs[k + 1], ys[k], ys[k + 1], m[k], m[k + 1], tc);
581        if !(p > 0.0) || !p.is_finite() {
582            return Err(ValidationError::DivideByZero("SWIMON percent reported"));
583        }
584        cdfs.push(1.0 / p);
585    }
586
587    Ok(build_pattern(
588        SubannualInterpMethod::Swimon,
589        target_ages,
590        cdfs,
591    ))
592}
593
594// ===========================================================================
595// 6. Spliced Weibull (Robbin 2018)
596// ===========================================================================
597
598/// Robbin (2018) Spliced Weibull sub-annual interpolation.
599///
600/// Splices a two-parameter Weibull emergence curve `P(t) = 1 - exp(-a_k · t^{b_k})`
601/// across each consecutive pair of annual knots `(t_k, P_k)` and `(t_{k+1}, P_{k+1})`,
602/// preserving exact annual anchor points while producing smooth sub-annual emergence.
603///
604/// For `t in (0, anchor_ages[0])`, evaluates the first segment's Weibull curve
605/// (which naturally satisfies `P(0) = 0`). If a knot has `P = 1.0` (i.e. `CDF = 1.0`,
606/// fully developed), falls back cleanly to linear percent-reported on that final segment.
607pub fn interp_spliced_weibull(
608    anchor_ages: &[f64],
609    anchor_cdfs: &[f64],
610    target_ages: &[f64],
611) -> Result<InterpolatedPattern, ValidationError> {
612    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
613    let t_max = *anchor_ages.last().expect("len >= 2");
614    let tol = 1e-9 * t_max;
615
616    let pcts: Vec<f64> = anchor_cdfs.iter().map(|&c| 1.0 / c).collect();
617    let n_seg = anchor_ages.len() - 1;
618
619    // Fit (ln_a, b) for each interior segment where 0 < p0 < p1 < 1.
620    let mut seg_params: Vec<Option<(f64, f64)>> = Vec::with_capacity(n_seg);
621    for k in 0..n_seg {
622        let p0 = pcts[k];
623        let p1 = pcts[k + 1];
624        if p0 > 0.0 && p0 < 1.0 - 1e-12 && p1 > p0 && p1 < 1.0 - 1e-12 {
625            let y0 = (-(1.0 - p0).ln()).ln();
626            let y1 = (-(1.0 - p1).ln()).ln();
627            let x0 = anchor_ages[k].ln();
628            let x1 = anchor_ages[k + 1].ln();
629            let b = (y1 - y0) / (x1 - x0);
630            let ln_a = y0 - b * x0;
631            seg_params.push(Some((ln_a, b)));
632        } else {
633            seg_params.push(None);
634        }
635    }
636
637    let mut cdfs = Vec::with_capacity(target_ages.len());
638    for &t in target_ages {
639        if t > t_max + tol {
640            return Err(ValidationError::InvalidParameter(
641                "target age exceeds maximum anchor age for spliced Weibull interpolation",
642            ));
643        }
644        let tc = t.min(t_max);
645        let p = if tc < anchor_ages[0] {
646            if let Some((ln_a, b)) = seg_params[0] {
647                let v = (ln_a + b * tc.ln()).exp();
648                -(-v).exp_m1()
649            } else {
650                (tc / anchor_ages[0]) * pcts[0]
651            }
652        } else {
653            let k = find_bracket(anchor_ages, tc);
654            if let Some((ln_a, b)) = seg_params[k] {
655                let v = (ln_a + b * tc.ln()).exp();
656                -(-v).exp_m1()
657            } else {
658                // Fully mature boundary (P = 1.0) or flat segment: linear fallback in P-space.
659                let w = (tc - anchor_ages[k]) / (anchor_ages[k + 1] - anchor_ages[k]);
660                (1.0 - w) * pcts[k] + w * pcts[k + 1]
661            }
662        };
663        if !(p > 0.0) || !p.is_finite() {
664            return Err(ValidationError::DivideByZero("Weibull percent reported"));
665        }
666        cdfs.push(1.0 / p);
667    }
668
669    Ok(build_pattern(
670        SubannualInterpMethod::SplicedWeibull,
671        target_ages,
672        cdfs,
673    ))
674}
675
676// ===========================================================================
677// 7. IVF12 — Interpolated Volume Factor, 12-Month Basis (Robbin 2018)
678// ===========================================================================
679
680/// Robbin (2018) Interpolated Volume Factor (12-month basis) method.
681///
682/// Computes the 12-month development factor `F_12(t_k) = CDF(t_k) / CDF(t_k + 12)`
683/// at each annual knot, smoothly interpolates `F_12(t)` geometrically across
684/// intermediate sub-annual ages, and recursively constructs
685/// `CDF(t) = F_12(t) * CDF(t + 12)` backward from the final 12-month window.
686///
687/// Preserves every annual anchor CDF identically and guarantees exact 12-month
688/// multiplicative product parity across every annual window.
689///
690/// Requires equally spaced annual anchor ages (12-month spacing, e.g. `12, 24, 36, ...`).
691pub fn interp_ivf12(
692    anchor_ages: &[f64],
693    anchor_cdfs: &[f64],
694    target_ages: &[f64],
695) -> Result<InterpolatedPattern, ValidationError> {
696    validate_anchors_and_targets(anchor_ages, anchor_cdfs, target_ages)?;
697
698    let m = anchor_ages.len();
699    let step = anchor_ages[1] - anchor_ages[0];
700    for k in 1..m {
701        if ((anchor_ages[k] - anchor_ages[k - 1]) - step).abs() > 1e-6 * step {
702            return Err(ValidationError::InvalidParameter(
703                "interp_ivf12 requires equally spaced anchor ages (e.g. 12, 24, 36, ...)",
704            ));
705        }
706    }
707
708    let t_min = anchor_ages[0];
709    let t_max = anchor_ages[m - 1];
710    let tol = 1e-9 * t_max;
711
712    // 12-month volume factors at each knot: F(t_k) = CDF(t_k) / CDF(t_{k+1}),
713    // with F(t_{m-1}) = 1.0 (beyond the final knot, incremental annual development is 1.0).
714    let mut f12 = Vec::with_capacity(m);
715    for k in 0..(m - 1) {
716        f12.push(anchor_cdfs[k] / anchor_cdfs[k + 1]);
717    }
718    f12.push(1.0);
719
720    // Evaluate F_12(t) via log-linear interpolation between adjacent knots.
721    let eval_f12 = |t: f64| -> f64 {
722        if t >= t_max {
723            return 1.0;
724        }
725        let tc = t.max(t_min);
726        let k = find_bracket(anchor_ages, tc);
727        let w = (tc - anchor_ages[k]) / (anchor_ages[k + 1] - anchor_ages[k]);
728        ((1.0 - w) * f12[k].ln() + w * f12[k + 1].ln()).exp()
729    };
730
731    // Evaluate CDF(t) by stepping forward in `step` (12m) increments until landing
732    // inside the final window `[t_{m-2}, t_{m-1}]`, where CDF is anchored cleanly.
733    let eval_cdf = |t: f64| -> f64 {
734        let mut prod = 1.0;
735        let mut cur = t;
736        let last_window_start = anchor_ages[m - 2];
737        while cur < last_window_start - tol {
738            prod *= eval_f12(cur);
739            cur += step;
740        }
741        // Now cur is in [t_{m-2}, t_{m-1}]: geometric anchor inside the final window.
742        let w = ((cur - last_window_start) / step).clamp(0.0, 1.0);
743        let tail_cdf = ((1.0 - w) * anchor_cdfs[m - 2].ln() + w * anchor_cdfs[m - 1].ln()).exp();
744        prod * tail_cdf
745    };
746
747    let mut cdfs = Vec::with_capacity(target_ages.len());
748    for &t in target_ages {
749        if t < t_min - tol || t > t_max + tol {
750            return Err(ValidationError::InvalidParameter(
751                "target age outside [anchor_ages[0], anchor_ages[last]] for IVF12 interpolation",
752            ));
753        }
754        cdfs.push(eval_cdf(t.clamp(t_min, t_max)));
755    }
756
757    Ok(build_pattern(
758        SubannualInterpMethod::Ivf12,
759        target_ages,
760        cdfs,
761    ))
762}
763
764#[cfg(test)]
765mod tests {
766    use super::*;
767
768    fn sample_annual() -> ([f64; 5], [f64; 5]) {
769        // Annual ages 12..60 months, smooth decelerating pattern.
770        let ages = [12.0, 24.0, 36.0, 48.0, 60.0];
771        let cdfs = [2.50, 1.45, 1.18, 1.06, 1.00];
772        (ages, cdfs)
773    }
774
775    #[test]
776    fn all_interpolators_preserve_exact_annual_knots() {
777        let (ages, cdfs) = sample_annual();
778        let targets = [12.0, 18.0, 24.0, 30.0, 36.0, 42.0, 48.0, 54.0, 60.0];
779        let methods = [
780            SubannualInterpMethod::LinearCdf,
781            SubannualInterpMethod::LinearPctReported,
782            SubannualInterpMethod::Exponential,
783            SubannualInterpMethod::InversePower,
784            SubannualInterpMethod::Swimon,
785            SubannualInterpMethod::SplicedWeibull,
786            SubannualInterpMethod::Ivf12,
787        ];
788        for method in methods {
789            let pat = interpolate_pattern(method, &ages, &cdfs, &targets).expect("interp");
790            for (k, &expected) in cdfs.iter().enumerate() {
791                let got = pat.cdfs[k * 2];
792                assert!(
793                    (got - expected).abs() < 1e-10,
794                    "{method:?} knot {k}: got {got}, expected {expected}"
795                );
796            }
797            // Monotonic non-increasing CDFs across all targets.
798            for w in pat.cdfs.windows(2) {
799                assert!(
800                    w[0] >= w[1] - 1e-10,
801                    "{method:?} non-monotone: {} < {}",
802                    w[0],
803                    w[1]
804                );
805            }
806        }
807    }
808
809    #[test]
810    fn linear_cdf_exceeds_linear_pct_reported_between_knots() {
811        // Jensen's inequality: 1/p is strictly convex, so linear CDF >= linear % reported.
812        let (ages, cdfs) = sample_annual();
813        let targets = [18.0, 30.0, 42.0, 54.0];
814        let lin_cdf = interp_linear_cdf(&ages, &cdfs, &targets).unwrap();
815        let lin_pct = interp_linear_pct_reported(&ages, &cdfs, &targets).unwrap();
816        for (a, b) in lin_cdf.cdfs.iter().zip(lin_pct.cdfs.iter()) {
817            assert!(
818                a > b,
819                "expected linear CDF ({a}) > linear pct reported ({b})"
820            );
821        }
822    }
823
824    #[test]
825    fn swimon_produces_non_increasing_monthly_emergence() {
826        let (ages, cdfs) = sample_annual();
827        let targets: Vec<f64> = (1..=60).map(|m| m as f64).collect();
828        let pat = interp_swimon(&ages, &cdfs, &targets).unwrap();
829        let mut prev_inc = pat.pct_reported[0];
830        for k in 1..pat.pct_reported.len() {
831            let inc = pat.pct_reported[k] - pat.pct_reported[k - 1];
832            assert!(
833                inc <= prev_inc + 1e-9,
834                "SWIMON sawtooth at month {}: inc={inc} > prev={prev_inc}",
835                k + 1
836            );
837            prev_inc = inc;
838        }
839    }
840}