experiment-toolkit 0.1.0__tar.gz → 0.2.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.
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/CHANGELOG.md +22 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/PKG-INFO +7 -3
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/README.md +6 -2
- experiment_toolkit-0.2.0/docs/hero.png +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/pyproject.toml +4 -1
- experiment_toolkit-0.2.0/scripts/make_hero.py +86 -0
- experiment_toolkit-0.2.0/src/experiment_toolkit/__init__.py +41 -0
- experiment_toolkit-0.2.0/src/experiment_toolkit/cs_did.py +292 -0
- experiment_toolkit-0.2.0/src/experiment_toolkit/sample_size.py +102 -0
- experiment_toolkit-0.2.0/src/experiment_toolkit/sensitivity.py +211 -0
- experiment_toolkit-0.2.0/src/experiment_toolkit/sequential.py +152 -0
- experiment_toolkit-0.2.0/tests/test_v02_additions.py +198 -0
- experiment_toolkit-0.1.0/src/experiment_toolkit/__init__.py +0 -17
- experiment_toolkit-0.1.0/src/experiment_toolkit/sample_size.py +0 -61
- experiment_toolkit-0.1.0/src/experiment_toolkit/sequential.py +0 -69
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/.github/workflows/ci.yml +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/.github/workflows/publish.yml +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/.gitignore +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/CONTRIBUTING.md +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/LICENSE +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/src/experiment_toolkit/cli.py +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/src/experiment_toolkit/cuped.py +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/src/experiment_toolkit/ratio.py +0 -0
- {experiment_toolkit-0.1.0 → experiment_toolkit-0.2.0}/tests/test_toolkit.py +0 -0
|
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [0.2.0] - 2026-04-19
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- `cs_did`: Callaway & Sant'Anna (2021) staggered difference-in-differences
|
|
12
|
+
with never-treated controls and a unit cluster bootstrap for inference.
|
|
13
|
+
Includes `simulate_staggered_panel` for teaching / tests. Robust to
|
|
14
|
+
treatment-effect heterogeneity across cohorts — unlike TWFE.
|
|
15
|
+
- `sensitivity`: E-value (VanderWeele & Ding 2017) for risk-ratio / odds-ratio
|
|
16
|
+
/ standardised-mean-difference effects and Rosenbaum bounds for matched-pair
|
|
17
|
+
Wilcoxon signed-rank tests (`rosenbaum_wilcoxon_bounds`,
|
|
18
|
+
`rosenbaum_gamma_threshold`).
|
|
19
|
+
- `sequential`: `msprt_cuped_pvalue` composes CUPED variance reduction with
|
|
20
|
+
mSPRT to tighten always-valid peeks.
|
|
21
|
+
- `sample_size`: `rho` parameter added to `sample_size_for_mde` / `mde_for_n`
|
|
22
|
+
for CUPED-aware power planning. Zero-default keeps v0.1 behaviour.
|
|
23
|
+
New `cuped_sample_size_summary` reports side-by-side naive vs CUPED sample
|
|
24
|
+
sizes and percent savings.
|
|
25
|
+
|
|
26
|
+
### Notes
|
|
27
|
+
- Pure-numpy / scipy; no new runtime dependencies.
|
|
28
|
+
- All v0.1.0 APIs remain backwards compatible.
|
|
29
|
+
|
|
8
30
|
## [0.1.0] - 2026-04-19
|
|
9
31
|
|
|
10
32
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: experiment-toolkit
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Small, well-tested utilities for online controlled experiments: sample size, CUPED, sequential testing, delta-method variance.
|
|
5
5
|
Project-URL: Homepage, https://github.com/wavde/experiment-toolkit
|
|
6
6
|
Project-URL: Issues, https://github.com/wavde/experiment-toolkit/issues
|
|
@@ -54,14 +54,18 @@ Description-Content-Type: text/markdown
|
|
|
54
54
|
[](https://pypi.org/project/experiment-toolkit/)
|
|
55
55
|

|
|
56
56
|
|
|
57
|
+

|
|
58
|
+
|
|
57
59
|
## What's inside
|
|
58
60
|
|
|
59
61
|
| Module | Purpose |
|
|
60
62
|
|--------|---------|
|
|
61
|
-
| `sample_size` |
|
|
63
|
+
| `sample_size` | Per-arm sample size / MDE, CUPED-aware (`rho` kwarg) |
|
|
62
64
|
| `cuped` | Deng et al. (2013) CUPED variance reduction |
|
|
63
65
|
| `ratio` | Delta-method variance for ratio metrics (revenue/session, etc.) |
|
|
64
|
-
| `sequential` | mSPRT always-valid p-values
|
|
66
|
+
| `sequential` | mSPRT always-valid p-values, with optional CUPED compounding |
|
|
67
|
+
| `cs_did` | Callaway & Sant'Anna (2021) staggered DiD, robust to heterogeneous effects |
|
|
68
|
+
| `sensitivity` | E-value and Rosenbaum bounds for observational-causal sensitivity |
|
|
65
69
|
|
|
66
70
|
Every function is tested, typed, and has a reference to the paper it implements.
|
|
67
71
|
|
|
@@ -7,14 +7,18 @@
|
|
|
7
7
|
[](https://pypi.org/project/experiment-toolkit/)
|
|
8
8
|

|
|
9
9
|
|
|
10
|
+

|
|
11
|
+
|
|
10
12
|
## What's inside
|
|
11
13
|
|
|
12
14
|
| Module | Purpose |
|
|
13
15
|
|--------|---------|
|
|
14
|
-
| `sample_size` |
|
|
16
|
+
| `sample_size` | Per-arm sample size / MDE, CUPED-aware (`rho` kwarg) |
|
|
15
17
|
| `cuped` | Deng et al. (2013) CUPED variance reduction |
|
|
16
18
|
| `ratio` | Delta-method variance for ratio metrics (revenue/session, etc.) |
|
|
17
|
-
| `sequential` | mSPRT always-valid p-values
|
|
19
|
+
| `sequential` | mSPRT always-valid p-values, with optional CUPED compounding |
|
|
20
|
+
| `cs_did` | Callaway & Sant'Anna (2021) staggered DiD, robust to heterogeneous effects |
|
|
21
|
+
| `sensitivity` | E-value and Rosenbaum bounds for observational-causal sensitivity |
|
|
18
22
|
|
|
19
23
|
Every function is tested, typed, and has a reference to the paper it implements.
|
|
20
24
|
|
|
Binary file
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "experiment-toolkit"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Small, well-tested utilities for online controlled experiments: sample size, CUPED, sequential testing, delta-method variance."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = { file = "LICENSE" }
|
|
@@ -46,6 +46,9 @@ target-version = "py310"
|
|
|
46
46
|
[tool.ruff.lint]
|
|
47
47
|
select = ["E", "F", "N", "W", "UP", "B", "SIM"]
|
|
48
48
|
|
|
49
|
+
[tool.ruff.lint.per-file-ignores]
|
|
50
|
+
"scripts/*" = ["N806"]
|
|
51
|
+
|
|
49
52
|
[tool.pytest.ini_options]
|
|
50
53
|
testpaths = ["tests"]
|
|
51
54
|
addopts = "-q"
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Generate the hero chart shown in README.md.
|
|
2
|
+
|
|
3
|
+
Two panels that tell the package's story:
|
|
4
|
+
(1) Sample size vs MDE — the classic power-calc curve every DS needs.
|
|
5
|
+
(2) mSPRT Type-I error under H0 over peeks — the always-valid story,
|
|
6
|
+
with the buggy variant overlaid to show why the fix mattered.
|
|
7
|
+
|
|
8
|
+
Run: python scripts/make_hero.py
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import matplotlib.pyplot as plt
|
|
16
|
+
import numpy as np
|
|
17
|
+
from scipy import stats
|
|
18
|
+
|
|
19
|
+
RNG = np.random.default_rng(7)
|
|
20
|
+
OUT = Path(__file__).resolve().parents[1] / "docs" / "hero.png"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def sample_size_curve(ax: plt.Axes) -> None:
|
|
24
|
+
baseline = 0.10
|
|
25
|
+
mdes_rel = np.linspace(0.01, 0.10, 50)
|
|
26
|
+
sigma2 = baseline * (1 - baseline)
|
|
27
|
+
z_alpha = stats.norm.ppf(1 - 0.025)
|
|
28
|
+
z_beta = stats.norm.ppf(0.80)
|
|
29
|
+
n_per_arm = 2 * sigma2 * (z_alpha + z_beta) ** 2 / (baseline * mdes_rel) ** 2
|
|
30
|
+
|
|
31
|
+
ax.plot(mdes_rel * 100, n_per_arm / 1000, lw=2.2, color="#1f77b4")
|
|
32
|
+
ax.set_xlabel("Minimum detectable effect (% relative)")
|
|
33
|
+
ax.set_ylabel("Sample size per arm (thousands)")
|
|
34
|
+
ax.set_title("Power calculation\nα=0.05, power=0.80, p=10%")
|
|
35
|
+
ax.set_yscale("log")
|
|
36
|
+
ax.grid(True, alpha=0.3, which="both")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def msprt_type1(ax: plt.Axes) -> None:
|
|
40
|
+
n_max = 2000
|
|
41
|
+
tau2 = 1.0
|
|
42
|
+
alpha = 0.05
|
|
43
|
+
ns = np.arange(1, n_max + 1)
|
|
44
|
+
trials = 500
|
|
45
|
+
|
|
46
|
+
def simulate(use_bug: bool) -> np.ndarray:
|
|
47
|
+
cum_reject = np.zeros(n_max)
|
|
48
|
+
for _ in range(trials):
|
|
49
|
+
x = RNG.normal(size=n_max)
|
|
50
|
+
y = RNG.normal(size=n_max)
|
|
51
|
+
diff = np.cumsum(x) / ns - np.cumsum(y) / ns
|
|
52
|
+
V = (1.0 if use_bug else 2.0) / ns
|
|
53
|
+
logbf = 0.5 * np.log(V / (V + tau2)) + 0.5 * (diff**2) * (tau2 / (V + tau2)) / V
|
|
54
|
+
pval = np.minimum(1.0, 1.0 / np.exp(logbf))
|
|
55
|
+
running_min = np.minimum.accumulate(pval)
|
|
56
|
+
cum_reject += (running_min < alpha).astype(float)
|
|
57
|
+
return cum_reject / trials
|
|
58
|
+
|
|
59
|
+
buggy = simulate(True)
|
|
60
|
+
fixed = simulate(False)
|
|
61
|
+
|
|
62
|
+
ax.plot(ns, buggy * 100, lw=2, color="#d62728", label="Buggy variant (pre-fix)")
|
|
63
|
+
ax.plot(ns, fixed * 100, lw=2, color="#2ca02c", label="Shipped formula")
|
|
64
|
+
ax.axhline(5, color="black", ls="--", lw=1, alpha=0.6, label="α = 5%")
|
|
65
|
+
ax.set_xlabel("Sample size per arm (peeks)")
|
|
66
|
+
ax.set_ylabel("Cumulative Type-I error (%)")
|
|
67
|
+
ax.set_title("mSPRT always-valid control\nType-I under H0 across all peeks")
|
|
68
|
+
ax.legend(loc="center right", fontsize=9)
|
|
69
|
+
ax.grid(True, alpha=0.3)
|
|
70
|
+
ax.set_ylim(0, 25)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def main() -> None:
|
|
74
|
+
OUT.parent.mkdir(parents=True, exist_ok=True)
|
|
75
|
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4.2))
|
|
76
|
+
sample_size_curve(axes[0])
|
|
77
|
+
msprt_type1(axes[1])
|
|
78
|
+
fig.suptitle("experiment-toolkit — power calcs and always-valid sequential tests",
|
|
79
|
+
fontsize=12, y=1.02)
|
|
80
|
+
fig.tight_layout()
|
|
81
|
+
fig.savefig(OUT, dpi=140, bbox_inches="tight")
|
|
82
|
+
print(f"wrote {OUT}")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == "__main__":
|
|
86
|
+
main()
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""experiment-toolkit: small utilities for online controlled experiments."""
|
|
2
|
+
|
|
3
|
+
from experiment_toolkit.cs_did import (
|
|
4
|
+
CSResult,
|
|
5
|
+
cs_staggered_att,
|
|
6
|
+
simulate_staggered_panel,
|
|
7
|
+
)
|
|
8
|
+
from experiment_toolkit.cuped import apply_cuped, compute_theta
|
|
9
|
+
from experiment_toolkit.ratio import ratio_metric_variance
|
|
10
|
+
from experiment_toolkit.sample_size import (
|
|
11
|
+
cuped_sample_size_summary,
|
|
12
|
+
mde_for_n,
|
|
13
|
+
sample_size_for_mde,
|
|
14
|
+
)
|
|
15
|
+
from experiment_toolkit.sensitivity import (
|
|
16
|
+
EValueResult,
|
|
17
|
+
e_value,
|
|
18
|
+
rosenbaum_gamma_threshold,
|
|
19
|
+
rosenbaum_wilcoxon_bounds,
|
|
20
|
+
)
|
|
21
|
+
from experiment_toolkit.sequential import msprt_cuped_pvalue, msprt_pvalue
|
|
22
|
+
|
|
23
|
+
__version__ = "0.2.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"CSResult",
|
|
27
|
+
"EValueResult",
|
|
28
|
+
"apply_cuped",
|
|
29
|
+
"compute_theta",
|
|
30
|
+
"cs_staggered_att",
|
|
31
|
+
"cuped_sample_size_summary",
|
|
32
|
+
"e_value",
|
|
33
|
+
"mde_for_n",
|
|
34
|
+
"msprt_cuped_pvalue",
|
|
35
|
+
"msprt_pvalue",
|
|
36
|
+
"ratio_metric_variance",
|
|
37
|
+
"rosenbaum_gamma_threshold",
|
|
38
|
+
"rosenbaum_wilcoxon_bounds",
|
|
39
|
+
"sample_size_for_mde",
|
|
40
|
+
"simulate_staggered_panel",
|
|
41
|
+
]
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Callaway & Sant'Anna (2021) staggered difference-in-differences.
|
|
3
|
+
|
|
4
|
+
Robust to treatment-effect heterogeneity across adoption cohorts — unlike
|
|
5
|
+
two-way fixed-effects DiD, which is biased when effects differ across
|
|
6
|
+
cohorts or over time (Goodman-Bacon 2021; de Chaisemartin & D'Haultfoeuille
|
|
7
|
+
2020). Implementation uses a never-treated control group and the
|
|
8
|
+
outcome-regression (unconditional) identifier:
|
|
9
|
+
|
|
10
|
+
ATT(g, t) = mean[Y_t - Y_{g-1} | cohort = g]
|
|
11
|
+
- mean[Y_t - Y_{g-1} | never treated]
|
|
12
|
+
|
|
13
|
+
for each treated cohort ``g`` and post-treatment period ``t >= g``.
|
|
14
|
+
|
|
15
|
+
Standard errors come from a unit cluster bootstrap, so the implementation
|
|
16
|
+
is pure numpy (no statsmodels / pandas dependency for the package).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
from numpy.typing import ArrayLike
|
|
26
|
+
from scipy import stats
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class CSResult:
|
|
31
|
+
"""Structured Callaway-Sant'Anna estimation result.
|
|
32
|
+
|
|
33
|
+
Attributes
|
|
34
|
+
----------
|
|
35
|
+
group_time_att : list of dicts (one per (g, t) cell) with keys
|
|
36
|
+
``cohort``, ``period``, ``relative_time``, ``att``, ``se``,
|
|
37
|
+
``ci_low``, ``ci_high``, ``n_treated``, ``n_control``.
|
|
38
|
+
event_study : list of dicts (one per relative time ``e``) with keys
|
|
39
|
+
``relative_time``, ``att``, ``se``, ``ci_low``, ``ci_high``.
|
|
40
|
+
overall_att, overall_se, overall_ci_low, overall_ci_high : simple
|
|
41
|
+
equal-weighted aggregation across all (g, t) with ``t >= g``.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
group_time_att: list[dict[str, Any]] = field(default_factory=list)
|
|
45
|
+
event_study: list[dict[str, Any]] = field(default_factory=list)
|
|
46
|
+
overall_att: float = float("nan")
|
|
47
|
+
overall_se: float = float("nan")
|
|
48
|
+
overall_ci_low: float = float("nan")
|
|
49
|
+
overall_ci_high: float = float("nan")
|
|
50
|
+
n_units: int = 0
|
|
51
|
+
n_bootstrap: int = 0
|
|
52
|
+
|
|
53
|
+
def __repr__(self) -> str: # pragma: no cover - convenience
|
|
54
|
+
return (
|
|
55
|
+
f"CS(overall ATT={self.overall_att:+.3f}, "
|
|
56
|
+
f"95% CI [{self.overall_ci_low:+.3f}, {self.overall_ci_high:+.3f}], "
|
|
57
|
+
f"n_units={self.n_units}, boot={self.n_bootstrap})"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def simulate_staggered_panel(
|
|
62
|
+
cohort_sizes: dict[int, int] | None = None,
|
|
63
|
+
n_never_treated: int = 20,
|
|
64
|
+
n_periods: int = 20,
|
|
65
|
+
cohort_effects: dict[int, float] | None = None,
|
|
66
|
+
dynamic_slope: float = 0.0,
|
|
67
|
+
seed: int = 0,
|
|
68
|
+
) -> dict[str, np.ndarray]:
|
|
69
|
+
"""Simulate a staggered-adoption panel.
|
|
70
|
+
|
|
71
|
+
Returns a dict of numpy arrays (all length ``n_units * n_periods``):
|
|
72
|
+
``unit`` (int), ``period`` (int), ``y`` (float), ``cohort`` (int — the
|
|
73
|
+
treatment period, ``0`` for never-treated).
|
|
74
|
+
|
|
75
|
+
Default DGP has three cohorts treated at periods 6/10/14 with static
|
|
76
|
+
effects 1/3/5 — a textbook setting where TWFE is biased but CS is not.
|
|
77
|
+
"""
|
|
78
|
+
if cohort_sizes is None:
|
|
79
|
+
cohort_sizes = {6: 15, 10: 15, 14: 15}
|
|
80
|
+
if cohort_effects is None:
|
|
81
|
+
cohort_effects = {6: 1.0, 10: 3.0, 14: 5.0}
|
|
82
|
+
|
|
83
|
+
rng = np.random.default_rng(seed)
|
|
84
|
+
common_shocks = rng.normal(0, 1.0, size=n_periods).cumsum() * 0.3
|
|
85
|
+
common_trend = 0.4
|
|
86
|
+
|
|
87
|
+
units: list[int] = []
|
|
88
|
+
periods: list[int] = []
|
|
89
|
+
ys: list[float] = []
|
|
90
|
+
cohorts: list[int] = []
|
|
91
|
+
|
|
92
|
+
unit_id = 0
|
|
93
|
+
|
|
94
|
+
def add_unit(cohort: int, effect: float) -> None:
|
|
95
|
+
nonlocal unit_id
|
|
96
|
+
intercept = rng.normal(100, 8)
|
|
97
|
+
noise = rng.normal(0, 1.0, size=n_periods)
|
|
98
|
+
for p in range(n_periods):
|
|
99
|
+
rel_time = p - cohort if cohort > 0 else -9999
|
|
100
|
+
is_post = cohort > 0 and p >= cohort
|
|
101
|
+
te = effect + dynamic_slope * rel_time if is_post else 0.0
|
|
102
|
+
y = intercept + common_trend * p + common_shocks[p] + noise[p] + te
|
|
103
|
+
units.append(unit_id)
|
|
104
|
+
periods.append(p)
|
|
105
|
+
ys.append(float(y))
|
|
106
|
+
cohorts.append(cohort)
|
|
107
|
+
unit_id += 1
|
|
108
|
+
|
|
109
|
+
for g, n in cohort_sizes.items():
|
|
110
|
+
for _ in range(n):
|
|
111
|
+
add_unit(g, cohort_effects[g])
|
|
112
|
+
for _ in range(n_never_treated):
|
|
113
|
+
add_unit(0, 0.0)
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
"unit": np.asarray(units, dtype=int),
|
|
117
|
+
"period": np.asarray(periods, dtype=int),
|
|
118
|
+
"y": np.asarray(ys, dtype=float),
|
|
119
|
+
"cohort": np.asarray(cohorts, dtype=int),
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _to_wide(
|
|
124
|
+
unit: np.ndarray, period: np.ndarray, y: np.ndarray, cohort: np.ndarray
|
|
125
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
126
|
+
"""Reshape a balanced long panel into wide form. Returns (unit_ids,
|
|
127
|
+
period_grid, y_matrix [n_units x n_periods], cohort_per_unit)."""
|
|
128
|
+
unit_ids, unit_idx = np.unique(unit, return_inverse=True)
|
|
129
|
+
period_grid, period_idx = np.unique(period, return_inverse=True)
|
|
130
|
+
n_u, n_p = len(unit_ids), len(period_grid)
|
|
131
|
+
y_mat = np.full((n_u, n_p), np.nan, dtype=float)
|
|
132
|
+
y_mat[unit_idx, period_idx] = y
|
|
133
|
+
if np.isnan(y_mat).any():
|
|
134
|
+
raise ValueError("panel is unbalanced; every (unit, period) must be present")
|
|
135
|
+
cohort_per_unit = np.zeros(n_u, dtype=int)
|
|
136
|
+
# cohort is constant within unit — take the first occurrence
|
|
137
|
+
seen = np.zeros(n_u, dtype=bool)
|
|
138
|
+
for u_idx, c in zip(unit_idx, cohort, strict=False):
|
|
139
|
+
if not seen[u_idx]:
|
|
140
|
+
cohort_per_unit[u_idx] = c
|
|
141
|
+
seen[u_idx] = True
|
|
142
|
+
return unit_ids, period_grid, y_mat, cohort_per_unit
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _cs_point_estimates(
|
|
146
|
+
y_mat: np.ndarray,
|
|
147
|
+
cohort_per_unit: np.ndarray,
|
|
148
|
+
period_grid: np.ndarray,
|
|
149
|
+
cohorts: list[int],
|
|
150
|
+
) -> dict[tuple[int, int], float]:
|
|
151
|
+
"""ATT(g, t) point estimates via the 2x2 CS identifier."""
|
|
152
|
+
period_to_col = {int(p): i for i, p in enumerate(period_grid.tolist())}
|
|
153
|
+
never_mask = cohort_per_unit == 0
|
|
154
|
+
out: dict[tuple[int, int], float] = {}
|
|
155
|
+
for g in cohorts:
|
|
156
|
+
baseline = g - 1
|
|
157
|
+
if baseline not in period_to_col:
|
|
158
|
+
continue
|
|
159
|
+
treated_mask = cohort_per_unit == g
|
|
160
|
+
if not treated_mask.any() or not never_mask.any():
|
|
161
|
+
continue
|
|
162
|
+
b_col = period_to_col[baseline]
|
|
163
|
+
for p in period_grid:
|
|
164
|
+
p_int = int(p)
|
|
165
|
+
if p_int < g or p_int not in period_to_col:
|
|
166
|
+
continue
|
|
167
|
+
t_col = period_to_col[p_int]
|
|
168
|
+
diff_treated = float(
|
|
169
|
+
(y_mat[treated_mask, t_col] - y_mat[treated_mask, b_col]).mean()
|
|
170
|
+
)
|
|
171
|
+
diff_control = float(
|
|
172
|
+
(y_mat[never_mask, t_col] - y_mat[never_mask, b_col]).mean()
|
|
173
|
+
)
|
|
174
|
+
out[(g, p_int)] = diff_treated - diff_control
|
|
175
|
+
return out
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def cs_staggered_att(
|
|
179
|
+
unit: ArrayLike,
|
|
180
|
+
period: ArrayLike,
|
|
181
|
+
y: ArrayLike,
|
|
182
|
+
cohort: ArrayLike,
|
|
183
|
+
n_bootstrap: int = 500,
|
|
184
|
+
alpha: float = 0.05,
|
|
185
|
+
seed: int = 0,
|
|
186
|
+
) -> CSResult:
|
|
187
|
+
"""Callaway-Sant'Anna staggered DiD with never-treated controls.
|
|
188
|
+
|
|
189
|
+
Parameters
|
|
190
|
+
----------
|
|
191
|
+
unit, period, y, cohort : equal-length arrays forming a long panel.
|
|
192
|
+
``cohort`` must be the treatment period for treated units and
|
|
193
|
+
``0`` for never-treated units. Panel must be balanced.
|
|
194
|
+
n_bootstrap : number of unit-cluster bootstrap replicates.
|
|
195
|
+
alpha : two-sided confidence level (0.05 = 95% CI).
|
|
196
|
+
seed : RNG seed for the bootstrap.
|
|
197
|
+
"""
|
|
198
|
+
unit_arr = np.asarray(unit)
|
|
199
|
+
period_arr = np.asarray(period, dtype=int)
|
|
200
|
+
y_arr = np.asarray(y, dtype=float)
|
|
201
|
+
cohort_arr = np.asarray(cohort, dtype=int)
|
|
202
|
+
|
|
203
|
+
unit_ids, period_grid, y_mat, cohort_per_unit = _to_wide(
|
|
204
|
+
unit_arr, period_arr, y_arr, cohort_arr
|
|
205
|
+
)
|
|
206
|
+
n_units = len(unit_ids)
|
|
207
|
+
cohorts = sorted({int(c) for c in cohort_per_unit.tolist() if c > 0})
|
|
208
|
+
|
|
209
|
+
point_gt = _cs_point_estimates(y_mat, cohort_per_unit, period_grid, cohorts)
|
|
210
|
+
if not point_gt:
|
|
211
|
+
raise ValueError("No identifiable (g, t) cells — check cohort/period coding.")
|
|
212
|
+
|
|
213
|
+
rng = np.random.default_rng(seed)
|
|
214
|
+
boot_gt: dict[tuple[int, int], list[float]] = {k: [] for k in point_gt}
|
|
215
|
+
for _ in range(n_bootstrap):
|
|
216
|
+
idx = rng.integers(0, n_units, size=n_units)
|
|
217
|
+
y_boot = y_mat[idx]
|
|
218
|
+
c_boot = cohort_per_unit[idx]
|
|
219
|
+
b = _cs_point_estimates(y_boot, c_boot, period_grid, cohorts)
|
|
220
|
+
for k in boot_gt:
|
|
221
|
+
if k in b:
|
|
222
|
+
boot_gt[k].append(b[k])
|
|
223
|
+
|
|
224
|
+
z = float(stats.norm.ppf(1 - alpha / 2))
|
|
225
|
+
|
|
226
|
+
gt_rows: list[dict[str, Any]] = []
|
|
227
|
+
for (g, t), point in point_gt.items():
|
|
228
|
+
boots = np.asarray(boot_gt[(g, t)])
|
|
229
|
+
se = float(boots.std(ddof=1)) if len(boots) > 1 else float("nan")
|
|
230
|
+
gt_rows.append(
|
|
231
|
+
{
|
|
232
|
+
"cohort": g,
|
|
233
|
+
"period": t,
|
|
234
|
+
"relative_time": t - g,
|
|
235
|
+
"att": point,
|
|
236
|
+
"se": se,
|
|
237
|
+
"ci_low": point - z * se,
|
|
238
|
+
"ci_high": point + z * se,
|
|
239
|
+
"n_treated": int((cohort_per_unit == g).sum()),
|
|
240
|
+
"n_control": int((cohort_per_unit == 0).sum()),
|
|
241
|
+
}
|
|
242
|
+
)
|
|
243
|
+
gt_rows.sort(key=lambda r: (r["cohort"], r["period"]))
|
|
244
|
+
|
|
245
|
+
# Event-study aggregation
|
|
246
|
+
es_points: dict[int, list[float]] = {}
|
|
247
|
+
es_boots: dict[int, list[list[float]]] = {}
|
|
248
|
+
for (g, t), point in point_gt.items():
|
|
249
|
+
es_points.setdefault(t - g, []).append(point)
|
|
250
|
+
es_boots.setdefault(t - g, []).append(boot_gt[(g, t)])
|
|
251
|
+
|
|
252
|
+
es_rows: list[dict[str, Any]] = []
|
|
253
|
+
for e in sorted(es_points):
|
|
254
|
+
att_e = float(np.mean(es_points[e]))
|
|
255
|
+
valid = [np.asarray(b) for b in es_boots[e] if len(b) > 1]
|
|
256
|
+
if valid:
|
|
257
|
+
min_len = min(len(v) for v in valid)
|
|
258
|
+
stacked = np.vstack([v[:min_len] for v in valid])
|
|
259
|
+
replicate_means = stacked.mean(axis=0)
|
|
260
|
+
se_e = float(replicate_means.std(ddof=1))
|
|
261
|
+
else:
|
|
262
|
+
se_e = float("nan")
|
|
263
|
+
es_rows.append(
|
|
264
|
+
{
|
|
265
|
+
"relative_time": e,
|
|
266
|
+
"att": att_e,
|
|
267
|
+
"se": se_e,
|
|
268
|
+
"ci_low": att_e - z * se_e,
|
|
269
|
+
"ci_high": att_e + z * se_e,
|
|
270
|
+
}
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
overall_point = float(np.mean(list(point_gt.values())))
|
|
274
|
+
valid_keys = [k for k in point_gt if len(boot_gt[k]) > 1]
|
|
275
|
+
if valid_keys:
|
|
276
|
+
min_len = min(len(boot_gt[k]) for k in valid_keys)
|
|
277
|
+
boot_mat = np.vstack([np.asarray(boot_gt[k][:min_len]) for k in valid_keys])
|
|
278
|
+
overall_replicates = boot_mat.mean(axis=0)
|
|
279
|
+
overall_se = float(overall_replicates.std(ddof=1))
|
|
280
|
+
else:
|
|
281
|
+
overall_se = float("nan")
|
|
282
|
+
|
|
283
|
+
return CSResult(
|
|
284
|
+
group_time_att=gt_rows,
|
|
285
|
+
event_study=es_rows,
|
|
286
|
+
overall_att=overall_point,
|
|
287
|
+
overall_se=overall_se,
|
|
288
|
+
overall_ci_low=overall_point - z * overall_se,
|
|
289
|
+
overall_ci_high=overall_point + z * overall_se,
|
|
290
|
+
n_units=n_units,
|
|
291
|
+
n_bootstrap=n_bootstrap,
|
|
292
|
+
)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sample size and MDE calculators for two-sample experiments on continuous
|
|
3
|
+
outcomes. Uses the standard normal approximation (valid for n > ~30 per arm).
|
|
4
|
+
|
|
5
|
+
For a two-sided test at significance alpha and power 1-beta, comparing two
|
|
6
|
+
means with equal per-arm sample size n and pooled standard deviation sigma:
|
|
7
|
+
|
|
8
|
+
n = 2 * sigma^2 * (z_{1-alpha/2} + z_{1-beta})^2 / mde^2
|
|
9
|
+
|
|
10
|
+
where mde is the minimum detectable effect in outcome units.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
|
|
17
|
+
from scipy import stats
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def sample_size_for_mde(
|
|
21
|
+
mde: float,
|
|
22
|
+
std_dev: float,
|
|
23
|
+
alpha: float = 0.05,
|
|
24
|
+
power: float = 0.80,
|
|
25
|
+
two_sided: bool = True,
|
|
26
|
+
rho: float = 0.0,
|
|
27
|
+
) -> int:
|
|
28
|
+
"""Required per-arm sample size to detect `mde` with the given power.
|
|
29
|
+
|
|
30
|
+
When ``rho`` (the correlation between the outcome and a pre-experiment
|
|
31
|
+
covariate) is non-zero, the formula applies the CUPED variance reduction
|
|
32
|
+
factor ``(1 - rho^2)`` — see Deng, Xu, Kohavi, Walker (2013). At ``rho=0``
|
|
33
|
+
the result is the classical two-sample z-formula (backwards compatible).
|
|
34
|
+
"""
|
|
35
|
+
if mde <= 0:
|
|
36
|
+
raise ValueError("mde must be positive")
|
|
37
|
+
if std_dev <= 0:
|
|
38
|
+
raise ValueError("std_dev must be positive")
|
|
39
|
+
if not 0 < alpha < 1:
|
|
40
|
+
raise ValueError("alpha must be in (0, 1)")
|
|
41
|
+
if not 0 < power < 1:
|
|
42
|
+
raise ValueError("power must be in (0, 1)")
|
|
43
|
+
if not -1 <= rho <= 1:
|
|
44
|
+
raise ValueError("rho must be in [-1, 1]")
|
|
45
|
+
|
|
46
|
+
z_alpha = stats.norm.ppf(1 - alpha / 2) if two_sided else stats.norm.ppf(1 - alpha)
|
|
47
|
+
z_beta = stats.norm.ppf(power)
|
|
48
|
+
variance = std_dev**2 * (1 - rho**2)
|
|
49
|
+
|
|
50
|
+
n = 2 * variance * (z_alpha + z_beta) ** 2 / mde**2
|
|
51
|
+
return math.ceil(n)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def mde_for_n(
|
|
55
|
+
n_per_arm: int,
|
|
56
|
+
std_dev: float,
|
|
57
|
+
alpha: float = 0.05,
|
|
58
|
+
power: float = 0.80,
|
|
59
|
+
two_sided: bool = True,
|
|
60
|
+
rho: float = 0.0,
|
|
61
|
+
) -> float:
|
|
62
|
+
"""Inverse: given a fixed per-arm sample size, return the MDE you can
|
|
63
|
+
detect with the given power. ``rho`` enables CUPED variance reduction."""
|
|
64
|
+
if n_per_arm <= 0:
|
|
65
|
+
raise ValueError("n_per_arm must be positive")
|
|
66
|
+
if std_dev <= 0:
|
|
67
|
+
raise ValueError("std_dev must be positive")
|
|
68
|
+
if not -1 <= rho <= 1:
|
|
69
|
+
raise ValueError("rho must be in [-1, 1]")
|
|
70
|
+
|
|
71
|
+
z_alpha = stats.norm.ppf(1 - alpha / 2) if two_sided else stats.norm.ppf(1 - alpha)
|
|
72
|
+
z_beta = stats.norm.ppf(power)
|
|
73
|
+
variance = std_dev**2 * (1 - rho**2)
|
|
74
|
+
|
|
75
|
+
return (z_alpha + z_beta) * (2 * variance / n_per_arm) ** 0.5
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def cuped_sample_size_summary(
|
|
79
|
+
mde: float,
|
|
80
|
+
std_dev: float,
|
|
81
|
+
rho: float,
|
|
82
|
+
alpha: float = 0.05,
|
|
83
|
+
power: float = 0.80,
|
|
84
|
+
) -> dict[str, float | int]:
|
|
85
|
+
"""Side-by-side comparison of required sample size with and without CUPED.
|
|
86
|
+
|
|
87
|
+
Returns a dict with per-arm sample sizes under the naive two-sample z test
|
|
88
|
+
(``rho=0``) and CUPED at the supplied ``rho``, plus absolute and percent
|
|
89
|
+
sample-size savings and the underlying variance-reduction factor.
|
|
90
|
+
"""
|
|
91
|
+
n_naive = sample_size_for_mde(mde, std_dev, alpha=alpha, power=power, rho=0.0)
|
|
92
|
+
n_cuped = sample_size_for_mde(mde, std_dev, alpha=alpha, power=power, rho=rho)
|
|
93
|
+
return {
|
|
94
|
+
"n_naive_per_arm": n_naive,
|
|
95
|
+
"n_cuped_per_arm": n_cuped,
|
|
96
|
+
"absolute_saving": n_naive - n_cuped,
|
|
97
|
+
"percent_reduction": float(1 - n_cuped / n_naive) if n_naive > 0 else 0.0,
|
|
98
|
+
"variance_reduction_factor": 1 - rho**2,
|
|
99
|
+
"rho": rho,
|
|
100
|
+
"mde": mde,
|
|
101
|
+
"std_dev": std_dev,
|
|
102
|
+
}
|