Skip to main content

dml_core/
fit.rs

1//! The shared DML driver and its result type, [`DmlFit`].
2
3use std::fmt;
4
5use ndarray::{Array1, Array2, Array3, ArrayView1, ArrayView2, ArrayView3, Axis};
6
7use crate::blp::Blp;
8use crate::cluster::{derive_test_clusters, ClusterFold, ClusterInfo};
9use crate::crossfit::Fold;
10use crate::data::DmlData;
11use crate::error::{DmlError, Result};
12use crate::model::{CateSignal, LinearScoreModel, LossKind, ScoreInput};
13use crate::policy::PolicyTree;
14use crate::sensitivity::SensitivityStore;
15use crate::stats::{median, norm_ppf, norm_sf};
16
17/// Fit any [`LinearScoreModel`] on the given sample splits (one `Vec<Fold>`
18/// per repetition): for every repetition and treatment, cross-fit the
19/// nuisances, solve the DML2 score and estimate the standard error; then
20/// aggregate over repetitions.
21///
22/// (`?Sized` lets this accept trait objects such as `&dyn LinearScoreModel`
23/// as well as concrete models.)
24pub fn fit_model<M: LinearScoreModel + ?Sized>(
25    model: &M,
26    data: &DmlData,
27    splits: &[Vec<Fold>],
28) -> Result<DmlFit> {
29    // With clustered data, the test clusters of each fold are read off its test rows.
30    let cluster = match data.clusters() {
31        Some(c) => Some(ClusterInfo::new(
32            c.to_vec(),
33            splits
34                .iter()
35                .map(|rep| {
36                    rep.iter()
37                        .map(|f| ClusterFold {
38                            fold: f.clone(),
39                            test_clusters: derive_test_clusters(c, f),
40                        })
41                        .collect()
42                })
43                .collect(),
44        )?),
45        None => None,
46    };
47    fit_model_impl(model, data, splits, cluster)
48}
49
50/// Fit on clustered data with explicit cluster folds (one `Vec<ClusterFold>`
51/// per repetition), e.g. to reproduce another implementation exactly.
52pub fn fit_model_clustered<M: LinearScoreModel + ?Sized>(
53    model: &M,
54    data: &DmlData,
55    splits: &[Vec<ClusterFold>],
56) -> Result<DmlFit> {
57    let clusters = data.clusters().ok_or_else(|| {
58        DmlError::InvalidArgument(
59            "cluster folds need clustered data: use DmlData::with_clusters".into(),
60        )
61    })?;
62    let folds: Vec<Vec<Fold>> = splits
63        .iter()
64        .map(|rep| rep.iter().map(|cf| cf.fold.clone()).collect())
65        .collect();
66    let cluster = ClusterInfo::new(clusters.to_vec(), splits.to_vec())?;
67    fit_model_impl(model, data, &folds, Some(cluster))
68}
69
70fn fit_model_impl<M: LinearScoreModel + ?Sized>(
71    model: &M,
72    data: &DmlData,
73    splits: &[Vec<Fold>],
74    cluster: Option<ClusterInfo>,
75) -> Result<DmlFit> {
76    model.validate(data)?;
77    let n = data.n_obs();
78    check_splits(splits, n)?;
79    let (k, n_rep) = (data.n_treat(), splits.len());
80
81    let mut all_coef = Array2::<f64>::zeros((k, n_rep));
82    let mut all_se = Array2::<f64>::zeros((k, n_rep));
83    let mut psi = Array3::<f64>::zeros((n, k, n_rep));
84    let mut psi_deriv = Array2::<f64>::zeros((k, n_rep));
85    let mut psi_a = Array3::<f64>::zeros((n, k, n_rep));
86    let mut psi_b = Array3::<f64>::zeros((n, k, n_rep));
87    let mut predictions: Vec<(String, Array3<f64>)> = Vec::new();
88    // Population variance of y, for sensitivity benchmarks.
89    let y_mean = data.y().mean().expect("n > 0");
90    let var_y = data
91        .y()
92        .mapv(|v| (v - y_mean).powi(2))
93        .mean()
94        .expect("n > 0");
95    let mut sensitivity = Some(SensitivityStore::new(n, k, n_rep, var_y));
96    let mut cate = Some(CateStore {
97        signal: Array3::zeros((n, k, n_rep)),
98        scale: None,
99        is_effect: true,
100    });
101    let mut losses: Vec<NuisanceLoss> = Vec::new();
102
103    for j in 0..k {
104        let x_j = data.covariates_for(j);
105        for (r, folds) in splits.iter().enumerate() {
106            let input = ScoreInput {
107                y: data.y(),
108                d: data.treatment(j),
109                x: x_j.view(),
110                z: data.z(),
111                t: data.time(),
112                rep: r,
113            };
114            let est = model.estimate_score(&input, folds)?;
115            let mut sol = est.score.solve()?;
116            if let Some(ci) = &cluster {
117                // Fold-weighted estimate and cluster-robust variance; ψ is
118                // scaled by the plain mean of ψ_a elsewhere, as in DoubleML.
119                let theta = ci.solve_theta(&est.score, r)?;
120                let psi_r = &est.score.psi_a * theta + &est.score.psi_b;
121                let sigma2 = ci.variance(psi_r.view(), est.score.psi_a.view(), r);
122                sol.theta = theta;
123                sol.se = sigma2.sqrt();
124                sol.psi = psi_r;
125            }
126            if !(sol.theta.is_finite() && sol.se.is_finite()) {
127                return Err(DmlError::InvalidArgument(format!(
128                    "non-finite estimate for treatment {j}, repetition {r}"
129                )));
130            }
131            all_coef[[j, r]] = sol.theta;
132            all_se[[j, r]] = sol.se;
133            psi_deriv[[j, r]] = sol.j;
134            psi.slice_mut(ndarray::s![.., j, r]).assign(&sol.psi);
135            psi_a
136                .slice_mut(ndarray::s![.., j, r])
137                .assign(&est.score.psi_a);
138            psi_b
139                .slice_mut(ndarray::s![.., j, r])
140                .assign(&est.score.psi_b);
141            for target in &est.targets {
142                let Some((_, pred)) = est.predictions.iter().find(|(nm, _)| *nm == target.name)
143                else {
144                    continue;
145                };
146                let slot = match losses.iter().position(|l| l.name == target.name) {
147                    Some(i) => i,
148                    None => {
149                        losses.push(NuisanceLoss {
150                            name: target.name.to_string(),
151                            kind: target.kind,
152                            loss: Array2::from_elem((k, n_rep), f64::NAN),
153                            targets: Array3::from_elem((n, n_rep, k), f64::NAN),
154                        });
155                        losses.len() - 1
156                    }
157                };
158                losses[slot].loss[[j, r]] = target.loss(pred);
159                losses[slot]
160                    .targets
161                    .slice_mut(ndarray::s![.., r, j])
162                    .assign(&target.target);
163            }
164            match (&est.sensitivity, &mut sensitivity) {
165                (Some(parts), Some(store)) => store.set(j, r, &parts.elements(sol.theta)),
166                _ => sensitivity = None,
167            }
168            match (&est.cate, &mut cate) {
169                (Some(c), Some(store)) => store.set(j, r, c, sol.theta),
170                _ => cate = None,
171            }
172            for (name, pred) in est.predictions {
173                let slot = match predictions.iter().position(|(nm, _)| nm == name) {
174                    Some(i) => i,
175                    None => {
176                        predictions
177                            .push((name.to_string(), Array3::from_elem((n, n_rep, k), f64::NAN)));
178                        predictions.len() - 1
179                    }
180                };
181                predictions[slot]
182                    .1
183                    .slice_mut(ndarray::s![.., r, j])
184                    .assign(&pred);
185            }
186        }
187    }
188
189    let (coef, se) = aggregate(&all_coef, &all_se);
190    Ok(DmlFit {
191        model: model.name(),
192        treatment_names: data.treatment_names().to_vec(),
193        n_obs: n,
194        n_folds: splits[0].len(),
195        coef,
196        se,
197        all_coef,
198        all_se,
199        psi,
200        psi_a,
201        psi_b,
202        psi_deriv,
203        predictions,
204        sensitivity,
205        cate,
206        losses,
207        cluster,
208    })
209}
210
211/// Signal (and basis scale) for CATE / GATE inference, per treatment and
212/// repetition, shape `(n, k, n_rep)`.
213#[derive(Debug, Clone)]
214pub(crate) struct CateStore {
215    pub signal: Array3<f64>,
216    pub scale: Option<Array3<f64>>,
217    pub is_effect: bool,
218}
219
220impl CateStore {
221    fn set(&mut self, j: usize, r: usize, c: &CateSignal, theta: f64) {
222        let signal = match &c.theta_factor {
223            Some(f) => &c.signal - &(theta * f),
224            None => c.signal.clone(),
225        };
226        self.signal.slice_mut(ndarray::s![.., j, r]).assign(&signal);
227        self.is_effect &= c.is_effect;
228        if let Some(scale) = &c.basis_scale {
229            let dim = self.signal.dim();
230            self.scale
231                .get_or_insert_with(|| Array3::zeros(dim))
232                .slice_mut(ndarray::s![.., j, r])
233                .assign(scale);
234        }
235    }
236}
237
238/// Out-of-sample loss of one nuisance learner, per treatment and repetition.
239#[derive(Debug, Clone)]
240pub(crate) struct NuisanceLoss {
241    pub name: String,
242    pub kind: LossKind,
243    /// Shape `(k, n_rep)`.
244    pub loss: Array2<f64>,
245    /// Targets, shape `(n, n_rep, k)`; `NaN` where the nuisance does not apply.
246    pub targets: Array3<f64>,
247}
248
249fn check_splits(splits: &[Vec<Fold>], n: usize) -> Result<()> {
250    if splits.is_empty() {
251        return Err(DmlError::InvalidArgument("no sample splits given".into()));
252    }
253    for (r, folds) in splits.iter().enumerate() {
254        let mut seen = vec![false; n];
255        for fold in folds {
256            for &i in &fold.test {
257                if i >= n || seen[i] {
258                    return Err(DmlError::InvalidArgument(format!(
259                        "repetition {r}: test sets must partition 0..{n}"
260                    )));
261                }
262                seen[i] = true;
263            }
264            if fold.train.iter().any(|&i| i >= n) {
265                return Err(DmlError::InvalidArgument(format!(
266                    "repetition {r}: training index out of range"
267                )));
268            }
269        }
270        if seen.iter().any(|s| !s) {
271            return Err(DmlError::InvalidArgument(format!(
272                "repetition {r}: test sets must partition 0..{n}"
273            )));
274        }
275    }
276    Ok(())
277}
278
279/// DoubleML's aggregation over repetitions: median coefficient, and the
280/// standard error implied by the median of the upper bounds `θ_r + 1.96·se_r`.
281pub(crate) fn aggregate(
282    all_coef: &Array2<f64>,
283    all_se: &Array2<f64>,
284) -> (Array1<f64>, Array1<f64>) {
285    const CRIT: f64 = 1.96;
286    let k = all_coef.nrows();
287    let mut coef = Array1::zeros(k);
288    let mut se = Array1::zeros(k);
289    for j in 0..k {
290        let c = all_coef.row(j);
291        coef[j] = median(&c.to_vec());
292        let upper: Vec<f64> = c
293            .iter()
294            .zip(all_se.row(j))
295            .map(|(&t, &s)| t + CRIT * s)
296            .collect();
297        se[j] = (median(&upper) - coef[j]) / CRIT;
298    }
299    (coef, se)
300}
301
302/// Multiple-testing adjustment for [`DmlFit::p_adjust`].
303#[derive(Debug, Clone, Copy, PartialEq, Eq)]
304pub enum PAdjust {
305    Bonferroni,
306    /// Holm's step-down procedure.
307    Holm,
308}
309
310/// A fitted DML model: estimates, standard errors and the per-repetition
311/// scores and nuisance predictions behind them.
312///
313/// Arrays indexed by treatment have length `k = n_treat`; per-repetition
314/// arrays have shape `(k, n_rep)`.
315#[derive(Debug, Clone)]
316pub struct DmlFit {
317    pub(crate) model: String,
318    pub(crate) treatment_names: Vec<String>,
319    pub(crate) n_obs: usize,
320    pub(crate) n_folds: usize,
321    pub(crate) coef: Array1<f64>,
322    pub(crate) se: Array1<f64>,
323    pub(crate) all_coef: Array2<f64>,
324    pub(crate) all_se: Array2<f64>,
325    /// Shape `(n, k, n_rep)`.
326    pub(crate) psi: Array3<f64>,
327    /// Score elements, shape `(n, k, n_rep)`.
328    pub(crate) psi_a: Array3<f64>,
329    pub(crate) psi_b: Array3<f64>,
330    /// `J = mean(ψ_a)`, shape `(k, n_rep)`.
331    pub(crate) psi_deriv: Array2<f64>,
332    /// Each array has shape `(n, n_rep, k)`.
333    pub(crate) predictions: Vec<(String, Array3<f64>)>,
334    /// Sensitivity elements, for models that support sensitivity analysis.
335    pub(crate) sensitivity: Option<SensitivityStore>,
336    /// Signal for CATE / GATE inference, for models that support it.
337    pub(crate) cate: Option<CateStore>,
338    /// Out-of-sample losses of the nuisance learners.
339    pub(crate) losses: Vec<NuisanceLoss>,
340    /// Cluster structure, for clustered data.
341    pub(crate) cluster: Option<ClusterInfo>,
342}
343
344impl DmlFit {
345    pub fn model_name(&self) -> &str {
346        &self.model
347    }
348
349    pub fn treatment_names(&self) -> &[String] {
350        &self.treatment_names
351    }
352
353    pub fn n_obs(&self) -> usize {
354        self.n_obs
355    }
356
357    pub fn n_treat(&self) -> usize {
358        self.coef.len()
359    }
360
361    pub fn n_rep(&self) -> usize {
362        self.all_coef.ncols()
363    }
364
365    pub fn n_folds(&self) -> usize {
366        self.n_folds
367    }
368
369    /// Number of clusters (two-way: the smaller dimension) for a clustered
370    /// fit, `None` otherwise.
371    pub fn n_clusters(&self) -> Option<usize> {
372        self.cluster.as_ref().map(ClusterInfo::n_clusters)
373    }
374
375    /// Point estimates θ̂ (median over repetitions).
376    pub fn coef(&self) -> ArrayView1<'_, f64> {
377        self.coef.view()
378    }
379
380    /// Standard errors (aggregated over repetitions).
381    pub fn se(&self) -> ArrayView1<'_, f64> {
382        self.se.view()
383    }
384
385    pub fn t_stat(&self) -> Array1<f64> {
386        &self.coef / &self.se
387    }
388
389    /// Two-sided p-values for `H0: θ = 0` from the aggregated t-statistic,
390    /// as DoubleML's `pval`. (Multiple-testing adjustments in
391    /// [`p_adjust`](Self::p_adjust) instead take the median over repetitions.)
392    pub fn p_value(&self) -> Array1<f64> {
393        self.t_stat().mapv(|t| 2.0 * norm_sf(t.abs()))
394    }
395
396    fn per_rep_pvals(&self) -> Array2<f64> {
397        let mut p = &self.all_coef / &self.all_se;
398        p.mapv_inplace(|t| 2.0 * norm_sf(t.abs()));
399        p
400    }
401
402    /// Pointwise Wald confidence intervals at `level`, shape `(k, 2)`
403    /// (median over repetitions of each repetition's interval).
404    pub fn confint(&self, level: f64) -> Result<Array2<f64>> {
405        check_level(level)?;
406        let z = norm_ppf(0.5 + level / 2.0);
407        Ok(confint_from(
408            &self.all_coef,
409            &self.all_se,
410            &Array1::from_elem(self.n_rep(), z),
411        ))
412    }
413
414    /// Multiple-testing adjusted p-values across treatments (applied per
415    /// repetition, then the median is taken). For the bootstrap-based
416    /// Romano–Wolf procedure see [`Bootstrap::romano_wolf`](crate::Bootstrap::romano_wolf).
417    pub fn p_adjust(&self, method: PAdjust) -> Array1<f64> {
418        let raw = self.per_rep_pvals();
419        let mut adjusted = Array2::<f64>::zeros(raw.raw_dim());
420        for (r, col) in raw.columns().into_iter().enumerate() {
421            let adj = match method {
422                PAdjust::Bonferroni => {
423                    let m = col.len() as f64;
424                    col.mapv(|p| (m * p).min(1.0))
425                }
426                PAdjust::Holm => holm(col),
427            };
428            adjusted.column_mut(r).assign(&adj);
429        }
430        adjusted
431            .rows()
432            .into_iter()
433            .map(|row| median(&row.to_vec()))
434            .collect()
435    }
436
437    /// Estimates for every repetition, shape `(k, n_rep)`.
438    pub fn all_coef(&self) -> ArrayView2<'_, f64> {
439        self.all_coef.view()
440    }
441
442    pub fn all_se(&self) -> ArrayView2<'_, f64> {
443        self.all_se.view()
444    }
445
446    /// Score values ψ at θ̂, shape `(n, k, n_rep)`.
447    pub fn psi(&self) -> ArrayView3<'_, f64> {
448        self.psi.view()
449    }
450
451    /// Score elements `ψ_a` and `ψ_b` (ψ = ψ_a·θ + ψ_b), shape `(n, k, n_rep)`.
452    pub fn psi_elements(&self) -> (ArrayView3<'_, f64>, ArrayView3<'_, f64>) {
453        (self.psi_a.view(), self.psi_b.view())
454    }
455
456    /// Best linear predictor of the CATE on `basis` (shape `(n, p)`, include a
457    /// constant column for an intercept), with HC0 inference (Semenova and
458    /// Chernozhukov, 2021), as DoubleML's `cate`. Available for a single
459    /// treatment of [`Plr`](crate::Plr) (outcome residual on the basis scaled by
460    /// the treatment residual), [`Irm`](crate::Irm) with the ATE score and
461    /// [`Apo`](crate::Apo) (orthogonal signal on the basis).
462    pub fn cate(&self, basis: ArrayView2<'_, f64>) -> Result<Blp> {
463        let (signal, bases) = self.cate_inputs(basis)?;
464        Blp::fit_bases(signal.view(), &bases)
465    }
466
467    /// Group average treatment effects for mutually exclusive groups given as
468    /// 0/1 dummy columns (shape `(n, n_groups)`), as DoubleML's `gate`.
469    pub fn gate(&self, groups: ArrayView2<'_, f64>) -> Result<Blp> {
470        let (signal, bases) = self.cate_inputs(groups)?;
471        Blp::fit_gate_bases(signal.view(), groups, &bases)
472    }
473
474    /// Policy tree recommending treatment where the estimated effect is
475    /// positive, as DoubleML's `policy_tree` (for [`Irm`](crate::Irm) with the
476    /// ATE score, one treatment and one repetition). DoubleML's defaults:
477    /// `depth = 2`, `min_samples_leaf = 8`, `ccp_alpha = 0.01`.
478    pub fn policy_tree(
479        &self,
480        features: ArrayView2<'_, f64>,
481        depth: usize,
482        min_samples_leaf: usize,
483        ccp_alpha: f64,
484    ) -> Result<PolicyTree> {
485        let store = self.cate.as_ref().filter(|c| c.is_effect).ok_or_else(|| {
486            DmlError::InvalidArgument(format!(
487                "policy trees need a treatment-effect signal (IRM with the ATE score), not {}",
488                self.model
489            ))
490        })?;
491        if self.n_treat() != 1 || self.n_rep() != 1 {
492            return Err(DmlError::InvalidArgument(
493                "policy trees need a single treatment and one repetition (as DoubleML)".into(),
494            ));
495        }
496        if features.nrows() != self.n_obs {
497            return Err(DmlError::DimensionMismatch(format!(
498                "features have {} rows, the data {}",
499                features.nrows(),
500                self.n_obs
501            )));
502        }
503        PolicyTree::fit(
504            store.signal.slice(ndarray::s![.., 0, 0]),
505            features,
506            depth,
507            min_samples_leaf,
508            ccp_alpha,
509        )
510    }
511
512    /// The signal of every repetition and the matching (scaled) bases.
513    fn cate_inputs(&self, basis: ArrayView2<'_, f64>) -> Result<(Array2<f64>, Vec<Array2<f64>>)> {
514        let store = self.cate.as_ref().ok_or_else(|| {
515            DmlError::InvalidArgument(format!(
516                "CATE / GATE are not available for {} (PLR, IRM with the ATE score and APO support them)",
517                self.model
518            ))
519        })?;
520        if self.n_treat() != 1 {
521            return Err(DmlError::InvalidArgument(
522                "CATE / GATE need a single treatment".into(),
523            ));
524        }
525        if basis.nrows() != self.n_obs {
526            return Err(DmlError::DimensionMismatch(format!(
527                "basis has {} rows, the data {}",
528                basis.nrows(),
529                self.n_obs
530            )));
531        }
532        let signal = store.signal.index_axis(Axis(1), 0).to_owned();
533        let bases = (0..self.n_rep())
534            .map(|r| match &store.scale {
535                Some(scale) => {
536                    let s = scale.slice(ndarray::s![.., 0, r]);
537                    &basis * &s.insert_axis(Axis(1))
538                }
539                None => basis.to_owned(),
540            })
541            .collect();
542        Ok((signal, bases))
543    }
544
545    /// Out-of-sample loss of a nuisance learner, shape `(n_treat, n_rep)`:
546    /// RMSE for regression learners, log loss for classifiers (DoubleML's
547    /// `nuisance_loss`). Computed on the rows where the nuisance applies.
548    pub fn nuisance_loss(&self, name: &str) -> Option<ArrayView2<'_, f64>> {
549        self.losses
550            .iter()
551            .find(|l| l.name == name)
552            .map(|l| l.loss.view())
553    }
554
555    /// `(name, loss kind, losses)` for every evaluated nuisance learner.
556    pub fn nuisance_losses(&self) -> impl Iterator<Item = (&str, LossKind, ArrayView2<'_, f64>)> {
557        self.losses
558            .iter()
559            .map(|l| (l.name.as_str(), l.kind, l.loss.view()))
560    }
561
562    /// Targets of a nuisance learner, shape `(n, n_rep, n_treat)`, with `NaN`
563    /// where the nuisance does not apply (to evaluate custom metrics).
564    pub fn nuisance_targets(&self, name: &str) -> Option<ArrayView3<'_, f64>> {
565        self.losses
566            .iter()
567            .find(|l| l.name == name)
568            .map(|l| l.targets.view())
569    }
570
571    /// Names of the stored nuisance predictions (e.g. `ml_l`, `ml_m`).
572    pub fn nuisance_names(&self) -> impl Iterator<Item = &str> {
573        self.predictions.iter().map(|(n, _)| n.as_str())
574    }
575
576    /// All predictions of one nuisance, shape `(n, n_rep, k)`.
577    pub fn predictions(&self, name: &str) -> Option<ArrayView3<'_, f64>> {
578        self.predictions
579            .iter()
580            .find(|(n, _)| n == name)
581            .map(|(_, p)| p.view())
582    }
583
584    /// Out-of-fold predictions of one nuisance for a repetition and treatment.
585    pub fn prediction(&self, name: &str, rep: usize, treatment: usize) -> Option<Array1<f64>> {
586        let p = self.predictions(name)?;
587        (rep < self.n_rep() && treatment < self.n_treat())
588            .then(|| p.index_axis(Axis(2), treatment).column(rep).to_owned())
589    }
590}
591
592/// Per-repetition intervals `θ_r ± crit_r · se_r`, aggregated by the median
593/// over repetitions (DoubleML's convention). Shape `(k, 2)`.
594pub(crate) fn confint_from(
595    all_coef: &Array2<f64>,
596    all_se: &Array2<f64>,
597    crit: &Array1<f64>,
598) -> Array2<f64> {
599    let (k, n_rep) = all_coef.dim();
600    let mut ci = Array2::zeros((k, 2));
601    for j in 0..k {
602        let lo: Vec<f64> = (0..n_rep)
603            .map(|r| all_coef[[j, r]] - crit[r] * all_se[[j, r]])
604            .collect();
605        let hi: Vec<f64> = (0..n_rep)
606            .map(|r| all_coef[[j, r]] + crit[r] * all_se[[j, r]])
607            .collect();
608        ci[[j, 0]] = median(&lo);
609        ci[[j, 1]] = median(&hi);
610    }
611    ci
612}
613
614impl DmlFit {
615    /// Assemble a fit from per-repetition estimates and score elements that
616    /// are already laid out over all `n` units (zero for units a sub-model did
617    /// not use). Standard errors follow DoubleML: `J = mean(ψ_a)` and
618    /// `se = √(mean(ψ²) / J² / n)` over all `n` units.
619    #[allow(clippy::too_many_arguments)]
620    pub(crate) fn from_scores(
621        model: String,
622        treatment_names: Vec<String>,
623        n_folds: usize,
624        all_coef: Array2<f64>,
625        psi: Array3<f64>,
626        psi_a: Array3<f64>,
627        psi_b: Array3<f64>,
628        predictions: Vec<(String, Array3<f64>)>,
629    ) -> Self {
630        let (n, k, n_rep) = psi.dim();
631        let mut psi_deriv = Array2::<f64>::zeros((k, n_rep));
632        let mut all_se = Array2::<f64>::zeros((k, n_rep));
633        for j in 0..k {
634            for r in 0..n_rep {
635                let jac = psi_a.slice(ndarray::s![.., j, r]).sum() / n as f64;
636                let col = psi.slice(ndarray::s![.., j, r]);
637                psi_deriv[[j, r]] = jac;
638                all_se[[j, r]] = (col.dot(&col) / n as f64 / (jac * jac) / n as f64).sqrt();
639            }
640        }
641        let (coef, se) = aggregate(&all_coef, &all_se);
642        Self {
643            model,
644            treatment_names,
645            n_obs: n,
646            n_folds,
647            coef,
648            se,
649            all_coef,
650            all_se,
651            psi,
652            psi_a,
653            psi_b,
654            psi_deriv,
655            predictions,
656            sensitivity: None,
657            cate: None,
658            losses: Vec::new(),
659            cluster: None,
660        }
661    }
662
663    /// Linear combinations `Σ_j w_cj θ_j` of this fit's estimates (one row of
664    /// `weights` per combination), with influence functions combined the same
665    /// way, so correlation between the estimates is accounted for.
666    pub(crate) fn linear_combination(
667        &self,
668        model: String,
669        names: Vec<String>,
670        weights: &Array2<f64>,
671    ) -> Self {
672        let (n, k, n_rep) = self.psi.dim();
673        assert_eq!(weights.ncols(), k, "one weight per estimate");
674        let n_comb = weights.nrows();
675        let mut scaled = Array3::<f64>::zeros((n, n_comb, n_rep));
676        let mut all_coef = Array2::<f64>::zeros((n_comb, n_rep));
677        let mut all_se = Array2::<f64>::zeros((n_comb, n_rep));
678        for r in 0..n_rep {
679            for c in 0..n_comb {
680                let mut col = Array1::<f64>::zeros(n);
681                let mut theta = 0.0;
682                for j in 0..k {
683                    let w = weights[[c, j]];
684                    if w != 0.0 {
685                        col.scaled_add(
686                            w / self.psi_deriv[[j, r]],
687                            &self.psi.slice(ndarray::s![.., j, r]),
688                        );
689                        theta += w * self.all_coef[[j, r]];
690                    }
691                }
692                all_coef[[c, r]] = theta;
693                all_se[[c, r]] = match &self.cluster {
694                    // The combined influence function is already scaled (J = 1).
695                    Some(ci) => ci.variance(col.view(), Array1::ones(n).view(), r).sqrt(),
696                    None => (col.dot(&col) / n as f64 / n as f64).sqrt(),
697                };
698                scaled.slice_mut(ndarray::s![.., c, r]).assign(&col);
699            }
700        }
701        let (coef, se) = aggregate(&all_coef, &all_se);
702        Self {
703            model,
704            treatment_names: names,
705            n_obs: n,
706            n_folds: self.n_folds,
707            coef,
708            se,
709            all_coef,
710            all_se,
711            // Influence functions are stored already scaled (J = 1); the score
712            // elements are zero so CATE methods correctly refuse this fit.
713            psi: scaled,
714            psi_a: Array3::zeros((n, n_comb, n_rep)),
715            psi_b: Array3::zeros((n, n_comb, n_rep)),
716            psi_deriv: Array2::ones((n_comb, n_rep)),
717            predictions: Vec::new(),
718            sensitivity: None,
719            cate: None,
720            losses: Vec::new(),
721            cluster: self.cluster.clone(),
722        }
723    }
724
725    /// Stack fits of the same data and sample splits into one fit with all
726    /// their estimates (DoubleML's `concat`), for joint inference: the
727    /// bootstrap, simultaneous confidence bands and linear combinations then
728    /// account for the correlation between the estimates.
729    ///
730    /// Predictions and learner losses are stacked by nuisance name (`NaN` where
731    /// a fit has no such nuisance); sensitivity elements are kept if every fit
732    /// has them.
733    pub fn concat(fits: &[DmlFit]) -> Result<DmlFit> {
734        let first = fits
735            .first()
736            .ok_or_else(|| DmlError::InvalidArgument("concat needs at least one fit".into()))?;
737        let (n, n_rep) = (first.n_obs, first.n_rep());
738        for f in fits {
739            if f.n_obs != n || f.n_rep() != n_rep || f.n_folds != first.n_folds {
740                return Err(DmlError::DimensionMismatch(
741                    "concat needs fits with the same observations, folds and repetitions".into(),
742                ));
743            }
744            let same_clusters = match (&f.cluster, &first.cluster) {
745                (None, None) => true,
746                (Some(a), Some(b)) => a.clusters == b.clusters && a.folds == b.folds,
747                _ => false,
748            };
749            if !same_clusters {
750                return Err(DmlError::InvalidArgument(
751                    "concat needs the same clusters and cluster splits in every fit".into(),
752                ));
753            }
754        }
755        let cat1 = |f: fn(&DmlFit) -> &Array1<f64>| {
756            let v: Vec<_> = fits.iter().map(|x| f(x).view()).collect();
757            ndarray::concatenate(Axis(0), &v).expect("1-D")
758        };
759        let cat2 = |f: fn(&DmlFit) -> &Array2<f64>| {
760            let v: Vec<_> = fits.iter().map(|x| f(x).view()).collect();
761            ndarray::concatenate(Axis(0), &v).expect("same n_rep")
762        };
763        let cat3 = |f: fn(&DmlFit) -> &Array3<f64>| {
764            let v: Vec<_> = fits.iter().map(|x| f(x).view()).collect();
765            ndarray::concatenate(Axis(1), &v).expect("same n and n_rep")
766        };
767        let ks: Vec<usize> = fits.iter().map(DmlFit::n_treat).collect();
768        let k_total: usize = ks.iter().sum();
769
770        // Stack per-nuisance arrays (shape (n, n_rep, k)); NaN where absent.
771        let mut predictions: Vec<(String, Array3<f64>)> = Vec::new();
772        let mut losses: Vec<NuisanceLoss> = Vec::new();
773        let mut offset = 0;
774        for (f, &k) in fits.iter().zip(&ks) {
775            for (name, pred) in &f.predictions {
776                let slot = match predictions.iter().position(|(nm, _)| nm == name) {
777                    Some(i) => i,
778                    None => {
779                        predictions.push((
780                            name.clone(),
781                            Array3::from_elem((n, n_rep, k_total), f64::NAN),
782                        ));
783                        predictions.len() - 1
784                    }
785                };
786                predictions[slot]
787                    .1
788                    .slice_mut(ndarray::s![.., .., offset..offset + k])
789                    .assign(pred);
790            }
791            for l in &f.losses {
792                let slot = match losses.iter().position(|x| x.name == l.name) {
793                    Some(i) => i,
794                    None => {
795                        losses.push(NuisanceLoss {
796                            name: l.name.clone(),
797                            kind: l.kind,
798                            loss: Array2::from_elem((k_total, n_rep), f64::NAN),
799                            targets: Array3::from_elem((n, n_rep, k_total), f64::NAN),
800                        });
801                        losses.len() - 1
802                    }
803                };
804                losses[slot]
805                    .loss
806                    .slice_mut(ndarray::s![offset..offset + k, ..])
807                    .assign(&l.loss);
808                losses[slot]
809                    .targets
810                    .slice_mut(ndarray::s![.., .., offset..offset + k])
811                    .assign(&l.targets);
812            }
813            offset += k;
814        }
815        let stores: Option<Vec<&SensitivityStore>> =
816            fits.iter().map(|f| f.sensitivity.as_ref()).collect();
817        // CATE signals stack if every fit has one and all or none scale the basis.
818        let cates: Option<Vec<&CateStore>> = fits.iter().map(|f| f.cate.as_ref()).collect();
819        let cate_store = cates.and_then(|c| {
820            let views: Vec<_> = c.iter().map(|s| s.signal.view()).collect();
821            let signal = ndarray::concatenate(Axis(1), &views).ok()?;
822            let scales: Option<Vec<_>> = c
823                .iter()
824                .map(|s| s.scale.as_ref().map(|a| a.view()))
825                .collect();
826            let is_effect = c.iter().all(|s| s.is_effect);
827            match scales {
828                Some(v) => Some(CateStore {
829                    signal,
830                    scale: Some(ndarray::concatenate(Axis(1), &v).ok()?),
831                    is_effect,
832                }),
833                None if c.iter().all(|s| s.scale.is_none()) => Some(CateStore {
834                    signal,
835                    scale: None,
836                    is_effect,
837                }),
838                None => None,
839            }
840        });
841        let names: Vec<&str> = fits.iter().map(|f| f.model.as_str()).collect();
842        Ok(DmlFit {
843            model: if names.iter().all(|m| *m == names[0]) {
844                names[0].to_string()
845            } else {
846                names.join(" + ")
847            },
848            treatment_names: fits
849                .iter()
850                .flat_map(|f| f.treatment_names.iter().cloned())
851                .collect(),
852            n_obs: n,
853            n_folds: first.n_folds,
854            coef: cat1(|f| &f.coef),
855            se: cat1(|f| &f.se),
856            all_coef: cat2(|f| &f.all_coef),
857            all_se: cat2(|f| &f.all_se),
858            psi: cat3(|f| &f.psi),
859            psi_a: cat3(|f| &f.psi_a),
860            psi_b: cat3(|f| &f.psi_b),
861            psi_deriv: cat2(|f| &f.psi_deriv),
862            predictions,
863            sensitivity: stores.map(|s| SensitivityStore::concat(&s)),
864            cate: cate_store,
865            losses,
866            cluster: first.cluster.clone(),
867        })
868    }
869}
870
871pub(crate) fn check_level(level: f64) -> Result<()> {
872    if level > 0.0 && level < 1.0 {
873        Ok(())
874    } else {
875        Err(DmlError::InvalidArgument(
876            "confidence level must be in (0, 1)".into(),
877        ))
878    }
879}
880
881/// Holm step-down adjustment (as `statsmodels.multipletests(method="holm")`).
882fn holm(p: ArrayView1<'_, f64>) -> Array1<f64> {
883    let m = p.len();
884    let mut order: Vec<usize> = (0..m).collect();
885    order.sort_by(|&a, &b| p[a].total_cmp(&p[b]));
886    let mut out = Array1::zeros(m);
887    let mut running = 0.0_f64;
888    for (rank, &i) in order.iter().enumerate() {
889        running = running.max(((m - rank) as f64 * p[i]).min(1.0));
890        out[i] = running;
891    }
892    out
893}
894
895impl fmt::Display for DmlFit {
896    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
897        let clustering = match &self.cluster {
898            Some(ci) if ci.n_ways() == 2 => {
899                format!(", two-way clustered ({} clusters)", ci.n_clusters())
900            }
901            Some(ci) => format!(", clustered ({} clusters)", ci.n_clusters()),
902            None => String::new(),
903        };
904        writeln!(
905            f,
906            "{}  |  n_obs = {}, n_folds = {}, n_rep = {}{clustering}",
907            self.model,
908            self.n_obs,
909            self.n_folds,
910            self.n_rep()
911        )?;
912        let ci = self.confint(0.95).map_err(|_| fmt::Error)?;
913        let (t, p) = (self.t_stat(), self.p_value());
914        let width = self
915            .treatment_names
916            .iter()
917            .map(String::len)
918            .max()
919            .unwrap_or(1)
920            .max(4);
921        write!(
922            f,
923            "{:<width$} {:>10} {:>10} {:>8} {:>8} {:>10} {:>10}",
924            "", "coef", "std err", "t", "P>|t|", "2.5 %", "97.5 %"
925        )?;
926        for j in 0..self.n_treat() {
927            write!(
928                f,
929                "\n{:<width$} {:>10.4} {:>10.4} {:>8.3} {:>8.4} {:>10.4} {:>10.4}",
930                self.treatment_names[j],
931                self.coef[j],
932                self.se[j],
933                t[j],
934                p[j],
935                ci[[j, 0]],
936                ci[[j, 1]]
937            )?;
938        }
939        if !self.losses.is_empty() {
940            write!(
941                f,
942                "\nNuisance learners (out-of-sample, mean over repetitions):"
943            )?;
944            for l in &self.losses {
945                let metric = match l.kind {
946                    LossKind::Rmse => "RMSE",
947                    LossKind::LogLoss => "log loss",
948                };
949                for j in 0..self.n_treat() {
950                    let row: Vec<f64> = l
951                        .loss
952                        .row(j)
953                        .iter()
954                        .copied()
955                        .filter(|v| v.is_finite())
956                        .collect();
957                    if row.is_empty() {
958                        continue;
959                    }
960                    let mean = row.iter().sum::<f64>() / row.len() as f64;
961                    let who = if self.n_treat() > 1 {
962                        format!(" ({})", self.treatment_names[j])
963                    } else {
964                        String::new()
965                    };
966                    write!(f, "\n  {:<12} {metric:<8} {mean:.4}{who}", l.name)?;
967                }
968            }
969        }
970        Ok(())
971    }
972}
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977    use ndarray::array;
978
979    #[test]
980    fn aggregation_matches_doubleml_definition() {
981        let coef = array![[1.0, 2.0, 4.0]];
982        let se = array![[0.5, 0.1, 0.2]];
983        let (c, s) = aggregate(&coef, &se);
984        assert_eq!(c[0], 2.0);
985        // upper bounds: 1.98, 2.196, 4.392 → median 2.196
986        assert!((s[0] - (2.196 - 2.0) / 1.96).abs() < 1e-12);
987    }
988
989    #[test]
990    fn holm_matches_statsmodels() {
991        // statsmodels.multipletests([0.01, 0.04, 0.03], method="holm")[1]
992        let adj = holm(array![0.01, 0.04, 0.03].view());
993        assert_eq!(adj, array![0.03, 0.06, 0.06]);
994    }
995}