Skip to main content

reserving_kernels/
dependence.rs

1//! Multi-line portfolio dependence: Iman–Conover rank reordering and
2//! synchronized multi-line ODP bootstrapping.
3//!
4//! Implements two distinct dependence integration points from primary
5//! actuarial literature:
6//!
7//! * **Iman–Conover (1982) / Mildenhall (2006)** — *Correlation and Aggregate
8//!   Loss Distributions With an Emphasis on the Iman–Conover Method*, CAS
9//!   Winter 2006 Forum, pp. 43–82. Post-simulation batch permutation that
10//!   induces target rank correlation across marginal scenario vectors while
11//!   preserving each empirical marginal distribution exactly. Returns whole-
12//!   scenario index permutations so multi-origin and multi-line scenario
13//!   records move coherently.
14//! * **Synchronized ODP Bootstrap** — Kirschner, Kerley & Isaacs (2002),
15//!   *Two Approaches to Calculating Correlated Reserve Indications Across
16//!   Multiple Lines of Business*, CAS Forum, pp. 211–246; Shapland (2016),
17//!   CAS Monograph No. 4, §9. Samples a single shared triangle coordinate map
18//!   per iteration across aligned lines of business so empirical calendar/
19//!   residual cross-line dependence is preserved during parameter resampling.
20
21use std::f64::consts::PI;
22
23use crate::bootstrap_odp::{
24    DeterministicRng, OdpBootstrapOptions, OdpBootstrapScratch, OdpFit, ResidualAdjustment,
25    build_adjusted_residual_pool, cholesky_lower, fit_odp, run_odp_iteration_with_scratch,
26};
27use crate::reserve_distribution::{ReserveDistributionSummary, summarize_with_scratch};
28use crate::types::TriangleView;
29use crate::validate::ValidationError;
30
31/// Semantic interpretation of the supplied target correlation matrix for
32/// [`iman_conover`].
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
34pub enum CorrelationType {
35    /// Target matrix is directly the Pearson correlation of latent Gaussian
36    /// van der Waerden reference scores (Mildenhall 2006, §3).
37    #[default]
38    LatentGaussian,
39    /// Target matrix specifies Spearman rank correlations `ρ_S`, converted via
40    /// the continuous Gaussian copula relation `ρ = 2 · sin(π · ρ_S / 6)`.
41    SpearmanTarget,
42    /// Target matrix specifies Kendall's tau `τ`, converted via the continuous
43    /// Gaussian copula relation `ρ = sin(π · τ / 2)`.
44    KendallTarget,
45}
46
47/// Output of [`iman_conover`] batch rank reordering.
48#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
49pub struct ImanConoverResult {
50    /// Number of scenarios `N`.
51    pub n_scenarios: usize,
52    /// Number of correlated variables/lines `K`.
53    pub n_variables: usize,
54    /// Whole-scenario permutations: `permutations[col][row]` is the original
55    /// scenario index placed into output position `row` for variable `col`.
56    pub permutations: Vec<Vec<usize>>,
57    /// Reordered marginal columns preserving exact empirical multisets.
58    pub reordered_columns: Vec<Vec<f64>>,
59    /// Row-major `K × K` effective latent Gaussian correlation matrix `S`.
60    pub effective_latent_correlation: Vec<f64>,
61    /// Row-major `K × K` achieved empirical Spearman rank correlation matrix.
62    pub achieved_spearman: Vec<f64>,
63    /// Row-major `K × K` achieved empirical monetary Pearson correlation matrix.
64    pub achieved_pearson: Vec<f64>,
65}
66
67/// Output of [`synchronized_odp_bootstrap`] across `K` aligned lines of business.
68#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
69pub struct SynchronizedBootstrapResult {
70    /// Underlying ODP fits per line.
71    pub line_fits: Vec<OdpFit>,
72    /// Simulated total reserves per line: `line_totals[line][iter]`.
73    pub line_totals: Vec<Vec<f64>>,
74    /// Coherent portfolio aggregate reserves: `aggregate_totals[iter] = Σ_k line_totals[k][iter]`.
75    pub aggregate_totals: Vec<f64>,
76    /// Standalone reserve distribution summary for each line.
77    pub line_summaries: Vec<ReserveDistributionSummary>,
78    /// Correlated portfolio reserve distribution summary.
79    pub aggregate_summary: ReserveDistributionSummary,
80    /// Sum of standalone line standard deviations minus correlated portfolio
81    /// standard deviation (`>= 0` under diversification).
82    pub std_dev_diversification_benefit: f64,
83    /// Row-major `K × K` empirical Spearman rank correlation of simulated line reserves.
84    pub achieved_spearman: Vec<f64>,
85    /// Row-major `K × K` empirical Pearson correlation of simulated line reserves.
86    pub achieved_pearson: Vec<f64>,
87    /// Count of rejected joint iterations (any line failing refit rejects the joint draw).
88    pub failed_iterations: usize,
89}
90
91// ===========================================================================
92// Normal Quantile (Acklam 2003, max relative error < 1.15e-9)
93// ===========================================================================
94
95/// Inverse standard normal CDF `Φ^{-1}(p)` for `p ∈ (0, 1)`.
96pub(crate) fn inv_normal_cdf(p: f64) -> f64 {
97    const A: [f64; 6] = [
98        -3.969_683_028_665_376e1,
99        2.209_460_984_245_205e2,
100        -2.759_285_104_469_687e2,
101        1.383_577_518_672_69e2,
102        -3.066_479_806_614_716e1,
103        2.506_628_277_459_239e0,
104    ];
105    const B: [f64; 5] = [
106        -5.447_609_879_822_406e1,
107        1.615_858_368_580_409e2,
108        -1.556_989_798_598_866e2,
109        6.680_131_188_771_972e1,
110        -1.328_068_155_288_572e1,
111    ];
112    const C: [f64; 6] = [
113        -7.784_894_002_430_293e-3,
114        -3.223_964_580_411_365e-1,
115        -2.400_758_277_161_838e0,
116        -2.549_732_539_343_734e0,
117        4.374_664_141_464_968e0,
118        2.938_163_982_698_783e0,
119    ];
120    const D: [f64; 4] = [
121        7.784_695_709_041_462e-3,
122        3.224_671_290_700_398e-1,
123        2.445_134_137_142_996e0,
124        3.754_408_661_907_416e0,
125    ];
126    const P_LOW: f64 = 0.02425;
127    const P_HIGH: f64 = 1.0 - P_LOW;
128
129    if p < P_LOW {
130        let q = (-2.0 * p.ln()).sqrt();
131        (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
132            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
133    } else if p <= P_HIGH {
134        let q = p - 0.5;
135        let r = q * q;
136        (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q
137            / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0)
138    } else {
139        let q = (-2.0 * (1.0 - p).ln()).sqrt();
140        -(((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5])
141            / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0)
142    }
143}
144
145// ===========================================================================
146// Correlation Matrix Helpers (Pearson & Tie-Adjusted Spearman)
147// ===========================================================================
148
149/// Compute tie-adjusted average ranks (1-based midranks) for a slice.
150pub(crate) fn average_ranks(values: &[f64]) -> Vec<f64> {
151    let n = values.len();
152    let mut order: Vec<usize> = (0..n).collect();
153    order.sort_unstable_by(|&a, &b| values[a].total_cmp(&values[b]));
154
155    let mut ranks = vec![0.0; n];
156    let mut i = 0;
157    while i < n {
158        let mut j = i + 1;
159        while j < n && values[order[j]] == values[order[i]] {
160            j += 1;
161        }
162        // 1-based midrank for indices i..j is (i + 1 + j) / 2.
163        let avg_rank = f64::midpoint((i + 1) as f64, j as f64);
164        for &idx in &order[i..j] {
165            ranks[idx] = avg_rank;
166        }
167        i = j;
168    }
169    ranks
170}
171
172/// Sample Pearson correlation between two equal-length slices.
173pub fn pearson_correlation(x: &[f64], y: &[f64]) -> f64 {
174    let n = x.len();
175    if n < 2 || n != y.len() {
176        return f64::NAN;
177    }
178    let nf = n as f64;
179    let mx = x.iter().sum::<f64>() / nf;
180    let my = y.iter().sum::<f64>() / nf;
181    let mut sxx = 0.0;
182    let mut syy = 0.0;
183    let mut sxy = 0.0;
184    for (&a, &b) in x.iter().zip(y.iter()) {
185        let dx = a - mx;
186        let dy = b - my;
187        sxx += dx * dx;
188        syy += dy * dy;
189        sxy += dx * dy;
190    }
191    let denom = (sxx * syy).sqrt();
192    if denom > 0.0 {
193        (sxy / denom).clamp(-1.0, 1.0)
194    } else {
195        f64::NAN
196    }
197}
198
199/// Tie-adjusted Spearman rank correlation between two equal-length slices.
200pub fn spearman_correlation(x: &[f64], y: &[f64]) -> f64 {
201    if x.len() < 2 || x.len() != y.len() {
202        return f64::NAN;
203    }
204    if x.iter().any(|v| v.is_nan()) || y.iter().any(|v| v.is_nan()) {
205        return f64::NAN;
206    }
207    let rx = average_ranks(x);
208    let ry = average_ranks(y);
209    pearson_correlation(&rx, &ry)
210}
211
212fn correlation_matrix(columns: &[Vec<f64>], spearman: bool) -> Vec<f64> {
213    let k = columns.len();
214    let mut out = vec![0.0; k * k];
215    let ranked: Vec<Vec<f64>> = if spearman {
216        columns.iter().map(|c| average_ranks(c)).collect()
217    } else {
218        Vec::new()
219    };
220    let slice_at = |idx: usize| -> &[f64] {
221        if spearman {
222            &ranked[idx]
223        } else {
224            &columns[idx]
225        }
226    };
227
228    // Precompute column means and inverse norms once so each pair is a single dot product.
229    let mut means = vec![0.0; k];
230    let mut inv_norms = vec![0.0; k];
231    for i in 0..k {
232        let col = slice_at(i);
233        let nf = col.len() as f64;
234        let m = col.iter().sum::<f64>() / nf;
235        means[i] = m;
236        let ss: f64 = col.iter().map(|&v| (v - m) * (v - m)).sum();
237        inv_norms[i] = if ss > 0.0 { 1.0 / ss.sqrt() } else { f64::NAN };
238    }
239
240    for i in 0..k {
241        out[i * k + i] = 1.0;
242        let ci = slice_at(i);
243        let mi = means[i];
244        let ni = inv_norms[i];
245        for j in (i + 1)..k {
246            let cj = slice_at(j);
247            let mj = means[j];
248            let nj = inv_norms[j];
249            let r = if ni.is_finite() && nj.is_finite() {
250                let mut sxy = 0.0;
251                for (&a, &b) in ci.iter().zip(cj.iter()) {
252                    sxy += (a - mi) * (b - mj);
253                }
254                (sxy * ni * nj).clamp(-1.0, 1.0)
255            } else {
256                f64::NAN
257            };
258            out[i * k + j] = r;
259            out[j * k + i] = r;
260        }
261    }
262    out
263}
264
265/// Solve `U * x = b` where `U` is upper-triangular (represented as `L^T` from
266/// lower-triangular `l` of size `dim × dim`).
267fn solve_upper_from_lower_transpose(l: &[f64], dim: usize, b: &[f64]) -> Vec<f64> {
268    let mut x = vec![0.0; dim];
269    for i in (0..dim).rev() {
270        let mut sum = b[i];
271        for j in (i + 1)..dim {
272            // U[i, j] = L[j, i].
273            sum -= l[j * dim + i] * x[j];
274        }
275        x[i] = sum / l[i * dim + i];
276    }
277    x
278}
279
280fn validate_and_convert_correlation_matrix(
281    target_corr: &[f64],
282    k: usize,
283    corr_type: CorrelationType,
284) -> Result<Vec<f64>, ValidationError> {
285    if target_corr.len() != k * k {
286        return Err(ValidationError::ShapeMismatch);
287    }
288    let mut s = vec![0.0; k * k];
289    for i in 0..k {
290        for j in 0..k {
291            let v = target_corr[i * k + j];
292            if !v.is_finite() {
293                return Err(ValidationError::NotFinite);
294            }
295            if i == j {
296                if (v - 1.0).abs() > 1e-10 {
297                    return Err(ValidationError::InvalidParameter(
298                        "correlation matrix diagonal entries must equal 1.0",
299                    ));
300                }
301                s[i * k + j] = 1.0;
302            } else {
303                let sym = target_corr[j * k + i];
304                if (v - sym).abs() > 1e-10 {
305                    return Err(ValidationError::InvalidParameter(
306                        "correlation matrix must be symmetric",
307                    ));
308                }
309                if !(-1.0..=1.0).contains(&v) {
310                    return Err(ValidationError::InvalidParameter(
311                        "correlation matrix entries must lie in [-1, 1]",
312                    ));
313                }
314                s[i * k + j] = match corr_type {
315                    CorrelationType::LatentGaussian => v,
316                    CorrelationType::SpearmanTarget => 2.0 * (PI * v / 6.0).sin(),
317                    CorrelationType::KendallTarget => (PI * v / 2.0).sin(),
318                };
319            }
320        }
321    }
322    Ok(s)
323}
324
325// ===========================================================================
326// Iman–Conover (1982) / Mildenhall (2006) Batch Rank Permutation
327// ===========================================================================
328
329/// Apply Iman–Conover (1982) batch rank reordering following Mildenhall (2006,
330/// CAS Winter Forum, pp. 43–50).
331///
332/// * Preserves each column's empirical marginal multiset **exactly**.
333/// * Induces the positive-definite target correlation matrix `target_corr`
334///   (row-major `K × K`) on van der Waerden normal reference scores without
335///   explicitly inverting triangular Cholesky factors (`F · A = C`).
336/// * Returns whole-scenario [`ImanConoverResult::permutations`] so callers can
337///   move full multi-origin / multi-layer scenario structures coherently.
338pub fn iman_conover(
339    columns: &[&[f64]],
340    target_corr: &[f64],
341    corr_type: CorrelationType,
342    seed: u64,
343) -> Result<ImanConoverResult, ValidationError> {
344    let k = columns.len();
345    if k < 2 {
346        return Err(ValidationError::InvalidParameter(
347            "Iman-Conover requires at least 2 variables",
348        ));
349    }
350    let n = columns[0].len();
351    if n <= k {
352        return Err(ValidationError::InvalidParameter(
353            "Iman-Conover requires more scenarios than variables (N > K)",
354        ));
355    }
356    for col in columns {
357        if col.len() != n {
358            return Err(ValidationError::ShapeMismatch);
359        }
360        if col.iter().any(|v| !v.is_finite()) {
361            return Err(ValidationError::NotFinite);
362        }
363    }
364
365    let s = validate_and_convert_correlation_matrix(target_corr, k, corr_type)?;
366    // S = L_S * L_S^T => upper-triangular C = L_S^T satisfies S = C^T * C.
367    let l_s = cholesky_lower(&s, k)?;
368
369    // Build centered, unit-variance van der Waerden normal scores.
370    let mut base_scores: Vec<f64> = (0..n)
371        .map(|r| inv_normal_cdf((r as f64 + 1.0) / (n as f64 + 1.0)))
372        .collect();
373    let mean_z = base_scores.iter().sum::<f64>() / n as f64;
374    let var_z = base_scores
375        .iter()
376        .map(|z| (z - mean_z).powi(2))
377        .sum::<f64>()
378        / (n as f64 - 1.0);
379    let sd_z = var_z.sqrt();
380    for z in &mut base_scores {
381        *z = (*z - mean_z) / sd_z;
382    }
383
384    // Construct shuffled N × K score matrix M with positive-definite empirical correlation E.
385    let mut rng = DeterministicRng::from_seed(seed);
386    let mut m_cols: Vec<Vec<f64>> = Vec::with_capacity(k);
387    let mut l_e_opt = None;
388    for _attempt in 0..16 {
389        m_cols.clear();
390        for _ in 0..k {
391            let mut col = base_scores.clone();
392            // Fisher–Yates shuffle.
393            for i in (1..n).rev() {
394                let j = rng.next_index(i + 1);
395                col.swap(i, j);
396            }
397            m_cols.push(col);
398        }
399        let e = correlation_matrix(&m_cols, false);
400        if let Ok(l_e) = cholesky_lower(&e, k) {
401            l_e_opt = Some(l_e);
402            break;
403        }
404    }
405    let l_e = l_e_opt.ok_or(ValidationError::InvalidParameter(
406        "failed to generate full-rank normal score matrix E",
407    ))?;
408
409    // Solve F * A = C column-by-column where F = L_E^T and C = L_S^T.
410    // Store A column-major as a_cols[j][i] = A[i, j].
411    let mut a_cols: Vec<Vec<f64>> = Vec::with_capacity(k);
412    for col_j in 0..k {
413        let mut c_col = vec![0.0; k];
414        for row_i in 0..=col_j {
415            // C[row_i, col_j] = L_S[col_j, row_i].
416            c_col[row_i] = l_s[col_j * k + row_i];
417        }
418        a_cols.push(solve_upper_from_lower_transpose(&l_e, k, &c_col));
419    }
420
421    // Form T = M * A and reorder each input column to match the rank order of T[:, col].
422    let mut permutations = Vec::with_capacity(k);
423    let mut reordered_columns = Vec::with_capacity(k);
424    let mut t_col = vec![0.0; n];
425    let mut t_order: Vec<usize> = (0..n).collect();
426    let mut val_order: Vec<usize> = (0..n).collect();
427
428    for col_j in 0..k {
429        let a_col = &a_cols[col_j];
430        t_col.fill(0.0);
431        for p in 0..k {
432            let ap = a_col[p];
433            if ap != 0.0 {
434                for (dst, &mp) in t_col.iter_mut().zip(m_cols[p].iter()) {
435                    *dst += mp * ap;
436                }
437            }
438        }
439
440        for (idx, slot) in t_order.iter_mut().enumerate() {
441            *slot = idx;
442        }
443        t_order.sort_unstable_by(|&a, &b| t_col[a].total_cmp(&t_col[b]));
444
445        let col_vals = columns[col_j];
446        for (idx, slot) in val_order.iter_mut().enumerate() {
447            *slot = idx;
448        }
449        val_order.sort_unstable_by(|&a, &b| col_vals[a].total_cmp(&col_vals[b]));
450        // Randomly break ties within equal-value runs to avoid inheriting original row order.
451        let mut tie_start = 0usize;
452        while tie_start < n {
453            let v0 = col_vals[val_order[tie_start]];
454            let mut tie_end = tie_start + 1;
455            while tie_end < n && col_vals[val_order[tie_end]] == v0 {
456                tie_end += 1;
457            }
458            if tie_end - tie_start > 1 {
459                for m in (tie_start + 1..tie_end).rev() {
460                    let swap_idx = tie_start + rng.next_index(m - tie_start + 1);
461                    val_order.swap(m, swap_idx);
462                }
463            }
464            tie_start = tie_end;
465        }
466
467        let mut perm = vec![0usize; n];
468        let mut reordered = vec![0.0; n];
469        for rank_idx in 0..n {
470            let dst_row = t_order[rank_idx];
471            let src_row = val_order[rank_idx];
472            perm[dst_row] = src_row;
473            reordered[dst_row] = col_vals[src_row];
474        }
475        permutations.push(perm);
476        reordered_columns.push(reordered);
477    }
478
479    let achieved_spearman = correlation_matrix(&reordered_columns, true);
480    let achieved_pearson = correlation_matrix(&reordered_columns, false);
481
482    Ok(ImanConoverResult {
483        n_scenarios: n,
484        n_variables: k,
485        permutations,
486        reordered_columns,
487        effective_latent_correlation: s,
488        achieved_spearman,
489        achieved_pearson,
490    })
491}
492
493// ===========================================================================
494// Synchronized Multi-Line ODP Bootstrap (Kirschner, Kerley & Isaacs 2002)
495// ===========================================================================
496
497/// Run a synchronized multi-line ODP bootstrap across `K >= 2` aligned loss
498/// triangles (Kirschner, Kerley & Isaacs 2002; Shapland 2016, §9).
499///
500/// On each bootstrap draw, one shared triangle coordinate resampling map is
501/// drawn and applied identically to every line, pulling each line's own
502/// adjusted Pearson residual from the same `(origin, dev)` source location.
503/// Requires identical square dimensions and aligned eligible residual pools
504/// across all lines; mismatched geometry or missing pairs fail explicitly.
505pub fn synchronized_odp_bootstrap(
506    triangles: &[TriangleView<'_>],
507    tails: &[f64],
508    options: OdpBootstrapOptions,
509) -> Result<SynchronizedBootstrapResult, ValidationError> {
510    let k = triangles.len();
511    if k < 2 {
512        return Err(ValidationError::InvalidParameter(
513            "synchronized ODP bootstrap requires at least 2 triangles",
514        ));
515    }
516    if tails.len() != k || options.iterations == 0 {
517        return Err(ValidationError::ShapeMismatch);
518    }
519
520    let n0 = triangles[0].n_origins;
521    for t in triangles {
522        if t.n_origins != n0 || t.n_devs != n0 {
523            return Err(ValidationError::ShapeMismatch);
524        }
525    }
526
527    let mut line_fits = Vec::with_capacity(k);
528    let mut pools = Vec::with_capacity(k);
529    let mut coord_signature: Option<Vec<(usize, usize)>> = None;
530
531    for (t, &tail) in triangles.iter().zip(tails.iter()) {
532        let fit = fit_odp(t, tail, options.monotonicity_policy)?;
533        let coords: Vec<(usize, usize)> = match options.residual_adjustment {
534            ResidualAdjustment::DegreesOfFreedom => {
535                fit.residuals.iter().map(|r| (r.origin, r.dev)).collect()
536            }
537            ResidualAdjustment::HatMatrixLeverage => fit
538                .residuals
539                .iter()
540                .filter(|r| !r.saturated)
541                .map(|r| (r.origin, r.dev))
542                .collect(),
543        };
544        if let Some(ref expected) = coord_signature {
545            if &coords != expected {
546                return Err(ValidationError::InvalidParameter(
547                    "synchronized bootstrap requires identical eligible residual coordinates across lines",
548                ));
549            }
550        } else {
551            coord_signature = Some(coords);
552        }
553        let (pool, _) = build_adjusted_residual_pool(
554            &fit,
555            options.residual_adjustment,
556            options.center_residuals,
557        )?;
558        line_fits.push(fit);
559        pools.push(pool);
560    }
561
562    let pool_len = pools[0].len();
563    let n_obs = line_fits[0].n_observed;
564    let mut rng = DeterministicRng::from_seed(options.seed);
565
566    let mut line_totals: Vec<Vec<f64>> = (0..k)
567        .map(|_| Vec::with_capacity(options.iterations))
568        .collect();
569    let mut aggregate_totals = Vec::with_capacity(options.iterations);
570    let mut shared_indices = vec![0usize; n_obs];
571    let mut line_residuals = vec![0.0; n_obs];
572    let mut scratches: Vec<OdpBootstrapScratch> =
573        line_fits.iter().map(OdpBootstrapScratch::for_fit).collect();
574    let mut draw_totals = vec![0.0; k];
575    let mut failed_iterations = 0usize;
576
577    for _ in 0..options.iterations {
578        for slot in &mut shared_indices {
579            *slot = rng.next_index(pool_len);
580        }
581        let mut all_ok = true;
582        for line in 0..k {
583            for (dst, &pool_idx) in line_residuals.iter_mut().zip(shared_indices.iter()) {
584                *dst = pools[line][pool_idx];
585            }
586            if let Some(origin_res) = run_odp_iteration_with_scratch(
587                &line_fits[line],
588                &line_residuals,
589                options.process_distribution,
590                &mut rng,
591                &mut scratches[line],
592            ) {
593                let tot: f64 = origin_res.iter().sum();
594                if tot.is_finite() {
595                    draw_totals[line] = tot;
596                } else {
597                    all_ok = false;
598                    break;
599                }
600            } else {
601                all_ok = false;
602                break;
603            }
604        }
605        if all_ok {
606            let agg: f64 = draw_totals.iter().sum();
607            aggregate_totals.push(agg);
608            for (line, &tot) in draw_totals.iter().enumerate() {
609                line_totals[line].push(tot);
610            }
611        } else {
612            failed_iterations += 1;
613        }
614    }
615
616    if aggregate_totals.is_empty() {
617        return Err(ValidationError::NotFinite);
618    }
619
620    let mut summary_buf = Vec::with_capacity(aggregate_totals.len());
621    let mut line_summaries = Vec::with_capacity(k);
622    for series in &line_totals {
623        line_summaries.push(summarize_with_scratch(series, &mut summary_buf, true)?);
624    }
625    let aggregate_summary = summarize_with_scratch(&aggregate_totals, &mut summary_buf, true)?;
626    let sum_standalone_sd: f64 = line_summaries.iter().map(|s| s.std_dev).sum();
627    let std_dev_diversification_benefit = sum_standalone_sd - aggregate_summary.std_dev;
628    let achieved_spearman = correlation_matrix(&line_totals, true);
629    let achieved_pearson = correlation_matrix(&line_totals, false);
630
631    Ok(SynchronizedBootstrapResult {
632        line_fits,
633        line_totals,
634        aggregate_totals,
635        line_summaries,
636        aggregate_summary,
637        std_dev_diversification_benefit,
638        achieved_spearman,
639        achieved_pearson,
640        failed_iterations,
641    })
642}
643
644#[cfg(test)]
645mod tests {
646    use super::*;
647    use crate::types::Triangle;
648
649    #[test]
650    fn iman_conover_preserves_marginals_and_induces_target_rank_correlation() {
651        let mut rng = DeterministicRng::from_seed(42069);
652        let n = 4_000usize;
653        // Skewed lognormal marginals (heterogeneous severities).
654        let x: Vec<f64> = (0..n)
655            .map(|_| (10.0 + 0.8 * rng.next_standard_normal()).exp())
656            .collect();
657        let y: Vec<f64> = (0..n)
658            .map(|_| (11.0 + 1.1 * rng.next_standard_normal()).exp())
659            .collect();
660        let z: Vec<f64> = (0..n)
661            .map(|_| (9.5 + 0.5 * rng.next_standard_normal()).exp())
662            .collect();
663
664        #[rustfmt::skip]
665        let target = [
666            1.0,  0.65, -0.30,
667            0.65, 1.0,   0.20,
668           -0.30, 0.20,  1.0,
669        ];
670
671        let res = iman_conover(
672            &[&x, &y, &z],
673            &target,
674            CorrelationType::SpearmanTarget,
675            12345,
676        )
677        .expect("iman_conover");
678
679        // Exact multiset preservation of every empirical marginal.
680        for (orig, reord) in [&x, &y, &z].iter().zip(res.reordered_columns.iter()) {
681            let mut a = (*orig).clone();
682            let mut b = reord.clone();
683            a.sort_by(f64::total_cmp);
684            b.sort_by(f64::total_cmp);
685            assert_eq!(a, b);
686        }
687
688        // Permutation coherence check: reordered[col][r] == orig[col][perm[col][r]].
689        for (col, orig) in [&x, &y, &z].iter().enumerate() {
690            for r in 0..n {
691                assert_eq!(
692                    res.reordered_columns[col][r],
693                    orig[res.permutations[col][r]]
694                );
695            }
696        }
697
698        // Achieved Spearman rank correlations match target within tight finite-sample tolerance.
699        assert!(
700            (res.achieved_spearman[1] - 0.65).abs() < 0.025,
701            "rho_01={}",
702            res.achieved_spearman[1]
703        );
704        assert!(
705            (res.achieved_spearman[2] - (-0.30)).abs() < 0.025,
706            "rho_02={}",
707            res.achieved_spearman[2]
708        );
709        assert!(
710            (res.achieved_spearman[5] - 0.20).abs() < 0.025,
711            "rho_12={}",
712            res.achieved_spearman[5]
713        );
714    }
715
716    #[test]
717    fn iman_conover_rejects_non_positive_definite_matrix() {
718        let a = [1.0, 2.0, 3.0, 4.0, 5.0];
719        let b = [2.0, 3.0, 4.0, 5.0, 6.0];
720        let c = [3.0, 4.0, 5.0, 6.0, 7.0];
721        #[rustfmt::skip]
722        let bad = [
723            1.0,  0.9,  0.9,
724            0.9,  1.0, -0.9,
725            0.9, -0.9,  1.0,
726        ];
727        assert!(matches!(
728            iman_conover(&[&a, &b, &c], &bad, CorrelationType::LatentGaussian, 1),
729            Err(ValidationError::InvalidParameter(_))
730        ));
731    }
732
733    #[test]
734    fn synchronized_bootstrap_preserves_positive_dependence_on_comonotonic_lines() {
735        const NAN: f64 = f64::NAN;
736        #[rustfmt::skip]
737        let t1 = Triangle::new(5, 5, vec![
738            1000.0, 1520.0, 1730.0, 1820.0, 1860.0,
739            1150.0, 1690.0, 1980.0, 2060.0,    NAN,
740            1320.0, 2090.0, 2320.0,    NAN,    NAN,
741            1480.0, 2110.0,    NAN,    NAN,    NAN,
742            1650.0,    NAN,    NAN,    NAN,    NAN,
743        ]);
744        // Identically scaled line -> identical residual signs -> strong positive parameter correlation.
745        let t2 = Triangle::new(
746            5,
747            5,
748            t1.data()
749                .iter()
750                .map(|v| if v.is_finite() { v * 2.0 } else { NAN })
751                .collect(),
752        );
753        let opts = OdpBootstrapOptions::shapland(400, 42069);
754        let sync = synchronized_odp_bootstrap(&[t1.view(), t2.view()], &[1.0, 1.0], opts)
755            .expect("synchronized bootstrap");
756
757        assert!(
758            sync.achieved_spearman[1] > 0.30,
759            "spearman={}",
760            sync.achieved_spearman[1]
761        );
762        assert!(sync.std_dev_diversification_benefit >= 0.0);
763    }
764}