Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
00b44c9
fix(stacked_did): anticipation-aware clean controls and survey-infere…
igerber Nov 27, 2026
3af17a3
fix(visualization, reporting): undefined stored inference stays undef…
igerber Nov 27, 2026
ee4ddd4
fix(visualization, reporting): break the Plotly band at rows without …
igerber Nov 27, 2026
0af98e5
fix(visualization): draw a one-row band segment as a vertical bar so …
igerber Nov 27, 2026
9a120d4
test(visualization): pin the undefined-row and isolated-row plot case…
igerber Nov 27, 2026
3ea641f
fix(visualization, reporting): undefined inference on the dCDH plot r…
igerber Nov 27, 2026
e103467
fix(visualization): the Plotly band bridges only a declared or caller…
igerber Nov 27, 2026
97b8566
fix(visualization): keep a declared reference label exact; it is a co…
igerber Nov 27, 2026
13cc9e7
fix(visualization): compare a declared reference label without a floa…
igerber Nov 27, 2026
b8a69a0
fix(visualization): compare horizon and reference labels exactly, acr…
igerber Nov 27, 2026
4605dd7
refactor(visualization): reduce the plot change to the undefined-infe…
igerber Nov 27, 2026
3a5b4a8
docs(todo): track the mixed-type horizon label handling in plot_event…
igerber Nov 27, 2026
a4c9148
fix(stacked_did, visualization, reporting): validate implicit PSUs on…
igerber Nov 27, 2026
acd102d
fix(reporting): say the requested alpha cannot produce an interval, n…
igerber Nov 27, 2026
63a8b06
fix(stacked_did): an empty panel raises a descriptive ValueError befo…
igerber Nov 27, 2026
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
4 changes: 3 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ Related tracking surfaces:
| 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` + `survey_design=` REFUSES (`NotImplementedError`) a panel holding a cohort with no pre-treatment observation, where the unweighted fit excludes the cohort with a warning: dropping its rows under a survey design is naive subsetting, not domain estimation (strata, PSU counts and the design df change). Implement the design-based version - keep the rows and give the excluded cohort no contribution to the other cohorts' estimates or scores - together with the same gap in `WooldridgeDiD` (its domain-estimation row below); one mechanism serves both. | `diff_diff/sun_abraham.py`, `diff_diff/wooldridge.py` | SunAbraham reference PR | Heavy | Low |
| `SunAbraham` + `survey_design=` fails with an array shape mismatch (`operands could not be broadcast together with shapes (720,) (712,)`) when the frame holds a unit whose `first_treat` is negative or missing: the survey arrays are sized to `data`, while `df_reg` drops those rows under `control_group="never_treated"`. Loud, not silent, and pre-existing. Either filter the survey arrays with the same mask or reject such rows up front with a clear message; decide what a negative `first_treat` means first (today it is silently neither treated nor a control). | `diff_diff/sun_abraham.py` | SunAbraham reference PR | Quick | Low |
| `StackedDiD` + `survey_design=` does not retain the full survey design. The design is re-resolved on the stacked rows, so the PSUs and strata of every unit outside the stack leave the Taylor-linearized meat and `df_survey` with no warning (balanced panel, 120 single-unit PSUs in 3 strata, one cohort trimmed by IC1 under `control_group="never_treated"`: 90 PSUs in the fit, `df_survey` 87 where the full design gives 117). For the same reason two cases are REFUSED (`NotImplementedError`) under a survey design where the unweighted fit proceeds with a warning: a unit not observed across its event window, and an adoption event left without complete units. Implement domain estimation - keep the full design and give out-of-stack PSUs zero scores (REGISTRY *Subpopulation Analysis*) - then lift both refusals. | `diff_diff/stacked_did.py`, `diff_diff/survey.py` | StackedDiD complete-window PR | Mid | Medium |
| `plot_event_study` on the plotly backend filters rows without an interval out of the band polygon and fills across their position, so an estimate whose inference is undefined (or whose SE is zero) appears inside a shaded band when its neighbours have intervals; matplotlib draws no bar there. Break the band at such rows (one polygon per run, a visible bar for a one-row run) and continue it only across a real normalization constraint. Doing that needs reference provenance on the raw-results route, which today styles event time `-1` as the reference when the producer marks none (an estimated placebo under `base_period="varying"`) and casts a declared `reference_period` with `int()` (a reference at `-0.5`, as `SunAbraham` can declare, lands on event time 0), plus exact handling of horizon labels of mixed numeric types: the plotting DataFrame coerces mixed int/float labels to `float64`, and `==` between an integer reference and a float horizon is lossy beyond 2**53, so two distinct horizons can share a position (and one can be masked as the reference under explicit normalization). Keep native labels through rendering and position rows by index. | `diff_diff/visualization/_event_study.py` | StackedDiD anticipation PR | Mid | Medium |
| Zero survey degrees of freedom (`df_survey = n_PSU - n_strata = 0` under Taylor linearization) is not handled one way. `StackedDiD` returns NaN inference with a warning, and `safe_inference` returns NaN for any `df <= 0`. `SunAbraham` clamps the df to 1 for its overall and event-study aggregates (`max(survey_metadata.df_survey, 1)`), which then get t(1) inference, while its cell-level inference goes through `LinearRegression.get_inference`, which warns and falls back to the normal distribution for a non-positive df (measured: six units in six strata, `lonely_psu="adjust"`). Decide the rule for a variance-unidentified design (NaN) and apply it in `SunAbraham` and in `get_inference`'s survey branch. | `diff_diff/sun_abraham.py`, `diff_diff/linalg.py` | StackedDiD anticipation PR | Mid | Medium |
| `StackedDiD` + `survey_design=` does not retain the full survey design. The design is re-resolved on the stacked rows, so the PSUs and strata of every unit outside the stack leave the Taylor-linearized meat and `df_survey` with no warning (balanced panel, 120 single-unit PSUs in 3 strata, one cohort trimmed by IC1 under `control_group="never_treated"`: 90 PSUs in the fit, `df_survey` 87 where the full design gives 117). For the same reason three cases are REFUSED (`NotImplementedError`) under a survey design where the unweighted fit proceeds: a unit not observed across its event window, an adoption event left without complete units, and (with `anticipation > 0`) a later cohort that the anticipation-adjusted clean-control cutoff leaves out of every sub-experiment. Implement domain estimation - keep the full design and give out-of-stack PSUs zero scores (REGISTRY *Subpopulation Analysis*) - then lift the three refusals. | `diff_diff/stacked_did.py`, `diff_diff/survey.py` | StackedDiD complete-window PR | Mid | Medium |
| 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 Down
84 changes: 84 additions & 0 deletions changelog.d/20261127-stacked-did-anticipation-survey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
### Fixed
- **`StackedDiD` with `anticipation > 0` no longer uses a later adopter as a
control while that unit is already responding.** The clean-control cutoff
ignored `anticipation`, so under `control_group="not_yet_treated"` (the
default) a cohort adopting at `a + kappa_post + 1` up to
`a + kappa_post + anticipation` stayed in event `a`'s control pool through
periods in which it had started to respond, and the estimate was biased
with no warning. On a noiseless balanced panel (periods 0-8, equal-sized
cohorts adopting at 3 and 6 plus never-treated units, an effect of 2
starting one period before adoption, `kappa_pre = kappa_post = 2`,
`anticipation = 1`) the fit returned 1.5 at event time 2 and an overall ATT
of 1.875; both are now 2 exactly. The cutoff is now
`A_s > a + kappa_post + anticipation`, and
`A_s > a + kappa_post + kappa_pre + anticipation` under
`control_group="strict"`. A strict fit used a responding control only when
`anticipation > kappa_pre`, but its control set changes more widely: the
new cutoff also drops later cohorts adopting up to `anticipation` periods
past the old one, so that their own window, which now starts
`anticipation` periods earlier, stays disjoint from this one. The inclusion check uses the
same rule, so an adoption event whose only later cohort falls inside the
cutoff is now trimmed. Estimates change only for fits with
`anticipation > 0` that had a later cohort between the old and the new
cutoff; `anticipation=0` and `control_group="never_treated"` are unchanged.
Under `survey_design=`, a fit in which the `anticipation` term leaves a
later cohort out of every sub-experiment now raises `NotImplementedError`:
the design is re-resolved on the stacked rows, so that cohort's PSUs or
strata can leave the variance and its degrees of freedom (on a stratified
census the fit would have reported SE 0.136 with 9 df where the full design
gives SE 0 with 15 df).
Each fit records the rule on the new
`StackedDiDResults.control_cutoff_includes_anticipation` (`True`; `None` on
a result saved by an earlier version). For a `"not_yet_treated"` or
`"strict"` result with `anticipation > 0`, `BusinessReport` and
`DiagnosticReport` state the adjusted cutoff when the result records it; when
it does not, they show the earlier cutoff, label it unverified and say to
rerun the fit. Results with `anticipation=0` or never-treated controls get
no such caveat. Separately, the `BusinessReport` assumption text now gives
the event window with its `anticipation` term whenever `anticipation > 0`.

- **`StackedDiD` + `survey_design=` without a `psu` column no longer uses
`(unit, sub-experiment)` pairs as survey PSUs under
`cluster="unit_subexp"` (Taylor-linearized variance; replicate-weight
designs are unaffected).** Each original unit is the PSU, as it already was
under the default `cluster="unit"`; a `UserWarning` says that
`"unit_subexp"` does not apply to the survey variance. The pairs duplicated
sampled units and their count moved with the stack: on a stratified panel
with a finite-population correction the fit reported SE 0 with 21 survey
degrees of freedom where the sampled units give SE 0.07906 with 15.
Standard errors change for survey fits that combined `cluster="unit_subexp"`
with a design that names no `psu`; fits with an explicit `psu` or the
default cluster are unchanged.
- **`StackedDiD` + `survey_design=` with zero survey degrees of freedom now
returns NaN inference.** When `n_PSU - n_strata = 0` under Taylor
linearization (for example one PSU per stratum with `lonely_psu="adjust"`)
the df was clamped to 1 and the fit reported t(1) p-values and confidence
intervals. Estimates and standard errors are still reported; t-statistics,
p-values and intervals are NaN, overall and per event time, with a
`UserWarning`.
- **`StackedDiD` + `survey_design=` without a `psu` column validates its
implicit unit PSUs like explicit ones.** A stratum with a single unit now
warns that it is excluded from variance estimation under
`lonely_psu="remove"`, and a finite-population size below a stratum's unit
count raises `ValueError`; both checks were skipped before. The count is
that of the supplied sample, not of the units that reach the stack.
- **`plot_event_study(results)` no longer rebuilds intervals for rows whose
stored inference is undefined.** A results object passed directly has its
intervals recomputed from the standard error; a row with a finite standard
error and a stored interval with a missing or NaN endpoint (inference
failed closed, for example a
survey design with zero degrees of freedom) now gets none, as the
`aggregate("event_study")` container already did. This holds for dCDH
results (effects and placebos) too. On the matplotlib backend the row is a
point with no error bar. The Plotly backend still fills its band across
the position of such a row when the rows on both sides have intervals.
- `BusinessReport` no longer describes a Taylor-linearized fit with zero
survey degrees of freedom as "replicate-weight" inference whose interval
"remains at the fit's native level". The same applies to a replicate
design that records no degrees of freedom and stored no interval. When the fit stored no interval it
names the variance method and says that none is available; when the fit
did store one (an estimator that falls back to a reference distribution at
zero df) it describes that interval.
- `StackedDiD.fit()` on a panel with no rows raises a `ValueError` that says
so. It raised "cannot convert float NaN to integer", or an `IndexError`
when the survey design named a finite-population column.
47 changes: 44 additions & 3 deletions diff_diff/_reporting_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

from __future__ import annotations

from typing import Any, Dict, List, Optional
from typing import Any, Dict, List, Optional, Tuple

from diff_diff.results_base import Diagnostic

Expand Down Expand Up @@ -180,6 +180,46 @@ def is_staggered_ddd(results: Any) -> bool:
return results_design(results) == "staggered"


def stacked_control_cutoff_wording(results: Any) -> Tuple[str, str]:
"""Wording for a StackedDiD result's clean-control cutoff.

Returns ``(shift, caveat)``: ``shift`` is appended to the cutoff formula
and ``caveat`` to the sentence that states it.

Under ``anticipation > 0`` a later adopter responds from
``A_s - anticipation``, and fits select later-adopter controls with
``+ anticipation`` in the cutoff. A fit records that on
``control_cutoff_includes_anticipation``. A result without the record
(saved by diff-diff 4.1.0 or earlier, whose cutoff ignored
``anticipation``, or built by hand) is described with the cutoff those
versions used and a caveat that the rule is unverified, so that a report
never asserts a comparison set the fit may not have used.

Both strings are empty when ``anticipation == 0`` (the rule never
changed) and for never-treated controls (no cutoff applies).
"""
if (getattr(results, "anticipation", 0) or 0) <= 0:
return "", ""
if getattr(results, "control_group", None) == "never_treated":
return "", ""
if getattr(results, "control_cutoff_includes_anticipation", None) is True:
return (
" + anticipation",
" A later adopter responds from ``A_s - anticipation``, which is "
"why the cutoff includes it.",
)
return (
"",
" This result does not record which cutoff built its stack, so the "
"rule shown is unverified: it is the one diff-diff 4.1.0 and earlier "
"used, which ignores ``anticipation``. If the result was fitted with "
"one of those versions, a later adopter may be a control while it is "
"already responding (from ``A_s - anticipation``) and the fit should "
"be rerun; later versions add ``+ anticipation`` to the cutoff and "
"record that on the result.",
)


def describe_target_parameter(results: Any) -> Dict[str, Any]:
"""Return the target-parameter block for a fitted result.

Expand Down Expand Up @@ -427,19 +467,20 @@ def describe_target_parameter(results: Any) -> Dict[str, Any]:
# clean_control fallback (a getattr default would silently
# misreport the comparison group after the 4.0 removal).
clean_control = getattr(results, "control_group", None)
shift, cutoff_caveat = stacked_control_cutoff_wording(results)
if clean_control == "never_treated":
control_clause = "Controls are the never-treated units (``A_s = infinity``)."
elif clean_control == "strict":
control_clause = (
"Controls for each sub-experiment ``a`` are units strictly "
"untreated across the full pre/post event window "
"(``A_s > a + kappa_post + kappa_pre``)."
f"(``A_s > a + kappa_post + kappa_pre{shift}``).{cutoff_caveat}"
)
else: # "not_yet_treated" or unknown -> default rule
control_clause = (
"Controls for each sub-experiment ``a`` are units not yet "
"treated through the event's post-window "
"(``A_s > a + kappa_post``)."
f"(``A_s > a + kappa_post{shift}``).{cutoff_caveat}"
)
# Each scheme aggregates the sub-experiment ATTs with its own cohort
# share (Wing et al. 2024, Table 1); a getattr default keeps results
Expand Down
Loading
Loading