1use ndarray::{Array1, Array2, ArrayView1, ArrayView2};
12
13use super::{
14 dml_model_api, CateSignal, LinearScoreModel, NuisanceTarget, ScoreEstimate, ScoreInput,
15};
16use crate::crossfit::{cross_fit_predict_proba, cross_fit_predict_subset, Fold, SampleSplitting};
17use crate::data::DmlData;
18use crate::error::{DmlError, Result};
19use crate::learner::{Classifier, Regressor};
20use crate::score::LinearScore;
21use crate::sensitivity::{Nu2Parts, SensitivityParts};
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum IrmScore {
26 #[default]
28 Ate,
29 Atte,
31}
32
33pub struct Irm {
37 ml_g: Box<dyn Regressor>,
38 ml_m: Box<dyn Classifier>,
39 score: IrmScore,
40 clipping_threshold: f64,
41 normalize_ipw: bool,
42 weights: Option<ScoreWeights>,
43 splitting: SampleSplitting,
44}
45
46#[derive(Debug, Clone)]
50pub(crate) struct ScoreWeights {
51 pub weights: Array1<f64>,
52 pub weights_bar: Option<Array2<f64>>,
53}
54
55impl ScoreWeights {
56 pub(crate) fn check(&self, n: usize) -> Result<()> {
57 let ok = |w: &mut dyn Iterator<Item = f64>| {
58 let (mut sum, mut all_ok) = (0.0, true);
59 for v in w {
60 all_ok &= v.is_finite() && v >= 0.0;
61 sum += v;
62 }
63 all_ok && sum > 0.0
64 };
65 if self.weights.len() != n {
66 return Err(DmlError::DimensionMismatch(format!(
67 "weights have length {}, the data {n} rows",
68 self.weights.len()
69 )));
70 }
71 if !ok(&mut self.weights.iter().copied()) {
72 return Err(DmlError::InvalidArgument(
73 "weights must be finite, non-negative and not all zero".into(),
74 ));
75 }
76 if let Some(bar) = &self.weights_bar {
77 if bar.nrows() != n || bar.ncols() == 0 {
78 return Err(DmlError::DimensionMismatch(format!(
79 "weights_bar must have shape ({n}, n_rep), got {:?}",
80 bar.dim()
81 )));
82 }
83 if !ok(&mut bar.iter().copied()) {
84 return Err(DmlError::InvalidArgument(
85 "weights_bar must be finite, non-negative and not all zero".into(),
86 ));
87 }
88 }
89 Ok(())
90 }
91
92 pub(crate) fn ate(
94 weights: Option<&ScoreWeights>,
95 n: usize,
96 rep: usize,
97 ) -> Result<(Array1<f64>, Array1<f64>)> {
98 let Some(w) = weights else {
99 return Ok((Array1::ones(n), Array1::ones(n)));
100 };
101 let bar = match &w.weights_bar {
102 None => w.weights.clone(),
103 Some(bar) if rep < bar.ncols() => bar.column(rep).to_owned(),
104 Some(bar) => {
105 return Err(DmlError::DimensionMismatch(format!(
106 "weights_bar has {} columns, one per repetition is needed (repetition {rep})",
107 bar.ncols()
108 )))
109 }
110 };
111 Ok((w.weights.clone(), bar))
112 }
113}
114
115impl Irm {
116 pub fn new(ml_g: impl Regressor + 'static, ml_m: impl Classifier + 'static) -> Self {
117 Self::from_boxed(Box::new(ml_g), Box::new(ml_m))
118 }
119
120 pub fn from_boxed(ml_g: Box<dyn Regressor>, ml_m: Box<dyn Classifier>) -> Self {
121 Self {
122 ml_g,
123 ml_m,
124 score: IrmScore::default(),
125 clipping_threshold: 1e-2,
126 normalize_ipw: false,
127 weights: None,
128 splitting: SampleSplitting::default(),
129 }
130 }
131
132 pub fn weights(mut self, weights: Array1<f64>) -> Self {
137 self.weights = Some(ScoreWeights {
138 weights,
139 weights_bar: None,
140 });
141 self
142 }
143
144 pub fn weights_with_bar(mut self, weights: Array1<f64>, weights_bar: Array2<f64>) -> Self {
147 self.weights = Some(ScoreWeights {
148 weights,
149 weights_bar: Some(weights_bar),
150 });
151 self
152 }
153
154 pub fn score(mut self, score: IrmScore) -> Self {
155 self.score = score;
156 self
157 }
158
159 pub fn clipping_threshold(mut self, t: f64) -> Self {
161 self.clipping_threshold = t;
162 self
163 }
164
165 pub fn normalize_ipw(mut self, normalize: bool) -> Self {
168 self.normalize_ipw = normalize;
169 self
170 }
171
172 dml_model_api!();
173}
174
175pub(crate) fn normalize_propensity(m: &Array1<f64>, d: &Array1<f64>) -> Array1<f64> {
178 let n = m.len() as f64;
179 let mean1 = d.iter().zip(m).map(|(&di, &mi)| di / mi).sum::<f64>() / n;
180 let mean0 = d
181 .iter()
182 .zip(m)
183 .map(|(&di, &mi)| (1.0 - di) / (1.0 - mi))
184 .sum::<f64>()
185 / n;
186 d.iter()
187 .zip(m)
188 .map(|(&di, &mi)| di * mi * mean1 + (1.0 - di) * (1.0 - (1.0 - mi) * mean0))
189 .collect()
190}
191
192impl LinearScoreModel for Irm {
193 fn name(&self) -> String {
194 match self.score {
195 IrmScore::Ate => "IRM (ATE)".into(),
196 IrmScore::Atte => "IRM (ATTE)".into(),
197 }
198 }
199
200 fn validate(&self, data: &DmlData) -> Result<()> {
201 if data.n_treat() != 1 || !data.is_binary_treatment(0) {
202 return Err(DmlError::InvalidArgument(
203 "IRM requires exactly one binary (0/1) treatment".into(),
204 ));
205 }
206 if !(self.clipping_threshold > 0.0 && self.clipping_threshold < 0.5) {
207 return Err(DmlError::InvalidArgument(
208 "clipping_threshold must be in (0, 0.5)".into(),
209 ));
210 }
211 if let Some(w) = &self.weights {
212 w.check(data.n_obs())?;
213 if self.score == IrmScore::Atte
214 && (w.weights_bar.is_some() || w.weights.iter().any(|&v| v != 0.0 && v != 1.0))
215 {
216 return Err(DmlError::InvalidArgument(
217 "with the ATTE score, weights must be 0/1 (without weights_bar)".into(),
218 ));
219 }
220 }
221 Ok(())
222 }
223
224 fn estimate_score(&self, input: &ScoreInput<'_>, folds: &[Fold]) -> Result<ScoreEstimate> {
225 let ScoreInput { y, d, x, rep, .. } = *input;
226 let (g0, g1, m) = irm_nuisances(
227 self.ml_g.as_ref(),
228 self.ml_m.as_ref(),
229 x,
230 y,
231 d,
232 folds,
233 self.clipping_threshold,
234 )?;
235 let d = d.to_owned();
236 let m_adj = if self.normalize_ipw {
237 normalize_propensity(&m, &d)
238 } else {
239 m.clone()
240 };
241 let ipw = ipw_residual(y, &d, &g0, &g1, &m_adj);
242
243 let n = d.len();
244 let (weights, weights_bar) = match self.score {
245 IrmScore::Ate => ScoreWeights::ate(self.weights.as_ref(), n, rep)?,
246 IrmScore::Atte => {
247 let w = self
249 .weights
250 .as_ref()
251 .map_or_else(|| Array1::ones(n), |w| w.weights.clone());
252 let subgroup = &w * &d;
253 let p = subgroup.mean().expect("n > 0");
254 (&subgroup / p, &m_adj * &w / p)
255 }
256 };
257 let psi_b = &weights * &(&g1 - &g0) + &weights_bar * &ipw;
258 let psi_a = -(&weights / weights.mean().expect("n > 0"));
259
260 let outcome_residual = &y - &(&d * &g1) - &(&(1.0 - &d) * &g0);
263 let m_alpha = &weights * &weights_bar * &(1.0 / &m_adj + 1.0 / &(1.0 - &m_adj));
264 let riesz = &weights_bar * &(&d / &m_adj - &(1.0 - &d) / &(1.0 - &m_adj));
265 let nu2 = 2.0 * &m_alpha - &riesz.mapv(|a| a * a);
266 let estimate = ScoreEstimate::new(
267 LinearScore::new(psi_a, psi_b.clone())?,
268 vec![("ml_g0", g0), ("ml_g1", g1), ("ml_m", m)],
269 )
270 .with_sensitivity(SensitivityParts {
271 outcome_residual,
272 theta_factor: None,
273 riesz,
274 nu2: Nu2Parts::Elementwise(nu2),
275 })
276 .with_targets(vec![
277 NuisanceTarget::regression("ml_g0", y.to_owned()).only_where(|i| d[i] == 0.0),
278 NuisanceTarget::regression("ml_g1", y.to_owned()).only_where(|i| d[i] == 1.0),
279 NuisanceTarget::classification("ml_m", d.clone()),
280 ]);
281 Ok(match self.score {
283 IrmScore::Ate => estimate.with_cate_signal(CateSignal {
284 signal: psi_b,
285 theta_factor: None,
286 basis_scale: None,
287 is_effect: true,
288 }),
289 IrmScore::Atte => estimate,
290 })
291 }
292}
293
294pub(crate) fn irm_nuisances(
297 ml_g: &dyn Regressor,
298 ml_m: &dyn Classifier,
299 x: ArrayView2<'_, f64>,
300 y: ArrayView1<'_, f64>,
301 d: ArrayView1<'_, f64>,
302 folds: &[Fold],
303 clipping_threshold: f64,
304) -> Result<(Array1<f64>, Array1<f64>, Array1<f64>)> {
305 let treated: Vec<bool> = d.iter().map(|&v| v == 1.0).collect();
306 let control: Vec<bool> = treated.iter().map(|t| !t).collect();
307 let g0 = cross_fit_predict_subset(ml_g, x, y, folds, &control)?;
308 let g1 = cross_fit_predict_subset(ml_g, x, y, folds, &treated)?;
309 let t = clipping_threshold;
310 let m = cross_fit_predict_proba(ml_m, x, d, folds)?.mapv(|p| p.clamp(t, 1.0 - t));
311 Ok((g0, g1, m))
312}
313
314pub(crate) fn ipw_residual(
317 y: ArrayView1<'_, f64>,
318 d: &Array1<f64>,
319 g0: &Array1<f64>,
320 g1: &Array1<f64>,
321 m: &Array1<f64>,
322) -> Array1<f64> {
323 let u0: Array1<f64> = &y - g0;
324 let u1: Array1<f64> = &y - g1;
325 d * &u1 / m - &(1.0 - d) * &u0 / &(1.0 - m)
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331 use crate::learner::{LogisticRegression, Ols};
332 use ndarray::{array, Array2};
333
334 #[test]
335 fn rejects_continuous_treatment_and_bad_clipping() {
336 let data = DmlData::new(
337 array![1.0, 2.0, 3.0],
338 array![0.0, 0.5, 1.0],
339 array![[1.0], [2.0], [3.0]],
340 )
341 .unwrap();
342 let irm = Irm::new(Ols::new(), LogisticRegression::default());
343 assert!(irm.fit(&data).is_err());
344 let binary =
345 DmlData::new(array![1.0, 2.0], array![0.0, 1.0], array![[1.0], [2.0]]).unwrap();
346 let bad = Irm::new(Ols::new(), LogisticRegression::default()).clipping_threshold(0.7);
347 assert!(bad.validate(&binary).is_err());
348 }
349
350 #[test]
351 fn normalized_weights_have_unit_means() {
352 let m = array![0.2, 0.5, 0.7, 0.4];
353 let d = array![1.0, 0.0, 1.0, 0.0];
354 let adj = normalize_propensity(&m, &d);
355 let n = 4.0;
356 let mean1: f64 = d.iter().zip(&adj).map(|(&a, &b)| a / b).sum::<f64>() / n;
357 let mean0: f64 = d
358 .iter()
359 .zip(&adj)
360 .map(|(&a, &b)| (1.0 - a) / (1.0 - b))
361 .sum::<f64>()
362 / n;
363 assert!((mean1 - 1.0).abs() < 1e-12 && (mean0 - 1.0).abs() < 1e-12);
364 }
365
366 #[test]
367 fn randomized_experiment_recovers_difference_in_means() {
368 let n = 200;
370 let x = Array2::from_shape_fn((n, 1), |(i, _)| ((i * 37) % 17) as f64);
371 let d: Array1<f64> = (0..n).map(|i| ((i * 7919) % 2) as f64).collect();
372 let y: Array1<f64> = (0..n).map(|i| 2.0 * d[i] + ((i * 31) % 7) as f64).collect();
373 let data = DmlData::new(y, d, x).unwrap();
374 let fit = Irm::new(Ols::new(), LogisticRegression::default())
375 .fit(&data)
376 .unwrap();
377 assert!((fit.coef()[0] - 2.0).abs() < 0.5, "ate = {}", fit.coef()[0]);
378 }
379}