Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions benchmarks/python/pretrend_planning_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]),
Expand Down Expand Up @@ -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))
Expand All @@ -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():
Expand Down
6 changes: 4 additions & 2 deletions changelog.d/20261126-sensitivity-planning.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions diff_diff/_reporting_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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"]],
}


Expand Down
34 changes: 17 additions & 17 deletions diff_diff/design.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 = (
Expand All @@ -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.
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 "-"
Expand All @@ -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}"
Expand Down Expand Up @@ -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)
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -2174,7 +2174,7 @@ def diagnose_design(
_ABSENT = "<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")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions diff_diff/dml_did_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``)."""
Expand Down
4 changes: 2 additions & 2 deletions diff_diff/guides/llms-autonomous.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 10 additions & 8 deletions diff_diff/guides/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -2573,7 +2575,7 @@ and `checks` (one per item: `estimator_name`, `params.<name>`,
`estimator_kwargs.<key>`, `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
Expand All @@ -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`.
Expand Down
Loading
Loading