forked from pymc-labs/CausalPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_integration_skl_examples.py
329 lines (286 loc) · 10.4 KB
/
test_integration_skl_examples.py
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
323
324
325
326
327
328
329
# Copyright 2022 - 2025 The PyMC Labs Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import pandas as pd
import pytest
from matplotlib import pyplot as plt
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ExpSineSquared, WhiteKernel
from sklearn.linear_model import LinearRegression
import causalpy as cp
@pytest.mark.integration
def test_did():
"""
Test Difference in Differences (DID) Sci-Kit Learn experiment.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.DifferenceInDifferences returns correct type
"""
data = cp.load_data("did")
result = cp.DifferenceInDifferences(
data,
formula="y ~ 1 + group*post_treatment",
time_variable_name="t",
group_variable_name="group",
treated=1,
untreated=0,
model=LinearRegression(),
)
assert isinstance(data, pd.DataFrame)
assert isinstance(result, cp.DifferenceInDifferences)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
assert isinstance(ax, plt.Axes)
@pytest.mark.integration
def test_rd_drinking():
"""
Test Regression Discontinuity Sci-Kit Learn experiment on drinking age data.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.RegressionDiscontinuity returns correct type
"""
df = (
cp.load_data("drinking")
.rename(columns={"agecell": "age"})
.assign(treated=lambda df_: df_.age > 21)
)
result = cp.RegressionDiscontinuity(
df,
formula="all ~ 1 + age + treated",
running_variable_name="age",
model=LinearRegression(),
treatment_threshold=21,
epsilon=0.001,
)
assert isinstance(df, pd.DataFrame)
assert isinstance(result, cp.RegressionDiscontinuity)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
assert isinstance(ax, plt.Axes)
@pytest.mark.integration
def test_its():
"""
Test Interrupted Time Series Sci-Kit Learn experiment.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.InterruptedTimeSeries returns correct type
"""
df = (
cp.load_data("its")
.assign(date=lambda x: pd.to_datetime(x["date"]))
.set_index("date")
)
treatment_time = pd.to_datetime("2017-01-01")
result = cp.InterruptedTimeSeries(
df,
treatment_time,
formula="y ~ 1 + t + C(month)",
model=LinearRegression(),
)
assert isinstance(df, pd.DataFrame)
assert isinstance(result, cp.InterruptedTimeSeries)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
# For multi-panel plots, ax should be an array of axes
assert isinstance(ax, np.ndarray) and all(
isinstance(item, plt.Axes) for item in ax
), "ax must be a numpy.ndarray of plt.Axes"
plot_data = result.get_plot_data()
assert isinstance(plot_data, pd.DataFrame), "The returned object is not a pandas DataFrame"
expected_columns = ['prediction', 'impact']
assert set(expected_columns).issubset(set(plot_data.columns)), f"DataFrame is missing expected columns {expected_columns}"
@pytest.mark.integration
def test_sc():
"""
Test Synthetic Control Sci-Kit Learn experiment.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.SyntheticControl returns correct type
"""
df = cp.load_data("sc")
treatment_time = 70
result = cp.SyntheticControl(
df,
treatment_time,
formula="actual ~ 0 + a + b + c + d + e + f + g",
model=cp.skl_models.WeightedProportion(),
)
assert isinstance(df, pd.DataFrame)
assert isinstance(result, cp.SyntheticControl)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
# For multi-panel plots, ax should be an array of axes
assert isinstance(ax, np.ndarray) and all(
isinstance(item, plt.Axes) for item in ax
), "ax must be a numpy.ndarray of plt.Axes"
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
# For multi-panel plots, ax should be an array of axes
assert isinstance(ax, np.ndarray) and all(
isinstance(item, plt.Axes) for item in ax
), "ax must be a numpy.ndarray of plt.Axes"
plot_data = result.get_plot_data()
assert isinstance(plot_data, pd.DataFrame), "The returned object is not a pandas DataFrame"
expected_columns = ['prediction', 'impact']
assert set(expected_columns).issubset(set(plot_data.columns)), f"DataFrame is missing expected columns {expected_columns}"
@pytest.mark.integration
def test_rd_linear_main_effects():
"""
Test Regression Discontinuity Sci-Kit Learn experiment main effects.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.RegressionDiscontinuity returns correct type
"""
data = cp.load_data("rd")
result = cp.RegressionDiscontinuity(
data,
formula="y ~ 1 + x + treated",
model=LinearRegression(),
treatment_threshold=0.5,
epsilon=0.001,
)
assert isinstance(data, pd.DataFrame)
assert isinstance(result, cp.RegressionDiscontinuity)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
assert isinstance(ax, plt.Axes)
@pytest.mark.integration
def test_rd_linear_main_effects_bandwidth():
"""
Test Regression Discontinuity Sci-Kit Learn experiment, main effects with
bandwidth parameter.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.RegressionDiscontinuity returns correct type
"""
data = cp.load_data("rd")
result = cp.RegressionDiscontinuity(
data,
formula="y ~ 1 + x + treated",
model=LinearRegression(),
treatment_threshold=0.5,
epsilon=0.001,
bandwidth=0.3,
)
assert isinstance(data, pd.DataFrame)
assert isinstance(result, cp.RegressionDiscontinuity)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
assert isinstance(ax, plt.Axes)
@pytest.mark.integration
def test_rd_linear_with_interaction():
"""
Test Regression Discontinuity Sci-Kit Learn experiment with interaction.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.RegressionDiscontinuity returns correct type
"""
data = cp.load_data("rd")
result = cp.RegressionDiscontinuity(
data,
formula="y ~ 1 + x + treated + x:treated",
model=LinearRegression(),
treatment_threshold=0.5,
epsilon=0.001,
)
assert isinstance(data, pd.DataFrame)
assert isinstance(result, cp.RegressionDiscontinuity)
result.summary()
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
assert isinstance(ax, plt.Axes)
@pytest.mark.integration
def test_rd_linear_with_gaussian_process():
"""
Test Regression Discontinuity Sci-Kit Learn experiment with Gaussian process model.
Loads data and checks:
1. data is a dataframe
2. skl_experiements.RegressionDiscontinuity returns correct type
"""
data = cp.load_data("rd")
kernel = 1.0 * ExpSineSquared(1.0, 5.0) + WhiteKernel(1e-1)
result = cp.RegressionDiscontinuity(
data,
formula="y ~ 1 + x + treated",
model=GaussianProcessRegressor(kernel=kernel),
model_kwargs={"kernel": kernel},
treatment_threshold=0.5,
epsilon=0.001,
)
assert isinstance(data, pd.DataFrame)
assert isinstance(result, cp.RegressionDiscontinuity)
fig, ax = result.plot()
assert isinstance(fig, plt.Figure)
assert isinstance(ax, plt.Axes)
# DEPRECATION WARNING TESTS ============================================================
def test_did_deprecation_warning():
"""Test that the old DifferenceInDifferences class raises a deprecation warning."""
with pytest.warns(DeprecationWarning):
data = cp.load_data("did")
result = cp.skl_experiments.DifferenceInDifferences(
data,
formula="y ~ 1 + group*post_treatment",
time_variable_name="t",
group_variable_name="group",
treated=1,
untreated=0,
model=LinearRegression(),
)
assert isinstance(result, cp.DifferenceInDifferences)
def test_its_deprecation_warning():
"""Test that the old InterruptedTimeSeries class raises a deprecation warning."""
with pytest.warns(DeprecationWarning):
df = (
cp.load_data("its")
.assign(date=lambda x: pd.to_datetime(x["date"]))
.set_index("date")
)
treatment_time = pd.to_datetime("2017-01-01")
result = cp.skl_experiments.InterruptedTimeSeries(
df,
treatment_time,
formula="y ~ 1 + t + C(month)",
model=LinearRegression(),
)
assert isinstance(result, cp.InterruptedTimeSeries)
def test_sc_deprecation_warning():
"""Test that the old SyntheticControl class raises a deprecation warning."""
with pytest.warns(DeprecationWarning):
df = cp.load_data("sc")
treatment_time = 70
result = cp.skl_experiments.SyntheticControl(
df,
treatment_time,
formula="actual ~ 0 + a + b + c + d + e + f + g",
model=cp.skl_models.WeightedProportion(),
)
assert isinstance(result, cp.SyntheticControl)
def test_rd_deprecation_warning():
"""Test that the old RegressionDiscontinuity class raises a deprecation warning."""
with pytest.warns(DeprecationWarning):
data = cp.load_data("rd")
result = cp.skl_experiments.RegressionDiscontinuity(
data,
formula="y ~ 1 + x + treated",
model=LinearRegression(),
treatment_threshold=0.5,
epsilon=0.001,
)
assert isinstance(result, cp.RegressionDiscontinuity)