Skip to content
Merged
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
9 changes: 8 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ Related tracking surfaces:
| `absorbed_fe_rank` N>=3 general rank: the helper keeps `sum(levels-1)` for 3+ absorbed dims, exact for independent connected dims but an over-count for duplicated/nested triples (measured `a(5),b(4),c==b(4)`: true 7 vs formula 10) and for disconnected N-way graphs. Two-way is component-exact. Deriving general N-way FE rank is a hypergraph problem; do it with a reference (fixest's `fixef.rm`/reghdfe df_a) rather than a guess. See `docs/methodology/variance-conventions.md` D3. | `diff_diff/utils.py` | #variance-inventory | Mid | Low |
| `SyntheticControl` conformal (CWZ 2021) AR / innovation-permutation path (Lemmas 5-7) for time-series proxies — the residual-permutation shortcut is only valid for time-permutation-invariant proxies (SC/Lasso/DiD); an AR proxy needs innovation permutation. | `diff_diff/conformal.py`, `diff_diff/synthetic_control_results.py` | CWZ-2021 | Heavy | Low |
| Re-run the R-dependent benchmark refresh so `docs/benchmarks.rst`'s TWFE "SE Rel Diff 0.1%" cell reflects the 3.9 K_reference convergence (expected 0.1% -> 0.0%; the table is generated, never hand-edited — the movement is noted in the CHANGELOG entry). | `docs/benchmarks.rst`, `benchmarks/R/` | #variance-inventory | Quick | Low |
| `SunAbraham`: a cohort not observed at its own reference relative period (`e = -1 - anticipation`) makes that cohort's block collinear, so QR drops an unnamed column (`dropping 1 of 12 columns (column 9)`) and `overall_att` comes back **NaN**. Found by auditing the sibling estimator while fixing the ETWFE analogue (#724); PRE-EXISTING, not introduced there. Lower severity than #724 — that returned a silently WRONG finite number, this returns NaN with a rank warning — but the event-study surface still looks complete, so a user may not notice the loss. SA already omits its reference explicitly and tracks `_reference_observed`, so the fix is per-cohort support for that flag rather than the ETWFE-style redesign. | `diff_diff/sun_abraham.py` | #724-audit | Mid | Low |
| `SunAbraham`: a cohort not observed at its own reference relative period (`e = -1 - anticipation`) makes that cohort's block collinear, so QR drops an unnamed column (`dropping 1 of 12 columns (column 9)`) and `overall_att` comes back **NaN**. Reproduces on the bundled `load_divorce_laws()` panel (cohort 1968 is treated from the first panel year), where `SunAbraham().fit(...)` returns `att = NaN` after "dropping 1 of 261 columns (column 10)". Found by auditing the sibling estimator while fixing the ETWFE analogue (#724); PRE-EXISTING, not introduced there. Lower severity than #724 — that returned a silently WRONG finite number, this returns NaN with a rank warning — but the event-study surface still looks complete, so a user may not notice the loss. SA already omits its reference explicitly and tracks `_reference_observed`, so the fix is per-cohort support for that flag rather than the ETWFE-style redesign. | `diff_diff/sun_abraham.py` | #724-audit | Mid | Low |
| Define `N_g` (W2025 Eqs. 7.4/7.6) for UNBALANCED panels where comparison-support filtering removes every observation of some units in an estimated cohort, then replace the fail-closed guard with the defined behavior. `_n_g_per_cohort` is read off the final sample, so those units vanish from the cohort-share weights; measured on a cohort supplied with 100 units of which 90 appear only at a dropped period, `aggregate(weights="cohort_share")` moves 1.8078 -> 3.8157. The paper assumes a balanced panel and does not say whether `N_g` counts the supplied cohort or the surviving units, and the two disagree materially, so `aggregate` currently raises naming the cohorts and counts ([M-125]); `weights="cell"` is unaffected and balanced panels never trip it. Settle the estimand (likely: count the supplied cohort, since ATT(g,t) is a cohort-level quantity, but that weights units with no retained observation) and gate with a test computing Eq. 7.4 by hand on unequal cohort sizes. | `diff_diff/wooldridge_results.py`, `diff_diff/wooldridge.py` | #729-followup | Mid | Medium |
| `WooldridgeDiD` + `survey_design=` does not support DOMAIN ESTIMATION, so BOTH row-deleting paths are currently REFUSED (`NotImplementedError`, all three methods) rather than performed: unidentified-cohort exclusion ([M-123]) and comparison-support period filtering ([M-125]). One fix unblocks both. Implementing it properly means zero-padding the excluded rows' weights while retaining strata/PSU/FPC, per REGISTRY *Subpopulation Analysis (Phase 6)* / Lumley (2004) 3.4, so TSL variance and `df_survey = n_PSU - n_strata` use the full design (naive deletion measured 22 -> 14 on a two-stratum panel). `SurveyDesign.subpopulation()` already implements the contract and SpilloverDiD Wave E.3 is the in-repo precedent; the blocker is that the weighted within-transform rejects zero-weight units, shared machinery behind 7 estimators. Landing it would turn both refusals back into supported fits. Gate with a `SurveyDesign.subpopulation()` parity test on ATT, TSL SE and survey df where the excluded cohort exhausts a PSU. | `diff_diff/wooldridge.py`, `diff_diff/utils.py` | #724-codex-R4/R5 | Heavy | Medium |
| `WooldridgeDiD` REFUSES a fit whose only treatment cells fall inside the anticipation window, discarding estimates it successfully computed. `_require_estimable_overall_att` ([M-124]) raises when no cell has `t >= g`, because the overall ATT averages only `t >= g` (W2025 excludes anticipation leads) while cells from `t >= g - anticipation` are ESTIMATED. For a cohort never observed at or after its own treatment date, those anticipation-window ATT(g, t) are real, identified estimates and are thrown away with the fit. **The refusal is a stopgap for the missing estimand semantics, not the intended end state.** Real fix: decide what such a fit should return — most likely the per-cell ATT(g, t) plus an overall that is explicitly undefined with a stated reason (not a bare NaN, per the no-silent-NaN convention) — then relax the guard to that. Needs a REGISTRY note defining the estimand and an `aggregate()` story for the anticipation-only case. | `diff_diff/wooldridge.py` | #724-codex-R2 | Mid | Medium |
Expand All @@ -67,6 +67,13 @@ Related tracking surfaces:
| DurationDiD alternative finite-sample PH estimators (the repaired cumulative-increment slope of Equation 3.5 and the average-hazard slope of Equation 3.6) as an opt-in beside the shipped mean-of-ratios coefficient; they coincide under exact PH and differ under sampling noise (review table, lines 306-311) | `duration_did.py` | #822 | Mid | Low |
| `DiagnosticReport` / `BusinessReport` admission of `DurationDiDResults`: both reject it by type today (their batteries are keyed to mean-outcome parallel-trends diagnostics); admission needs a hazard-restriction check family (the Algorithm 2 pretest, the invalid-curve statuses, per-family bootstrap failure counts) and a narrative for per-date absorption ATTs | `diagnostic_report.py`, `business_report.py` | #822 | Mid | Low |
| `SyntheticControl` at an exact-fit tie (treated predictors inside the donors' convex hull): `W` and `V` are not identified, and the inner solve reports the active set's vertex (REGISTRY §SyntheticControl). A stated selection rule (Abadie-L'Hour 2021 penalty, or the minimum-norm `W`) is a methodology choice; note that any strictly convex tie-break makes `W(V)` continuous, and the nested search then moves `V` toward a corner where a predictor's weight is negligible (Tutorial 25 under a 1e-10 relative ridge: `V` = (0.017, 2e-12, 0.983)). | `synthetic_control.py`, `utils.py` | #838 | Mid | Low |
| `plot_event_study` rejects the unified `EVENT_STUDY_SCHEMA` frame that every `to_dataframe(level="event_study")` returns (`ValueError: DataFrame must have 'period' column`; the DataFrame branch accepts only `period`/`effect`/`se`). Accepting it needs two decisions first: which level the stored `conf_int_*` are drawn at when the frame carries no `alpha` to compare with the caller's, and how multiple `is_reference` rows map onto the container route's row-aligned marking. Plot the container (`results.aggregate('event_study')`) in the meantime. | `visualization/_event_study.py` | 4.0 tutorial review | Mid | Low |
| `WooldridgeDiDResults.to_dataframe(level="group" / "calendar" / "simple")` names its interval columns `conf_int_lo` / `conf_int_hi`, while its own `level="event_study"` frame and every other results class use `conf_int_lower` / `conf_int_upper`. A public column rename, so it needs a deprecation-ledger row and a transition release. | `wooldridge_results.py` | 4.0 tutorial review | Mid | Low |
| `ChangesInChanges.fit(time=)` takes the 0/1 post indicator, while the 2x2 estimators take that indicator as `post=` and reserve `time=` for the calendar column (the 4.0 TWFE split). Tutorial 27 shows the two side by side. Resolving it is a keyword rename with a ledger row. | `changes_in_changes.py` | 4.0 tutorial review | Mid | Low |
| TROP convergence defaults: on the tutorial-10 panels the default `max_iter=100` leaves most per-observation fits unconverged (the aggregated warning fires on essentially every fit), and the warning text reads "... fits did not converge did not converge in 100 iterations" because the callers pass a method name that already ends in "did not converge" to `warn_if_not_converged`. Fix the wording at the three call sites; separately assess whether the default iteration cap or tolerance should change (needs a convergence study on the paper's designs, not just the tutorial). | `trop.py`, `trop_local.py`, `trop_global.py`, `utils.py` | 4.0 tutorial review | Mid | Low |
| `ImputationDiDResults.pretrend_test()` emits pandas' `Pandas4Warning` ("The inplace keyword in DataFrame.drop is deprecated", PDEP-8) on pandas 3.1: three `drop(..., inplace=True)` calls in the lead-regression path. Rebind instead of dropping in place, and grep the package for the remaining `inplace=True` uses in the same pass. | `imputation_aggregation.py` | 4.0 tutorial review | Quick | Low |
| Conley bandwidth diagnostic: when `conley_cutoff_km` covers the whole treated set (one treated spatial cluster inside the bandwidth), the spatial-HAC meat collapses and the SE falls far below HC1 on data with no spatial correlation (tutorial 23's panel: HC1 0.117; Conley 0.117 at 0.5 km, 0.090 at 25 km, 0.062 at 100 km). This is the usual large-bandwidth HAC degeneracy, not a variance bug, but nothing warns. Candidate: a `UserWarning` when the share of treated-treated pairs inside the cutoff exceeds a threshold; the threshold needs a small simulation to choose. | `conley.py`, `spillover.py` | 4.0 tutorial review | Mid | Low |
| No public idiom for a static staggered TWFE with a time-varying covariate (`Y ~ D_it + X_it` with unit and calendar fixed effects): `TwoWayFixedEffects.fit` is 2x2-shaped in static mode and `decompose()` takes no covariates, so tutorial 33's "include the bad control" benchmark builds it from `within_transform` plus `solve_ols`. Either document that route as the supported one or add a staggered static mode. | `twfe.py`, `docs/tutorials/33_bad_controls.ipynb` | 4.0 tutorial review | Mid | Low |

### Performance

Expand Down
15 changes: 15 additions & 0 deletions changelog.d/20261125-plot-event-study-wooldridge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### Fixed
- **`plot_event_study` accepts `WooldridgeDiDResults`**: passing a Wooldridge
ETWFE result (the object `results.aggregate("event_study")` returns) raised
`KeyError: 'effect'`. The result is now converted to the unified event-study
container at entry, so its stored intervals are drawn as-is, the
stored-`alpha` mismatch warning applies, and a `weights="cohort_share"`
aggregation (NaN intervals by design) draws no error bars. A fit on which
`aggregate("event_study")` has not been called raises a `ValueError` naming
that call. On every container input, a row whose stored interval is NaN now
also stays without an interval under an explicit `reference_period=`
(previously the normalization path recomputed one from the SE, which would
have redrawn inference that a producer had disabled). A contract test now pins the one event-study idiom the tutorials
teach (`es = results.aggregate("event_study")` where the class has
`aggregate`, else the result; `plot_event_study(es)`) on all thirteen
estimators that produce an event study.
3 changes: 2 additions & 1 deletion diff_diff/guides/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2544,7 +2544,8 @@ All plotting functions return a matplotlib `Figure` object.
from diff_diff import plot_event_study

plot_event_study(
results, # EventStudyResults (TWFE event-study surface), CS, SA, BJS, TwoStageDiD, StackedDiD, or DataFrame
results, # EventStudyResults (TWFE event-study surface), CS, SA, BJS, TwoStageDiD, StackedDiD,
# WooldridgeDiD (after results.aggregate('event_study')), or DataFrame
effects=None, # Manual dict of effects (alternative to results)
se=None, # Manual dict of SEs
periods=None,
Expand Down
51 changes: 47 additions & 4 deletions diff_diff/visualization/_event_study.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from diff_diff.staggered import CallawaySantAnnaResults
from diff_diff.sun_abraham import SunAbrahamResults
from diff_diff.two_stage import TwoStageDiDResults
from diff_diff.wooldridge_results import WooldridgeDiDResults

# Type alias for results that can be plotted
PlottableResults = Union[
Expand All @@ -26,6 +27,7 @@
"TwoStageDiDResults",
"StackedDiDResults",
"ChaisemartinDHaultfoeuilleResults",
"WooldridgeDiDResults",
"EventStudyResults",
pd.DataFrame,
]
Expand Down Expand Up @@ -72,8 +74,12 @@ def plot_event_study(
Results object from CallawaySantAnna, a unified
:class:`~diff_diff.results_base.EventStudyResults` container (from
any producer's ``aggregate('event_study')`` or
``build_event_study_surface``), or a DataFrame with columns
'period', 'effect', 'se' (and optionally 'conf_int_lower',
``build_event_study_surface``), a
:class:`~diff_diff.WooldridgeDiDResults` on which
``aggregate('event_study')`` has been called (it is converted to
the unified container, so its stored intervals are drawn as-is;
an un-aggregated fit raises ``ValueError``), or a DataFrame with
columns 'period', 'effect', 'se' (and optionally 'conf_int_lower',
'conf_int_upper'). If None, must provide effects and se directly.
effects : dict, optional
Dictionary mapping periods to effect estimates. Used if results is None.
Expand Down Expand Up @@ -191,10 +197,27 @@ def plot_event_study(
# Track if reference_period was explicitly provided by user
reference_period_explicit = reference_period is not None

# WooldridgeDiDResults stores its event-study dict keyed ``att`` (not
# ``effect``) and returns ITSELF from ``aggregate("event_study")``, so
# convert it to the unified container here - BEFORE extraction and the
# stored-alpha guard - and let it take the EventStudyResults route end
# to end (stored intervals preserved, including the NaN intervals of a
# ``weights="cohort_share"`` aggregation, so no misleading error bars
# are recomputed from its conditional-on-shares SE). An un-aggregated
# fit raises the surface builder's ValueError naming the call to make.
if results is not None:
from diff_diff.wooldridge_results import WooldridgeDiDResults as _WooldridgeResults

if isinstance(results, _WooldridgeResults):
from diff_diff.results_base import build_event_study_surface

results = build_event_study_surface(results)

# Extract data from results if provided
ci_lower_override = None
ci_upper_override = None
reference_marks: Optional[Set[Any]] = None
undefined_inference: Set[Any] = set()
if results is not None:
(
effects,
Expand All @@ -210,6 +233,18 @@ def plot_event_study(
pw_upper_override,
reference_marks,
) = _extract_plot_data(results, periods, pre_periods, post_periods, reference_period)
# Rows whose STORED inference is undefined (a NaN stored pointwise
# interval on a route that carries one - the container route). Their
# inference was disabled by the producer (e.g. WooldridgeDiD
# ``weights="cohort_share"``, whose conditional-on-shares SE stays
# finite while t/p/CI fail closed to NaN), so no interval may be
# reconstructed for them from the SE on any later path.
if pw_lower_override is not None and pw_upper_override is not None:
undefined_inference = {
p
for p, lo in pw_lower_override.items()
if not (np.isfinite(lo) and np.isfinite(pw_upper_override.get(p, np.nan)))
}
# If reference was inferred from results, it was NOT explicitly provided
if reference_inferred:
reference_period_explicit = False
Expand Down Expand Up @@ -248,7 +283,14 @@ def plot_event_study(
effects = {p: e - ref_effect for p, e in effects.items()}
# Set reference SE to NaN (it's now a constraint, not an estimate)
# This follows fixest convention where the omitted category has no SE/CI
se = {p: (np.nan if p == reference_period else s) for p, s in se.items()}
# Rows with undefined STORED inference get a NaN SE too: the
# overrides are discarded just below and the intervals recomputed
# from the SE, which must not revive inference the producer
# disabled (their normalized point estimates still plot).
se = {
p: (np.nan if (p == reference_period or p in undefined_inference) else s)
for p, s in se.items()
}
# REGISTRY (Event Study Plotting): after explicit normalization,
# CIs are RECOMPUTED from the normalized effects and original
# SEs, and the reference CI becomes (NaN, NaN). Any simultaneous
Expand Down Expand Up @@ -1018,7 +1060,8 @@ def _extract_plot_data(
f"Cannot extract plot data from {type(results).__name__}. "
"Expected CallawaySantAnnaResults, "
"SunAbrahamResults, ImputationDiDResults, "
"ChaisemartinDHaultfoeuilleResults, EventStudyResults, or DataFrame. "
"ChaisemartinDHaultfoeuilleResults, WooldridgeDiDResults, "
"EventStudyResults, or DataFrame. "
"For a result that stores no event-study surface (DMLDiD, "
"EfficientDiD, every CallawaySantAnna fit since 4.0, and ANALYTICAL "
"ImputationDiD / TwoStageDiD / ContinuousDiD fits), plot the "
Expand Down
16 changes: 16 additions & 0 deletions docs/api/visualization.rst
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@ Example
ax = plot_event_study(results)
ax.figure.savefig('event_study.png', dpi=300, bbox_inches='tight')

For an estimator with post-fit aggregation, plot the event-study container:

.. code-block:: python

from diff_diff import CallawaySantAnna, WooldridgeDiD, plot_event_study

cs = CallawaySantAnna().fit(data, outcome='y', unit='unit_id',
time='period', first_treat='first_treat')
plot_event_study(cs.aggregate('event_study'))

# WooldridgeDiD.aggregate() returns the results object itself, which
# plot_event_study accepts once the event study has been aggregated
etwfe = WooldridgeDiD().fit(data, outcome='y', unit='unit_id',
time='period', first_treat='first_treat')
plot_event_study(etwfe.aggregate('event_study'))

plot_group_effects
------------------

Expand Down
Loading
Loading