1use ndarray::{Array1, Array2, Array3, ArrayView3, Axis};
5use rand::{Rng, SeedableRng};
6use rand_chacha::ChaCha8Rng;
7use rand_distr::{Exp1, StandardNormal};
8
9use crate::error::{DmlError, Result};
10use crate::fit::{check_level, confint_from, DmlFit};
11use crate::stats::{median, quantile_mut};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum BootstrapMethod {
16 #[default]
18 Normal,
19 Bayes,
21 Wild,
23}
24
25pub fn draw_weights(
27 method: BootstrapMethod,
28 n_boot: usize,
29 n: usize,
30 rng: &mut impl Rng,
31) -> Array2<f64> {
32 let shape = (n_boot, n);
33 match method {
34 BootstrapMethod::Normal => {
35 Array2::from_shape_simple_fn(shape, || rng.sample(StandardNormal))
36 }
37 BootstrapMethod::Bayes => {
38 Array2::from_shape_simple_fn(shape, || rng.sample::<f64, _>(Exp1) - 1.0)
39 }
40 BootstrapMethod::Wild => Array2::from_shape_simple_fn(shape, || {
41 let a: f64 = rng.sample(StandardNormal);
42 let b: f64 = rng.sample(StandardNormal);
43 a / std::f64::consts::SQRT_2 + (b * b - 1.0) / 2.0
44 }),
45 }
46}
47
48#[derive(Debug, Clone)]
53pub struct Bootstrap {
54 all_coef: Array2<f64>,
55 all_se: Array2<f64>,
56 t_stats: Array3<f64>,
58}
59
60impl DmlFit {
61 pub fn bootstrap(
64 &self,
65 method: BootstrapMethod,
66 n_boot: usize,
67 seed: u64,
68 ) -> Result<Bootstrap> {
69 if n_boot == 0 {
70 return Err(DmlError::InvalidArgument("n_boot must be positive".into()));
71 }
72 let mut rng = ChaCha8Rng::seed_from_u64(seed);
73 let weights: Vec<Array2<f64>> = (0..self.n_rep())
74 .map(|_| draw_weights(method, n_boot, self.n_obs, &mut rng))
75 .collect();
76 self.bootstrap_with_weights(&weights)
77 }
78
79 pub fn bootstrap_with_weights(&self, weights: &[Array2<f64>]) -> Result<Bootstrap> {
82 if weights.len() != self.n_rep() {
83 return Err(DmlError::DimensionMismatch(format!(
84 "{} weight matrices for {} repetitions",
85 weights.len(),
86 self.n_rep()
87 )));
88 }
89 let n_boot = weights[0].nrows();
90 let (n, k) = (self.n_obs, self.n_treat());
91 let mut t_stats = Array3::<f64>::zeros((n_boot, k, self.n_rep()));
92 for (r, w) in weights.iter().enumerate() {
93 if w.dim() != (n_boot, n) {
94 return Err(DmlError::DimensionMismatch(
95 "every weight matrix must be (n_boot, n_obs)".into(),
96 ));
97 }
98 let mut scaled = self.psi.index_axis(Axis(2), r).to_owned();
100 for j in 0..k {
101 let denom = self.psi_deriv[[j, r]] * n as f64 * self.all_se[[j, r]];
102 scaled.column_mut(j).mapv_inplace(|v| v / denom);
103 }
104 t_stats.index_axis_mut(Axis(2), r).assign(&w.dot(&scaled));
105 }
106 Ok(Bootstrap {
107 all_coef: self.all_coef.clone(),
108 all_se: self.all_se.clone(),
109 t_stats,
110 })
111 }
112}
113
114impl Bootstrap {
115 pub fn t_stats(&self) -> ArrayView3<'_, f64> {
117 self.t_stats.view()
118 }
119
120 pub fn critical_values(&self, level: f64) -> Result<Array1<f64>> {
122 check_level(level)?;
123 Ok(self
124 .t_stats
125 .axis_iter(Axis(2))
126 .map(|rep| {
127 let mut max_abs: Vec<f64> = rep
128 .rows()
129 .into_iter()
130 .map(|row| row.iter().fold(0.0_f64, |m, v| m.max(v.abs())))
131 .collect();
132 quantile_mut(&mut max_abs, level)
133 })
134 .collect())
135 }
136
137 pub fn joint_confint(&self, level: f64) -> Result<Array2<f64>> {
140 Ok(confint_from(
141 &self.all_coef,
142 &self.all_se,
143 &self.critical_values(level)?,
144 ))
145 }
146
147 pub fn romano_wolf(&self) -> Array1<f64> {
149 let (k, n_rep) = self.all_coef.dim();
150 let mut all = Array2::<f64>::zeros((k, n_rep));
151 for r in 0..n_rep {
152 let boot = self.t_stats.index_axis(Axis(2), r);
153 let abs_t: Vec<f64> = (0..k)
154 .map(|j| (self.all_coef[[j, r]] / self.all_se[[j, r]]).abs())
155 .collect();
156 let mut order: Vec<usize> = (0..k).collect();
158 order.sort_by(|&a, &b| abs_t[b].total_cmp(&abs_t[a]));
159 let mut running = 0.0_f64;
160 for (step, &j) in order.iter().enumerate() {
161 let remaining = &order[step..];
162 let exceed = boot
163 .rows()
164 .into_iter()
165 .filter(|row| {
166 remaining.iter().fold(0.0_f64, |m, &i| m.max(row[i].abs())) >= abs_t[j]
167 })
168 .count();
169 let p = (exceed as f64 / boot.nrows() as f64).min(1.0);
170 running = running.max(p);
171 all[[j, r]] = running;
172 }
173 }
174 all.rows()
175 .into_iter()
176 .map(|row| median(&row.to_vec()))
177 .collect()
178 }
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 #[test]
186 fn weights_have_mean_zero_unit_variance() {
187 let mut rng = ChaCha8Rng::seed_from_u64(1);
188 for method in [
189 BootstrapMethod::Normal,
190 BootstrapMethod::Bayes,
191 BootstrapMethod::Wild,
192 ] {
193 let w = draw_weights(method, 200, 500, &mut rng);
194 let mean = w.mean().unwrap();
195 let var = w.mapv(|v| (v - mean).powi(2)).mean().unwrap();
196 assert!(mean.abs() < 0.02, "{method:?} mean {mean}");
197 assert!((var - 1.0).abs() < 0.03, "{method:?} var {var}");
198 }
199 }
200}