diff --git a/DEFERRED.md b/DEFERRED.md index 7f43b14dc..111f8da3a 100644 --- a/DEFERRED.md +++ b/DEFERRED.md @@ -19,6 +19,7 @@ provenance and AI-review deviation-documentation: a row here (or in | Issue | Location | PR | Priority | |-------|----------|----|----------| +| `diagnose_design` under a survey design: `survey_design` is refused because placebo assignment and unit resampling are done at the unit level, which is not valid when sampling or dependence sits above the unit (PSUs, strata). Needs a derivation of the placebo and resampling scheme at the PSU level; none of the four source papers covers survey designs. | `design.py::_REFUSED_FIT_KEYS` | design diagnosis PR-B | Low | | Chang (2020) Case 3 (multilevel treatment intensity) DML estimator: the paper prints no Case 3 regularity assumptions or variance theorem (Theorems 2/4 cover Cases 1-2 only; "same arguments" p. 13), the printed multilevel algorithm carries typos (review Gaps items 5-6), and no oracle exists (`DoubleMLDIDMulti` is staggered TIMING, not intensity) — needs the variance derivation + overlap assumptions before implementation. Published-version cross-check (2026-08-30) CONFIRMS the blocker in the version of record: printed Appendix A carries the same score/algorithm (same typos) with no Case 3 regularity/rate assumptions and no variance theorem | `docs/methodology/papers/chang-2020-review.md` | dml-b0 | Low | | LWDiD PSM matching variance: implement the Abadie-Imbens (2006) matching variance (matched-control reuse + first-stage matching uncertainty) so `estimation_method='psm'` can report valid inference instead of the current fail-closed NaN tuple (point retained; naive var(diffs)/n was invalid under with-replacement reuse) | `diff_diff/lwdid.py` | #588 | Low | | LWDiD cohort-relative sensitivity exclusions: `robustness_pre_periods` / `sensitivity_no_anticipation` currently reject multi-cohort staggered inputs because their exclusion windows are defined relative to the EARLIEST adoption (later cohorts' own pre periods fall inside the global post window and survive every restriction, mislabeling the specification). Supporting staggered inputs needs per-cohort window semantics (exclude the last k periods of each cohort's own `t < g` window before its transformation), which the current row-subset design cannot express — a per-cohort masking derivation + its aggregation contract | `diff_diff/lwdid_sensitivity.py` | #588 | Low | @@ -81,6 +82,7 @@ For survey-specific limitations (`NotImplementedError` paths), see the | Issue | Location | PR | Priority | |-------|----------|----|----------| +| `diagnose_design` on unbalanced panels and with a non-numeric calendar column: both are refused. Unit resampling and the placebo post window assume every unit is observed in every period, and the staggered estimators need numeric periods. Parked pending a user request; the source papers use balanced state-by-year panels. | `design.py::_prepare_panel` | design diagnosis PR-B | Low | | Hard "changelog fragment required" CI gate (diff-aware job + exemption convention), and extending the fragment pattern to the other shared-file collision surfaces (TODO.md / DEFERRED.md / docs/v4-deprecations.yaml rows — rare, trivially resolvable one-line conflicts today). The shipped system enforces only the pointer-only `## [Unreleased]` invariant plus prose/reviewer nudges. | `changelog.d/` | #806 | Low | | RDDensityTest public bandwidth-selector helper (an `rdbwdensity`-equivalent exposed function) and a Tutorial-28 executed density-test demo cell (Act 4d; needs notebook re-execution + drift-suite updates): the selector ships internal-only and the tutorial carries a prose pointer for now. | `diff_diff/rddensity.py`, `docs/tutorials/28_rdd_scholarship_illusion.ipynb` | rddensity PR-B | Low | | LW 2025 Sec 4.3 all-eventually-treated mode for LWDiD (drop `D_infinity`, effects relative to the last cohort as reference, last cohort's own effect not estimable). Current behavior (by decision, see the REGISTRY LWDiD Sec 4.3 note): such designs raise ValueError under both control strategies rather than silently truncating | `diff_diff/lwdid_staggered.py` | #588 | Low | diff --git a/METHODOLOGY_REVIEW.md b/METHODOLOGY_REVIEW.md index a57aa57f2..b5c12c678 100644 --- a/METHODOLOGY_REVIEW.md +++ b/METHODOLOGY_REVIEW.md @@ -83,6 +83,7 @@ The catalog grew incrementally over several quarters, so formats vary across the | PreTrendsPower | `pretrends.py` | `pretrends` package | **Complete** | 2026-05-19 | | PowerAnalysis | `power.py` | `pwr` / `DeclareDesign` | **Complete** | 2026-05-31 | | PlaceboTests | `diagnostics.py` | Bertrand-Duflo-Mullainathan (2004); base-R exact-enumeration parity | **Complete** | 2026-06-26 | +| DesignDiagnosis | `design.py` | No R parity target (`DeclareDesign` diagnoses simulated designs); internal exact enumeration | **Complete** | 2026-11-22 | ### Cross-Cutting Inference Features @@ -1309,6 +1310,36 @@ CI and extending covariate-adjusted R parity are tracked follow-ups in `DEFERRED --- +#### DesignDiagnosis + +| Field | Value | +|-------|-------| +| Module | `design.py` | +| Primary References | Bertrand, Duflo & Mullainathan (2004) - placebo assignment on real data, unit resampling, rejection rates, additive effect injection; Mizushima & Powell (2025) - staggered placebos; Coglianese & Fang (2026) - shared placebo events across estimators; Blair, Cooper, Coppock & Humphreys (2019) - diagnosands. Paper reviews under `docs/methodology/papers/`. | +| R Reference | None. `DeclareDesign` implements Blair et al.'s diagnosis on simulated data, not placebo assignment on a user's panel; the source papers distribute no placebo generator. | +| Status | **Complete** | +| Last Review | 2026-11-22 | + +**Verified components:** +- Placebo assignment follows the declared design: exact treated count, adoption periods drawn from `cohort_periods`, absorbing treatment, never-treated controls, effect injected only from each unit's own adoption on - `tests/test_design.py::TestPlaceboGenerator`. +- All eight supported estimators recover an injected effect under common timing, and the six staggered ones under staggered timing - `TestRecovery`. +- Every estimator and every effect size sees the same placebo draws, including under `seed=None` - `TestPlaceboDraws`. +- With the panel held fixed, the rejection rate agrees with exact enumeration of all C(6,3) assignments - `TestPlaceboDraws::test_fixed_panel_matches_exact_enumeration`. +- The outcome-blind truncation never reads rows from the first real adoption on - `TestOutcomeBlindGuard`. +- Paper-shaped findings on simulated panels - `tests/test_methodology_design.py`: with AR(1) outcomes (rho = 0.8, 50 units x 21 periods) classical TWFE standard errors reject a true null far above the nominal level while unit-clustered ones are near it (Bertrand et al.); with 2 of 40 units treated, asymptotic inference over-rejects, and with 20 it is near nominal (Mizushima-Powell). + +**Deviations and library choices (documented in REGISTRY `## DesignDiagnosis`):** +- The size check, the minimum detectable effect on real data, the two-pre-period minimum and the data fingerprint have no paper source. +- A fit with non-finite inference is excluded from every rate; `simulate_power` alone counts it as a non-rejection. +- RMSE is the existing `ddof = 1` form, not Blair et al.'s root mean squared error. +- Adoption periods are declared; Bertrand et al.'s randomly drawn passage year is not implemented. + +**Not validated:** no R parity; the source papers' CPS tables are not reproduced. + +**Tests:** `tests/test_design.py` (behaviour, guards, failure policy, results contract) + `tests/test_methodology_design.py` (paper-shaped findings and documented choices). + +--- + #### PlaceboTests | Field | Value | diff --git a/README.md b/README.md index 2fe9d1258..a4911b3c1 100644 --- a/README.md +++ b/README.md @@ -134,6 +134,7 @@ Full guide: `diff_diff.get_llm_guide("practitioner")`. - [Honest DiD](https://diff-diff.readthedocs.io/en/stable/api/honest_did.html) - Rambachan & Roth (2023) sensitivity analysis: robust CI under PT violations, breakdown values - [Pre-Trends Power Analysis](https://diff-diff.readthedocs.io/en/stable/api/pretrends.html) - Roth (2022) minimum detectable violation and power curves - [Power Analysis](https://diff-diff.readthedocs.io/en/stable/api/power.html) - analytical and simulation-based MDE, sample size, power curves for study design +- [Design Diagnosis](https://diff-diff.readthedocs.io/en/stable/api/design.html) - `diagnose_design`: placebo assignments on your own untreated panel, reporting each candidate estimator's size, power, bias, coverage and MDE before any real analysis - [MMM Calibration Export](https://diff-diff.readthedocs.io/en/stable/api/mmm.html) - convert experiment results into MMM calibration inputs: PyMC-Marketing lift-test frames and Google Meridian lognormal ROI priors - Conley spatial HAC SE (`vcov_type="conley"`) on cross-sectional `LinearRegression` / `compute_robust_vcov` plus panel `DifferenceInDifferences` / `TwoWayFixedEffects` (with `conley_lag_cutoff` for within-unit Bartlett temporal HAC) - Conley (1999) spatial-correlation-aware SEs with parity vs R `conleyreg` on cross-sectional + panel fixtures, optional combined spatial + cluster product kernel via explicit `cluster=`, auto-activating sparse k-d-tree fast path for `n > 5_000` diff --git a/TODO.md b/TODO.md index 2852ec1cf..9b025b713 100644 --- a/TODO.md +++ b/TODO.md @@ -21,6 +21,9 @@ Related tracking surfaces: | Issue | Location | Origin | Effort | Priority | |-------|----------|--------|--------|----------| +| `diagnose_design` staggered placebo for `DifferenceInDifferences` / `TwoWayFixedEffects`: both are refused under a staggered declaration (two or more `cohort_periods`) because they are fitted with one `post` dummy. Supporting them needs a staggered TWFE placebo fit (a time-varying treatment column) and a stated estimand, since static TWFE under staggered timing does not target the injected effect cleanly. | `design.py::_validate_estimators` | design diagnosis PR-B | Mid | Low | +| `diagnose_design` with `anticipation > 0`: refused today because the candidate's aggregate averages periods before adoption where no effect is injected. Inject the effect from `g - anticipation` so that bias and coverage are scored against the right target. | `design.py::_validate_estimators`, `design.py::_make_placebo_generator` | design diagnosis PR-B | Mid | Low | +| `diagnose_design` randomly drawn common adoption period (the Bertrand, Duflo & Mullainathan 2004 main design: one passage year drawn per replicate from an interior window). `cohort_periods` is required and declared; a `None` default would have altered its meaning relative to `generate_staggered_data`, so the random-date variant needs its own argument. | `design.py::diagnose_design` | design diagnosis PR-B | Quick | Low | | One-way (unclustered) Bell-McCaffrey DOF for `SunAbraham` / `WooldridgeDiD` `vcov_type="hc2_bm"` + `cluster=False`: both reject the combination at 4.0 (item 7b) because their BM contrast helper `_compute_cr2_bm_contrast_dof` is cluster-only; port the one-way lane through `linalg._compute_bm_dof_from_contrasts` (the TWFE event-study core's helper) with a clubSandwich `vcovCR(cluster=1:n, type="CR2")` parity pin, then lift the two rejects and their tests | `diff_diff/sun_abraham.py`, `diff_diff/wooldridge.py` | #v4-7b | Mid | Low | | `decompose_twfe_weights(method="aipw")`: port upstream `implicit_aipw_weights` (covariate-adjusted only; `twfe_weights.py` rejects the value today and lists `"fwl"`). The R goldens already carry the `decompose.aipw` / `balance.aipw` / `two_period.*` blocks under `meta.reserved_blocks`, so no R re-run is needed | `diff_diff/twfe_weights.py` | #812 | Mid | Medium | | Consolidate the remaining estimator-entangled DR/logit score variants (`staggered.py::_doubly_robust` + RC twins, `triple_diff.py`, `lwdid.py`, `wooldridge.py`) onto the shared `_dr_scores.py` module, each migration with its own committed oracle capture (the ContinuousDiD lift's two-tier pattern in `tests/test_dr_scores.py`); and add a ridge vcov path to `solve_ridge` if an estimator ever needs analytical ridge inference | `diff_diff/_dr_scores.py` | dml-b0 | Mid | Low | @@ -84,6 +87,7 @@ generic sparse-FE, QR+SVD rank-detection redundancy, `check_finite` bypass — m | Issue | Location | Origin | Effort | Priority | |-------|----------|--------|--------|----------| +| Design-stage tutorial ("Study Design" group of `docs/tutorials/index.rst`): the full workflow - `diagnose_design`, then the design lock and reconciliation - deferred from the diagnosis PR because the lock does not exist yet; `llms-full.txt` carries a worked example in the meantime. Ships with the report-wiring PR, before the release that carries `diagnose_design`. | `docs/tutorials/`, `design.py` | design diagnosis PR-B | Mid | Medium | | Relay `to_dataframe(level='group')` to `aggregate('group').to_dataframe()` on CallawaySantAnna/DMLDiD, EfficientDiD and TripleDifference (staggered) - the level still raises with the post-fit pointer while `level='event_study'` was rewired to the aggregate route at the 4.0 cut (item 8b, [M-093]); ImputationDiD/TwoStageDiD keep their native `group` frames and need the same decision | `diff_diff/staggered_results.py`, `diff_diff/efficient_did_results.py`, `diff_diff/triple_diff_results.py` | #883 | Quick | Low | | TWFE event-study one-way HC2-BM absorbed-FE R parity against the `mpd_absorbed_fe_did` golden (`clubSandwich::vcovCR(cluster=1:n, type="CR2")`): since 4.0 (item 7b) `cluster=False` + hc2_bm reaches the one-way lane directly (no singleton-cluster column needed; `tests/test_v4_cluster_policy.py` pins finiteness and the static-surface LinearRegression parity only), so the open item is the R pin itself; the hc2 lane is pinned by `TestTWFEEventStudyAbsorbedFERParity` and the clustered hc2_bm per-period lane by `test_twfe_event_study_cluster_hc2_bm_per_period_df_matches_clubsandwich`; the MultiPeriodDiD lanes died at the 4.0 cut (PR 4c-ii) | `tests/test_estimators_vcov_type.py` | #v4-4c-i | Mid | Medium | | TWFE event-study power profile: `simulate_power`/`simulate_mde`/`simulate_sample_size` have no `_EstimatorProfile` for `TwoWayFixedEffects.fit(event_study=True)` since the MultiPeriodDiD registry entry went with the class (PR 4c-ii); `EventStudyResults` carries no scalar headline, so the profile needs a design (post-period average via the `tests/helpers/event_study_average.py` arithmetic, or a named period) plus its `_SURVEY_FIT_BUILDERS` twin | `diff_diff/power.py` | #v4-4c-ii | Mid | Low | diff --git a/changelog.d/20261122-design-diagnosis.md b/changelog.d/20261122-design-diagnosis.md new file mode 100644 index 000000000..3a0e5fbdb --- /dev/null +++ b/changelog.d/20261122-design-diagnosis.md @@ -0,0 +1,24 @@ +### Added +- **`diagnose_design`: design diagnosis on your own untreated panel.** Before + analysing a study, check how each candidate estimator behaves on the panel + you will actually use. `diagnose_design(data, outcome=, unit=, time=, + estimators=, cohort_periods=, n_treated= | treatment_fraction=, ...)` + repeatedly assigns placebo treatments that follow the declared design, + optionally adds a known effect to the placebo-treated observations, fits + every estimator on the same placebo draws, and returns a + `DesignDiagnosisResults` with, per estimator, the rejection rate under no + effect (size) and the power, bias, RMSE and coverage at each injected effect, + plus an optional minimum detectable effect (`power=`). + - Outcome-blind: no real treatment effect is estimated. Pass `first_treat=` + to drop every period from the earliest real adoption onward. + - Estimators are returned in input order and never ranked. `size_controlled` + flags those whose no-effect rejection rate is consistent with `alpha`; no + minimum detectable effect is reported for the others. + - Supports `DifferenceInDifferences`, `TwoWayFixedEffects`, + `CallawaySantAnna`, `SunAbraham`, `ImputationDiD`, `TwoStageDiD`, + `StackedDiD` and `EfficientDiD`, under common or staggered timing. + - Sources: Bertrand, Duflo & Mullainathan (2004), Mizushima & Powell (2025), + Coglianese & Fang (2026) and Blair et al. (2019). The size check, the + minimum detectable effect on real data and the other choices with no paper + source are documented as Notes in `docs/methodology/REGISTRY.md` + `## DesignDiagnosis`. diff --git a/diff_diff/__init__.py b/diff_diff/__init__.py index 566219cd3..18d80146f 100644 --- a/diff_diff/__init__.py +++ b/diff_diff/__init__.py @@ -75,6 +75,7 @@ load_prop99, load_walmart, ) +from diff_diff.design import DesignDiagnosisResults, diagnose_design from diff_diff.diagnostic_report import ( DIAGNOSTIC_REPORT_SCHEMA_VERSION, DiagnosticReport, @@ -492,6 +493,9 @@ "simulate_mde", "simulate_power", "simulate_sample_size", + # Design diagnosis + "DesignDiagnosisResults", + "diagnose_design", # Pre-trends power analysis "PreTrendsPower", "PreTrendsPowerResults", diff --git a/diff_diff/design.py b/diff_diff/design.py new file mode 100644 index 000000000..2c82e162f --- /dev/null +++ b/diff_diff/design.py @@ -0,0 +1,1347 @@ +""" +Design diagnosis on the user's own data. + +Before analysing a difference-in-differences study, :func:`diagnose_design` +takes an *untreated* panel, repeatedly assigns placebo treatments that follow a +declared design (how many units, which adoption periods), optionally adds a +known effect to the placebo-treated observations, fits each candidate +estimator, and reports per estimator how often it rejects when nothing +happened (size), how often it rejects an injected effect (power), and the +bias, RMSE and coverage of its estimates. + +The run is outcome-blind: no real treatment effect is ever estimated. When a +real treatment column is supplied, every period from the earliest real +adoption onward is dropped before anything else happens. + +References +---------- +Bertrand, M., Duflo, E., & Mullainathan, S. (2004). "How Much Should We Trust + Differences-in-Differences Estimates?" Quarterly Journal of Economics, + 119(1), 249-275. + +Blair, G., Cooper, J., Coppock, A., & Humphreys, M. (2019). "Declaring and + Diagnosing Research Designs." American Political Science Review, 113(3), + 838-859. + +Coglianese, J., & Fang, J. A. (2026). "An Evaluation of Difference-in-Differences + Methods Using Placebo Event Studies." Finance and Economics Discussion Series + 2026-045, Board of Governors of the Federal Reserve System. + +Mizushima, Y., & Powell, D. (2025). "Inference with Modern + Difference-in-Differences Methods." SSRN working paper 5221387. +""" + +import dataclasses +import hashlib +import inspect +import json +import warnings +from dataclasses import dataclass +from datetime import date, datetime +from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np +import pandas as pd + +from diff_diff.power import ( + SimulationMDEResults, + SimulationPowerResults, + simulate_mde, + simulate_power, +) +from diff_diff.results_base import Diagnostic + +__all__ = ["diagnose_design", "DesignDiagnosisResults"] + +# Estimators that need one common post indicator (common timing only). +_COMMON_TIMING_ESTIMATORS = ("DifferenceInDifferences", "TwoWayFixedEffects") +# Estimators driven by a first-treatment-period column (common or staggered). +_STAGGERED_ESTIMATORS = ( + "CallawaySantAnna", + "SunAbraham", + "ImputationDiD", + "TwoStageDiD", + "StackedDiD", + "EfficientDiD", +) +_SUPPORTED_ESTIMATORS = _COMMON_TIMING_ESTIMATORS + _STAGGERED_ESTIMATORS + +_FIRST_TREAT_COLUMN = "_placebo_first_treat" +_TREATED_COLUMN = "_placebo_treated" +_POST_COLUMN = "_placebo_post" +_PLACEBO_COLUMNS = (_FIRST_TREAT_COLUMN, _TREATED_COLUMN, _POST_COLUMN) + +# fit() keywords a caller may not pass: each would bypass or contradict the +# placebo columns this module supplies. +_REFUSED_FIT_KEYS = ( + "data", + "outcome", + "unit", + "time", + "first_treat", + "treatment", + "post", + "formula", + "post_periods", + "survey_design", +) + +# The exception classes simulate_power treats as data-dependent replicate +# failures (diff_diff/power.py). Anything else is a programming error and +# propagates. +_DATA_DEPENDENT_ERRORS = ( + ValueError, + np.linalg.LinAlgError, + KeyError, + RuntimeError, + ZeroDivisionError, +) + +_PREFLIGHT_ATTEMPTS = 5 +_MAX_LOST_SHARE = 0.10 +_MIN_PRE_PERIODS = 2 +_MAX_ERROR_MESSAGES = 5 + + +# --------------------------------------------------------------------------- +# Results container +# --------------------------------------------------------------------------- + + +@dataclass +class DesignDiagnosisResults(Diagnostic): + """ + Results of :func:`diagnose_design`. + + Attributes + ---------- + results : dict + Label -> list of :class:`~diff_diff.SimulationPowerResults`, one per + entry of ``effect_sizes``. The first entry is the no-effect run, so + its ``rejection_rate`` is the estimator's size on this design. + mde_results : dict + Label -> :class:`~diff_diff.SimulationMDEResults` for every estimator + whose minimum-detectable-effect search ran. + estimators : dict + Label -> an unfitted copy of the estimator as configured. + size_controlled : dict + Label -> whether the estimator passed the size gate at effect 0. + n_nan_inference : dict + Label -> list aligned with ``effect_sizes``: replicates excluded + because the fit returned non-finite inference. + mde : dict + Label -> minimum detectable effect, NaN when not reported. + effect_sizes : list of float + The effects actually run: 0 first, then the requested non-zero values. + alpha : float + Significance level of the tests. + target_power : float or None + Target power of the minimum-detectable-effect search. + outcome, unit, time : str + Column names used. + first_treat : str or None + Real first-treatment column used to truncate the panel. ``None`` means + the caller declared the panel untreated; that was not verified. + treatment_fraction : float or None + Declared share of treated units, when given. + n_treated : int + Number of placebo-treated units per replicate. + cohort_periods : list + Declared adoption periods (values of the ``time`` column). + resample_units : bool + Whether units were resampled with replacement in each replicate. + estimator_kwargs : dict + Extra ``fit()`` keywords applied to every estimator. + seed : int + Seed of the placebo draws (resolved to a concrete value). + n_units, n_periods, n_obs : int + Shape of the panel actually used. + n_dropped : int + Rows removed by truncating at the earliest real adoption. + data_sha256 : str + Fingerprint of the panel actually used. + data_columns : list of str + Columns the fingerprint covers. + """ + + results: Dict[str, List[SimulationPowerResults]] + mde_results: Dict[str, SimulationMDEResults] + estimators: Dict[str, Any] + size_controlled: Dict[str, bool] + n_nan_inference: Dict[str, List[int]] + mde: Dict[str, float] + effect_sizes: List[float] + alpha: float + target_power: Optional[float] + outcome: str + unit: str + time: str + first_treat: Optional[str] + treatment_fraction: Optional[float] + n_treated: int + cohort_periods: List[Any] + resample_units: bool + estimator_kwargs: Dict[str, Any] + seed: int + n_units: int + n_periods: int + n_obs: int + n_dropped: int + data_sha256: str + data_columns: List[str] + + def __repr__(self) -> str: + """Concise string representation.""" + n_ok = sum(1 for ok in self.size_controlled.values() if ok) + return ( + f"DesignDiagnosisResults(estimators={len(self.estimators)}, " + f"size_controlled={n_ok}, effect_sizes={self.effect_sizes})" + ) + + def to_dataframe(self) -> pd.DataFrame: + """ + One row per estimator and effect size, in input order. + + Returns + ------- + pd.DataFrame + Column ``label`` first, then the columns of + ``SimulationPowerResults.to_dict()``, then ``size_controlled``, + ``n_nan_inference`` and ``mde``. + """ + rows: List[Dict[str, Any]] = [] + for label, cells in self.results.items(): + for i, cell in enumerate(cells): + row: Dict[str, Any] = {"label": label} + row.update(cell.to_dict()) + row["size_controlled"] = self.size_controlled[label] + row["n_nan_inference"] = self.n_nan_inference[label][i] + row["mde"] = self.mde[label] + rows.append(row) + return pd.DataFrame(rows) + + def to_dict(self) -> Dict[str, Any]: + """ + Convert results to a dictionary. + + Returns + ------- + Dict[str, Any] + The declared design, the estimators (class name and parameters), + and the per-estimator, per-effect rows. + """ + return { + "estimators": { + label: { + "estimator_name": type(est).__name__, + "params": dict(est.get_params()), + } + for label, est in self.estimators.items() + }, + "effect_sizes": list(self.effect_sizes), + "alpha": self.alpha, + "target_power": self.target_power, + "outcome": self.outcome, + "unit": self.unit, + "time": self.time, + "first_treat": self.first_treat, + "treatment_fraction": self.treatment_fraction, + "n_treated": self.n_treated, + "cohort_periods": list(self.cohort_periods), + "resample_units": self.resample_units, + "estimator_kwargs": dict(self.estimator_kwargs), + "seed": self.seed, + "n_units": self.n_units, + "n_periods": self.n_periods, + "n_obs": self.n_obs, + "n_dropped": self.n_dropped, + "data_sha256": self.data_sha256, + "data_columns": list(self.data_columns), + "size_controlled": dict(self.size_controlled), + "mde": dict(self.mde), + "results": self.to_dataframe().to_dict("records"), + } + + def summary(self) -> str: + """ + Generate a formatted summary of the design diagnosis. + + Returns + ------- + str + Formatted summary. Estimators appear in input order; nothing is + ranked. + """ + width = 78 + timing = "common" if len(self.cohort_periods) == 1 else "staggered" + untreated = ( + f"truncated at earliest real adoption ({self.n_dropped} rows dropped)" + if self.first_treat is not None + else "declared by caller (no first_treat column given; not verified)" + ) + lines = [ + "=" * width, + "Design Diagnosis (placebo assignments on the supplied panel)".center(width), + "=" * width, + "", + f"{'Units x periods:':<32} {self.n_units} x {self.n_periods}", + f"{'Untreated status:':<32} {untreated}", + f"{'Placebo-treated units:':<32} {self.n_treated}", + f"{'Adoption periods (' + timing + '):':<32} {list(self.cohort_periods)}", + f"{'Units resampled:':<32} {self.resample_units}", + f"{'Significance level (alpha):':<32} {self.alpha:.3f}", + f"{'Seed:':<32} {self.seed}", + "", + "-" * width, + "No-effect runs (size)".center(width), + "-" * width, + f"{'Estimator':<26}{'Size':>8}{'Scored':>8}{'Lost':>7}{'Coverage':>10}" + f"{'Size OK':>9}{'MDE':>10}", + ] + for label, cells in self.results.items(): + null = cells[0] + mde = self.mde[label] + mde_text = f"{mde:.4g}" if np.isfinite(mde) else "-" + lines.append( + f"{label[:25]:<26}{_fmt_rate(null.rejection_rate):>8}" + f"{null.n_simulations:>8}{null.n_simulation_failures:>7}" + f"{_fmt_rate(null.coverage):>10}" + f"{('yes' if self.size_controlled[label] else 'NO'):>9}{mde_text:>10}" + ) + if len(self.effect_sizes) > 1: + lines.extend(["", "-" * width, "Injected effects".center(width), "-" * width]) + lines.append( + f"{'Estimator':<26}{'Effect':>10}{'Power':>8}{'Bias':>11}{'RMSE':>11}" + f"{'Coverage':>10}" + ) + for label, cells in self.results.items(): + for cell in cells[1:]: + lines.append( + f"{label[:25]:<26}{cell.true_effect:>10.4g}" + f"{_fmt_rate(cell.power):>8}{_fmt_num(cell.bias):>11}" + f"{_fmt_num(cell.rmse):>11}{_fmt_rate(cell.coverage):>10}" + ) + lines.extend( + [ + "", + "Estimators are listed in input order and are not ranked. 'Size OK' is", + "a check on the no-effect runs only; power for an estimator that fails", + "it is not meaningful.", + "=" * width, + ] + ) + return "\n".join(lines) + + def print_summary(self) -> None: + """Print the summary to stdout.""" + print(self.summary()) + + +def _fmt_rate(value: float) -> str: + return f"{value:.1%}" if np.isfinite(value) else "-" + + +def _fmt_num(value: float) -> str: + return f"{value:.4g}" if np.isfinite(value) else "-" + + +# --------------------------------------------------------------------------- +# Warning capture +# --------------------------------------------------------------------------- + + +class _WarningCapture: + """Record every warning raised in a block, regardless of caller filters.""" + + def __init__(self) -> None: + self.records: List[warnings.WarningMessage] = [] + self._ctx: Optional[warnings.catch_warnings] = None + + def __enter__(self) -> "_WarningCapture": + self._ctx = warnings.catch_warnings(record=True) + captured = self._ctx.__enter__() + warnings.simplefilter("always") + assert captured is not None + self.records = captured + return self + + def __exit__(self, *exc_info: Any) -> None: + assert self._ctx is not None + self._ctx.__exit__(*exc_info) + + +def _reemit(label: str, records: Sequence[warnings.WarningMessage]) -> None: + """Re-emit captured warnings once per (category, source), labelled. + + Estimator warnings embed per-replicate values, so they are aggregated by + where they were raised, not by message text. Re-emission goes through the + caller's own warning filters. + """ + grouped: Dict[Tuple[Any, str, int], Tuple[str, int]] = {} + for record in records: + key = (record.category, record.filename, record.lineno) + first, count = grouped.get(key, (str(record.message), 0)) + grouped[key] = (first, count + 1) + for (category, _filename, _lineno), (message, count) in grouped.items(): + suffix = f" (raised {count} times; first message shown)" if count > 1 else "" + warnings.warn(f"[{label}] {message}{suffix}", category, stacklevel=3) + + +# --------------------------------------------------------------------------- +# Fit adapter +# --------------------------------------------------------------------------- + + +def _has_scalar_inference(result: Any) -> bool: + """Whether a fit result exposes scalar att / se / p_value and a 2-interval.""" + for name in ("att", "se", "p_value", "conf_int"): + if not hasattr(result, name): + return False + for name in ("att", "se", "p_value"): + if np.ndim(getattr(result, name)) != 0: + return False + conf_int = result.conf_int + try: + return len(conf_int) == 2 and all(np.ndim(bound) == 0 for bound in conf_int) + except TypeError: + return False + + +def _has_finite_inference(result: Any) -> bool: + """Whether att, se, p_value and both interval bounds are finite.""" + values = [result.att, result.se, result.p_value, result.conf_int[0], result.conf_int[1]] + try: + return bool(np.all(np.isfinite(np.asarray(values, dtype=float)))) + except (TypeError, ValueError): + return False + + +class _PlaceboFit: + """Wrap one estimator copy for one cell and count the replicates it loses. + + ``simulate_power`` counts a NaN p-value as a non-rejection; raising here + instead excludes such a replicate from every rate. Only the exception + classes ``simulate_power`` already treats as data-dependent are counted; + anything else propagates. + """ + + def __init__(self, estimator: Any) -> None: + self._estimator = estimator + self.n_fits = 0 + self.n_nan = 0 + self.n_raised = 0 + self.errors: Dict[str, int] = {} + + @property + def n_lost(self) -> int: + return self.n_nan + self.n_raised + + def fit(self, data: pd.DataFrame, **kwargs: Any) -> Any: + self.n_fits += 1 + try: + result = self._estimator.fit(data, **kwargs) + except _DATA_DEPENDENT_ERRORS as exc: + self.n_raised += 1 + message = f"{type(exc).__name__}: {exc}" + if message in self.errors or len(self.errors) < _MAX_ERROR_MESSAGES: + self.errors[message] = self.errors.get(message, 0) + 1 + raise + if not _has_scalar_inference(result) or not _has_finite_inference(result): + self.n_nan += 1 + raise ValueError("non-finite inference") + return result + + +def _clone(estimator: Any) -> Any: + """An unfitted copy with the same constructor parameters.""" + return type(estimator)(**estimator.get_params()) + + +# --------------------------------------------------------------------------- +# Size gate +# --------------------------------------------------------------------------- + + +def _size_controlled(rejection_rate: float, n_scored: int, n_lost: int, alpha: float) -> bool: + """Whether a no-effect run is consistent with the nominal level. + + False when nothing was scored, or when more than 10% of the replicates + were lost (an estimator that fails on hard draws would otherwise look + better than it is). Otherwise true exactly when the rejection rate is at + most ``alpha`` plus 1.96 Monte Carlo standard errors at ``alpha``. + """ + if n_scored <= 0: + return False + if n_lost / (n_scored + n_lost) > _MAX_LOST_SHARE: + return False + bound = alpha + 1.96 * np.sqrt(alpha * (1.0 - alpha) / n_scored) + return bool(rejection_rate <= bound) + + +# --------------------------------------------------------------------------- +# Data fingerprint +# --------------------------------------------------------------------------- + + +def _is_missing(value: Any) -> bool: + if value is None or value is pd.NaT: + return True + if value is getattr(pd, "NA", None): + return True + return isinstance(value, (float, np.floating)) and bool(np.isnan(value)) + + +def _encode_cell(value: Any) -> List[str]: + """Type-tagged text for one cell, so distinct values never encode alike.""" + if _is_missing(value): + return ["n", ""] + if isinstance(value, (bool, np.bool_)): + return ["b", "True" if bool(value) else "False"] + if isinstance(value, (int, np.integer)): + return ["i", str(int(value))] + if isinstance(value, (float, np.floating)): + return ["f", format(float(value), ".17g")] + if isinstance(value, np.datetime64): + return ["t", pd.Timestamp(value).isoformat()] + if isinstance(value, (datetime, date)): + return ["t", value.isoformat()] + if isinstance(value, str): + return ["s", value] + return ["o:" + type(value).__name__, repr(value)] + + +def _data_fingerprint(panel: pd.DataFrame, unit: str, time: str) -> Tuple[str, List[str]]: + """SHA-256 of a canonical text of the panel, and the columns it covers. + + Rows are sorted by (unit, time) and columns by name, so the digest does + not depend on row or column order. The text is built by hand (one JSON + line of type-tagged cells per row) so that it does not depend on the + pandas version. + """ + by_name = {str(c): c for c in panel.columns} + if len(by_name) != len(panel.columns): + raise ValueError( + "data has column labels that are equal as strings (for example 1 and " + "'1'); the data fingerprint needs distinct column names. Rename them." + ) + columns = sorted(by_name) + ordered = panel.sort_values([unit, time], kind="mergesort") + digest = hashlib.sha256() + digest.update(json.dumps(columns, ensure_ascii=True, separators=(",", ":")).encode("utf-8")) + column_values = [ordered[by_name[name]].tolist() for name in columns] + for row in zip(*column_values): + line = json.dumps( + [_encode_cell(value) for value in row], ensure_ascii=True, separators=(",", ":") + ) + digest.update(b"\n") + digest.update(line.encode("utf-8")) + return digest.hexdigest(), columns + + +# --------------------------------------------------------------------------- +# Validation +# --------------------------------------------------------------------------- + + +def _resolve_estimators( + estimators: Union[Sequence[Any], Mapping[str, Any]], +) -> Dict[str, Any]: + """Label -> estimator, in input order.""" + if isinstance(estimators, Mapping): + resolved = {str(label): est for label, est in estimators.items()} + if len(resolved) != len(estimators): + raise ValueError("estimators has labels that are equal as strings.") + else: + if isinstance(estimators, (str, bytes)) or not isinstance(estimators, Sequence): + raise TypeError( + "estimators must be a list of estimator instances or a mapping " + "from label to estimator instance." + ) + resolved = {} + for est in estimators: + label = type(est).__name__ + if label in resolved: + raise ValueError( + f"estimators contains more than one {label}. Pass a mapping " + f"from label to estimator to compare variants of one class, " + f"e.g. {{'did': {label}(), 'did_clustered': {label}(cluster=...)}}." + ) + resolved[label] = est + if not resolved: + raise ValueError("estimators is empty.") + return resolved + + +def _validate_estimators( + resolved: Dict[str, Any], + alpha: float, + staggered: bool, + unit: str, + resample_units: bool, +) -> None: + for label, est in resolved.items(): + name = type(est).__name__ + if name not in _SUPPORTED_ESTIMATORS: + raise ValueError( + f"Estimator '{label}' is a {name}, which diagnose_design does not " + f"support. Supported: {', '.join(_SUPPORTED_ESTIMATORS)}." + ) + params = est.get_params() + est_alpha = params.get("alpha", alpha) + if not np.isclose(est_alpha, alpha): + raise ValueError( + f"Estimator '{label}' has alpha={est_alpha} but diagnose_design was " + f"called with alpha={alpha}. Coverage is computed from each fit's " + f"own confidence interval, so the two must agree." + ) + anticipation = params.get("anticipation", 0) + if anticipation != 0: + raise ValueError( + f"Estimator '{label}' has anticipation={anticipation}. Its aggregate " + f"then averages periods before adoption, where no effect is " + f"injected, so bias and coverage would be scored against the wrong " + f"target. diagnose_design supports anticipation=0 only." + ) + if params.get("vcov_type") == "conley": + raise ValueError( + f"Estimator '{label}' uses vcov_type='conley', which diagnose_design " + f"does not support. {name} takes its Conley time dimension from the " + f"0/1 post indicator, so on a multi-period panel every pre-period " + f"would count as one period and the spatial and serial terms would " + f"be wrong; resampled copies of a unit would also share one location." + ) + cluster = params.get("cluster") + # StackedDiD's ``cluster`` is a mode ("unit" / "unit_subexp"), not a column. + if resample_units and name != "StackedDiD" and isinstance(cluster, str) and cluster != unit: + raise ValueError( + f"Estimator '{label}' clusters on column '{cluster}', but with " + f"resample_units=True a unit drawn twice gets a fresh id in " + f"'{unit}' only, so its copies would share one '{cluster}' cluster. " + f"Cluster on '{unit}', or pass resample_units=False to keep the " + f"panel, and its clusters, as observed." + ) + if staggered and name in _COMMON_TIMING_ESTIMATORS: + raise ValueError( + f"Estimator '{label}' ({name}) needs one common adoption period, but " + f"cohort_periods declares a staggered design. Pass a single adoption " + f"period, or drop this estimator." + ) + + +def _validate_estimator_kwargs(resolved: Dict[str, Any], estimator_kwargs: Dict[str, Any]) -> None: + refused = [key for key in estimator_kwargs if key in _REFUSED_FIT_KEYS] + if refused: + raise ValueError( + f"estimator_kwargs may not contain {sorted(refused)}: diagnose_design " + f"supplies the outcome and the placebo treatment columns itself." + ) + for label, est in resolved.items(): + parameters = inspect.signature(est.fit).parameters + if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values()): + continue + unknown = [key for key in estimator_kwargs if key not in parameters] + if unknown: + raise ValueError( + f"estimator_kwargs key(s) {sorted(unknown)} are not accepted by " + f"{type(est).__name__}.fit (estimator '{label}'). estimator_kwargs " + f"is applied to every estimator." + ) + + +def _prepare_panel( + data: pd.DataFrame, + outcome: str, + unit: str, + time: str, + first_treat: Optional[str], +) -> Tuple[pd.DataFrame, int]: + """Validate the panel and drop every row from the earliest real adoption on.""" + if not isinstance(data, pd.DataFrame): + raise TypeError("data must be a pandas DataFrame.") + needed = [outcome, unit, time] + ([first_treat] if first_treat is not None else []) + missing = [col for col in needed if col not in data.columns] + if missing: + raise ValueError(f"Column(s) {missing} not found in data.") + present = [col for col in _PLACEBO_COLUMNS if col in data.columns] + if present: + raise ValueError( + f"data already has column(s) {present}; diagnose_design reserves the " + f"'_placebo_' prefix. Rename them." + ) + if not pd.api.types.is_numeric_dtype(data[time]) or pd.api.types.is_bool_dtype(data[time]): + raise ValueError( + f"'{time}' must be numeric: the staggered estimators need numeric " + f"periods. Convert dates to an integer period index first." + ) + if data[time].isna().any() or data[unit].isna().any(): + raise ValueError(f"'{unit}' and '{time}' must not contain missing values.") + + n_dropped = 0 + panel = data + if first_treat is not None: + if not pd.api.types.is_numeric_dtype(data[first_treat]): + raise ValueError(f"'{first_treat}' must be numeric (0, inf or NaN = never treated).") + if (data.groupby(unit)[first_treat].nunique(dropna=False) > 1).any(): + raise ValueError(f"'{first_treat}' must be constant within each unit.") + # na_value: a nullable column (Int64 / Float64) marks never-treated + # units with pd.NA, which older pandas will not convert on its own. + values = data[first_treat].to_numpy(dtype=float, na_value=np.nan) + if np.any(values[np.isfinite(values)] < 0): + raise ValueError(f"'{first_treat}' has negative values.") + adopted = np.isfinite(values) & (values > 0) + if adopted.any(): + first_period = data[time].min() + always = sorted(data.loc[adopted & (values <= first_period), unit].unique().tolist()) + if always: + shown = ", ".join(repr(u) for u in always[:5]) + more = f" and {len(always) - 5} more" if len(always) > 5 else "" + raise ValueError( + f"{len(always)} unit(s) are treated from the first period on " + f"({shown}{more}), so no untreated period exists for them. " + f"Drop always-treated units before calling diagnose_design." + ) + earliest = float(values[adopted].min()) + keep = _period_values(data[time]).astype(float) < earliest + n_dropped = int((~keep).sum()) + panel = data.loc[keep] + + if len(panel) == 0: + raise ValueError("No untreated rows remain after truncation.") + if not pd.api.types.is_numeric_dtype(panel[outcome]) or pd.api.types.is_bool_dtype( + panel[outcome] + ): + raise ValueError(f"'{outcome}' must be numeric.") + if panel[outcome].isna().any(): + raise ValueError(f"'{outcome}' has missing values; diagnose_design needs a complete panel.") + if panel.duplicated([unit, time]).any(): + raise ValueError(f"data has more than one row per ({unit}, {time}).") + n_units = panel[unit].nunique() + n_periods = panel[time].nunique() + if len(panel) != n_units * n_periods: + raise ValueError( + "diagnose_design needs a balanced panel (every unit observed in " + f"every period); found {len(panel)} rows for {n_units} units x " + f"{n_periods} periods." + ) + panel = panel.sort_values([unit, time], kind="mergesort").reset_index(drop=True) + return panel, n_dropped + + +def _validate_cohort_periods(cohort_periods: Any, periods: np.ndarray) -> List[Any]: + if isinstance(cohort_periods, (str, bytes)) or not isinstance( + cohort_periods, (list, tuple, np.ndarray) + ): + raise TypeError("cohort_periods must be a list of adoption periods (values of time).") + declared = list(cohort_periods) + if not declared: + raise ValueError("cohort_periods is empty; declare at least one adoption period.") + if len(set(declared)) != len(declared): + raise ValueError("cohort_periods contains duplicates.") + for period in declared: + if period not in periods: + raise ValueError( + f"Adoption period {period!r} is not a period of the untreated panel " + f"(periods run from {periods[0]!r} to {periods[-1]!r})." + ) + if not period > 0: + raise ValueError( + f"Adoption period {period!r} is not positive; 0 marks never-treated " + f"units. Shift the period values." + ) + n_before = int(np.sum(periods < period)) + if n_before < _MIN_PRE_PERIODS: + raise ValueError( + f"Too few periods: adoption period {period!r} has {n_before} earlier " + f"period(s) in the untreated panel; at least {_MIN_PRE_PERIODS} are " + f"needed." + ) + return declared + + +def _period_values(column: pd.Series) -> np.ndarray: + """The calendar column as a plain numpy array (handles nullable dtypes).""" + if pd.api.types.is_integer_dtype(column): + return column.to_numpy(dtype=np.int64) + return column.to_numpy(dtype=float) + + +def _resolve_n_treated( + treatment_fraction: Optional[float], n_treated: Optional[int], n_units: int +) -> int: + if (treatment_fraction is None) == (n_treated is None): + raise ValueError("Pass exactly one of treatment_fraction and n_treated.") + if treatment_fraction is not None: + if not 0.0 < treatment_fraction < 1.0: + raise ValueError(f"treatment_fraction must be in (0, 1), got {treatment_fraction}.") + count = int(n_units * treatment_fraction) + else: + if isinstance(n_treated, bool) or not isinstance(n_treated, (int, np.integer)): + raise ValueError(f"n_treated must be an integer, got {n_treated!r}.") + count = int(n_treated) + if not 1 <= count <= n_units - 1: + raise ValueError( + f"The design gives {count} treated unit(s) out of {n_units}; it must " + f"leave at least one treated and one untreated unit." + ) + return count + + +def _resolve_effect_sizes(effect_sizes: Optional[List[float]]) -> List[float]: + """The effects actually run: 0 first, then the non-zero values, deduplicated.""" + resolved: List[float] = [0.0] + for effect in effect_sizes or []: + value = float(effect) + if not np.isfinite(value): + raise ValueError(f"effect_sizes must be finite, got {effect!r}.") + if value not in resolved: + resolved.append(value) + return resolved + + +def _uses_unseeded_bootstrap(estimator: Any) -> bool: + params = estimator.get_params() + if "seed" not in params or params["seed"] is not None: + return False + if type(estimator).__name__ in _COMMON_TIMING_ESTIMATORS: + return params.get("inference") == "wild_bootstrap" + return bool(params.get("n_bootstrap", 0)) + + +# --------------------------------------------------------------------------- +# Placebo generator +# --------------------------------------------------------------------------- + + +def _make_placebo_generator( + panel: pd.DataFrame, + outcome: str, + unit: str, + time: str, + n_treated: int, + cohort_periods: List[Any], + resample_units: bool, +) -> Callable[..., pd.DataFrame]: + """A ``data_generator`` for ``simulate_power`` that draws placebo designs. + + ``panel`` is balanced and sorted by (unit, time). The returned callable + uses only ``treatment_effect`` and ``seed``; the remaining keywords + ``simulate_power`` passes describe a synthetic design and are ignored. + """ + n_periods = panel[time].nunique() + n_units = len(panel) // n_periods + period_values = _period_values(panel[time])[:n_periods] + time_tiled = np.tile(period_values, n_units) + offsets = np.arange(n_periods) + outcome_position = panel.columns.get_loc(outcome) + cohorts = np.asarray(cohort_periods) + common = len(cohort_periods) == 1 + first_treat_dtype = np.result_type(cohorts.dtype, np.int64) + + def data_generator( + treatment_effect: float = 0.0, seed: Optional[int] = None, **ignored: Any + ) -> pd.DataFrame: + rng = np.random.default_rng(seed) + if resample_units: + drawn = rng.integers(0, n_units, size=n_units) + rows = (drawn[:, None] * n_periods + offsets[None, :]).ravel() + frame = panel.iloc[rows].reset_index(drop=True) + # Fresh ids: a unit drawn twice becomes two distinct units. + frame[unit] = np.repeat(np.arange(n_units), n_periods) + else: + frame = panel.copy() + treated_units = rng.choice(n_units, size=n_treated, replace=False) + first_treat_by_unit = np.zeros(n_units, dtype=first_treat_dtype) + if common: + first_treat_by_unit[treated_units] = cohorts[0] + else: + first_treat_by_unit[treated_units] = rng.choice(cohorts, size=n_treated) + first_treat_rows = np.repeat(first_treat_by_unit, n_periods) + ever_treated = first_treat_rows > 0 + active = ever_treated & (time_tiled >= first_treat_rows) + if treatment_effect != 0.0: + values = frame.iloc[:, outcome_position].to_numpy(dtype=float, copy=True) + values[active] += treatment_effect + frame[outcome] = values + frame[_FIRST_TREAT_COLUMN] = first_treat_rows + frame[_TREATED_COLUMN] = ever_treated.astype(int) + if common: + frame[_POST_COLUMN] = (time_tiled >= cohorts[0]).astype(int) + return frame + + return data_generator + + +def _fit_kwargs( + estimator: Any, outcome: str, unit: str, time: str, estimator_kwargs: Dict[str, Any] +) -> Dict[str, Any]: + """The complete ``fit()`` keywords for one estimator on a placebo frame.""" + if type(estimator).__name__ in _COMMON_TIMING_ESTIMATORS: + columns: Dict[str, Any] = { + "outcome": outcome, + "treatment": _TREATED_COLUMN, + "post": _POST_COLUMN, + "unit": unit, + } + else: + columns = { + "outcome": outcome, + "unit": unit, + "time": time, + "first_treat": _FIRST_TREAT_COLUMN, + } + columns.update(estimator_kwargs) + return columns + + +# --------------------------------------------------------------------------- +# Runners +# --------------------------------------------------------------------------- + + +def _replicate_seeds(seed: int, count: int) -> List[int]: + """The first ``count`` per-replicate seeds ``simulate_power`` will draw.""" + rng = np.random.default_rng(seed) + return [int(rng.integers(0, 2**31)) for _ in range(count)] + + +def _preflight( + label: str, + estimator: Any, + data_generator: Callable[..., pd.DataFrame], + fit_kwargs: Dict[str, Any], + seed: int, +) -> None: + """Refuse an estimator that cannot fit any of the first placebo replicates.""" + first_error: Optional[str] = None + name = type(estimator).__name__ + for replicate_seed in _replicate_seeds(seed, _PREFLIGHT_ATTEMPTS): + frame = data_generator(treatment_effect=0.0, seed=replicate_seed) + try: + result = _clone(estimator).fit(frame, **fit_kwargs) + except _DATA_DEPENDENT_ERRORS as exc: + if first_error is None: + first_error = f"{type(exc).__name__}: {exc}" + continue + if not _has_scalar_inference(result): + raise ValueError( + f"Estimator '{label}' ({name}) is misconfigured for diagnose_design: " + f"its fit returned a {type(result).__name__} without scalar att, se, " + f"p_value and a two-element conf_int." + ) + if _has_finite_inference(result): + return + if first_error is None: + first_error = "non-finite inference" + raise ValueError( + f"Estimator '{label}' ({name}) could not be fitted on any of the first " + f"{_PREFLIGHT_ATTEMPTS} placebo replicates of this design. First problem: " + f"{first_error}. Fix its configuration or drop it from estimators." + ) + + +def _failed_cell(effect: float, alpha: float, name: str, n_simulations: int) -> Any: + nan = float("nan") + return SimulationPowerResults( + power=nan, + power_se=nan, + power_ci=(nan, nan), + rejection_rate=nan, + mean_estimate=nan, + std_estimate=nan, + mean_se=nan, + coverage=nan, + n_simulations=0, + effect_sizes=[effect], + powers=[nan], + true_effect=effect, + alpha=alpha, + estimator_name=name, + n_simulation_failures=n_simulations, + ) + + +def _run_cell( + estimator: Any, + effect: float, + data_generator: Callable[..., pd.DataFrame], + fit_kwargs: Dict[str, Any], + n_units: int, + n_periods: int, + n_simulations: int, + alpha: float, + seed: int, +) -> Tuple[Any, _PlaceboFit]: + """One estimator at one effect size, through ``simulate_power``.""" + name = type(estimator).__name__ + adapter = _PlaceboFit(_clone(estimator)) + try: + cell = simulate_power( + adapter, + n_units=n_units, + n_periods=n_periods, + treatment_effect=effect, + n_simulations=n_simulations, + alpha=alpha, + seed=seed, + data_generator=data_generator, + estimator_kwargs=fit_kwargs, + progress=False, + ) + except RuntimeError as exc: + if "All simulations failed" not in str(exc): + raise + return _failed_cell(effect, alpha, name, n_simulations), adapter + return dataclasses.replace(cell, estimator_name=name), adapter + + +def _lost_message(adapter: _PlaceboFit) -> str: + parts = [f"{adapter.n_lost} of {adapter.n_fits} fits lost"] + if adapter.n_nan: + parts.append(f"{adapter.n_nan} with non-finite inference") + for message, count in adapter.errors.items(): + parts.append(f"{count} x {message}") + return "; ".join(parts) + + +def _run_mde( + estimator: Any, + null_cell: Any, + data_generator: Callable[..., pd.DataFrame], + fit_kwargs: Dict[str, Any], + n_units: int, + n_periods: int, + n_simulations: int, + alpha: float, + power: float, + seed: int, +) -> Tuple[Optional[Any], float]: + """Minimum detectable effect by ``simulate_mde``; NaN when not reportable. + + Runs inside the caller's warning capture, which adds the estimator label + on re-emission, so the warnings raised here carry none. + """ + nan = float("nan") + scale = float(null_cell.std_estimate) + if not np.isfinite(scale) or scale <= 0.0: + warnings.warn( + f"MDE not reported: the spread of the no-effect estimates is " + f"{scale}, so the search cannot be scaled.", + UserWarning, + stacklevel=3, + ) + return None, nan + name = type(estimator).__name__ + adapter = _PlaceboFit(_clone(estimator)) + try: + found = simulate_mde( + adapter, + n_units=n_units, + n_periods=n_periods, + sigma=scale, + n_simulations=n_simulations, + power=power, + alpha=alpha, + seed=seed, + data_generator=data_generator, + estimator_kwargs=fit_kwargs, + progress=False, + ) + except RuntimeError as exc: + if "All simulations failed" not in str(exc): + raise + warnings.warn( + f"MDE not reported: a search step lost every replicate " f"({_lost_message(adapter)}).", + UserWarning, + stacklevel=3, + ) + return None, nan + found = dataclasses.replace(found, estimator_name=name) + if adapter.n_fits and adapter.n_lost / adapter.n_fits > _MAX_LOST_SHARE: + warnings.warn( + f"MDE not reported: more than {_MAX_LOST_SHARE:.0%} of the " + f"fits in the search were lost ({_lost_message(adapter)}).", + UserWarning, + stacklevel=3, + ) + return found, nan + if not found.power_at_mde >= power or not found.mde > 0.0: + # simulate_mde has already warned (not bracketed, or power at effect 0 + # already at the target); the caller re-emits that warning labelled. + return found, nan + return found, float(found.mde) + + +# --------------------------------------------------------------------------- +# Public entry point +# --------------------------------------------------------------------------- + + +def diagnose_design( + data: pd.DataFrame, + outcome: str, + unit: str, + time: str, + estimators: Union[Sequence[Any], Mapping[str, Any]], + cohort_periods: List[Any], + treatment_fraction: Optional[float] = None, + n_treated: Optional[int] = None, + effect_sizes: Optional[List[float]] = None, + n_simulations: int = 500, + alpha: float = 0.05, + power: Optional[float] = None, + first_treat: Optional[str] = None, + resample_units: bool = True, + estimator_kwargs: Optional[Dict[str, Any]] = None, + seed: Optional[int] = None, + progress: bool = True, +) -> DesignDiagnosisResults: + """ + Diagnose a planned DiD design on your own untreated panel. + + Repeatedly assigns placebo treatments that follow the declared design, + optionally adds a known effect to the placebo-treated observations, fits + every estimator on the same placebo draws, and reports each estimator's + rejection rate under no effect (size), its power, bias, RMSE and coverage + at each injected effect, and optionally a minimum detectable effect. + + No real treatment effect is estimated at any point. + + Parameters + ---------- + data : pd.DataFrame + A balanced panel with no missing outcomes. It must be untreated: pass + only pre-treatment data, or pass ``first_treat`` so that every period + from the earliest real adoption onward is dropped. + outcome : str + Name of the outcome column. + unit : str + Name of the unit identifier column. + time : str + Name of the calendar period column (numeric). + estimators : list or dict + Estimator instances to compare. A list is labelled by class name; pass + a dict ``{label: estimator}`` to compare variants of one class. + Supported: DifferenceInDifferences, TwoWayFixedEffects, + CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, + EfficientDiD. + cohort_periods : list + The planned adoption periods, as values of ``time``. One value + declares a common adoption date; two or more declare a staggered + design in which each placebo-treated unit draws its period uniformly + from the list. Each needs at least two earlier periods. + treatment_fraction : float, optional + Share of units treated; the count is ``int(n_units * treatment_fraction)``. + Pass exactly one of ``treatment_fraction`` and ``n_treated``. + n_treated : int, optional + Number of units treated. + effect_sizes : list of float, optional + Effects to inject, on the outcome's scale, added to every treated + observation from adoption onward. Effect 0 is always run first. + n_simulations : int, default=500 + Placebo replicates per estimator and effect. + alpha : float, default=0.05 + Significance level. Must equal each estimator's own ``alpha``. + power : float, optional + Target power for a minimum-detectable-effect search, run only for + estimators that pass the size check. ``None`` skips the search. + first_treat : str, optional + Column with each unit's real first treatment period (0, inf or NaN + for never-treated). When given, the panel is truncated just before the + earliest real adoption. + resample_units : bool, default=True + Draw units with replacement in every replicate before assigning the + placebo. With ``False`` the panel is used as observed and the expected + rejection rate of a correctly sized test is not known exactly. With + ``True``, an estimator may cluster only on the ``unit`` column: copies + of a resampled unit are distinct units there and nowhere else. + estimator_kwargs : dict, optional + Extra ``fit()`` keywords applied to every estimator (for example + ``covariates``). Column-role keywords are refused. + seed : int, optional + Seed of the placebo draws. ``None`` draws one and records it. + progress : bool, default=True + Print one line per estimator and effect. + + Returns + ------- + DesignDiagnosisResults + One :class:`~diff_diff.SimulationPowerResults` per estimator and + effect, the size check, and the minimum detectable effects. + + Notes + ----- + Estimators are returned in input order and are never ranked. An estimator + that cannot fit any of the first five placebo replicates is refused with + its error before the run starts. After that, a replicate whose fit raises + a data-dependent error or returns non-finite inference is excluded from + every rate and counted; an estimator that loses more than 10% of its + no-effect replicates fails the size check. + + The methodology, its sources and the choices that have no paper source + are documented in ``docs/methodology/REGISTRY.md`` ``## DesignDiagnosis``. + + Examples + -------- + >>> from diff_diff import CallawaySantAnna, ImputationDiD, diagnose_design + >>> result = diagnose_design( + ... panel, outcome="y", unit="id", time="year", + ... estimators=[CallawaySantAnna(), ImputationDiD()], + ... cohort_periods=[2019], treatment_fraction=0.2, + ... effect_sizes=[0.05], n_simulations=200, seed=1, + ... ) # doctest: +SKIP + >>> result.to_dataframe() # doctest: +SKIP + """ + if isinstance(n_simulations, bool) or not isinstance(n_simulations, (int, np.integer)): + raise ValueError(f"n_simulations must be a positive integer, got {n_simulations!r}.") + if n_simulations < 1: + raise ValueError(f"n_simulations must be a positive integer, got {n_simulations}.") + if not 0.0 < alpha < 1.0: + raise ValueError(f"alpha must be in (0, 1), got {alpha}.") + if power is not None and not alpha < power < 1.0: + raise ValueError(f"power must satisfy alpha < power < 1, got {power}.") + + resolved = _resolve_estimators(estimators) + fit_extras = dict(estimator_kwargs or {}) + effects = _resolve_effect_sizes(effect_sizes) + + panel, n_dropped = _prepare_panel(data, outcome, unit, time, first_treat) + periods = np.unique(_period_values(panel[time])) + n_periods = len(periods) + n_units = panel[unit].nunique() + if n_periods < _MIN_PRE_PERIODS + 1: + raise ValueError( + f"Too few periods: the untreated panel has {n_periods} period(s); at " + f"least {_MIN_PRE_PERIODS + 1} are needed." + ) + declared = _validate_cohort_periods(cohort_periods, periods) + count = _resolve_n_treated(treatment_fraction, n_treated, n_units) + _validate_estimators( + resolved, + alpha, + staggered=len(declared) > 1, + unit=unit, + resample_units=resample_units, + ) + _validate_estimator_kwargs(resolved, fit_extras) + + if seed is None: + resolved_seed = int(np.random.SeedSequence().generate_state(1)[0]) + else: + resolved_seed = int(seed) + + for label, est in resolved.items(): + if _uses_unseeded_bootstrap(est): + warnings.warn( + f"[{label}] uses bootstrap inference with seed=None, so its results " + f"are not reproducible; the seed of diagnose_design fixes the " + f"placebo draws only. Set the estimator's own seed.", + UserWarning, + stacklevel=2, + ) + + data_sha256, data_columns = _data_fingerprint(panel, unit, time) + data_generator = _make_placebo_generator( + panel, outcome, unit, time, count, declared, resample_units + ) + fit_kwargs = { + label: _fit_kwargs(est, outcome, unit, time, fit_extras) for label, est in resolved.items() + } + + for label, est in resolved.items(): + with _WarningCapture() as capture: + _preflight(label, est, data_generator, fit_kwargs[label], resolved_seed) + _reemit(label, capture.records) + + results: Dict[str, List[SimulationPowerResults]] = {} + n_nan_inference: Dict[str, List[int]] = {} + size_controlled: Dict[str, bool] = {} + mde_results: Dict[str, SimulationMDEResults] = {} + mde: Dict[str, float] = {} + + for label, est in resolved.items(): + cells: List[SimulationPowerResults] = [] + nan_counts: List[int] = [] + null_adapter: Optional[_PlaceboFit] = None + for effect in effects: + with _WarningCapture() as capture: + cell, adapter = _run_cell( + est, + effect, + data_generator, + fit_kwargs[label], + n_units, + n_periods, + int(n_simulations), + alpha, + resolved_seed, + ) + _reemit(label, capture.records) + cells.append(cell) + nan_counts.append(adapter.n_nan) + if null_adapter is None: + null_adapter = adapter + if progress: + print( + f" diagnose_design: {label}, effect={effect:g}: " + f"rejection rate {_fmt_rate(cell.power)} " + f"({cell.n_simulations} scored, {adapter.n_lost} lost)" + ) + assert null_adapter is not None + null_cell = cells[0] + results[label] = cells + n_nan_inference[label] = nan_counts + size_controlled[label] = _size_controlled( + float(null_cell.rejection_rate), + int(null_cell.n_simulations), + null_adapter.n_lost, + alpha, + ) + mde[label] = float("nan") + if power is not None and size_controlled[label]: + with _WarningCapture() as capture: + found, value = _run_mde( + est, + null_cell, + data_generator, + fit_kwargs[label], + n_units, + n_periods, + int(n_simulations), + alpha, + power, + resolved_seed, + ) + _reemit(label, capture.records) + if found is not None: + mde_results[label] = found + mde[label] = value + if progress: + print(f" diagnose_design: {label}, MDE search: {_fmt_num(value)}") + + return DesignDiagnosisResults( + results=results, + mde_results=mde_results, + estimators={label: _clone(est) for label, est in resolved.items()}, + size_controlled=size_controlled, + n_nan_inference=n_nan_inference, + mde=mde, + effect_sizes=effects, + alpha=alpha, + target_power=power, + outcome=outcome, + unit=unit, + time=time, + first_treat=first_treat, + treatment_fraction=treatment_fraction, + n_treated=count, + cohort_periods=declared, + resample_units=resample_units, + estimator_kwargs=fit_extras, + seed=resolved_seed, + n_units=n_units, + n_periods=n_periods, + n_obs=len(panel), + n_dropped=n_dropped, + data_sha256=data_sha256, + data_columns=data_columns, + ) diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index c2fb0ba16..3019c7257 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -2389,6 +2389,67 @@ sim_result = simulate_power( ) ``` +## Design Diagnosis + +Check a planned design on your own UNTREATED panel before any real analysis. +`diagnose_design` assigns placebo treatments that follow the declared design, +optionally adds a known effect to the placebo-treated observations, and fits +every listed estimator on the same placebo draws. It never estimates a real +treatment effect. + +```python +from diff_diff import CallawaySantAnna, ImputationDiD, TwoWayFixedEffects, diagnose_design + +# `panel`: balanced, pre-treatment only (or pass first_treat= to truncate at +# the earliest real adoption). One row per unit and period. +result = diagnose_design( + panel, outcome="sales", unit="store", time="year", + estimators={"twfe": TwoWayFixedEffects(), "cs": CallawaySantAnna(), + "imputation": ImputationDiD()}, + cohort_periods=[2019], # planned adoption period(s); 2+ values = staggered + n_treated=12, # or treatment_fraction=0.2 + effect_sizes=[0.02, 0.05], # injected effects on the outcome scale; 0 always runs + n_simulations=500, + power=0.80, # optional: minimum detectable effect search + seed=1, +) +result.print_summary() +table = result.to_dataframe() # one row per estimator and effect size +null_run = result.results["cs"][0] # SimulationPowerResults at effect 0 +size = null_run.rejection_rate # should be near alpha +ok = result.size_controlled["cs"] # False -> power is not meaningful +mde = result.mde["cs"] # NaN unless size is controlled +``` + +**Parameters:** `data`, `outcome`, `unit`, `time`, `estimators` (list, or dict +`{label: estimator}` to compare variants of one class), `cohort_periods` +(required), `treatment_fraction` or `n_treated` (exactly one), `effect_sizes`, +`n_simulations=500`, `alpha=0.05`, `power=None`, `first_treat=None`, +`resample_units=True`, `estimator_kwargs=None`, `seed=None`, `progress=True`. + +**Supported estimators:** DifferenceInDifferences, TwoWayFixedEffects (common +timing only), CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, +StackedDiD, EfficientDiD (common or staggered timing). + +**Returns** `DesignDiagnosisResults`: `results` (label -> list of +`SimulationPowerResults`, aligned with `effect_sizes`; the first is the +no-effect run), `size_controlled`, `n_nan_inference`, `mde`, `mde_results`, +the declared design, `seed`, `data_sha256`. Methods: `summary()`, +`print_summary()`, `to_dataframe()`, `to_dict()`. + +**Reading the output:** estimators come back in input order and are never +ranked - do not pick the one with the highest power or the smallest MDE without +checking `size_controlled` first. An estimator that over-rejects under no effect +(for example unclustered standard errors with serially correlated outcomes, or +asymptotic inference with very few treated units) shows inflated power. + +**Refusals:** unbalanced panels, missing outcomes, non-numeric `time`, a +non-zero `anticipation`, `vcov_type="conley"`, an estimator `alpha` different from `alpha`, +DifferenceInDifferences / TwoWayFixedEffects under a staggered declaration, and +the fit keywords `formula`, `survey_design`, `post_periods` and the column-role +names, and (with the default `resample_units=True`) an estimator whose +`cluster` names a column other than `unit`. + ## Pre-Trends Power Analysis ```python diff --git a/diff_diff/guides/llms.txt b/diff_diff/guides/llms.txt index dc0487606..9e9f856d5 100644 --- a/diff_diff/guides/llms.txt +++ b/diff_diff/guides/llms.txt @@ -93,6 +93,7 @@ The site is organized into 5 sections, each with a landing page: - [Honest DiD](https://diff-diff.readthedocs.io/en/stable/api/honest_did.html): Rambachan & Roth (2023) sensitivity analysis — robust CI under parallel trends violations, breakdown values - [Pre-Trends Power Analysis](https://diff-diff.readthedocs.io/en/stable/api/pretrends.html): Roth (2022) Section II.A-B no-individually-significant (NIS) box-probability pretest power + minimum detectable violation; `pretest_form='nis'` (default) implements the paper's primary form, `pretest_form='wald'` retained as paper-supported alternative (Propositions 1+3+4 all apply); linear-violation MDV in Roth's γ units when relative-time labels are threaded through `fit()`; full Σ_22 routing on non-bootstrap CallawaySantAnna and SunAbraham adapters and on admitted CS-/StackedDiD-sourced `aggregate('event_study')` containers (StackedDiD persists its ES VCV in every inference mode) - [Power Analysis](https://diff-diff.readthedocs.io/en/stable/api/power.html): Analytical and simulation-based power analysis — MDE, sample size, power curves for study design +- [Design Diagnosis](https://diff-diff.readthedocs.io/en/stable/api/design.html): `diagnose_design(data, outcome=, unit=, time=, estimators=, cohort_periods=, n_treated= | treatment_fraction=, effect_sizes=, power=)` checks a planned design on the user's own UNTREATED panel before any real analysis (Bertrand, Duflo & Mullainathan 2004 placebo assignment and effect injection; Mizushima & Powell 2025 staggered placebos; Blair et al. 2019 diagnosands). It assigns placebo treatments that follow the declared design, fits every listed estimator on the same placebo draws, and returns per estimator the rejection rate under no effect (size), and power, bias, RMSE and coverage at each injected effect, plus an optional MDE. Outcome-blind (no real effect is estimated; pass `first_treat=` to truncate at the earliest real adoption). Estimators are returned in input order and never ranked; `size_controlled` flags estimators whose null rejection rate is consistent with `alpha`. Supports DifferenceInDifferences, TwoWayFixedEffects, CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, EfficientDiD - [MMM Calibration Export](https://diff-diff.readthedocs.io/en/stable/api/mmm.html): Assemble Marketing Mix Model calibration inputs from experiment results. Two input routes: explicit already-scoped numbers, or the pinned `AggregationResult` container from post-fit `results.aggregate('simple'|'group')` via `aggregation_result=` + `scale=`, or a `results.aggregate('total')` container ALONE (its single row is the estimator-owned total; scale is rejected - for overall totals this supersedes scale="auto") (effect = att x scale per row, in `to_dataframe()` order; `scale="auto"` reads the container's treated-obs count and is honored ONLY for ImputationDiD/TwoStageDiD fits - it acknowledges an additive-level outcome, an unweighted fit, and fully identified effects; other estimators and raw results objects fail closed). `to_pymc_marketing_lift_test(channel, x, delta_x, delta_y=, sigma=, aggregation_result=, scale=, dims=, on_wrong_sign=)` builds the PyMC-Marketing/prophetverse lift-test DataFrame with sign/zero/positivity guards. `to_meridian_roi_prior(incremental_outcome=, incremental_outcome_se=, aggregation_result=, scale=, spend, parameter="roi_m"|"mroi_m", se_widening=)` builds Google Meridian lognormal ROI priors (spend-weighted pooling, lognormal parity with `lognormal_dist_from_mean_std`, channel- and time-scoped `.to_code()` snippet setting `media_prior_type` - time scope via `meridian_calibration_mask(media_times=, media_channels=, channel=, window=)`, which builds the boolean (n_media_times, n_media_channels) mask (window = inclusive (start, end) tuple or explicit-labels list; experiment channel True on the window, every other channel ALL-TRUE per Meridian's documented convention; roi_m priors only - Meridian rejects the mask for mroi_m) and whose array `.to_code()` serializes into the snippet, or via a mask expression string, or full_model_window=True; widen `se_widening` when pooling a group-level container's same-fit cohorts). Pure numpy/pandas; imports no MMM package; never calls `aggregate()` itself. - Conley spatial HAC SE (`vcov_type="conley"`) on cross-sectional `LinearRegression` / `compute_robust_vcov` PLUS panel `DifferenceInDifferences` / `TwoWayFixedEffects` (with `conley_lag_cutoff=` for within-unit Bartlett temporal HAC) — Conley (1999) spatial-correlation-aware SEs with haversine/euclidean/callable distance metric and Bartlett/uniform spatial kernel; panel path uses the R `conleyreg`-form block-decomposed sandwich (within-period spatial + within-unit Bartlett serial, same-time excluded); parity vs R `conleyreg` (Düsterhöft 2021) on cross-sectional AND panel `lag_cutoff > 0` fixtures. Combining with explicit `cluster=` applies the combined spatial + cluster product kernel `K_total[i,j] = K_space · 1{c_i = c_j}` (cluster must be constant within each unit across periods on the panel path; validator-enforced). DiD takes `unit=` as a fit-time kwarg when `vcov_type="conley"` (not on `__init__`). Sparse k-d-tree fast path auto-activates for `n > 5_000` with bartlett kernel + haversine/euclidean metric diff --git a/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst new file mode 100644 index 000000000..d82cae9ca --- /dev/null +++ b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst @@ -0,0 +1,52 @@ +diff\_diff.DesignDiagnosisResults +================================= + +.. currentmodule:: diff_diff + +.. autoclass:: DesignDiagnosisResults + :no-members: + + + .. rubric:: Methods + + .. autosummary:: + + ~DesignDiagnosisResults.__init__ + ~DesignDiagnosisResults.print_summary + ~DesignDiagnosisResults.summary + ~DesignDiagnosisResults.to_dataframe + ~DesignDiagnosisResults.to_dict + + + + + .. rubric:: Attributes + + .. autosummary:: + + ~DesignDiagnosisResults.results + ~DesignDiagnosisResults.mde_results + ~DesignDiagnosisResults.estimators + ~DesignDiagnosisResults.size_controlled + ~DesignDiagnosisResults.n_nan_inference + ~DesignDiagnosisResults.mde + ~DesignDiagnosisResults.effect_sizes + ~DesignDiagnosisResults.alpha + ~DesignDiagnosisResults.target_power + ~DesignDiagnosisResults.outcome + ~DesignDiagnosisResults.unit + ~DesignDiagnosisResults.time + ~DesignDiagnosisResults.first_treat + ~DesignDiagnosisResults.treatment_fraction + ~DesignDiagnosisResults.n_treated + ~DesignDiagnosisResults.cohort_periods + ~DesignDiagnosisResults.resample_units + ~DesignDiagnosisResults.estimator_kwargs + ~DesignDiagnosisResults.seed + ~DesignDiagnosisResults.n_units + ~DesignDiagnosisResults.n_periods + ~DesignDiagnosisResults.n_obs + ~DesignDiagnosisResults.n_dropped + ~DesignDiagnosisResults.data_sha256 + ~DesignDiagnosisResults.data_columns + diff --git a/docs/api/_autosummary/diff_diff.diagnose_design.rst b/docs/api/_autosummary/diff_diff.diagnose_design.rst new file mode 100644 index 000000000..6cd0da2e7 --- /dev/null +++ b/docs/api/_autosummary/diff_diff.diagnose_design.rst @@ -0,0 +1,7 @@ +diff\_diff.diagnose\_design +=========================== + +.. currentmodule:: diff_diff + +.. autofunction:: diagnose_design + :no-index: \ No newline at end of file diff --git a/docs/api/design.rst b/docs/api/design.rst new file mode 100644 index 000000000..1af6fdd5e --- /dev/null +++ b/docs/api/design.rst @@ -0,0 +1,107 @@ +Design Diagnosis +================ + +Check a planned DiD design on your own untreated panel before analysing it. + +.. module:: diff_diff.design + +Overview +-------- + +:func:`~diff_diff.diagnose_design` answers two questions about a planned study, for +each candidate estimator, using the panel you will actually analyse: + +1. **Size**: when nothing happened, how often does the estimator reject? +2. **Power**: how often does it detect an effect of a given size, and how biased + and how precise are its estimates? + +It takes a panel in which no unit is treated yet, repeatedly assigns placebo +treatments that follow your declared design (how many units, which adoption +periods), optionally adds a known effect to the placebo-treated observations, and +fits every estimator on the same placebo draws. No real treatment effect is +estimated at any point: pass pre-treatment data only, or pass ``first_treat`` so +that every period from the earliest real adoption onward is dropped. + +Estimators are reported in the order you pass them and are never ranked. An +estimator fails the size check when its no-effect rejection rate is above +``alpha + 1.96 * sqrt(alpha * (1 - alpha) / R)`` - the nominal level plus a Monte +Carlo allowance for the ``R`` replicates scored - or when it loses more than 10% +of its replicates. Its power is then not meaningful and no minimum detectable +effect is reported for it. + +The methodology, its sources and the choices that have no paper source are in +the Methodology Registry under ``DesignDiagnosis``. + +diagnose_design +--------------- + +.. autofunction:: diff_diff.diagnose_design + +DesignDiagnosisResults +---------------------- + +.. autoclass:: diff_diff.DesignDiagnosisResults + :no-index: + :members: + :undoc-members: + :show-inheritance: + +Example +------- + +.. code-block:: python + + from diff_diff import ( + CallawaySantAnna, + ImputationDiD, + TwoWayFixedEffects, + diagnose_design, + ) + + # `panel` holds pre-treatment data only: one row per unit and year. + result = diagnose_design( + panel, + outcome="sales", + unit="store", + time="year", + estimators={ + "twfe": TwoWayFixedEffects(), + "cs": CallawaySantAnna(), + "imputation": ImputationDiD(), + }, + cohort_periods=[2019], # the planned adoption year + n_treated=12, # the planned number of treated stores + effect_sizes=[0.02, 0.05], # effects to inject, on the outcome's scale + n_simulations=500, + power=0.80, # also search for the minimum detectable effect + seed=1, + ) + + result.print_summary() + table = result.to_dataframe() # one row per estimator and effect size + + # The no-effect run of one estimator: its rejection_rate is the size. + null_run = result.results["cs"][0] + print(null_run.rejection_rate, result.size_controlled["cs"], result.mde["cs"]) + +A staggered design declares several adoption periods; each placebo-treated unit +draws its period from the list: + +.. code-block:: python + + result = diagnose_design( + panel, + outcome="sales", + unit="store", + time="year", + estimators=[CallawaySantAnna(), ImputationDiD()], + cohort_periods=[2018, 2019, 2020], + treatment_fraction=0.4, + n_simulations=500, + ) + +See Also +-------- + +- :doc:`power` - Power analysis on synthetic data +- :doc:`diagnostics` - Placebo tests for a fitted estimator diff --git a/docs/api/index.rst b/docs/api/index.rst index deed96831..13e6eea28 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -250,6 +250,18 @@ Power analysis for study design: diff_diff.simulate_mde diff_diff.simulate_sample_size +Design Diagnosis +---------------- + +Size and power of candidate estimators on your own untreated panel: + +.. autosummary:: + :toctree: _autosummary + :nosignatures: + + diff_diff.diagnose_design + diff_diff.DesignDiagnosisResults + Pre-Trends Power Analysis ------------------------- @@ -412,6 +424,7 @@ Diagnostics & Inference bacon honest_did power + design pretrends twfe_weights diff --git a/docs/doc-deps.yaml b/docs/doc-deps.yaml index 05b506a94..414f00850 100644 --- a/docs/doc-deps.yaml +++ b/docs/doc-deps.yaml @@ -1440,6 +1440,41 @@ sources: - path: docs/index.rst type: user_guide note: "Diagnostics & Sensitivity table row" + - path: docs/methodology/REGISTRY.md + section: "DesignDiagnosis" + type: methodology + note: "diagnose_design drives simulate_power / simulate_mde unchanged: the replicate-seed stream, the unregistered-estimator fit path, the narrow exception list and the MDE bracket are relied on" + + diff_diff/design.py: + drift_risk: medium + docs: + - path: docs/methodology/REGISTRY.md + section: "DesignDiagnosis" + type: methodology + - path: docs/methodology/papers/bertrand-duflo-mullainathan-2004-review.md + type: methodology + note: "Placebo assignment on real data, unit resampling, additive effect injection" + - path: docs/methodology/papers/mizushima-powell-2025-review.md + type: methodology + note: "Staggered placebo adoption; few-treated-unit over-rejection" + - path: docs/methodology/papers/coglianese-fang-2026-review.md + type: methodology + note: "Several estimators on the same placebo events" + - path: docs/methodology/papers/blair-2019-review.md + type: methodology + note: "Diagnosand vocabulary (bias, RMSE, power, coverage)" + - path: docs/api/design.rst + type: api_reference + - path: docs/index.rst + type: user_guide + note: "Diagnostics & Sensitivity table row" + - path: README.md + type: user_guide + note: "Diagnostics & Sensitivity catalog line" + - path: diff_diff/guides/llms.txt + type: user_guide + - path: diff_diff/guides/llms-full.txt + type: user_guide # ── Survey support ───────────────────────────────────────────────── diff --git a/docs/index.rst b/docs/index.rst index 499771d7b..5f4ad753d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -222,6 +222,8 @@ section): - Simple and Wasserstein-robust parallel trends tests, equivalence testing (TOST) * - :func:`~diff_diff.run_placebo_test` - Placebo timing, group, permutation, and leave-one-out tests + * - :func:`~diff_diff.diagnose_design` + - Design diagnosis on your own untreated panel: placebo assignments that follow the planned design, with each candidate estimator's size, power, bias, RMSE, coverage and minimum detectable effect (Bertrand, Duflo & Mullainathan 2004; Blair et al. 2019) * - :func:`~diff_diff.attgt_weights` / :func:`~diff_diff.decompose_twfe_weights` - Baker et al. (2025) implicit weights a TWFE regression places on each ATT(g,t), against the ATT^O / ATT^simple targets, with the pre-period contribution (ports Callaway's ``twfeweights``) * - :func:`~diff_diff.did_had_pretest_workflow` diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index e8d3bb437..f6d4ad8b3 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -45,6 +45,7 @@ This document provides the academic foundations and key implementation requireme - [HonestDiD](#honestdid) - [PreTrendsPower](#pretrendspower) - [PowerAnalysis](#poweranalysis) + - [DesignDiagnosis](#designdiagnosis) **Archived sections.** Sections marked *archived* are the methodology record of classes removed at the 4.0 cut (ledger rows M-010, M-013, M-015 - [M-090], cut item 9): each opens with an archive Note naming the surviving surface that runs the same estimation core, and the body is kept verbatim in the removed class's vocabulary. They are not live entry points. @@ -6952,6 +6953,91 @@ where δ is the target effect. --- +## DesignDiagnosis + +**Primary source:** +- Bertrand, M., Duflo, E., & Mullainathan, S. (2004). How Much Should We Trust Differences-in-Differences Estimates? *The Quarterly Journal of Economics*, 119(1), 249-275. https://doi.org/10.1162/003355304772839588 - placebo assignment on real untreated data, unit resampling, rejection rates, additive effect injection. Paper review: `docs/methodology/papers/bertrand-duflo-mullainathan-2004-review.md`. +- Mizushima, Y., & Powell, D. (2025). Inference with Modern Difference-in-Differences Methods. SSRN working paper 5221387 (unpublished). - placebo staggered adoption, rejection rates across estimators. Paper review: `docs/methodology/papers/mizushima-powell-2025-review.md`. +- Coglianese, J., & Fang, J. A. (2026). An Evaluation of Difference-in-Differences Methods Using Placebo Event Studies. Finance and Economics Discussion Series 2026-045, Board of Governors of the Federal Reserve System. https://doi.org/10.17016/FEDS.2026.045 - several estimators evaluated on the same placebo events. Paper review: `docs/methodology/papers/coglianese-fang-2026-review.md`. +- Blair, G., Cooper, J., Coppock, A., & Humphreys, M. (2019). Declaring and Diagnosing Research Designs. *American Political Science Review*, 113(3), 838-859. https://doi.org/10.1017/S0003055419000194 - the diagnosand vocabulary (bias, RMSE, power, coverage). Paper review: `docs/methodology/papers/blair-2019-review.md`. + +**Module:** `diff_diff/design.py` (`diagnose_design`, `DesignDiagnosisResults`) + +**Scope:** On a user's own untreated panel, repeatedly assign placebo treatments that follow a declared design, optionally add a known effect to the placebo-treated observations, fit every candidate on the same placebo draws, and report per candidate the rejection rate under no effect (size), and power, bias, RMSE and coverage at each injected effect, plus an optional minimum detectable effect. Supported: `DifferenceInDifferences`, `TwoWayFixedEffects`, `CallawaySantAnna`, `SunAbraham`, `ImputationDiD`, `TwoStageDiD`, `StackedDiD`, `EfficientDiD`, under absorbing binary treatment with common or staggered timing. The run is outcome-blind: no real treatment effect is estimated. It complements `## PlaceboTests` (single placebo fits and a permutation test for one fitted `DifferenceInDifferences`) and `## PowerAnalysis` (power on synthetic data); it shares the simulation loop of the latter. + +**Key implementation requirements:** + +*Outcome-blind guard:* +- The panel must be untreated. When `first_treat` is given, every row at or after the earliest real adoption (the smallest finite positive value; 0, `inf` and NaN mean never-treated) is dropped before anything else and counted in `n_dropped`. A unit already treated in the first period is refused by name. +- When `first_treat` is not given, untreated status is the caller's declaration and is not verified; the results record this as `first_treat=None` and `summary()` says so. + +*Declared design:* +- The number of placebo-treated units is fixed per replicate (`n_treated`, or `int(n_units * treatment_fraction)`), as in the source designs (BDM p.256: "exactly half the states"; Mizushima-Powell p.13: 5, 10 or 25 states). +- `cohort_periods` lists the planned adoption periods as values of the calendar column. One value is a common adoption date (BDM footnote 15 reports runs with the treatment year fixed). Two or more values are a staggered design in which each placebo-treated unit draws its period independently and uniformly from the list (BDM footnote 22; Mizushima-Powell p.13). Treatment is absorbing and untreated units are never-treated (Mizushima-Powell p.13). + +*Placebo replicate:* +``` +1. (resample_units=True) draw N units with replacement, each with its whole + series; a unit drawn twice becomes two distinct units [BDM p.258] +2. draw the treated set without replacement, size n_treated [BDM p.256] +3. assign each treated unit its adoption period g_i from cohort_periods +4. Y*_it = Y_it + delta * 1{i treated, t >= g_i} [BDM pp.259, 261] +5. fit every candidate on that same frame [Coglianese-Fang p.16: one set + of placebo events for all] +``` + +*Reported quantities* (per candidate and injected effect `delta`, over the `R` scored replicates; names are those of `SimulationPowerResults`): +``` +rejection_rate = power = (1/R) sum_r 1{p_r < alpha} size when delta = 0 +mean_estimate = (1/R) sum_r tau_hat_r +bias = mean_estimate - delta +std_estimate = sample SD of tau_hat_r (ddof = 1) +rmse = sqrt(bias^2 + std_estimate^2) +coverage = (1/R) sum_r 1{CI_r contains delta} +``` +The injected effect is constant over treated unit-periods, so `delta` is the value of the overall ATT every supported candidate targets, and coverage and bias are scored against it. BDM report the rejection rate with and without an injected effect; bias, RMSE and coverage are Blair et al.'s diagnosands (their Table 1), not quantities BDM or Mizushima-Powell tabulate. + +*Standard errors / inference:* none of its own. Each replicate uses the fitted candidate's own p-value and confidence interval; `alpha` must equal the candidate's own level. + +*Edge cases:* +- A replicate whose fit raises `ValueError`, `LinAlgError`, `KeyError`, `RuntimeError` or `ZeroDivisionError`, or returns non-finite `att` / `se` / `p_value` / interval bounds, is excluded from every rate and counted (`n_simulation_failures`; `n_nan_inference` is the non-finite part). +- A cell in which every replicate is lost is reported with NaN statistics and zero scored replicates; the run continues. +- Any other exception propagates. +- Fail-closed pre-flight: a candidate that cannot produce a finite, scalar fit on any of the first five placebo replicates is refused with its first error before the run starts. + +**Deviations and library choices:** +- **Note (failure policy):** three kinds of failure are kept apart. Programming errors propagate, as in `simulate_power` (see the narrow-exception Note under `## PowerAnalysis`). Configuration errors are refused by the pre-flight. Data-dependent losses are counted and excluded. One difference from `simulate_power` alone, which counts a NaN p-value as a non-rejection: here a fit with non-finite inference is excluded, because a candidate that returns NaN inference would otherwise look conservative. +- **Note (size check):** `size_controlled` is a library rule with no paper source. It is evaluated on the no-effect run in this order: false when nothing was scored; false when more than 10% of the replicates were lost (the threshold at which `simulate_power` already warns), since a candidate that fails on hard draws would otherwise look better than it is; otherwise true exactly when `rejection_rate <= alpha + 1.96 * sqrt(alpha * (1 - alpha) / R)`. Candidates are returned in input order and never ranked; the check is on null performance only. +- **Note (minimum detectable effect):** no source paper computes an MDE on real data. When `power` is given, the MDE is found by `simulate_mde`'s bisection on the injected effect, only for candidates that pass the size check, with the search bracket seeded from the candidate's own no-effect `std_estimate` so that it starts on the outcome's scale. It is reported as NaN when the bracket fails, when power at effect 0 already reaches the target, when a search step loses every replicate, or when more than 10% of the fits in the search are lost. The search draws its own placebo replicates per step: reproducible from `seed`, but not the draws used for the reported power cells. +- **Note (RMSE):** `rmse` is the existing `SimulationPowerResults` field, `sqrt(bias^2 + std_estimate^2)` with the `ddof = 1` standard deviation. Blair et al. define RMSE as the root of the plain mean squared error, so the variance term here is larger by the factor `R / (R - 1)`. +- **Note (fixed versus resampled outcomes):** `resample_units=True` is the default. With `resample_units=False` the panel is used as observed and only the assignment is random; BDM note that in that case "the exact rejection rate we should expect is not known, and may be different from 5 percent even for a correctly sized test" (p.258), so the size check against `alpha` carries that caveat. Mizushima-Powell and Coglianese-Fang assign placebos on fixed outcomes. +- **Note (declared adoption dates):** adoption periods are declared, not drawn. BDM's main design draws one passage year at random from an interior window; that variant is not implemented. Each declared period must be a period of the untreated panel with at least two earlier periods (a library minimum). +- **Note (units as the assignment level):** treatment is assigned, and units are resampled, at the level of the `unit` column. Designs whose assignment or dependence sits above the unit (survey designs, clusters of units) are not supported; `survey_design` is refused. With `resample_units=True`, a candidate whose `cluster` names a column other than the unit column is refused: a unit drawn twice gets a fresh id in the unit column only, so its copies would share one cluster and the candidate's inference would no longer be the one it has on the real panel. With `resample_units=False` the panel and its clusters are used as observed, so any cluster column is accepted. +- **Note (Conley standard errors):** a candidate with `vcov_type="conley"` is refused. `DifferenceInDifferences` and static `TwoWayFixedEffects` take the Conley time dimension from the 0/1 post indicator they are fitted with, so on a multi-period placebo panel every pre-period (and every post-period) would be treated as one period, contradicting the within-calendar-period spatial sum and period-distance serial kernel of the Conley section below; under unit resampling, copies of a unit would also share one location. +- **Note (anticipation):** a candidate with a non-zero `anticipation` is refused. Its aggregate averages periods before adoption, where no effect is injected, so bias and coverage would be scored against the wrong target. +- **Note (common-timing candidates):** `DifferenceInDifferences` and `TwoWayFixedEffects` are fitted with a time-invariant group indicator and one post indicator, so they are refused under a staggered declaration. +- **Note (calendar gaps):** `StackedDiD` needs the period just before adoption to exist. On a calendar with gaps it is refused by the pre-flight when every declared adoption period follows a gap; otherwise the affected replicates are counted as losses. +- **Note (bootstrap reproducibility):** `seed` fixes the placebo draws only. A candidate configured for bootstrap inference with its own `seed=None` is not reproducible; a warning says so and its configuration is not altered. +- **Note (balanced panels):** the panel must be balanced with no missing outcomes and a numeric calendar column. +- **Note (data fingerprint):** `data_sha256` is the SHA-256 of a canonical text of the panel actually used (every column, rows sorted by unit and period, columns sorted by name, one JSON line of type-tagged cells per row; column labels must be distinct as strings), so it does not depend on row order, column order or the pandas version. It has no paper source; it exists so that a later analysis can be checked against the diagnosed sample. + +**Reference implementation(s):** +- None to match. The source papers run their placebo procedures on their own US state-level data with their own code, and none distributes a placebo generator (BDM: only block-bootstrap code is offered, "available upon request"; Mizushima-Powell name the Stata estimation commands they call but reference no replication code; Coglianese-Fang name no software). R `DeclareDesign` implements Blair et al.'s diagnosis on simulated data, not placebo assignment on a user's panel. There is no R parity target. +- Validation is therefore internal: exact enumeration of all assignments on a six-unit panel, exact recovery of an injected effect, shared placebo draws across candidates, and the papers' qualitative findings reproduced on simulated panels (serially correlated outcomes make unclustered standard errors over-reject while unit-clustered ones are near nominal; very few treated units make asymptotic inference over-reject). The papers' own tables are not reproduced. + +**Requirements checklist:** +- [x] Placebo assignment follows the declared design; treated count exact; absorbing; untreated units never-treated: `tests/test_design.py::TestPlaceboGenerator` +- [x] Injected effect recovered by all eight candidates (common timing) and the six staggered ones (staggered timing): `TestRecovery` +- [x] Same placebo draws for every candidate and every effect, including `seed=None`: `TestPlaceboDraws` +- [x] Fixed-panel rejection rate agrees with exact enumeration of all assignments: `TestPlaceboDraws::test_fixed_panel_matches_exact_enumeration` +- [x] Outcome-blind truncation never reads rows from the first real adoption on: `TestOutcomeBlindGuard` +- [x] Failure policy (bugs propagate, pre-flight refusal, counted losses) and the size check boundaries: `TestFailurePolicy`, `TestSizeGate` +- [x] Serial correlation: unclustered standard errors over-reject, unit-clustered are near nominal (BDM, in shape): `tests/test_methodology_design.py::TestSerialCorrelationOverRejection` +- [x] Few treated units over-reject under asymptotic inference (Mizushima-Powell, in shape): `TestFewTreatedUnits` +- [x] Power rises with the injected effect; the MDE is near the normal multiplier for a correctly sized test: `TestEffectInjection`, `TestDocumentedChoices` + +--- + # Visualization ## Event Study Plotting (`plot_event_study`) diff --git a/docs/references.rst b/docs/references.rst index d2918f9fb..521b238b9 100644 --- a/docs/references.rst +++ b/docs/references.rst @@ -391,6 +391,25 @@ Power Analysis Establishes the power gains from multiple pre/post periods in panel experiments (the ``(m+r)/(mr)`` period factor); the ψ = 0 special case of Burlig, Preonas & Woerman (2020) Eq. 2. +Design Diagnosis +---------------- + +- **Bertrand, M., Duflo, E., & Mullainathan, S. (2004).** "How Much Should We Trust Differences-in-Differences Estimates?" *The Quarterly Journal of Economics*, 119(1), 249-275. https://doi.org/10.1162/003355304772839588 + + Source for placebo assignment on real untreated data, resampling whole units, the rejection rate under no effect, and power by adding a known effect to the placebo-treated observations, as implemented in ``diagnose_design``. See ``docs/methodology/REGISTRY.md`` ``## DesignDiagnosis``. + +- **Mizushima, Y., & Powell, D. (2025).** "Inference with Modern Difference-in-Differences Methods." SSRN working paper 5221387. https://papers.ssrn.com/sol3/papers.cfm?abstract_id=5221387 + + Unpublished working paper. Placebo staggered adoption and rejection rates across estimators; documents over-rejection when few units are treated. + +- **Coglianese, J., & Fang, J. A. (2026).** "An Evaluation of Difference-in-Differences Methods Using Placebo Event Studies." Finance and Economics Discussion Series 2026-045, Board of Governors of the Federal Reserve System. https://doi.org/10.17016/FEDS.2026.045 + + Evaluates many estimators on one shared set of placebo events. + +- **Blair, G., Cooper, J., Coppock, A., & Humphreys, M. (2019).** "Declaring and Diagnosing Research Designs." *American Political Science Review*, 113(3), 838-859. https://doi.org/10.1017/S0003055419000194 + + Source of the diagnosand vocabulary (bias, RMSE, power, coverage) that ``diagnose_design`` reports. + MMM Calibration Interop ----------------------- diff --git a/tests/helpers/results_foundation.py b/tests/helpers/results_foundation.py index 4506c53bd..e8be6d7d9 100644 --- a/tests/helpers/results_foundation.py +++ b/tests/helpers/results_foundation.py @@ -291,6 +291,53 @@ def make_constructed_diagnostics() -> Dict[str, Any]: search_path=[{"n": 140, "power": 0.81}], estimator_name="DifferenceInDifferences", ), + "DesignDiagnosisResults": diff_diff.DesignDiagnosisResults( + results={ + "DifferenceInDifferences": [ + diff_diff.SimulationPowerResults( + power=power, + power_se=0.02, + power_ci=(max(power - 0.04, 0.0), min(power + 0.04, 1.0)), + rejection_rate=power, + mean_estimate=effect, + std_estimate=0.11, + mean_se=0.1, + coverage=0.95, + n_simulations=100, + effect_sizes=[effect], + powers=[power], + true_effect=effect, + alpha=0.05, + estimator_name="DifferenceInDifferences", + ) + for effect, power in ((0.0, 0.05), (0.3, 0.78)) + ] + }, + mde_results={}, + estimators={"DifferenceInDifferences": diff_diff.DifferenceInDifferences()}, + size_controlled={"DifferenceInDifferences": True}, + n_nan_inference={"DifferenceInDifferences": [0, 0]}, + mde={"DifferenceInDifferences": 0.31}, + effect_sizes=[0.0, 0.3], + alpha=0.05, + target_power=0.8, + outcome="y", + unit="unit", + time="period", + first_treat=None, + treatment_fraction=0.5, + n_treated=10, + cohort_periods=[5], + resample_units=True, + estimator_kwargs={}, + seed=1, + n_units=20, + n_periods=8, + n_obs=160, + n_dropped=0, + data_sha256="0" * 64, + data_columns=["period", "unit", "y"], + ), "PlaceboTestResults": diff_diff.PlaceboTestResults( test_type="placebo_treatment", placebo_effect=0.02, diff --git a/tests/test_design.py b/tests/test_design.py new file mode 100644 index 000000000..b44681784 --- /dev/null +++ b/tests/test_design.py @@ -0,0 +1,952 @@ +"""Behavioural tests for diff_diff.design (diagnose_design).""" + +import itertools +import warnings + +import numpy as np +import pandas as pd +import pytest + +from diff_diff import ( + CallawaySantAnna, + DesignDiagnosisResults, + Diagnostic, + DifferenceInDifferences, + EfficientDiD, + ImputationDiD, + StackedDiD, + SunAbraham, + SyntheticDiD, + TwoStageDiD, + TwoWayFixedEffects, + diagnose_design, +) +from diff_diff.design import ( + _data_fingerprint, + _make_placebo_generator, + _size_controlled, +) +from diff_diff.power import SimulationPowerResults + +POWER_COLUMNS = list( + SimulationPowerResults( + power=0.5, + power_se=0.1, + power_ci=(0.3, 0.7), + rejection_rate=0.5, + mean_estimate=0.0, + std_estimate=1.0, + mean_se=1.0, + coverage=0.9, + n_simulations=10, + effect_sizes=[0.0], + powers=[0.5], + true_effect=0.0, + alpha=0.05, + estimator_name="X", + ) + .to_dict() + .keys() +) + + +def make_panel(n_units=20, n_periods=8, noise=1.0, seed=0, first_period=1): + """Additive unit and period effects plus iid noise.""" + rng = np.random.default_rng(seed) + unit_fe = rng.normal(size=n_units) + time_fe = np.linspace(0.0, 1.0, n_periods) + y = unit_fe[:, None] + time_fe[None, :] + noise * rng.normal(size=(n_units, n_periods)) + return pd.DataFrame( + { + "unit": np.repeat(np.arange(n_units), n_periods), + "period": np.tile(np.arange(first_period, first_period + n_periods), n_units), + "y": y.ravel(), + } + ) + + +def run(panel, estimators, **kwargs): + kwargs.setdefault("cohort_periods", [6]) + if "n_treated" not in kwargs: + kwargs.setdefault("treatment_fraction", 0.5) + kwargs.setdefault("n_simulations", 20) + kwargs.setdefault("seed", 11) + kwargs.setdefault("progress", False) + return diagnose_design(panel, "y", "unit", "period", estimators, **kwargs) + + +def estimates(result, label, cell=0): + return np.array([r["estimate"] for r in result.results[label][cell].simulation_results]) + + +ALL_EIGHT = [ + DifferenceInDifferences, + TwoWayFixedEffects, + CallawaySantAnna, + SunAbraham, + ImputationDiD, + TwoStageDiD, + StackedDiD, + EfficientDiD, +] +STAGGERED_SIX = ALL_EIGHT[2:] + + +class TestRecovery: + def test_all_eight_recover_injected_effect_common_timing(self): + panel = make_panel(n_units=24, n_periods=8, noise=1e-3, seed=1) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run(panel, [cls() for cls in ALL_EIGHT], effect_sizes=[2.0], n_simulations=4) + assert list(result.results) == [cls.__name__ for cls in ALL_EIGHT] + for label, cells in result.results.items(): + assert cells[0].n_simulations == 4, label + assert abs(cells[0].mean_estimate) < 1e-2, label + assert abs(cells[1].mean_estimate - 2.0) < 1e-2, label + assert abs(cells[1].bias) < 1e-2, label + + def test_staggered_six_recover_injected_effect(self): + panel = make_panel(n_units=30, n_periods=9, noise=1e-3, seed=2) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run( + panel, + [cls() for cls in STAGGERED_SIX], + cohort_periods=[5, 7], + n_treated=14, + effect_sizes=[1.5], + n_simulations=4, + ) + for label, cells in result.results.items(): + assert cells[1].n_simulations == 4, label + assert abs(cells[1].mean_estimate - 1.5) < 1e-2, label + + def test_negative_effect_shifts_estimates_down(self): + panel = make_panel(seed=3) + result = run(panel, [DifferenceInDifferences()], effect_sizes=[-0.7]) + shift = estimates(result, "DifferenceInDifferences", 1) - estimates( + result, "DifferenceInDifferences", 0 + ) + np.testing.assert_allclose(shift, -0.7, atol=1e-10) + + +class TestPlaceboDraws: + def test_seed_reproducible(self): + panel = make_panel(seed=4) + first = run(panel, [DifferenceInDifferences(), CallawaySantAnna()], effect_sizes=[0.5]) + second = run(panel, [DifferenceInDifferences(), CallawaySantAnna()], effect_sizes=[0.5]) + pd.testing.assert_frame_equal(first.to_dataframe(), second.to_dataframe()) + assert first.seed == 11 + + def test_seed_none_is_resolved_and_shared_across_estimators(self): + panel = make_panel(seed=5) + result = run( + panel, + {"a": DifferenceInDifferences(), "b": DifferenceInDifferences(cluster="unit")}, + seed=None, + ) + assert isinstance(result.seed, int) + # Same placebo draws for both labels: identical point estimates. + np.testing.assert_allclose(estimates(result, "a"), estimates(result, "b"), atol=1e-12) + again = run( + panel, + {"a": DifferenceInDifferences(), "b": DifferenceInDifferences(cluster="unit")}, + seed=result.seed, + ) + np.testing.assert_allclose(estimates(result, "a"), estimates(again, "a"), atol=1e-12) + + def test_same_draws_across_effect_sizes(self): + panel = make_panel(seed=6) + result = run(panel, [DifferenceInDifferences()], effect_sizes=[0.25, 1.0]) + base = estimates(result, "DifferenceInDifferences", 0) + np.testing.assert_allclose( + estimates(result, "DifferenceInDifferences", 1) - base, 0.25, atol=1e-10 + ) + np.testing.assert_allclose( + estimates(result, "DifferenceInDifferences", 2) - base, 1.0, atol=1e-10 + ) + + def test_row_order_invariant(self): + panel = make_panel(seed=7) + shuffled = panel.sample(frac=1.0, random_state=0).reset_index(drop=True) + first = run(panel, [TwoWayFixedEffects()]) + second = run(shuffled, [TwoWayFixedEffects()]) + np.testing.assert_allclose( + estimates(first, "TwoWayFixedEffects"), + estimates(second, "TwoWayFixedEffects"), + atol=1e-10, + ) + assert first.data_sha256 == second.data_sha256 + + def test_fixed_panel_matches_exact_enumeration(self): + """N=6, one date, no resampling: 20 possible assignments, all enumerable.""" + panel = make_panel(n_units=6, n_periods=6, noise=1.0, seed=8) + estimator = DifferenceInDifferences(vcov_type="classical") + enumerated = {} + for treated in itertools.combinations(range(6), 3): + frame = panel.copy() + frame["g"] = frame["unit"].isin(treated).astype(int) + frame["p"] = (frame["period"] >= 4).astype(int) + fit = DifferenceInDifferences(vcov_type="classical").fit( + frame, outcome="y", treatment="g", post="p" + ) + enumerated[round(float(fit.att), 10)] = bool(fit.p_value < 0.05) + exact_rate = float(np.mean(list(enumerated.values()))) + result = run( + panel, + [estimator], + cohort_periods=[4], + n_treated=3, + resample_units=False, + n_simulations=400, + ) + cell = result.results["DifferenceInDifferences"][0] + drawn = {round(float(e), 10) for e in estimates(result, "DifferenceInDifferences")} + assert drawn <= set(enumerated) + assert len(drawn) > 10 + rate_from_draws = np.mean( + [enumerated[round(float(e), 10)] for e in estimates(result, "DifferenceInDifferences")] + ) + assert cell.rejection_rate == pytest.approx(rate_from_draws) + assert abs(cell.rejection_rate - exact_rate) < 0.1 + + +class TestPlaceboGenerator: + def test_resampled_duplicates_are_distinct_units(self): + panel = make_panel(n_units=10, n_periods=6, seed=9) + generator = _make_placebo_generator(panel, "y", "unit", "period", 4, [4], True) + frame = generator(treatment_effect=0.0, seed=3) + assert len(frame) == len(panel) + assert not frame.duplicated(["unit", "period"]).any() + assert frame["unit"].nunique() == 10 + # With replacement, some original series repeat. + first_period = frame[frame["period"] == 1]["y"].round(12) + assert first_period.nunique() < 10 + + def test_common_timing_columns(self): + panel = make_panel(n_units=10, n_periods=6, seed=10) + generator = _make_placebo_generator(panel, "y", "unit", "period", 4, [4], False) + null = generator(treatment_effect=0.0, seed=5) + shifted = generator(treatment_effect=2.0, seed=5) + by_unit = null.groupby("unit")["_placebo_treated"].agg(["min", "max"]) + assert (by_unit["min"] == by_unit["max"]).all() # time-invariant group indicator + assert by_unit["max"].sum() == 4 + np.testing.assert_array_equal(null["_placebo_post"], (null["period"] >= 4).astype(int)) + active = (null["_placebo_treated"] == 1) & (null["_placebo_post"] == 1) + np.testing.assert_allclose((shifted["y"] - null["y"])[active], 2.0) + np.testing.assert_allclose((shifted["y"] - null["y"])[~active], 0.0) + np.testing.assert_allclose(null["y"], panel["y"]) # fixed panel left as observed + + def test_staggered_columns(self): + panel = make_panel(n_units=40, n_periods=8, seed=11) + generator = _make_placebo_generator(panel, "y", "unit", "period", 15, [4, 6, 7], True) + null = generator(treatment_effect=0.0, seed=2) + shifted = generator(treatment_effect=1.0, seed=2) + assert "_placebo_post" not in null.columns + first_treat = null.groupby("unit")["_placebo_first_treat"].agg(["min", "max"]) + assert (first_treat["min"] == first_treat["max"]).all() + per_unit = first_treat["max"] + assert (per_unit > 0).sum() == 15 + assert set(per_unit[per_unit > 0]) <= {4, 6, 7} + assert len(set(per_unit[per_unit > 0])) > 1 + active = (null["_placebo_first_treat"] > 0) & ( + null["period"] >= null["_placebo_first_treat"] + ) + np.testing.assert_allclose((shifted["y"] - null["y"])[active], 1.0) + np.testing.assert_allclose((shifted["y"] - null["y"])[~active], 0.0) + + +class TestOutcomeBlindGuard: + def test_truncates_at_earliest_real_adoption(self): + panel = make_panel(n_units=20, n_periods=10, seed=12) + panel["ft"] = np.where(panel["unit"] < 5, 8, np.where(panel["unit"] < 8, 9, 0)) + clean = panel[panel["period"] < 8] + result = run(panel, [DifferenceInDifferences()], cohort_periods=[5], first_treat="ft") + assert result.n_dropped == 20 * 3 + assert result.n_periods == 7 + assert result.first_treat == "ft" + # Rows from the first real adoption on are never read. + poisoned = panel.copy() + poisoned.loc[poisoned["period"] >= 8, "y"] = np.nan + again = run(poisoned, [DifferenceInDifferences()], cohort_periods=[5], first_treat="ft") + np.testing.assert_allclose( + estimates(result, "DifferenceInDifferences"), + estimates(again, "DifferenceInDifferences"), + ) + assert result.data_sha256 == again.data_sha256 + assert result.data_sha256 == _data_fingerprint(clean, "unit", "period")[0] + + @pytest.mark.parametrize("never", [0, np.inf, np.nan]) + def test_never_treated_codes_drop_nothing(self, never): + panel = make_panel(seed=13) + panel["ft"] = float(never) + result = run(panel, [DifferenceInDifferences()], first_treat="ft") + assert result.n_dropped == 0 + assert result.n_periods == 8 + + @pytest.mark.parametrize("dtype", ["Int64", "Float64"]) + def test_nullable_first_treat_with_pd_na(self, dtype): + """pd.NA marks never-treated units in a nullable column.""" + panel = make_panel(n_units=20, n_periods=10, seed=64) + plain = panel.assign(ft=np.where(panel["unit"] < 5, 8.0, np.nan)) + nullable = panel.assign( + ft=pd.array([8 if u < 5 else pd.NA for u in panel["unit"]], dtype=dtype) + ) + assert nullable["ft"].isna().any() + expected = run(plain, [DifferenceInDifferences()], cohort_periods=[5], first_treat="ft") + result = run(nullable, [DifferenceInDifferences()], cohort_periods=[5], first_treat="ft") + assert result.n_periods == 7 # periods 8 onward are dropped + assert result.n_dropped == expected.n_dropped == 20 * 3 + np.testing.assert_allclose( + estimates(result, "DifferenceInDifferences"), + estimates(expected, "DifferenceInDifferences"), + ) + + def test_nullable_integer_calendar_column(self): + panel = make_panel(seed=65) + expected = run(panel, [DifferenceInDifferences(), CallawaySantAnna()]) + nullable = panel.assign(period=panel["period"].astype("Int64")) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run(nullable, [DifferenceInDifferences(), CallawaySantAnna()]) + for label in ("DifferenceInDifferences", "CallawaySantAnna"): + np.testing.assert_allclose(estimates(result, label), estimates(expected, label)) + + def test_always_treated_unit_is_named(self): + panel = make_panel(seed=14) + panel["ft"] = np.where(panel["unit"] == 3, 1, 0) + with pytest.raises(ValueError, match="always-treated"): + run(panel, [DifferenceInDifferences()], first_treat="ft") + + def test_declared_untreated_is_reported_in_summary(self): + result = run(make_panel(seed=15), [DifferenceInDifferences()]) + assert result.first_treat is None + assert "declared by caller" in result.summary() + + def test_first_treat_must_be_constant_within_unit(self): + panel = make_panel(seed=16) + panel["ft"] = np.where(panel["period"] > 4, 7, 0) + with pytest.raises(ValueError, match="constant within each unit"): + run(panel, [DifferenceInDifferences()], first_treat="ft") + + +class TestRefusals: + def test_unbalanced_panel(self): + panel = make_panel(seed=17).iloc[1:] + with pytest.raises(ValueError, match="balanced panel"): + run(panel, [DifferenceInDifferences()]) + + def test_missing_outcome(self): + panel = make_panel(seed=18) + panel.loc[3, "y"] = np.nan + with pytest.raises(ValueError, match="missing values"): + run(panel, [DifferenceInDifferences()]) + + def test_non_numeric_time(self): + panel = make_panel(seed=19) + panel["period"] = panel["period"].astype(str) + with pytest.raises(ValueError, match="must be numeric"): + run(panel, [DifferenceInDifferences()], cohort_periods=["6"]) + + def test_reserved_column(self): + panel = make_panel(seed=20) + panel["_placebo_post"] = 0 + with pytest.raises(ValueError, match="_placebo_"): + run(panel, [DifferenceInDifferences()]) + + @pytest.mark.parametrize( + "cohort_periods, match", + [ + ([], "empty"), + ([6, 6], "duplicates"), + ([99], "not a period"), + ([2], "Too few periods"), + ], + ) + def test_cohort_periods(self, cohort_periods, match): + with pytest.raises(ValueError, match=match): + run(make_panel(seed=21), [CallawaySantAnna()], cohort_periods=cohort_periods) + + def test_non_positive_adoption_period(self): + panel = make_panel(seed=22, first_period=-5) # periods -5..2 + with pytest.raises(ValueError, match="not positive"): + run(panel, [CallawaySantAnna()], cohort_periods=[0]) + + @pytest.mark.parametrize( + "kwargs, match", + [ + ({"treatment_fraction": None, "n_treated": None}, "exactly one"), + ({"treatment_fraction": 0.5, "n_treated": 3}, "exactly one"), + ({"treatment_fraction": 0.01, "n_treated": None}, "at least one treated"), + ({"treatment_fraction": None, "n_treated": 20}, "at least one treated"), + ({"treatment_fraction": 1.5, "n_treated": None}, r"in \(0, 1\)"), + ], + ) + def test_treated_count(self, kwargs, match): + with pytest.raises(ValueError, match=match): + run(make_panel(seed=23), [DifferenceInDifferences()], **kwargs) + + def test_unsupported_estimator(self): + with pytest.raises(ValueError, match="does not support"): + run(make_panel(seed=24), [SyntheticDiD()]) + + def test_duplicate_class_in_list_asks_for_mapping(self): + with pytest.raises(ValueError, match="Pass a mapping"): + run( + make_panel(seed=25), + [DifferenceInDifferences(), DifferenceInDifferences(cluster="unit")], + ) + + def test_alpha_mismatch(self): + with pytest.raises(ValueError, match="alpha"): + run(make_panel(seed=26), [DifferenceInDifferences(alpha=0.10)]) + + def test_anticipation_refused(self): + with pytest.raises(ValueError, match="anticipation"): + run(make_panel(seed=27), [CallawaySantAnna(anticipation=1)]) + + def test_other_cluster_column_refused_when_resampling(self): + panel = make_panel(seed=60) + panel["unit_copy"] = panel["unit"] + with pytest.raises(ValueError, match="clusters on column 'unit_copy'"): + run(panel, [DifferenceInDifferences(cluster="unit_copy")]) + with pytest.raises(ValueError, match="clusters on column 'unit_copy'"): + run(panel, [CallawaySantAnna(cluster="unit_copy")]) + + def test_other_cluster_column_allowed_on_the_fixed_panel(self): + """Without resampling the panel's clusters are as observed, so an + equivalent cluster column gives identical inference.""" + panel = make_panel(seed=61) + panel["unit_copy"] = panel["unit"] + result = run( + panel, + { + "by_unit": DifferenceInDifferences(cluster="unit"), + "by_copy": DifferenceInDifferences(cluster="unit_copy"), + }, + resample_units=False, + ) + a, b = result.results["by_unit"][0], result.results["by_copy"][0] + assert a.rejection_rate == b.rejection_rate + assert a.mean_se == pytest.approx(b.mean_se, rel=1e-12) + + def test_unit_cluster_allowed_when_resampling_whatever_the_column_is_called(self): + panel = make_panel(seed=62).rename(columns={"unit": "store"}) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = diagnose_design( + panel, + "y", + "store", + "period", + # StackedDiD's cluster="unit" is a mode, not a column name. + {"did": DifferenceInDifferences(cluster="store"), "stacked": StackedDiD()}, + cohort_periods=[6], + treatment_fraction=0.5, + n_simulations=5, + seed=1, + progress=False, + ) + for cells in result.results.values(): + assert cells[0].n_simulations == 5 + + def test_common_timing_estimator_under_staggered_declaration(self): + with pytest.raises(ValueError, match="one common adoption period"): + run(make_panel(seed=28), [TwoWayFixedEffects()], cohort_periods=[5, 6]) + + @pytest.mark.parametrize( + "key", + ["data", "outcome", "unit", "time", "first_treat", "treatment", "post", "formula"] + + ["post_periods", "survey_design"], + ) + def test_refused_fit_keywords(self, key): + with pytest.raises(ValueError, match="may not contain"): + run(make_panel(seed=29), [DifferenceInDifferences()], estimator_kwargs={key: "x"}) + + def test_fit_keyword_not_accepted_by_one_estimator(self): + with pytest.raises(ValueError, match="not accepted by TwoWayFixedEffects.fit"): + run( + make_panel(seed=30), + [DifferenceInDifferences(), TwoWayFixedEffects()], + estimator_kwargs={"absorb": ["unit"]}, + ) + + @pytest.mark.parametrize( + "kwargs, match", + [ + ({"n_simulations": 0}, "positive integer"), + ({"n_simulations": 2.5}, "positive integer"), + ({"alpha": 0.0}, "alpha"), + ({"power": 0.05}, "alpha < power < 1"), + ({"power": 1.0}, "alpha < power < 1"), + ({"effect_sizes": [np.inf]}, "finite"), + ], + ) + def test_scalar_validation(self, kwargs, match): + with pytest.raises(ValueError, match=match): + run(make_panel(seed=31), [DifferenceInDifferences()], **kwargs) + + +def _stub_fit(monkeypatch, behaviour): + """Replace TwoWayFixedEffects.fit with a call-counted wrapper. + + ``behaviour(call_index, result_factory)`` returns the fit result (or + raises). Call order is deterministic: the pre-flight fit(s), then + n_simulations fits per cell in effect order, then the MDE search. + """ + original = TwoWayFixedEffects.fit + calls = {"n": 0} + + def fit(self, data, **kwargs): + calls["n"] += 1 + return behaviour(calls["n"], lambda: original(self, data, **kwargs)) + + monkeypatch.setattr(TwoWayFixedEffects, "fit", fit) + return calls + + +def _with_nan_inference(result): + result.se = np.nan + result.p_value = np.nan + result.conf_int = (np.nan, np.nan) + return result + + +class TestFailurePolicy: + estimators = staticmethod( + lambda: {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()} + ) + + def test_nan_inference_after_preflight_is_excluded_and_counted(self, monkeypatch): + _stub_fit(monkeypatch, lambda i, make: make() if i == 1 else _with_nan_inference(make())) + with pytest.warns(UserWarning): + result = run(make_panel(seed=32), self.estimators(), n_simulations=15, power=0.8) + cell = result.results["twfe"][0] + assert cell.n_simulations == 0 + assert cell.n_simulation_failures == 15 + assert np.isnan(cell.rejection_rate) + assert result.n_nan_inference["twfe"] == [15] + assert result.size_controlled["twfe"] is False + assert np.isnan(result.mde["twfe"]) + assert "twfe" not in result.mde_results + assert result.results["did"][0].n_simulations == 15 # the other estimator completes + + def test_some_nan_replicates_leave_rates_over_the_rest(self, monkeypatch): + # Calls 2..6 are the first five replicates of the effect-0 cell. + _stub_fit( + monkeypatch, + lambda i, make: _with_nan_inference(make()) if 2 <= i <= 6 else make(), + ) + with pytest.warns(UserWarning): + result = run(make_panel(seed=33), self.estimators(), n_simulations=20) + cell = result.results["twfe"][0] + assert cell.n_simulations == 15 + assert cell.n_simulation_failures == 5 + assert result.n_nan_inference["twfe"] == [5] + assert np.isfinite(cell.mean_estimate) + assert result.size_controlled["twfe"] is False # 25% lost > 10% + + def test_value_error_after_preflight_is_a_failed_row(self, monkeypatch): + def behaviour(i, make): + if i == 1: + return make() + raise ValueError("boom on this draw") + + _stub_fit(monkeypatch, behaviour) + with pytest.warns(UserWarning): + result = run(make_panel(seed=34), self.estimators(), n_simulations=12) + cell = result.results["twfe"][0] + assert cell.n_simulations == 0 + assert cell.n_simulation_failures == 12 + assert result.n_nan_inference["twfe"] == [0] + assert result.size_controlled["twfe"] is False + assert result.results["did"][0].n_simulations == 12 + + def test_value_error_on_every_call_is_refused_by_preflight(self, monkeypatch): + def behaviour(i, make): + raise ValueError("cannot fit this design") + + calls = _stub_fit(monkeypatch, behaviour) + with pytest.raises(ValueError, match="'twfe'.*cannot fit this design"): + run(make_panel(seed=35), self.estimators()) + assert calls["n"] == 5 # all pre-flight attempts, nothing else + + def test_nan_inference_on_every_call_is_refused_by_preflight(self, monkeypatch): + _stub_fit(monkeypatch, lambda i, make: _with_nan_inference(make())) + with pytest.raises(ValueError, match="non-finite inference"): + run(make_panel(seed=36), self.estimators()) + + def test_type_error_propagates(self, monkeypatch): + def behaviour(i, make): + if i == 1: + return make() + raise TypeError("a bug, not a data problem") + + _stub_fit(monkeypatch, behaviour) + with pytest.raises(TypeError, match="a bug"): + run(make_panel(seed=37), self.estimators()) + + def test_failures_after_the_null_cell_leave_size_intact(self, monkeypatch): + n = 12 + + def behaviour(i, make): + if i > 1 + n: # pre-flight + effect-0 cell succeed + raise ValueError("fails once an effect is injected") + return make() + + _stub_fit(monkeypatch, behaviour) + with pytest.warns(UserWarning): + result = run( + make_panel(seed=38), self.estimators(), n_simulations=n, effect_sizes=[1.0] + ) + null, shifted = result.results["twfe"] + assert null.n_simulations == n and null.n_simulation_failures == 0 + assert shifted.n_simulations == 0 and shifted.n_simulation_failures == n + assert np.isfinite(null.rejection_rate) + + def test_lost_fits_during_mde_search_give_nan_mde(self, monkeypatch): + n = 30 + + def behaviour(i, make): + # After the pre-flight and the effect-0 cell, lose every third fit. + if i > 1 + n and i % 3 == 0: + raise ValueError("lost during the search") + return make() + + _stub_fit(monkeypatch, behaviour) + panel = make_panel(n_units=30, n_periods=8, seed=39) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + result = run(panel, self.estimators(), n_simulations=n, power=0.8) + messages = [str(w.message) for w in caught] + assert any(m.startswith("[twfe] MDE not reported") for m in messages) + assert result.results["twfe"][0].n_simulation_failures == 0 + assert result.size_controlled["twfe"] # the gate looks at effect 0 only + assert np.isnan(result.mde["twfe"]) + assert "twfe" in result.mde_results # the search ran; its value is withheld + assert result.size_controlled["did"] and np.isfinite(result.mde["did"]) + + def test_event_study_keyword_is_refused_by_preflight(self): + with pytest.raises(ValueError, match="could not be fitted"): + run( + make_panel(seed=40), + [TwoWayFixedEffects()], + estimator_kwargs={"event_study": True}, + ) + + def test_stacked_did_on_gapped_calendar_is_refused(self): + panel = make_panel(n_units=20, n_periods=8, seed=41) + panel["period"] = panel["period"] * 2 # 2, 4, ..., 16: no period before adoption + with pytest.raises(ValueError, match="'StackedDiD'.*could not be fitted"): + run(panel, [StackedDiD()], cohort_periods=[10]) + + +class TestSizeGate: + def test_bound(self): + alpha, n = 0.05, 400 + bound = alpha + 1.96 * np.sqrt(alpha * (1 - alpha) / n) + assert _size_controlled(bound - 1e-9, n, 0, alpha) is True + assert _size_controlled(bound, n, 0, alpha) is True + assert _size_controlled(bound + 1e-9, n, 0, alpha) is False + assert _size_controlled(0.0, n, 0, alpha) is True + + def test_bound_uses_scored_count(self): + # 0.09 passes with 100 scored replicates but not with 10,000. + assert _size_controlled(0.09, 100, 0, 0.05) is True + assert _size_controlled(0.09, 10_000, 0, 0.05) is False + + def test_lost_share_boundary(self): + assert _size_controlled(0.05, 90, 10, 0.05) is True # exactly 10% lost + assert _size_controlled(0.05, 89, 11, 0.05) is False # 11% lost + assert _size_controlled(0.0, 80, 20, 0.05) is False + + def test_nothing_scored(self): + assert _size_controlled(float("nan"), 0, 50, 0.05) is False + assert _size_controlled(0.0, 0, 0, 0.05) is False + + +class TestFingerprint: + def frame(self): + return pd.DataFrame( + { + "unit": [1, 1, 2, 2], + "period": [1, 2, 1, 2], + "y": [0.1, 0.2, 0.3, 0.4], + "tag": ["a", "b", "c", "d"], + } + ) + + def test_deterministic_and_order_invariant(self): + frame = self.frame() + digest, columns = _data_fingerprint(frame, "unit", "period") + assert columns == ["period", "tag", "unit", "y"] + assert _data_fingerprint(frame, "unit", "period")[0] == digest + reordered = frame.iloc[[3, 0, 2, 1]][["tag", "y", "unit", "period"]] + assert _data_fingerprint(reordered, "unit", "period")[0] == digest + + def test_changes_with_any_value(self): + frame = self.frame() + digest = _data_fingerprint(frame, "unit", "period")[0] + changed = frame.copy() + changed.loc[2, "y"] = 0.3000000001 + assert _data_fingerprint(changed, "unit", "period")[0] != digest + changed = frame.copy() + changed.loc[1, "tag"] = "B" + assert _data_fingerprint(changed, "unit", "period")[0] != digest + + def test_distinguishes_types(self): + def digest(values): + frame = self.frame() + frame["tag"] = pd.Series(values, dtype=object) + return _data_fingerprint(frame, "unit", "period")[0] + + base = ["a", "b", "c", "d"] + assert digest(["", "b", "c", "d"]) != digest([None, "b", "c", "d"]) + assert digest(["", "b", "c", "d"]) != digest([np.nan, "b", "c", "d"]) + assert digest([True, "b", "c", "d"]) != digest([1, "b", "c", "d"]) + assert digest([1, "b", "c", "d"]) != digest([1.0, "b", "c", "d"]) + assert digest([(1, 2), "b", "c", "d"]) != digest(["(1, 2)", "b", "c", "d"]) + assert digest(base) == digest(list(base)) + + def test_column_labels_equal_as_strings_are_refused(self): + frame = self.frame() + frame[1] = [1.0, 2.0, 3.0, 4.0] + frame["1"] = [5.0, 6.0, 7.0, 8.0] + with pytest.raises(ValueError, match="equal as strings"): + _data_fingerprint(frame, "unit", "period") + panel = make_panel(seed=63) + panel[1] = 0.0 + panel["1"] = 1.0 + with pytest.raises(ValueError, match="equal as strings"): + run(panel, [DifferenceInDifferences()]) + + def test_not_fooled_by_punctuation_inside_values(self): + def digest(first, second): + frame = self.frame().iloc[:2].copy() + frame["tag"] = [first, second] + frame["tag2"] = ["x", "y"] + return _data_fingerprint(frame, "unit", "period")[0] + + assert digest('a"],["s","b', "c") != digest("a", 'b"],["s","c') + assert digest("a\nb", "c") != digest("a", "b\nc") + + +class _Chatty: + """Stub behaviour: warn on every fit, with a different message each time.""" + + def __call__(self, i, make): + warnings.warn(f"chatty estimator, call {i}", UserWarning) + return make() + + +class TestWarnings: + estimators = staticmethod( + lambda: {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()} + ) + + def test_aggregated_and_labelled(self, monkeypatch): + _stub_fit(monkeypatch, _Chatty()) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + result = run(make_panel(seed=42), self.estimators(), n_simulations=10) + messages = [str(w.message) for w in caught if "chatty" in str(w.message)] + assert messages and all(m.startswith("[twfe] ") for m in messages) + # One per block (pre-flight, the single cell), not one per fit. + assert len(messages) == 2 + assert any("raised 10 times" in m for m in messages) + assert result.results["twfe"][0].n_simulation_failures == 0 + + def test_caller_ignore_filter_does_not_lose_replicates(self, monkeypatch): + _stub_fit(monkeypatch, _Chatty()) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("ignore") + result = run(make_panel(seed=43), self.estimators(), n_simulations=10) + assert caught == [] + assert result.results["twfe"][0].n_simulations == 10 + + def test_caller_error_filter_raises_the_labelled_warning(self, monkeypatch): + _stub_fit(monkeypatch, _Chatty()) + with warnings.catch_warnings(): + warnings.simplefilter("error") + # Raised at re-emission (labelled), not from inside a fit, and the + # estimator is not refused by the pre-flight because of it. + with pytest.raises(UserWarning, match=r"^\[twfe\] chatty estimator, call 1$"): + run(make_panel(seed=44), self.estimators(), n_simulations=10) + + def test_unseeded_bootstrap_warns(self): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + run( + make_panel(seed=45), + {"cs": CallawaySantAnna(n_bootstrap=19)}, + n_simulations=3, + ) + assert [w for w in caught if "[cs] uses bootstrap inference" in str(w.message)] + + def test_seeded_bootstrap_does_not_warn(self): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + run( + make_panel(seed=46), + {"cs": CallawaySantAnna(n_bootstrap=19, seed=1)}, + n_simulations=3, + ) + assert not [w for w in caught if "not reproducible" in str(w.message)] + + +@pytest.fixture(scope="module") +def contract_result(): + return run( + make_panel(seed=47), + { + "did": DifferenceInDifferences(), + "did_clustered": DifferenceInDifferences(cluster="unit"), + }, + effect_sizes=[0.5, 0.5, 0.0, 1.0], + n_simulations=15, + ) + + +class TestResultsContract: + @pytest.fixture + def result(self, contract_result): + return contract_result + + def test_is_a_diagnostic_without_the_estimator_quintet(self, result): + assert isinstance(result, DesignDiagnosisResults) + assert isinstance(result, Diagnostic) + for name in ("att", "se", "t_stat", "p_value", "conf_int"): + assert not hasattr(result, name) + + def test_effect_sizes_are_the_ones_run(self, result): + assert result.effect_sizes == [0.0, 0.5, 1.0] + for cells in result.results.values(): + assert [cell.true_effect for cell in cells] == [0.0, 0.5, 1.0] + + def test_dataframe_layout(self, result): + frame = result.to_dataframe() + assert list(frame.columns) == ( + ["label"] + POWER_COLUMNS + ["size_controlled", "n_nan_inference", "mde"] + ) + assert list(frame["label"]) == ["did"] * 3 + ["did_clustered"] * 3 + assert set(frame["estimator_name"]) == {"DifferenceInDifferences"} + assert list(frame["true_effect"]) == [0.0, 0.5, 1.0] * 2 + # The requested count is scored + failed on every row. + assert ((frame["n_simulations"] + frame["n_simulation_failures"]) == 15).all() + + def test_rejection_rate_at_zero_is_the_size(self, result): + null = result.results["did"][0] + assert null.true_effect == 0.0 + assert null.rejection_rate == null.power + assert 0.0 <= null.rejection_rate <= 1.0 + + def test_to_dict(self, result): + payload = result.to_dict() + assert payload["estimators"]["did_clustered"] == { + "estimator_name": "DifferenceInDifferences", + "params": DifferenceInDifferences(cluster="unit").get_params(), + } + assert payload["n_treated"] == 10 + assert payload["cohort_periods"] == [6] + assert len(payload["results"]) == 6 + assert payload["data_sha256"] == result.data_sha256 + + def test_estimators_field_holds_unfitted_copies(self, result): + copy = result.estimators["did_clustered"] + assert isinstance(copy, DifferenceInDifferences) + assert copy.get_params()["cluster"] == "unit" + assert not getattr(copy, "is_fitted_", False) + + def test_summary_lists_every_estimator_in_input_order(self, result): + text = result.summary() + assert text.index("did ") < text.index("did_clustered") + assert "not ranked" in text + + def test_progress_prints_one_line_per_cell(self, capsys): + run( + make_panel(seed=48), + [DifferenceInDifferences()], + effect_sizes=[0.5], + n_simulations=5, + progress=True, + ) + lines = [ln for ln in capsys.readouterr().out.splitlines() if "diagnose_design" in ln] + assert len(lines) == 2 + + +class TestMDE: + def test_mde_reported_only_for_size_controlled_estimators(self, monkeypatch): + import diff_diff.design as design + + monkeypatch.setattr( + design, + "_size_controlled", + lambda rate, n_scored, n_lost, alpha: False, + ) + result = run(make_panel(seed=49), [DifferenceInDifferences()], power=0.8) + assert np.isnan(result.mde["DifferenceInDifferences"]) + assert result.mde_results == {} + assert result.target_power == 0.8 + + def test_mde_is_on_the_outcome_scale(self): + # Same panel in two units: the MDE scales with the outcome. + panel = make_panel(n_units=30, n_periods=8, seed=50) + scaled = panel.assign(y=panel["y"] * 1000.0) + kwargs = dict( + estimators=[DifferenceInDifferences(cluster="unit")], + n_simulations=60, + power=0.8, + ) + small = run(panel, **kwargs) + large = run(scaled, **kwargs) + label = "DifferenceInDifferences" + assert small.size_controlled[label] + assert np.isfinite(small.mde[label]) and small.mde[label] > 0 + assert large.mde[label] == pytest.approx(1000.0 * small.mde[label], rel=1e-6) + found = small.mde_results[label] + assert found.estimator_name == label + assert found.power_at_mde >= 0.8 + + def test_no_mde_without_power(self): + result = run(make_panel(seed=51), [DifferenceInDifferences()]) + assert result.target_power is None + assert np.isnan(result.mde["DifferenceInDifferences"]) + + +class TestConfigurations: + @pytest.mark.parametrize("estimator_class", [DifferenceInDifferences, TwoWayFixedEffects]) + @pytest.mark.parametrize("lag_cutoff", [0, 1]) + @pytest.mark.parametrize("resample_units", [True, False]) + def test_conley_candidates_are_refused(self, estimator_class, lag_cutoff, resample_units): + """Their Conley calendar would be the 0/1 post indicator, not the period.""" + panel = make_panel(n_units=20, n_periods=8, seed=52) + rng = np.random.default_rng(0) + coords = pd.DataFrame( + { + "unit": np.arange(20), + "lat": rng.uniform(30, 45, size=20), + "lon": rng.uniform(-120, -80, size=20), + } + ) + panel = panel.merge(coords, on="unit") + estimator = estimator_class( + vcov_type="conley", + conley_coords=("lat", "lon"), + conley_cutoff_km=500.0, + conley_lag_cutoff=lag_cutoff, + ) + with pytest.raises(ValueError, match="vcov_type='conley'"): + run(panel, [estimator], resample_units=resample_units) + + def test_fit_keyword_reaches_every_estimator(self): + panel = make_panel(seed=53) + panel["x"] = np.random.default_rng(1).normal(size=len(panel)) + result = run( + panel, + [DifferenceInDifferences(), TwoWayFixedEffects()], + estimator_kwargs={"covariates": ["x"]}, + n_simulations=5, + ) + assert result.estimator_kwargs == {"covariates": ["x"]} + for cells in result.results.values(): + assert cells[0].n_simulations == 5 diff --git a/tests/test_diagnostic_marker.py b/tests/test_diagnostic_marker.py index df758e1a5..d96a363a0 100644 --- a/tests/test_diagnostic_marker.py +++ b/tests/test_diagnostic_marker.py @@ -41,6 +41,7 @@ "SimulationPowerResults", "SimulationMDEResults", "SimulationSampleSizeResults", + "DesignDiagnosisResults", "PlaceboTestResults", "QUGTestResults", "StuteTestResults", diff --git a/tests/test_methodology_design.py b/tests/test_methodology_design.py new file mode 100644 index 000000000..699e3ac8b --- /dev/null +++ b/tests/test_methodology_design.py @@ -0,0 +1,225 @@ +"""Methodology tests for diff_diff.design (diagnose_design). + +``docs/methodology/REGISTRY.md`` ``## DesignDiagnosis`` is the contract. The +source papers evaluate their procedures on CPS data that is not reproduced +here; these tests reproduce the *shape* of their findings on simulated panels +and pin the library choices the registry documents. + +Sources: Bertrand, Duflo & Mullainathan (2004); Mizushima & Powell (2025); +Blair, Cooper, Coppock & Humphreys (2019). Paper reviews: +``docs/methodology/papers/``. +""" + +import warnings + +import numpy as np +import pandas as pd +import pytest +from scipy import stats + +from diff_diff import ( + CallawaySantAnna, + DifferenceInDifferences, + ImputationDiD, + SunAbraham, + TwoWayFixedEffects, + diagnose_design, +) + + +def ar1_panel(n_units, n_periods, rho, seed, unit_sd=1.0): + """Unit effects plus a stationary AR(1) error, no treatment anywhere.""" + rng = np.random.default_rng(seed) + errors = np.empty((n_units, n_periods)) + state = rng.normal(size=n_units) + for t in range(n_periods): + state = rho * state + np.sqrt(1.0 - rho**2) * rng.normal(size=n_units) + errors[:, t] = state + y = rng.normal(scale=unit_sd, size=(n_units, 1)) + errors + return pd.DataFrame( + { + "unit": np.repeat(np.arange(n_units), n_periods), + "period": np.tile(np.arange(1, n_periods + 1), n_units), + "y": y.ravel(), + } + ) + + +def diagnose(panel, estimators, **kwargs): + kwargs.setdefault("seed", 7) + kwargs.setdefault("progress", False) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return diagnose_design(panel, "y", "unit", "period", estimators, **kwargs) + + +@pytest.fixture(scope="module") +def serial_correlation_result(): + """50 units x 21 periods, rho = 0.8: the Bertrand et al. AR(1) design.""" + panel = ar1_panel(50, 21, 0.8, seed=1) + return diagnose( + panel, + { + "twfe_classical": TwoWayFixedEffects(vcov_type="classical"), + "twfe_clustered": TwoWayFixedEffects(), + }, + cohort_periods=[11], + treatment_fraction=0.5, + effect_sizes=[0.25, 0.5, 1.0], + n_simulations=300, + ) + + +class TestSerialCorrelationOverRejection: + """Bertrand, Duflo & Mullainathan (2004), Table II Panel B, in shape. + + With serially correlated outcomes and an absorbing treatment, standard + errors that ignore within-unit correlation reject a true null far above + the nominal level; clustering on the unit restores it. + """ + + def test_unclustered_standard_errors_over_reject(self, serial_correlation_result): + null = serial_correlation_result.results["twfe_classical"][0] + assert null.true_effect == 0.0 + assert null.rejection_rate > 0.25 + assert serial_correlation_result.size_controlled["twfe_classical"] is False + + def test_unit_clustered_standard_errors_are_near_nominal(self, serial_correlation_result): + null = serial_correlation_result.results["twfe_clustered"][0] + assert null.rejection_rate < 0.12 + assert serial_correlation_result.size_controlled["twfe_clustered"] is True + + def test_both_variants_share_point_estimates(self, serial_correlation_result): + """Same estimator, same placebo draws: only the inference differs.""" + cells = serial_correlation_result.results + for i in range(4): + assert cells["twfe_classical"][i].mean_estimate == pytest.approx( + cells["twfe_clustered"][i].mean_estimate, abs=1e-10 + ) + + def test_coverage_mirrors_size_under_the_null(self, serial_correlation_result): + for cells in serial_correlation_result.results.values(): + null = cells[0] + assert null.coverage == pytest.approx(1.0 - null.rejection_rate, abs=1e-12) + + +class TestEffectInjection: + """Bertrand et al. (2004), pp.259, 261: add the effect to treated observations.""" + + def test_power_rises_with_the_injected_effect(self, serial_correlation_result): + cells = serial_correlation_result.results["twfe_clustered"] + powers = [cell.power for cell in cells] + assert powers[0] < powers[1] < powers[2] <= powers[3] + assert powers[3] > 0.8 + + def test_estimates_are_unbiased_for_the_injected_effect(self, serial_correlation_result): + cells = serial_correlation_result.results["twfe_clustered"] + for cell in cells: + # Bias is the same at every effect: the placebo draws are shared. + assert cell.bias == pytest.approx(cells[0].bias, abs=1e-10) + assert abs(cell.bias) < 4.0 * cell.std_estimate / np.sqrt(cell.n_simulations) + + def test_over_rejecting_test_shows_inflated_power(self, serial_correlation_result): + """The raw rejection rate of an over-sized test is not size-adjusted.""" + cells = serial_correlation_result.results + assert cells["twfe_classical"][1].power > cells["twfe_clustered"][1].power + + +class TestFewTreatedUnits: + """Mizushima & Powell (2025), in shape: asymptotic inference over-rejects + when very few units are treated, and is near nominal when many are.""" + + estimators = staticmethod(lambda: [CallawaySantAnna(), ImputationDiD(), SunAbraham()]) + + def test_two_treated_units_over_reject(self): + result = diagnose( + ar1_panel(40, 12, 0.5, seed=2), + self.estimators(), + cohort_periods=[8], + n_treated=2, + n_simulations=300, + ) + for label, cells in result.results.items(): + assert cells[0].rejection_rate > 0.15, label + assert result.size_controlled[label] is False, label + + def test_twenty_treated_units_are_near_nominal(self): + result = diagnose( + ar1_panel(40, 12, 0.5, seed=2), + self.estimators(), + cohort_periods=[8], + n_treated=20, + n_simulations=300, + ) + for label, cells in result.results.items(): + assert cells[0].rejection_rate < 0.12, label + + +class TestDocumentedChoices: + """Library choices recorded as Notes in REGISTRY ``## DesignDiagnosis``.""" + + def test_rmse_is_the_existing_sample_sd_form(self, serial_correlation_result): + """Not Blair et al.'s root mean squared error: the variance term uses ddof=1.""" + cell = serial_correlation_result.results["twfe_clustered"][2] + estimates = np.array([r["estimate"] for r in cell.simulation_results]) + bias = estimates.mean() - cell.true_effect + assert cell.rmse == pytest.approx(np.sqrt(bias**2 + estimates.std(ddof=1) ** 2)) + root_mse = np.sqrt(np.mean((estimates - cell.true_effect) ** 2)) + n = len(estimates) + assert cell.rmse**2 - root_mse**2 == pytest.approx(estimates.var(ddof=1) / n) + + def test_mde_is_close_to_the_normal_multiplier(self): + """For a correctly sized test the MDE is about (z_{1-a/2} + z_power) standard errors.""" + panel = ar1_panel(60, 10, 0.0, seed=3) + result = diagnose( + panel, + {"did": DifferenceInDifferences(cluster="unit")}, + cohort_periods=[6], + treatment_fraction=0.5, + n_simulations=300, + power=0.8, + ) + assert result.size_controlled["did"] is True + spread = result.results["did"][0].std_estimate + multiplier = stats.norm.ppf(0.975) + stats.norm.ppf(0.8) + assert result.mde["did"] == pytest.approx(multiplier * spread, rel=0.25) + assert result.mde_results["did"].power_at_mde >= 0.8 + + def test_no_mde_for_an_estimator_that_fails_the_size_check(self): + result = diagnose( + ar1_panel(50, 21, 0.8, seed=1), + {"twfe_classical": TwoWayFixedEffects(vcov_type="classical")}, + cohort_periods=[11], + treatment_fraction=0.5, + n_simulations=200, + power=0.8, + ) + assert result.size_controlled["twfe_classical"] is False + assert np.isnan(result.mde["twfe_classical"]) + assert result.mde_results == {} + + def test_fixed_panel_and_resampled_panel_both_run(self): + """``resample_units=False`` reassigns treatment on the panel as observed.""" + panel = ar1_panel(30, 10, 0.3, seed=4) + kwargs = dict(cohort_periods=[6], treatment_fraction=0.5, n_simulations=100) + estimator = {"did": DifferenceInDifferences(cluster="unit")} + resampled = diagnose(panel, estimator, **kwargs) + fixed = diagnose(panel, estimator, resample_units=False, **kwargs) + assert resampled.resample_units is True and fixed.resample_units is False + assert fixed.results["did"][0].n_simulations == 100 + # Different designs, hence different draws. + assert fixed.results["did"][0].mean_estimate != resampled.results["did"][0].mean_estimate + + def test_staggered_declaration_draws_each_unit_from_the_declared_periods(self): + panel = ar1_panel(40, 12, 0.3, seed=5) + result = diagnose( + panel, + [CallawaySantAnna(), ImputationDiD()], + cohort_periods=[6, 8, 10], + n_treated=18, + effect_sizes=[1.0], + n_simulations=100, + ) + for label, cells in result.results.items(): + assert cells[1].mean_estimate == pytest.approx(1.0, abs=0.15), label + assert cells[1].power > cells[0].power, label diff --git a/tests/test_naming_guard.py b/tests/test_naming_guard.py index 3eb08eea6..d0dc1826d 100644 --- a/tests/test_naming_guard.py +++ b/tests/test_naming_guard.py @@ -513,6 +513,9 @@ def _build_rowed_index(): "CallawaySantAnna.fit[time]", "ChaisemartinDHaultfoeuille.fit[time]", "DMLDiD.fit[time]", + # diagnose_design takes the calendar period column, and its results + # container echoes that column name. + "DesignDiagnosisResults.time", "DurationDiD.fit[time]", "ChangesInChanges.fit[time]", "ContinuousDiD.fit[time]", @@ -537,6 +540,7 @@ def _build_rowed_index(): "agent_workflow[time]", "check_parallel_trends[time]", "check_parallel_trends_robust[time]", + "diagnose_design[time]", "did_had_pretest_workflow[time]", "equivalence_test_trends[time]", "joint_homogeneity_test[time]",