Skip to content

feat(design): diagnose_design - size and power of candidate estimators on your own untreated panel - #898

Merged
igerber merged 3 commits into
mainfrom
feat/design-diagnosis
Nov 23, 2026
Merged

igerber merged 3 commits into
mainfrom
feat/design-diagnosis

Conversation

@igerber

@igerber igerber commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

Add diagnose_design, the first design-stage tool: before analysing a study, check how each candidate estimator behaves on the panel that will actually be used.

  • What it does. On an untreated panel it repeatedly assigns placebo treatments that follow a declared design (number of treated units, planned adoption period or periods), optionally adds a known effect to the placebo-treated observations, and fits every listed estimator on the same placebo draws. It returns a DesignDiagnosisResults with, per estimator, the rejection rate under no effect (size) and the power, bias, RMSE and coverage at each injected effect, plus an optional minimum detectable effect.
  • Outcome-blind. No real treatment effect is estimated. With first_treat=, every period from the earliest real adoption onward is dropped before anything else.
  • No ranking. Estimators come back in input order. size_controlled flags those whose no-effect rejection rate is consistent with alpha and that lost at most 10% of their replicates; no minimum detectable effect is reported for the others.
  • Scope. DifferenceInDifferences, TwoWayFixedEffects, CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, EfficientDiD; absorbing binary treatment; common or staggered timing.
  • Reuse. New module diff_diff/design.py. It drives simulate_power and simulate_mde unchanged, through their existing data_generator hook, and returns existing SimulationPowerResults / SimulationMDEResults objects. diff_diff/power.py is not modified.
  • New public names: the function diagnose_design, the results class DesignDiagnosisResults (fields results, mde_results, estimators, size_controlled, n_nan_inference, mde, data_sha256, data_columns, n_dropped, plus echoed arguments), and the arguments estimators and resample_units. Every other argument and field reuses an existing spelling with its existing meaning (cohort_periods, treatment_fraction, n_treated, effect_sizes, n_simulations, alpha, power, first_treat, estimator_kwargs, seed, progress, target_power).
  • Refused configurations (each with a message saying why): a non-zero anticipation; an estimator alpha different from the function's; DifferenceInDifferences / TwoWayFixedEffects under a staggered declaration; vcov_type="conley" (those two estimators take the Conley time dimension from the 0/1 post indicator, which is wrong on a multi-period placebo panel); with resample_units=True, a cluster column other than the unit column (copies of a resampled unit would share a cluster); unbalanced panels, missing outcomes and a non-numeric calendar column.
  • Failure policy. Programming errors propagate. An estimator that cannot produce a finite fit on any of the first five placebo replicates is refused before the run. After that, a replicate that raises a data-dependent error or returns non-finite inference is excluded from every rate and counted.
  • Follow-ups (tracked): the design lock and held-out periods are the next PR and are intended to ship in the same release; the tutorial follows with them.

Methodology references (required if estimator / math changes)

  • Method name(s): design diagnosis by placebo assignment on real untreated data with additive effect injection (diagnose_design).
  • Paper / source link(s):
    • Bertrand, M., Duflo, E., & Mullainathan, S. (2004). How Much Should We Trust Differences-in-Differences Estimates? QJE 119(1), 249-275. https://doi.org/10.1162/003355304772839588 (placebo assignment on real data, unit resampling, rejection rates, effect injection)
    • Mizushima, Y., & Powell, D. (2025). Inference with Modern Difference-in-Differences Methods. SSRN 5221387. https://papers.ssrn.com/sol3/papers.cfm?abstract_id=5221387 (staggered placebos)
    • Coglianese, J., & Fang, J. A. (2026). An Evaluation of Difference-in-Differences Methods Using Placebo Event Studies. FEDS 2026-045. https://doi.org/10.17016/FEDS.2026.045 (several estimators on the same placebo events)
    • Blair, G., Cooper, J., Coppock, A., & Humphreys, M. (2019). Declaring and Diagnosing Research Designs. APSR 113(3), 838-859. https://doi.org/10.1017/S0003055419000194 (diagnosands)
    • Paper reviews for all four are under docs/methodology/papers/.
  • Any intentional deviations from the source (and why): documented as Notes in the new REGISTRY section ## DesignDiagnosis. The ones with no paper source: the size check and its 10% lost-replicate condition; the minimum detectable effect on real data (bisection via simulate_mde, bracket seeded from the estimator's own no-effect spread); the two-pre-period minimum; the data fingerprint. Differences from a source: RMSE is the existing ddof = 1 form, not Blair et al.'s root mean squared error; adoption periods are declared, where Bertrand et al.'s main design draws the year at random; a fit with non-finite inference is excluded from the rates, where simulate_power alone counts it as a non-rejection.

