catesim 0.1.0__py3-none-any.whl

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/__init__.py 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
+ ]
catesim/_arrays.py ADDED
@@ -0,0 +1,9 @@
1
+ """Owned, read-only numeric copies."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def readonly(values, dtype=float):
7
+ array = np.array(values, dtype=dtype, copy=True)
8
+ array.flags.writeable = False
9
+ return array
catesim/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Package version. This module must stay free of third-party imports."""
2
+
3
+ __version__ = "0.1.0"
catesim/diagnostics.py ADDED
@@ -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
+ }
catesim/draws.py ADDED
@@ -0,0 +1,170 @@
1
+ """Population-independent draws for paired samples."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, fields
6
+
7
+ import numpy as np
8
+
9
+ from ._arrays import readonly
10
+
11
+
12
+ def _positive_int(value, name):
13
+ if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or int(value) <= 0:
14
+ raise ValueError(f"{name} must be a positive integer")
15
+ return int(value)
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class RandomDraws:
20
+ """Row uniforms, treatment uniforms, and standard normal arm errors.
21
+
22
+ Parameters
23
+ ----------
24
+ row_uniforms : array_like of shape (n,)
25
+ Row-selection uniforms in [0, 1), applied to a population's weighted CDF.
26
+ treatment_uniforms : array_like of shape (n,)
27
+ Uniforms in [0, 1), compared with each sampled row's propensity.
28
+ control_noise, treated_noise : array_like of shape (n,)
29
+ Standardized error realizations for the two arms. ``draw_randomness``
30
+ generates independent standard normals; direct construction accepts
31
+ any finite realizations for controlled comparisons.
32
+
33
+ Attributes
34
+ ----------
35
+ row_uniforms, treatment_uniforms, control_noise, treated_noise : ndarray
36
+ Owned, read-only float vectors of the same nonzero length.
37
+
38
+ Raises
39
+ ------
40
+ ValueError
41
+ If a vector is empty, nonfinite, or misaligned, or uniforms are outside
42
+ [0, 1).
43
+
44
+ Notes
45
+ -----
46
+ Draws are population-independent. Sharing row uniforms across different
47
+ populations does not imply equal sampled rows. Sharing treatment uniforms
48
+ across different propensities does not imply equal treatment assignments.
49
+
50
+ Examples
51
+ --------
52
+ >>> draws = draw_randomness(20, seed=123)
53
+ >>> len(draws.prefix(5))
54
+ 5
55
+ """
56
+
57
+ row_uniforms: np.ndarray
58
+ treatment_uniforms: np.ndarray
59
+ control_noise: np.ndarray
60
+ treated_noise: np.ndarray
61
+
62
+ def __post_init__(self):
63
+ size = None
64
+ for field in fields(self):
65
+ values = readonly(getattr(self, field.name))
66
+ if values.ndim != 1 or not len(values) or not np.isfinite(values).all():
67
+ raise ValueError("draws must be nonempty finite vectors of equal length")
68
+ if size is None:
69
+ size = len(values)
70
+ elif len(values) != size:
71
+ raise ValueError("draws must be nonempty finite vectors of equal length")
72
+ if field.name.endswith("uniforms") and ((values < 0).any() or (values >= 1).any()):
73
+ raise ValueError("uniform draws must lie in [0, 1)")
74
+ object.__setattr__(self, field.name, values)
75
+
76
+ def __len__(self):
77
+ return len(self.row_uniforms)
78
+
79
+ def __repr__(self):
80
+ return f"RandomDraws(n={len(self)})"
81
+
82
+ def prefix(self, n):
83
+ """Return the first ``n`` realizations in every draw stream.
84
+
85
+ Parameters
86
+ ----------
87
+ n : int
88
+ Positive prefix length no greater than ``len(self)``.
89
+
90
+ Returns
91
+ -------
92
+ RandomDraws
93
+ A new read-only collection for a nested sample.
94
+
95
+ Raises
96
+ ------
97
+ ValueError
98
+ If ``n`` is not a positive integer or exceeds this collection.
99
+
100
+ Examples
101
+ --------
102
+ >>> import numpy as np
103
+ >>> draws = draw_randomness(20, seed=123)
104
+ >>> np.array_equal(draws.prefix(5).control_noise, draws.control_noise[:5])
105
+ True
106
+ """
107
+ n = _positive_int(n, "prefix length")
108
+ if n > len(self):
109
+ raise ValueError("prefix exceeds the draw collection")
110
+ return RandomDraws(
111
+ self.row_uniforms[:n],
112
+ self.treatment_uniforms[:n],
113
+ self.control_noise[:n],
114
+ self.treated_noise[:n],
115
+ )
116
+
117
+
118
+ def draw_randomness(n, seed):
119
+ """Draw population-independent random inputs from an explicit seed.
120
+
121
+ Parameters
122
+ ----------
123
+ n : int
124
+ Positive number of realizations per stream. Booleans are rejected.
125
+ seed : int or sequence of int
126
+ Nonnegative entropy accepted by ``numpy.random.SeedSequence``.
127
+ ``None`` and Python booleans are rejected.
128
+
129
+ Returns
130
+ -------
131
+ RandomDraws
132
+ Four read-only vectors: row uniforms, treatment uniforms, and independent
133
+ standard-normal errors for control and treated outcomes.
134
+
135
+ Raises
136
+ ------
137
+ ValueError
138
+ If ``n`` is not a positive integer, ``seed`` is ``None`` or a Python
139
+ boolean, or seed entropy is invalid.
140
+ TypeError
141
+ If NumPy cannot interpret the seed type.
142
+
143
+ Notes
144
+ -----
145
+ Four PCG64 streams are spawned in the order listed above. The first ``k``
146
+ draws equal those from ``draw_randomness(k, seed)``. The global NumPy
147
+ random state is not used. ``DGP.sample(n, seed)`` applies this collection
148
+ to a frozen mechanism without recalibration.
149
+
150
+ Examples
151
+ --------
152
+ >>> import numpy as np
153
+ >>> short = draw_randomness(5, seed=123)
154
+ >>> long = draw_randomness(20, seed=123)
155
+ >>> np.array_equal(short.row_uniforms, long.prefix(5).row_uniforms)
156
+ True
157
+ """
158
+ n = _positive_int(n, "sample size")
159
+ if seed is None or isinstance(seed, bool):
160
+ raise ValueError("an explicit seed is required")
161
+ generators = [
162
+ np.random.Generator(np.random.PCG64(child))
163
+ for child in np.random.SeedSequence(seed).spawn(4)
164
+ ]
165
+ return RandomDraws(
166
+ generators[0].random(n),
167
+ generators[1].random(n),
168
+ generators[2].normal(size=n),
169
+ generators[3].normal(size=n),
170
+ )
catesim/examples.py ADDED
@@ -0,0 +1,105 @@
1
+ """A self-contained population and mechanism specification for learning CateSim."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+ from .mechanism import Shapes, Targets
8
+ from .population import EmpiricalPopulation
9
+
10
+ __all__ = ["make_example"]
11
+
12
+
13
+ def _assignment(X):
14
+ return X[:, 0]
15
+
16
+
17
+ def _baseline(X):
18
+ return X[:, 1] + 0.3 * X[:, 0] ** 2
19
+
20
+
21
+ def _effect(X):
22
+ return np.sin(X[:, 2]) + 0.2 * X[:, 3] ** 2
23
+
24
+
25
+ def make_example(
26
+ population_size: int = 512, seed: int = 7
27
+ ) -> tuple[EmpiricalPopulation, Shapes, Targets]:
28
+ """Create a reproducible example population, input shapes, and targets.
29
+
30
+ Parameters
31
+ ----------
32
+ population_size : int, default=512
33
+ Number of rows in the empirical covariate population, at least four.
34
+ This is the population support size, not the number of observations
35
+ later requested from a calibrated mechanism.
36
+ seed : int, default=7
37
+ Nonnegative integer seed for generating the covariates with a local
38
+ NumPy random generator. The global random state is not changed.
39
+ Dataset sampling uses a separate seed supplied to ``DGP.sample``.
40
+
41
+ Returns
42
+ -------
43
+ population : EmpiricalPopulation
44
+ Four independent standard-normal covariates with uniform row weights.
45
+ The population owns a read-only copy of the generated matrix.
46
+ shapes : Shapes
47
+ Assignment index ``X[:, 0]``, baseline shape
48
+ ``X[:, 1] + 0.3 * X[:, 0]**2``, and effect shape
49
+ ``sin(X[:, 2]) + 0.2 * X[:, 3]**2``. Both noise shapes are constant one.
50
+ These deterministic input shapes are not the final conditional means
51
+ or CATE, which are constructed by calibration.
52
+ targets : Targets
53
+ Explicit defaults: ``pi=0.3``, ``q=0.12``, ``R0_squared=0.6``,
54
+ ``delta=0.2``, ``s_tau=0.7``, ``nu=1.0``, ``rho_be=0.4``,
55
+ ``rho_ue=-0.2``, and ``rho_ub=0.1``. These stay fixed across seeds.
56
+
57
+ Raises
58
+ ------
59
+ ValueError
60
+ If the support size is not an integer of at least four, or the seed
61
+ is not a nonnegative integer. Booleans are rejected for either input.
62
+
63
+ Notes
64
+ -----
65
+ This function generates inputs without calibrating or sampling a DGP.
66
+ Each call returns new population, shape, and target objects. Four support
67
+ rows are the minimum for the three nondegenerate aligned surfaces in this
68
+ example; ``calibrate`` performs its usual feasibility and numerical checks.
69
+ No downloads, fitted models, or optional dependencies are needed.
70
+
71
+ Examples
72
+ --------
73
+ Construct and sample a calibrated mechanism:
74
+
75
+ >>> from catesim import calibrate
76
+ >>> population, shapes, targets = make_example()
77
+ >>> population.X.shape
78
+ (512, 4)
79
+ >>> dgp = calibrate(population, shapes, targets)
80
+ >>> data = dgp.sample(n=1000, seed=123)
81
+ >>> data.X.shape
82
+ (1000, 4)
83
+ >>> abs(dgp.calibration.achieved["q"] - targets.q) < 1e-8
84
+ True
85
+
86
+ Change overlap while keeping the same inputs and other scalar targets:
87
+
88
+ >>> from dataclasses import replace
89
+ >>> weaker = calibrate(population, shapes, replace(targets, q=0.06))
90
+ >>> abs(weaker.calibration.achieved["rho_be"] - targets.rho_be) < 1e-8
91
+ True
92
+ """
93
+ if isinstance(population_size, bool) or not isinstance(population_size, (int, np.integer)) or population_size < 4:
94
+ raise ValueError("population_size must be an integer of at least four")
95
+ if isinstance(seed, bool) or not isinstance(seed, (int, np.integer)) or seed < 0:
96
+ raise ValueError("seed must be a nonnegative integer")
97
+ X = np.random.default_rng(int(seed)).normal(size=(int(population_size), 4))
98
+ population = EmpiricalPopulation(X, name="seeded_example")
99
+ shapes = Shapes(assignment=_assignment, baseline=_baseline, effect=_effect)
100
+ targets = Targets(
101
+ pi=0.3, q=0.12, R0_squared=0.6,
102
+ delta=0.2, s_tau=0.7, nu=1.0,
103
+ rho_be=0.4, rho_ue=-0.2, rho_ub=0.1,
104
+ )
105
+ return population, shapes, targets