1use crate::triangle::latest_diagonal;
27use crate::types::TriangleView;
28use crate::validate::{
29 MonotonicityPolicy, ValidationError, validate_monotone_cumulative, validate_tail,
30 validate_triangle,
31};
32
33#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
35pub struct MurphyOptions {
36 pub variance_power: f64,
40 pub include_intercept: bool,
43 pub tail: f64,
45 pub policy: MonotonicityPolicy,
47}
48
49impl Default for MurphyOptions {
50 fn default() -> Self {
51 Self::mack_equivalent()
52 }
53}
54
55impl MurphyOptions {
56 pub const fn mack_equivalent() -> Self {
58 Self {
59 variance_power: 1.0,
60 include_intercept: false,
61 tail: 1.0,
62 policy: MonotonicityPolicy::Strict,
63 }
64 }
65
66 pub const fn simple_average() -> Self {
68 Self {
69 variance_power: 2.0,
70 include_intercept: false,
71 tail: 1.0,
72 policy: MonotonicityPolicy::Strict,
73 }
74 }
75
76 pub const fn ols_through_origin() -> Self {
78 Self {
79 variance_power: 0.0,
80 include_intercept: false,
81 tail: 1.0,
82 policy: MonotonicityPolicy::Strict,
83 }
84 }
85
86 pub const fn brosius_equivalent() -> Self {
88 Self {
89 variance_power: 0.0,
90 include_intercept: true,
91 tail: 1.0,
92 policy: MonotonicityPolicy::Strict,
93 }
94 }
95}
96
97#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
99pub struct MurphyLinkFit {
100 pub dev: usize,
102 pub n_obs: usize,
104 pub intercept: f64,
106 pub slope: f64,
108 pub sigma_sq: f64,
110 pub var_intercept: f64,
112 pub var_slope: f64,
114 pub cov_intercept_slope: f64,
116}
117
118#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
120pub struct MurphyResult {
121 pub options: MurphyOptions,
123 pub links: Vec<MurphyLinkFit>,
125 pub latest: Vec<f64>,
127 pub ultimate: Vec<f64>,
129 pub reserve: Vec<f64>,
131 pub process_variance: Vec<f64>,
133 pub parameter_variance: Vec<f64>,
135 pub mse: Vec<f64>,
137 pub standard_error: Vec<f64>,
139 pub total_reserve: f64,
141 pub total_mse: f64,
143 pub total_standard_error: f64,
145 pub total_cv: f64,
147}
148
149impl std::fmt::Display for MurphyResult {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 write!(
152 f,
153 "Murphy(delta={}, intercept={}, reserve={:.2}, se={:.2})",
154 self.options.variance_power,
155 self.options.include_intercept,
156 self.total_reserve,
157 self.total_standard_error
158 )
159 }
160}
161
162pub fn analyze(
164 t: &TriangleView<'_>,
165 options: MurphyOptions,
166) -> Result<MurphyResult, ValidationError> {
167 validate_triangle(t)?;
168 validate_tail(options.tail)?;
169 if !options.variance_power.is_finite() || options.variance_power < 0.0 {
170 return Err(ValidationError::InvalidParameter(
171 "variance_power must be finite and non-negative",
172 ));
173 }
174 if matches!(options.policy, MonotonicityPolicy::Strict) {
175 validate_monotone_cumulative(t)?;
176 }
177
178 let n = t.n_origins;
179 let n_links = n.saturating_sub(1);
180 let delta = options.variance_power;
181
182 struct RawLink {
184 n_obs: usize,
185 alpha: f64,
186 beta: f64,
187 sigma_sq: Option<f64>,
188 u_aa: f64,
190 u_ab: f64,
191 u_bb: f64,
192 }
193
194 let mut raw_links = Vec::with_capacity(n_links);
195 for j in 0..n_links {
196 let nk = n - j - 1;
197 let mut xs = Vec::with_capacity(nk);
198 let mut ys = Vec::with_capacity(nk);
199 let mut ws = Vec::with_capacity(nk);
200
201 for i in 0..nk {
202 let x = t.get(i, j);
203 let y = t.get(i, j + 1);
204 if x > 0.0 {
205 xs.push(x);
206 ys.push(y);
207 ws.push(if delta == 0.0 { 1.0 } else { x.powf(-delta) });
208 } else if x == 0.0 && y == 0.0 {
209 continue;
210 } else if delta == 0.0 {
211 xs.push(x);
212 ys.push(y);
213 ws.push(1.0);
214 } else {
215 return Err(ValidationError::DivideByZero(
216 "zero prior cumulative with positive variance_power",
217 ));
218 }
219 }
220
221 let m = xs.len();
222 if m == 0 {
223 return Err(ValidationError::DivideByZero(
224 "no valid observations for development link",
225 ));
226 }
227
228 if !options.include_intercept || m == 1 {
229 let mut num = 0.0;
231 let mut den = 0.0;
232 for k in 0..m {
233 num += ws[k] * xs[k] * ys[k];
234 den += ws[k] * xs[k] * xs[k];
235 }
236 if den <= 0.0 {
237 return Err(ValidationError::DivideByZero("weighted sum of squares"));
238 }
239 let beta = num / den;
240 let sigma_sq = if m >= 2 {
241 let mut rss = 0.0;
242 for k in 0..m {
243 let r = ys[k] - beta * xs[k];
244 rss += ws[k] * r * r;
245 }
246 Some(rss / (m as f64 - 1.0))
247 } else {
248 None
249 };
250 raw_links.push(RawLink {
251 n_obs: m,
252 alpha: 0.0,
253 beta,
254 sigma_sq,
255 u_aa: 0.0,
256 u_ab: 0.0,
257 u_bb: 1.0 / den,
258 });
259 } else {
260 let sum_w: f64 = ws.iter().sum();
262 let mean_x = (0..m).map(|k| ws[k] * xs[k]).sum::<f64>() / sum_w;
263 let mean_y = (0..m).map(|k| ws[k] * ys[k]).sum::<f64>() / sum_w;
264 let mut sxx = 0.0;
265 let mut sxy = 0.0;
266 for k in 0..m {
267 let dx = xs[k] - mean_x;
268 let dy = ys[k] - mean_y;
269 sxx += ws[k] * dx * dx;
270 sxy += ws[k] * dx * dy;
271 }
272 let var_tol = 1e-12 * sum_w * mean_x * mean_x;
273 let (alpha, beta, u_aa, u_ab, u_bb) = if sxx > var_tol {
274 let b = sxy / sxx;
275 let a = mean_y - b * mean_x;
276 (
277 a,
278 b,
279 1.0 / sum_w + (mean_x * mean_x) / sxx,
280 -mean_x / sxx,
281 1.0 / sxx,
282 )
283 } else {
284 (mean_y, 0.0, 1.0 / sum_w, 0.0, 0.0)
286 };
287 let sigma_sq = if m >= 3 {
288 let mut rss = 0.0;
289 for k in 0..m {
290 let r = ys[k] - (alpha + beta * xs[k]);
291 rss += ws[k] * r * r;
292 }
293 Some(rss / (m as f64 - 2.0))
294 } else {
295 None
296 };
297 raw_links.push(RawLink {
298 n_obs: m,
299 alpha,
300 beta,
301 sigma_sq,
302 u_aa,
303 u_ab,
304 u_bb,
305 });
306 }
307 }
308
309 let mut sigma_sq_extrap = vec![0.0; n_links];
311 for j in 0..n_links {
312 if let Some(s2) = raw_links[j].sigma_sq {
313 sigma_sq_extrap[j] = s2;
314 } else if j >= 2 {
315 let a = sigma_sq_extrap[j - 1];
316 let b = sigma_sq_extrap[j - 2];
317 sigma_sq_extrap[j] = if a > 0.0 && b > 0.0 {
318 (a * a / b).min(a).min(b).max(0.0)
319 } else {
320 0.0
321 };
322 } else if j == 1 {
323 sigma_sq_extrap[j] = sigma_sq_extrap[0].max(0.0);
324 } else {
325 sigma_sq_extrap[j] = 0.0;
326 }
327 }
328
329 let mut links = Vec::with_capacity(n_links);
330 for j in 0..n_links {
331 let s2 = sigma_sq_extrap[j];
332 let r = &raw_links[j];
333 links.push(MurphyLinkFit {
334 dev: j,
335 n_obs: r.n_obs,
336 intercept: r.alpha,
337 slope: r.beta,
338 sigma_sq: s2,
339 var_intercept: s2 * r.u_aa,
340 var_slope: s2 * r.u_bb,
341 cov_intercept_slope: s2 * r.u_ab,
342 });
343 }
344
345 let latest = latest_diagonal(t);
347 let mut proj = vec![0.0; n * n];
348 let mut ultimate = vec![0.0; n];
349 let mut reserve = vec![0.0; n];
350 let mut process_variance = vec![0.0; n];
351 let mut parameter_variance = vec![0.0; n];
352 let mut mse = vec![0.0; n];
353 let mut standard_error = vec![0.0; n];
354
355 let tail_sq = options.tail * options.tail;
356
357 for i in 0..n {
358 let last_obs = n - 1 - i;
359 for k in 0..=last_obs {
360 proj[i * n + k] = t.get(i, k);
361 }
362 let mut c = latest[i];
363 let mut pv = 0.0;
364 let mut ev = 0.0;
365 for k in last_obs..n_links {
366 let lk = &links[k];
367 let b2 = lk.slope * lk.slope;
368 let c_pow = if delta == 0.0 {
369 1.0
370 } else if c > 0.0 {
371 c.powf(delta)
372 } else {
373 0.0
374 };
375 pv = b2 * pv + lk.sigma_sq * c_pow;
376 let step_param_var =
377 lk.var_intercept + 2.0 * c * lk.cov_intercept_slope + c * c * lk.var_slope;
378 ev = b2 * ev + step_param_var;
379 c = lk.intercept + lk.slope * c;
380 proj[i * n + k + 1] = c;
381 }
382 let ult = c * options.tail;
383 let pv_ult = pv * tail_sq;
384 let ev_ult = ev * tail_sq;
385 let m_ult = (pv_ult + ev_ult).max(0.0);
386
387 ultimate[i] = ult;
388 reserve[i] = ult - latest[i];
389 process_variance[i] = pv_ult;
390 parameter_variance[i] = ev_ult;
391 mse[i] = m_ult;
392 standard_error[i] = m_ult.sqrt();
393 }
394
395 let mut total_mse: f64 = mse.iter().sum();
397 for i in 1..n {
398 let start_k = n - 1 - i;
399 for j in (i + 1)..n {
400 let mut cov_ij = 0.0;
401 for k in start_k..n_links {
402 let lk = &links[k];
403 let ci = proj[i * n + k];
404 let cj = proj[j * n + k];
405 let step_cov =
406 lk.var_intercept + (ci + cj) * lk.cov_intercept_slope + ci * cj * lk.var_slope;
407 cov_ij = lk.slope * lk.slope * cov_ij + step_cov;
408 }
409 total_mse += 2.0 * cov_ij * tail_sq;
410 }
411 }
412 total_mse = total_mse.max(0.0);
413 let total_standard_error = total_mse.sqrt();
414 let total_reserve: f64 = reserve.iter().sum();
415 let total_cv = if total_reserve != 0.0 {
416 total_standard_error / total_reserve
417 } else {
418 0.0
419 };
420
421 Ok(MurphyResult {
422 options,
423 links,
424 latest,
425 ultimate,
426 reserve,
427 process_variance,
428 parameter_variance,
429 mse,
430 standard_error,
431 total_reserve,
432 total_mse,
433 total_standard_error,
434 total_cv,
435 })
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441 use crate::Triangle;
442 use crate::brosius;
443 use crate::mack;
444
445 #[test]
446 fn exact_equivalence_to_mack_at_delta_1_no_intercept() {
447 let tri = Triangle::try_from_upper_rows(&[
448 &[100.0, 165.0, 200.0, 212.0, 218.0],
449 &[120.0, 190.0, 238.0, 250.0],
450 &[135.0, 222.0, 268.0],
451 &[150.0, 240.0],
452 &[160.0],
453 ])
454 .unwrap();
455
456 let m = mack::analyze(&tri.view(), 1.0).unwrap();
457 let mu = analyze(&tri.view(), MurphyOptions::mack_equivalent()).unwrap();
458
459 for j in 0..4 {
460 assert!((mu.links[j].slope - m.ldf[j]).abs() < 1e-12);
461 assert!((mu.links[j].sigma_sq - m.sigma_sq[j]).abs() < 1e-10);
462 }
463 for i in 0..5 {
464 assert!((mu.reserve[i] - m.reserve[i]).abs() < 1e-10);
465 assert!((mu.standard_error[i] - m.standard_error[i]).abs() < 1e-10);
466 }
467 assert!((mu.total_reserve - m.total_reserve).abs() < 1e-10);
468 assert!((mu.total_standard_error - m.total_standard_error).abs() < 1e-10);
469 }
470
471 #[test]
472 fn exact_equivalence_to_brosius_at_delta_0_with_intercept() {
473 let tri = Triangle::try_from_upper_rows(&[
474 &[100.0, 165.0, 200.0, 212.0, 218.0],
475 &[120.0, 190.0, 238.0, 250.0],
476 &[135.0, 222.0, 268.0],
477 &[150.0, 240.0],
478 &[160.0],
479 ])
480 .unwrap();
481
482 let br = brosius::project(&tri.view(), 1.0).unwrap();
483 let mu = analyze(&tri.view(), MurphyOptions::brosius_equivalent()).unwrap();
484
485 for j in 0..4 {
486 assert!((mu.links[j].intercept - br.intercept[j]).abs() < 1e-10);
487 assert!((mu.links[j].slope - br.slope[j]).abs() < 1e-10);
488 }
489 for i in 0..5 {
490 assert!((mu.ultimate[i] - br.ultimate[i]).abs() < 1e-9);
491 assert!((mu.reserve[i] - br.reserve[i]).abs() < 1e-9);
492 }
493 assert!(mu.total_standard_error > 0.0);
494 }
495
496 #[test]
497 fn delta_2_recovers_simple_average_ldf() {
498 let tri =
499 Triangle::try_from_upper_rows(&[&[100.0, 150.0, 180.0], &[200.0, 340.0], &[150.0]])
500 .unwrap();
501
502 let mu = analyze(&tri.view(), MurphyOptions::simple_average()).unwrap();
503 let expected_f0 = 0.5 * (150.0 / 100.0 + 340.0 / 200.0);
504 assert!((mu.links[0].slope - expected_f0).abs() < 1e-12);
505 }
506}