Validation

  • Tests added/updated: tests/test_design.py (104 tests: effect recovery for all eight estimators, shared placebo draws, exact enumeration of all assignments on a six-unit panel, the outcome-blind truncation, every refusal, the failure policy via call-counted stubs, size-check boundaries, the fingerprint, warning handling, the results contract, the minimum detectable effect) and tests/test_methodology_design.py (14 tests). tests/test_diagnostic_marker.py and tests/helpers/results_foundation.py enrol the new results class; tests/test_naming_guard.py registers the two new calendar-column surfaces.
  • Paper-shaped checks on simulated panels (the papers' own CPS tables are not reproduced):
    • Serial correlation (AR(1), rho = 0.8, 50 units x 21 periods, 300 placebo draws): TwoWayFixedEffects(vcov_type="classical") rejects a true null above 25% and fails the size check; the default unit-clustered fit is below 12% and passes.
    • Few treated units (40 units x 12 periods): with 2 treated units CallawaySantAnna, ImputationDiD and SunAbraham each reject above 15%; with 20 treated units each is below 12%.
    • For a correctly sized test the minimum detectable effect is within 25% of (z_0.975 + z_0.80) times the spread of the no-effect estimates.
  • Executed locally: pytest tests/test_design.py tests/test_methodology_design.py on the Rust backend and with DIFF_DIFF_BACKEND=python - 118 passed on each. pytest tests/test_power.py - passed (unchanged module). pytest tests/test_naming_guard.py tests/test_diagnostic_marker.py tests/test_v4_diagnostic_family_docs.py tests/test_doc_deps_integrity.py tests/test_docs_ia.py tests/test_changelog_fragments.py tests/test_tracking_files.py - passed. black --check and ruff check clean. mypy diff_diff/design.py clean. The Sphinx HTML build with warnings as errors (-W, same dependency set as the docs workflow) completes with no warnings.
  • Not validated: there is no R parity target (DeclareDesign diagnoses simulated designs, not placebo assignment on a user's panel).
  • Backtest / simulation / notebook evidence (if applicable): the simulated-panel checks above; no notebook in this PR.

Security / privacy

  • Confirm no secrets/PII in this PR: Yes.

Changelog

  • changelog.d/ fragment added (or N/A - no user-visible change): Yes

…s on your own untreated panel

Add diff_diff/design.py with diagnose_design and DesignDiagnosisResults.
On an untreated panel it repeatedly assigns placebo treatments that follow
a declared design, optionally injects a known effect, fits every listed
estimator on the same placebo draws through simulate_power, and reports
each estimator's rejection rate under no effect, its power, bias, RMSE and
coverage at each injected effect, and an optional minimum detectable
effect. Outcome-blind; estimators are returned in input order and never
ranked.

Methodology and the choices without a paper source are documented in
REGISTRY ## DesignDiagnosis.
@github-actions

Copy link
Copy Markdown

Overall assessment: ⛔ Blocker

Executive summary

  • P0: Common-timing Conley fits use the generated post indicator as their calendar, producing incorrect covariance calculations.
  • P1: Nullable first-treatment columns containing pd.NA fail before truncation.
  • The placebo assignment, resampling, effect injection, and shared draws align with the cited source reviews. Documented registry choices are accepted.
  • Static syntax checks passed. Runtime tests could not run because NumPy is unavailable.

Methodology

P0 — Conley inference loses the calendar period
Location: diff_diff/design.py:L857-L867

Impact: The common-timing adapter supplies _placebo_post without preserving the calendar for covariance estimation. Both underlying estimators derive Conley’s time array from this post column (diff_diff/estimators.py:L725, diff_diff/twfe.py:L691).

Consequently, observations from different years within the same pre/post window enter the spatial sandwich as contemporaneous observations. With conley_lag_cutoff=1, periods 1 and 8 can also receive a temporal weight of 0.5 because their post indicators differ by one.

This contradicts the within-calendar-period spatial sum and period-distance serial kernel in docs/methodology/REGISTRY.md:L7514-L7527. It can silently produce incorrect SEs and confidence intervals, contaminating size, power, coverage, and MDE diagnostics. No registry note documents this exception.

Concrete fix: Refuse vcov_type="conley" for DifferenceInDifferences and static TwoWayFixedEffects in diagnose_design until their covariance calculation can receive the actual calendar separately.

P3 — Documented methodological choices are accepted
Location: docs/methodology/REGISTRY.md:L7008-L7023

Impact: The size gate, failed-fit exclusion, MDE search, RMSE convention, and declared adoption dates intentionally differ from—or extend—the sources.

Concrete fix: None required. These choices are explicitly documented.

The source cross-check used the registry, estimator references, and repository paper reviews, including BDM’s whole-unit resampling and additive injection, Mizushima–Powell’s staggered assignments, Coglianese–Fang’s shared events, and Blair et al.’s diagnosands. Primary PDFs were unavailable locally.

Code Quality

P1 — Nullable first-treatment values are not converted safely
Location: diff_diff/design.py:L674-L681

Impact: A numeric pandas nullable column such as Int64 containing pd.NA passes the dtype check, but to_numpy(dtype=float) raises on supported pandas versions without an explicit missing-value replacement. Valid never-treated observations therefore prevent diagnosis from running.

Concrete fix: Use to_numpy(dtype=float, na_value=np.nan) before identifying adoption dates.

Performance

No additional findings.

Maintainability

No additional findings.

Tech Debt

P3 — Scope limitations and tutorial work are tracked
Locations: added rows in TODO.md and DEFERRED.md.

Impact: Unbalanced panels, additional calendar types, anticipation support, and the full tutorial remain unavailable or deferred.

Concrete fix: None required for this PR; these limitations are tracked and unsupported paths are refused.

Security

No findings in the reviewed changes.

Documentation/Tests

The changelog fragment is present. Existing tests cover shared draws, recovery, truncation, and failure handling, but the Conley test checks successful fitting rather than covariance correctness (tests/test_design.py:L889-L908). Never-treated encoding tests cover ordinary floating NaN, not nullable numeric columns.

Static syntax checks passed for all seven changed Python files. Runtime validation stopped at ModuleNotFoundError: numpy; the reported pytest results were not independently verified.

Path to Approval

  1. Add an early refusal for common-timing Conley candidates. Test both DifferenceInDifferences and TwoWayFixedEffects on a balanced multi-period panel with conley_lag_cutoff=0 and 1.
  2. Convert nullable first-treatment values with na_value=np.nan. Add parametrized Int64/Float64 tests containing adoption period 8 and pd.NA; verify truncation excludes periods 8 onward and matches an equivalent ordinary-float column.
  3. Run tests/test_design.py and tests/test_methodology_design.py after these fixes.

…lable first_treat and calendar columns explicitly

DifferenceInDifferences and static TwoWayFixedEffects take the Conley
time dimension from the 0/1 post indicator, so on a multi-period placebo
panel the spatial and serial terms would treat each pre/post window as one
period. Refuse vcov_type='conley' candidates up front.

A nullable first_treat column that marks never-treated units with pd.NA
is now converted with an explicit missing value, and a nullable integer
calendar column is read as a plain array.
@github-actions

Copy link
Copy Markdown

🔁 AI review rerun (requested by @igerber)

Head SHA: 7aa14059da6c8ba92376c7df75ff4a815eb4f4ab


Overall assessment: ✅ Looks good

Both prior blocking findings are addressed. No unmitigated P0 or P1 findings remain within this re-review’s scope.

Executive summary

  • Conley candidates are refused before fitting, resolving the prior P0.
  • Nullable first-treatment columns now handle pd.NA, resolving the prior P1.
  • Regression tests cover both fixes.
  • Documented methodology choices and tracked limitations remain acceptable.
  • Syntax checks passed; runtime tests could not run because this environment lacks pytest and NumPy.

Methodology

Prior P0 — Resolved: Conley inference loses the calendar period
Location: diff_diff/design.py:L605-L612

Impact: The early refusal prevents size, power, coverage and MDE calculations from using an incorrect Conley calendar. Tests cover both affected estimators, lag cutoffs 0/1 and both resampling modes (tests/test_design.py:L916-L939).

Concrete fix: None remaining.

P3 — Informational: documented methodology choices accepted
Location: docs/methodology/REGISTRY.md:L7007-L7022

Impact: The size gate, failed-fit exclusion, MDE procedure, RMSE convention and declared adoption dates are explicitly documented choices. Cross-checking the registry, docstrings and repository reviews of BDM, Mizushima–Powell, Coglianese–Fang and Blair et al. identified no additional undocumented mismatch. Primary PDFs were unavailable locally.

Concrete fix: None required.

Code Quality

Prior P1 — Resolved: nullable first-treatment conversion
Location: diff_diff/design.py:L681-L706

Impact: to_numpy(dtype=float, na_value=np.nan) safely converts nullable never-treated values before determining adoption dates. Parametrized Int64/Float64 tests verify truncation at period 8 and equivalent estimates against ordinary floating-point input (tests/test_design.py::TestOutcomeBlindGuard::test_nullable_first_treat_with_pd_na).

Concrete fix: None remaining.

Performance

No additional findings within the re-review scope.

Maintainability

No additional findings within the re-review scope.

Tech Debt

P3 — Informational: limitations and tutorial work are tracked
Locations: TODO.md:L24-L26, TODO.md:L90, DEFERRED.md:L22, DEFERRED.md:L85

Impact: Unsupported configurations are refused, while survey support, broader panel/calendar support and tutorial work have tracking entries.

Concrete fix: None required for this PR.

Security

No findings in the reviewed changes.

Documentation/Tests

The required changelog fragment is present at changelog.d/20261122-design-diagnosis.md. Documentation records the Conley refusal, and regression tests address both previous findings.

Syntax compilation passed for all seven changed Python files. Attempting the two design test suites stopped because pytest is unavailable; NumPy is also missing. The PR’s reported runtime results were therefore not independently verified.

@igerber igerber added the ready-for-ci Triggers CI test workflows label Nov 23, 2026
@igerber
igerber merged commit 8190dfc into main Nov 23, 2026
43 of 44 checks passed
@igerber
igerber deleted the feat/design-diagnosis branch November 23, 2026 02:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ci Triggers CI test workflows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant