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
4 changes: 3 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ 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**. 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 |
| `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` returns shifted estimates with NO warning on ragged event windows (found by the sibling audit for the SunAbraham reference fix). On a noiseless panel that the balanced fit recovers exactly (`kappa_pre=2, kappa_post=2`, true effect `2 + 0.5 e`): one cohort missing its `e = -1` rows shifts every event-study row by +0.164 (ATT 2.664 for a true 2.5); a cohort with no pre-treatment rows shifts the post rows by -0.164; ONE missing never-treated observation moves them by 0.003. The `balance="entropy"` path already fails closed on ragged windows (REGISTRY StackedDiD); the default path should either handle unit-level missingness inside a sub-experiment (unit fixed effects, or trimming to units observed over the whole window) or fail closed the same way. Establish what Wing, Freedman and Hollingsworth prescribe before choosing. | `diff_diff/stacked_did.py`, `docs/methodology/REGISTRY.md` | SunAbraham reference 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
70 changes: 70 additions & 0 deletions changelog.d/20261125-sunab-reference-support.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
### Fixed
- **`SunAbraham` no longer reports wrong finite numbers when a
cohort-by-period coefficient is not identified.** The saturated regression
omitted one relative period, `e = -1 - anticipation`, for every cohort.
Whenever some coefficient was not identified in that design the QR step
dropped one unnamed column (a data-dependent choice, often a
post-treatment one), every coefficient sharing the dependency was then
measured against the dropped one, and those numbers were pooled into the
event-study rows and the overall ATT. On a noiseless panel with true
effect `2 + 0.5 e` (90 units, 8 periods, cohorts 3 and 5):
- a cohort treated at the first panel period: overall ATT NaN, seven wrong
cohort coefficients, an `e = 0` row of 0.0 for a true 2.0;
- a cohort first observed at `e = 0`: ATT NaN, five wrong coefficients, an
`e = 0` row of -0.25;
- a cohort whose units are observed at disjoint sets of periods: ATT NaN,
four wrong coefficients, an `e = 0` row of 1.0;
- never-treated units absent at one post-treatment calendar period: ATT
NaN and an `e = 3` row of 2.25 for a true 3.5;
- a cohort with a gap at `e = -1`: the baseline for that cohort was
whichever of its columns QR dropped (a pre-period one on this panel,
which left the estimates right and the `e = -2` row NaN).
On 50 random-missingness panels, 14 had a wrong finite cohort coefficient,
5 of them with no rank-deficiency warning at all (the demeaned design was
not detected as deficient). Each case is now handled (see Behavioral
Changes). `fixest::sunab` has the same defect on
these panels, so the corrected behavior is a documented deviation from R.
- **`SunAbraham` bootstrap SEs were wrong, or the fit raised `IndexError`,
on a frame whose index is not `0..n-1`.** Both the pairs bootstrap and the
Rao-Wu bootstrap used index labels as row positions. A filtered frame
(reversed labels on the regression-test panel: SE 0.1085 instead of
0.0958), a frame with shifted labels, and a default-index frame holding a
unit with a negative or missing `first_treat` were all affected.
- **`SunAbraham` under survey weights: a cohort-by-period cell with zero
total weight no longer turns identified results into NaN.** Such a cell
got an all-zero weighted design column, and its NaN coefficient was then
pooled at weight zero (`0 * NaN`). With one cohort entirely at weight 0
the overall ATT and five event-study rows were NaN although the other
cohort identified them.

