1use crate::validate::{ValidationError, validate_positive_finite_slice};
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
25pub enum SubannualInterpMethod {
26 LinearCdf,
28 LinearPctReported,
30 Exponential,
32 InversePower,
34 Swimon,
36 SplicedWeibull,
38 Ivf12,
40}
41
42#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
44pub struct InterpolatedPattern {
45 pub method: SubannualInterpMethod,
47 pub ages_months: Vec<f64>,
49 pub cdfs: Vec<f64>,
51 pub pct_reported: Vec<f64>,
53 pub ldfs: Vec<f64>,
55}
56
57#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
60pub struct InversePowerInterpResult {
61 pub pattern: InterpolatedPattern,
63 pub a: f64,
65 pub b: f64,
67 pub r_squared: f64,
69}
70
71pub 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#[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
156pub 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
194pub 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
241pub 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
280const 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
306fn 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
322pub 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 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; let intercept = y_bar - slope * x_bar; 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#[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
442pub 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 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 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 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 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 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 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 for _ in 0..8 {
532 for k in 0..n_seg {
533 let sk = s[k].max(0.0);
534 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 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 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
594pub 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 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 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
676pub 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 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 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 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 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 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 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 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}