diff --git a/DEFERRED.md b/DEFERRED.md index 111f8da3..9fa72b86 100644 --- a/DEFERRED.md +++ b/DEFERRED.md @@ -82,7 +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 | +| `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::_check_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 b5c12c67..e35c561b 100644 --- a/METHODOLOGY_REVIEW.md +++ b/METHODOLOGY_REVIEW.md @@ -83,7 +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 | +| DesignDiagnosis | `design.py` | No R parity target (`DeclareDesign` diagnoses simulated designs); internal exact enumeration | **Complete** | 2026-11-23 | ### Cross-Cutting Inference Features @@ -1318,7 +1318,7 @@ CI and extending covariate-adjusted R parity are tracked follow-ups in `DEFERRED | 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 | +| Last Review | 2026-11-23 | **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`. @@ -1328,15 +1328,21 @@ CI and extending covariate-adjusted R parity are tracked follow-ups in `DEFERRED - 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). +- Held-out periods are not read by the comparison, including for an integer outcome that pandas stores as float - `tests/test_design.py::TestHoldout`. +- The lock run equals a plain run of the chosen estimator on the full panel at the derived seed, and fits only that estimator - `TestLock`; on the AR(1) panel its size for unit-clustered TWFE is near nominal - `tests/test_methodology_design.py::TestHeldOutRun`. +- The design lock round-trips through JSON, detects edits, and rebuilds each of the eight estimators - `TestLockSerialization`, `TestToEstimator`. +- Reconciliation reports each deviating item (class, parameter, fit keyword, column name, `alpha`, diagnosed data, unit count, balance, treated count, cohort count, post-window length) - `TestReconcile`. + **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. +- Held-out periods, their default count, the derived lock seed, the lock file hash and the binary `pre-specified` / `deviates` label are library choices; only the idea of reconciling the planned and the realized design is from Blair et al. (p.852). `reconcile` is a declaration check: fitted results do not record their configuration. The reduction in selection inflation from the held-out rerun is not validated numerically. - 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). +**Tests:** `tests/test_design.py` (behaviour, guards, failure policy, results contract, held-out periods, lock, reconcile) + `tests/test_methodology_design.py` (paper-shaped findings and documented choices). --- diff --git a/README.md b/README.md index a4911b3c..658c0a94 100644 --- a/README.md +++ b/README.md @@ -134,7 +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 +- [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; lock the chosen design and reconcile the analysis against it - [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 9b025b71..d24c6983 100644 --- a/TODO.md +++ b/TODO.md @@ -87,7 +87,8 @@ 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 | +| Design-stage tutorial ("Study Design" group of `docs/tutorials/index.rst`): the full workflow - `diagnose_design`, `lock`, then `DesignLock.reconcile` after the analysis - on one worked panel. `docs/api/design.rst` and `llms-full.txt` carry 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 | +| Wire the design-lock label into the reports: `DiagnosticReport` / `BusinessReport` accept a `DesignReconciliationResults` (or a `DesignLock` to reconcile) and state whether the result is `pre-specified` or `deviates`, with the deviating items; schema and `REPORTING.md` updates. Until then the label is available only from `DesignLock.reconcile` itself. Ships before the release that carries `diagnose_design`. | `diagnostic_report.py`, `business_report.py`, `design.py` | design lock PR | 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/20261123-design-lock.md b/changelog.d/20261123-design-lock.md new file mode 100644 index 00000000..b0806b13 --- /dev/null +++ b/changelog.d/20261123-design-lock.md @@ -0,0 +1,35 @@ +### Added +- **Design lock: carry the pre-specified estimator from `diagnose_design` into + the analysis.** `DesignDiagnosisResults.lock(label, data=)` records one + estimator as the choice made before the analysis and returns a `DesignLock`; + `DesignLock.reconcile(estimator, outcome=, unit=, time=, ...)` later checks + the analysis that was run against it and labels it `pre-specified` or + `deviates`. + - Held-out periods: when more than one estimator is compared, + `diagnose_design` now leaves the last periods of the panel out of the + comparison (new `n_holdout=`; default half of the periods at or after the + latest adoption period, `n_holdout=0` compares on the whole panel). + `lock()` reruns only the chosen estimator with those periods included, on + fresh placebo draws, so its reported power is not taken from the runs used + to choose it. + - `DesignLock` is plain JSON data (`to_json()`, `DesignLock.from_json()`, + `DESIGN_LOCK_SCHEMA_VERSION`) holding the chosen estimator and its + configuration, the declared design, a fingerprint of the panel, every + estimator that was compared and the chosen estimator's diagnosands. + `to_estimator()` builds the estimator exactly as locked. + - `reconcile` reports one check per item (estimator class, each constructor + parameter, `fit()` keywords, column names, and with `data=` the fingerprint + of the diagnosed periods, unit count, panel balance, treated count, cohort + count and post-window lengths) in a `DesignReconciliationResults`. It + compares what the analyst declares with the lock; `pre-specified` covers + the listed checks only and a deviation is not graded. + - The reconciliation idea follows Blair et al. (2019); held-out periods, the + lock format and the label are library choices documented as Notes in + `docs/methodology/REGISTRY.md` `## DesignDiagnosis`. + +### Changed +- **`diagnose_design` data fingerprint encodes numbers by value.** + `data_sha256` no longer distinguishes `1` from `1.0`, so the digest of a set + of rows does not change when pandas stores an integer column as float because + some other row is missing. `diagnose_design` has not been released, so no + stored fingerprint is affected. diff --git a/diff_diff/__init__.py b/diff_diff/__init__.py index 18d80146..19b05375 100644 --- a/diff_diff/__init__.py +++ b/diff_diff/__init__.py @@ -75,7 +75,13 @@ load_prop99, load_walmart, ) -from diff_diff.design import DesignDiagnosisResults, diagnose_design +from diff_diff.design import ( + DESIGN_LOCK_SCHEMA_VERSION, + DesignDiagnosisResults, + DesignLock, + DesignReconciliationResults, + diagnose_design, +) from diff_diff.diagnostic_report import ( DIAGNOSTIC_REPORT_SCHEMA_VERSION, DiagnosticReport, @@ -495,6 +501,9 @@ "simulate_sample_size", # Design diagnosis "DesignDiagnosisResults", + "DesignLock", + "DesignReconciliationResults", + "DESIGN_LOCK_SCHEMA_VERSION", "diagnose_design", # Pre-trends power analysis "PreTrendsPower", diff --git a/diff_diff/design.py b/diff_diff/design.py index 2c82e162..535512ff 100644 --- a/diff_diff/design.py +++ b/diff_diff/design.py @@ -13,6 +13,12 @@ real treatment column is supplied, every period from the earliest real adoption onward is dropped before anything else happens. +When several estimators are compared, the last periods are held out of the +comparison. :meth:`DesignDiagnosisResults.lock` then reruns the one chosen +estimator with those periods included and records the choice as a +:class:`DesignLock`; :meth:`DesignLock.reconcile` checks the analysis that was +finally run against it. + References ---------- Bertrand, M., Duflo, E., & Mullainathan, S. (2004). "How Much Should We Trust @@ -31,12 +37,14 @@ Difference-in-Differences Methods." SSRN working paper 5221387. """ +import copy import dataclasses import hashlib import inspect import json +import math import warnings -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import date, datetime from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union @@ -51,7 +59,15 @@ ) from diff_diff.results_base import Diagnostic -__all__ = ["diagnose_design", "DesignDiagnosisResults"] +__all__ = [ + "diagnose_design", + "DesignDiagnosisResults", + "DesignLock", + "DesignReconciliationResults", + "DESIGN_LOCK_SCHEMA_VERSION", +] + +DESIGN_LOCK_SCHEMA_VERSION = "1.0" # Estimators that need one common post indicator (common timing only). _COMMON_TIMING_ESTIMATORS = ("DifferenceInDifferences", "TwoWayFixedEffects") @@ -155,13 +171,19 @@ class DesignDiagnosisResults(Diagnostic): 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. + Shape of the panel actually used (without held-out periods). n_dropped : int - Rows removed by truncating at the earliest real adoption. + Rows removed by truncating at the earliest real adoption. Held-out + rows are not counted here. data_sha256 : str Fingerprint of the panel actually used. data_columns : list of str Columns the fingerprint covers. + n_holdout : int + Trailing periods of the untreated panel that were held out of the + comparison and not read. :meth:`lock` uses them. + time_periods : list + Period values of the panel actually used. """ results: Dict[str, List[SimulationPowerResults]] @@ -189,6 +211,13 @@ class DesignDiagnosisResults(Diagnostic): n_dropped: int data_sha256: str data_columns: List[str] + n_holdout: int + time_periods: List[Any] + # The configuration as diagnosed (lock() refuses one that was changed + # afterwards) and the labels a held-out run was made for. + _params: Dict[str, Dict[str, Any]] = field(default_factory=dict, repr=False, compare=False) + _fit_keywords: Optional[Dict[str, Any]] = field(default=None, repr=False, compare=False) + _holdout_labels: List[str] = field(default_factory=list, repr=False, compare=False) def __repr__(self) -> str: """Concise string representation.""" @@ -211,13 +240,15 @@ def to_dataframe(self) -> pd.DataFrame: """ 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) + rows.extend( + _records( + label, + cells, + self.size_controlled[label], + self.n_nan_inference[label], + self.mde[label], + ) + ) return pd.DataFrame(rows) def to_dict(self) -> Dict[str, Any]: @@ -257,6 +288,8 @@ def to_dict(self) -> Dict[str, Any]: "n_dropped": self.n_dropped, "data_sha256": self.data_sha256, "data_columns": list(self.data_columns), + "n_holdout": self.n_holdout, + "time_periods": list(self.time_periods), "size_controlled": dict(self.size_controlled), "mde": dict(self.mde), "results": self.to_dataframe().to_dict("records"), @@ -279,6 +312,7 @@ def summary(self) -> str: if self.first_treat is not None else "declared by caller (no first_treat column given; not verified)" ) + held_out = f"{self.n_holdout} (not read; used by lock())" if self.n_holdout else "0 (none)" lines = [ "=" * width, "Design Diagnosis (placebo assignments on the supplied panel)".center(width), @@ -288,6 +322,7 @@ def summary(self) -> str: f"{'Untreated status:':<32} {untreated}", f"{'Placebo-treated units:':<32} {self.n_treated}", f"{'Adoption periods (' + timing + '):':<32} {list(self.cohort_periods)}", + f"{'Held-out periods:':<32} {held_out}", f"{'Units resampled:':<32} {self.resample_units}", f"{'Significance level (alpha):':<32} {self.alpha:.3f}", f"{'Seed:':<32} {self.seed}", @@ -336,6 +371,68 @@ def print_summary(self) -> None: """Print the summary to stdout.""" print(self.summary()) + def lock( + self, + label: Optional[str] = None, + data: Optional[pd.DataFrame] = None, + progress: bool = True, + ) -> "DesignLock": + """ + Record one estimator as the pre-specified choice. + + When periods were held out of the comparison (``n_holdout > 0``), + the chosen estimator alone is rerun on the panel with those periods + included, with fresh placebo draws, and the lock reports that run. + Its numbers were not used to compare estimators, so they are not + inflated by the choice. + + Parameters + ---------- + label : str, optional + Key of the chosen entry of ``estimators``. May be omitted only + when one estimator was diagnosed. + data : pd.DataFrame, optional + The panel that was passed to :func:`diagnose_design`. Required + when ``n_holdout > 0`` (the results do not keep the panel). Its + fingerprint must match ``data_sha256`` on the periods that were + compared. + progress : bool, default=True + Print one line per effect of the held-out run. + + Returns + ------- + DesignLock + The pre-specified design. Write ``lock.to_json()`` to a file to + keep it; :meth:`DesignLock.reconcile` checks an analysis against + it. + + Notes + ----- + The held-out run uses a seed derived from the recorded one, so it + cannot be re-rolled. Running it for a second label emits a warning: + the two runs would amount to a second comparison. + """ + return _lock(self, label, data, progress) + + +def _records( + label: str, + cells: Sequence[Any], + size_controlled: bool, + n_nan_inference: Sequence[int], + mde: float, +) -> List[Dict[str, Any]]: + """One row per effect size for one estimator (the ``to_dataframe`` rows).""" + rows: List[Dict[str, Any]] = [] + for i, cell in enumerate(cells): + row: Dict[str, Any] = {"label": label} + row.update(cell.to_dict()) + row["size_controlled"] = size_controlled + row["n_nan_inference"] = n_nan_inference[i] + row["mde"] = mde + rows.append(row) + return rows + def _fmt_rate(value: float) -> str: return f"{value:.1%}" if np.isfinite(value) else "-" @@ -370,7 +467,7 @@ def __exit__(self, *exc_info: Any) -> None: self._ctx.__exit__(*exc_info) -def _reemit(label: str, records: Sequence[warnings.WarningMessage]) -> None: +def _reemit(label: str, records: Sequence[warnings.WarningMessage], stacklevel: int = 3) -> None: """Re-emit captured warnings once per (category, source), labelled. Estimator warnings embed per-replicate values, so they are aggregated by @@ -384,7 +481,7 @@ def _reemit(label: str, records: Sequence[warnings.WarningMessage]) -> None: 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) + warnings.warn(f"[{label}] {message}{suffix}", category, stacklevel=stacklevel) # --------------------------------------------------------------------------- @@ -492,7 +589,13 @@ def _is_missing(value: Any) -> bool: def _encode_cell(value: Any) -> List[str]: - """Type-tagged text for one cell, so distinct values never encode alike.""" + """Tagged text for one cell, so distinct values never encode alike. + + Numbers are encoded by value, not by storage type: ``1`` and ``1.0`` are + the same cell. pandas stores an integer column as float as soon as any + row is missing, so a type tag would make the digest of some rows depend + on rows outside them. + """ if _is_missing(value): return ["n", ""] if isinstance(value, (bool, np.bool_)): @@ -500,7 +603,10 @@ def _encode_cell(value: Any) -> List[str]: if isinstance(value, (int, np.integer)): return ["i", str(int(value))] if isinstance(value, (float, np.floating)): - return ["f", format(float(value), ".17g")] + number = float(value) + if number.is_integer(): + return ["i", str(int(number))] + return ["f", format(number, ".17g")] if isinstance(value, np.datetime64): return ["t", pd.Timestamp(value).isoformat()] if isinstance(value, (datetime, date)): @@ -538,6 +644,85 @@ def _data_fingerprint(panel: pd.DataFrame, unit: str, time: str) -> Tuple[str, L return digest.hexdigest(), columns +# --------------------------------------------------------------------------- +# JSON values of a design lock +# --------------------------------------------------------------------------- + + +def _json_value(value: Any, path: str, nonfinite: str = "raise") -> Any: + """``value`` as plain JSON data, or ``ValueError`` naming ``path``. + + Strict on purpose: a lock must rebuild the estimator exactly, so anything + that is not a JSON scalar, list or string-keyed mapping is refused instead + of being passed through. ``nonfinite="none"`` maps NaN and infinities to + ``None`` (result records); ``"raise"`` refuses them (configuration). + """ + if value is None or isinstance(value, str): + return value + if isinstance(value, (bool, np.bool_)): + return bool(value) + if isinstance(value, (int, np.integer)): + return int(value) + if isinstance(value, (float, np.floating)): + number = float(value) + if math.isfinite(number): + return number + if nonfinite == "none": + return None + raise ValueError(f"{path} is a non-finite number ({number!r})") + if isinstance(value, np.ndarray): + value = value.tolist() + if isinstance(value, (list, tuple)): + return [_json_value(item, f"{path}[{i}]", nonfinite) for i, item in enumerate(value)] + if isinstance(value, Mapping): + converted: Dict[str, Any] = {} + for key, item in value.items(): + if not isinstance(key, str): + raise ValueError(f"{path} has a key that is not a string ({key!r})") + converted[key] = _json_value(item, f"{path}.{key}", nonfinite) + return converted + raise ValueError(f"{path} holds a {type(value).__name__}, which cannot be written as JSON") + + +def _snapshot(values: Mapping[str, Any]) -> Dict[str, Any]: + """Each value as JSON data, or a marker when it has no JSON form. + + Taken at diagnosis time and compared again in ``lock()``: the stored + estimators and ``fit()`` keywords are live objects, and a lock must record + the configuration that produced the numbers it reports. + """ + snapshot: Dict[str, Any] = {} + for name, value in values.items(): + try: + snapshot[str(name)] = _json_value(value, str(name)) + except ValueError: + snapshot[str(name)] = ["", repr(value)] + return snapshot + + +def _unlockable(estimator: Any, estimator_kwargs: Dict[str, Any]) -> List[str]: + """Why ``lock()`` would refuse this configuration (empty when it would not).""" + problems: List[str] = [] + for group, values in ( + ("params", estimator.get_params()), + ("estimator_kwargs", estimator_kwargs), + ): + for name, value in values.items(): + try: + _json_value(value, f"{group}.{name}") + except ValueError as exc: + problems.append(str(exc)) + return problems + + +def _lock_digest(payload: Mapping[str, Any]) -> str: + """SHA-256 of the canonical JSON of a lock's fields (without ``sha256``).""" + text = json.dumps( + payload, sort_keys=True, ensure_ascii=True, separators=(",", ":"), allow_nan=False + ) + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + # --------------------------------------------------------------------------- # Validation # --------------------------------------------------------------------------- @@ -648,14 +833,18 @@ def _validate_estimator_kwargs(resolved: Dict[str, Any], estimator_kwargs: Dict[ ) -def _prepare_panel( +def _untreated_rows( 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.""" + """Drop every row from the earliest real adoption on. + + Reads only the ``unit``, ``time`` and ``first_treat`` columns, so the + caller can remove held-out periods before any outcome is looked at. + """ 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 []) @@ -707,6 +896,11 @@ def _prepare_panel( if len(panel) == 0: raise ValueError("No untreated rows remain after truncation.") + return panel, n_dropped + + +def _check_panel(panel: pd.DataFrame, outcome: str, unit: str, time: str) -> pd.DataFrame: + """Validate outcomes and balance; return the panel sorted by (unit, time).""" if not pd.api.types.is_numeric_dtype(panel[outcome]) or pd.api.types.is_bool_dtype( panel[outcome] ): @@ -723,8 +917,52 @@ def _prepare_panel( 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 + return panel.sort_values([unit, time], kind="mergesort").reset_index(drop=True) + + +def _resolve_n_holdout( + n_holdout: Optional[int], n_estimators: int, periods: np.ndarray, declared: List[Any] +) -> int: + """How many trailing periods the comparison leaves unread.""" + n_post = int(np.sum(periods >= max(declared))) + if n_holdout is None: + if n_estimators == 1: + return 0 + count = n_post // 2 + if count == 0: + raise ValueError( + f"Several estimators are compared, so periods are held out of the " + f"comparison by default, but the latest adoption period " + f"{max(declared)!r} is the final period of the untreated panel and " + f"nothing can be held out. Declare an earlier adoption period, or " + f"pass n_holdout=0 to compare on the whole panel." + ) + return count + if isinstance(n_holdout, bool) or not isinstance(n_holdout, (int, np.integer)): + raise ValueError(f"n_holdout must be a non-negative integer, got {n_holdout!r}.") + count = int(n_holdout) + if not 0 <= count <= n_post - 1: + raise ValueError( + f"n_holdout={count} is out of range: the latest adoption period " + f"{max(declared)!r} has {n_post} period(s) at or after it, and at least " + f"one must stay in the comparison (0 <= n_holdout <= {n_post - 1})." + ) + return count + + +def _select_columns(frame: pd.DataFrame, data_columns: Sequence[str]) -> pd.DataFrame: + """The columns a fingerprint covers, found by their names as strings.""" + by_name = {str(c): c for c in frame.columns} + if len(by_name) != len(frame.columns): + # Otherwise a diagnosed column could be swapped for a same-named one. + raise ValueError( + "data has column labels that are equal as strings (for example 1 and " + "'1'), so the diagnosed columns cannot be identified. Rename them." + ) + missing = [name for name in data_columns if name not in by_name] + if missing: + raise ValueError(f"Column(s) {missing} of the diagnosed panel are not in data.") + return frame[[by_name[name] for name in data_columns]] def _validate_cohort_periods(cohort_periods: Any, periods: np.ndarray) -> List[Any]: @@ -1071,6 +1309,86 @@ def _run_mde( return found, float(found.mde) +def _run_estimator( + caller: str, + label: str, + estimator: Any, + effects: Sequence[float], + data_generator: Callable[..., pd.DataFrame], + fit_kwargs: Dict[str, Any], + n_units: int, + n_periods: int, + n_simulations: int, + alpha: float, + power: Optional[float], + seed: int, + progress: bool, + stacklevel: int = 4, +) -> Tuple[List[Any], List[int], bool, Optional[Any], float]: + """Every effect size, the size check and the MDE search for one estimator. + + Returns the cells, the non-finite-inference counts, whether the size + check passed, the MDE search result (``None`` when it did not run) and + the reported MDE (NaN when not reported). Warnings are re-emitted with + the label. + """ + cells: List[Any] = [] + nan_counts: List[int] = [] + null_adapter: Optional[_PlaceboFit] = None + for effect in effects: + with _WarningCapture() as capture: + cell, adapter = _run_cell( + estimator, + effect, + data_generator, + fit_kwargs, + n_units, + n_periods, + n_simulations, + alpha, + seed, + ) + _reemit(label, capture.records, stacklevel) + cells.append(cell) + nan_counts.append(adapter.n_nan) + if null_adapter is None: + null_adapter = adapter + if progress: + print( + f" {caller}: {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] + size_ok = _size_controlled( + float(null_cell.rejection_rate), + int(null_cell.n_simulations), + null_adapter.n_lost, + alpha, + ) + found: Optional[Any] = None + value = float("nan") + if power is not None and size_ok: + with _WarningCapture() as capture: + found, value = _run_mde( + estimator, + null_cell, + data_generator, + fit_kwargs, + n_units, + n_periods, + n_simulations, + alpha, + power, + seed, + ) + _reemit(label, capture.records, stacklevel) + if progress: + print(f" {caller}: {label}, MDE search: {_fmt_num(value)}") + return cells, nan_counts, size_ok, found, value + + # --------------------------------------------------------------------------- # Public entry point # --------------------------------------------------------------------------- @@ -1094,6 +1412,7 @@ def diagnose_design( estimator_kwargs: Optional[Dict[str, Any]] = None, seed: Optional[int] = None, progress: bool = True, + n_holdout: Optional[int] = None, ) -> DesignDiagnosisResults: """ Diagnose a planned DiD design on your own untreated panel. @@ -1161,6 +1480,14 @@ def diagnose_design( Seed of the placebo draws. ``None`` draws one and records it. progress : bool, default=True Print one line per estimator and effect. + n_holdout : int, optional + Trailing periods of the untreated panel to hold out of the comparison. + They are not read here; :meth:`DesignDiagnosisResults.lock` reruns the + chosen estimator with them included, so its reported power is not + taken from the runs that were used to choose it. ``None`` holds out + nothing for a single estimator and, for several, half of the periods + at or after the latest adoption period (rounded down); if that is + zero the call raises. Pass ``0`` to compare on the whole panel. Returns ------- @@ -1201,19 +1528,30 @@ def diagnose_design( raise ValueError(f"power must satisfy alpha < power < 1, got {power}.") resolved = _resolve_estimators(estimators) - fit_extras = dict(estimator_kwargs or {}) + # A private copy: the caller's dict and the lists in it stay theirs. + fit_extras = copy.deepcopy(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: + untreated, n_dropped = _untreated_rows(data, outcome, unit, time, first_treat) + all_periods = np.unique(_period_values(untreated[time])) + if len(all_periods) < _MIN_PRE_PERIODS + 1: raise ValueError( - f"Too few periods: the untreated panel has {n_periods} period(s); at " + f"Too few periods: the untreated panel has {len(all_periods)} period(s); at " f"least {_MIN_PRE_PERIODS + 1} are needed." ) - declared = _validate_cohort_periods(cohort_periods, periods) + declared = _validate_cohort_periods(cohort_periods, all_periods) + held_out = _resolve_n_holdout(n_holdout, len(resolved), all_periods, declared) + if held_out: + # Held-out rows are removed by period value alone, before any outcome + # is validated, hashed or fitted. + periods = all_periods[:-held_out] + keep = np.isin(_period_values(untreated[time]), periods) + untreated = untreated.loc[keep] + else: + periods = all_periods + panel = _check_panel(untreated, outcome, unit, time) + n_periods = len(periods) + n_units = panel[unit].nunique() count = _resolve_n_treated(treatment_fraction, n_treated, n_units) _validate_estimators( resolved, @@ -1238,6 +1576,14 @@ def diagnose_design( UserWarning, stacklevel=2, ) + problems = _unlockable(est, fit_extras) + if problems: + warnings.warn( + f"[{label}] cannot be recorded in a design lock: {'; '.join(problems)}. " + f"The diagnosis runs, but lock() will refuse this estimator.", + UserWarning, + stacklevel=2, + ) data_sha256, data_columns = _data_fingerprint(panel, unit, time) data_generator = _make_placebo_generator( @@ -1259,64 +1605,27 @@ def diagnose_design( 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, + cells, nan_counts, size_ok, found, value = _run_estimator( + "diagnose_design", + label, + est, + effects, + data_generator, + fit_kwargs[label], + n_units, + n_periods, + int(n_simulations), alpha, + power, + resolved_seed, + progress, ) - 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)}") + results[label] = cells + n_nan_inference[label] = nan_counts + size_controlled[label] = size_ok + if found is not None: + mde_results[label] = found + mde[label] = value return DesignDiagnosisResults( results=results, @@ -1344,4 +1653,871 @@ def diagnose_design( n_dropped=n_dropped, data_sha256=data_sha256, data_columns=data_columns, + n_holdout=held_out, + time_periods=periods.tolist(), + _params={label: _snapshot(est.get_params()) for label, est in resolved.items()}, + _fit_keywords=_snapshot(fit_extras), ) + + +# --------------------------------------------------------------------------- +# Design lock +# --------------------------------------------------------------------------- + +_ABSENT = "" +_MATCH = "match" +_DEVIATES = "deviates" +_NOT_CHECKED = "not checked" +_PRE_SPECIFIED = "pre-specified" +# Lock fields whose NaN entries (a cell that could not be scored, an MDE that +# was not reported) are stored as None. +_RECORD_FIELDS = ("comparison_results", "holdout_results", "mde") + + +def _lock( + diagnosis: DesignDiagnosisResults, + label: Optional[str], + data: Optional[pd.DataFrame], + progress: bool, +) -> "DesignLock": + """Implementation of :meth:`DesignDiagnosisResults.lock`.""" + labels = list(diagnosis.estimators) + if label is None: + if len(labels) != 1: + raise ValueError( + f"Several estimators were diagnosed; pass the label of the one to " + f"lock. Labels: {labels}." + ) + label = labels[0] + if label not in diagnosis.estimators: + raise ValueError(f"Unknown label {label!r}. Labels: {labels}.") + chosen = diagnosis.estimators[label] + + snapshot = diagnosis._params.get(label) + if snapshot is not None and _snapshot(chosen.get_params()) != snapshot: + raise ValueError( + f"The estimator stored under '{label}' was changed after the diagnosis " + f"(its parameters no longer match the ones that were diagnosed). Run " + f"diagnose_design again with the configuration you want to lock." + ) + if ( + diagnosis._fit_keywords is not None + and _snapshot(diagnosis.estimator_kwargs) != diagnosis._fit_keywords + ): + raise ValueError( + "estimator_kwargs was changed after the diagnosis (it no longer matches " + "the fit() keywords that were diagnosed). Run diagnose_design again with " + "the configuration you want to lock." + ) + problems = _unlockable(chosen, diagnosis.estimator_kwargs) + if problems: + raise ValueError( + f"Estimator '{label}' cannot be locked: {'; '.join(problems)}. A lock " + f"must be able to rebuild the estimator exactly." + ) + + outcome, unit, time = diagnosis.outcome, diagnosis.unit, diagnosis.time + if diagnosis.n_holdout > 0 and data is None: + raise ValueError( + f"{diagnosis.n_holdout} period(s) were held out of the comparison, so " + f"lock() needs the panel to rerun '{label}' with them: pass data= (the " + f"frame given to diagnose_design)." + ) + + n_units, n_periods, n_obs = diagnosis.n_units, diagnosis.n_periods, diagnosis.n_obs + time_periods = list(diagnosis.time_periods) + data_sha256 = diagnosis.data_sha256 + size_ok = diagnosis.size_controlled[label] + mde = diagnosis.mde[label] + holdout_records: List[Dict[str, Any]] = [] + + if data is not None: + untreated, _ = _untreated_rows(data, outcome, unit, time, diagnosis.first_treat) + untreated = _select_columns(untreated, diagnosis.data_columns) + found_periods = np.unique(_period_values(untreated[time])).tolist() + n_compared = len(time_periods) + if ( + found_periods[:n_compared] != time_periods + or len(found_periods) - n_compared != diagnosis.n_holdout + ): + missing = [period for period in time_periods if period not in found_periods] + other = [period for period in found_periods if period not in time_periods] + raise ValueError( + f"data does not have the periods of the diagnosed panel: expected the " + f"{n_compared} compared period(s) followed by {diagnosis.n_holdout} " + f"held-out one(s). Compared periods missing: {missing}; other periods " + f"found: {other}." + ) + compared = untreated.loc[np.isin(_period_values(untreated[time]), time_periods)] + digest, _ = _data_fingerprint(compared, unit, time) + if digest != diagnosis.data_sha256: + raise ValueError( + "data is not the panel that was diagnosed: its fingerprint on the " + "compared periods differs from data_sha256." + ) + + if diagnosis.n_holdout > 0: + if diagnosis._holdout_labels and label not in diagnosis._holdout_labels: + warnings.warn( + f"The held-out periods were already used for " + f"{diagnosis._holdout_labels}. A held-out run for '{label}' as " + f"well makes the two runs a second comparison: do not use them " + f"to choose between estimators.", + UserWarning, + stacklevel=3, + ) + full = _check_panel(untreated, outcome, unit, time) + n_units = full[unit].nunique() + n_periods = len(found_periods) + generator = _make_placebo_generator( + full, + outcome, + unit, + time, + diagnosis.n_treated, + list(diagnosis.cohort_periods), + diagnosis.resample_units, + ) + fit_kwargs = _fit_kwargs(chosen, outcome, unit, time, dict(diagnosis.estimator_kwargs)) + # Derived, not an argument: the held-out run cannot be re-rolled. + lock_seed = int(np.random.SeedSequence([int(diagnosis.seed), 1]).generate_state(1)[0]) + null = diagnosis.results[label][0] + n_simulations = int(null.n_simulations) + int(null.n_simulation_failures) + with _WarningCapture() as capture: + _preflight(label, chosen, generator, fit_kwargs, lock_seed) + _reemit(label, capture.records, stacklevel=4) + cells, nan_counts, size_ok, _found, mde = _run_estimator( + "lock", + label, + chosen, + diagnosis.effect_sizes, + generator, + fit_kwargs, + n_units, + n_periods, + n_simulations, + diagnosis.alpha, + diagnosis.target_power, + lock_seed, + progress, + stacklevel=5, + ) + holdout_records = _records(label, cells, size_ok, nan_counts, mde) + n_obs = len(full) + time_periods = found_periods + data_sha256, _ = _data_fingerprint(full, unit, time) + if label not in diagnosis._holdout_labels: + diagnosis._holdout_labels.append(label) + + if not size_ok: + warnings.warn( + f"'{label}' did not pass the size check on the no-effect runs the lock " + f"reports, so its power is not meaningful. The lock records " + f"size_controlled=False.", + UserWarning, + stacklevel=3, + ) + + from diff_diff import __version__ + + payload: Dict[str, Any] = { + "schema_version": DESIGN_LOCK_SCHEMA_VERSION, + "diff_diff_version": __version__, + "label": label, + "estimator_name": type(chosen).__name__, + "params": chosen.get_params(), + "estimator_kwargs": diagnosis.estimator_kwargs, + "outcome": outcome, + "unit": unit, + "time": time, + "first_treat": diagnosis.first_treat, + "alpha": diagnosis.alpha, + "target_power": diagnosis.target_power, + "effect_sizes": diagnosis.effect_sizes, + "n_treated": diagnosis.n_treated, + "treatment_fraction": diagnosis.treatment_fraction, + "cohort_periods": diagnosis.cohort_periods, + "resample_units": diagnosis.resample_units, + "seed": diagnosis.seed, + "n_holdout": diagnosis.n_holdout, + "n_units": n_units, + "n_periods": n_periods, + "n_obs": n_obs, + "time_periods": time_periods, + "data_sha256": data_sha256, + "data_columns": diagnosis.data_columns, + "comparison_results": diagnosis.to_dataframe().to_dict("records"), + "holdout_results": holdout_records, + "size_controlled": size_ok, + "mde": mde, + } + converted = { + key: _json_value(value, key, "none" if key in _RECORD_FIELDS else "raise") + for key, value in payload.items() + } + return DesignLock(**converted, sha256=_lock_digest(converted)) + + +@dataclass(frozen=True) +class DesignLock(Diagnostic): + """ + A pre-specified design: the estimator chosen before the analysis. + + Made by :meth:`DesignDiagnosisResults.lock`. It records the chosen + estimator and its configuration, the declared design, a fingerprint of + the panel, every estimator that was compared, and the chosen estimator's + size, power, bias, RMSE, coverage and minimum detectable effect. All + values are plain JSON data, so ``DesignLock.from_json(lock.to_json())`` + equals ``lock``. + + Attributes + ---------- + schema_version : str + ``DESIGN_LOCK_SCHEMA_VERSION`` at the time the lock was made. + diff_diff_version : str + Library version that made the lock. + label : str + The chosen estimator's label in the comparison. + estimator_name : str + Its class name. + params : dict + Its constructor parameters. + estimator_kwargs : dict + Extra ``fit()`` keywords that were applied. + outcome, unit, time : str + Column names of the diagnosed panel. + first_treat : str or None + Real first-treatment column used to truncate the diagnosed panel. + alpha : float + Significance level. + target_power : float or None + Target power of the minimum-detectable-effect search. + effect_sizes : list of float + Injected effects, 0 first. + n_treated : int + Placebo-treated units per replicate. + treatment_fraction : float or None + Declared share of treated units, when given. + cohort_periods : list + Declared adoption periods. + resample_units : bool + Whether units were resampled in each replicate. + seed : int + Seed of the comparison. The held-out run uses a seed derived from it. + n_holdout : int + Periods held out of the comparison. + n_units, n_periods, n_obs : int + Shape of the panel the reported numbers come from: the panel with the + held-out periods when a held-out run was made, else the compared one. + time_periods : list + Its period values. + data_sha256 : str + Its fingerprint. + data_columns : list of str + Columns the fingerprint covers. + comparison_results : list of dict + One record per estimator and effect from the comparison, for every + estimator that was compared. + holdout_results : list of dict + The chosen estimator's records from the held-out run; empty when no + periods were held out. + size_controlled : bool + Whether the chosen estimator passed the size check in the run the + lock reports. + mde : float or None + Its minimum detectable effect; ``None`` when not reported. + sha256 : str + SHA-256 of the canonical JSON of every other field. It detects + accidental edits; it is not a signature. + """ + + schema_version: str + diff_diff_version: str + label: str + estimator_name: str + params: Dict[str, Any] + estimator_kwargs: Dict[str, Any] + outcome: str + unit: str + time: str + first_treat: Optional[str] + alpha: float + target_power: Optional[float] + effect_sizes: List[float] + n_treated: int + treatment_fraction: Optional[float] + cohort_periods: List[Any] + resample_units: bool + seed: int + n_holdout: int + n_units: int + n_periods: int + n_obs: int + time_periods: List[Any] + data_sha256: str + data_columns: List[str] + comparison_results: List[Dict[str, Any]] + holdout_results: List[Dict[str, Any]] + size_controlled: bool + mde: Optional[float] + sha256: str + + def __repr__(self) -> str: + """Concise string representation.""" + return ( + f"DesignLock(label={self.label!r}, estimator_name={self.estimator_name!r}, " + f"n_holdout={self.n_holdout}, sha256={self.sha256[:12]!r}...)" + ) + + def __hash__(self) -> int: + # The generated hash would fail on the dict and list fields. + return hash(self.sha256) + + def _payload(self) -> Dict[str, Any]: + return { + f.name: getattr(self, f.name) for f in dataclasses.fields(self) if f.name != "sha256" + } + + def _verify(self) -> None: + """Raise if the fields no longer match ``sha256``.""" + try: + digest = _lock_digest(self._payload()) + except (TypeError, ValueError) as exc: + raise ValueError(f"The design lock holds a value that is not JSON data: {exc}.") + if digest != self.sha256: + raise ValueError( + "The design lock does not match its sha256: it was edited after it " + "was made. Reload it from the original file." + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Convert the lock to a dictionary of plain JSON data. + + Returns + ------- + Dict[str, Any] + Every field, as a deep copy. + """ + result = copy.deepcopy(self._payload()) + result["sha256"] = self.sha256 + return result + + def to_json(self, *, indent: int = 2) -> str: + """Return ``to_dict()`` serialized as JSON.""" + return json.dumps(self.to_dict(), indent=indent, allow_nan=False) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "DesignLock": + """ + Rebuild a lock from ``to_dict()`` output. + + Raises + ------ + ValueError + If a key is unknown or missing, the schema version has a + different major number, or the content does not match ``sha256``. + """ + if not isinstance(data, Mapping): + raise TypeError("A design lock is read from a dictionary.") + names = [f.name for f in dataclasses.fields(cls)] + unknown = sorted(str(key) for key in set(data) - set(names)) + missing = sorted(set(names) - set(data)) + if unknown or missing: + raise ValueError( + f"Not a design lock: unknown key(s) {unknown}, missing key(s) {missing}." + ) + version = str(data["schema_version"]) + if version.split(".")[0] != DESIGN_LOCK_SCHEMA_VERSION.split(".")[0]: + raise ValueError( + f"Design lock schema version {version!r} is not supported by this " + f"library version (which reads {DESIGN_LOCK_SCHEMA_VERSION!r})." + ) + lock = cls(**copy.deepcopy(dict(data))) + lock._verify() + return lock + + @classmethod + def from_json(cls, text: str) -> "DesignLock": + """Rebuild a lock from ``to_json()`` output.""" + return cls.from_dict(json.loads(text)) + + def to_dataframe(self) -> pd.DataFrame: + """ + The chosen estimator's reported rows, one per effect size. + + Returns + ------- + pd.DataFrame + ``holdout_results`` when a held-out run was made, otherwise the + chosen estimator's rows of ``comparison_results``. + """ + if self.holdout_results: + return pd.DataFrame(copy.deepcopy(self.holdout_results)) + rows = [row for row in self.comparison_results if row.get("label") == self.label] + return pd.DataFrame(copy.deepcopy(rows)) + + def summary(self) -> str: + """ + Generate a formatted summary of the lock. + + Returns + ------- + str + Formatted summary. + """ + width = 78 + timing = "common" if len(self.cohort_periods) == 1 else "staggered" + source = ( + f"held-out run ({self.n_holdout} period(s) the comparison did not read)" + if self.holdout_results + else "comparison run (not confirmed on held-out periods)" + ) + compared = list(dict.fromkeys(str(row.get("label")) for row in self.comparison_results)) + mde_text = f"{self.mde:.4g}" if self.mde is not None else "-" + lines = [ + "=" * width, + "Design Lock (pre-specified design)".center(width), + "=" * width, + "", + f"{'Chosen:':<32} {self.label} ({self.estimator_name})", + f"{'Compared:':<32} {', '.join(compared)}", + f"{'Units x periods:':<32} {self.n_units} x {self.n_periods}", + f"{'Placebo-treated units:':<32} {self.n_treated}", + f"{'Adoption periods (' + timing + '):':<32} {list(self.cohort_periods)}", + f"{'Significance level (alpha):':<32} {self.alpha:.3f}", + f"{'Reported numbers from:':<32} {source}", + f"{'Size OK:':<32} {'yes' if self.size_controlled else 'NO'}", + f"{'MDE:':<32} {mde_text}", + "", + "-" * width, + f"{'Effect':>10}{'Rejects':>10}{'Bias':>12}{'RMSE':>12}{'Coverage':>10}" + f"{'Scored':>8}{'Lost':>7}", + "-" * width, + ] + for row in self.to_dataframe().to_dict("records"): + lines.append( + f"{row['true_effect']:>10.4g}{_fmt_cell(row['rejection_rate'], rate=True):>10}" + f"{_fmt_cell(row['bias']):>12}{_fmt_cell(row['rmse']):>12}" + f"{_fmt_cell(row['coverage'], rate=True):>10}" + f"{row['n_simulations']:>8}{row['n_simulation_failures']:>7}" + ) + lines.extend( + [ + "", + f"diff-diff {self.diff_diff_version}, lock schema {self.schema_version}", + f"sha256 {self.sha256}", + "=" * width, + ] + ) + return "\n".join(lines) + + def print_summary(self) -> None: + """Print the summary to stdout.""" + print(self.summary()) + + def to_estimator(self) -> Any: + """ + Build the locked estimator. + + Returns + ------- + estimator + A fresh, unfitted instance of ``estimator_name`` configured with + ``params``. Fitting it, with ``estimator_kwargs``, is the + pre-specified analysis. + """ + self._verify() + if self.estimator_name not in _SUPPORTED_ESTIMATORS: + raise ValueError( + f"The lock names {self.estimator_name!r}, which is not one of " + f"{', '.join(_SUPPORTED_ESTIMATORS)}." + ) + import diff_diff + + return getattr(diff_diff, self.estimator_name)(**copy.deepcopy(self.params)) + + def reconcile( + self, + estimator: Any, + *, + outcome: str, + unit: str, + time: str, + first_treat: Optional[str] = None, + treatment: Optional[str] = None, + post: Optional[str] = None, + estimator_kwargs: Optional[Dict[str, Any]] = None, + data: Optional[pd.DataFrame] = None, + results: Optional[Any] = None, + ) -> "DesignReconciliationResults": + """ + Check the analysis that was run against this lock. + + Parameters + ---------- + estimator : estimator + The estimator used for the analysis. + outcome, unit, time : str + Outcome, unit and calendar-period column names of the analysis. + first_treat : str, optional + Column with each unit's real first treatment period (0, inf or + NaN for never-treated), for the estimators that take one. + treatment : str, optional + 0/1 group column, for ``DifferenceInDifferences`` and + ``TwoWayFixedEffects``. Pass ``first_treat`` or ``treatment``, + not both. + post : str, optional + 0/1 post-period column that goes with ``treatment``. + estimator_kwargs : dict, optional + Extra ``fit()`` keywords the analysis used. + data : pd.DataFrame, optional + The analysis data. When given, the data and the realized design + are checked too. + results : results object, optional + The fitted results. It must be ``estimator.results_``. + + Returns + ------- + DesignReconciliationResults + One check per item and an overall ``status``: ``"pre-specified"`` + when every check that was run matches, otherwise ``"deviates"``. + + Notes + ----- + This compares what the analyst declares with the lock. Fitted results + do not record the constructor parameters or column names that + produced them, so a parameter changed with ``set_params()`` after + fitting cannot be detected. ``"pre-specified"`` covers the listed + checks only. + + The data fingerprint covers every column the diagnosed panel had, on + the locked periods. A column whose values changed there deviates; + that includes an adoption column that was all never-treated when the + design was diagnosed and holds the real dates now. + + Adoption dates are not compared: placebo dates lie inside the + diagnosed panel and real ones after it. The number of cohorts, the + number of treated units, the length of each cohort's post window and + whether the panel is balanced are. + """ + self._verify() + if not hasattr(estimator, "get_params"): + raise TypeError("reconcile needs the estimator instance used for the analysis.") + if first_treat is not None and treatment is not None: + raise ValueError( + "Pass first_treat (a first-treatment-period column) or treatment (a " + "0/1 group column), not both." + ) + if results is not None and getattr(estimator, "results_", None) is not results: + raise ValueError( + "results is not this estimator's results_: it was not produced by " + "the estimator being reconciled." + ) + if data is not None and not isinstance(data, pd.DataFrame): + raise TypeError("data must be a pandas DataFrame.") + + checks = [_compare("estimator_name", self.estimator_name, type(estimator).__name__)] + checks.extend(_compare_mapping("params", self.params, estimator.get_params())) + checks.extend( + _compare_mapping( + "estimator_kwargs", self.estimator_kwargs, dict(estimator_kwargs or {}) + ) + ) + checks.append(_compare("outcome", self.outcome, outcome)) + checks.append(_compare("unit", self.unit, unit)) + checks.append(_compare("time", self.time, time)) + if results is None: + checks.append(_check_row("alpha", self.alpha, None, _NOT_CHECKED)) + else: + checks.append(_compare("alpha", self.alpha, getattr(results, "alpha", _ABSENT))) + checks.extend(_design_checks(self, data, unit, time, first_treat, treatment, post)) + + deviates = any(check["status"] == _DEVIATES for check in checks) + return DesignReconciliationResults( + status=_DEVIATES if deviates else _PRE_SPECIFIED, + checks=checks, + label=self.label, + lock_sha256=self.sha256, + ) + + +def _fmt_cell(value: Optional[float], rate: bool = False) -> str: + if value is None: + return "-" + return _fmt_rate(value) if rate else _fmt_num(value) + + +def _check_row(item: str, locked: Any, realized: Any, status: str) -> Dict[str, Any]: + return {"item": item, "locked": locked, "realized": realized, "status": status} + + +def _same(locked: Any, realized: Any) -> bool: + """Equality of two JSON values; a boolean never equals a number.""" + if isinstance(locked, bool) != isinstance(realized, bool): + return False + if isinstance(locked, list) and isinstance(realized, list): + return len(locked) == len(realized) and all(_same(a, b) for a, b in zip(locked, realized)) + if isinstance(locked, dict) and isinstance(realized, dict): + return set(locked) == set(realized) and all( + _same(locked[key], realized[key]) for key in locked + ) + return bool(locked == realized) + + +def _compare(item: str, locked: Any, realized: Any) -> Dict[str, Any]: + """One check. A realized value that is not JSON data cannot match a lock.""" + try: + value = _json_value(realized, item) + except ValueError: + return _check_row(item, locked, repr(realized), _DEVIATES) + return _check_row(item, locked, value, _MATCH if _same(locked, value) else _DEVIATES) + + +def _compare_mapping( + group: str, locked: Mapping[str, Any], realized: Mapping[str, Any] +) -> List[Dict[str, Any]]: + names = list(locked) + [name for name in realized if name not in locked] + rows = [] + for name in names: + item = f"{group}.{name}" + if name not in realized: + rows.append(_check_row(item, locked[name], _ABSENT, _DEVIATES)) + elif name not in locked: + rows.append(_check_row(item, _ABSENT, repr(realized[name]), _DEVIATES)) + else: + rows.append(_compare(item, locked[name], realized[name])) + return rows + + +def _design_checks( + lock: DesignLock, + data: Optional[pd.DataFrame], + unit: str, + time: str, + first_treat: Optional[str], + treatment: Optional[str], + post: Optional[str], +) -> List[Dict[str, Any]]: + """The checks that need the analysis data.""" + cohorts = sorted(lock.cohort_periods) + locked: Dict[str, Any] = { + "data_sha256": lock.data_sha256, + "n_units": lock.n_units, + "is_balanced": True, + "n_treated": lock.n_treated, + "n_cohorts": len(cohorts), + "n_post_by_cohort": [ + sum(1 for period in lock.time_periods if period >= cohort) for cohort in cohorts + ], + } + realized: Dict[str, Any] = {} + problems: Dict[str, str] = {} + timing = ("n_treated", "n_cohorts", "n_post_by_cohort") + + if data is not None: + # The fingerprint is taken with the lock's own column names: it asks + # whether the diagnosed panel is still in the data. + try: + selected = _select_columns(data, lock.data_columns) + by_name = {str(column): column for column in selected.columns} + lock_unit, lock_time = by_name[str(lock.unit)], by_name[str(lock.time)] + rows = selected.loc[selected[lock_time].isin(lock.time_periods)] + realized["data_sha256"], _ = _data_fingerprint(rows, lock_unit, lock_time) + except (KeyError, ValueError) as exc: + problems["data_sha256"] = f"unavailable: {exc}" + + absent = [column for column in (unit, time) if column not in data.columns] + if absent: + requested = timing if (first_treat is not None or treatment is not None) else () + for item in ("n_units", "is_balanced") + requested: + problems[item] = f"column(s) {absent} not in data" + else: + n_units = int(data[unit].nunique()) + periods = pd.unique(data[time]) + realized["n_units"] = n_units + realized["is_balanced"] = bool( + not data.duplicated([unit, time]).any() and len(data) == n_units * len(periods) + ) + if first_treat is not None: + problem, values = _realized_first_treat(data, unit, first_treat) + if problem is not None: + for item in timing: + problems[item] = problem + else: + realized_cohorts = sorted(set(values)) + realized["n_treated"] = len(values) + realized["n_cohorts"] = len(realized_cohorts) + try: + realized["n_post_by_cohort"] = [ + int(np.sum(periods >= cohort)) for cohort in realized_cohorts + ] + except TypeError: + problems["n_post_by_cohort"] = ( + f"'{time}' cannot be compared with '{first_treat}'" + ) + elif treatment is not None: + if treatment not in data.columns: + problems["n_treated"] = problems["n_cohorts"] = ( + f"column {treatment!r} not in data" + ) + elif (data.groupby(unit)[treatment].nunique(dropna=False) > 1).any(): + problems["n_treated"] = problems["n_cohorts"] = "varies within unit" + else: + n_treated = int((data.groupby(unit)[treatment].first() == 1).sum()) + realized["n_treated"] = n_treated + realized["n_cohorts"] = 1 if n_treated else 0 + if post is not None: + if post not in data.columns: + problems["n_post_by_cohort"] = f"column {post!r} not in data" + elif (data.groupby(time)[post].nunique(dropna=False) > 1).any(): + problems["n_post_by_cohort"] = "varies within period" + else: + realized["n_post_by_cohort"] = [ + int((data.groupby(time)[post].first() == 1).sum()) + ] + + rows_out = [] + for item, value in locked.items(): + if item in problems: + rows_out.append(_check_row(item, value, problems[item], _DEVIATES)) + elif item in realized: + rows_out.append(_compare(item, value, realized[item])) + else: + rows_out.append(_check_row(item, value, None, _NOT_CHECKED)) + return rows_out + + +def _realized_first_treat( + data: pd.DataFrame, unit: str, first_treat: str +) -> Tuple[Optional[str], List[float]]: + """Each treated unit's adoption period, or why it cannot be read.""" + if first_treat not in data.columns: + return f"column {first_treat!r} not in data", [] + if not pd.api.types.is_numeric_dtype(data[first_treat]): + return f"'{first_treat}' is not numeric", [] + if (data.groupby(unit)[first_treat].nunique(dropna=False) > 1).any(): + return "varies within unit", [] + values = data[first_treat].to_numpy(dtype=float, na_value=np.nan) + first_rows = ~data[unit].duplicated().to_numpy() + per_unit = values[first_rows] + adopted = per_unit[np.isfinite(per_unit) & (per_unit > 0)] + return None, [float(value) for value in adopted] + + +@dataclass +class DesignReconciliationResults(Diagnostic): + """ + Results of :meth:`DesignLock.reconcile`. + + Attributes + ---------- + status : str + ``"pre-specified"`` when every check that was run matches the lock, + otherwise ``"deviates"``. The size of a deviation is not graded. + checks : list of dict + One entry per reconciled item, with keys ``item``, ``locked``, + ``realized`` and ``status`` (``"match"``, ``"deviates"`` or + ``"not checked"``). + label : str + Label of the locked estimator. + lock_sha256 : str + ``sha256`` of the lock that was reconciled against. + """ + + status: str + checks: List[Dict[str, Any]] + label: str + lock_sha256: str + + def __repr__(self) -> str: + """Concise string representation.""" + n_deviating = sum(1 for check in self.checks if check["status"] == _DEVIATES) + return ( + f"DesignReconciliationResults(status={self.status!r}, " + f"checks={len(self.checks)}, deviating={n_deviating})" + ) + + def to_dataframe(self) -> pd.DataFrame: + """ + One row per reconciled item. + + Returns + ------- + pd.DataFrame + Columns ``item``, ``locked``, ``realized``, ``status``. + """ + return pd.DataFrame( + copy.deepcopy(self.checks), columns=["item", "locked", "realized", "status"] + ) + + def to_dict(self) -> Dict[str, Any]: + """ + Convert results to a dictionary. + + Returns + ------- + Dict[str, Any] + The overall status, the lock reconciled against and every check. + """ + return { + "status": self.status, + "label": self.label, + "lock_sha256": self.lock_sha256, + "checks": copy.deepcopy(self.checks), + } + + def summary(self) -> str: + """ + Generate a formatted summary of the reconciliation. + + Returns + ------- + str + Formatted summary: the overall status and every item that + deviates or was not checked. + """ + width = 78 + counts = {status: 0 for status in (_MATCH, _DEVIATES, _NOT_CHECKED)} + for check in self.checks: + counts[check["status"]] = counts.get(check["status"], 0) + 1 + lines = [ + "=" * width, + "Design Reconciliation (analysis vs. design lock)".center(width), + "=" * width, + "", + f"{'Locked estimator:':<24} {self.label}", + f"{'Status:':<24} {self.status}", + f"{'Checks:':<24} {counts[_MATCH]} match, {counts[_DEVIATES]} deviate, " + f"{counts[_NOT_CHECKED]} not checked", + f"{'Lock sha256:':<24} {self.lock_sha256}", + ] + shown = [check for check in self.checks if check["status"] != _MATCH] + if shown: + lines.extend( + [ + "", + "-" * width, + f"{'Item':<30}{'Locked':<17}{'Realized':<17}{'Status':<14}", + "-" * width, + ] + ) + for check in shown: + realized = "" if check["realized"] is None else str(check["realized"]) + lines.append( + f"{str(check['item'])[:29]:<30}{str(check['locked'])[:16]:<17}" + f"{realized[:16]:<17}{check['status']:<14}" + ) + lines.extend( + [ + "", + "'pre-specified' means every check that was run matches the lock. It is", + "a statement about the listed items only, and deviations are not graded.", + "=" * width, + ] + ) + return "\n".join(lines) + + def print_summary(self) -> None: + """Print the summary to stdout.""" + print(self.summary()) diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index 3019c725..1966689f 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -2419,13 +2419,58 @@ null_run = result.results["cs"][0] # SimulationPowerResults at effect 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 + +# Several estimators were compared, so the last periods were held out +# (result.n_holdout). Lock the choice: only "cs" is rerun, with those periods. +lock = result.lock("cs", data=panel) +open("design_lock.json", "w").write(lock.to_json()) + +# After the study has run: +from diff_diff import DesignLock +lock = DesignLock.from_json(open("design_lock.json").read()) +estimator = lock.to_estimator() # the estimator exactly as locked +fit = estimator.fit(analysis, outcome="sales", unit="store", time="year", + first_treat="adopted") +check = lock.reconcile(estimator, outcome="sales", unit="store", time="year", + first_treat="adopted", data=analysis, results=fit) +check.status # "pre-specified" or "deviates" +check.to_dataframe() # item, locked, realized, status ``` **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`. +`resample_units=True`, `estimator_kwargs=None`, `seed=None`, `progress=True`, +`n_holdout=None`. + +**Held-out periods:** with more than one estimator, the last `n_holdout` periods +are not read by the comparison (default: half of the periods at or after the +latest adoption period, rounded down; an error if that is zero; `n_holdout=0` +compares on the whole panel). `result.lock(label, data=panel)` reruns only the +chosen estimator with them, on fresh placebo draws, so its reported power is not +taken from the runs used to choose it. `data` is required when periods were held +out and must be the diagnosed panel. + +**`DesignLock`:** plain JSON data. Fields include `label`, `estimator_name`, +`params`, `estimator_kwargs`, the declared design, `time_periods`, +`data_sha256`, `comparison_results` (every estimator compared), +`holdout_results` (the chosen one's rerun), `size_controlled`, `mde`, +`schema_version` (`DESIGN_LOCK_SCHEMA_VERSION`), `sha256`. Methods: +`to_json()`, `to_dict()`, `DesignLock.from_json()`, `DesignLock.from_dict()`, +`to_estimator()`, `reconcile()`, `to_dataframe()`, `summary()`. + +**`lock.reconcile(estimator, outcome=, unit=, time=, first_treat= | treatment= +(+ post=), estimator_kwargs=, data=, results=)`** returns +`DesignReconciliationResults` with `status` (`"pre-specified"` or `"deviates"`) +and `checks` (one per item: `estimator_name`, `params.`, +`estimator_kwargs.`, `outcome`, `unit`, `time`, `alpha`, and with `data`: +`data_sha256`, `n_units`, `is_balanced`, `n_treated`, `n_cohorts`, +`n_post_by_cohort`). Any checked item that differs gives `"deviates"`; items +whose inputs were not passed are `"not checked"`. It compares what you declare +with the lock (fitted results do not record their configuration), does not +compare adoption dates (placebo dates lie inside the diagnosed panel), and +`"pre-specified"` covers the listed checks only. **Supported estimators:** DifferenceInDifferences, TwoWayFixedEffects (common timing only), CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, @@ -2434,8 +2479,9 @@ 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()`. +the declared design, `seed`, `data_sha256`, `n_holdout`, `time_periods`. +Methods: `summary()`, `print_summary()`, `to_dataframe()`, `to_dict()`, +`lock()`. **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 diff --git a/diff_diff/guides/llms.txt b/diff_diff/guides/llms.txt index 9e9f856d..b4e5686f 100644 --- a/diff_diff/guides/llms.txt +++ b/diff_diff/guides/llms.txt @@ -93,7 +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 +- [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. With several estimators the last periods are held out of the comparison (`n_holdout`); `result.lock(label, data=)` reruns only the chosen estimator with them and returns a JSON-serializable `DesignLock` (`to_json()` / `DesignLock.from_json()`, `to_estimator()`), and `lock.reconcile(estimator, outcome=, unit=, time=, first_treat=, data=, results=)` labels the analysis that was run `pre-specified` or `deviates` (reconciliation idea: Blair et al. 2019) - [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 index d82cae9c..a68b9f50 100644 --- a/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst +++ b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst @@ -12,6 +12,7 @@ .. autosummary:: ~DesignDiagnosisResults.__init__ + ~DesignDiagnosisResults.lock ~DesignDiagnosisResults.print_summary ~DesignDiagnosisResults.summary ~DesignDiagnosisResults.to_dataframe @@ -49,4 +50,6 @@ ~DesignDiagnosisResults.n_dropped ~DesignDiagnosisResults.data_sha256 ~DesignDiagnosisResults.data_columns + ~DesignDiagnosisResults.n_holdout + ~DesignDiagnosisResults.time_periods diff --git a/docs/api/_autosummary/diff_diff.DesignLock.rst b/docs/api/_autosummary/diff_diff.DesignLock.rst new file mode 100644 index 00000000..4b11d39d --- /dev/null +++ b/docs/api/_autosummary/diff_diff.DesignLock.rst @@ -0,0 +1,62 @@ +diff\_diff.DesignLock +===================== + +.. currentmodule:: diff_diff + +.. autoclass:: DesignLock + :no-members: + + + .. rubric:: Methods + + .. autosummary:: + + ~DesignLock.__init__ + ~DesignLock.from_dict + ~DesignLock.from_json + ~DesignLock.print_summary + ~DesignLock.reconcile + ~DesignLock.summary + ~DesignLock.to_dataframe + ~DesignLock.to_dict + ~DesignLock.to_estimator + ~DesignLock.to_json + + + + + .. rubric:: Attributes + + .. autosummary:: + + ~DesignLock.schema_version + ~DesignLock.diff_diff_version + ~DesignLock.label + ~DesignLock.estimator_name + ~DesignLock.params + ~DesignLock.estimator_kwargs + ~DesignLock.outcome + ~DesignLock.unit + ~DesignLock.time + ~DesignLock.first_treat + ~DesignLock.alpha + ~DesignLock.target_power + ~DesignLock.effect_sizes + ~DesignLock.n_treated + ~DesignLock.treatment_fraction + ~DesignLock.cohort_periods + ~DesignLock.resample_units + ~DesignLock.seed + ~DesignLock.n_holdout + ~DesignLock.n_units + ~DesignLock.n_periods + ~DesignLock.n_obs + ~DesignLock.time_periods + ~DesignLock.data_sha256 + ~DesignLock.data_columns + ~DesignLock.comparison_results + ~DesignLock.holdout_results + ~DesignLock.size_controlled + ~DesignLock.mde + ~DesignLock.sha256 + diff --git a/docs/api/_autosummary/diff_diff.DesignReconciliationResults.rst b/docs/api/_autosummary/diff_diff.DesignReconciliationResults.rst new file mode 100644 index 00000000..48616f6d --- /dev/null +++ b/docs/api/_autosummary/diff_diff.DesignReconciliationResults.rst @@ -0,0 +1,31 @@ +diff\_diff.DesignReconciliationResults +====================================== + +.. currentmodule:: diff_diff + +.. autoclass:: DesignReconciliationResults + :no-members: + + + .. rubric:: Methods + + .. autosummary:: + + ~DesignReconciliationResults.__init__ + ~DesignReconciliationResults.print_summary + ~DesignReconciliationResults.summary + ~DesignReconciliationResults.to_dataframe + ~DesignReconciliationResults.to_dict + + + + + .. rubric:: Attributes + + .. autosummary:: + + ~DesignReconciliationResults.status + ~DesignReconciliationResults.checks + ~DesignReconciliationResults.label + ~DesignReconciliationResults.lock_sha256 + diff --git a/docs/api/design.rst b/docs/api/design.rst index 1af6fdd5..6ada87bb 100644 --- a/docs/api/design.rst +++ b/docs/api/design.rst @@ -29,6 +29,30 @@ 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. +**Held-out periods.** Comparing several estimators and then quoting the chosen +one's power from the same runs overstates it. When more than one estimator is +passed, the last periods of the panel are therefore held out of the comparison: +by default half of the periods at or after the latest adoption period, rounded +down (``n_holdout``; pass ``n_holdout=0`` to compare on the whole panel). Those +rows are not read by :func:`~diff_diff.diagnose_design`. + +**Design lock.** :meth:`~diff_diff.DesignDiagnosisResults.lock` records one +estimator as the pre-specified choice. If periods were held out it reruns that +estimator alone, with them included and with fresh placebo draws, and the +:class:`~diff_diff.DesignLock` reports that run. The lock is plain JSON data: +write ``lock.to_json()`` to a file and read it back with +:meth:`~diff_diff.DesignLock.from_json`. + +**Reconcile.** After the analysis, :meth:`~diff_diff.DesignLock.reconcile` checks +it against the lock item by item - estimator class, every constructor parameter, +``fit()`` keywords, column names, and, when the analysis data is passed, the +fingerprint of the diagnosed periods and the realized design - and labels it +``pre-specified`` or ``deviates``. It compares what you declare with the lock: +fitted results do not record the parameters that produced them, so +:meth:`~diff_diff.DesignLock.to_estimator` is provided to build the estimator +straight from the lock. ``pre-specified`` covers the listed checks only, and a +deviation is not graded. + The methodology, its sources and the choices that have no paper source are in the Methodology Registry under ``DesignDiagnosis``. @@ -46,6 +70,24 @@ DesignDiagnosisResults :undoc-members: :show-inheritance: +DesignLock +---------- + +.. autoclass:: diff_diff.DesignLock + :no-index: + :members: + :undoc-members: + :show-inheritance: + +DesignReconciliationResults +--------------------------- + +.. autoclass:: diff_diff.DesignReconciliationResults + :no-index: + :members: + :undoc-members: + :show-inheritance: + Example ------- @@ -84,8 +126,44 @@ Example null_run = result.results["cs"][0] print(null_run.rejection_rate, result.size_controlled["cs"], result.mde["cs"]) +Three estimators were compared, so the last periods of ``panel`` were held out +(``result.n_holdout``). Locking the choice reruns it with them: + +.. code-block:: python + + from pathlib import Path + + from diff_diff import DesignLock + + lock = result.lock("cs", data=panel) # reruns "cs" only, held-out periods included + lock.print_summary() + Path("design_lock.json").write_text(lock.to_json()) + +Later, once the study has run: + +.. code-block:: python + + lock = DesignLock.from_json(Path("design_lock.json").read_text()) + estimator = lock.to_estimator() # the estimator exactly as locked + fit = estimator.fit( + analysis, outcome="sales", unit="store", time="year", first_treat="adopted" + ) + check = lock.reconcile( + estimator, + outcome="sales", + unit="store", + time="year", + first_treat="adopted", + data=analysis, + results=fit, + ) + print(check.status) # "pre-specified" or "deviates" + check.to_dataframe() # one row per checked item + A staggered design declares several adoption periods; each placebo-treated unit -draws its period from the list: +draws its period from the list. With two estimators, periods are held out by +default, so the latest adoption period must leave at least two periods at or +after it (here the panel runs through 2023): .. code-block:: python diff --git a/docs/api/index.rst b/docs/api/index.rst index 13e6eea2..c99ad585 100644 --- a/docs/api/index.rst +++ b/docs/api/index.rst @@ -261,6 +261,8 @@ Size and power of candidate estimators on your own untreated panel: diff_diff.diagnose_design diff_diff.DesignDiagnosisResults + diff_diff.DesignLock + diff_diff.DesignReconciliationResults Pre-Trends Power Analysis ------------------------- diff --git a/docs/doc-deps.yaml b/docs/doc-deps.yaml index 414f0085..9e79374c 100644 --- a/docs/doc-deps.yaml +++ b/docs/doc-deps.yaml @@ -1462,7 +1462,7 @@ sources: 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)" + note: "Diagnosand vocabulary (bias, RMSE, power, coverage); reconciling the planned and the realized design (DesignLock.reconcile)" - path: docs/api/design.rst type: api_reference - path: docs/index.rst diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index f6d4ad8b..fcbfee86 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -6961,9 +6961,9 @@ where δ is the target effect. - 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`) +**Module:** `diff_diff/design.py` (`diagnose_design`, `DesignDiagnosisResults`, `DesignDiagnosisResults.lock`, `DesignLock`, `DesignLock.reconcile`, `DesignReconciliationResults`, `DESIGN_LOCK_SCHEMA_VERSION`) -**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. +**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. When several candidates are compared, the last periods are held out of the comparison; the chosen candidate is then rerun with them and recorded as a design lock, and the analysis that is finally run can be reconciled against that lock. **Key implementation requirements:** @@ -6997,6 +6997,32 @@ 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. +*Held-out periods* (library choice, no paper source): +``` +n_post = number of periods of the untreated panel at or after max(cohort_periods) +n_holdout = 0 one candidate + = n_post // 2 several candidates (ValueError if that is 0) + = the caller's value, 0 <= n_holdout <= n_post - 1 +comparison panel = untreated panel without its last n_holdout periods +``` +- Held-out rows are removed by period value before any outcome is validated, fingerprinted or fitted; `data_sha256`, `n_periods`, `n_obs` and `time_periods` describe the comparison panel. `n_dropped` still counts only the rows removed by truncation at the earliest real adoption. +- `DesignDiagnosisResults.lock(label, data)` reruns the one chosen candidate on the untreated panel with the held-out periods included, at the adoption dates exactly as declared, with the comparison's replicate count and the seed `SeedSequence([seed, 1])`. The lock reports that run. With `n_holdout = 0` there is no rerun and the lock reports the chosen candidate's comparison rows. +- The panel passed to `lock` must have the compared periods followed by exactly `n_holdout` later ones, and its fingerprint on the compared periods must equal `data_sha256`; otherwise it is refused. + +*Design lock and reconciliation:* +- `DesignLock` records the chosen candidate (label, class name, constructor parameters, extra `fit()` keywords), the declared design, the panel fingerprint and period values, the comparison rows of every candidate that was compared, the chosen candidate's reported rows, its size check and MDE, the library version and a schema version. All values are plain JSON data; NaN statistics are stored as `null`. +- `DesignLock.reconcile(estimator, outcome=, unit=, time=, ...)` compares an analysis with the lock item by item and labels it `pre-specified` when every check that was run matches and `deviates` otherwise. Reconciling the planned and the realized design, and reporting which it is, follows Blair et al. (p.852); the items, the binary label and everything else about the mechanism are library choices. +``` +always: estimator_name, params., estimator_kwargs., outcome, unit, time +with results: alpha +with data: data_sha256 fingerprint of the rows in the locked periods + n_units + is_balanced one row per (unit, period), every unit in every period + n_treated units with a finite positive first_treat (or treatment == 1) + n_cohorts distinct finite positive first_treat values (1 under treatment) + n_post_by_cohort per cohort, the number of periods at or after adoption +``` + *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:* @@ -7004,6 +7030,10 @@ The injected effect is constant over treated unit-periods, so `delta` is the val - 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. +- Several candidates with the latest adoption in the final period: the default held-out count is zero periods, which is refused with a message naming `n_holdout=0`. +- `lock` refuses: a missing `data` when periods were held out; a panel whose periods or fingerprint differ from the diagnosed one; a stored candidate whose parameters, or stored `fit()` keywords, were changed after the diagnosis (the keywords are copied when the diagnosis starts, so later edits to the caller's own objects have no effect); a panel whose column labels are equal as strings; a parameter or `fit()` keyword that is not JSON data or is a non-finite number (`diagnose_design` warns about these before the run). +- `reconcile` does not raise because of what the analysis looks like: a missing column, an adoption column that varies within a unit, a `post` column that varies within a period, or a realized parameter that is not JSON data is reported as a deviation. Items whose inputs were not passed are reported as `not checked`. +- A lock whose content no longer matches its `sha256` is refused by `from_dict`, `from_json`, `reconcile` and `to_estimator`. **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. @@ -7019,7 +7049,14 @@ The injected effect is constant over treated unit-periods, so `delta` is the val - **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. +- **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 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. Missing values, booleans, strings and numbers carry different tags; numbers are encoded by value, so `1` and `1.0` are the same cell. pandas stores an integer column as float as soon as one row is missing, and a storage-type tag would make the digest of some rows depend on rows outside them (held-out rows, or the later periods of an analysis frame). It has no paper source; it exists so that the lock step and a later analysis can be checked against the diagnosed sample. Because it covers every column the diagnosed frame had, a column whose values change in the locked periods makes the `data_sha256` check of `reconcile` deviate - including an adoption column that was all never-treated at diagnosis and holds the real dates at analysis; keep such a column out of the diagnosed frame. +- **Note (held-out periods):** comparing several candidates and then quoting the chosen one's power from the same runs overstates it. Holding out the last periods and rerunning only the chosen candidate is a library choice with no paper source, as is the default count (half the post window of the latest adoption period, rounded down). The lock run uses the declared adoption dates on the full untreated panel, so its data overlaps the comparison's, and the comparison is run on a post window `n_holdout` periods shorter than the one the lock reports; window length can change the candidates' relative power. How much selection inflation the rerun removes is not validated numerically. +- **Note (lock seed and second label):** the lock run's seed is derived from the recorded seed and is not an argument, so the run cannot be re-rolled. A held-out run for a second label on the same results emits a warning, since the two runs would amount to a second comparison; it is not refused (a fresh `diagnose_design` call would get around a refusal). +- **Note (binary label):** `reconcile` returns `pre-specified` or `deviates` and does not grade the size of a deviation; any checked item that differs gives `deviates`. `pre-specified` covers the listed checks only: it does not certify aspects of the analysis data that are not listed. +- **Note (declaration check):** fitted results do not record the constructor parameters or column names that produced them, so `reconcile` compares what the analyst passes (the estimator instance, the column names, the `fit()` keywords) with the lock. A `results` object must be the estimator's own `results_`, and its `alpha` is compared; a parameter changed with `set_params()` after fitting cannot be detected. `DesignLock.to_estimator()` builds the locked estimator, so that fitting from the lock cannot drift from it. +- **Note (realized timing):** adoption dates are not reconciled. Placebo dates lie inside the diagnosed panel and real ones after it, so they cannot be equal. What carries over is the number of cohorts, the number of treated units, the length of each cohort's post window, and a balanced panel; the number of pre-periods is not reconciled. +- **Note (lock file):** `sha256` is the SHA-256 of the lock's canonical JSON (sorted keys, no whitespace, NaN not allowed). It detects accidental edits and is not a signature. `DESIGN_LOCK_SCHEMA_VERSION` is `"1.0"`; a lock with a different major version is refused on load. +- **Note (lockable configurations):** a lock must be able to rebuild the estimator exactly, so a parameter or `fit()` keyword that is not a JSON scalar, list or string-keyed mapping, or that is a non-finite number (for example `epv_threshold=inf`, or a callable `conley_metric`), is refused by `lock`. **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. @@ -7035,6 +7072,11 @@ The injected effect is constant over treated unit-periods, so `delta` is the val - [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` +- [x] Held-out rows are not read by the comparison (also for an integer outcome that pandas stores as float); default count and its refusal: `tests/test_design.py::TestHoldout` +- [x] The lock run equals a plain run of the chosen candidate on the full panel at the derived seed; only that candidate is fitted; mismatched panels are refused: `TestLock` +- [x] JSON round trip, hash check, schema version, refusal of configurations that cannot be rebuilt: `TestLockSerialization`, `TestToEstimator` +- [x] One test per reconciled item, including realized timing, panel balance and the two-group path: `TestReconcile` +- [x] Lock run of a correctly sized candidate is near nominal on serially correlated data: `tests/test_methodology_design.py::TestHeldOutRun` --- diff --git a/tests/helpers/results_foundation.py b/tests/helpers/results_foundation.py index e8be6d7d..a1c69062 100644 --- a/tests/helpers/results_foundation.py +++ b/tests/helpers/results_foundation.py @@ -27,6 +27,58 @@ from diff_diff.diagnostic_report import DiagnosticReportResults +def _design_lock() -> Any: + """A directly constructed DesignLock whose sha256 matches its fields.""" + from diff_diff.design import _lock_digest + + row = { + "label": "DifferenceInDifferences", + "power": 0.05, + "rejection_rate": 0.05, + "bias": 0.0, + "rmse": 0.11, + "coverage": 0.95, + "n_simulations": 100, + "n_simulation_failures": 0, + "true_effect": 0.0, + "size_controlled": True, + "n_nan_inference": 0, + "mde": 0.31, + } + fields: Dict[str, Any] = { + "schema_version": diff_diff.DESIGN_LOCK_SCHEMA_VERSION, + "diff_diff_version": diff_diff.__version__, + "label": "DifferenceInDifferences", + "estimator_name": "DifferenceInDifferences", + "params": {"alpha": 0.05, "cluster": None}, + "estimator_kwargs": {}, + "outcome": "y", + "unit": "unit", + "time": "period", + "first_treat": None, + "alpha": 0.05, + "target_power": 0.8, + "effect_sizes": [0.0], + "n_treated": 10, + "treatment_fraction": 0.5, + "cohort_periods": [5], + "resample_units": True, + "seed": 1, + "n_holdout": 0, + "n_units": 20, + "n_periods": 8, + "n_obs": 160, + "time_periods": [1, 2, 3, 4, 5, 6, 7, 8], + "data_sha256": "0" * 64, + "data_columns": ["period", "unit", "y"], + "comparison_results": [row], + "holdout_results": [], + "size_controlled": True, + "mde": 0.31, + } + return diff_diff.DesignLock(**fields, sha256=_lock_digest(fields)) + + def make_constructed_diagnostics() -> Dict[str, Any]: """Return {class_name: instance} for the direct-construction roster.""" rng_bins = pd.DataFrame( @@ -337,6 +389,29 @@ def make_constructed_diagnostics() -> Dict[str, Any]: n_dropped=0, data_sha256="0" * 64, data_columns=["period", "unit", "y"], + n_holdout=0, + time_periods=[1, 2, 3, 4, 5, 6, 7, 8], + ), + "DesignLock": _design_lock(), + "DesignReconciliationResults": diff_diff.DesignReconciliationResults( + status="deviates", + checks=[ + { + "item": "estimator_name", + "locked": "DifferenceInDifferences", + "realized": "DifferenceInDifferences", + "status": "match", + }, + { + "item": "params.cluster", + "locked": None, + "realized": "unit", + "status": "deviates", + }, + {"item": "n_units", "locked": 20, "realized": None, "status": "not checked"}, + ], + label="DifferenceInDifferences", + lock_sha256="0" * 64, ), "PlaceboTestResults": diff_diff.PlaceboTestResults( test_type="placebo_treatment", diff --git a/tests/test_design.py b/tests/test_design.py index b4468178..d72608f8 100644 --- a/tests/test_design.py +++ b/tests/test_design.py @@ -1,6 +1,9 @@ """Behavioural tests for diff_diff.design (diagnose_design).""" +import dataclasses import itertools +import json +import types import warnings import numpy as np @@ -8,8 +11,11 @@ import pytest from diff_diff import ( + DESIGN_LOCK_SCHEMA_VERSION, CallawaySantAnna, DesignDiagnosisResults, + DesignLock, + DesignReconciliationResults, Diagnostic, DifferenceInDifferences, EfficientDiD, @@ -23,6 +29,10 @@ ) from diff_diff.design import ( _data_fingerprint, + _encode_cell, + _failed_cell, + _json_value, + _lock_digest, _make_placebo_generator, _size_controlled, ) @@ -72,6 +82,9 @@ def run(panel, estimators, **kwargs): kwargs.setdefault("n_simulations", 20) kwargs.setdefault("seed", 11) kwargs.setdefault("progress", False) + # Held-out periods are tested in TestHoldout; everywhere else the + # comparison runs on the whole panel. + kwargs.setdefault("n_holdout", 0) return diagnose_design(panel, "y", "unit", "period", estimators, **kwargs) @@ -442,6 +455,7 @@ def test_unit_cluster_allowed_when_resampling_whatever_the_column_is_called(self # StackedDiD's cluster="unit" is a mode, not a column name. {"did": DifferenceInDifferences(cluster="store"), "stacked": StackedDiD()}, cohort_periods=[6], + n_holdout=0, treatment_fraction=0.5, n_simulations=5, seed=1, @@ -704,7 +718,10 @@ def digest(values): 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"]) + # Numbers are encoded by value, not by storage type. + assert digest([1, "b", "c", "d"]) == digest([1.0, "b", "c", "d"]) + assert digest([1, "b", "c", "d"]) != digest([1.5, "b", "c", "d"]) + assert digest([1, "b", "c", "d"]) != digest(["1", "b", "c", "d"]) assert digest([(1, 2), "b", "c", "d"]) != digest(["(1, 2)", "b", "c", "d"]) assert digest(base) == digest(list(base)) @@ -950,3 +967,744 @@ def test_fit_keyword_reaches_every_estimator(self): assert result.estimator_kwargs == {"covariates": ["x"]} for cells in result.results.values(): assert cells[0].n_simulations == 5 + + +# --------------------------------------------------------------------------- +# Held-out periods, the design lock and reconcile +# --------------------------------------------------------------------------- + +NUMERIC = ["power", "rejection_rate", "mean_estimate", "bias", "rmse", "mean_se", "coverage"] + + +def lock_seed(seed): + return int(np.random.SeedSequence([seed, 1]).generate_state(1)[0]) + + +def relock(lock, **changes): + """A lock with some fields replaced and its sha256 recomputed.""" + fields = {k: v for k, v in lock.to_dict().items() if k != "sha256"} + fields.update(changes) + return DesignLock(**fields, sha256=_lock_digest(fields)) + + +def deviating(reconciliation): + return {c["item"] for c in reconciliation.checks if c["status"] == "deviates"} + + +def statuses(reconciliation): + return {c["item"]: c["status"] for c in reconciliation.checks} + + +def analysis_frame(panel, n_new=3, cohorts=((9, range(10)),)): + """The diagnosed panel plus ``n_new`` later periods and a real adoption column.""" + last = int(panel["period"].max()) + units = np.sort(panel["unit"].unique()) + rng = np.random.default_rng(5) + later = pd.DataFrame( + { + "unit": np.repeat(units, n_new), + "period": np.tile(np.arange(last + 1, last + 1 + n_new), len(units)), + "y": rng.normal(size=len(units) * n_new), + } + ) + frame = pd.concat([panel[["unit", "period", "y"]], later], ignore_index=True) + frame["g"] = 0 + for period, members in cohorts: + frame.loc[frame["unit"].isin(list(members)), "g"] = period + return frame + + +class TestHoldout: + def test_default_is_zero_for_one_estimator(self): + result = run(make_panel(seed=70), [DifferenceInDifferences()], n_holdout=None) + assert result.n_holdout == 0 + assert result.n_periods == 8 + assert result.time_periods == list(range(1, 9)) + + def test_default_is_half_the_post_window_for_several(self): + panel = make_panel(n_periods=12, seed=71) + result = run( + panel, + [DifferenceInDifferences(), TwoWayFixedEffects()], + cohort_periods=[7], + n_holdout=None, + n_simulations=5, + ) + # Periods 7..12 are at or after adoption: 6 // 2 = 3 held out. + assert result.n_holdout == 3 + assert result.n_periods == 9 + assert result.n_obs == 20 * 9 + assert result.time_periods == list(range(1, 10)) + assert result.n_dropped == 0 + assert result.to_dict()["n_holdout"] == 3 + assert result.to_dict()["time_periods"] == list(range(1, 10)) + assert "Held-out periods:" in result.summary() + + def test_default_raises_when_adoption_is_the_final_period(self): + with pytest.raises(ValueError, match="n_holdout=0"): + run( + make_panel(seed=72), + [DifferenceInDifferences(), TwoWayFixedEffects()], + cohort_periods=[8], + n_holdout=None, + ) + + @pytest.mark.parametrize("value", [3, -1]) + def test_out_of_range_is_refused(self, value): + # Adoption at 6 on periods 1..8: at most 2 can be held out. + with pytest.raises(ValueError, match="out of range"): + run(make_panel(seed=73), [DifferenceInDifferences()], n_holdout=value) + + @pytest.mark.parametrize("value", [True, 1.0, "1"]) + def test_non_integer_is_refused(self, value): + with pytest.raises(ValueError, match="non-negative integer"): + run(make_panel(seed=73), [DifferenceInDifferences()], n_holdout=value) + + def test_numpy_integer_and_single_estimator_are_honoured(self): + result = run(make_panel(seed=74), [DifferenceInDifferences()], n_holdout=np.int64(2)) + assert result.n_holdout == 2 + assert result.time_periods == list(range(1, 7)) + + @pytest.mark.parametrize("integer_outcome", [False, True]) + def test_held_out_rows_are_not_read(self, integer_outcome): + panel = make_panel(n_periods=10, seed=75) + if integer_outcome: + panel["y"] = np.round(panel["y"] * 10).astype(int) + estimators = {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()} + kwargs = dict(cohort_periods=[6], n_holdout=2, effect_sizes=[1.0], n_simulations=8) + base = run(panel, estimators, **kwargs) + + changed = panel.copy() + held_out = changed["period"] > 8 + changed.loc[held_out, "y"] = changed.loc[held_out, "y"] + 1000 + missing = panel.copy() + missing["y"] = missing["y"].astype(float) + missing.loc[held_out, "y"] = np.nan # an integer column is now stored as float + + for other_panel in (changed, missing): + other = run(other_panel, estimators, **kwargs) + assert other.data_sha256 == base.data_sha256 + pd.testing.assert_frame_equal(other.to_dataframe(), base.to_dataframe()) + + def test_numbers_are_fingerprinted_by_value(self): + assert _encode_cell(1) == _encode_cell(1.0) == _encode_cell(np.int64(1)) + assert _encode_cell(1.5) != _encode_cell(1) + assert _encode_cell(True) != _encode_cell(1) + assert _encode_cell("1") != _encode_cell(1) + assert _encode_cell(np.inf) != _encode_cell(-np.inf) + + def test_truncation_happens_before_the_held_out_split(self): + panel = make_panel(n_periods=10, seed=76) + panel["ft"] = np.where(panel["unit"] < 5, 9, 0) + estimators = {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()} + result = run( + panel, + estimators, + cohort_periods=[5], + first_treat="ft", + n_holdout=None, + n_simulations=6, + ) + # Truncated to periods 1..8; periods 5..8 follow adoption: 2 held out. + assert result.n_dropped == 2 * 20 + assert result.n_holdout == 2 + assert result.time_periods == list(range(1, 7)) + lock = result.lock("did", data=panel, progress=False) + assert lock.time_periods == list(range(1, 9)) + assert lock.n_periods == 8 + assert lock.first_treat == "ft" + + def test_unlockable_parameter_warns_before_the_run(self): + estimator = CallawaySantAnna(epv_threshold=np.inf) + with pytest.warns(UserWarning, match="cannot be recorded in a design lock"): + result = run(make_panel(seed=77), {"cs": estimator}, n_simulations=3) + with pytest.raises(ValueError, match=r"params\.epv_threshold"): + result.lock() + + +def diagnosed(seed=80, **kwargs): + panel = make_panel(n_periods=10, seed=seed) + kwargs.setdefault("cohort_periods", [6]) + kwargs.setdefault("n_holdout", None) + kwargs.setdefault("effect_sizes", [1.0]) + kwargs.setdefault("n_simulations", 12) + estimators = kwargs.pop( + "estimators", {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()} + ) + return panel, run(panel, estimators, **kwargs) + + +class TestLock: + def test_held_out_run_needs_data(self): + _, result = diagnosed() + assert result.n_holdout == 2 + with pytest.raises(ValueError, match="pass data="): + result.lock("did") + + def test_label_rules(self): + panel, result = diagnosed() + with pytest.raises(ValueError, match="pass the label"): + result.lock(data=panel) + with pytest.raises(ValueError, match="Unknown label"): + result.lock("nope", data=panel) + single = run(make_panel(seed=81), [DifferenceInDifferences()], n_simulations=5) + assert single.lock().label == "DifferenceInDifferences" + + def test_refuses_a_panel_that_was_not_diagnosed(self): + panel, result = diagnosed() + changed = panel.copy() + changed.loc[(changed["unit"] == 3) & (changed["period"] == 2), "y"] += 1.0 + with pytest.raises(ValueError, match="not the panel that was diagnosed"): + result.lock("did", data=changed) + + def test_refuses_extra_or_missing_periods(self): + panel, result = diagnosed() + extra = pd.concat( + [panel, panel[panel["period"] == 10].assign(period=11)], ignore_index=True + ) + with pytest.raises(ValueError, match=r"other periods found: \[9, 10, 11\]"): + result.lock("did", data=extra) + with pytest.raises(ValueError, match="periods of the diagnosed panel"): + result.lock("did", data=panel[panel["period"] != 10]) + with pytest.raises(ValueError, match=r"Compared periods missing: \[4\]"): + result.lock("did", data=panel[panel["period"] != 4]) + + def test_held_out_run_is_a_plain_run_on_the_full_panel(self): + panel, result = diagnosed() + lock = result.lock("did", data=panel, progress=False) + expected = run( + panel, + {"did": DifferenceInDifferences()}, + cohort_periods=[6], + effect_sizes=[1.0], + n_simulations=12, + seed=lock_seed(result.seed), + ) + np.testing.assert_allclose( + pd.DataFrame(lock.holdout_results)[NUMERIC].to_numpy(dtype=float), + expected.to_dataframe()[NUMERIC].to_numpy(dtype=float), + rtol=1e-12, + ) + assert lock.n_holdout == 2 + assert lock.n_periods == 10 and lock.n_obs == 200 + assert lock.time_periods == list(range(1, 11)) + assert lock.data_sha256 == expected.data_sha256 + assert lock.data_sha256 != result.data_sha256 + assert lock.size_controlled == expected.size_controlled["did"] + # The comparison rows of every estimator are kept alongside. + assert [row["label"] for row in lock.comparison_results] == ["did", "did", "twfe", "twfe"] + pd.testing.assert_frame_equal(lock.to_dataframe(), pd.DataFrame(lock.holdout_results)) + # The locked rows are a different run from the comparison rows. + compared = result.to_dataframe().query("label == 'did'")[NUMERIC].to_numpy(dtype=float) + assert not np.allclose(compared, lock.to_dataframe()[NUMERIC].to_numpy(dtype=float)) + + def test_only_the_chosen_estimator_is_fitted(self, monkeypatch): + panel, result = diagnosed() + calls = {"twfe": 0} + original = TwoWayFixedEffects.fit + + def counting(self, *args, **kwargs): + calls["twfe"] += 1 + return original(self, *args, **kwargs) + + monkeypatch.setattr(TwoWayFixedEffects, "fit", counting) + result.lock("did", data=panel, progress=False) + assert calls["twfe"] == 0 + + def test_relocking_is_reproducible_and_a_second_label_warns(self): + panel, result = diagnosed() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + first = result.lock("did", data=panel, progress=False) + second = result.lock("did", data=panel, progress=False) + assert first == second + assert not [w for w in caught if "already used" in str(w.message)] + with pytest.warns(UserWarning, match="already used for \\['did'\\]"): + result.lock("twfe", data=panel, progress=False) + + def test_progress_prints_one_line_per_effect(self, capsys): + panel, result = diagnosed() + result.lock("did", data=panel) + lines = [line for line in capsys.readouterr().out.splitlines() if "lock: did" in line] + assert len(lines) == 2 + + def test_size_failing_estimator_warns_and_is_recorded(self): + _, result = diagnosed(n_holdout=0) + result.size_controlled["did"] = False + with pytest.warns(UserWarning, match="did not pass the size check"): + lock = result.lock("did") + assert lock.size_controlled is False + + def test_estimator_changed_after_the_diagnosis_is_refused(self): + _, result = diagnosed(n_holdout=0) + result.estimators["did"].set_params(cluster="unit") + with pytest.raises(ValueError, match="changed after the diagnosis"): + result.lock("did") + + @pytest.mark.parametrize("n_holdout", [0, 2]) + def test_fit_keywords_changed_after_the_diagnosis(self, n_holdout): + panel = make_panel(n_periods=10, seed=85) + panel["x"] = np.random.default_rng(2).normal(size=len(panel)) + covariates = ["x"] + result = run( + panel, + {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()}, + cohort_periods=[6], + n_holdout=n_holdout, + n_simulations=5, + estimator_kwargs={"covariates": covariates}, + ) + # The caller's own list is not the one the results keep. + covariates.clear() + assert result.estimator_kwargs == {"covariates": ["x"]} + lock = result.lock("did", data=panel, progress=False) + assert lock.estimator_kwargs == {"covariates": ["x"]} + # Editing the stored keywords is refused. + result.estimator_kwargs["covariates"].clear() + with pytest.raises(ValueError, match="estimator_kwargs was changed after"): + result.lock("did", data=panel, progress=False) + + def test_column_swapped_for_a_same_named_one_is_refused(self): + panel, _ = diagnosed() + panel[1] = np.arange(len(panel), dtype=float) + result = run( + panel, + {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()}, + cohort_periods=[6], + n_holdout=2, + n_simulations=5, + ) + lock = result.lock("did", data=panel, progress=False) + swapped = panel.copy() + swapped["1"] = swapped[1] # the diagnosed values, under a string label + swapped[1] = 0.0 # the diagnosed column, changed + with pytest.raises(ValueError, match="equal as strings"): + result.lock("did", data=swapped, progress=False) + reconciliation = lock.reconcile( + DifferenceInDifferences(), outcome="y", unit="unit", time="period", data=swapped + ) + assert statuses(reconciliation)["data_sha256"] == "deviates" + assert reconciliation.status == "deviates" + + def test_without_held_out_periods_no_data_is_needed(self): + panel = make_panel(seed=82) + # A calendar with gaps cannot be rebuilt from a period count. + panel["period"] = panel["period"].map(dict(zip(range(1, 9), [1, 2, 4, 5, 7, 8, 10, 11]))) + result = run(panel, [DifferenceInDifferences()], cohort_periods=[8], n_simulations=6) + lock = result.lock(progress=False) + assert lock.n_holdout == 0 + assert lock.holdout_results == [] + assert lock.time_periods == [1, 2, 4, 5, 7, 8, 10, 11] + assert lock.data_sha256 == result.data_sha256 + assert "not confirmed on held-out periods" in lock.summary() + pd.testing.assert_frame_equal( + lock.to_dataframe()[NUMERIC], result.to_dataframe()[NUMERIC], check_dtype=False + ) + # data is optional here, but it is still verified when given. + assert result.lock(data=panel) == lock + changed = panel.copy() + changed.loc[0, "y"] += 1.0 + with pytest.raises(ValueError, match="not the panel that was diagnosed"): + result.lock(data=changed) + + def test_non_string_column_label_locks_and_reconciles(self): + panel, _ = diagnosed() + panel[1] = 0.5 + result = run( + panel, + {"did": DifferenceInDifferences(), "twfe": TwoWayFixedEffects()}, + cohort_periods=[6], + n_holdout=2, + n_simulations=5, + ) + assert result.data_columns == ["1", "period", "unit", "y"] + lock = result.lock("did", data=panel, progress=False) + reconciliation = lock.reconcile( + DifferenceInDifferences(), outcome="y", unit="unit", time="period", data=panel + ) + assert statuses(reconciliation)["data_sha256"] == "match" + + def test_contract(self): + panel, result = diagnosed() + lock = result.lock("did", data=panel, progress=False) + assert isinstance(lock, Diagnostic) + for name in ("att", "se", "t_stat", "p_value", "conf_int"): + assert not hasattr(lock, name) + with pytest.raises(dataclasses.FrozenInstanceError): + lock.label = "twfe" + assert lock.label == "did" and lock.estimator_name == "DifferenceInDifferences" + assert lock.params == _json_value(DifferenceInDifferences().get_params(), "params") + assert lock.schema_version == DESIGN_LOCK_SCHEMA_VERSION == "1.0" + text = lock.summary() + assert "did (DifferenceInDifferences)" in text and lock.sha256 in text + assert "held-out run" in text + assert repr(lock).startswith("DesignLock(label='did'") + + +class TestLockSerialization: + def lock(self, **kwargs): + panel, result = diagnosed(**kwargs) + return result.lock("did", data=panel, progress=False) + + def test_json_round_trip(self): + lock = self.lock() + text = lock.to_json() + assert DesignLock.from_json(text) == lock + assert DesignLock.from_dict(lock.to_dict()) == lock + payload = json.loads(text) + assert payload["schema_version"] == DESIGN_LOCK_SCHEMA_VERSION + assert set(payload) == {f.name for f in dataclasses.fields(DesignLock)} + # to_dict returns copies. + lock.to_dict()["params"]["alpha"] = 0.5 + assert lock.params["alpha"] == 0.05 + + def test_edited_file_fails_the_hash(self): + payload = self.lock().to_dict() + payload["n_treated"] += 1 + with pytest.raises(ValueError, match="does not match its sha256"): + DesignLock.from_dict(payload) + with pytest.raises(ValueError, match="does not match its sha256"): + DesignLock.from_json(json.dumps(payload)) + + def test_unknown_missing_and_unsupported(self): + payload = self.lock().to_dict() + with pytest.raises(ValueError, match=r"unknown key\(s\) \['extra'\]"): + DesignLock.from_dict({**payload, "extra": 1}) + with pytest.raises(ValueError, match=r"missing key\(s\) \['seed'\]"): + DesignLock.from_dict({k: v for k, v in payload.items() if k != "seed"}) + with pytest.raises(ValueError, match="schema version '2.0' is not supported"): + DesignLock.from_dict({**payload, "schema_version": "2.0"}) + with pytest.raises(TypeError, match="dictionary"): + DesignLock.from_dict([1, 2]) + + def test_unreported_mde_is_none(self): + lock = self.lock() # no power= target, so no MDE search ran + assert lock.mde is None + assert DesignLock.from_json(lock.to_json()).mde is None + assert all(row["mde"] is None for row in lock.comparison_results) + + def test_reported_mde_round_trips(self): + panel = make_panel(n_units=40, n_periods=10, noise=0.2, seed=83) + result = run( + panel, + {"did": DifferenceInDifferences(cluster="unit"), "twfe": TwoWayFixedEffects()}, + cohort_periods=[6], + n_holdout=None, + n_simulations=30, + power=0.8, + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + lock = result.lock("twfe", data=panel, progress=False) + if lock.size_controlled: + assert lock.mde is not None and lock.mde > 0 + assert DesignLock.from_json(lock.to_json()) == lock + + def test_cell_that_could_not_be_scored_round_trips(self): + _, result = diagnosed(n_holdout=0) + result.results["did"][1] = _failed_cell(1.0, 0.05, "DifferenceInDifferences", 12) + lock = result.lock("did") + failed = lock.comparison_results[1] + for name in ("power", "power_ci_lower", "power_ci_upper", "bias", "rmse", "coverage"): + assert failed[name] is None + assert failed["n_simulations"] == 0 and failed["n_simulation_failures"] == 12 + assert DesignLock.from_json(lock.to_json()) == lock + assert "-" in lock.summary() + + def test_callable_parameter_is_refused(self): + estimator = DifferenceInDifferences(conley_metric=lambda a, b: np.zeros((len(a), len(b)))) + with pytest.warns(UserWarning, match="cannot be recorded in a design lock"): + result = run(make_panel(seed=84), {"did": estimator}, n_simulations=3) + with pytest.raises(ValueError, match=r"params\.conley_metric holds a function"): + result.lock() + + def test_editing_a_lock_in_place_is_caught(self): + lock = self.lock() + lock.params["cluster"] = "unit" + with pytest.raises(ValueError, match="edited after it was made"): + lock.to_estimator() + with pytest.raises(ValueError, match="edited after it was made"): + lock.reconcile(DifferenceInDifferences(), outcome="y", unit="unit", time="period") + + +class TestToEstimator: + @pytest.mark.parametrize( + "estimator", + [ + DifferenceInDifferences(cluster="unit"), + TwoWayFixedEffects(), + CallawaySantAnna(control_group="not_yet_treated"), + SunAbraham(), + ImputationDiD(), + TwoStageDiD(), + StackedDiD(kappa_pre=2), + EfficientDiD(), + ], + ids=lambda est: type(est).__name__, + ) + def test_rebuilds_the_locked_estimator(self, estimator): + _, result = diagnosed(n_holdout=0, n_simulations=3) + params = _json_value(estimator.get_params(), "params") + lock = relock( + result.lock("did", progress=False), + estimator_name=type(estimator).__name__, + params=params, + ) + built = lock.to_estimator() + assert type(built) is type(estimator) + assert not getattr(built, "is_fitted_", False) + assert _json_value(built.get_params(), "params") == params + reconciliation = lock.reconcile(built, outcome="y", unit="unit", time="period") + assert reconciliation.status == "pre-specified" + assert not deviating(reconciliation) + + def test_unsupported_class_name_is_refused(self): + _, result = diagnosed(n_holdout=0, n_simulations=3) + lock = relock(result.lock("did", progress=False), estimator_name="SyntheticDiD") + with pytest.raises(ValueError, match="not one of"): + lock.to_estimator() + + +@pytest.fixture(scope="module") +def staggered(): + """A diagnosed panel and the lock of a staggered-API estimator on it.""" + panel = make_panel(seed=90) + lock = run( + panel, {"cs": CallawaySantAnna()}, cohort_periods=[6], n_treated=10, n_simulations=4 + ).lock(progress=False) + return panel, lock + + +@pytest.fixture(scope="module") +def two_group(): + """An analysis frame with 0/1 group and post columns, and a DiD lock.""" + panel = make_panel(seed=91) + lock = run( + panel, + {"did": DifferenceInDifferences()}, + cohort_periods=[6], + n_treated=10, + n_simulations=4, + ).lock(progress=False) + frame = analysis_frame(panel) + frame["treated"] = (frame["unit"] < 10).astype(int) + frame["post"] = (frame["period"] >= 9).astype(int) + return frame, lock + + +class TestReconcile: + DATA = ("data_sha256", "n_units", "is_balanced", "n_treated", "n_cohorts", "n_post_by_cohort") + + def reconcile(self, lock, estimator=None, **kwargs): + estimator = CallawaySantAnna() if estimator is None else estimator + kwargs.setdefault("outcome", "y") + kwargs.setdefault("unit", "unit") + kwargs.setdefault("time", "period") + return lock.reconcile(estimator, **kwargs) + + def test_matching_analysis_is_pre_specified(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + estimator = lock.to_estimator() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fit = estimator.fit(frame, outcome="y", unit="unit", time="period", first_treat="g") + reconciliation = self.reconcile(lock, estimator, first_treat="g", data=frame, results=fit) + assert reconciliation.status == "pre-specified" + assert set(statuses(reconciliation).values()) == {"match"} + assert reconciliation.label == "cs" + assert reconciliation.lock_sha256 == lock.sha256 + assert isinstance(reconciliation, DesignReconciliationResults) + assert isinstance(reconciliation, Diagnostic) + + def test_never_treated_coded_inf_is_not_a_cohort(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + frame["g"] = frame["g"].astype(float).replace(0.0, np.inf) + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + assert reconciliation.status == "pre-specified" + + def test_estimator_class(self, staggered): + _, lock = staggered + reconciliation = self.reconcile(lock, SunAbraham()) + assert reconciliation.status == "deviates" + assert "estimator_name" in deviating(reconciliation) + + def test_one_parameter(self, staggered): + _, lock = staggered + reconciliation = self.reconcile(lock, CallawaySantAnna(control_group="not_yet_treated")) + assert deviating(reconciliation) == {"params.control_group"} + assert reconciliation.status == "deviates" + + def test_fit_keyword(self, staggered): + _, lock = staggered + reconciliation = self.reconcile(lock, estimator_kwargs={"covariates": ["x"]}) + assert deviating(reconciliation) == {"estimator_kwargs.covariates"} + + def test_column_name(self, staggered): + _, lock = staggered + assert deviating(self.reconcile(lock, outcome="sales")) == {"outcome"} + + def test_alpha_on_results(self, staggered): + _, lock = staggered + estimator = CallawaySantAnna() + estimator.results_ = types.SimpleNamespace(alpha=0.10) + reconciliation = self.reconcile(lock, estimator, results=estimator.results_) + assert deviating(reconciliation) == {"alpha"} + assert statuses(self.reconcile(lock))["alpha"] == "not checked" + + def test_results_of_another_estimator_are_refused(self, staggered): + _, lock = staggered + with pytest.raises(ValueError, match="not this estimator's results_"): + self.reconcile(lock, results=types.SimpleNamespace(alpha=0.05)) + + def test_changed_pre_period_data(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + frame.loc[(frame["unit"] == 4) & (frame["period"] == 3), "y"] += 1.0 + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + assert deviating(reconciliation) == {"data_sha256"} + + def test_unit_count(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + frame = frame[frame["unit"] != 19] + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + # The dropped unit's diagnosed rows are gone too. + assert deviating(reconciliation) == {"n_units", "data_sha256"} + + def test_treated_count(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel, cohorts=((9, range(9)),)) + assert deviating(self.reconcile(lock, first_treat="g", data=frame)) == {"n_treated"} + + def test_cohort_count(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel, cohorts=((9, range(5)), (10, range(5, 10)))) + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + # One more cohort also means one more post window. + assert deviating(reconciliation) == {"n_cohorts", "n_post_by_cohort"} + rows = {c["item"]: c for c in reconciliation.checks} + assert rows["n_post_by_cohort"]["locked"] == [3] + assert rows["n_post_by_cohort"]["realized"] == [3, 2] + + def test_post_window_length(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel, n_new=4) + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + assert deviating(reconciliation) == {"n_post_by_cohort"} + + def test_lost_follow_up_shows_as_unbalanced(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + frame = frame[~((frame["unit"] < 10) & (frame["period"] == 11))] + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + assert deviating(reconciliation) == {"is_balanced"} + + def test_adoption_varying_within_unit(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + frame.loc[(frame["unit"] == 0) & (frame["period"] < 5), "g"] = 0 + reconciliation = self.reconcile(lock, first_treat="g", data=frame) + assert deviating(reconciliation) == {"n_treated", "n_cohorts", "n_post_by_cohort"} + rows = {c["item"]: c for c in reconciliation.checks} + assert rows["n_treated"]["realized"] == "varies within unit" + + def test_missing_columns_deviate_and_do_not_raise(self, staggered): + panel, lock = staggered + frame = analysis_frame(panel) + reconciliation = self.reconcile(lock, first_treat="nope", data=frame) + assert deviating(reconciliation) == {"n_treated", "n_cohorts", "n_post_by_cohort"} + reconciliation = self.reconcile(lock, data=frame.drop(columns="y")) + assert deviating(reconciliation) == {"data_sha256"} + reconciliation = self.reconcile(lock, unit="store", data=frame) + assert deviating(reconciliation) == {"unit", "n_units", "is_balanced"} + + def test_what_is_not_checked(self, staggered): + panel, lock = staggered + without_data = statuses(self.reconcile(lock)) + assert all(without_data[item] == "not checked" for item in self.DATA) + assert self.reconcile(lock).status == "pre-specified" + with_data = statuses(self.reconcile(lock, data=analysis_frame(panel))) + for item in ("n_treated", "n_cohorts", "n_post_by_cohort"): + assert with_data[item] == "not checked" + for item in ("data_sha256", "n_units", "is_balanced"): + assert with_data[item] == "match" + + def test_integer_outcome_stored_as_float_still_matches(self): + panel = make_panel(seed=92) + panel["y"] = np.round(panel["y"] * 10).astype(int) + lock = run(panel, [DifferenceInDifferences()], n_simulations=3).lock(progress=False) + frame = analysis_frame(panel) + frame.loc[frame["period"] > 8, "y"] = np.nan + assert frame["y"].dtype == float + reconciliation = self.reconcile(lock, DifferenceInDifferences(), data=frame) + assert statuses(reconciliation)["data_sha256"] == "match" + + def test_unserializable_realized_parameter_deviates(self, staggered, two_group): + _, lock = staggered + reconciliation = self.reconcile(lock, CallawaySantAnna(epv_threshold=np.inf)) + assert deviating(reconciliation) == {"params.epv_threshold"} + rows = {c["item"]: c for c in reconciliation.checks} + assert rows["params.epv_threshold"]["realized"] == "inf" + _, did_lock = two_group + estimator = DifferenceInDifferences(conley_metric=lambda a, b: None) + assert deviating(self.reconcile(did_lock, estimator)) == {"params.conley_metric"} + + def test_two_group_design(self, two_group): + frame, lock = two_group + estimator = DifferenceInDifferences() + reconciliation = self.reconcile( + lock, estimator, treatment="treated", post="post", data=frame + ) + assert reconciliation.status == "pre-specified" + assert not [s for s in statuses(reconciliation).values() if s == "deviates"] + without_post = statuses(self.reconcile(lock, estimator, treatment="treated", data=frame)) + assert without_post["n_post_by_cohort"] == "not checked" + assert without_post["n_treated"] == "match" + + def test_two_group_structure(self, two_group): + frame, lock = two_group + estimator = DifferenceInDifferences() + varying = frame.copy() + varying.loc[(varying["unit"] == 0) & (varying["period"] < 9), "treated"] = 0 + reconciliation = self.reconcile( + lock, estimator, treatment="treated", post="post", data=varying + ) + assert deviating(reconciliation) == {"n_treated", "n_cohorts"} + staggered_post = frame.copy() + staggered_post.loc[ + (staggered_post["unit"] == 0) & (staggered_post["period"] == 9), "post" + ] = 0 + reconciliation = self.reconcile( + lock, estimator, treatment="treated", post="post", data=staggered_post + ) + assert deviating(reconciliation) == {"n_post_by_cohort"} + rows = {c["item"]: c for c in reconciliation.checks} + assert rows["n_post_by_cohort"]["realized"] == "varies within period" + + def test_argument_rules(self, two_group): + frame, lock = two_group + with pytest.raises(ValueError, match="not both"): + self.reconcile(lock, first_treat="g", treatment="treated", data=frame) + with pytest.raises(TypeError, match="estimator instance"): + self.reconcile(lock, "DifferenceInDifferences") + with pytest.raises(TypeError, match="DataFrame"): + self.reconcile(lock, DifferenceInDifferences(), data=[1, 2]) + + def test_results_contract(self, staggered): + _, lock = staggered + reconciliation = self.reconcile(lock, CallawaySantAnna(control_group="not_yet_treated")) + frame = reconciliation.to_dataframe() + assert list(frame.columns) == ["item", "locked", "realized", "status"] + assert len(frame) == len(reconciliation.checks) + assert frame.loc[0, "item"] == "estimator_name" + as_dict = reconciliation.to_dict() + assert as_dict["status"] == "deviates" and as_dict["lock_sha256"] == lock.sha256 + json.dumps(as_dict) + text = reconciliation.summary() + assert "deviates" in text and "params.control_group" in text + assert "1 deviate" in text + assert repr(reconciliation).startswith("DesignReconciliationResults(status='deviates'") + for name in ("att", "se", "t_stat", "p_value", "conf_int"): + assert not hasattr(reconciliation, name) diff --git a/tests/test_diagnostic_marker.py b/tests/test_diagnostic_marker.py index d96a363a..471fbb3e 100644 --- a/tests/test_diagnostic_marker.py +++ b/tests/test_diagnostic_marker.py @@ -42,6 +42,8 @@ "SimulationMDEResults", "SimulationSampleSizeResults", "DesignDiagnosisResults", + "DesignLock", + "DesignReconciliationResults", "PlaceboTestResults", "QUGTestResults", "StuteTestResults", @@ -166,8 +168,8 @@ def test_twfe_weights_result_is_neither(): def test_frozen_diagnostic_constructs(constructed): - # DiagnosticReportResults is the only frozen roster member; pin that - # frozen-dataclass + non-dataclass marker inheritance is safe. + # DiagnosticReportResults and DesignLock are the frozen roster members; + # pin that frozen-dataclass + non-dataclass marker inheritance is safe. drr = constructed["DiagnosticReportResults"] assert isinstance(drr, DiagnosticReportResults) assert isinstance(drr, Diagnostic) diff --git a/tests/test_methodology_design.py b/tests/test_methodology_design.py index 699e3ac8..d5b94c1a 100644 --- a/tests/test_methodology_design.py +++ b/tests/test_methodology_design.py @@ -48,6 +48,7 @@ def ar1_panel(n_units, n_periods, rho, seed, unit_sd=1.0): def diagnose(panel, estimators, **kwargs): kwargs.setdefault("seed", 7) kwargs.setdefault("progress", False) + kwargs.setdefault("n_holdout", 0) with warnings.catch_warnings(): warnings.simplefilter("ignore") return diagnose_design(panel, "y", "unit", "period", estimators, **kwargs) @@ -223,3 +224,57 @@ def test_staggered_declaration_draws_each_unit_from_the_declared_periods(self): 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 + + +@pytest.fixture(scope="module") +def locked(): + """The AR(1) comparison with held-out periods, and the lock of one variant.""" + panel = ar1_panel(50, 21, 0.8, seed=1) + result = diagnose( + panel, + { + "twfe_classical": TwoWayFixedEffects(vcov_type="classical"), + "twfe_clustered": TwoWayFixedEffects(), + }, + cohort_periods=[11], + treatment_fraction=0.5, + effect_sizes=[0.5], + n_simulations=300, + n_holdout=None, + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + lock = result.lock("twfe_clustered", data=panel, progress=False) + return result, lock + + +class TestHeldOutRun: + """Library choice (REGISTRY ``## DesignDiagnosis``, held-out periods). + + The comparison leaves the last periods unread; the lock reruns the chosen + estimator with them, on fresh placebo draws. Nothing here validates how + much winner's-curse inflation that removes; the tests pin that the lock + run is a correctly sized, separate run of the declared design. + """ + + def test_default_holds_out_half_the_post_window(self, locked): + result, lock = locked + # Periods 11..21 follow adoption: 11 // 2 = 5 held out of the comparison. + assert result.n_holdout == 5 + assert result.n_periods == 16 + assert lock.n_periods == 21 + + def test_lock_run_of_a_correctly_sized_estimator_is_near_nominal(self, locked): + _, lock = locked + null = lock.holdout_results[0] + assert null["true_effect"] == 0.0 + assert null["rejection_rate"] < 0.12 + assert lock.size_controlled is True + + def test_lock_run_is_separate_from_the_comparison(self, locked): + result, lock = locked + compared = result.results["twfe_clustered"] + for cell, row in zip(compared, lock.holdout_results): + assert row["true_effect"] == cell.true_effect + assert row["mean_estimate"] != cell.mean_estimate + assert row["n_simulations"] == cell.n_simulations diff --git a/tests/test_naming_guard.py b/tests/test_naming_guard.py index d0dc1826..5ec60de5 100644 --- a/tests/test_naming_guard.py +++ b/tests/test_naming_guard.py @@ -516,6 +516,10 @@ def _build_rowed_index(): # diagnose_design takes the calendar period column, and its results # container echoes that column name. "DesignDiagnosisResults.time", + # The design lock echoes that column name, and reconcile takes the + # calendar column of the analysis. + "DesignLock.reconcile[time]", + "DesignLock.time", "DurationDiD.fit[time]", "ChangesInChanges.fit[time]", "ContinuousDiD.fit[time]", @@ -582,6 +586,10 @@ def _build_rowed_index(): ) for fn in ("simulate_power", "simulate_mde", "simulate_sample_size") }, + "DesignLock.reconcile[estimator]": ( + "the estimator INSTANCE used for the analysis, as in the power API; " + "unrelated to CiC's results method tag (M-143)" + ), **{f"{cls}.groups": _CS_COHORT for cls in _CS_GROUPS_CLASSES}, "GroupTimeEffect.group": _CS_COHORT, "HADPretestReport.aggregate": (