Metadata-Version: 2.4
Name: catesim
Version: 0.1.0
Summary: Calibrated simulation of conditional average treatment effects
Author: Alireza S. Mahani, Mansour T. A. Sharabiani, Alex Bottle
License-Expression: MIT
Keywords: causal inference,conditional average treatment effect,simulation,treatment effects
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.26
Requires-Dist: scipy>=1.11
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Provides-Extra: fit
Requires-Dist: scikit-learn>=1.6; extra == "fit"
Requires-Dist: threadpoolctl>=3.1; extra == "fit"
Dynamic: license-file

# CateSim

CateSim (`catesim`) constructs calibrated data-generating processes for conditional average treatment effects.
Supply a finite covariate population, callable shape functions, and nine
scientific targets. `calibrate` freezes one mechanism. Ordinary Python loops
then handle sample sizes, replications, and comparisons.

## Install

Install with Python 3.11 or later:

```bash
python -m pip install catesim
```

Calibration and sampling use NumPy and SciPy only. Truth-assisted fitting is optional:

```bash
python -m pip install 'catesim[fit]'
```

## Calibrate a mechanism

For a self-contained example with no downloads:

```python
from catesim import calibrate
from catesim.examples import make_example

population, shapes, targets = make_example(population_size=512, seed=7)
dgp = calibrate(population, shapes, targets)
data = dgp.sample(n=1000, seed=123)
truth = dgp.truth(data.X)
```

The factory generates a uniformly weighted population with four Gaussian
covariates and returns deterministic input shapes and feasible default targets.
Its seed controls the population; the sampling seed controls observations.
The population support size and sample size are separate choices.

To change a target while retaining the same population and input shapes:

```python
from dataclasses import replace
from catesim import calibrate
from catesim.examples import make_example

population, shapes, targets = make_example()
weaker = calibrate(population, shapes, replace(targets, q=0.06))
```

The other eight scalar targets stay fixed when feasible. Final conditional
functions may change through calibration; input shapes are not those final
functions. Modified targets receive the usual feasibility checks.

The same example can be constructed explicitly from a user-provided covariate
matrix, callables, and targets:

```python
import numpy as np
from catesim import EmpiricalPopulation, Shapes, Targets, calibrate

X = np.random.default_rng(7).normal(size=(512, 4))
pop = EmpiricalPopulation(X, weights=None, name="example")
shapes = Shapes(
    assignment=lambda x: x[:, 0],
    baseline=lambda x: x[:, 1] + 0.3 * x[:, 0] ** 2,
    effect=lambda x: np.sin(x[:, 2]) + 0.2 * x[:, 3] ** 2,
)
targets = Targets(
    pi=0.3, q=0.12, R0_squared=0.6,
    delta=0.2, s_tau=0.7, nu=1.0,
    rho_be=0.4, rho_ue=-0.2, rho_ub=0.1,
)
dgp = calibrate(pop, shapes, targets)
data = dgp.sample(n=1000, seed=123)
truth = dgp.truth(data.X)
```

The nine targets are:

- `pi`: treatment prevalence, the population mean of the propensity.
- `q`: average overlap, the population mean of propensity times one minus propensity.
- `R0_squared`: baseline prognostic strength, from zero up to but not including one.
- `delta`: population mean CATE, in noise-RMS units.
- `s_tau`: population standard deviation of CATE, in the same units. Zero is a constant effect.
- `nu`: treated-to-control arm-noise RMS ratio. Zero makes the treated arm noiseless.
- `rho_be`: correlation of the control conditional mean with propensity.
- `rho_ue`: correlation of CATE with propensity.
- `rho_ub`: correlation of the control conditional mean with CATE.

Undefined correlations are `None`, not zero. Attainable values and the cases
where a correlation is undefined are documented in `help(Targets)`.

The initial gauge fixes the population mean of the control conditional mean
at zero and factual noise RMS at one, so `delta` and `s_tau` are in noise units.
Noise RMS is the square root of the population average conditional noise
variance, not the factual outcome SD or the average conditional SD.
Treatment is binary, outcomes are continuous, and arm errors are independent
standard Gaussians. A finite arm-noise ratio may be zero, which makes the
treated arm noiseless. Fully noiseless mechanisms are outside this gauge.

Shape callables take a covariate matrix and return one value per row. They
are not copied at calibration time, so they must be deterministic and their
captured state must stay fixed. Omitted noise shapes default to the constant
one. An unused assignment, baseline, or effect shape may be omitted and is
not called.

`dgp.calibration` reports targets, achieved values, residuals, tolerances,
and the frozen coefficients. `dgp.characteristics()` and
`dgp.approximation()` can take a separate evaluation population without
recalibrating.

## Sample and compare

`draw_randomness` builds a reusable draw collection;
`draws.prefix(n)` is the nested-sample contract. `sample(n, seed)` is the
same mechanism applied to `draw_randomness(n, seed)`.

`cate_mse` scores a CATE prediction against conditional truth under explicit
weights. Pass `population.weights` when the truth and predictions cover the
calibration population.

Core API docstrings describe parameter shapes, units, feasibility, returned
objects, and runnable examples. Use `help(Targets)`, `help(calibrate)`,
`help(dgp.sample)`, or `help(cate_mse)` in Python to inspect the API.
Examples in those docstrings are exercised by the test suite and use only
the core dependencies.

## Truth-assisted fitting

Optional truth-assisted fitting is available in `catesim.fitting`.
From a source tree, `python -m pip install '.[fit]'` installs the extra
shown above.

The fitter requires known CATE on every declared population row. It estimates
propensity and a pooled baseline from `Y - T * cate(X)`, with a common Gaussian
noise SD estimated from cross-fitted baseline residuals. It does not estimate
an unknown causal effect from observational outcomes.

```python
from catesim import calibrate
from catesim.examples import make_example
from catesim.fitting import fit_truth_assisted

population, shapes, targets = make_example(population_size=128)
source = calibrate(population, shapes, targets)
observed = source.sample(n=1000, seed=123)
fit = fit_truth_assisted(
    population, observed.X, observed.T, observed.Y,
    cate=source.truth().tau, seed=7, propensity_clip=None,
)
fitted = calibrate(fit.population, fit.shapes, fit.targets)
generated = fitted.sample(n=1000, seed=456)
original_units_Y = fit.outcome_offset + fit.outcome_scale * generated.Y
original_units_cate = fit.outcome_scale * fitted.truth(generated.X).tau
```

The result contains read-only fitted surface tables, raw propensity scores,
calibration inputs, and diagnostics. Fitted shapes support only the declared
covariate rows; there is no covariate generation or extrapolation. Population
weights define calibration and sampling, not observation-fitting weights.
The original-unit transformation is separate from the core's noise-based gauge.
Changing the returned targets intentionally changes the fitted mechanism.

By default, propensity clipping at 1e-6 is explicit and counted. Raw decision
scores are retained because clipping can erase ordering needed for later
calibration; use `propensity_clip=None` to keep the original finite score family,
as above. Residual diagnostics expose mean-model error and deviations from the
assumed Gaussian, constant-variance noise law. Residual RMS need not equal true
irreducible noise SD. Defaults and overrides are recorded; there is no tuning
or automatic reconstruction-quality guarantee. See `help(fit_truth_assisted)`.
Importing the module or inspecting a result needs no optional dependencies;
scikit-learn and threadpoolctl are loaded only when fitting is called.