### Behavioral Changes
- **`SunAbraham`: per-cohort reference period.** A cohort that cannot be
normalized at `e = -1 - anticipation` (it is not observed there, or no
never-treated unit is observed at that calendar period) is normalized at
its latest usable pre-treatment period instead, and `fit()` warns naming
the cohort and its reference. `SunAbrahamResults.reference_event_times` (new field) lists the
distinct bases, and `reference_period` reports the shared fallback when no
cohort is observed at `e = -1 - anticipation` and all share one (for
example `-2` on a biennial grid), so the event-study anchor row sits at the
true base. Panels in which every cohort is observed at the reference
period, with never-treated units observed at those calendar periods, are
unchanged.
- **`SunAbraham`: cohorts with no pre-treatment observation are excluded.**
`fit()` warns naming the cohort and estimates on the data without it; with
no treated cohort left it raises `ValueError`. Under `survey_design=` it
raises `NotImplementedError` instead, since dropping rows there would not
be domain estimation.
- **`SunAbraham`: unidentified coefficients are NaN.** A cohort-by-period
coefficient that the observed rows do not identify is reported as NaN with
one warning naming the cells, as is every pooled event-study row that
contains one (and the overall ATT when a post-treatment row does).
`event_study_vcov` is NaN on those rows and columns only. Bootstrap draws
that cannot identify a row are dropped for that row, and replicate-weight
variances are computed over the identified entries.
`rank_deficient_action="error"` raises on such a panel and `"silent"`
suppresses the warning.
- **`compute_pretrends_power` refuses a `SunAbraham` fit whose cohorts are
normalized against different reference periods** (`reference_event_times`
with more than one entry): the hypothesized violation is defined relative
to one reference. `DiagnosticReport` reports that as an error status on its
`pretrends_power` section.
4 changes: 4 additions & 0 deletions diff_diff/guides/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,8 @@ results = sa.fit(data, outcome='outcome', unit='unit',
results.print_summary()
```

**Unbalanced panels:** the omitted reference is `e = -1 - anticipation` for every cohort observed there with a never-treated unit observed at that calendar period. A cohort for which that fails is normalized at its latest usable pre-treatment period (warned; `results.reference_event_times` lists the bases). A cohort with no pre-treatment observation has no identified effect: it is excluded with a warning (`NotImplementedError` under `survey_design=`). Any cohort-by-period coefficient the observed rows do not identify (no never-treated observation at that calendar period; a cohort whose units are observed at disjoint periods) is reported as NaN with a warning naming the cells, as is every pooled row that contains one; `rank_deficient_action="error"` raises instead.

### ImputationDiD

Borusyak-Jaravel-Spiess (2024) imputation DiD estimator. Efficient estimator producing shorter CIs than CS/SA under homogeneous effects.
Expand Down Expand Up @@ -1610,6 +1612,8 @@ Returned by `SunAbraham.fit()`.
| `cluster_name` | `str | None` | Cluster ids the analytical regression received (`"unit"` on the default, the explicit column; 4.0); None on unclustered, survey and pairs-bootstrap fits |
| `n_clusters` | `int | None` | Effective count of those clusters (4.0, appended field); None when `cluster_name` is None |
| `event_study_df` | `dict[int, float] | None` | Per-event-time df provenance (G-1 on plain clustered analytic fits under the 4.0 default; the finite residual df under `df_convention="residual"`; None under bootstrap) |
| `reference_period` | `float | None` | The reference relative period: `-1 - anticipation`, or the one fallback period every cohort shares when no cohort is observed there |
| `reference_event_times` | `tuple | None` | The distinct relative periods the cohorts are normalized against; more than one entry means some cohort could not be normalized at `-1 - anticipation` and is normalized at its latest usable pre-treatment period (pre-trends power refuses such a fit) |

**Methods:** `summary()`, `print_summary()`, `to_dataframe(level="event_study"|"cohort")` (the event-study level is the unified `EVENT_STUDY_SCHEMA` frame with the omitted reference period as a synthesized `is_reference` row - 4.0 M-093)

Expand Down
36 changes: 31 additions & 5 deletions diff_diff/pretrends.py
Original file line number Diff line number Diff line change
Expand Up @@ -1270,6 +1270,26 @@ def _extract_pre_period_params(
from diff_diff.sun_abraham import SunAbrahamResults

if isinstance(results, SunAbrahamResults):
# Common-reference guard (mirrors the container route). A
# SunAbraham fit records more than one base when some cohort
# was not observed at e = -1 - anticipation and is normalized
# at its latest observed pre-treatment period instead.
_sa_ref_e = getattr(results, "reference_event_times", None)
if _sa_ref_e is not None and len(set(_sa_ref_e)) > 1:
raise ValueError(
"PreTrendsPower requires pre-period coefficients "
"normalized against one common reference period, but "
"this SunAbraham fit records DISTINCT normalization "
f"bases at event times {sorted(set(_sa_ref_e))}. The "
"hypothesized violation delta is defined relative to "
"one reference, so power/MDV over mixed-base "
"coefficients target an ill-defined alternative. This "
"arises when a cohort is not observed at the reference "
"relative period (see the fit-time warning naming the "
"cohort) - re-estimate on a panel in which every "
"cohort is observed at one common pre-treatment "
"relative period."
)
# Same anticipation-aware pre-period cutoff as
# CallawaySantAnna above.
_ant = getattr(results, "anticipation", 0) or 0
Expand Down Expand Up @@ -1324,11 +1344,17 @@ def _extract_pre_period_params(
results, pre_periods, ses
)

# SunAbraham omits e = -1 - anticipation as its COMMON
# reference (saturated-regression omitted category):
# anchor Roth's linear violation there (see the CS
# branch for the normalization rationale).
_sa_ref = getattr(results, "reference_period", None)
# SunAbraham omits its COMMON reference (e = -1 - anticipation,
# or the one fallback period every cohort shares when no
# cohort is observed there): anchor Roth's linear violation
# at that base (see the CS branch for the normalization
# rationale). The recorded singleton wins; results without the
# provenance field keep the `reference_period` anchor.
_sa_ref = (
next(iter(set(_sa_ref_e)))
if _sa_ref_e is not None and len(set(_sa_ref_e)) == 1
else getattr(results, "reference_period", None)
)
if _sa_ref is None:
_sa_ref = -1 - int(getattr(results, "anticipation", 0) or 0)
relative_times = np.asarray(
Expand Down
9 changes: 6 additions & 3 deletions diff_diff/results_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,9 +345,12 @@ class EventStudyResults(BaseResults):
estimated horizon, where NO reference-only row exists to mark
it, so this field (not ``is_reference``) is the authoritative
common-reference signal. HonestDiD and PreTrendsPower fail
closed when it carries more than one entry. None when the
producer records no such notion (varying base, non-CS
producers, hand-built surfaces).
closed when it carries more than one entry. SunAbraham records
the distinct relative periods its cohorts are normalized against
(one entry unless some cohort is not observed at
``e = -1 - anticipation`` and falls back to its latest observed
pre-treatment period). None when the producer records no such
notion (varying base, other producers, hand-built surfaces).
"""

event_time: np.ndarray
Expand Down
Loading
Loading