[6ac965]: / catenets / experiment_utils / simulation_utils.py

Download this file

323 lines (274 with data), 8.9 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""
Simulation utils, allowing to flexibly consider different DGPs
"""
# Author: Alicia Curth
from typing import Any, Optional, Tuple
import numpy as np
from scipy.special import expit
def simulate_treatment_setup(
n: int,
d: int = 25,
n_w: int = 0,
n_c: int = 0,
n_o: int = 0,
n_t: int = 0,
covariate_model: Any = None,
covariate_model_params: Optional[dict] = None,
propensity_model: Any = None,
propensity_model_params: Optional[dict] = None,
mu_0_model: Any = None,
mu_0_model_params: Optional[dict] = None,
mu_1_model: Any = None,
mu_1_model_params: Optional[dict] = None,
error_sd: float = 1,
seed: int = 42,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""
Generic function to flexibly simulate a treatment setup.
Parameters
----------
n: int
Number of observations to generate
d: int
dimension of X to generate
n_o: int
Dimension of outcome-factor
n_c: int
Dimension of confounding factor
n_t: int
Dimension of purely predictive variables (support of tau(x)
n_w: int
Dimension of treatment assignment factor
covariate_model:
Model to generate covariates. Default: multivariate normal
covariate_model_params: dict
Additional parameters to pass to covariate model
propensity_model:
Model to generate propensity scores
propensity_model_params:
Additional parameters to pass to propensity model
mu_0_model:
Model to generate untreated outcomes
mu_0_model_params:
Additional parameters to pass to untreated outcome model
mu_1_model:
Model to generate treated outcomes.
mu_1_model_params:
Additional parameters to pass to treated outcome model
error_sd: float, default 1
Standard deviation of normal errors
seed: int
Seed
Returns
-------
X, y, w, p, t - Covariates, observed outcomes, treatment indicators, propensities, CATE
"""
# input checks
n_nuisance = d - (n_c + n_o + n_w + n_t)
if n_nuisance < 0:
raise ValueError("Dimensions should add up to maximally d.")
# set defaults
if covariate_model is None:
covariate_model = normal_covariate_model
if covariate_model_params is None:
covariate_model_params = {}
if propensity_model is None:
propensity_model = propensity_AISTATS
if propensity_model_params is None:
propensity_model_params = {}
if mu_0_model is None:
mu_0_model = mu0_AISTATS
if mu_0_model_params is None:
mu_0_model_params = {}
if mu_1_model is None:
mu_1_model = mu1_AISTATS
if mu_1_model_params is None:
mu_1_model_params = {}
np.random.seed(seed)
# generate data and outcomes
X = covariate_model(
n=n,
n_nuisance=n_nuisance,
n_c=n_c,
n_o=n_o,
n_w=n_w,
n_t=n_t,
**covariate_model_params
)
mu_0 = mu_0_model(X, n_c=n_c, n_o=n_o, n_w=n_w, **mu_0_model_params)
mu_1 = mu_1_model(
X, n_c=n_c, n_o=n_o, n_w=n_w, n_t=n_t, mu_0=mu_0, **mu_1_model_params
)
t = mu_1 - mu_0
# generate treatments
p = propensity_model(X, n_c=n_c, n_w=n_w, **propensity_model_params)
w = np.random.binomial(1, p=p)
# generate observables
y = w * mu_1 + (1 - w) * mu_0 + np.random.normal(0, error_sd, n)
return X, y, w, p, t
# normal covariate model (Adapted from Hassanpour & Greiner, 2020) -------------
def get_multivariate_normal_params(
m: int, correlated: bool = False
) -> Tuple[np.ndarray, np.ndarray]:
# Adapted from Hassanpour & Greiner (2020)
if correlated:
mu = np.zeros(m) # np.random.normal(size=m)/10
temp = np.random.uniform(size=(m, m))
temp = 0.5 * (np.transpose(temp) + temp)
sig = (np.ones((m, m)) - np.eye(m)) * temp / 10 + 0.5 * np.eye(
m
) # (temp + m * np.eye(m)) / 10
else:
mu = np.zeros(m)
sig = np.eye(m)
return mu, sig
def get_set_normal_covariates(m: int, n: int, correlated: bool = False) -> np.ndarray:
if m == 0:
return
mu, sig = get_multivariate_normal_params(m, correlated=correlated)
return np.random.multivariate_normal(mean=mu, cov=sig, size=n)
def normal_covariate_model(
n: int,
n_nuisance: int = 25,
n_c: int = 0,
n_o: int = 0,
n_w: int = 0,
n_t: int = 0,
correlated: bool = False,
) -> np.ndarray:
X_stack: Tuple = ()
for n_x in [n_w, n_c, n_o, n_t, n_nuisance]:
if n_x > 0:
X_stack = (*X_stack, get_set_normal_covariates(n_x, n, correlated))
return np.hstack(X_stack)
def propensity_AISTATS(
X: np.ndarray,
n_c: int = 0,
n_w: int = 0,
xi: float = 0.5,
nonlinear: bool = True,
offset: Any = 0,
target_prop: Optional[np.ndarray] = None,
) -> np.ndarray:
if n_c + n_w == 0:
# constant propensity
return xi * np.ones(X.shape[0])
else:
coefs = np.ones(n_c + n_w)
if nonlinear:
z = np.dot(X[:, : (n_c + n_w)] ** 2, coefs) / (n_c + n_w)
else:
z = np.dot(X[:, : (n_c + n_w)], coefs) / (n_c + n_w)
if type(offset) is float or type(offset) is int:
prop = expit(xi * z + offset)
if target_prop is not None:
avg_prop = np.average(prop)
prop = target_prop / avg_prop * prop
return prop
elif offset == "center":
# center the propensity scores to median 0.5
prop = expit(xi * (z - np.median(z)))
if target_prop is not None:
avg_prop = np.average(prop)
prop = target_prop / avg_prop * prop
return prop
else:
raise ValueError("Not a valid value for offset")
def propensity_constant(
X: np.ndarray, n_c: int = 0, n_w: int = 0, xi: float = 0.5
) -> np.ndarray:
return xi * np.ones(X.shape[0])
def mu0_AISTATS(
X: np.ndarray, n_w: int = 0, n_c: int = 0, n_o: int = 0, scale: bool = False
) -> np.ndarray:
if n_c + n_o == 0:
return np.zeros((X.shape[0]))
else:
if not scale:
coefs = np.ones(n_c + n_o)
else:
coefs = 10 * np.ones(n_c + n_o) / (n_c + n_o)
return np.dot(X[:, n_w : (n_w + n_c + n_o)] ** 2, coefs)
def mu1_AISTATS(
X: np.ndarray,
n_w: int = 0,
n_c: int = 0,
n_o: int = 0,
n_t: int = 0,
mu_0: Optional[np.ndarray] = None,
nonlinear: int = 2,
withbase: bool = True,
scale: bool = False,
) -> np.ndarray:
if n_t == 0:
return mu_0
# use additive effect
else:
if scale:
coefs = 10 * np.ones(n_t) / n_t
else:
coefs = np.ones(n_t)
X_sel = X[:, (n_w + n_c + n_o) : (n_w + n_c + n_o + n_t)]
if withbase:
return mu_0 + np.dot(X_sel ** nonlinear, coefs)
else:
return np.dot(X_sel ** nonlinear, coefs)
# Other simulation settings not used in AISTATS paper
# uniform covariate model
def uniform_covariate_model(
n: int,
n_nuisance: int = 0,
n_c: int = 0,
n_o: int = 0,
n_w: int = 0,
n_t: int = 0,
low: int = -1,
high: int = 1,
) -> np.ndarray:
d = n_nuisance + n_c + n_o + n_w + n_t
return np.random.uniform(low=low, high=high, size=(n, d))
def mu1_additive(
X: np.ndarray,
n_w: int = 0,
n_c: int = 0,
n_o: int = 0,
n_t: int = 0,
mu_0: Optional[np.ndarray] = None,
) -> np.ndarray:
if n_t == 0:
return mu_0
else:
coefs = np.random.normal(size=n_t)
return np.dot(X[:, (n_w + n_c + n_o) : (n_w + n_c + n_o + n_t)], coefs) / n_t
# regression surfaces from Hassanpour & Greiner
def mu0_hg(X: np.ndarray, n_w: int = 0, n_c: int = 0, n_o: int = 0) -> np.ndarray:
if n_c + n_o == 0:
return np.zeros((X.shape[0]))
else:
coefs = np.random.normal(size=n_c + n_o)
return np.dot(X[:, n_w : (n_w + n_c + n_o)], coefs) / (n_c + n_o)
def mu1_hg(
X: np.ndarray,
n_w: int = 0,
n_c: int = 0,
n_o: int = 0,
n_t: int = 0,
mu_0: Optional[np.ndarray] = None,
) -> np.ndarray:
if n_c + n_o == 0:
return np.zeros((X.shape[0]))
else:
coefs = np.random.normal(size=n_c + n_o)
return np.dot(X[:, n_w : (n_w + n_c + n_o)] ** 2, coefs) / (n_c + n_o)
def propensity_hg(
X: np.ndarray, n_c: int = 0, n_w: int = 0, xi: Optional[float] = None
) -> np.ndarray:
# propensity set-up used in Hassanpour & Greiner (2020)
if n_c + n_w == 0:
return 0.5 * np.ones(X.shape[0])
else:
if xi is None:
xi = 1
coefs = np.random.normal(size=n_c + n_w)
z = np.dot(X[:, : (n_c + n_w)], coefs)
return expit(xi * z)