reserving_kernels/deterministic/
separation.rs1use crate::linalg::weighted_least_squares_qr_beta_only;
23use crate::preprocessing::triangle::{cumulative_to_incremental, latest_diagonal};
24use crate::types::TriangleView;
25use crate::validate::{ValidationError, validate_positive_finite_slice, validate_triangle};
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
29pub enum SeparationMethod {
30 Arithmetic,
32 Geometric,
34}
35
36#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
38pub enum InflationProjection {
39 ConstantRate(f64),
42 HistoricalGeometricMean,
45 ExplicitFutureIndices(Vec<f64>),
48}
49
50#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
52pub struct SeparationResult {
53 pub method: SeparationMethod,
55 pub delay_proportions: Vec<f64>,
57 pub calendar_indices: Vec<f64>,
59 pub future_calendar_indices: Vec<f64>,
61 pub implied_inflation_rates: Vec<f64>,
63 pub latest: Vec<f64>,
65 pub reserve: Vec<f64>,
67 pub ultimate: Vec<f64>,
69 pub total_reserve: f64,
71}
72
73impl std::fmt::Display for SeparationResult {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 write!(
76 f,
77 "Separation({:?}, total_reserve={:.2})",
78 self.method, self.total_reserve
79 )
80 }
81}
82
83pub fn analyze(
86 cumulative: &TriangleView<'_>,
87 exposures: &[f64],
88 method: SeparationMethod,
89 projection: &InflationProjection,
90) -> Result<SeparationResult, ValidationError> {
91 validate_triangle(cumulative)?;
92 let n = cumulative.n_origins;
93 if n < 2 {
94 return Err(ValidationError::InvalidParameter(
95 "triangle must be at least 2x2",
96 ));
97 }
98 if exposures.len() != n {
99 return Err(ValidationError::ShapeMismatch);
100 }
101 validate_positive_finite_slice(exposures, "exposures")?;
102
103 let inc = cumulative_to_incremental(cumulative);
104 let mut s = vec![f64::NAN; n * n];
105 for i in 0..n {
106 for j in 0..(n - i) {
107 let x = inc[i * n + j];
108 if !x.is_finite() {
109 return Err(ValidationError::NotFinite);
110 }
111 s[i * n + j] = x / exposures[i];
112 }
113 }
114
115 let (delay_proportions, calendar_indices) = match method {
116 SeparationMethod::Arithmetic => fit_arithmetic(&s, n)?,
117 SeparationMethod::Geometric => fit_geometric(&s, n)?,
118 };
119
120 let mut implied_inflation_rates = Vec::with_capacity(n - 1);
121 for k in 1..n {
122 let prev = calendar_indices[k - 1];
123 let curr = calendar_indices[k];
124 if prev.abs() > 0.0 {
125 implied_inflation_rates.push(curr / prev - 1.0);
126 } else {
127 implied_inflation_rates.push(f64::NAN);
128 }
129 }
130
131 let future_calendar_indices = match projection {
132 InflationProjection::ConstantRate(rate) => {
133 if !rate.is_finite() || *rate <= -1.0 {
134 return Err(ValidationError::InvalidParameter(
135 "inflation rate must be finite and > -1.0",
136 ));
137 }
138 let base = calendar_indices[n - 1];
139 (1..n).map(|h| base * (1.0 + rate).powi(h as i32)).collect()
140 }
141 InflationProjection::HistoricalGeometricMean => {
142 let first = calendar_indices[0];
143 let last = calendar_indices[n - 1];
144 if first <= 0.0 || last <= 0.0 {
145 return Err(ValidationError::InvalidParameter(
146 "geometric mean inflation requires positive first and last calendar indices",
147 ));
148 }
149 let g = (last / first).powf(1.0 / (n as f64 - 1.0));
150 (1..n).map(|h| last * g.powi(h as i32)).collect()
151 }
152 InflationProjection::ExplicitFutureIndices(indices) => {
153 if indices.len() != n - 1 {
154 return Err(ValidationError::ShapeMismatch);
155 }
156 for &v in indices {
157 if !v.is_finite() || v < 0.0 {
158 return Err(ValidationError::InvalidParameter(
159 "future calendar indices must be finite and non-negative",
160 ));
161 }
162 }
163 indices.clone()
164 }
165 };
166
167 let latest = latest_diagonal(cumulative);
168 let mut reserve = vec![0.0; n];
169 let mut ultimate = vec![0.0; n];
170 for i in 0..n {
171 let mut r_i = 0.0;
172 for j in (n - i)..n {
173 let cal_idx = i + j; let lam = future_calendar_indices[cal_idx - n];
175 r_i += exposures[i] * delay_proportions[j] * lam;
176 }
177 reserve[i] = r_i;
178 ultimate[i] = latest[i] + r_i;
179 }
180 let total_reserve: f64 = reserve.iter().sum();
181
182 Ok(SeparationResult {
183 method,
184 delay_proportions,
185 calendar_indices,
186 future_calendar_indices,
187 implied_inflation_rates,
188 latest,
189 reserve,
190 ultimate,
191 total_reserve,
192 })
193}
194
195fn fit_arithmetic(s: &[f64], n: usize) -> Result<(Vec<f64>, Vec<f64>), ValidationError> {
196 let mut diag_sums = vec![0.0; n];
197 let mut col_sums = vec![0.0; n];
198
199 for i in 0..n {
200 for j in 0..(n - i) {
201 let v = s[i * n + j];
202 diag_sums[i + j] += v;
203 col_sums[j] += v;
204 }
205 }
206
207 let mut r = vec![0.0; n];
208 let mut lam = vec![0.0; n];
209
210 let mut sum_r_tail = 0.0_f64;
211 let mut sum_lam_tail = 0.0_f64;
212
213 for k in (0..n).rev() {
214 let rem_r = 1.0_f64 - sum_r_tail;
215 if rem_r.abs() <= 1e-14 {
216 return Err(ValidationError::DivideByZero(
217 "arithmetic separation remaining delay proportion",
218 ));
219 }
220 lam[k] = diag_sums[k] / rem_r;
221 sum_lam_tail += lam[k];
222 if sum_lam_tail.abs() <= 1e-14 {
223 return Err(ValidationError::DivideByZero(
224 "arithmetic separation cumulative calendar index",
225 ));
226 }
227 r[k] = col_sums[k] / sum_lam_tail;
228 sum_r_tail += r[k];
229 }
230
231 Ok((r, lam))
232}
233
234fn fit_geometric(s: &[f64], n: usize) -> Result<(Vec<f64>, Vec<f64>), ValidationError> {
235 let p = 2 * n - 1;
238 let mut x_rows = Vec::new();
239 let mut y_vals = Vec::new();
240
241 for i in 0..n {
242 for j in 0..(n - i) {
243 let v = s[i * n + j];
244 if v <= 0.0 {
245 return Err(ValidationError::InvalidParameter(
246 "geometric separation requires strictly positive incremental losses",
247 ));
248 }
249 let mut row = vec![0.0; p];
250 row[j] = 1.0;
251 let k = i + j;
252 if k < n - 1 {
253 row[n + k] = 1.0;
254 }
255 x_rows.extend_from_slice(&row);
256 y_vals.push(v.ln());
257 }
258 }
259
260 let n_obs = y_vals.len();
261 let weights = vec![1.0; n_obs];
262 let beta = weighted_least_squares_qr_beta_only(&x_rows, &y_vals, &weights, n_obs, p)?;
263
264 let raw_r: Vec<f64> = (0..n).map(|j| beta[j].exp()).collect();
265 let sum_r: f64 = raw_r.iter().sum();
266 if !sum_r.is_finite() || sum_r <= 0.0 {
267 return Err(ValidationError::DivideByZero(
268 "geometric separation delay normalization",
269 ));
270 }
271
272 let r: Vec<f64> = raw_r.into_iter().map(|v| v / sum_r).collect();
273 let mut lam = Vec::with_capacity(n);
274 for k in 0..(n - 1) {
275 lam.push(beta[n + k].exp() * sum_r);
276 }
277 lam.push(sum_r);
278
279 Ok((r, lam))
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use crate::Triangle;
286
287 #[test]
288 fn exact_recovery_on_synthetic_stepped_inflation_triangle() {
289 let true_r = [0.40, 0.30, 0.18, 0.08, 0.04];
290 let true_lam = [100.0, 108.0, 120.0, 140.0, 165.0];
291 let exposures = [50.0, 55.0, 60.0, 62.0, 70.0];
292 let n = 5;
293
294 let mut inc_rows: Vec<Vec<f64>> = Vec::new();
295 for i in 0..n {
296 let mut row = Vec::new();
297 for j in 0..(n - i) {
298 row.push(exposures[i] * true_r[j] * true_lam[i + j]);
299 }
300 inc_rows.push(row);
301 }
302 let slices: Vec<&[f64]> = inc_rows.iter().map(std::vec::Vec::as_slice).collect();
303 let tri = Triangle::try_from_incremental_rows(&slices).unwrap();
304
305 for method in [SeparationMethod::Arithmetic, SeparationMethod::Geometric] {
306 let res = analyze(
307 &tri.view(),
308 &exposures,
309 method,
310 &InflationProjection::ConstantRate(0.10),
311 )
312 .unwrap();
313
314 let sum_r: f64 = res.delay_proportions.iter().sum();
315 assert!((sum_r - 1.0).abs() < 1e-12);
316 for j in 0..n {
317 assert!(
318 (res.delay_proportions[j] - true_r[j]).abs() < 1e-10,
319 "{method:?} r[{j}] mismatch"
320 );
321 assert!(
322 (res.calendar_indices[j] - true_lam[j]).abs() < 1e-9,
323 "{method:?} lam[{j}] mismatch"
324 );
325 }
326 assert!(res.total_reserve > 0.0);
327 }
328 }
329}