causal-toolkit-urman 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- causal_toolkit_urman-0.1.0/LICENSE +21 -0
- causal_toolkit_urman-0.1.0/PKG-INFO +44 -0
- causal_toolkit_urman-0.1.0/README.md +4 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman/__init__.py +24 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman/meta_learners.py +101 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman/propensity.py +40 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman/rct.py +40 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman.egg-info/PKG-INFO +44 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman.egg-info/SOURCES.txt +13 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman.egg-info/dependency_links.txt +1 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman.egg-info/requires.txt +15 -0
- causal_toolkit_urman-0.1.0/causal_toolkit_urman.egg-info/top_level.txt +1 -0
- causal_toolkit_urman-0.1.0/pyproject.toml +71 -0
- causal_toolkit_urman-0.1.0/setup.cfg +4 -0
- causal_toolkit_urman-0.1.0/tests/test_meta_learners.py +131 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Maxwell Urman
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: causal-toolkit-urman
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python package for causal inference methods including ATE estimation, propensity score methods, and meta-learners
|
|
5
|
+
Author-email: Max Urman <maxwell.urman@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/maxwellurman/causal-toolkit-urman
|
|
8
|
+
Project-URL: Documentation, https://github.com/maxwellurman/causal-toolkit-urman#readme
|
|
9
|
+
Project-URL: Repository, https://github.com/maxwellurman/causal-toolkit-urman
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/maxwellurman/causal-toolkit-urman/issues
|
|
11
|
+
Keywords: causal inference,statistics,machine learning,treatment effects
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
22
|
+
Requires-Python: >=3.8
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: pandas>=1.3.0
|
|
26
|
+
Requires-Dist: numpy>=1.21.0
|
|
27
|
+
Requires-Dist: scipy>=1.7.0
|
|
28
|
+
Requires-Dist: scikit-learn>=1.0.0
|
|
29
|
+
Requires-Dist: lightgbm>=3.3.0
|
|
30
|
+
Requires-Dist: patsy>=0.5.0
|
|
31
|
+
Requires-Dist: pytest>=7.0.0
|
|
32
|
+
Requires-Dist: pytest-cov>=3.0.0
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
35
|
+
Requires-Dist: pytest-cov>=3.0.0; extra == "dev"
|
|
36
|
+
Requires-Dist: black>=22.0.0; extra == "dev"
|
|
37
|
+
Requires-Dist: pylint>=2.12.0; extra == "dev"
|
|
38
|
+
Requires-Dist: mypy>=0.950; extra == "dev"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
Package description: Causal analysis functions
|
|
42
|
+
Installation instructions:
|
|
43
|
+
Usage examples: Calculate CATE with different meta learners
|
|
44
|
+
API documentation
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""causal-toolkit-urman - Causal Inference Toolkit"""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.1.0"
|
|
4
|
+
|
|
5
|
+
# Import key functions for easy access
|
|
6
|
+
from .rct import calculate_ate_ci, calculate_ate_pvalue
|
|
7
|
+
from .propensity import ipw, doubly_robust
|
|
8
|
+
from .meta_learners import (
|
|
9
|
+
s_learner_discrete,
|
|
10
|
+
t_learner_discrete,
|
|
11
|
+
x_learner_discrete,
|
|
12
|
+
double_ml_cate
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"calculate_ate_ci",
|
|
17
|
+
"calculate_ate_pvalue",
|
|
18
|
+
"ipw",
|
|
19
|
+
"doubly_robust",
|
|
20
|
+
"s_learner_discrete",
|
|
21
|
+
"t_learner_discrete",
|
|
22
|
+
"x_learner_discrete",
|
|
23
|
+
"double_ml_cate",
|
|
24
|
+
]
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from sklearn.linear_model import LogisticRegression
|
|
4
|
+
from lightgbm import LGBMRegressor
|
|
5
|
+
from sklearn.model_selection import cross_val_predict
|
|
6
|
+
|
|
7
|
+
# Task 1: S-Learner
|
|
8
|
+
def s_learner_discrete(train, test, X, T, y):
|
|
9
|
+
"""Return a copy of the test DataFrame with an additional column name, "cate" that contains CATE for the test DataFrame."""
|
|
10
|
+
|
|
11
|
+
features = X + [T]
|
|
12
|
+
|
|
13
|
+
train_x = train[features]
|
|
14
|
+
train_y = train[y]
|
|
15
|
+
|
|
16
|
+
model = LGBMRegressor()
|
|
17
|
+
model.fit(train_x, train_y)
|
|
18
|
+
|
|
19
|
+
test_x_t_1 = test[features].copy()
|
|
20
|
+
test_x_t_1[T] = 1
|
|
21
|
+
test_x_t_0 = test[features].copy()
|
|
22
|
+
test_x_t_0[T] = 0
|
|
23
|
+
|
|
24
|
+
result = test.copy()
|
|
25
|
+
result['cate'] = model.predict(test_x_t_1) - model.predict(test_x_t_0)
|
|
26
|
+
return result
|
|
27
|
+
|
|
28
|
+
# Task 2: T-Learner
|
|
29
|
+
def t_learner_discrete(train, test, X, T, y):
|
|
30
|
+
"""Return a copy of the test DataFrame with an additional column name, "cate" that contains CATE for the test DataFrame."""
|
|
31
|
+
|
|
32
|
+
train_0 = train[train[T] == 0]
|
|
33
|
+
train_1 = train[train[T] == 1]
|
|
34
|
+
|
|
35
|
+
model_0 = LGBMRegressor()
|
|
36
|
+
model_0.fit(train_0[X], train_0[y])
|
|
37
|
+
|
|
38
|
+
model_1 = LGBMRegressor()
|
|
39
|
+
model_1.fit(train_1[X], train_1[y])
|
|
40
|
+
|
|
41
|
+
result = test.copy()
|
|
42
|
+
result['cate'] = model_1.predict(test[X]) - model_0.predict(test[X])
|
|
43
|
+
return result
|
|
44
|
+
|
|
45
|
+
# Task 3: X-Learner
|
|
46
|
+
def x_learner_discrete(train, test, X, T, y):
|
|
47
|
+
"""Return a copy of the test DataFrame with an additional column name, "cate" that contains CATE for the test DataFrame."""
|
|
48
|
+
|
|
49
|
+
# Propensity Score Model
|
|
50
|
+
model_ps = LogisticRegression(penalty=None)
|
|
51
|
+
model_ps.fit(train[X], train[T])
|
|
52
|
+
test_ps = model_ps.predict_proba(test[X])[:, 1]
|
|
53
|
+
|
|
54
|
+
# Outcome Models
|
|
55
|
+
train_0 = train[train[T] == 0]
|
|
56
|
+
train_1 = train[train[T] == 1]
|
|
57
|
+
|
|
58
|
+
model_0 = LGBMRegressor()
|
|
59
|
+
model_0.fit(train_0[X], train_0[y])
|
|
60
|
+
|
|
61
|
+
model_1 = LGBMRegressor()
|
|
62
|
+
model_1.fit(train_1[X], train_1[y])
|
|
63
|
+
|
|
64
|
+
#pseudo treatment effects
|
|
65
|
+
d_0 = model_1.predict(train_0[X]) - train_0[y]
|
|
66
|
+
d_1 = train_1[y] - model_0.predict(train_1[X])
|
|
67
|
+
|
|
68
|
+
# Second Stage Model
|
|
69
|
+
model_tau_0 = LGBMRegressor()
|
|
70
|
+
model_tau_0.fit(train_0[X], d_0)
|
|
71
|
+
|
|
72
|
+
model_tau_1 = LGBMRegressor()
|
|
73
|
+
model_tau_1.fit(train_1[X], d_1)
|
|
74
|
+
|
|
75
|
+
# Final Estimate
|
|
76
|
+
tau_0 = model_tau_0.predict(test[X])
|
|
77
|
+
tau_1 = model_tau_1.predict(test[X])
|
|
78
|
+
|
|
79
|
+
result = test.copy()
|
|
80
|
+
result['cate'] = test_ps * tau_0 + (1- test_ps) * tau_1
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
# Task 4: double_ml_cate
|
|
84
|
+
def double_ml_cate(train, test, X, T, y):
|
|
85
|
+
"""Return a copy of the test DataFrame with an additional column name, "cate" that contains CATE for the test DataFrame."""
|
|
86
|
+
|
|
87
|
+
model_treatment = LGBMRegressor()
|
|
88
|
+
train_t_res = train[T] - cross_val_predict(model_treatment, train[X], train[T], cv=5)
|
|
89
|
+
|
|
90
|
+
model_outcome = LGBMRegressor()
|
|
91
|
+
train_y_res = train[y] - cross_val_predict(model_outcome, train[X], train[y], cv=5)
|
|
92
|
+
|
|
93
|
+
train_y_star = train_y_res / train_t_res
|
|
94
|
+
w = train_t_res ** 2
|
|
95
|
+
|
|
96
|
+
model_cate = LGBMRegressor()
|
|
97
|
+
model_cate.fit(train[X], train_y_star, sample_weight=w)
|
|
98
|
+
|
|
99
|
+
results = test.copy()
|
|
100
|
+
results['cate'] = model_cate.predict(test[X])
|
|
101
|
+
return results
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from patsy import dmatrix
|
|
4
|
+
from sklearn.linear_model import LogisticRegression, LinearRegression
|
|
5
|
+
|
|
6
|
+
### Task 1
|
|
7
|
+
def ipw(df, ps_formula: str, T: str, Y:str):
|
|
8
|
+
X = dmatrix(ps_formula, df, return_type="dataframe")
|
|
9
|
+
model = LogisticRegression(penalty=None, max_iter=1000)
|
|
10
|
+
model.fit(X, df[T])
|
|
11
|
+
ps = model.predict_proba(X)[:, 1]
|
|
12
|
+
df["ps"] = ps
|
|
13
|
+
|
|
14
|
+
ATE = np.mean(
|
|
15
|
+
df[Y] * ((df[T] - df["ps"]) / ((df["ps"]) * (1 - df["ps"]))))
|
|
16
|
+
return ATE
|
|
17
|
+
|
|
18
|
+
### Task 2
|
|
19
|
+
def doubly_robust(df: pd.DataFrame, formula: str, T: str, Y: str):
|
|
20
|
+
X = dmatrix(formula, df, return_type="dataframe")
|
|
21
|
+
|
|
22
|
+
model = LogisticRegression(penalty=None, max_iter=1000)
|
|
23
|
+
model.fit(X, df[T])
|
|
24
|
+
ps = model.predict_proba(X)[:, 1]
|
|
25
|
+
|
|
26
|
+
model_0 = LinearRegression().fit(X[df[T]==0], df.loc[df[T]==0, Y])
|
|
27
|
+
mu_0 = model_0.predict(X)
|
|
28
|
+
|
|
29
|
+
model_1 = LinearRegression().fit(X[df[T]==1], df.loc[df[T]==1, Y])
|
|
30
|
+
mu_1 = model_1.predict(X)
|
|
31
|
+
|
|
32
|
+
t = df[T].to_numpy()
|
|
33
|
+
y = df[Y].to_numpy()
|
|
34
|
+
|
|
35
|
+
ATE = np.mean(
|
|
36
|
+
(t * (y - mu_1) / ps + mu_1)
|
|
37
|
+
- ((1 - t) * (y - mu_0) / (1 - ps) + mu_0)
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
return float(ATE)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
def calculate_ate_ci(data, alpha = 0.05):
|
|
5
|
+
from scipy import stats
|
|
6
|
+
z = np.abs(stats.norm.ppf(alpha/2))
|
|
7
|
+
|
|
8
|
+
treatment_mean = data.loc[data['T'] == 1, 'Y'].mean()
|
|
9
|
+
treatment_var = data.loc[data['T'] == 1, 'Y'].var()
|
|
10
|
+
treatment_n = len(data.loc[data['T'] == 1, 'Y'])
|
|
11
|
+
|
|
12
|
+
control_mean = data.loc[data['T'] == 0, 'Y'].mean()
|
|
13
|
+
control_var = data.loc[data['T'] == 0, 'Y'].var()
|
|
14
|
+
control_n = len(data.loc[data['T'] == 0, 'Y'])
|
|
15
|
+
|
|
16
|
+
ATE_estimate = treatment_mean - control_mean
|
|
17
|
+
SE_diff = np.sqrt((treatment_var/treatment_n) + (control_var/control_n))
|
|
18
|
+
CI_upper = ATE_estimate + z*SE_diff
|
|
19
|
+
CI_lower = ATE_estimate - z*SE_diff
|
|
20
|
+
|
|
21
|
+
return (ATE_estimate, CI_lower, CI_upper)
|
|
22
|
+
|
|
23
|
+
def calculate_ate_pvalue(data):
|
|
24
|
+
from scipy import stats
|
|
25
|
+
|
|
26
|
+
treatment_mean = data.loc[data['T'] == 1, 'Y'].mean()
|
|
27
|
+
treatment_var = data.loc[data['T'] == 1, 'Y'].var()
|
|
28
|
+
treatment_n = len(data.loc[data['T'] == 1, 'Y'])
|
|
29
|
+
|
|
30
|
+
control_mean = data.loc[data['T'] == 0, 'Y'].mean()
|
|
31
|
+
control_var = data.loc[data['T'] == 0, 'Y'].var()
|
|
32
|
+
control_n = len(data.loc[data['T'] == 0, 'Y'])
|
|
33
|
+
|
|
34
|
+
ATE_estimate = treatment_mean - control_mean
|
|
35
|
+
SE_diff = np.sqrt((treatment_var/treatment_n) + (control_var/control_n))
|
|
36
|
+
|
|
37
|
+
t_statistic = (ATE_estimate - 0) / SE_diff
|
|
38
|
+
p_value = 2 * (1 - stats.norm.cdf(abs(t_statistic)))
|
|
39
|
+
|
|
40
|
+
return (ATE_estimate, t_statistic, p_value)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: causal-toolkit-urman
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python package for causal inference methods including ATE estimation, propensity score methods, and meta-learners
|
|
5
|
+
Author-email: Max Urman <maxwell.urman@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/maxwellurman/causal-toolkit-urman
|
|
8
|
+
Project-URL: Documentation, https://github.com/maxwellurman/causal-toolkit-urman#readme
|
|
9
|
+
Project-URL: Repository, https://github.com/maxwellurman/causal-toolkit-urman
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/maxwellurman/causal-toolkit-urman/issues
|
|
11
|
+
Keywords: causal inference,statistics,machine learning,treatment effects
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
22
|
+
Requires-Python: >=3.8
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: pandas>=1.3.0
|
|
26
|
+
Requires-Dist: numpy>=1.21.0
|
|
27
|
+
Requires-Dist: scipy>=1.7.0
|
|
28
|
+
Requires-Dist: scikit-learn>=1.0.0
|
|
29
|
+
Requires-Dist: lightgbm>=3.3.0
|
|
30
|
+
Requires-Dist: patsy>=0.5.0
|
|
31
|
+
Requires-Dist: pytest>=7.0.0
|
|
32
|
+
Requires-Dist: pytest-cov>=3.0.0
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
35
|
+
Requires-Dist: pytest-cov>=3.0.0; extra == "dev"
|
|
36
|
+
Requires-Dist: black>=22.0.0; extra == "dev"
|
|
37
|
+
Requires-Dist: pylint>=2.12.0; extra == "dev"
|
|
38
|
+
Requires-Dist: mypy>=0.950; extra == "dev"
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
|
|
41
|
+
Package description: Causal analysis functions
|
|
42
|
+
Installation instructions:
|
|
43
|
+
Usage examples: Calculate CATE with different meta learners
|
|
44
|
+
API documentation
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
causal_toolkit_urman/__init__.py
|
|
5
|
+
causal_toolkit_urman/meta_learners.py
|
|
6
|
+
causal_toolkit_urman/propensity.py
|
|
7
|
+
causal_toolkit_urman/rct.py
|
|
8
|
+
causal_toolkit_urman.egg-info/PKG-INFO
|
|
9
|
+
causal_toolkit_urman.egg-info/SOURCES.txt
|
|
10
|
+
causal_toolkit_urman.egg-info/dependency_links.txt
|
|
11
|
+
causal_toolkit_urman.egg-info/requires.txt
|
|
12
|
+
causal_toolkit_urman.egg-info/top_level.txt
|
|
13
|
+
tests/test_meta_learners.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
causal_toolkit_urman
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "causal-toolkit-urman"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A Python package for causal inference methods including ATE estimation, propensity score methods, and meta-learners"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = {text = "MIT"}
|
|
12
|
+
authors = [
|
|
13
|
+
{name = "Max Urman", email = "maxwell.urman@gmail.com"}
|
|
14
|
+
]
|
|
15
|
+
keywords = ["causal inference", "statistics", "machine learning", "treatment effects"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.8",
|
|
22
|
+
"Programming Language :: Python :: 3.9",
|
|
23
|
+
"Programming Language :: Python :: 3.10",
|
|
24
|
+
"Programming Language :: Python :: 3.11",
|
|
25
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
26
|
+
"Topic :: Scientific/Engineering :: Information Analysis",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
dependencies = [
|
|
30
|
+
"pandas>=1.3.0",
|
|
31
|
+
"numpy>=1.21.0",
|
|
32
|
+
"scipy>=1.7.0",
|
|
33
|
+
"scikit-learn>=1.0.0",
|
|
34
|
+
"lightgbm>=3.3.0",
|
|
35
|
+
"patsy>=0.5.0",
|
|
36
|
+
"pytest>=7.0.0",
|
|
37
|
+
"pytest-cov>=3.0.0",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
[project.optional-dependencies]
|
|
41
|
+
dev = [
|
|
42
|
+
"pytest>=7.0.0",
|
|
43
|
+
"pytest-cov>=3.0.0",
|
|
44
|
+
"black>=22.0.0",
|
|
45
|
+
"pylint>=2.12.0",
|
|
46
|
+
"mypy>=0.950",
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
[project.urls]
|
|
50
|
+
Homepage = "https://github.com/maxwellurman/causal-toolkit-urman"
|
|
51
|
+
Documentation = "https://github.com/maxwellurman/causal-toolkit-urman#readme"
|
|
52
|
+
Repository = "https://github.com/maxwellurman/causal-toolkit-urman"
|
|
53
|
+
"Bug Tracker" = "https://github.com/maxwellurman/causal-toolkit-urman/issues"
|
|
54
|
+
|
|
55
|
+
[tool.pytest.ini_options]
|
|
56
|
+
testpaths = ["tests"]
|
|
57
|
+
python_files = ["test_*.py"]
|
|
58
|
+
python_classes = ["Test*"]
|
|
59
|
+
python_functions = ["test_*"]
|
|
60
|
+
addopts = "-v --cov=causal-toolkit-urman --cov-report=html --cov-report=term"
|
|
61
|
+
|
|
62
|
+
[tool.black]
|
|
63
|
+
line-length = 88
|
|
64
|
+
target-version = ['py38', 'py39', 'py310', 'py311']
|
|
65
|
+
include = '\.pyi?$'
|
|
66
|
+
|
|
67
|
+
[tool.mypy]
|
|
68
|
+
python_version = "3.8"
|
|
69
|
+
warn_return_any = true
|
|
70
|
+
warn_unused_configs = true
|
|
71
|
+
disallow_untyped_defs = false
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
def simple_data():
|
|
6
|
+
"""Generate simple data with known treatment effect"""
|
|
7
|
+
np.random.seed(42)
|
|
8
|
+
n = 1000
|
|
9
|
+
|
|
10
|
+
# Covariates
|
|
11
|
+
x1 = np.random.normal(0, 1, n)
|
|
12
|
+
x2 = np.random.normal(0, 1, n)
|
|
13
|
+
|
|
14
|
+
# Treatment assignment (confounded)
|
|
15
|
+
prob_t = 1 / (1 + np.exp(-(0.5 * x1 + 0.3 * x2)))
|
|
16
|
+
t = np.random.binomial(1, prob_t, n)
|
|
17
|
+
|
|
18
|
+
# Outcome with constant treatment effect = 2.0
|
|
19
|
+
y = 2.0 * t + x1 + 0.5 * x2 + np.random.normal(0, 0.5, n)
|
|
20
|
+
|
|
21
|
+
df = pd.DataFrame({'x1': x1, 'x2': x2, 't': t, 'y': y})
|
|
22
|
+
|
|
23
|
+
# Split into train/test
|
|
24
|
+
train = df.iloc[:800].copy()
|
|
25
|
+
test = df.iloc[800:].copy()
|
|
26
|
+
|
|
27
|
+
return train, test
|
|
28
|
+
|
|
29
|
+
def continuous_treatment_data():
|
|
30
|
+
"""Generate data with continuous treatment"""
|
|
31
|
+
np.random.seed(789)
|
|
32
|
+
n = 1000
|
|
33
|
+
|
|
34
|
+
# Covariates
|
|
35
|
+
x1 = np.random.normal(0, 1, n)
|
|
36
|
+
x2 = np.random.normal(0, 1, n)
|
|
37
|
+
|
|
38
|
+
# Continuous treatment
|
|
39
|
+
t = 10 + x1 + 2*x2 + np.random.normal(0, 1, n)
|
|
40
|
+
|
|
41
|
+
# Outcome: linear effect of treatment
|
|
42
|
+
y = t + x1 + 0.5*x2 + np.random.normal(0, 0.5, n)
|
|
43
|
+
|
|
44
|
+
df = pd.DataFrame({'x1': x1, 'x2': x2, 't': t, 'y': y})
|
|
45
|
+
|
|
46
|
+
train = df.iloc[:800].copy()
|
|
47
|
+
test = df.iloc[800:].copy()
|
|
48
|
+
|
|
49
|
+
return train, test
|
|
50
|
+
|
|
51
|
+
# Test 1: Returns DataFrame
|
|
52
|
+
from causal_toolkit_urman.meta_learners import s_learner_discrete
|
|
53
|
+
|
|
54
|
+
def test_s_learner_returns_dataframe():
|
|
55
|
+
train, test = simple_data()
|
|
56
|
+
|
|
57
|
+
result = s_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
58
|
+
|
|
59
|
+
assert isinstance(result, pd.DataFrame)
|
|
60
|
+
|
|
61
|
+
# Test 2: Has 'cate' column
|
|
62
|
+
def test_s_learner_has_cate_column():
|
|
63
|
+
train, test = simple_data()
|
|
64
|
+
|
|
65
|
+
result = s_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
66
|
+
|
|
67
|
+
assert 'cate' in result.columns
|
|
68
|
+
|
|
69
|
+
# Test 3: Recovers the true effect
|
|
70
|
+
def test_s_learner_constant_effect(true_effect=2, tolerance=.1):
|
|
71
|
+
train, test = simple_data()
|
|
72
|
+
|
|
73
|
+
result = s_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
74
|
+
|
|
75
|
+
estimated_ate = result['cate'].mean()
|
|
76
|
+
|
|
77
|
+
assert abs(estimated_ate - true_effect) < tolerance
|
|
78
|
+
|
|
79
|
+
# Test 4: Numeric CATE values
|
|
80
|
+
def test_s_learner_return_numeric_cate():
|
|
81
|
+
train, test = simple_data()
|
|
82
|
+
|
|
83
|
+
result = s_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
84
|
+
|
|
85
|
+
assert pd.api.types.is_numeric_dtype(result['cate'])
|
|
86
|
+
|
|
87
|
+
# Test 5: No NaN in CATE
|
|
88
|
+
def test_s_learner_no_nan_values():
|
|
89
|
+
train, test = simple_data()
|
|
90
|
+
|
|
91
|
+
result = s_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
92
|
+
|
|
93
|
+
assert not result['cate'].isna().any()
|
|
94
|
+
|
|
95
|
+
# Test 6: Returns DataFrame
|
|
96
|
+
from causal_toolkit_urman.meta_learners import t_learner_discrete
|
|
97
|
+
|
|
98
|
+
def test_t_learner_returns_dataframe():
|
|
99
|
+
train, test = simple_data()
|
|
100
|
+
|
|
101
|
+
result = t_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
102
|
+
|
|
103
|
+
assert isinstance(result, pd.DataFrame)
|
|
104
|
+
|
|
105
|
+
# Test 7: Returns DataFrame
|
|
106
|
+
from causal_toolkit_urman.meta_learners import x_learner_discrete
|
|
107
|
+
|
|
108
|
+
def test_x_learner_returns_dataframe():
|
|
109
|
+
train, test = simple_data()
|
|
110
|
+
|
|
111
|
+
result = x_learner_discrete(train, test, ['x1', 'x2'], 't', 'y')
|
|
112
|
+
|
|
113
|
+
assert isinstance(result, pd.DataFrame)
|
|
114
|
+
|
|
115
|
+
# Test 8: Returns DataFrame
|
|
116
|
+
from causal_toolkit_urman.meta_learners import double_ml_cate
|
|
117
|
+
|
|
118
|
+
def test_double_ml_returns_dataframe():
|
|
119
|
+
train, test = simple_data()
|
|
120
|
+
|
|
121
|
+
result = double_ml_cate(train, test, ['x1', 'x2'], 't', 'y')
|
|
122
|
+
|
|
123
|
+
assert isinstance(result, pd.DataFrame)
|
|
124
|
+
|
|
125
|
+
# Test 9: Works with Continuous T
|
|
126
|
+
def test_double_ml_continuous_treatment():
|
|
127
|
+
train, test = continuous_treatment_data()
|
|
128
|
+
|
|
129
|
+
result = double_ml_cate(train, test, ['x1', 'x2'], 't', 'y')
|
|
130
|
+
|
|
131
|
+
assert len(result) == len(test)
|