catesim 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.
- catesim-0.1.0/CHANGELOG.md +8 -0
- catesim-0.1.0/LICENSE +21 -0
- catesim-0.1.0/MANIFEST.in +2 -0
- catesim-0.1.0/PKG-INFO +203 -0
- catesim-0.1.0/README.md +174 -0
- catesim-0.1.0/pyproject.toml +49 -0
- catesim-0.1.0/setup.cfg +4 -0
- catesim-0.1.0/src/catesim/__init__.py +49 -0
- catesim-0.1.0/src/catesim/_arrays.py +9 -0
- catesim-0.1.0/src/catesim/_version.py +3 -0
- catesim-0.1.0/src/catesim/diagnostics.py +117 -0
- catesim-0.1.0/src/catesim/draws.py +170 -0
- catesim-0.1.0/src/catesim/examples.py +105 -0
- catesim-0.1.0/src/catesim/fitting.py +397 -0
- catesim-0.1.0/src/catesim/mechanism.py +1386 -0
- catesim-0.1.0/src/catesim/metrics.py +77 -0
- catesim-0.1.0/src/catesim/population.py +143 -0
- catesim-0.1.0/src/catesim/py.typed +0 -0
- catesim-0.1.0/src/catesim.egg-info/PKG-INFO +203 -0
- catesim-0.1.0/src/catesim.egg-info/SOURCES.txt +29 -0
- catesim-0.1.0/src/catesim.egg-info/dependency_links.txt +1 -0
- catesim-0.1.0/src/catesim.egg-info/requires.txt +9 -0
- catesim-0.1.0/src/catesim.egg-info/top_level.txt +1 -0
- catesim-0.1.0/tests/support.py +46 -0
- catesim-0.1.0/tests/test_calibration.py +195 -0
- catesim-0.1.0/tests/test_diagnostics.py +233 -0
- catesim-0.1.0/tests/test_docstrings.py +16 -0
- catesim-0.1.0/tests/test_examples.py +61 -0
- catesim-0.1.0/tests/test_fitting.py +212 -0
- catesim-0.1.0/tests/test_parity.py +53 -0
- catesim-0.1.0/tests/test_sampling.py +176 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First public release of CateSim. Calibrate a conditional average treatment effect
|
|
6
|
+
mechanism from a finite covariate population, deterministic input shapes, and
|
|
7
|
+
nine scientific targets, then sample it. Optional truth-assisted fitting is
|
|
8
|
+
available as the `fit` extra.
|
catesim-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alireza S. Mahani, Mansour T. A. Sharabiani, and Alex Bottle
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
catesim-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: catesim
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Calibrated simulation of conditional average treatment effects
|
|
5
|
+
Author: Alireza S. Mahani, Mansour T. A. Sharabiani, Alex Bottle
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: causal inference,conditional average treatment effect,simulation,treatment effects
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: numpy>=1.26
|
|
22
|
+
Requires-Dist: scipy>=1.11
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
25
|
+
Provides-Extra: fit
|
|
26
|
+
Requires-Dist: scikit-learn>=1.6; extra == "fit"
|
|
27
|
+
Requires-Dist: threadpoolctl>=3.1; extra == "fit"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# CateSim
|
|
31
|
+
|
|
32
|
+
CateSim (`catesim`) constructs calibrated data-generating processes for conditional average treatment effects.
|
|
33
|
+
Supply a finite covariate population, callable shape functions, and nine
|
|
34
|
+
scientific targets. `calibrate` freezes one mechanism. Ordinary Python loops
|
|
35
|
+
then handle sample sizes, replications, and comparisons.
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
Install with Python 3.11 or later:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
python -m pip install catesim
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Calibration and sampling use NumPy and SciPy only. Truth-assisted fitting is optional:
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
python -m pip install 'catesim[fit]'
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Calibrate a mechanism
|
|
52
|
+
|
|
53
|
+
For a self-contained example with no downloads:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from catesim import calibrate
|
|
57
|
+
from catesim.examples import make_example
|
|
58
|
+
|
|
59
|
+
population, shapes, targets = make_example(population_size=512, seed=7)
|
|
60
|
+
dgp = calibrate(population, shapes, targets)
|
|
61
|
+
data = dgp.sample(n=1000, seed=123)
|
|
62
|
+
truth = dgp.truth(data.X)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The factory generates a uniformly weighted population with four Gaussian
|
|
66
|
+
covariates and returns deterministic input shapes and feasible default targets.
|
|
67
|
+
Its seed controls the population; the sampling seed controls observations.
|
|
68
|
+
The population support size and sample size are separate choices.
|
|
69
|
+
|
|
70
|
+
To change a target while retaining the same population and input shapes:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from dataclasses import replace
|
|
74
|
+
from catesim import calibrate
|
|
75
|
+
from catesim.examples import make_example
|
|
76
|
+
|
|
77
|
+
population, shapes, targets = make_example()
|
|
78
|
+
weaker = calibrate(population, shapes, replace(targets, q=0.06))
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The other eight scalar targets stay fixed when feasible. Final conditional
|
|
82
|
+
functions may change through calibration; input shapes are not those final
|
|
83
|
+
functions. Modified targets receive the usual feasibility checks.
|
|
84
|
+
|
|
85
|
+
The same example can be constructed explicitly from a user-provided covariate
|
|
86
|
+
matrix, callables, and targets:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
import numpy as np
|
|
90
|
+
from catesim import EmpiricalPopulation, Shapes, Targets, calibrate
|
|
91
|
+
|
|
92
|
+
X = np.random.default_rng(7).normal(size=(512, 4))
|
|
93
|
+
pop = EmpiricalPopulation(X, weights=None, name="example")
|
|
94
|
+
shapes = Shapes(
|
|
95
|
+
assignment=lambda x: x[:, 0],
|
|
96
|
+
baseline=lambda x: x[:, 1] + 0.3 * x[:, 0] ** 2,
|
|
97
|
+
effect=lambda x: np.sin(x[:, 2]) + 0.2 * x[:, 3] ** 2,
|
|
98
|
+
)
|
|
99
|
+
targets = Targets(
|
|
100
|
+
pi=0.3, q=0.12, R0_squared=0.6,
|
|
101
|
+
delta=0.2, s_tau=0.7, nu=1.0,
|
|
102
|
+
rho_be=0.4, rho_ue=-0.2, rho_ub=0.1,
|
|
103
|
+
)
|
|
104
|
+
dgp = calibrate(pop, shapes, targets)
|
|
105
|
+
data = dgp.sample(n=1000, seed=123)
|
|
106
|
+
truth = dgp.truth(data.X)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
The nine targets are:
|
|
110
|
+
|
|
111
|
+
- `pi`: treatment prevalence, the population mean of the propensity.
|
|
112
|
+
- `q`: average overlap, the population mean of propensity times one minus propensity.
|
|
113
|
+
- `R0_squared`: baseline prognostic strength, from zero up to but not including one.
|
|
114
|
+
- `delta`: population mean CATE, in noise-RMS units.
|
|
115
|
+
- `s_tau`: population standard deviation of CATE, in the same units. Zero is a constant effect.
|
|
116
|
+
- `nu`: treated-to-control arm-noise RMS ratio. Zero makes the treated arm noiseless.
|
|
117
|
+
- `rho_be`: correlation of the control conditional mean with propensity.
|
|
118
|
+
- `rho_ue`: correlation of CATE with propensity.
|
|
119
|
+
- `rho_ub`: correlation of the control conditional mean with CATE.
|
|
120
|
+
|
|
121
|
+
Undefined correlations are `None`, not zero. Attainable values and the cases
|
|
122
|
+
where a correlation is undefined are documented in `help(Targets)`.
|
|
123
|
+
|
|
124
|
+
The initial gauge fixes the population mean of the control conditional mean
|
|
125
|
+
at zero and factual noise RMS at one, so `delta` and `s_tau` are in noise units.
|
|
126
|
+
Noise RMS is the square root of the population average conditional noise
|
|
127
|
+
variance, not the factual outcome SD or the average conditional SD.
|
|
128
|
+
Treatment is binary, outcomes are continuous, and arm errors are independent
|
|
129
|
+
standard Gaussians. A finite arm-noise ratio may be zero, which makes the
|
|
130
|
+
treated arm noiseless. Fully noiseless mechanisms are outside this gauge.
|
|
131
|
+
|
|
132
|
+
Shape callables take a covariate matrix and return one value per row. They
|
|
133
|
+
are not copied at calibration time, so they must be deterministic and their
|
|
134
|
+
captured state must stay fixed. Omitted noise shapes default to the constant
|
|
135
|
+
one. An unused assignment, baseline, or effect shape may be omitted and is
|
|
136
|
+
not called.
|
|
137
|
+
|
|
138
|
+
`dgp.calibration` reports targets, achieved values, residuals, tolerances,
|
|
139
|
+
and the frozen coefficients. `dgp.characteristics()` and
|
|
140
|
+
`dgp.approximation()` can take a separate evaluation population without
|
|
141
|
+
recalibrating.
|
|
142
|
+
|
|
143
|
+
## Sample and compare
|
|
144
|
+
|
|
145
|
+
`draw_randomness` builds a reusable draw collection;
|
|
146
|
+
`draws.prefix(n)` is the nested-sample contract. `sample(n, seed)` is the
|
|
147
|
+
same mechanism applied to `draw_randomness(n, seed)`.
|
|
148
|
+
|
|
149
|
+
`cate_mse` scores a CATE prediction against conditional truth under explicit
|
|
150
|
+
weights. Pass `population.weights` when the truth and predictions cover the
|
|
151
|
+
calibration population.
|
|
152
|
+
|
|
153
|
+
Core API docstrings describe parameter shapes, units, feasibility, returned
|
|
154
|
+
objects, and runnable examples. Use `help(Targets)`, `help(calibrate)`,
|
|
155
|
+
`help(dgp.sample)`, or `help(cate_mse)` in Python to inspect the API.
|
|
156
|
+
Examples in those docstrings are exercised by the test suite and use only
|
|
157
|
+
the core dependencies.
|
|
158
|
+
|
|
159
|
+
## Truth-assisted fitting
|
|
160
|
+
|
|
161
|
+
Optional truth-assisted fitting is available in `catesim.fitting`.
|
|
162
|
+
From a source tree, `python -m pip install '.[fit]'` installs the extra
|
|
163
|
+
shown above.
|
|
164
|
+
|
|
165
|
+
The fitter requires known CATE on every declared population row. It estimates
|
|
166
|
+
propensity and a pooled baseline from `Y - T * cate(X)`, with a common Gaussian
|
|
167
|
+
noise SD estimated from cross-fitted baseline residuals. It does not estimate
|
|
168
|
+
an unknown causal effect from observational outcomes.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
from catesim import calibrate
|
|
172
|
+
from catesim.examples import make_example
|
|
173
|
+
from catesim.fitting import fit_truth_assisted
|
|
174
|
+
|
|
175
|
+
population, shapes, targets = make_example(population_size=128)
|
|
176
|
+
source = calibrate(population, shapes, targets)
|
|
177
|
+
observed = source.sample(n=1000, seed=123)
|
|
178
|
+
fit = fit_truth_assisted(
|
|
179
|
+
population, observed.X, observed.T, observed.Y,
|
|
180
|
+
cate=source.truth().tau, seed=7, propensity_clip=None,
|
|
181
|
+
)
|
|
182
|
+
fitted = calibrate(fit.population, fit.shapes, fit.targets)
|
|
183
|
+
generated = fitted.sample(n=1000, seed=456)
|
|
184
|
+
original_units_Y = fit.outcome_offset + fit.outcome_scale * generated.Y
|
|
185
|
+
original_units_cate = fit.outcome_scale * fitted.truth(generated.X).tau
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
The result contains read-only fitted surface tables, raw propensity scores,
|
|
189
|
+
calibration inputs, and diagnostics. Fitted shapes support only the declared
|
|
190
|
+
covariate rows; there is no covariate generation or extrapolation. Population
|
|
191
|
+
weights define calibration and sampling, not observation-fitting weights.
|
|
192
|
+
The original-unit transformation is separate from the core's noise-based gauge.
|
|
193
|
+
Changing the returned targets intentionally changes the fitted mechanism.
|
|
194
|
+
|
|
195
|
+
By default, propensity clipping at 1e-6 is explicit and counted. Raw decision
|
|
196
|
+
scores are retained because clipping can erase ordering needed for later
|
|
197
|
+
calibration; use `propensity_clip=None` to keep the original finite score family,
|
|
198
|
+
as above. Residual diagnostics expose mean-model error and deviations from the
|
|
199
|
+
assumed Gaussian, constant-variance noise law. Residual RMS need not equal true
|
|
200
|
+
irreducible noise SD. Defaults and overrides are recorded; there is no tuning
|
|
201
|
+
or automatic reconstruction-quality guarantee. See `help(fit_truth_assisted)`.
|
|
202
|
+
Importing the module or inspecting a result needs no optional dependencies;
|
|
203
|
+
scikit-learn and threadpoolctl are loaded only when fitting is called.
|
catesim-0.1.0/README.md
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# CateSim
|
|
2
|
+
|
|
3
|
+
CateSim (`catesim`) constructs calibrated data-generating processes for conditional average treatment effects.
|
|
4
|
+
Supply a finite covariate population, callable shape functions, and nine
|
|
5
|
+
scientific targets. `calibrate` freezes one mechanism. Ordinary Python loops
|
|
6
|
+
then handle sample sizes, replications, and comparisons.
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
Install with Python 3.11 or later:
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
python -m pip install catesim
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Calibration and sampling use NumPy and SciPy only. Truth-assisted fitting is optional:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
python -m pip install 'catesim[fit]'
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## Calibrate a mechanism
|
|
23
|
+
|
|
24
|
+
For a self-contained example with no downloads:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from catesim import calibrate
|
|
28
|
+
from catesim.examples import make_example
|
|
29
|
+
|
|
30
|
+
population, shapes, targets = make_example(population_size=512, seed=7)
|
|
31
|
+
dgp = calibrate(population, shapes, targets)
|
|
32
|
+
data = dgp.sample(n=1000, seed=123)
|
|
33
|
+
truth = dgp.truth(data.X)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The factory generates a uniformly weighted population with four Gaussian
|
|
37
|
+
covariates and returns deterministic input shapes and feasible default targets.
|
|
38
|
+
Its seed controls the population; the sampling seed controls observations.
|
|
39
|
+
The population support size and sample size are separate choices.
|
|
40
|
+
|
|
41
|
+
To change a target while retaining the same population and input shapes:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from dataclasses import replace
|
|
45
|
+
from catesim import calibrate
|
|
46
|
+
from catesim.examples import make_example
|
|
47
|
+
|
|
48
|
+
population, shapes, targets = make_example()
|
|
49
|
+
weaker = calibrate(population, shapes, replace(targets, q=0.06))
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The other eight scalar targets stay fixed when feasible. Final conditional
|
|
53
|
+
functions may change through calibration; input shapes are not those final
|
|
54
|
+
functions. Modified targets receive the usual feasibility checks.
|
|
55
|
+
|
|
56
|
+
The same example can be constructed explicitly from a user-provided covariate
|
|
57
|
+
matrix, callables, and targets:
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import numpy as np
|
|
61
|
+
from catesim import EmpiricalPopulation, Shapes, Targets, calibrate
|
|
62
|
+
|
|
63
|
+
X = np.random.default_rng(7).normal(size=(512, 4))
|
|
64
|
+
pop = EmpiricalPopulation(X, weights=None, name="example")
|
|
65
|
+
shapes = Shapes(
|
|
66
|
+
assignment=lambda x: x[:, 0],
|
|
67
|
+
baseline=lambda x: x[:, 1] + 0.3 * x[:, 0] ** 2,
|
|
68
|
+
effect=lambda x: np.sin(x[:, 2]) + 0.2 * x[:, 3] ** 2,
|
|
69
|
+
)
|
|
70
|
+
targets = Targets(
|
|
71
|
+
pi=0.3, q=0.12, R0_squared=0.6,
|
|
72
|
+
delta=0.2, s_tau=0.7, nu=1.0,
|
|
73
|
+
rho_be=0.4, rho_ue=-0.2, rho_ub=0.1,
|
|
74
|
+
)
|
|
75
|
+
dgp = calibrate(pop, shapes, targets)
|
|
76
|
+
data = dgp.sample(n=1000, seed=123)
|
|
77
|
+
truth = dgp.truth(data.X)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
The nine targets are:
|
|
81
|
+
|
|
82
|
+
- `pi`: treatment prevalence, the population mean of the propensity.
|
|
83
|
+
- `q`: average overlap, the population mean of propensity times one minus propensity.
|
|
84
|
+
- `R0_squared`: baseline prognostic strength, from zero up to but not including one.
|
|
85
|
+
- `delta`: population mean CATE, in noise-RMS units.
|
|
86
|
+
- `s_tau`: population standard deviation of CATE, in the same units. Zero is a constant effect.
|
|
87
|
+
- `nu`: treated-to-control arm-noise RMS ratio. Zero makes the treated arm noiseless.
|
|
88
|
+
- `rho_be`: correlation of the control conditional mean with propensity.
|
|
89
|
+
- `rho_ue`: correlation of CATE with propensity.
|
|
90
|
+
- `rho_ub`: correlation of the control conditional mean with CATE.
|
|
91
|
+
|
|
92
|
+
Undefined correlations are `None`, not zero. Attainable values and the cases
|
|
93
|
+
where a correlation is undefined are documented in `help(Targets)`.
|
|
94
|
+
|
|
95
|
+
The initial gauge fixes the population mean of the control conditional mean
|
|
96
|
+
at zero and factual noise RMS at one, so `delta` and `s_tau` are in noise units.
|
|
97
|
+
Noise RMS is the square root of the population average conditional noise
|
|
98
|
+
variance, not the factual outcome SD or the average conditional SD.
|
|
99
|
+
Treatment is binary, outcomes are continuous, and arm errors are independent
|
|
100
|
+
standard Gaussians. A finite arm-noise ratio may be zero, which makes the
|
|
101
|
+
treated arm noiseless. Fully noiseless mechanisms are outside this gauge.
|
|
102
|
+
|
|
103
|
+
Shape callables take a covariate matrix and return one value per row. They
|
|
104
|
+
are not copied at calibration time, so they must be deterministic and their
|
|
105
|
+
captured state must stay fixed. Omitted noise shapes default to the constant
|
|
106
|
+
one. An unused assignment, baseline, or effect shape may be omitted and is
|
|
107
|
+
not called.
|
|
108
|
+
|
|
109
|
+
`dgp.calibration` reports targets, achieved values, residuals, tolerances,
|
|
110
|
+
and the frozen coefficients. `dgp.characteristics()` and
|
|
111
|
+
`dgp.approximation()` can take a separate evaluation population without
|
|
112
|
+
recalibrating.
|
|
113
|
+
|
|
114
|
+
## Sample and compare
|
|
115
|
+
|
|
116
|
+
`draw_randomness` builds a reusable draw collection;
|
|
117
|
+
`draws.prefix(n)` is the nested-sample contract. `sample(n, seed)` is the
|
|
118
|
+
same mechanism applied to `draw_randomness(n, seed)`.
|
|
119
|
+
|
|
120
|
+
`cate_mse` scores a CATE prediction against conditional truth under explicit
|
|
121
|
+
weights. Pass `population.weights` when the truth and predictions cover the
|
|
122
|
+
calibration population.
|
|
123
|
+
|
|
124
|
+
Core API docstrings describe parameter shapes, units, feasibility, returned
|
|
125
|
+
objects, and runnable examples. Use `help(Targets)`, `help(calibrate)`,
|
|
126
|
+
`help(dgp.sample)`, or `help(cate_mse)` in Python to inspect the API.
|
|
127
|
+
Examples in those docstrings are exercised by the test suite and use only
|
|
128
|
+
the core dependencies.
|
|
129
|
+
|
|
130
|
+
## Truth-assisted fitting
|
|
131
|
+
|
|
132
|
+
Optional truth-assisted fitting is available in `catesim.fitting`.
|
|
133
|
+
From a source tree, `python -m pip install '.[fit]'` installs the extra
|
|
134
|
+
shown above.
|
|
135
|
+
|
|
136
|
+
The fitter requires known CATE on every declared population row. It estimates
|
|
137
|
+
propensity and a pooled baseline from `Y - T * cate(X)`, with a common Gaussian
|
|
138
|
+
noise SD estimated from cross-fitted baseline residuals. It does not estimate
|
|
139
|
+
an unknown causal effect from observational outcomes.
|
|
140
|
+
|
|
141
|
+
```python
|
|
142
|
+
from catesim import calibrate
|
|
143
|
+
from catesim.examples import make_example
|
|
144
|
+
from catesim.fitting import fit_truth_assisted
|
|
145
|
+
|
|
146
|
+
population, shapes, targets = make_example(population_size=128)
|
|
147
|
+
source = calibrate(population, shapes, targets)
|
|
148
|
+
observed = source.sample(n=1000, seed=123)
|
|
149
|
+
fit = fit_truth_assisted(
|
|
150
|
+
population, observed.X, observed.T, observed.Y,
|
|
151
|
+
cate=source.truth().tau, seed=7, propensity_clip=None,
|
|
152
|
+
)
|
|
153
|
+
fitted = calibrate(fit.population, fit.shapes, fit.targets)
|
|
154
|
+
generated = fitted.sample(n=1000, seed=456)
|
|
155
|
+
original_units_Y = fit.outcome_offset + fit.outcome_scale * generated.Y
|
|
156
|
+
original_units_cate = fit.outcome_scale * fitted.truth(generated.X).tau
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
The result contains read-only fitted surface tables, raw propensity scores,
|
|
160
|
+
calibration inputs, and diagnostics. Fitted shapes support only the declared
|
|
161
|
+
covariate rows; there is no covariate generation or extrapolation. Population
|
|
162
|
+
weights define calibration and sampling, not observation-fitting weights.
|
|
163
|
+
The original-unit transformation is separate from the core's noise-based gauge.
|
|
164
|
+
Changing the returned targets intentionally changes the fitted mechanism.
|
|
165
|
+
|
|
166
|
+
By default, propensity clipping at 1e-6 is explicit and counted. Raw decision
|
|
167
|
+
scores are retained because clipping can erase ordering needed for later
|
|
168
|
+
calibration; use `propensity_clip=None` to keep the original finite score family,
|
|
169
|
+
as above. Residual diagnostics expose mean-model error and deviations from the
|
|
170
|
+
assumed Gaussian, constant-variance noise law. Residual RMS need not equal true
|
|
171
|
+
irreducible noise SD. Defaults and overrides are recorded; there is no tuning
|
|
172
|
+
or automatic reconstruction-quality guarantee. See `help(fit_truth_assisted)`.
|
|
173
|
+
Importing the module or inspecting a result needs no optional dependencies;
|
|
174
|
+
scikit-learn and threadpoolctl are loaded only when fitting is called.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "catesim"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Calibrated simulation of conditional average treatment effects"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
authors = [
|
|
14
|
+
{name = "Alireza S. Mahani"},
|
|
15
|
+
{name = "Mansour T. A. Sharabiani"},
|
|
16
|
+
{name = "Alex Bottle"},
|
|
17
|
+
]
|
|
18
|
+
keywords = [
|
|
19
|
+
"causal inference",
|
|
20
|
+
"conditional average treatment effect",
|
|
21
|
+
"simulation",
|
|
22
|
+
"treatment effects",
|
|
23
|
+
]
|
|
24
|
+
classifiers = [
|
|
25
|
+
"Development Status :: 4 - Beta",
|
|
26
|
+
"Intended Audience :: Science/Research",
|
|
27
|
+
"Operating System :: OS Independent",
|
|
28
|
+
"Programming Language :: Python :: 3",
|
|
29
|
+
"Programming Language :: Python :: 3.11",
|
|
30
|
+
"Programming Language :: Python :: 3.12",
|
|
31
|
+
"Programming Language :: Python :: 3.13",
|
|
32
|
+
"Topic :: Scientific/Engineering",
|
|
33
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
34
|
+
"Typing :: Typed",
|
|
35
|
+
]
|
|
36
|
+
dependencies = ["numpy>=1.26", "scipy>=1.11"]
|
|
37
|
+
|
|
38
|
+
[project.optional-dependencies]
|
|
39
|
+
dev = ["pytest>=8"]
|
|
40
|
+
fit = ["scikit-learn>=1.6", "threadpoolctl>=3.1"]
|
|
41
|
+
|
|
42
|
+
[tool.setuptools.dynamic]
|
|
43
|
+
version = {attr = "catesim._version.__version__"}
|
|
44
|
+
|
|
45
|
+
[tool.setuptools.packages.find]
|
|
46
|
+
where = ["src"]
|
|
47
|
+
|
|
48
|
+
[tool.pytest.ini_options]
|
|
49
|
+
testpaths = ["tests"]
|
catesim-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Calibrated simulation of conditional average treatment effects.
|
|
2
|
+
|
|
3
|
+
Supply an ``EmpiricalPopulation``, deterministic input ``Shapes``, and
|
|
4
|
+
scientific ``Targets`` to ``calibrate``. The resulting ``DGP`` freezes one
|
|
5
|
+
mechanism before sampling. Its ``Truth`` describes conditional functions;
|
|
6
|
+
``Dataset`` contains observations. ``draw_randomness`` supports paired and
|
|
7
|
+
nested samples, and ``cate_mse`` evaluates effects under explicit weights.
|
|
8
|
+
|
|
9
|
+
Examples
|
|
10
|
+
--------
|
|
11
|
+
>>> from catesim.examples import make_example
|
|
12
|
+
>>> population, shapes, targets = make_example()
|
|
13
|
+
>>> dgp = calibrate(population, shapes, targets)
|
|
14
|
+
>>> dgp.sample(n=100, seed=123).Y.shape
|
|
15
|
+
(100,)
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from ._version import __version__
|
|
19
|
+
from .diagnostics import linear_basis, sample_diagnostics
|
|
20
|
+
from .draws import RandomDraws, draw_randomness
|
|
21
|
+
from .mechanism import (
|
|
22
|
+
CalibrationError,
|
|
23
|
+
CalibrationReport,
|
|
24
|
+
DGP,
|
|
25
|
+
Dataset,
|
|
26
|
+
Shapes,
|
|
27
|
+
Targets,
|
|
28
|
+
Truth,
|
|
29
|
+
calibrate,
|
|
30
|
+
)
|
|
31
|
+
from .metrics import cate_mse
|
|
32
|
+
from .population import EmpiricalPopulation
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"CalibrationError",
|
|
36
|
+
"CalibrationReport",
|
|
37
|
+
"DGP",
|
|
38
|
+
"Dataset",
|
|
39
|
+
"EmpiricalPopulation",
|
|
40
|
+
"RandomDraws",
|
|
41
|
+
"Shapes",
|
|
42
|
+
"Targets",
|
|
43
|
+
"Truth",
|
|
44
|
+
"calibrate",
|
|
45
|
+
"cate_mse",
|
|
46
|
+
"draw_randomness",
|
|
47
|
+
"linear_basis",
|
|
48
|
+
"sample_diagnostics",
|
|
49
|
+
]
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Sample diagnostics and the default linear approximation basis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from .population import EmpiricalPopulation
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def linear_basis(X):
|
|
11
|
+
"""Build an intercept column followed by the numeric covariates.
|
|
12
|
+
|
|
13
|
+
Parameters
|
|
14
|
+
----------
|
|
15
|
+
X : array_like of shape (n, p)
|
|
16
|
+
Covariates already encoded numerically.
|
|
17
|
+
|
|
18
|
+
Returns
|
|
19
|
+
-------
|
|
20
|
+
ndarray of shape (n, p + 1)
|
|
21
|
+
Float matrix whose first column contains ones.
|
|
22
|
+
|
|
23
|
+
Raises
|
|
24
|
+
------
|
|
25
|
+
ValueError
|
|
26
|
+
If ``X`` is not two-dimensional.
|
|
27
|
+
|
|
28
|
+
Examples
|
|
29
|
+
--------
|
|
30
|
+
>>> linear_basis([[2.0], [3.0]]).tolist()
|
|
31
|
+
[[1.0, 2.0], [1.0, 3.0]]
|
|
32
|
+
"""
|
|
33
|
+
matrix = np.asarray(X, dtype=float)
|
|
34
|
+
if matrix.ndim != 2:
|
|
35
|
+
raise ValueError("linear basis expects a covariate matrix")
|
|
36
|
+
return np.column_stack([np.ones(len(matrix)), matrix])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _row_keys(X):
|
|
40
|
+
# Adding zero maps -0.0 to +0.0 so signed zeros compare as the same value.
|
|
41
|
+
packed = np.ascontiguousarray(np.asarray(X, dtype=np.float64) + 0.0)
|
|
42
|
+
if packed.ndim != 2 or packed.shape[1] == 0:
|
|
43
|
+
raise ValueError("covariate representation has no columns to compare")
|
|
44
|
+
width = packed.dtype.itemsize * packed.shape[1]
|
|
45
|
+
return packed.view(np.dtype((np.void, width))).ravel()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def sample_diagnostics(data, population):
|
|
49
|
+
"""Realized treatment prevalence and covariate-value coverage.
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
data : Dataset or object with X and T attributes
|
|
54
|
+
Nonempty finite sample matrix ``X`` and a row-aligned treatment vector
|
|
55
|
+
``T``. Generated samples use binary treatment; supplied treatment
|
|
56
|
+
values are averaged as provided.
|
|
57
|
+
population : EmpiricalPopulation
|
|
58
|
+
Reference population with the same covariate representation.
|
|
59
|
+
|
|
60
|
+
Returns
|
|
61
|
+
-------
|
|
62
|
+
dict
|
|
63
|
+
``n`` is the sample row count, ``prevalence`` is the unweighted mean
|
|
64
|
+
of treatment, and ``coverage`` is the total population weight of rows
|
|
65
|
+
whose covariate values occur at least once in the sample.
|
|
66
|
+
|
|
67
|
+
Raises
|
|
68
|
+
------
|
|
69
|
+
TypeError
|
|
70
|
+
If the population has the wrong type or the data lack ``X`` or ``T``.
|
|
71
|
+
ValueError
|
|
72
|
+
If sample arrays are empty, nonfinite, misaligned, or use an
|
|
73
|
+
incompatible or zero-column covariate representation.
|
|
74
|
+
|
|
75
|
+
Notes
|
|
76
|
+
-----
|
|
77
|
+
Coverage compares float64 covariate values exactly, treating signed zeros
|
|
78
|
+
as equal; row identifiers are not used. Duplicate population values retain
|
|
79
|
+
their combined weight. These are sample summaries, not the DGP's true
|
|
80
|
+
prevalence or overlap.
|
|
81
|
+
|
|
82
|
+
Examples
|
|
83
|
+
--------
|
|
84
|
+
>>> from catesim import calibrate
|
|
85
|
+
>>> from catesim.examples import make_example
|
|
86
|
+
>>> population, shapes, targets = make_example()
|
|
87
|
+
>>> sample = calibrate(population, shapes, targets).sample(100, seed=123)
|
|
88
|
+
>>> report = sample_diagnostics(sample, population)
|
|
89
|
+
>>> report["n"]
|
|
90
|
+
100
|
|
91
|
+
>>> 0.0 < report["coverage"] <= 1.0
|
|
92
|
+
True
|
|
93
|
+
"""
|
|
94
|
+
if not isinstance(population, EmpiricalPopulation):
|
|
95
|
+
raise TypeError("population must be an EmpiricalPopulation")
|
|
96
|
+
try:
|
|
97
|
+
observed = data.X
|
|
98
|
+
treatment = data.T
|
|
99
|
+
except AttributeError as exc:
|
|
100
|
+
raise TypeError("data must provide X and T") from exc
|
|
101
|
+
observed = np.asarray(observed, dtype=float)
|
|
102
|
+
treatment = np.asarray(treatment, dtype=float)
|
|
103
|
+
if observed.ndim != 2 or observed.shape[1] != population.X.shape[1]:
|
|
104
|
+
raise ValueError("sample covariates do not match the population representation")
|
|
105
|
+
if (
|
|
106
|
+
not len(observed)
|
|
107
|
+
or treatment.shape != (len(observed),)
|
|
108
|
+
or not np.isfinite(treatment).all()
|
|
109
|
+
or not np.isfinite(observed).all()
|
|
110
|
+
):
|
|
111
|
+
raise ValueError("sample must contain one finite treatment per covariate row")
|
|
112
|
+
present = np.isin(_row_keys(population.X), np.unique(_row_keys(observed)))
|
|
113
|
+
return {
|
|
114
|
+
"n": int(len(observed)),
|
|
115
|
+
"prevalence": float(treatment.mean()),
|
|
116
|
+
"coverage": float(population.weights @ present),
|
|
117
|
+
}
|