1use std::borrow::Cow;
2
3use ndarray::{concatenate, Array1, Array2, ArrayView1, ArrayView2, Axis};
4
5use crate::error::{DmlError, Result};
6
7#[derive(Debug, Clone)]
18pub struct DmlData {
19 y: Array1<f64>,
20 d: Array2<f64>,
21 x: Array2<f64>,
22 z: Option<Array1<f64>>,
23 t: Option<Array1<f64>>,
24 treatment_names: Vec<String>,
25}
26
27fn all_finite<'a>(mut values: impl Iterator<Item = &'a f64>) -> bool {
28 values.all(|v| v.is_finite())
29}
30
31impl DmlData {
32 pub fn new(y: Array1<f64>, d: Array1<f64>, x: Array2<f64>) -> Result<Self> {
34 let n = d.len();
35 let d = d.into_shape_with_order((n, 1)).expect("1-D to (n, 1)");
36 Self::with_treatments(y, d, x)
37 }
38
39 pub fn with_treatments(y: Array1<f64>, d: Array2<f64>, x: Array2<f64>) -> Result<Self> {
41 let n = y.len();
42 if n < 2 {
43 return Err(DmlError::InvalidArgument(
44 "need at least 2 observations".into(),
45 ));
46 }
47 if d.nrows() != n || x.nrows() != n {
48 return Err(DmlError::DimensionMismatch(format!(
49 "y has {n} rows, d has {}, x has {}",
50 d.nrows(),
51 x.nrows()
52 )));
53 }
54 if d.ncols() == 0 {
55 return Err(DmlError::InvalidArgument(
56 "need at least one treatment".into(),
57 ));
58 }
59 if !all_finite(y.iter()) || !all_finite(d.iter()) || !all_finite(x.iter()) {
60 return Err(DmlError::InvalidArgument(
61 "data contains NaN or infinite values".into(),
62 ));
63 }
64 let treatment_names = if d.ncols() == 1 {
65 vec!["d".to_string()]
66 } else {
67 (0..d.ncols()).map(|j| format!("d{j}")).collect()
68 };
69 Ok(Self {
70 y,
71 d,
72 x,
73 z: None,
74 t: None,
75 treatment_names,
76 })
77 }
78
79 pub fn with_instrument(mut self, z: Array1<f64>) -> Result<Self> {
81 if z.len() != self.n_obs() {
82 return Err(DmlError::DimensionMismatch(format!(
83 "z has {} rows, expected {}",
84 z.len(),
85 self.n_obs()
86 )));
87 }
88 if !all_finite(z.iter()) {
89 return Err(DmlError::InvalidArgument(
90 "instrument contains NaN or infinite values".into(),
91 ));
92 }
93 self.z = Some(z);
94 Ok(self)
95 }
96
97 pub fn with_time_indicator(mut self, t: Array1<f64>) -> Result<Self> {
100 if t.len() != self.n_obs() {
101 return Err(DmlError::DimensionMismatch(format!(
102 "t has {} rows, expected {}",
103 t.len(),
104 self.n_obs()
105 )));
106 }
107 if !is_binary(t.view()) {
108 return Err(DmlError::InvalidArgument(
109 "time indicator must contain only 0 and 1".into(),
110 ));
111 }
112 self.t = Some(t);
113 Ok(self)
114 }
115
116 pub fn with_treatment_names<S: Into<String>>(
118 mut self,
119 names: impl IntoIterator<Item = S>,
120 ) -> Result<Self> {
121 let names: Vec<String> = names.into_iter().map(Into::into).collect();
122 if names.len() != self.n_treat() {
123 return Err(DmlError::DimensionMismatch(format!(
124 "{} names for {} treatments",
125 names.len(),
126 self.n_treat()
127 )));
128 }
129 self.treatment_names = names;
130 Ok(self)
131 }
132
133 pub fn n_obs(&self) -> usize {
134 self.y.len()
135 }
136
137 pub fn n_features(&self) -> usize {
138 self.x.ncols()
139 }
140
141 pub fn n_treat(&self) -> usize {
142 self.d.ncols()
143 }
144
145 pub fn y(&self) -> ArrayView1<'_, f64> {
146 self.y.view()
147 }
148
149 pub fn d(&self) -> ArrayView2<'_, f64> {
151 self.d.view()
152 }
153
154 pub fn treatment(&self, j: usize) -> ArrayView1<'_, f64> {
156 self.d.column(j)
157 }
158
159 pub fn x(&self) -> ArrayView2<'_, f64> {
160 self.x.view()
161 }
162
163 pub fn z(&self) -> Option<ArrayView1<'_, f64>> {
164 self.z.as_ref().map(|z| z.view())
165 }
166
167 pub fn time(&self) -> Option<ArrayView1<'_, f64>> {
169 self.t.as_ref().map(|t| t.view())
170 }
171
172 pub fn treatment_names(&self) -> &[String] {
173 &self.treatment_names
174 }
175
176 pub fn covariates_for(&self, j: usize) -> Cow<'_, Array2<f64>> {
181 if self.n_treat() == 1 {
182 return Cow::Borrowed(&self.x);
183 }
184 let others: Vec<usize> = (0..self.n_treat()).filter(|&k| k != j).collect();
185 let d_other = self.d.select(Axis(1), &others);
186 Cow::Owned(concatenate![Axis(1), self.x, d_other])
187 }
188
189 pub fn is_binary_treatment(&self, j: usize) -> bool {
191 is_binary(self.d.column(j))
192 }
193}
194
195pub(crate) fn is_binary(v: ArrayView1<'_, f64>) -> bool {
197 v.iter().all(|&x| x == 0.0 || x == 1.0)
198}
199
200pub(crate) fn gather(v: ArrayView1<'_, f64>, idx: &[usize]) -> Array1<f64> {
202 idx.iter().map(|&i| v[i]).collect()
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use ndarray::array;
209
210 #[test]
211 fn rejects_mismatched_lengths() {
212 let err = DmlData::new(array![1.0, 2.0], array![0.0], array![[1.0], [2.0]]).unwrap_err();
213 assert!(matches!(err, DmlError::DimensionMismatch(_)));
214 }
215
216 #[test]
217 fn rejects_nan() {
218 let err = DmlData::new(
219 array![1.0, f64::NAN],
220 array![0.0, 1.0],
221 array![[1.0], [2.0]],
222 )
223 .unwrap_err();
224 assert!(matches!(err, DmlError::InvalidArgument(_)));
225 }
226
227 #[test]
228 fn detects_binary_treatment() {
229 let data = DmlData::new(array![1.0, 2.0], array![0.0, 1.0], array![[1.0], [2.0]]).unwrap();
230 assert!(data.is_binary_treatment(0));
231 }
232
233 #[test]
234 fn other_treatments_become_covariates() {
235 let d = array![[1.0, 10.0, 100.0], [2.0, 20.0, 200.0]];
236 let data = DmlData::with_treatments(array![0.0, 1.0], d, array![[5.0], [6.0]]).unwrap();
237 assert_eq!(data.treatment_names(), ["d0", "d1", "d2"]);
238 assert_eq!(
239 *data.covariates_for(1),
240 array![[5.0, 1.0, 100.0], [6.0, 2.0, 200.0]]
241 );
242 assert!(matches!(data.covariates_for(0), Cow::Owned(_)));
243 }
244
245 #[test]
246 fn time_indicator_must_be_binary() {
247 let data = DmlData::new(array![1.0, 2.0], array![0.0, 1.0], array![[1.0], [2.0]]).unwrap();
248 assert!(data.clone().with_time_indicator(array![0.0, 2.0]).is_err());
249 assert!(data.clone().with_time_indicator(array![1.0]).is_err());
250 assert!(data
251 .with_time_indicator(array![0.0, 1.0])
252 .unwrap()
253 .time()
254 .is_some());
255 }
256
257 #[test]
258 fn instrument_length_checked() {
259 let data = DmlData::new(array![1.0, 2.0], array![0.0, 1.0], array![[1.0], [2.0]]).unwrap();
260 assert!(data.clone().with_instrument(array![1.0]).is_err());
261 assert!(data
262 .with_instrument(array![1.0, 0.0])
263 .unwrap()
264 .z()
265 .is_some());
266 }
267}