From 2bddb4c9777f29bc0b2545d0e2d4ebaf3d396ad1 Mon Sep 17 00:00:00 2001 From: igerber Date: Thu, 26 Nov 2026 14:25:06 -0500 Subject: [PATCH] fix(design): align the unreleased design-stage API before release Every name changed here was introduced after 4.0.0. - DesignDiagnosisResults.results -> power_results (and the to_dict() key). `results` also names the fitted model on DesignReconciliationResults, which keeps it; the new name sits beside mde_results and event_study_results. - The reconciliation check status "not checked" -> "not_checked", the spelling of every other status value and of the report block's own keys. - design.placebo_pretest_rate and design.PLACEBO_ESTIMAND are private (neither was exported). - HonestDiD.power_by_M: `power` is the share of draws whose interval excludes zero on either side, the definition of the rejection rates diagnose_design reports (it counted the effect's side only). `mde` is unchanged and its guarantee still holds. The table gains the `size_controlled` column it computed and dropped. - HonestDiD.fit and its siblings raise the power_by_M pointer for a design diagnosis too, not a generic "Unsupported results type". - DMLDiDResults.get_loo_effects_df says it is not available for DMLDiD; the inherited message told the user to refit with CallawaySantAnna. --- benchmarks/python/pretrend_planning_check.py | 6 +- changelog.d/20261126-sensitivity-planning.md | 6 +- diff_diff/_reporting_helpers.py | 6 +- diff_diff/design.py | 34 +++++------ diff_diff/dml_did_results.py | 14 +++++ diff_diff/guides/llms-autonomous.txt | 4 +- diff_diff/guides/llms-full.txt | 18 +++--- diff_diff/honest_did.py | 59 +++++++++++-------- diff_diff/pretrends.py | 8 +-- .../diff_diff.DesignDiagnosisResults.rst | 2 +- docs/api/design.rst | 10 ++-- docs/methodology/REGISTRY.md | 11 ++-- docs/tutorials/34_design_diagnosis.ipynb | 2 +- tests/helpers/results_foundation.py | 4 +- tests/test_design.py | 54 ++++++++--------- tests/test_design_event_study.py | 12 ++-- tests/test_design_sensitivity.py | 52 ++++++++++++---- tests/test_diagnostic_marker.py | 18 ++++++ tests/test_methodology_design.py | 33 ++++++----- tests/test_staggered_jackknife.py | 5 +- tests/test_t34_design_diagnosis_drift.py | 6 +- 21 files changed, 224 insertions(+), 140 deletions(-) diff --git a/benchmarks/python/pretrend_planning_check.py b/benchmarks/python/pretrend_planning_check.py index 5bb845cdb..acfd013ec 100644 --- a/benchmarks/python/pretrend_planning_check.py +++ b/benchmarks/python/pretrend_planning_check.py @@ -331,7 +331,7 @@ def run_point(task): "n_pre": len(labels), "se_ratio_min": round(min(ratios), 4), "se_ratio_max": round(max(ratios), 4), - "size": round(float(diagnosis.results[label][0].rejection_rate), 4), + "size": round(float(diagnosis.power_results[label][0].rejection_rate), 4), "pretest_counted": round(checks["pretest_rejection_rate"], 4), "pretest_expected": round(checks["pretest_expected_rate"], 4), "pretest_agrees": bool(checks["pretest_agrees"]), @@ -392,7 +392,7 @@ def run_selection(task): comparison = diagnose( panel, estimators, cohorts, N_DIAGNOSIS, int(compare_seed), effect_sizes=[effect] ) - powers = {label: float(comparison.results[label][1].power) for label in estimators} + powers = {label: float(comparison.power_results[label][1].power) for label in estimators} picked = max(estimators, key=lambda label: powers[label]) surface = comparison.event_study_results.get(picked) rerun = diagnose(panel, {picked: estimators[picked]}, cohorts, N_DIAGNOSIS, int(rerun_seed)) @@ -418,7 +418,7 @@ def selection_effect_size(n_units, panel_seed, pilot_seed): int(pilot_seed), event_study=False, ) - return 2.0 * float(pilot.results["never_treated"][0].std_estimate) + return 2.0 * float(pilot.power_results["never_treated"][0].std_estimate) def main(): diff --git a/changelog.d/20261126-sensitivity-planning.md b/changelog.d/20261126-sensitivity-planning.md index 36e1f948d..18c6dfeff 100644 --- a/changelog.d/20261126-sensitivity-planning.md +++ b/changelog.d/20261126-sensitivity-planning.md @@ -6,8 +6,10 @@ them. It returns one row per `M`: the rate at which the robust interval excluded zero although no effect was present (`placebo_rejection_rate`), the interval's mean width (`ci_width`), the minimum detectable effect (`mde`), - the power at `effect_size` (`power`), and the number of replicates scored - and lost. + the power at `effect_size` (`power`: the share of draws whose interval + excludes zero, the definition of the rejection rates `diagnose_design` + reports), the number of replicates scored and lost, and whether the row + passes the size rule (`size_controlled`). - The numbers are counted, not derived from a formula. An effect that is the same across treated units moves a draw's robust interval by the value of the target parameter and changes nothing else, so the interval at any diff --git a/diff_diff/_reporting_helpers.py b/diff_diff/_reporting_helpers.py index ed7606787..8a4ea10f6 100644 --- a/diff_diff/_reporting_helpers.py +++ b/diff_diff/_reporting_helpers.py @@ -98,7 +98,7 @@ def describe_design_reconciliation(reconciliation: Any) -> Optional[Dict[str, An """ if reconciliation is None: return None - by_status: Dict[str, List[Dict[str, Any]]] = {"match": [], "deviates": [], "not checked": []} + by_status: Dict[str, List[Dict[str, Any]]] = {"match": [], "deviates": [], "not_checked": []} for check in reconciliation.checks: by_status[check["status"]].append(check) return { @@ -109,12 +109,12 @@ def describe_design_reconciliation(reconciliation: Any) -> Optional[Dict[str, An "n_checks": len(reconciliation.checks), "n_match": len(by_status["match"]), "n_deviates": len(by_status["deviates"]), - "n_not_checked": len(by_status["not checked"]), + "n_not_checked": len(by_status["not_checked"]), "deviations": [ {"item": check["item"], "locked": check["locked"], "realized": check["realized"]} for check in by_status["deviates"] ], - "not_checked": [check["item"] for check in by_status["not checked"]], + "not_checked": [check["item"] for check in by_status["not_checked"]], } diff --git a/diff_diff/design.py b/diff_diff/design.py index 4b29dbad8..0420ccbf7 100644 --- a/diff_diff/design.py +++ b/diff_diff/design.py @@ -130,7 +130,7 @@ # Attribute of a placebo event study that holds, per placebo draw, each # pre-period coefficient over its own reported standard error (absolute # value). PreTrendsPower counts the pre-trend test's rejections from it for -# whichever pre-periods it is asked to plan (see placebo_pretest_rate). +# whichever pre-periods it is asked to plan (see _placebo_pretest_rate). _PRETEST_RECORD = "_placebo_pretest" # Attribute of a placebo event study that holds the event-study container of # every placebo draw behind it, and how many no-effect replicates never became @@ -141,7 +141,7 @@ # results_base._validate_vcov_subblock applies when allow_singular=False). _RANK_TOLERANCE = 1e-10 # The estimand label of a placebo event-study surface (EventStudyResults.estimand). -PLACEBO_ESTIMAND = "placebo" +_PLACEBO_ESTIMAND = "placebo" # Printed by both summaries: what a placebo diagnosis does and does not test. _SCOPE_LINES = ( @@ -162,7 +162,7 @@ class DesignDiagnosisResults(Diagnostic): Attributes ---------- - results : dict + power_results : dict Label -> list of :class:`~diff_diff.SimulationPowerResults`, one per entry of ``effect_sizes``. The first entry is the no-effect run, so its ``rejection_rate`` is the estimator's size on this design. @@ -228,7 +228,7 @@ class DesignDiagnosisResults(Diagnostic): :class:`~diff_diff.PreTrendsPower` for planned pre-trend power. """ - results: Dict[str, List[SimulationPowerResults]] + power_results: Dict[str, List[SimulationPowerResults]] mde_results: Dict[str, SimulationMDEResults] estimators: Dict[str, Any] size_controlled: Dict[str, bool] @@ -300,7 +300,7 @@ def to_dataframe(self) -> pd.DataFrame: ``n_nan_inference`` and ``mde``. """ rows: List[Dict[str, Any]] = [] - for label, cells in self.results.items(): + for label, cells in self.power_results.items(): rows.extend( _records( label, @@ -353,7 +353,7 @@ def to_dict(self) -> Dict[str, Any]: "time_periods": list(self.time_periods), "size_controlled": dict(self.size_controlled), "mde": dict(self.mde), - "results": self.to_dataframe().to_dict("records"), + "power_results": self.to_dataframe().to_dict("records"), } def summary(self) -> str: @@ -392,7 +392,7 @@ def summary(self) -> str: f"{'Estimator':<26}{'Size':>8}{'Scored':>8}{'Lost':>7}{'Coverage':>10}" f"{'Size OK':>9}{'MDE':>10}", ] - for label, cells in self.results.items(): + for label, cells in self.power_results.items(): null = cells[0] mde = self.mde[label] mde_text = f"{mde:.4g}" if np.isfinite(mde) else "-" @@ -408,7 +408,7 @@ def summary(self) -> str: f"{'Estimator':<26}{'Effect':>10}{'Power':>8}{'Bias':>11}{'RMSE':>11}" f"{'Coverage':>10}" ) - for label, cells in self.results.items(): + for label, cells in self.power_results.items(): for cell in cells[1:]: lines.append( f"{label[:25]:<26}{cell.true_effect:>10.4g}" @@ -811,7 +811,7 @@ def _placebo_event_study( base_period=base_period, anticipation=0, reference_event_times=reference_event_times, - estimand=PLACEBO_ESTIMAND, + estimand=_PLACEBO_ESTIMAND, ) reported = np.vstack([record[2] for record in used]) mean_reported = reported.mean(axis=0) @@ -832,7 +832,7 @@ def _placebo_event_study( _PLACEBO_DRAWS, {"draws": containers, "n_lost": int(n_lost) + n_excluded}, ) - counted, _ = placebo_pretest_rate(surface, pre_labels, alpha) + counted, _ = _placebo_pretest_rate(surface, pre_labels, alpha) expected = _formula_pretest_rate(vcov[np.ix_(pre, pre)], alpha) checks = { "n_draws": n_used, @@ -905,7 +905,7 @@ def _resolve_event_study(results: Any) -> Tuple[Any, Optional["DesignDiagnosisRe return surface, results, label -def placebo_pretest_rate(surface: Any, tested: Sequence[Any], alpha: float) -> Tuple[float, int]: +def _placebo_pretest_rate(surface: Any, tested: Sequence[Any], alpha: float) -> Tuple[float, int]: """How often the pre-trend test rejected in the placebo draws, for ``tested``. The test is the one PreTrendsPower models by default: reject when any of @@ -2132,7 +2132,7 @@ def diagnose_design( ) return DesignDiagnosisResults( - results=results, + power_results=results, mde_results=mde_results, estimators={label: _clone(est) for label, est in resolved.items()}, size_controlled=size_controlled, @@ -2174,7 +2174,7 @@ def diagnose_design( _ABSENT = "" _MATCH = "match" _DEVIATES = "deviates" -_NOT_CHECKED = "not checked" +_NOT_CHECKED = "not_checked" # 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", "rerun_results", "mde") @@ -2297,7 +2297,7 @@ def _lock( fit_kwargs = _fit_kwargs(chosen, outcome, unit, time, dict(diagnosis.estimator_kwargs)) # Derived, not an argument: the rerun cannot be re-rolled. lock_seed = int(np.random.SeedSequence([int(diagnosis.seed), 1]).generate_state(1)[0]) - null = diagnosis.results[label][0] + null = diagnosis.power_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) @@ -2329,7 +2329,7 @@ def _lock( meaning = "" if size_ok else " Its power is not meaningful." warnings.warn( f"The size check gives different verdicts for '{label}'. " - f"{_size_facts('Comparison', diagnosis.results[label][0], compared_ok)}; " + f"{_size_facts('Comparison', diagnosis.power_results[label][0], compared_ok)}; " f"{_size_facts('rerun', rerun_null, size_ok)}. The lock records the " f"rerun's verdict, size_controlled={size_ok}.{meaning}", UserWarning, @@ -3126,11 +3126,11 @@ class DesignReconciliationResults(Diagnostic): status : str ``"match"`` when every check that was run matches the lock, otherwise ``"deviates"``. The size of a deviation is not graded, and - checks whose inputs were not passed are ``"not checked"``. + checks whose inputs were not passed are ``"not_checked"``. checks : list of dict One entry per reconciled item, with keys ``item``, ``locked``, ``realized`` and ``status`` (``"match"``, ``"deviates"`` or - ``"not checked"``). + ``"not_checked"``). label : str Label of the locked estimator. lock_sha256 : str diff --git a/diff_diff/dml_did_results.py b/diff_diff/dml_did_results.py index 206630c9a..63c3e8d38 100644 --- a/diff_diff/dml_did_results.py +++ b/diff_diff/dml_did_results.py @@ -319,6 +319,20 @@ def bad_control_summary(self) -> pd.DataFrame: ) return pd.DataFrame(rows, columns=cols) + def get_loo_effects_df(self) -> pd.DataFrame: + """Not available: ``DMLDiD`` has no cluster jackknife. + + The method is inherited from :class:`CallawaySantAnnaResults`, where it + returns the delete-one-cluster estimates of a + ``vcov_type="jackknife"`` fit. ``DMLDiD`` has no ``vcov_type`` option, + so there are no such estimates and this always raises ``ValueError``. + """ + raise ValueError( + "get_loo_effects_df() is not available for DMLDiD results: DMLDiD " + "has no cluster jackknife (it has no vcov_type option), so there " + "are no delete-one-cluster estimates to return." + ) + def to_dataframe(self, level: str = "group_time") -> pd.DataFrame: """Parent DataFrame; on bad-control fits the ``group_time`` level gains ``att_x`` / ``se_x`` (analytical, unlike a bootstrapped ``se``).""" diff --git a/diff_diff/guides/llms-autonomous.txt b/diff_diff/guides/llms-autonomous.txt index 0c1f9558d..6d72f45ed 100644 --- a/diff_diff/guides/llms-autonomous.txt +++ b/diff_diff/guides/llms-autonomous.txt @@ -1135,8 +1135,8 @@ section is the API-reference index. - `HonestDiD(...).power_by_M(diagnose_design(..., event_study=True))` - planned power of the sensitivity analysis, by `M`, counted on the placebo draws (rate at which the robust interval excludes zero with no effect, - width, MDE, power at `effect_size`); rows that fail the size rule have - blank `mde` / `power` + width, MDE, power at `effect_size`, `size_controlled`); rows that fail + the size rule have blank `mde` / `power` - `compute_pretrends_power(results, ...)` - standalone power analysis for the PT test; takes a fitted event-study results object (CS / SA results or an `EventStudyResults` container, e.g. the TWFE diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index 9d39c1c7f..176b83c15 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -2466,7 +2466,7 @@ result = diagnose_design( ) result.print_summary() table = result.to_dataframe() # one row per estimator and effect size -null_run = result.results["cs"][0] # SimulationPowerResults at effect 0 +null_run = result.power_results["cs"][0] # SimulationPowerResults at effect 0 size = null_run.rejection_rate # should be near alpha ok = result.size_controlled["cs"] # False -> power is not meaningful mde = result.mde["cs"] # NaN unless size is controlled @@ -2492,11 +2492,13 @@ honest_plan = HonestDiD(method="relative_magnitude").power_by_M( plan, M_grid=[0, 0.5, 1.0], effect_size=0.5, power=0.80, ) # columns: M, placebo_rejection_rate (interval excludes zero with no effect; a -# valid interval stays at or below alpha), ci_width, mde, power, -# n_simulations, n_simulation_failures -# mde / power are NaN on a row that fails the diagnosis size rule (typical for -# method="smoothness" at M=0 on a small panel). method="combined" is refused; -# a fitted model is refused (use sensitivity_analysis). +# valid interval stays at or below alpha), ci_width, mde, power +# (share of draws whose interval excludes zero at effect_size), +# n_simulations, n_simulation_failures, size_controlled +# mde / power are NaN and size_controlled is False on a row that fails the +# diagnosis size rule (typical for method="smoothness" at M=0 on a small +# panel). method="combined" is refused; a fitted model is refused (use +# sensitivity_analysis). # The formula assumes each coefficient's own test holds its level. For the # pre-periods being planned, PreTrendsPower compares the pre-trend test's # rejection rate in the placebo draws with the rate the formula assumes and @@ -2573,7 +2575,7 @@ 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 +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 `"match"` covers the checks that were run only. The lock does not record when it @@ -2584,7 +2586,7 @@ outcomes were seen. timing only), CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, EfficientDiD (common or staggered timing). -**Returns** `DesignDiagnosisResults`: `results` (label -> list of +**Returns** `DesignDiagnosisResults`: `power_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`, `time_periods`. diff --git a/diff_diff/honest_did.py b/diff_diff/honest_did.py index eb3906ff1..87a922c98 100644 --- a/diff_diff/honest_did.py +++ b/diff_diff/honest_did.py @@ -1175,12 +1175,20 @@ def _extract_event_study_params( Survey degrees of freedom for t-distribution inference (``0.0`` = replicate design with undefined df). """ + from diff_diff.design import _PLACEBO_ESTIMAND, DesignDiagnosisResults from diff_diff.results_base import EventStudyResults + if isinstance(results, DesignDiagnosisResults): + raise ValueError( + "This is a design diagnosis from diagnose_design: it holds placebo " + "draws, not an estimate of an effect, so HonestDiD bounds on it " + "have no meaning. To plan a sensitivity analysis from it, use " + "HonestDiD.power_by_M (the diagnosis must have been run with " + "event_study=True); PreTrendsPower accepts it for planned " + "pre-trend power." + ) if isinstance(results, EventStudyResults): - from diff_diff.design import PLACEBO_ESTIMAND - - if results.estimand == PLACEBO_ESTIMAND: + if results.estimand == _PLACEBO_ESTIMAND: raise ValueError( "This is a placebo event study from diagnose_design(..., " "event_study=True): its coefficients are means over placebo " @@ -3509,20 +3517,24 @@ def power_by_M( - ``ci_width``: mean width of the robust interval. - ``mde``: the effect magnitude above which, for an effect of either sign, at least ``power`` of the scored draws have an - interval lying entirely on the effect's side of zero. + interval lying entirely on the effect's side of zero. Power as + defined below is at least that share, so the target is reached + for every effect larger than ``mde``. - ``power``: at ``effect_size``, the share of scored draws whose - interval lies entirely on the effect's side of zero (an - interval that excludes zero on the wrong side is not a - detection). At ``effect_size=0`` it is the - ``placebo_rejection_rate``. NaN when ``effect_size`` is not - given. + interval excludes zero, on either side: the definition of the + rejection rates ``diagnose_design`` reports. At + ``effect_size=0`` it is the ``placebo_rejection_rate``. NaN + when ``effect_size`` is not given. - ``n_simulations``: draws with a finite robust interval. - ``n_simulation_failures``: no-effect replicates without one (the estimator or this analysis failed on them, or their event study had a different layout). + - ``size_controlled``: whether the row passes the size rule + below. ``mde`` and ``power`` are NaN on a row that fails the size rule of - ``diagnose_design``: more than 10% of the replicates were lost, or + ``diagnose_design`` (``size_controlled`` is False): more than 10% + of the replicates were lost, or ``placebo_rejection_rate`` exceeds ``alpha`` by more than 1.96 Monte Carlo standard errors. An interval that excludes zero too often when nothing happened has no meaningful power. One warning @@ -3555,7 +3567,7 @@ def power_by_M( """ from diff_diff.design import ( _DATA_DEPENDENT_ERRORS, - PLACEBO_ESTIMAND, + _PLACEBO_ESTIMAND, _placebo_draw_record, _reemit, _resolve_event_study, @@ -3563,7 +3575,7 @@ def power_by_M( from diff_diff.results_base import EventStudyResults surface, _diagnosis, _label = _resolve_event_study(results) - if not (isinstance(surface, EventStudyResults) and surface.estimand == PLACEBO_ESTIMAND): + if not (isinstance(surface, EventStudyResults) and surface.estimand == _PLACEBO_ESTIMAND): raise TypeError( "power_by_M plans a sensitivity analysis from a design diagnosis " "(diagnose_design(..., event_study=True)) or one of its placebo " @@ -3674,6 +3686,7 @@ def power_by_M( "power", "n_simulations", "n_simulation_failures", + "size_controlled", ] return pd.DataFrame(rows)[columns] @@ -3805,8 +3818,11 @@ def _score_planned_intervals( An effect that is the same across treated units moves a draw's interval by the value ``theta`` of the target parameter and changes nothing else, so - the interval at ``theta`` is ``[ci_lb + theta, ci_ub + theta]``. It detects - the effect when it lies entirely on the effect's side of zero. + the interval at ``theta`` is ``[ci_lb + theta, ci_ub + theta]``. Power is + the share of scored draws whose interval excludes zero, on either side + (the rule of ``HonestDiDResults.is_significant`` and of the rejection + rates ``diagnose_design`` reports). The MDE is set from the effect's side + alone, so the target is reached for every effect larger than it. """ from diff_diff.design import _size_controlled @@ -3832,20 +3848,17 @@ def _score_planned_intervals( if not _size_controlled(rate, n, lost, alpha): return row row["size_controlled"] = True - # The smallest magnitude from which the detecting share is at least - # ``power``, for a positive effect (a + theta > 0) and for a negative one - # (b - theta < 0); the larger of the two, and never below zero. + # The smallest magnitude from which the share of intervals lying on the + # effect's side of zero is at least ``power``, for a positive effect + # (a + theta > 0) and for a negative one (b - theta < 0); the larger of + # the two, and never below zero. Power counts exclusions on either side, + # so it is at least that share: the target holds above the MDE. k = max(int(np.ceil(power * n - 1e-9)), 1) positive = float(np.sort(-a)[k - 1]) negative = float(np.sort(b)[k - 1]) row["mde"] = max(positive, negative, 0.0) if effect_size is not None: - if effect_size > 0.0: - row["power"] = float(np.mean(a + effect_size > 0.0)) - elif effect_size < 0.0: - row["power"] = float(np.mean(b + effect_size < 0.0)) - else: - row["power"] = rate + row["power"] = float(np.mean((a + effect_size > 0.0) | (b + effect_size < 0.0))) return row diff --git a/diff_diff/pretrends.py b/diff_diff/pretrends.py index 95b948764..61c50ad8a 100644 --- a/diff_diff/pretrends.py +++ b/diff_diff/pretrends.py @@ -297,10 +297,10 @@ def _validate_violation_magnitude(M: Any) -> None: def _is_placebo_surface(obj: Any) -> bool: """Whether ``obj`` is a placebo event study recorded by ``diagnose_design``.""" - from diff_diff.design import PLACEBO_ESTIMAND + from diff_diff.design import _PLACEBO_ESTIMAND from diff_diff.results_base import EventStudyResults - return isinstance(obj, EventStudyResults) and obj.estimand == PLACEBO_ESTIMAND + return isinstance(obj, EventStudyResults) and obj.estimand == _PLACEBO_ESTIMAND def _resolve_planned_input(results: Any) -> Any: @@ -2359,7 +2359,7 @@ def _planned_pretest_check( the placebo record can count, and the one the library's simulation checked against direct trend injection. """ - from diff_diff.design import _pretest_size_ok, placebo_pretest_rate + from diff_diff.design import _placebo_pretest_rate, _pretest_size_ok if self.pretest_form != "nis": raise ValueError( @@ -2369,7 +2369,7 @@ def _planned_pretest_check( "error, which is the NIS test, and the joint Wald form has not " "been checked against placebo draws." ) - counted, n_draws = placebo_pretest_rate(surface, tested, self.alpha) + counted, n_draws = _placebo_pretest_rate(surface, tested, self.alpha) expected = float(self._compute_power(0.0, weights, vcov)[0]) return counted, expected, n_draws, _pretest_size_ok(counted, expected, n_draws) diff --git a/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst index 8e1190ca6..839ab2f2d 100644 --- a/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst +++ b/docs/api/_autosummary/diff_diff.DesignDiagnosisResults.rst @@ -26,7 +26,7 @@ .. autosummary:: ~DesignDiagnosisResults.event_study - ~DesignDiagnosisResults.results + ~DesignDiagnosisResults.power_results ~DesignDiagnosisResults.mde_results ~DesignDiagnosisResults.estimators ~DesignDiagnosisResults.size_controlled diff --git a/docs/api/design.rst b/docs/api/design.rst index 91d3726ea..c1f71c8b4 100644 --- a/docs/api/design.rst +++ b/docs/api/design.rst @@ -81,8 +81,10 @@ numbers are counted, not derived from a formula: an effect that is the same across treated units moves every draw's interval by the size of the effect and changes nothing else, so the interval at any effect size follows from the no-effect draw. A row whose interval excludes zero too often (the size rule the -diagnosis applies to its own MDE) shows the rate and leaves ``mde`` and -``power`` blank. On small panels this happens for ``method="smoothness"`` at +diagnosis applies to its own MDE) shows the rate, has ``size_controlled`` +set to ``False`` and leaves ``mde`` and ``power`` blank. ``power`` is the share +of draws whose interval excludes zero, as for the rejection rates of the +diagnosis. On small panels this happens for ``method="smoothness"`` at ``M = 0``, whose interval is built from each fit's own estimated covariance. These are powers when parallel trends hold; ``method="combined"`` is not planned. Keeping the draws costs about 3 KB per replicate on the diagnosis. @@ -123,7 +125,7 @@ Either way, the lock does not record when it was made. ``match`` says the analysis agrees with the lock on the checks that were run; whether the design was fixed before the outcomes were seen depends on when you saved or registered the lock file. A deviation is not graded, and checks whose inputs were not passed -are reported as ``not checked`` next to the status. +are reported as ``not_checked`` next to the status. **Reports.** Pass the reconciliation to :class:`~diff_diff.BusinessReport` or :class:`~diff_diff.DiagnosticReport` as @@ -200,7 +202,7 @@ Example table = result.to_dataframe() # one row per estimator and effect size # The no-effect run of one estimator: its rejection_rate is the size. - null_run = result.results["cs"][0] + null_run = result.power_results["cs"][0] print(null_run.rejection_rate, result.size_controlled["cs"], result.mde["cs"]) Three estimators were compared, so locking the choice reruns it alone, with new diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 9e4882e96..1ec1f9ef8 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -6803,14 +6803,15 @@ CRITICAL: δ_pre = β_pre pins pre-treatment violations to observed coefficients at target value th interval is [a_r + th, b_r + th] placebo_rejection_rate share of scored draws with a_r > 0 or b_r < 0 ci_width mean of b_r - a_r over scored draws - power(th) th > 0: share with a_r + th > 0; th < 0: share with b_r + th < 0; - th = 0: placebo_rejection_rate + power(th) share of scored draws with a_r + th > 0 or b_r + th < 0 + (at th = 0 this is placebo_rejection_rate) mde max(k-th smallest of -a_r, k-th smallest of b_r, 0), k = ceil(power * n) n_simulation_failures draws lost here + no-effect replicates that never became a draw + size_controlled whether the row passes the size rule below ``` The third line is the identity the count rests on: an effect that is the same across treated units at each event time moves each post-period coefficient by that event time's effect and leaves the pre-period coefficients and the event-study covariance unchanged, so it moves the robust interval by `th = l_vec' tau` and changes nothing else. Checked against real injection (`tests/test_design_sensitivity.py::TestShiftIdentity`) for `CallawaySantAnna` (never-treated and not-yet-treated controls, common and staggered adoption, a covariate, `n_bootstrap > 0`) and `StackedDiD`, for both restrictions, for an effect that differs by event time, and for `l_vec` that does not sum to one (the constant effect `e` that `diagnose_design` injects corresponds to `th = e * sum(l_vec)`). Effects that differ across treated units would change the standard errors; that case is not planned, as in the rest of the diagnosis. - - `power` counts an interval only when it lies entirely on the effect's side of zero: an interval that excludes zero on the wrong side is not a detection. `mde` is the larger of the two signs' thresholds, so the target is reached for every effect larger in magnitude than `mde`, of either sign (at `mde` itself an endpoint sits on zero, which is not an exclusion). - - Size rule: `mde` and `power` are NaN on a row for which `_size_controlled(placebo_rejection_rate, n_simulations, n_simulation_failures, alpha)` is false (the rule `diagnose_design` applies to its own MDE: more than 10% of the replicates lost, or a rate above `alpha` plus 1.96 Monte Carlo standard errors at `alpha`), and one warning lists those rows. The rate, the width and the counts are reported on every row. Replicates the estimator failed on never become a draw; they are counted as lost here, because no gate looks at them when the placebo event study is built. + - `power` is the share of scored draws whose interval excludes zero, on either side: the rule of `HonestDiDResults.is_significant` and of the rejection rates `diagnose_design` reports, so "power" has one meaning across the diagnosis. `mde` is set from the effect's side alone: for each sign it is the magnitude from which at least `power` of the intervals lie entirely on that side of zero, and the larger of the two is reported. An interval on the effect's side excludes zero, so `power` is at least that share and the target is reached for every effect larger in magnitude than `mde`, of either sign (at `mde` itself an endpoint sits on zero, which is not an exclusion). Just below `mde`, `power` can already be at the target when some intervals exclude zero on the other side; that share is at most `placebo_rejection_rate`. + - Size rule: `size_controlled` is False and `mde` and `power` are NaN on a row for which `_size_controlled(placebo_rejection_rate, n_simulations, n_simulation_failures, alpha)` is false (the rule `diagnose_design` applies to its own MDE: more than 10% of the replicates lost, or a rate above `alpha` plus 1.96 Monte Carlo standard errors at `alpha`), and one warning lists those rows. The rate, the width and the counts are reported on every row. Replicates the estimator failed on never become a draw; they are counted as lost here, because no gate looks at them when the placebo event study is built. - These are powers when parallel trends hold in the placebo draws. Under `method="smoothness"` with never-treated controls a linear difference in trends between treated and control units leaves the interval unchanged (it is neutral to linear trends by construction); under `method="relative_magnitude"` such a trend changes it (it enters the bound). - `method="combined"` raises `ValueError`: the library's interval for it is not supported by the paper (Proposition 4.2), so no planned number is reported for it. A fitted model raises `TypeError`: choosing `M`, `method` or `l_vec` from this table after seeing the estimate is a choice made on the outcome. - When the analysis cannot be computed on any draw (for example `l_vec` of the wrong length, or a layout `fit` refuses) the method raises with the draws' most frequent error. @@ -7184,7 +7185,7 @@ pre-test check for a set S of pre-periods (PreTrendsPower, the set it plans): - **Note (size verdict near the threshold):** the size check passes a rejection rate up to `alpha` plus 1.96 Monte Carlo standard errors, so a candidate whose true size is just above `alpha` can pass one run and fail the next. In the 500-replicate scenario of the same simulation the rerun flagged 27% of all locks after the comparison had passed the chosen candidate: 30% when `ImputationDiD` (reference size 6.4%) was chosen, 36% for classical-SE TWFE (6.7%) and 9% for unit-clustered TWFE (5.3%). The lock records the rerun's verdict and `lock` warns when the two differ; the rule itself is unchanged and is tracked in `TODO.md`. - **Note (what the size check covers):** placebo treatment is assigned at random, so parallel trends holds by construction in every replicate. `size_controlled` is therefore a statement about the candidate's inference on this panel's error structure (serial correlation, few treated units), not about identification: a design can pass it and still be biased when real treatment goes to units on a different trend. Both summaries say so. - **Note (lock seed and second label):** the rerun's seed is derived from the recorded seed and is not an argument, so the rerun cannot be re-rolled. A rerun 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 status):** `reconcile` returns `match` or `deviates` and does not grade the size of a deviation; any checked item that differs gives `deviates`. `match` covers the checks that were run only: it does not certify aspects of the analysis data that are not listed, and items whose inputs were not passed are `not checked` (the summary shows their count next to the status). The lock does not record when it was made, so `match` does not establish that the design was fixed before the outcomes were seen; that depends on when the lock file was saved or registered. +- **Note (binary status):** `reconcile` returns `match` or `deviates` and does not grade the size of a deviation; any checked item that differs gives `deviates`. `match` covers the checks that were run only: it does not certify aspects of the analysis data that are not listed, and items whose inputs were not passed are `not_checked` (the summary shows their count next to the status). The lock does not record when it was made, so `match` does not establish that the design was fixed before the outcomes were seen; that depends on when the lock file was saved or registered. - **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.fit` does not rely on a declaration: it builds the locked estimator, fits it with the locked columns and keywords and reconciles on the fitted frame, and its result carries `declared=False`. `reconcile` remains for an analysis that was fitted by hand (`declared=True`); `DesignLock.to_estimator()` builds the locked estimator for that path. Neither establishes when the lock was made. - **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. diff --git a/docs/tutorials/34_design_diagnosis.ipynb b/docs/tutorials/34_design_diagnosis.ipynb index 7eecb6961..53a942ac9 100644 --- a/docs/tutorials/34_design_diagnosis.ipynb +++ b/docs/tutorials/34_design_diagnosis.ipynb @@ -334,7 +334,7 @@ "source": [ "threshold = 0.05 + 1.96 * np.sqrt(0.05 * 0.95 / 200)\n", "print(f\"Size threshold with 200 replicates: {threshold:.1%}\")\n", - "for label, runs in result.results.items():\n", + "for label, runs in result.power_results.items():\n", " print(\n", " f\"{label:<15} size {runs[0].rejection_rate:5.1%} \"\n", " f\"size_controlled={result.size_controlled[label]} MDE {result.mde[label]:.2f}\"\n", diff --git a/tests/helpers/results_foundation.py b/tests/helpers/results_foundation.py index 6cfbe57e0..1d4799aa7 100644 --- a/tests/helpers/results_foundation.py +++ b/tests/helpers/results_foundation.py @@ -343,7 +343,7 @@ def make_constructed_diagnostics() -> Dict[str, Any]: estimator_name="DifferenceInDifferences", ), "DesignDiagnosisResults": diff_diff.DesignDiagnosisResults( - results={ + power_results={ "DifferenceInDifferences": [ diff_diff.SimulationPowerResults( power=power, @@ -406,7 +406,7 @@ def make_constructed_diagnostics() -> Dict[str, Any]: "realized": "unit", "status": "deviates", }, - {"item": "n_units", "locked": 20, "realized": None, "status": "not checked"}, + {"item": "n_units", "locked": 20, "realized": None, "status": "not_checked"}, ], label="DifferenceInDifferences", lock_sha256="0" * 64, diff --git a/tests/test_design.py b/tests/test_design.py index 3010e1b40..de5e09d61 100644 --- a/tests/test_design.py +++ b/tests/test_design.py @@ -86,7 +86,7 @@ def run(panel, estimators, **kwargs): def estimates(result, label, cell=0): - return np.array([r["estimate"] for r in result.results[label][cell].simulation_results]) + return np.array([r["estimate"] for r in result.power_results[label][cell].simulation_results]) ALL_EIGHT = [ @@ -108,8 +108,8 @@ def test_all_eight_recover_injected_effect_common_timing(self): with warnings.catch_warnings(): warnings.simplefilter("ignore") result = run(panel, [cls() for cls in ALL_EIGHT], effect_sizes=[2.0], n_simulations=4) - assert list(result.results) == [cls.__name__ for cls in ALL_EIGHT] - for label, cells in result.results.items(): + assert list(result.power_results) == [cls.__name__ for cls in ALL_EIGHT] + for label, cells in result.power_results.items(): assert cells[0].n_simulations == 4, label assert abs(cells[0].mean_estimate) < 1e-2, label assert abs(cells[1].mean_estimate - 2.0) < 1e-2, label @@ -127,7 +127,7 @@ def test_staggered_six_recover_injected_effect(self): effect_sizes=[1.5], n_simulations=4, ) - for label, cells in result.results.items(): + for label, cells in result.power_results.items(): assert cells[1].n_simulations == 4, label assert abs(cells[1].mean_estimate - 1.5) < 1e-2, label @@ -210,7 +210,7 @@ def test_fixed_panel_matches_exact_enumeration(self): resample_units=False, n_simulations=400, ) - cell = result.results["DifferenceInDifferences"][0] + cell = result.power_results["DifferenceInDifferences"][0] drawn = {round(float(e), 10) for e in estimates(result, "DifferenceInDifferences")} assert drawn <= set(enumerated) assert len(drawn) > 10 @@ -436,7 +436,7 @@ def test_other_cluster_column_allowed_on_the_fixed_panel(self): }, resample_units=False, ) - a, b = result.results["by_unit"][0], result.results["by_copy"][0] + a, b = result.power_results["by_unit"][0], result.power_results["by_copy"][0] assert a.rejection_rate == b.rejection_rate assert a.mean_se == pytest.approx(b.mean_se, rel=1e-12) @@ -457,7 +457,7 @@ def test_unit_cluster_allowed_when_resampling_whatever_the_column_is_called(self seed=1, progress=False, ) - for cells in result.results.values(): + for cells in result.power_results.values(): assert cells[0].n_simulations == 5 def test_common_timing_estimator_under_staggered_declaration(self): @@ -531,7 +531,7 @@ def test_nan_inference_after_preflight_is_excluded_and_counted(self, monkeypatch _stub_fit(monkeypatch, lambda i, make: make() if i == 1 else _with_nan_inference(make())) with pytest.warns(UserWarning): result = run(make_panel(seed=32), self.estimators(), n_simulations=15, power=0.8) - cell = result.results["twfe"][0] + cell = result.power_results["twfe"][0] assert cell.n_simulations == 0 assert cell.n_simulation_failures == 15 assert np.isnan(cell.rejection_rate) @@ -539,7 +539,7 @@ def test_nan_inference_after_preflight_is_excluded_and_counted(self, monkeypatch assert result.size_controlled["twfe"] is False assert np.isnan(result.mde["twfe"]) assert "twfe" not in result.mde_results - assert result.results["did"][0].n_simulations == 15 # the other estimator completes + assert result.power_results["did"][0].n_simulations == 15 # the other estimator completes def test_some_nan_replicates_leave_rates_over_the_rest(self, monkeypatch): # Calls 2..6 are the first five replicates of the effect-0 cell. @@ -549,7 +549,7 @@ def test_some_nan_replicates_leave_rates_over_the_rest(self, monkeypatch): ) with pytest.warns(UserWarning): result = run(make_panel(seed=33), self.estimators(), n_simulations=20) - cell = result.results["twfe"][0] + cell = result.power_results["twfe"][0] assert cell.n_simulations == 15 assert cell.n_simulation_failures == 5 assert result.n_nan_inference["twfe"] == [5] @@ -565,12 +565,12 @@ def behaviour(i, make): _stub_fit(monkeypatch, behaviour) with pytest.warns(UserWarning): result = run(make_panel(seed=34), self.estimators(), n_simulations=12) - cell = result.results["twfe"][0] + cell = result.power_results["twfe"][0] assert cell.n_simulations == 0 assert cell.n_simulation_failures == 12 assert result.n_nan_inference["twfe"] == [0] assert result.size_controlled["twfe"] is False - assert result.results["did"][0].n_simulations == 12 + assert result.power_results["did"][0].n_simulations == 12 def test_value_error_on_every_call_is_refused_by_preflight(self, monkeypatch): def behaviour(i, make): @@ -609,7 +609,7 @@ def behaviour(i, make): result = run( make_panel(seed=38), self.estimators(), n_simulations=n, effect_sizes=[1.0] ) - null, shifted = result.results["twfe"] + null, shifted = result.power_results["twfe"] assert null.n_simulations == n and null.n_simulation_failures == 0 assert shifted.n_simulations == 0 and shifted.n_simulation_failures == n assert np.isfinite(null.rejection_rate) @@ -630,7 +630,7 @@ def behaviour(i, make): result = run(panel, self.estimators(), n_simulations=n, power=0.8) messages = [str(w.message) for w in caught] assert any(m.startswith("[twfe] MDE not reported") for m in messages) - assert result.results["twfe"][0].n_simulation_failures == 0 + assert result.power_results["twfe"][0].n_simulation_failures == 0 assert result.size_controlled["twfe"] # the gate looks at effect 0 only assert np.isnan(result.mde["twfe"]) assert "twfe" in result.mde_results # the search ran; its value is withheld @@ -767,7 +767,7 @@ def test_aggregated_and_labelled(self, monkeypatch): # One per block (pre-flight, the single cell), not one per fit. assert len(messages) == 2 assert any("raised 10 times" in m for m in messages) - assert result.results["twfe"][0].n_simulation_failures == 0 + assert result.power_results["twfe"][0].n_simulation_failures == 0 def test_caller_ignore_filter_does_not_lose_replicates(self, monkeypatch): _stub_fit(monkeypatch, _Chatty()) @@ -775,7 +775,7 @@ def test_caller_ignore_filter_does_not_lose_replicates(self, monkeypatch): warnings.simplefilter("ignore") result = run(make_panel(seed=43), self.estimators(), n_simulations=10) assert caught == [] - assert result.results["twfe"][0].n_simulations == 10 + assert result.power_results["twfe"][0].n_simulations == 10 def test_caller_error_filter_raises_the_labelled_warning(self, monkeypatch): _stub_fit(monkeypatch, _Chatty()) @@ -833,7 +833,7 @@ def test_is_a_diagnostic_without_the_estimator_quintet(self, result): def test_effect_sizes_are_the_ones_run(self, result): assert result.effect_sizes == [0.0, 0.5, 1.0] - for cells in result.results.values(): + for cells in result.power_results.values(): assert [cell.true_effect for cell in cells] == [0.0, 0.5, 1.0] def test_dataframe_layout(self, result): @@ -848,7 +848,7 @@ def test_dataframe_layout(self, result): assert ((frame["n_simulations"] + frame["n_simulation_failures"]) == 15).all() def test_rejection_rate_at_zero_is_the_size(self, result): - null = result.results["did"][0] + null = result.power_results["did"][0] assert null.true_effect == 0.0 assert null.rejection_rate == null.power assert 0.0 <= null.rejection_rate <= 1.0 @@ -861,7 +861,7 @@ def test_to_dict(self, result): } assert payload["n_treated"] == 10 assert payload["cohort_periods"] == [6] - assert len(payload["results"]) == 6 + assert len(payload["power_results"]) == 6 assert payload["data_sha256"] == result.data_sha256 def test_estimators_field_holds_unfitted_copies(self, result): @@ -961,7 +961,7 @@ def test_fit_keyword_reaches_every_estimator(self): n_simulations=5, ) assert result.estimator_kwargs == {"covariates": ["x"]} - for cells in result.results.values(): + for cells in result.power_results.values(): assert cells[0].n_simulations == 5 @@ -1217,7 +1217,7 @@ def test_rerun_fails_the_size_check_the_comparison_passed(self): assert lock.size_controlled is False assert lock.rerun_results[0]["size_controlled"] is False message = next(str(w.message) for w in caught if "different verdicts" in str(w.message)) - compared, rerun = result.results["classical"][0], lock.rerun_results[0] + compared, rerun = result.power_results["classical"][0], lock.rerun_results[0] assert f"Comparison: no-effect rejection rate {compared.rejection_rate:.1%}" in message assert f"{compared.n_simulations} scored, {compared.n_simulation_failures} lost" in message assert f"rerun: no-effect rejection rate {rerun['rejection_rate']:.1%}" in message @@ -1425,7 +1425,7 @@ def test_reported_mde_round_trips(self): def test_cell_that_could_not_be_scored_round_trips(self): _, result = diagnosed(single=True) - result.results["did"][1] = _failed_cell(1.0, 0.05, "DifferenceInDifferences", 12) + result.power_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"): @@ -1574,7 +1574,7 @@ def test_alpha_on_results(self, staggered): 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" + assert statuses(self.reconcile(lock))["alpha"] == "not_checked" def test_results_of_another_estimator_are_refused(self, staggered): _, lock = staggered @@ -1697,11 +1697,11 @@ def test_duplicate_group_or_post_label_deviates(self, two_group, column, items): 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 all(without_data[item] == "not_checked" for item in self.DATA) assert self.reconcile(lock).status == "match" 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" + assert with_data[item] == "not_checked" for item in ("data_sha256", "n_units", "is_balanced"): assert with_data[item] == "match" @@ -1734,7 +1734,7 @@ def test_two_group_design(self, two_group): assert reconciliation.status == "match" 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_post_by_cohort"] == "not_checked" assert without_post["n_treated"] == "match" def test_two_group_structure(self, two_group): @@ -1788,7 +1788,7 @@ def test_status_is_never_shown_without_the_checks_not_run(self, staggered): analysis = analysis_frame(frame) # No data and no results: seven checks are not run. partial = self.reconcile(lock) - skipped = sum(1 for check in partial.checks if check["status"] == "not checked") + skipped = sum(1 for check in partial.checks if check["status"] == "not_checked") assert partial.status == "match" and skipped == 7 assert f"match - {skipped} not checked" in partial.summary() assert f"not_checked={skipped}, declared=True)" in repr(partial) diff --git a/tests/test_design_event_study.py b/tests/test_design_event_study.py index 94f100b01..d5eb8f59f 100644 --- a/tests/test_design_event_study.py +++ b/tests/test_design_event_study.py @@ -122,7 +122,7 @@ def _independent_surface(n_pre=4, se=0.5, inflate=(), n_draws=4000, seed=0): base_period="universal", anticipation=0, reference_event_times=(-1,), - estimand=design_module.PLACEBO_ESTIMAND, + estimand=design_module._PLACEBO_ESTIMAND, ) ratios = np.abs(np.random.default_rng(seed).normal(size=(n_draws, n_pre))) for column in inflate: @@ -270,7 +270,7 @@ def test_only_the_no_effect_cell_is_captured(self, panel): label = "CallawaySantAnna" assert searched.mde_results, "the MDE search must have run for this check to bind" checks = searched._event_study_checks[label] - assert checks["n_draws"] == searched.results[label][0].n_simulations + assert checks["n_draws"] == searched.power_results[label][0].n_simulations reference = plain._event_study_checks[label] for key in ("n_draws", "n_excluded", "se_ratio", "pretest_rejection_rate"): assert checks[key] == reference[key], key @@ -405,11 +405,11 @@ def test_pretest_record_and_rates(self): design_module._formula_pretest_rate(surface.vcov[:2, :2], 0.05), abs=NIS_ATOL ) # The same count for a subset, and at another level. - counted, n_draws = design_module.placebo_pretest_rate(surface, [-2], 0.10) + counted, n_draws = design_module._placebo_pretest_rate(surface, [-2], 0.10) assert n_draws == 200 assert counted == pytest.approx(np.mean(np.abs(values[:, 1]) > 1.6448536269514722)) with pytest.raises(ValueError, match="not in this placebo event study"): - design_module.placebo_pretest_rate(surface, [-9], 0.05) + design_module._placebo_pretest_rate(surface, [-9], 0.05) @pytest.mark.parametrize("scale, direction", [(0.6, "more"), (1.8, "less")]) def test_full_set_verdict_in_both_directions(self, scale, direction): @@ -582,7 +582,7 @@ def test_twfe_fit_keyword_of_the_same_name_still_works(self, panel): event_study=flag, estimator_kwargs={"event_study": False}, ) - assert diagnosis.results["TwoWayFixedEffects"][0].n_simulations == 40 + assert diagnosis.power_results["TwoWayFixedEffects"][0].n_simulations == 40 assert diagnosis.event_study_results == {} @@ -773,7 +773,7 @@ def test_rows_equal_fit_calls(self, cs_diagnosis, cs_surface): ) assert row["power"] == pytest.approx(fitted.power, abs=NIS_ATOL) assert row["power_no_violation"] == pytest.approx(fitted.power_at(0.0), abs=NIS_ATOL) - counted, _ = design_module.placebo_pretest_rate(cs_surface, row["pre_periods"], 0.05) + counted, _ = design_module._placebo_pretest_rate(cs_surface, row["pre_periods"], 0.05) assert row["placebo_rejection_rate"] == counted assert np.all(np.isnan(planner.power_by_pre_periods(cs_diagnosis)["power"])) diff --git a/tests/test_design_sensitivity.py b/tests/test_design_sensitivity.py index 8ce9ea48a..2d26b5426 100644 --- a/tests/test_design_sensitivity.py +++ b/tests/test_design_sensitivity.py @@ -37,6 +37,7 @@ "power", "n_simulations", "n_simulation_failures", + "size_controlled", ] @@ -198,21 +199,22 @@ def test_injected_effect_equals_shifted_interval(self, panel, estimator, cohorts assert row["n_simulations"] == n_simulations assert row["n_simulation_failures"] == 0 counted = np.mean((injected[:, 0] > 0) | (injected[:, 1] < 0)) - detected = np.mean(injected[:, 0] > 0) by_hand_rate = np.mean((no_effect[:, 0] > 0) | (no_effect[:, 1] < 0)) assert row["placebo_rejection_rate"] == pytest.approx(by_hand_rate, abs=1e-12) np.testing.assert_allclose( row["ci_width"], np.mean(no_effect[:, 1] - no_effect[:, 0]), rtol=1e-12 ) + passes = design_module._size_controlled(by_hand_rate, n_simulations, 0, 0.05) + assert bool(row["size_controlled"]) is passes if np.isnan(row["mde"]): # Withheld by the size rule: the planned numbers are blank together. assert np.isnan(row["power"]) - assert not design_module._size_controlled(by_hand_rate, n_simulations, 0, 0.05) + assert not passes else: - assert row["power"] == pytest.approx(detected, abs=1e-12) - # No draw excludes zero on the wrong side of a positive effect - # here, so the two-sided count agrees as well. - assert counted == pytest.approx(detected, abs=1e-12) + # Power is the share of really injected fits whose interval + # excludes zero, the rejection rate diagnose_design reports. + assert passes + assert row["power"] == pytest.approx(counted, abs=1e-12) def test_relative_magnitude_rows_are_reported(self, cs_diagnosis): """The identity test above is not vacuous: these rows pass the size rule.""" @@ -375,14 +377,32 @@ def test_mde_is_the_larger_of_the_two_signs(self): # The positive side needed far less. assert _score(lower, upper, alpha=0.5, effect_size=0.9)["power"] >= 0.8 - def test_wrong_side_exclusion_is_not_a_detection(self): - # One interval lies entirely below zero. With no effect it is a - # rejection; for a small positive effect it is not a detection. + def test_power_counts_exclusions_on_either_side(self): + # One interval lies entirely below zero. It excludes zero with no + # effect, and still does for a small positive effect: power is the + # share of intervals that exclude zero, as for any rejection rate. lower = np.array([-3.0] + [-1.0] * 99) upper = np.array([-2.0] + [1.0] * 99) assert _score(lower, upper)["placebo_rejection_rate"] == pytest.approx(0.01) - assert _score(lower, upper, effect_size=0.5)["power"] == 0.0 + assert _score(lower, upper, effect_size=0.5)["power"] == pytest.approx(0.01) assert _score(lower, upper, effect_size=-0.5)["power"] == pytest.approx(0.01) + # Once the effect moves that interval across zero it stops counting. + assert _score(lower, upper, effect_size=2.5)["power"] == pytest.approx(0.99) + + def test_mde_is_set_from_the_effects_side_only(self): + # 30 intervals lie below zero. Shifted by a positive effect of 0.7 + # they still exclude zero, on the wrong side, so power is already at + # the target there; the MDE does not count them and stays at 1. + lower = np.array([-3.0] * 30 + [-1.0] * 70) + upper = np.array([-2.0] * 30 + [1.0] * 70) + row = _score(lower, upper, alpha=0.5, power=0.3, effect_size=0.7) + assert row["power"] == pytest.approx(0.3) + assert row["mde"] == pytest.approx(1.0) + # Above the MDE the target holds for both signs. + for sign in (1.0, -1.0): + assert ( + _score(lower, upper, alpha=0.5, power=0.3, effect_size=sign * 1.001)["power"] >= 0.3 + ) def test_power_at_zero_effect_is_the_placebo_rate(self): lower = np.array([1.0, -3.0] + [-1.0] * 98) @@ -508,7 +528,8 @@ def test_negative_effect_size(self, cs_surface): draws, _ = design_module._placebo_draw_record(cs_surface) intervals = _intervals(HonestDiD(), draws, 0.5) row = _table(HonestDiD(), cs_surface, M_grid=[0.5], effect_size=-3.0).iloc[0] - assert row["power"] == pytest.approx(np.mean(intervals[:, 1] - 3.0 < 0), abs=1e-12) + expected = np.mean((intervals[:, 1] - 3.0 < 0) | (intervals[:, 0] - 3.0 > 0)) + assert row["power"] == pytest.approx(expected, abs=1e-12) def test_progress_lines(self, cs_diagnosis, capsys): with warnings.catch_warnings(): @@ -534,6 +555,7 @@ def test_over_rejecting_interval_is_withheld(self, panel, cs): assert row["placebo_rejection_rate"] > 0.15 assert np.isfinite(row["ci_width"]) assert np.isnan(row["mde"]) and np.isnan(row["power"]) + assert bool(row["size_controlled"]) is False withheld = [w for w in recorded if "fails the size check" in str(w.message)] assert len(withheld) == 1 assert "M=0 (excludes zero with no effect in" in str(withheld[0].message) @@ -543,6 +565,7 @@ def test_interval_that_holds_its_level_is_not_flagged(self, cs_diagnosis): warnings.simplefilter("error") table = HonestDiD().power_by_M(cs_diagnosis, M_grid=[1.0], progress=False) assert np.isfinite(table["mde"][0]) + assert bool(table["size_controlled"][0]) is True def test_only_the_failing_rows_are_blank(self, panel, cs): diagnosis = _diagnose(panel, [cs], n_simulations=60, n_treated=4) @@ -571,7 +594,7 @@ def flaky(self, *args, **kwargs): monkeypatch.setattr(CallawaySantAnna, "fit", flaky) diagnosis = _diagnose(panel, [cs], n_simulations=40) monkeypatch.undo() - null = diagnosis.results["CallawaySantAnna"][0] + null = diagnosis.power_results["CallawaySantAnna"][0] assert null.n_simulation_failures > 0.1 * 40 surface = diagnosis.event_study_results["CallawaySantAnna"] draws, n_lost = design_module._placebo_draw_record(surface) @@ -724,6 +747,9 @@ def test_fitted_model_entry_points_still_refuse_a_placebo_input(self, cs_diagnos lambda: honest.fit(cs_surface), lambda: honest.sensitivity_analysis(cs_surface), lambda: honest.breakdown_value(cs_surface), + # The diagnosis itself gets the same pointer, not a generic error. + lambda: honest.fit(cs_diagnosis), + lambda: honest.sensitivity_analysis(cs_diagnosis), ): with pytest.raises(ValueError, match="HonestDiD.power_by_M"): call() @@ -787,7 +813,7 @@ def test_the_diagnosis_itself_is_unchanged(self, panel, cs, cs_diagnosis): plain = _diagnose(panel, [cs], event_study=False) assert plain.summary() != "" for with_draws, without in zip( - cs_diagnosis.results["CallawaySantAnna"], plain.results["CallawaySantAnna"] + cs_diagnosis.power_results["CallawaySantAnna"], plain.power_results["CallawaySantAnna"] ): assert with_draws.power == without.power assert with_draws.mean_estimate == without.mean_estimate diff --git a/tests/test_diagnostic_marker.py b/tests/test_diagnostic_marker.py index 471fbb3e9..cf5537404 100644 --- a/tests/test_diagnostic_marker.py +++ b/tests/test_diagnostic_marker.py @@ -231,3 +231,21 @@ def test_describe_target_parameter_bacon_still_twfe(bacon_result): block = describe_target_parameter(bacon_result) assert block["aggregation"] == "twfe" assert block["headline_attribute"] == "twfe_estimate" + + +def test_constructed_reconciliation_uses_the_status_vocabulary(constructed): + # The shared fixture holds one check of each status; the summary and the + # report block must both see the skipped one (its status is "not_checked"). + from diff_diff._reporting_helpers import describe_design_reconciliation + + reconciliation = constructed["DesignReconciliationResults"] + assert [check["status"] for check in reconciliation.checks] == [ + "match", + "deviates", + "not_checked", + ] + assert "1 not checked" in reconciliation.summary() + assert "not_checked=1" in repr(reconciliation) + block = describe_design_reconciliation(reconciliation) + assert (block["n_match"], block["n_deviates"], block["n_not_checked"]) == (1, 1, 1) + assert block["not_checked"] == ["n_units"] diff --git a/tests/test_methodology_design.py b/tests/test_methodology_design.py index f05aad16c..dcc0857b7 100644 --- a/tests/test_methodology_design.py +++ b/tests/test_methodology_design.py @@ -81,26 +81,26 @@ class TestSerialCorrelationOverRejection: """ def test_unclustered_standard_errors_over_reject(self, serial_correlation_result): - null = serial_correlation_result.results["twfe_classical"][0] + null = serial_correlation_result.power_results["twfe_classical"][0] assert null.true_effect == 0.0 assert null.rejection_rate > 0.25 assert serial_correlation_result.size_controlled["twfe_classical"] is False def test_unit_clustered_standard_errors_are_near_nominal(self, serial_correlation_result): - null = serial_correlation_result.results["twfe_clustered"][0] + null = serial_correlation_result.power_results["twfe_clustered"][0] assert null.rejection_rate < 0.12 assert serial_correlation_result.size_controlled["twfe_clustered"] is True def test_both_variants_share_point_estimates(self, serial_correlation_result): """Same estimator, same placebo draws: only the inference differs.""" - cells = serial_correlation_result.results + cells = serial_correlation_result.power_results for i in range(4): assert cells["twfe_classical"][i].mean_estimate == pytest.approx( cells["twfe_clustered"][i].mean_estimate, abs=1e-10 ) def test_coverage_mirrors_size_under_the_null(self, serial_correlation_result): - for cells in serial_correlation_result.results.values(): + for cells in serial_correlation_result.power_results.values(): null = cells[0] assert null.coverage == pytest.approx(1.0 - null.rejection_rate, abs=1e-12) @@ -109,13 +109,13 @@ class TestEffectInjection: """Bertrand et al. (2004), pp.259, 261: add the effect to treated observations.""" def test_power_rises_with_the_injected_effect(self, serial_correlation_result): - cells = serial_correlation_result.results["twfe_clustered"] + cells = serial_correlation_result.power_results["twfe_clustered"] powers = [cell.power for cell in cells] assert powers[0] < powers[1] < powers[2] <= powers[3] assert powers[3] > 0.8 def test_estimates_are_unbiased_for_the_injected_effect(self, serial_correlation_result): - cells = serial_correlation_result.results["twfe_clustered"] + cells = serial_correlation_result.power_results["twfe_clustered"] for cell in cells: # Bias is the same at every effect: the placebo draws are shared. assert cell.bias == pytest.approx(cells[0].bias, abs=1e-10) @@ -123,7 +123,7 @@ def test_estimates_are_unbiased_for_the_injected_effect(self, serial_correlation def test_over_rejecting_test_shows_inflated_power(self, serial_correlation_result): """The raw rejection rate of an over-sized test is not size-adjusted.""" - cells = serial_correlation_result.results + cells = serial_correlation_result.power_results assert cells["twfe_classical"][1].power > cells["twfe_clustered"][1].power @@ -141,7 +141,7 @@ def test_two_treated_units_over_reject(self): n_treated=2, n_simulations=300, ) - for label, cells in result.results.items(): + for label, cells in result.power_results.items(): assert cells[0].rejection_rate > 0.15, label assert result.size_controlled[label] is False, label @@ -153,7 +153,7 @@ def test_twenty_treated_units_are_near_nominal(self): n_treated=20, n_simulations=300, ) - for label, cells in result.results.items(): + for label, cells in result.power_results.items(): assert cells[0].rejection_rate < 0.12, label @@ -162,7 +162,7 @@ class TestDocumentedChoices: def test_rmse_is_the_existing_sample_sd_form(self, serial_correlation_result): """Not Blair et al.'s root mean squared error: the variance term uses ddof=1.""" - cell = serial_correlation_result.results["twfe_clustered"][2] + cell = serial_correlation_result.power_results["twfe_clustered"][2] estimates = np.array([r["estimate"] for r in cell.simulation_results]) bias = estimates.mean() - cell.true_effect assert cell.rmse == pytest.approx(np.sqrt(bias**2 + estimates.std(ddof=1) ** 2)) @@ -182,7 +182,7 @@ def test_mde_is_close_to_the_normal_multiplier(self): power=0.8, ) assert result.size_controlled["did"] is True - spread = result.results["did"][0].std_estimate + spread = result.power_results["did"][0].std_estimate multiplier = stats.norm.ppf(0.975) + stats.norm.ppf(0.8) assert result.mde["did"] == pytest.approx(multiplier * spread, rel=0.25) assert result.mde_results["did"].power_at_mde >= 0.8 @@ -208,9 +208,12 @@ def test_fixed_panel_and_resampled_panel_both_run(self): resampled = diagnose(panel, estimator, **kwargs) fixed = diagnose(panel, estimator, resample_units=False, **kwargs) assert resampled.resample_units is True and fixed.resample_units is False - assert fixed.results["did"][0].n_simulations == 100 + assert fixed.power_results["did"][0].n_simulations == 100 # Different designs, hence different draws. - assert fixed.results["did"][0].mean_estimate != resampled.results["did"][0].mean_estimate + assert ( + fixed.power_results["did"][0].mean_estimate + != resampled.power_results["did"][0].mean_estimate + ) def test_staggered_declaration_draws_each_unit_from_the_declared_periods(self): panel = ar1_panel(40, 12, 0.3, seed=5) @@ -222,7 +225,7 @@ def test_staggered_declaration_draws_each_unit_from_the_declared_periods(self): effect_sizes=[1.0], n_simulations=100, ) - for label, cells in result.results.items(): + for label, cells in result.power_results.items(): assert cells[1].mean_estimate == pytest.approx(1.0, abs=0.15), label assert cells[1].power > cells[0].power, label @@ -273,7 +276,7 @@ def test_rerun_of_a_correctly_sized_estimator_is_near_nominal(self, locked): def test_rerun_is_separate_from_the_comparison(self, locked): result, lock = locked - compared = result.results["twfe_clustered"] + compared = result.power_results["twfe_clustered"] for cell, row in zip(compared, lock.rerun_results): assert row["true_effect"] == cell.true_effect assert row["mean_estimate"] != cell.mean_estimate diff --git a/tests/test_staggered_jackknife.py b/tests/test_staggered_jackknife.py index d1124be12..fd4d2fdaf 100644 --- a/tests/test_staggered_jackknife.py +++ b/tests/test_staggered_jackknife.py @@ -941,8 +941,11 @@ def test_refused_on_dml_did(self): res = DMLDiD(seed=0).fit( data, "outcome", "unit", "period", "first_treat", covariates=["x"] ) - with pytest.raises(ValueError, match="requires vcov_type='jackknife'"): + # DMLDiD has no vcov_type option: the accessor it inherits says that it + # is not available, and does not send the user to another estimator. + with pytest.raises(ValueError, match="not available for DMLDiD results") as excinfo: res.get_loo_effects_df() + assert "CallawaySantAnna" not in str(excinfo.value) def full_labels(reps, by_label): diff --git a/tests/test_t34_design_diagnosis_drift.py b/tests/test_t34_design_diagnosis_drift.py index 5dda2e703..00694240c 100644 --- a/tests/test_t34_design_diagnosis_drift.py +++ b/tests/test_t34_design_diagnosis_drift.py @@ -337,7 +337,7 @@ def diagnosis(history): @pytest.mark.slow def test_size_verdicts(diagnosis): """Section 3: classical SEs over-reject by a wide margin; the others pass.""" - size = {label: runs[0].rejection_rate for label, runs in diagnosis.results.items()} + size = {label: runs[0].rejection_rate for label, runs in diagnosis.power_results.items()} threshold = 0.05 + 1.96 * np.sqrt(0.05 * 0.95 / N_SIMULATIONS) assert round(threshold, 3) == 0.080 assert size["twfe_classical"] > 0.25 # prose: 32.5% @@ -355,9 +355,9 @@ def test_power_and_mde(diagnosis): """Section 3: cs has the most power and the smallest MDE among those passing.""" passing = ("twfe", "cs", "imp") for cell in (1, 2): - power = {label: diagnosis.results[label][cell].power for label in passing} + power = {label: diagnosis.power_results[label][cell].power for label in passing} assert max(power, key=power.get) == "cs" - assert abs(diagnosis.results["cs"][2].power - 0.56) < 0.05 # "roughly a coin flip" + assert abs(diagnosis.power_results["cs"][2].power - 0.56) < 0.05 # "roughly a coin flip" assert min(passing, key=lambda label: diagnosis.mde[label]) == "cs" assert abs(diagnosis.mde["cs"] - 0.65) < 0.05 assert diagnosis.mde["cs"] > TRUE_EFFECT # the design cannot reliably detect 0.5