diff --git a/TODO.md b/TODO.md index 27433dbe..756ea397 100644 --- a/TODO.md +++ b/TODO.md @@ -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 | diff --git a/changelog.d/20261125-sunab-reference-support.md b/changelog.d/20261125-sunab-reference-support.md new file mode 100644 index 00000000..96add083 --- /dev/null +++ b/changelog.d/20261125-sunab-reference-support.md @@ -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. diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index 9e6f0891..3205c556 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -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. @@ -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) diff --git a/diff_diff/pretrends.py b/diff_diff/pretrends.py index eed76bde..4f54692a 100644 --- a/diff_diff/pretrends.py +++ b/diff_diff/pretrends.py @@ -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 @@ -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( diff --git a/diff_diff/results_base.py b/diff_diff/results_base.py index f6937fce..594f69f2 100644 --- a/diff_diff/results_base.py +++ b/diff_diff/results_base.py @@ -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 diff --git a/diff_diff/sun_abraham.py b/diff_diff/sun_abraham.py index 10550b06..0244f999 100644 --- a/diff_diff/sun_abraham.py +++ b/diff_diff/sun_abraham.py @@ -77,6 +77,232 @@ class _SaturatedFitStats(NamedTuple): n_clusters: Optional[int] +def _observed_relative_times( + df: pd.DataFrame, + first_treat: str, + time: str, + weights: Optional[np.ndarray] = None, +) -> Dict[Any, Dict[Any, Any]]: + """Relative periods at which each treated cohort is OBSERVED. + + Returns ``{cohort: {relative period: calendar period}}``, relative periods + in increasing order. A cohort is observed at a period when it has at least + one row there with positive weight (every row counts when the fit is + unweighted). A cohort with no positive-weight row at all is absent from + the mapping: it is outside the weighted sample. + """ + keep = np.asarray(df[first_treat].values, dtype=float) > 0 + if weights is not None: + keep = keep & (np.asarray(weights) > 0) + pairs = df.loc[keep, [first_treat, time]].drop_duplicates() + out: Dict[Any, Dict[Any, Any]] = {} + for g, g_times in pairs.groupby(first_treat)[time]: + out[g] = {t - g: t for t in sorted(g_times.unique())} + return out + + +def _cohort_reference_periods( + rel_times_by_cohort: Dict[Any, Dict[Any, Any]], + anticipation: int, + comparison_periods: Optional[set] = None, +) -> Dict[Any, Any]: + """Per-cohort omitted (reference) relative period, or ``None``. + + Candidates are the cohort's observed PRE-TREATMENT relative periods + (``e < -anticipation``, i.e. ``t < g - anticipation``), tried in this + order: ``e = -1 - anticipation`` (the Sun-Abraham normalization), then the + others from the latest back. The reference is the first candidate whose + calendar period holds a never-treated observation (``comparison_periods``): + a reference at a period with no comparison rows does not tie the cohort to + the controls, and would leave its whole cell block unidentified. If no + candidate has one, the first candidate is used and the identification + guard reports what that leaves unidentified. ``None`` marks a cohort with + no pre-treatment observation: none of its effects are identified. + + On a panel in which every cohort is observed at ``-1 - anticipation`` and + never-treated units are observed at those calendar periods, every + reference is ``-1 - anticipation``. + """ + e_ref = -1 - anticipation + references: Dict[Any, Any] = {} + for g, rel_times in rel_times_by_cohort.items(): + pre = sorted((e for e in rel_times if e < -anticipation), reverse=True) + candidates = ([e_ref] if e_ref in rel_times else []) + [e for e in pre if e != e_ref] + if not candidates: + references[g] = None + continue + supported = [ + e + for e in candidates + if comparison_periods is None or rel_times[e] in comparison_periods + ] + references[g] = supported[0] if supported else candidates[0] + return references + + +def _structural_identification( + unit_vals: np.ndarray, + time_vals: np.ndarray, + cohort_vals: np.ndarray, + rel_periods: List[Any], + references: Dict[Any, Any], + default_reference: Any, + weights: Optional[np.ndarray] = None, +) -> Tuple[List[Tuple[Any, Any]], List[Tuple[Any, Any]]]: + """Which cohort-by-period coefficients the saturated regression identifies. + + Identification of a cell coefficient depends only on which (unit, period) + rows are observed, so it is decided exactly here, before the solve, with + no numerical tolerance: + + 1. every row that carries no cell dummy (a never-treated row, a treated row + at its cohort's reference) ties its unit to its period: on those rows + the outcome is ``unit effect + period effect``; + 2. the units that share a cell are tied to one another (their rows differ + only by unit effects); + 3. a cell ``(g, e)`` is identified iff its units end up in the same + connected set as its calendar period ``g + e``. Otherwise its + coefficient is a free offset between two sets. + + This is the null space of ``[cell dummies, unit dummies, period dummies]`` + read off a graph: a null vector assigns one constant to each connected set + and gives every cell the difference between its period's and its units' + constants. + + Returns + ------- + omit : list of (cohort, relative period) + A minimal set of cells whose columns must be left out for the cell + block to be full rank given the fixed effects (a spanning forest of + the graph whose edges are the unidentified cells, taken in sorted + order). Empty on an identified design. + unidentified : list of (cohort, relative period) + Every cell whose coefficient is not identified (``omit`` included). + The caller reports them as NaN. + """ + from scipy.sparse import coo_matrix + from scipy.sparse.csgraph import connected_components + + unit_vals = np.asarray(unit_vals) + time_vals = np.asarray(time_vals) + cohort_vals = np.asarray(cohort_vals, dtype=float) + observed = np.ones(len(unit_vals), dtype=bool) + if weights is not None: + observed &= np.asarray(weights) > 0 + if not observed.any(): + return [], [] + unit_vals = unit_vals[observed] + time_vals = time_vals[observed] + cohort_vals = cohort_vals[observed] + + treated = np.isfinite(cohort_vals) & (cohort_vals > 0) + rel_vals = np.where(treated, time_vals.astype(float) - cohort_vals, np.nan) + # A row carries a cell dummy iff its cohort is treated, its relative period + # is one the builder loops over, and that period is not the cohort's own + # reference -- the same rule the dummy builder applies. + rel_set = np.array(sorted(float(e) for e in rel_periods), dtype=float) + dummied = treated & np.isin(rel_vals, rel_set) + if dummied.any(): + ref_vals = np.full(len(cohort_vals), float(default_reference)) + for g, ref in references.items(): + if ref is not None: + ref_vals[cohort_vals == float(g)] = float(ref) + dummied &= rel_vals != ref_vals + if not dummied.any(): + return [], [] + + _, unit_idx = np.unique(unit_vals, return_inverse=True) + uniq_times, time_idx = np.unique(time_vals.astype(float), return_inverse=True) + n_units, n_times = int(unit_idx.max()) + 1, len(uniq_times) + + cell_pairs = np.column_stack([cohort_vals[dummied], rel_vals[dummied]]) + uniq_cells, cell_idx = np.unique(cell_pairs, axis=0, return_inverse=True) + cell_idx = np.asarray(cell_idx).ravel() + n_cells = len(uniq_cells) + # Period node of each cell: every row of a cell shares one calendar period + # (g + e), read off the rows rather than recomputed in floating point. + cell_period = np.zeros(n_cells, dtype=int) + cell_period[cell_idx] = time_idx[dummied] + + # Nodes: units, then periods, then one node per cell. Undummied rows join + # unit and period; dummied rows join the unit to its cell's node. + rows = np.concatenate([unit_idx[~dummied], unit_idx[dummied]]) + cols = np.concatenate( + [n_units + time_idx[~dummied], n_units + n_times + cell_idx], + ) + n_nodes = n_units + n_times + n_cells + graph = coo_matrix((np.ones(len(rows), dtype=np.int8), (rows, cols)), shape=(n_nodes, n_nodes)) + _, labels = connected_components(graph, directed=False) + cell_side = labels[n_units + n_times + np.arange(n_cells)] + period_side = labels[n_units + cell_period] + bad = np.flatnonzero(cell_side != period_side) + if len(bad) == 0: + return [], [] + + # Spanning forest over the connected sets: one omitted cell per independent + # free offset. ``np.unique(axis=0)`` already sorted the cells by (g, e). + parent: Dict[int, int] = {} + + def _find(x: int) -> int: + parent.setdefault(x, x) + while parent[x] != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + + omit: List[Tuple[Any, Any]] = [] + unidentified: List[Tuple[Any, Any]] = [] + for k in bad: + key = (float(uniq_cells[k, 0]), float(uniq_cells[k, 1])) + unidentified.append(key) + ra, rb = _find(int(cell_side[k])), _find(int(period_side[k])) + if ra != rb: + parent[rb] = ra + omit.append(key) + return omit, unidentified + + +def _replicate_variance_over_finite( + refit_fn: Any, full_estimate: np.ndarray, resolved_survey: Any +) -> Tuple[np.ndarray, int]: + """Replicate-refit variance over the entries the full sample identifies. + + ``compute_replicate_refit_variance`` rejects a replicate when ANY entry of + its estimate vector is non-finite. An entry that is non-finite in the + full-sample estimate (an unidentified cell, or a pooled row that contains + one) is non-finite in every replicate too, so leaving it in the vector + would reject them all and erase the variance of every identified entry. + The vectors are therefore restricted to the finite full-sample entries; + the excluded ones get NaN variance. A replicate that loses an entry the + full sample identifies is still rejected (and counted) by the callee. + """ + from diff_diff.survey import compute_replicate_refit_variance + + finite = np.isfinite(full_estimate) + k = len(full_estimate) + if finite.all(): + return compute_replicate_refit_variance(refit_fn, full_estimate, resolved_survey) + vcov = np.full((k, k), np.nan) + if not finite.any(): + # Nothing to price; no replicate was dropped. + return vcov, int(resolved_survey.n_replicates) + sub_vcov, n_valid = compute_replicate_refit_variance( + lambda w_r: np.asarray(refit_fn(w_r))[finite], full_estimate[finite], resolved_survey + ) + vcov[np.ix_(finite, finite)] = sub_vcov + return vcov, n_valid + + +def _format_cells(cells: List[Tuple[Any, Any]], limit: int = 12) -> str: + """``(cohort, relative period)`` pairs as text, truncated past ``limit``.""" + + def _num(x: Any) -> str: + return str(int(x)) if float(x).is_integer() else str(x) + + shown = ", ".join(f"({_num(g)}, {_num(e)})" for g, e in cells[:limit]) + return shown if len(cells) <= limit else f"{shown}, ... and {len(cells) - limit} more" + + @dataclass class SunAbrahamResults(BaseResults): """ @@ -184,16 +410,18 @@ class SunAbrahamResults(BaseResults): # survey and pairs-bootstrap fits. ``n_clusters`` (appended below) is its count. conley_lag_cutoff: Optional[int] = None cluster_name: Optional[str] = None - # The normalization reference relative time (e = -1 - anticipation, the - # omitted category of the saturated regression) and whether it was - # GENUINELY OBSERVED in the panel. The reference is excluded from - # event_study_effects either because it is the omitted baseline (observed) - # OR because no cohort has an observation there (unobserved, on a gapped - # grid) - the two are indistinguishable from the estimated keys alone, so - # the unified event-study surface synthesizes the anchor row only when - # reference_observed is True. Defaults are conservative (no synthesis) for - # externally / legacy-constructed results. - reference_period: Optional[int] = None + # The normalization reference relative time and whether some cohort is + # ACTUALLY normalized there. It is e = -1 - anticipation (the omitted + # category of the saturated regression) unless no cohort is observed at + # that period and every cohort shares one fallback reference, in which + # case it is that shared period (e.g. -2 on a biennial grid); the full set + # of bases is `reference_event_times`. The reference is absent from + # event_study_effects either because it is the omitted baseline OR because + # no cohort is normalized there - indistinguishable from the estimated + # keys alone, so the unified event-study surface synthesizes the anchor + # row only when reference_observed is True. Defaults are conservative (no + # synthesis) for externally / legacy-constructed results. + reference_period: Optional[float] = None reference_observed: bool = False # event_study_df (spec section 5, row M-092): per-event-time df @@ -235,6 +463,17 @@ class SunAbrahamResults(BaseResults): unclustered (``cluster=False`` / one-way) fits, under a survey design (the survey block owns PSU reporting) and on pairs-bootstrap fits.""" + reference_event_times: Optional[Tuple[Any, ...]] = None + """The distinct relative periods the estimated cohorts are normalized + against, sorted. One entry (``(-1 - anticipation,)`` on ordinary panels) + means a common reference. More than one means some cohort could not be + normalized at ``e = -1 - anticipation`` (not observed there, or no + never-treated observation at that calendar period) and is normalized at + its latest usable pre-treatment period instead, so the pooled event-study + rows mix bases - + analyses that need one common reference (pre-trends power) refuse such a + fit. None on results built before this field existed.""" + def __setstate__(self, state: Dict[str, Any]) -> None: """Migrate 3.x pickles written under the ``overall_*`` storage names. @@ -578,6 +817,11 @@ class SunAbraham(BaseEstimator): - "warn": Issue warning and drop linearly dependent columns (default) - "error": Raise ValueError - "silent": Drop columns silently without warning + + The same setting governs cohort-by-period coefficients that the + observed rows do not identify (see Notes): they are reported as NaN + with one warning naming them ("warn"), silently ("silent"), or + ``fit`` raises ("error"). vcov_type : {"classical", "hc1", "hc2", "hc2_bm", "conley"}, default "hc1" Variance-covariance family for analytical inference. Defaults to ``"hc1"`` (preserves prior behavior bit-equally; SA historically @@ -705,6 +949,21 @@ class SunAbraham(BaseEstimator): where w_{g,e} is the share of cohort g in the treated population at relative time e (interaction weights). + Reference period and unbalanced panels. The omitted category is + ``e = -1 - anticipation`` for every cohort that is observed there with a + never-treated unit observed at that calendar period. A cohort for which + that fails (a gap, a grid on which that period does not occur, or no + comparison observation at that period) is normalized at its latest usable + pre-treatment period instead; ``fit`` warns and + ``results.reference_event_times`` lists the distinct bases. A cohort with no pre-treatment observation has no identified + effect: its observations are excluded with a warning + (``NotImplementedError`` under ``survey_design=``, where dropping rows + would not be domain estimation). Beyond that, a coefficient + ``δ_{g,e}`` is reported only if the observed rows identify it; one that + they do not (no never-treated observation at that calendar period, or a + cohort whose units are observed at disjoint sets of periods) is NaN, as + is every pooled row that contains it. + Compared to Callaway-Sant'Anna: - SA uses saturated regression; CS uses 2x2 DiD comparisons - SA can be more efficient when model is correctly specified @@ -782,6 +1041,9 @@ def __init__( self.is_fitted_ = False self.results_: Optional[SunAbrahamResults] = None self._reference_period = -1 # Will be set during fit + # Per-cohort omitted relative period (set during fit); a cohort absent + # from the mapping uses `_reference_period`. + self._cohort_references: Dict[Any, Any] = {} def fit( self, @@ -987,6 +1249,85 @@ def fit( # Normalize np.inf → 0 so all downstream `> 0` checks exclude never-treated df.loc[df[first_treat] == np.inf, first_treat] = 0 + # Checked here, ahead of the reference selection below, so that a panel + # with no comparison group reports THAT rather than a cohort diagnosis. + if not bool(df["_never_treated"].any()): + raise ValueError("No never-treated units found. Check 'first_treat' column.") + + # Per-cohort reference period. A cohort that can be normalized at + # e = -1 - anticipation (observed there, with a never-treated unit + # observed at that calendar period) keeps it; one that cannot falls + # back to its latest usable pre-treatment period; one with no + # pre-treatment observation has no identified effect and is excluded + # (REGISTRY SunAbraham, per-cohort reference / unidentified cohorts + # Notes). "Observed" means a row with positive weight. + _e_ref = -1 - self.anticipation + rel_times_by_cohort = _observed_relative_times(df, first_treat, time, survey_weights) + # Calendar periods with a never-treated observation: a cohort's + # reference is preferred at a period that has one. + _nt_rows = df["_never_treated"].values.astype(bool) + if survey_weights is not None: + _nt_rows = _nt_rows & (np.asarray(survey_weights) > 0) + _comparison_periods = set(df.loc[_nt_rows, time].unique()) + cohort_references = _cohort_reference_periods( + rel_times_by_cohort, self.anticipation, _comparison_periods + ) + _no_pre = sorted(g for g, ref in cohort_references.items() if ref is None) + if _no_pre: + _labels = ", ".join(str(g) for g in _no_pre) + if survey_design is not None: + raise NotImplementedError( + f"Cohort(s) {_labels} have no observation (with positive " + "weight) before treatment begins, accounting for " + "anticipation, so none of their effects are identified. " + "Without a survey design SunAbraham excludes such cohorts; " + "under survey_design= that would be naive subsetting rather " + "than domain estimation (the design's strata, PSU counts and " + "degrees of freedom would change), which is not implemented. " + "Remove the cohort(s) in a way that is valid for your " + "design, or fit without survey_design=." + ) + df = df[~df[first_treat].isin(_no_pre)].copy() + for g in _no_pre: + del cohort_references[g] + del rel_times_by_cohort[g] + if not cohort_references: + raise ValueError( + f"Cohort(s) {_labels} have no observation before treatment " + "begins (accounting for anticipation), and they are the only " + "treated cohorts, so no effect is identified. Provide a panel " + "with pre-treatment observations, or reduce `anticipation`." + ) + warnings.warn( + f"Cohort(s) {_labels} have no observation before treatment begins " + "(accounting for anticipation), so none of their effects are " + "identified: there is no untreated period to measure them " + "against. Their observations are EXCLUDED from the estimation " + "sample, and every reported quantity is that of a fit on the " + "data without them.", + UserWarning, + stacklevel=2, + ) + _fallback = {g: ref for g, ref in cohort_references.items() if ref != _e_ref} + if _fallback: + _desc = "; ".join(f"cohort {g}: {ref}" for g, ref in sorted(_fallback.items())) + warnings.warn( + f"Not every cohort can be normalized at the reference relative " + f"period {_e_ref}: the cohort is not observed there, or no " + "never-treated unit is observed at that calendar period. The " + "cohorts below are normalized at their latest usable " + f"pre-treatment period instead ({_desc}), so their effects are " + "measured relative to that period" + + ( + ", and the pooled event-study rows mix normalization bases." + if len(set(cohort_references.values())) > 1 + else "." + ), + UserWarning, + stacklevel=2, + ) + self._cohort_references = cohort_references + # Identify groups and time periods time_periods = sorted(df[time].unique()) treatment_groups = sorted([g for g in df[first_treat].unique() if g > 0]) @@ -1008,36 +1349,39 @@ def fit( # Compute relative time for each observation (vectorized) df["_rel_time"] = np.where(df[first_treat] > 0, df[time] - df[first_treat], np.nan) - # Identify the range of relative time periods to estimate - rel_times_by_cohort = {} - for g in treatment_groups: - g_times = df[df[first_treat] == g][time].unique() - rel_times_by_cohort[g] = sorted([t - g for t in g_times]) - - # Find all relative time values - all_rel_times: set = set() - for g, rel_times in rel_times_by_cohort.items(): - all_rel_times.update(rel_times) - - all_rel_times_sorted = sorted(all_rel_times) - - # Use full range of relative times (no artificial truncation, matches R's fixest::sunab()) - min_rel = min(all_rel_times_sorted) - max_rel = max(all_rel_times_sorted) - - # Reference period: last pre-treatment period (typically -1) - self._reference_period = -1 - self.anticipation - # Whether that anchor was GENUINELY OBSERVED (vs a gap on an - # unbalanced grid). The unified event-study surface synthesizes the - # reference row only when it was observed. - self._reference_observed = self._reference_period in all_rel_times + # Reference period: last pre-treatment period (typically -1). This is + # the builder's default and is never an estimated relative period (a + # cohort observed there has it as its own reference). + self._reference_period = _e_ref + + # Relative periods to estimate: every period at which some cohort is + # observed other than at its own reference. Full range, no artificial + # truncation (matches R's fixest::sunab()). A period that holds only + # reference cells is not in the list. + rel_periods_to_estimate = sorted( + { + e + for g, rel_times in rel_times_by_cohort.items() + for e in rel_times + if e != _e_ref and e != cohort_references[g] + } + ) - # Get relative periods to estimate (excluding reference) - rel_periods_to_estimate = [ - e - for e in all_rel_times_sorted - if min_rel <= e <= max_rel and e != self._reference_period - ] + # What the results report as THE reference. With one normalization + # base it is that base (e_ref, or the shared fallback, so the + # event-study surface anchors at the true base); with several it stays + # e_ref. `reference_observed` says whether some cohort is actually + # normalized there - the surface synthesizes the anchor row only then. + _distinct_refs = sorted(set(cohort_references.values())) + _results_reference: Any = _e_ref + if len(_distinct_refs) == 1: + _results_reference = _distinct_refs[0] + if hasattr(_results_reference, "item"): + _results_reference = _results_reference.item() + _reference_event_times = tuple( + r.item() if hasattr(r, "item") else r for r in _distinct_refs + ) + self._reference_observed = _results_reference in _reference_event_times # Determine cluster variable # One-way HC2 and classical are single-way only — the linalg @@ -1111,6 +1455,7 @@ def fit( coef_index_map, bm_artifacts, _sa_fit_stats, + _unidentified_cells, ) = self._fit_saturated_regression( df_reg, outcome, @@ -1128,15 +1473,27 @@ def fit( # override vcov_cohort below with the correct estimator-level refit. resolved_survey=None if _uses_replicate_sa else resolved_survey, vcov_type=self.vcov_type, + enforce_rank_action=True, ) + if _unidentified_cells and self.rank_deficient_action != "silent": + warnings.warn( + "The cohort-by-period coefficient(s) " + f"{_format_cells(_unidentified_cells)} (cohort, relative period) " + "are not identified by the observed rows and are reported as " + "NaN, as is every pooled event-study row that contains one (and " + "the overall ATT when a post-treatment row does). The usual " + "causes: no never-treated observation at that calendar period, " + "or the cohort's units are observed at disjoint sets of periods.", + UserWarning, + stacklevel=2, + ) + # Replicate variance override: fully refit the IW estimator per # replicate, including recomputing cohort-share aggregation weights # from w_r, so replicate SEs reflect the complete estimator. _n_valid_rep_sa = None if _uses_replicate_sa: - from diff_diff.survey import compute_replicate_refit_variance - # The refit returns [overall_att, es_e0, es_e1, ...] after # full re-aggregation with replicate-weighted cohort shares. _sa_rel_periods = list(rel_periods_to_estimate) @@ -1146,7 +1503,7 @@ def _refit_sa(w_r): nz = w_r > 0 df_reg_nz = df_reg[nz] if not np.all(nz) else df_reg w_nz = w_r[nz] if not np.all(nz) else w_r - ce_r, _, vcov_r, cim_r, _, _ = self._fit_saturated_regression( + ce_r, _, vcov_r, cim_r, _, _, _ = self._fit_saturated_regression( df_reg_nz, outcome, unit, @@ -1292,7 +1649,23 @@ def _refit_sa(w_r): if (g, e) in coef_index_map: j = coef_index_map[(g, e)] W_mat[i, j] = w - es_vcov = W_mat @ vcov_cohort @ W_mat.T + # Aggregate over the cells with a finite effect only: a dropped or + # unidentified cell has NaN covariance, and `0 * NaN` would turn + # the WHOLE matrix NaN. The rows of the pooled periods that contain + # such a cell are NaN; the other rows keep their covariance block. + # Nothing is zeroed, so a vcov that is NaN for another reason + # (undefined variance) still propagates. + _finite_cols = np.zeros(n_interactions, dtype=bool) + for _key, _j in coef_index_map.items(): + _finite_cols[_j] = bool(np.isfinite(cohort_effects.get(_key, np.nan))) + _W_fin = W_mat[:, _finite_cols] + es_vcov = _W_fin @ vcov_cohort[np.ix_(_finite_cols, _finite_cols)] @ _W_fin.T + for i, e in enumerate(es_vcov_index): + if e not in event_study_effects or not np.isfinite( + event_study_effects[e]["effect"] + ): + es_vcov[i, :] = np.nan + es_vcov[:, i] = np.nan # Compute overall ATT (average of post-treatment effects). # Capture overall_weights_by_coef for the hc2_bm contrast-DOF path. @@ -1428,7 +1801,7 @@ def _refit_sa(w_r): event_study_effects[e]["effect"] if e in event_study_effects else np.nan ) - _vcov_sa, _n_valid_rep_sa = compute_replicate_refit_variance( + _vcov_sa, _n_valid_rep_sa = _replicate_variance_over_finite( _refit_sa, np.array(_full_est_sa), resolved_survey ) @@ -1483,7 +1856,7 @@ def _refit_sa_cohort(w_r): nz = w_r > 0 df_reg_nz = df_reg[nz] if not np.all(nz) else df_reg w_nz = w_r[nz] if not np.all(nz) else w_r - ce_r, _, _, _, _, _ = self._fit_saturated_regression( + ce_r, _, _, _, _, _, _ = self._fit_saturated_regression( df_reg_nz, outcome, unit, @@ -1502,7 +1875,7 @@ def _refit_sa_cohort(w_r): # n_valid is not consumed here: cohort effects store effect / se / # weight only (no t-stat, p-value or CI), so no df prices them. - _vcov_cohort_rep, _ = compute_replicate_refit_variance( + _vcov_cohort_rep, _ = _replicate_variance_over_finite( _refit_sa_cohort, _full_cohort_vec, resolved_survey ) for key in _keys_ordered: @@ -1627,8 +2000,9 @@ def _refit_sa_cohort(w_r): event_study_df=es_df_final, conley_lag_cutoff=(self.conley_lag_cutoff if self.vcov_type == "conley" else None), cluster_name=_sa_cluster_name, - reference_period=self._reference_period, + reference_period=_results_reference, reference_observed=self._reference_observed, + reference_event_times=_reference_event_times or None, df_convention=self.df_convention, inference_df=_overall_df_final, n_clusters=_sa_n_clusters, @@ -1652,6 +2026,7 @@ def _fit_saturated_regression( survey_weight_type: str = "pweight", resolved_survey: Optional["ResolvedSurveyDesign"] = None, vcov_type: str = "hc1", + enforce_rank_action: bool = False, ) -> Tuple[ Dict[Tuple[Any, int], float], Dict[Tuple[Any, int], float], @@ -1659,6 +2034,7 @@ def _fit_saturated_regression( Dict[Tuple[Any, int], int], Optional[Tuple[np.ndarray, Optional[np.ndarray], np.ndarray]], _SaturatedFitStats, + List[Tuple[Any, Any]], ]: """ Fit saturated TWFE regression with cohort × relative-time interactions. @@ -1691,6 +2067,18 @@ def _fit_saturated_regression( Mapping (cohort, rel_period) -> index in the cohort_effects block (0-based, NOT the index in the full coefficient vector of the underlying regression). + unidentified : list + The (cohort, rel_period) cells whose coefficient is not identified + in THIS frame (``_structural_identification``). They are present + in ``cohort_effects`` / ``cohort_ses`` as NaN; the ones that had a + design column also have NaN rows and columns in ``vcov``. + + ``enforce_rank_action`` is True for the full-sample fit only: there + ``rank_deficient_action="error"`` raises on an unidentified cell. A + refit (bootstrap draw, replicate) never raises for that reason - a + draw that cannot identify a cell must come back NaN and be dropped by + the caller's non-finite handling, not be replaced by the caller's + exception fallback. """ df = df.copy() @@ -1707,14 +2095,60 @@ def _fit_saturated_regression( coef_index_map: Dict[Tuple[Any, int], int] = {} idx = 0 + # Which cells this frame identifies, decided from the observation + # pattern before the solve (REGISTRY SunAbraham identification-guard + # Note). `omit` cells get no column, which leaves the cell block full + # rank given the fixed effects; every `unidentified` cell is reported + # as NaN below. + cohort_references = getattr(self, "_cohort_references", {}) + omit_cells, unidentified = _structural_identification( + df[unit].values, + df[time].values, + df[first_treat].values, + rel_periods, + cohort_references, + self._reference_period, + weights=survey_weights, + ) + if unidentified: + # The helper works in floats; hand the cells back under the same + # key objects the builder uses, so the results never mix key types. + _canonical = { + (float(g), float(e)): (g, e) for g in treatment_groups for e in rel_periods + } + omit_cells = [_canonical.get(k, k) for k in omit_cells] + unidentified = [_canonical.get(k, k) for k in unidentified] + if unidentified and enforce_rank_action and self.rank_deficient_action == "error": + raise ValueError( + "SunAbraham design is rank-deficient: the cohort-by-period " + f"coefficient(s) {_format_cells(unidentified)} are not identified " + "by the observed rows (no never-treated observation at that " + "calendar period, or the cohort's units are observed at " + "disjoint sets of periods)." + ) + omit_set = set(omit_cells) + obs_weights = None if survey_weights is None else np.asarray(survey_weights, dtype=float) + for g in treatment_groups: + ref_g = cohort_references.get(g, self._reference_period) for e in rel_periods: + # The cohort's own reference is its omitted category. + if e == ref_g or (g, e) in omit_set: + continue col_name = f"_D_{g}_{e}" # Indicator: unit is in cohort g AND at relative time e indicator = ((df[first_treat] == g) & (df["_rel_time"] == e)).astype(float) - # Only include if there are observations - if indicator.sum() > 0: + # Only include a cell that is OBSERVED in this frame: at least + # one row, with positive weight when the fit is weighted. A + # zero-weight cell would be an all-zero weighted column whose + # NaN coefficient would then be pooled at weight zero. + mass = ( + indicator.sum() + if obs_weights is None + else float(indicator.values @ (obs_weights > 0)) + ) + if mass > 0: interaction_data[col_name] = indicator.values coef_index_map[(g, e)] = idx idx += 1 @@ -1726,6 +2160,19 @@ def _fit_saturated_regression( df = pd.concat([df, interaction_df], axis=1) if len(interaction_cols) == 0: + if unidentified: + # Every candidate cell is unidentified: there is nothing to + # solve, and each cell is reported as NaN (the caller pools + # them into NaN rows and a NaN overall ATT). + return ( + {key: np.nan for key in unidentified}, + {key: np.nan for key in unidentified}, + np.empty((0, 0)), + {}, + None, + _SaturatedFitStats(df_residual=None, n_clusters=None), + unidentified, + ) raise ValueError( "No valid cohort × relative-time interactions found. " "Check your data structure." ) @@ -1924,6 +2371,20 @@ def _fit_saturated_regression( coef_offset : coef_offset + n_interactions, ] + # Unidentified cells are reported as NaN. One that kept a design column + # has a finite estimate that depends on which columns were omitted, so + # it is overwritten (with its covariance row and column); one that was + # omitted has no column and is added here so that pooling sees it. + if unidentified: + vcov_cohort = vcov_cohort.copy() + for key in unidentified: + cohort_effects[key] = np.nan + cohort_ses[key] = np.nan + j = coef_index_map.get(key) + if j is not None: + vcov_cohort[j, :] = np.nan + vcov_cohort[:, j] = np.nan + # Stash BM contrast-DOF artifacts when hc2_bm — needed by the # aggregated inference layer to compute per-event-time and # overall-ATT Satterthwaite DOF on user-facing outputs. Under @@ -1945,7 +2406,15 @@ def _fit_saturated_regression( n_clusters=reg.n_clusters_, ) - return cohort_effects, cohort_ses, vcov_cohort, coef_index_map, bm_artifacts, fit_stats + return ( + cohort_effects, + cohort_ses, + vcov_cohort, + coef_index_map, + bm_artifacts, + fit_stats, + unidentified, + ) def _compute_iw_effects( self, @@ -2023,6 +2492,21 @@ def _compute_iw_effects( cohort_weights[e] = weights + # A row that contains an unidentified (NaN) cohort coefficient is + # not identified either: report it as NaN rather than pooling the + # remaining cohorts under a silently different estimand. + if any(not np.isfinite(cohort_effects[(g, e)]) for g in cohorts_at_e): + nan_t, nan_p, nan_ci = safe_inference(np.nan, np.nan, alpha=self.alpha) + event_study_effects[e] = { + "effect": np.nan, + "se": np.nan, + "t_stat": nan_t, + "p_value": nan_p, + "conf_int": nan_ci, + "n_groups": len(cohorts_at_e), + } + continue + # Compute weighted average effect agg_effect = 0.0 for g in cohorts_at_e: @@ -2134,6 +2618,12 @@ def _compute_overall_att( post_weights_arr = post_weights_arr / post_weights_arr.sum() overall_att = float(np.sum(post_weights_arr * np.array(post_estimates))) + if not np.isfinite(overall_att): + # A post-treatment row is unidentified (NaN): the overall ATT and + # its SE are undefined together. + if return_overall_weights: + return np.nan, np.nan, None + return np.nan, np.nan # Compute SE using delta method # Need to trace back through the full weighting scheme @@ -2241,7 +2731,11 @@ def _run_bootstrap( n_units = len(all_units) # Pre-compute unit -> row indices mapping (avoids repeated boolean scans) - unit_row_indices = {u: df.index[df[unit] == u].values for u in all_units} + # Row POSITIONS, not index labels: `df` may carry any index (a filtered + # user frame, or one with an excluded cohort), and `.iloc` below is + # positional. + _unit_arr = df[unit].values + unit_row_indices = {u: np.flatnonzero(_unit_arr == u) for u in all_units} unit_row_counts = {u: len(idx) for u, idx in unit_row_indices.items()} # Store bootstrap samples @@ -2282,6 +2776,7 @@ def _run_bootstrap( coef_map_b, _, _, + _, ) = self._fit_saturated_regression( df_b, outcome, @@ -2471,7 +2966,9 @@ def _run_rao_wu_bootstrap( ) # Build unit -> row indices mapping for expanding unit-level weights - unit_to_rows = {u: df.index[df[unit] == u].values for u in all_units} + # Row POSITIONS (see the pairs path): `boot_weights[idx]` is positional. + _unit_arr = df[unit].values + unit_to_rows = {u: np.flatnonzero(_unit_arr == u) for u in all_units} unit_order = {u: i for i, u in enumerate(all_units)} # Store bootstrap samples @@ -2516,6 +3013,7 @@ def _run_rao_wu_bootstrap( coef_map_b, _, _, + _, ) = self._fit_saturated_regression( df_b, outcome, diff --git a/docs/api/staggered.rst b/docs/api/staggered.rst index b56abf51..43780caa 100644 --- a/docs/api/staggered.rst +++ b/docs/api/staggered.rst @@ -104,6 +104,19 @@ aggregate cohort-specific effects into event study estimates. **Reference:** Sun, L., & Abraham, S. (2021). Estimating dynamic treatment effects in event studies with heterogeneous treatment effects. *Journal of Econometrics*, 225(2), 175-199. +**Unbalanced panels:** every cohort observed at ``e = -1 - anticipation``, with +a never-treated unit observed at that calendar period, is normalized there. A +cohort for which that fails is normalized at its latest usable pre-treatment +period instead, with a warning, and +``results.reference_event_times`` lists the distinct bases (pre-trends power +refuses a fit with more than one). A cohort with no pre-treatment observation has +no identified effect and is excluded with a warning (``NotImplementedError`` +under ``survey_design=``). A cohort-by-period coefficient that the observed rows +do not identify - no never-treated observation at that calendar period, or a +cohort whose units are observed at disjoint sets of periods - is reported as NaN +with a warning naming the cells, as is every pooled event-study row that +contains one; ``rank_deficient_action="error"`` raises instead. + .. autoclass:: diff_diff.SunAbraham :no-index: :members: diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index aeb8cc41..019d2b01 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -1980,7 +1980,7 @@ where `q_{g,e} = pi_g / sum_{g' in G_{trt,e}} pi_{g'}`. *Assumption checks / warnings:* - Requires never-treated units as control group - Warns if treatment effects may be heterogeneous across cohorts (which the method handles) -- Reference period: e=-1-anticipation (defaults to e=-1 when anticipation=0) +- Reference period: e=-1-anticipation (defaults to e=-1 when anticipation=0) for every cohort observed there; a cohort that is not falls back to its latest observed pre-treatment period (see the per-cohort reference Note below) *Estimator equation (as implemented):* @@ -2088,7 +2088,11 @@ where weights ŵ_{g,e} = n_{g,e} / Σ_g n_{g,e} (sample share of cohort g at eve deliberately narrower than the `event_study_vcov` clear, which also fires under replicate refits whose rows DID use a genuine df. The scalar `inference_df` (added 3.9) mirrors the same rule for the overall ATT. -- **Note (to_dataframe schema, 4.0, [M-093] item 8b):** `to_dataframe(level='event_study')` (the default level) returns `build_event_study_surface(self).to_dataframe()` - the unified `EVENT_STUDY_SCHEMA` frame: the omitted reference period (`reference_period`, `e = -1 - anticipation`) appears as a synthesized `is_reference` row with `att = 0` and NaN inference/`n`; estimated rows carry `n` = the contributing-cohort count (`n_kind='groups'`). The 3.x bespoke `relative_period`/`effect` frame is gone. `'cohort'` is unchanged. +- **Note (to_dataframe schema, 4.0, [M-093] item 8b):** `to_dataframe(level='event_study')` (the default level) returns `build_event_study_surface(self).to_dataframe()` - the unified `EVENT_STUDY_SCHEMA` frame: the omitted reference period (`reference_period`: `e = -1 - anticipation`, or the one fallback period every cohort shares when no cohort is observed there - see the per-cohort reference Note) appears as a synthesized `is_reference` row with `att = 0` and NaN inference/`n`; estimated rows carry `n` = the contributing-cohort count (`n_kind='groups'`). The 3.x bespoke `relative_period`/`effect` frame is gone. `'cohort'` is unchanged. +- **Note (per-cohort reference period):** the saturated regression omits `e = -1 - anticipation` for every cohort that can be normalized there: the cohort is OBSERVED at that relative period and a never-treated unit is observed at that calendar period. A cohort for which that fails (a gap at `g - 1 - anticipation`, a grid on which that period never occurs, or no never-treated observation at that calendar period) is normalized instead at its latest observed pre-treatment relative period (`e < -anticipation`, i.e. `t < g - anticipation`) whose calendar period has a never-treated observation - or, when none has one, at its first candidate (`e = -1 - anticipation` if observed, else the latest observed pre-treatment period) - and `fit()` warns naming the cohort and its reference. A reference at a period with no comparison rows would not tie the cohort to the controls and would leave its whole cell block unidentified. `e = -1 - anticipation` itself is never an estimated relative period: a cohort normalized elsewhere that has rows there contributes them as further untreated rows. "Observed" means a row with positive weight (every row on an unweighted fit). Before this rule the single omitted category left such a cohort's dummies summing to its cohort indicator, which the unit fixed effects absorb, so QR dropped an arbitrary column of that cohort - possibly a post-treatment one - and the cohort's effects were measured against it. `SunAbrahamResults.reference_event_times` records the distinct bases: one entry on an ordinary panel; more than one when cohorts end up with different references, in which case the pooled event-study rows mix normalization bases and `compute_pretrends_power` refuses the fit (the hypothesized violation is defined relative to ONE reference), which `DiagnosticReport` reports as an error status on its `pretrends_power` section. `reference_period` is `e = -1 - anticipation`, except when every cohort shares one fallback reference (a biennial grid: no cohort is observed at `e = -1`, all are normalized at `-2`), where it is that shared period so the event-study anchor row sits at the true base. The rule follows WooldridgeDiD's latest-SUPPORTED-pre-period reference, with support defined here as a never-treated observation at that calendar period; anything the chosen references leave unidentified is handled by the identification guard below. +- **Note (cohorts with no pre-treatment observation - library identification limit):** a cohort with no observation before `g - anticipation` (treated at the first panel period, first observed after treatment, or observed only inside the anticipation window) has no untreated period to be measured against, so none of its effects are identified. `fit()` warns naming the cohort and EXCLUDES its observations; every reported quantity (point estimates, SEs, `groups`, unit and observation counts, bootstrap draws) is that of a fit on the data without it. Without covariates the exclusion does not move the other cohorts' estimates; with covariates it can, because the excluded rows no longer inform the covariate coefficients. If no treated cohort is left, `fit()` raises `ValueError`. Under `survey_design=` the exclusion would be naive subsetting rather than domain estimation, so `fit()` raises `NotImplementedError` instead (tracked in `TODO.md`). +- **Note (identification guard):** a cohort-by-period coefficient is reported, pooled and resampled only if the observed rows identify it. Identification is decided exactly from the observation pattern, before the solve, with no numerical tolerance: (1) every row that carries no cell dummy - a never-treated row, or a treated row at its cohort's reference - ties its unit to its calendar period; (2) the units that share a cell are tied to one another; (3) a cell `(g, e)` is identified iff its units end up in the same connected set as its calendar period `g + e`. This is the null space of `[cell dummies, unit dummies, period dummies]` read off a graph: a null vector assigns a constant to each connected set and gives each cell the difference between its period's and its units' constants. The two usual causes of an unidentified cell are a calendar period with no never-treated observation and a cohort whose units are observed at disjoint sets of periods. A minimal set of unidentified cells (a spanning forest of the graph they form) gets no design column, so the cell block is full rank given the fixed effects whatever the solver and the demeaning tolerance; every unidentified cell is then reported as NaN (effect, SE and covariance), with ONE warning naming the cells. `rank_deficient_action="error"` raises instead; `"silent"` suppresses the warning. That setting governs the full-sample fit only: a bootstrap draw or a replicate never raises for this reason (the pairs bootstrap's exception fallback would substitute the original estimate and shrink the SE), it returns NaN for what it cannot identify. When every candidate cell is unidentified there is no design left to solve and each cell is still reported as NaN. Consequences: a pooled event-study row that contains an unidentified cell is NaN, and so is the overall ATT when a post-treatment row is; `event_study_vcov` is NaN on those rows and columns and keeps its covariance block for the others; a bootstrap draw is analysed the same way and is dropped (and counted) for the rows it cannot identify; under replicate weights the variance is computed over the entries the full sample identifies. A cell with zero total weight is not observed: it gets no column and no pooling weight, instead of a NaN coefficient pooled at weight zero. Collinearity that involves covariates is outside this analysis and stays with the solver's rank detection. This differs from WooldridgeDiD, which refuses a cohort whose units split into disconnected support groups. +- **Deviation from R:** `fixest::sunab` (0.14.2) handles neither case. On a panel in which one cohort has a gap at `e = -1` it removes one of that cohort's interaction columns by collinearity (`time::3:cohort::5` on the regression-test panel: a post-treatment cell) and reports an overall ATT of 1.847 where the fallback-reference fit gives 3.021 (true value 3.05). On a panel containing a cohort with no pre-treatment observation it builds no interaction for that cohort and keeps all but one of its observations in the estimation sample, so the cohort acts as part of the comparison group (ATT 2.140). With the cohort's rows removed by hand `sunab` returns 2.74379 (SE 0.15997), which the exclusion reproduces to 1e-14; the fallback-reference fit matches `feols` with explicit cohort-by-period dummies (the same cells omitted) to 1e-12 in the coefficients and their clustered SEs. - **HC1 finite-sample correction (K_reference convergence, 3.9):** SA's clustered CR1 factor counts the absorbed unit + time FE via the `cluster_k_adjustment` increment (`K_reference = k_dm + 1 + rank(non-nested @@ -2170,7 +2174,8 @@ where weights ŵ_{g,e} = n_{g,e} / Σ_g n_{g,e} (sample share of cohort g at eve **Requirements checklist:** - [x] Never-treated units required as controls - [x] Interaction weights sum to 1 within each relative time period -- [x] Reference period defaults to e=-1, coefficient normalized to zero +- [x] Reference period defaults to e=-1, coefficient normalized to zero (per cohort: its latest observed pre-treatment period when it is not observed at e=-1) +- [x] Cohorts with no pre-treatment observation excluded with a warning; unidentified cohort-by-period coefficients reported as NaN - [x] Cohort-specific effects recoverable from results - [x] Cluster-robust SEs with delta method for aggregates - [x] R comparison: ATT matches within machine precision (<1e-11) @@ -6745,7 +6750,7 @@ CRITICAL: δ_pre = β_pre pins pre-treatment violations to observed coefficients - **Note:** Phase 7d: survey variance support. When input results carry `survey_metadata` with `df_survey`, Delta^SD smoothness uses folded non-central t critical values (`scipy.stats.nct`); Delta^RM and naive FLCI paths use `_get_critical_value(alpha, df)` (standard t-distribution). `df_survey=0` → NaN inference. CallawaySantAnnaResults stores `event_study_vcov` (full cross-event-time VCV from IF vectors; on bootstrap fits the covariance of the event-study bootstrap draws, see the CallawaySantAnna bootstrap event-study covariance Note), which HonestDiD uses instead of the diagonal fallback. For replicate-weight designs, the event-study VCV falls back to diagonal (multivariate replicate VCV deferred). - **Note (deviation from R):** When HonestDiD receives bootstrap-fitted CallawaySantAnna results (`n_bootstrap > 0`), it uses the covariance of the event-study bootstrap draws (see the CallawaySantAnna bootstrap event-study covariance Note), whose diagonal is the bootstrap SEs squared, so the analytical VCV is never mixed with bootstrap SEs. R's `honest_did.AGGTEobj` computes the covariance from the influence function matrix instead. On both input routes (native results and the `aggregate('event_study')` container) the stored matrix passes `_validate_vcov_subblock(..., allow_singular=False)` before use, so a singular matrix (fewer PSUs than horizons, analytical or bootstrap) raises `ValueError` rather than returning bounds; previously only the container route checked. Where no bootstrap covariance is stored (`n_bootstrap` at or below the number of event times, or a non-finite draw), HonestDiD falls back to `diag(se^2)` from the bootstrap SEs with a UserWarning; increase `n_bootstrap` or use analytical SEs (`n_bootstrap=0`) for the full covariance structure. - **Note (deviation from R):** When CallawaySantAnna results are passed to HonestDiD, `base_period != "universal"` emits a warning but does not error. R's `honest_did::honest_did.AGGTEobj` requires universal base period. Our implementation warns because the varying-base pre-treatment coefficients use consecutive comparisons (not a common reference), which changes the parallel-trends restriction interpretation. -- **Note (common-reference guard — gapped universal grids):** CallawaySantAnna `base_period="universal"` fits record `reference_event_times` — the distinct per-cohort positional-base event times (also carried on the `EventStudyResults` container). On a gapped time grid the positional bases land at different event times, and a cohort's base can OVERLAP another cohort's estimated horizon, where the aggregated row is a real estimate and NO reference-only row marks the anchor — `is_reference` cannot see it. When the field carries more than one entry, HonestDiD raises on BOTH input routes (native results and container) rather than returning bounds over coefficients normalized against different bases: Rambachan-Roth's `δ₀ = 0` normalization is defined around one common reference. PreTrendsPower applies the same guard (its hypothesized violation `δ` is likewise defined relative to one reference). Varying-base fits carry `reference_event_times=None` (no constant per-cohort reference exists) and are covered by the varying-base warnings instead. Universal-base inputs WITHOUT the field are never failed open: the native route re-derives the bases from the materialized reference cells (covers pre-3.9 pickles), and a provenance-less universal container (hand-built; producer-built containers always record the field) warns fail-safe that the common reference cannot be verified. Container admission covers CS- and Stacked-sourced containers (row M-024): StackedDiD threads `base_period="universal"` and a singleton `reference_event_times` by construction (one omitted reference per fit), needs `kappa_pre >= 2` for estimated pre-periods, and HonestDiD additionally requires the full retained event-study covariance (pre+post sub-block) non-singular — see the StackedDiD section's container-admission Note for the df_survey and withheld-inference semantics. +- **Note (common-reference guard — gapped universal grids):** CallawaySantAnna `base_period="universal"` fits record `reference_event_times` — the distinct per-cohort positional-base event times (also carried on the `EventStudyResults` container). On a gapped time grid the positional bases land at different event times, and a cohort's base can OVERLAP another cohort's estimated horizon, where the aggregated row is a real estimate and NO reference-only row marks the anchor — `is_reference` cannot see it. When the field carries more than one entry, HonestDiD raises on BOTH input routes (native results and container) rather than returning bounds over coefficients normalized against different bases: Rambachan-Roth's `δ₀ = 0` normalization is defined around one common reference. PreTrendsPower applies the same guard (its hypothesized violation `δ` is likewise defined relative to one reference). SunAbraham fits record the field too - the distinct per-cohort omitted relative periods, more than one when a cohort cannot be normalized at `e = -1 - anticipation` (SunAbraham per-cohort reference Note) - and the native SunAbraham route of PreTrendsPower applies the guard; HonestDiD has no SunAbraham route. Varying-base fits carry `reference_event_times=None` (no constant per-cohort reference exists) and are covered by the varying-base warnings instead. Universal-base inputs WITHOUT the field are never failed open: the native route re-derives the bases from the materialized reference cells (covers pre-3.9 pickles), and a provenance-less universal container (hand-built; producer-built containers always record the field) warns fail-safe that the common reference cannot be verified. Container admission covers CS- and Stacked-sourced containers (row M-024): StackedDiD threads `base_period="universal"` and a singleton `reference_event_times` by construction (one omitted reference per fit), needs `kappa_pre >= 2` for estimated pre-periods, and HonestDiD additionally requires the full retained event-study covariance (pre+post sub-block) non-singular — see the StackedDiD section's container-admission Note for the df_survey and withheld-inference semantics. **Reference implementation(s):** - R: `HonestDiD` package (Rambachan & Roth's official package) @@ -6811,7 +6816,7 @@ Violation types: - **Note (paper-supported alternative — Wald pretest form):** the library retains the Wald noncentral-χ² form as `pretest_form='wald'`. NIS is the paper's primary analysis convention (used for all 12 surveyed papers' empirical exercises in Section I), but the Wald form is also a paper-supported alternative: Roth's Propositions 1, 3, and 4 apply to any (measurable) acceptance region for the conditional moments (Props 1+3) and to any convex acceptance region for the variance-reduction guarantee (Prop 4). The Wald ellipsoid is convex, so all four propositions apply. Wald is faster (no MVN CDF call) and matches the pre-PR-B shipped numerical baseline. Use Wald for backwards-compat / speed; use NIS for canonical paper alignment and R `pretrends` parity. -- **Note (convention — `linear` violation pattern, γ-unit MDV):** `_get_violation_weights('linear')` consumes actual pre-period relative-time labels threaded through `fit()` (PR-B 2026-05-17 resolution of the PR-A linear-pattern deviation). When `relative_times` is provided, weights = `|t|` directly with NO L2 normalization, so `δ_pre = M · |t|` reflects Roth's `δ_t = γ · t` convention and the reported MDV equals γ. **The relative times are REFERENCE-ANCHORED on common-reference routes (2026-08 correction):** Roth's violation is normalized like the coefficients — it must vanish at the omitted period (his labeling puts the reference at `t = 0`) — so the threaded values are `t - t_ref`, not raw treatment-relative event labels: the TWFE event-study calendar container route derives them from the surface's `reference_period` provenance (`_coerce_relative_times_from_reference`; the removed MultiPeriodDiDResults route did the same), the CS universal route anchors at the singleton `reference_event_times`, SunAbraham at its omitted `e = -1 - anticipation`, and the `EventStudyResults` container at its single marked reference row (else the singleton provenance). Raw labels are retained ONLY where no common reference exists (CS `base_period="varying"` — covered by the varying-base warning and the TODO.md transformation row). Before the correction the CS/SA/container routes passed raw treatment-relative labels, overstating the violation at each pre-period by the reference offset (e.g. weights `[3, 2]` instead of `[2, 1]` for pre `[-3, -2]` around `t_ref = -1`) and understating γ-unit MDV correspondingly. Callers that bypass `fit()` and supply only `n_pre` retain the previous count-based, L2-normalized `[n_pre-1, ..., 0]` direction (preserves shipped Wald numerical baselines for unit tests). **Calendar period-label coverage:** on the calendar container route (the removed `MultiPeriodDiDResults`'s successor), the relative-time derivation supports numeric labels (`int` / `float` / `np.int64`) and `pandas.Period` / `pandas.Timestamp` / `np.datetime64` (via Period or Timedelta arithmetic with units of frequency / days respectively). For genuinely non-numeric or unordered labels (string period IDs, unranked categoricals), the helper emits an explicit `UserWarning` and falls back to the legacy count-based normalized direction — the reported MDV is then NOT in Roth's γ units. Users on string period IDs who need γ-unit MDV should re-fit with numeric labels. +- **Note (convention — `linear` violation pattern, γ-unit MDV):** `_get_violation_weights('linear')` consumes actual pre-period relative-time labels threaded through `fit()` (PR-B 2026-05-17 resolution of the PR-A linear-pattern deviation). When `relative_times` is provided, weights = `|t|` directly with NO L2 normalization, so `δ_pre = M · |t|` reflects Roth's `δ_t = γ · t` convention and the reported MDV equals γ. **The relative times are REFERENCE-ANCHORED on common-reference routes (2026-08 correction):** Roth's violation is normalized like the coefficients — it must vanish at the omitted period (his labeling puts the reference at `t = 0`) — so the threaded values are `t - t_ref`, not raw treatment-relative event labels: the TWFE event-study calendar container route derives them from the surface's `reference_period` provenance (`_coerce_relative_times_from_reference`; the removed MultiPeriodDiDResults route did the same), the CS universal route anchors at the singleton `reference_event_times`, SunAbraham at its recorded common reference (`e = -1 - anticipation`, or the one fallback period every cohort shares; a fit with more than one base is refused), and the `EventStudyResults` container at its single marked reference row (else the singleton provenance). Raw labels are retained ONLY where no common reference exists (CS `base_period="varying"` — covered by the varying-base warning and the TODO.md transformation row). Before the correction the CS/SA/container routes passed raw treatment-relative labels, overstating the violation at each pre-period by the reference offset (e.g. weights `[3, 2]` instead of `[2, 1]` for pre `[-3, -2]` around `t_ref = -1`) and understating γ-unit MDV correspondingly. Callers that bypass `fit()` and supply only `n_pre` retain the previous count-based, L2-normalized `[n_pre-1, ..., 0]` direction (preserves shipped Wald numerical baselines for unit tests). **Calendar period-label coverage:** on the calendar container route (the removed `MultiPeriodDiDResults`'s successor), the relative-time derivation supports numeric labels (`int` / `float` / `np.int64`) and `pandas.Period` / `pandas.Timestamp` / `np.datetime64` (via Period or Timedelta arithmetic with units of frequency / days respectively). For genuinely non-numeric or unordered labels (string period IDs, unranked categoricals), the helper emits an explicit `UserWarning` and falls back to the legacy count-based normalized direction — the reported MDV is then NOT in Roth's γ units. Users on string period IDs who need γ-unit MDV should re-fit with numeric labels. - **Note (CS varying-base input — warned, not rejected):** the `linear` construction `δ_pre = M · |t|` assumes pre-period coefficients are LEVELS against one common reference period. CallawaySantAnna `base_period="varying"` (the CS default) pre-treatment effects are consecutive-period comparisons — under a linear underlying trend they are constant increments, not values proportional to `|t|` — so linear power/MDV computed on them target a different violation shape. Both CS-sourced input routes (the native results object and the `EventStudyResults` container, which also warns fail-safe on `base_period=None` provenance) emit a `UserWarning` recommending `base_period='universal'`, mirroring HonestDiD's universal-base warning. (Admitted Stacked-sourced containers — row M-024 — are universal-base by construction and never trip this warning from a producer-built container; the guard messages derive the producer from `surface.source`.) Universal-base fits on GAPPED grids do not merely warn — they fail closed via the common-reference guard (`reference_event_times` provenance; see the HonestDiD note), because cohort-specific positional bases make the violation space ill-defined regardless of the pattern. Transforming the varying-base violation vector through each coefficient's actual base mapping (or requiring universal base) is tracked in TODO.md. *Standard errors:* @@ -6828,7 +6833,7 @@ Violation types: - **Note (deviation from paper — diagonal pre-period VCV fallback, bootstrap-only after PR-B):** Roth (2022)'s power and bias objects operate on the full pre-period covariance block Σ_22. After PR-B 2026-05-17, the shipped `compute_pretrends_power` adapter consumes full Σ_22 on the non-bootstrap paths for ALL three natively supported result types (and, since row M-024, on admitted CS-/StackedDiD-sourced `aggregate('event_study')` containers carrying `vcov` — StackedDiD persists its ES VCV in every inference mode, so Stacked containers always take the full-Σ_22 tier): - the TWFE event-study calendar `EventStudyResults` container (the removed `MultiPeriodDiDResults`'s successor since 4.0): full pre-period sub-block from the container's `vcov` / `vcov_index`; diag fallback only when the container carries no `vcov`. - `CallawaySantAnnaResults`: full `event_study_vcov` sub-block (the matrix is persisted at `staggered_results.py:126-128`). On bootstrap fits it is the covariance of the event-study bootstrap draws, whose diagonal is the bootstrap SEs squared (CallawaySantAnna bootstrap event-study covariance Note); fits where none is stored (`n_bootstrap` at or below the number of event times, replicate weights) fall through to `diag(ses^2)`. - - `SunAbrahamResults`: full `event_study_vcov` sub-block on non-bootstrap fits, constructed in `sun_abraham.py` via `W @ vcov_cohort @ W.T` where W is the cohort-aggregation matrix (PR-B Step 3 SA extension). Bootstrap SA fits and replicate-weight survey fits clear `event_study_vcov` to prevent mixing the analytical VCV with bootstrap / replicate SEs, so they fall through to `diag(ses^2)`. + - `SunAbrahamResults`: full `event_study_vcov` sub-block on non-bootstrap fits, constructed in `sun_abraham.py` via `W @ vcov_cohort @ W.T` where W is the cohort-aggregation matrix (PR-B Step 3 SA extension), taken over the cells with a finite effect: the rows and columns of pooled periods that contain an unidentified cell are NaN and the remaining block is unchanged. Bootstrap SA fits and replicate-weight survey fits clear `event_study_vcov` to prevent mixing the analytical VCV with bootstrap / replicate SEs, so they fall through to `diag(ses^2)`. The diag-fallback path is therefore reserved for cases where the analytical VCV is genuinely unavailable (bootstrap SA fits, bootstrap CS fits with `n_bootstrap` at or below the number of event times, replicate-weight survey fits, a calendar container without `vcov`). In those cases dropping off-diagonals is documented as a non-paper approximation — not provably conservative, since the direction of the discrepancy with the full-Σ_22 calc depends on the sign and magnitude of the dropped correlations. See `docs/methodology/papers/roth-2022-review.md` for the full derivation. diff --git a/docs/methodology/REPORTING.md b/docs/methodology/REPORTING.md index db646115..19dec420 100644 --- a/docs/methodology/REPORTING.md +++ b/docs/methodology/REPORTING.md @@ -458,7 +458,11 @@ what is reconciled. `compute_pretrends_power(results, violation_type='linear', alpha=alpha, target_power=0.80)` for the estimator families that ship a `compute_pretrends_power` adapter: `CallawaySantAnnaResults` - and `SunAbrahamResults` (the removed `MultiPeriodDiDResults` adapter went + and `SunAbrahamResults` (a SunAbraham fit whose cohorts are normalized + against different reference periods - `reference_event_times` with + more than one entry - is refused by the adapter, so the + `pretrends_power` section reports `status="error"` with that reason; + the removed `MultiPeriodDiDResults` adapter went at 4.0; the TWFE event-study mode's `EventStudyResults` surface is rejected by DR pending admission - see `_APPLICABILITY["pretrends_power"]` in diff --git a/docs/v4-deprecations.yaml b/docs/v4-deprecations.yaml index 051afc04..a09594c0 100644 --- a/docs/v4-deprecations.yaml +++ b/docs/v4-deprecations.yaml @@ -1029,7 +1029,7 @@ rows: phase: 2 test_ref: tests/test_event_study_surface.py code_refs: [diff_diff/results_base.py, diff_diff/__init__.py] - notes: "Phase 2 unified event-study representation (spec section 5): EventStudyResults container + builders for the 14 producers (CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, SpilloverDiD, ContinuousDiD, EfficientDiD, WooldridgeDiD, StaggeredTripleDifference, MultiPeriodDiD, LPDiD, ChaisemartinDHaultfoeuille, HeterogeneousAdoptionDiD). Canonical quintet columns, explicit is_reference marking (successor to the retiring sentinels [M-093]), vcov+vcov_index ordering, cband columns, event_time_convention metadata. Public exposure rides aggregate(type='event_study') in Phase 2 PR (b); merged TWFE returns it in Phase 3 [M-010]. introduced_in gates the 3.9 cut, mirroring [M-091]. Born done in this introducing diff (builder is package-internal; the class is exported). Amended pre-cut (same test_ref, introduced_in 3.9 not yet released): df became PER-ROW (one entry per event time, the df each stored p/CI actually used; joins the pinned to_dataframe schema) and StackedDiD/TwoStageDiD persist their internal full ES VCVs (event_study_vcov/_index/_df container fields; mode-gated for TwoStageDiD bootstrap/replicate). Completed pre-cut by the remaining producer channels: SunAbraham (per-event dict) and de Chaisemartin-D'Haultfoeuille (scalar) event_study_df, plus LPDiD pooled_df for the headline pre/post windows - every producer whose inference records a df now exposes it. Amended pre-cut a second time (2(b) PR-1, with M-026): three optional PROVENANCE fields appended last - base_period, anticipation, and df_survey (the fit's resolved SCALAR inference df beside the per-row channel: survey_metadata.df_survey with replicate-undefined mapping to the 0.0 fail-closed sentinel, else df_inference, else None - the per-row df column cannot encode that sentinel because __post_init__ NaNs it wherever p is non-finite) - threaded by the builders (the _empty_surface early return included) so the container consumers (HonestDiD's universal-base check, PreTrendsPower's anticipation cutoff, the honest df extraction) read fit-faithful values instead of dropping them. Amended pre-cut a third time (same PR): a fourth provenance field reference_event_times (also new on CallawaySantAnnaResults, computed at fit under base_period=universal) - the DISTINCT per-cohort positional-base event times, the common-reference signal is_reference cannot carry on gapped grids where a cohort's base overlaps another cohort's estimated horizon; HonestDiD and PreTrendsPower fail closed on more than one entry, on BOTH input routes (REGISTRY HonestDiD common-reference-guard Note). SCOPE QUALIFIER (2(b) PR-3a, with M-023): the 'every producer whose inference records a df now exposes it' sentence is satisfied on EfficientDiD through the SCALAR df_survey channel only - its newly public aggregate('event_study') container has no per-row df source (no event_study_df/df_inference field; the per-row column is all-NaN, contract-permitted for a producer that records none); threading the retained kit scalar into the per-row channel is the TODO.md M-092-completion row. The qualifier EXTENDS to ImputationDiD (2(b) PR-3b, with M-021): its newly public container likewise exposes only the scalar df_survey channel (no per-row df source; all-NaN per-row column, identical to its fit-time surface) - the same TODO.md completion row names it. The qualifier EXTENDS to ContinuousDiD (2(b) PR-3c, with M-025): its newly public container exposes only the scalar df_survey channel via the carrier's survey_metadata (no event_study_df/df_inference field, so _from_relative_dict publishes an all-NaN per-row df column on survey fits whose ES rows received a finite _survey_df - identical on the fit-time and post-fit routes); the same TODO.md completion row names it. Amended pre-cut a fourth time (2(b) PR-4, with M-027): an optional 'estimand' provenance field appended last plus a matching per-row 'estimand' column appended to the pinned to_dataframe schema - the per-row estimand discriminator ('att' for every ATT producer; the estimand label 'WAS'/'WAS_d_lower' where the att column is NOT an ATT, relayed by _from_had from target_parameter and honored by summary()'s column heading and to_dict()) - so neither the container nor a detached frame can silently relabel WAS-family numbers as ATT (the AggregationResult.target precedent). The qualifier EXTENDS to HeterogeneousAdoptionDiD (2(b) PR-4, with M-027): its newly public event-study container exposes only the scalar df_survey channel (the _from_had adapter passes no per-row df while survey ES fits pass a finite per-horizon df_infer into every safe_inference call); the same TODO.md completion row names it. Amended pre-cut a fifth time (Phase 3(a), with M-010): TWO optional provenance fields appended last - post_periods (the producer's AUTHORITATIVE calendar partition, an arbitrary subset being legal on MultiPeriodDiD, so consumers must never re-derive it positionally; threaded by _from_mpd and the TWFE event-study producer, None from every other builder; content-validated in __post_init__: nonempty, no duplicates, subset of event_time, disjoint from reference rows) and estimation_spec ('within'|'pooled', TWFE producer only, value-validated per the n_kind off-vocabulary precedent) - both routed through to_dict() with JSON-safe labels and consumed by the HonestDiD/PreTrendsPower calendar routes and the plotter's partition-aware split; same test_ref extended. QUALIFIERS RESOLVED (3.12, M-092 completion): the four SCOPE-QUALIFIER producers above (EfficientDiD, ImputationDiD, ContinuousDiD, HeterogeneousAdoptionDiD) now expose a results-level event_study_df scalar threaded into the container's per-row df column - finite on analytical survey fits (EDiD: the post-overall snapshot; Imputation: the FINAL survey df, level-matched on replicate replays, leads included; ContinuousDiD: the kit survey_df; HAD: the unit-level design df via _from_had), None on non-survey/bootstrapped/no-surface fits and for the replicate-undefined 0 sentinel. The formerly-named TODO.md completion row is CLOSED; per-row df pins live in tests/test_aggregate_contract.py (TestPerRowDfProvenanceCompletion)." + notes: "Phase 2 unified event-study representation (spec section 5): EventStudyResults container + builders for the 14 producers (CallawaySantAnna, SunAbraham, ImputationDiD, TwoStageDiD, StackedDiD, SpilloverDiD, ContinuousDiD, EfficientDiD, WooldridgeDiD, StaggeredTripleDifference, MultiPeriodDiD, LPDiD, ChaisemartinDHaultfoeuille, HeterogeneousAdoptionDiD). Canonical quintet columns, explicit is_reference marking (successor to the retiring sentinels [M-093]), vcov+vcov_index ordering, cband columns, event_time_convention metadata. Public exposure rides aggregate(type='event_study') in Phase 2 PR (b); merged TWFE returns it in Phase 3 [M-010]. introduced_in gates the 3.9 cut, mirroring [M-091]. Born done in this introducing diff (builder is package-internal; the class is exported). Amended pre-cut (same test_ref, introduced_in 3.9 not yet released): df became PER-ROW (one entry per event time, the df each stored p/CI actually used; joins the pinned to_dataframe schema) and StackedDiD/TwoStageDiD persist their internal full ES VCVs (event_study_vcov/_index/_df container fields; mode-gated for TwoStageDiD bootstrap/replicate). Completed pre-cut by the remaining producer channels: SunAbraham (per-event dict) and de Chaisemartin-D'Haultfoeuille (scalar) event_study_df, plus LPDiD pooled_df for the headline pre/post windows - every producer whose inference records a df now exposes it. Amended pre-cut a second time (2(b) PR-1, with M-026): three optional PROVENANCE fields appended last - base_period, anticipation, and df_survey (the fit's resolved SCALAR inference df beside the per-row channel: survey_metadata.df_survey with replicate-undefined mapping to the 0.0 fail-closed sentinel, else df_inference, else None - the per-row df column cannot encode that sentinel because __post_init__ NaNs it wherever p is non-finite) - threaded by the builders (the _empty_surface early return included) so the container consumers (HonestDiD's universal-base check, PreTrendsPower's anticipation cutoff, the honest df extraction) read fit-faithful values instead of dropping them. Amended pre-cut a third time (same PR): a fourth provenance field reference_event_times (also new on CallawaySantAnnaResults, computed at fit under base_period=universal) (post-cut: SunAbrahamResults records its distinct per-cohort omitted relative periods in the same field) - the DISTINCT per-cohort positional-base event times, the common-reference signal is_reference cannot carry on gapped grids where a cohort's base overlaps another cohort's estimated horizon; HonestDiD and PreTrendsPower fail closed on more than one entry, on BOTH input routes (REGISTRY HonestDiD common-reference-guard Note). SCOPE QUALIFIER (2(b) PR-3a, with M-023): the 'every producer whose inference records a df now exposes it' sentence is satisfied on EfficientDiD through the SCALAR df_survey channel only - its newly public aggregate('event_study') container has no per-row df source (no event_study_df/df_inference field; the per-row column is all-NaN, contract-permitted for a producer that records none); threading the retained kit scalar into the per-row channel is the TODO.md M-092-completion row. The qualifier EXTENDS to ImputationDiD (2(b) PR-3b, with M-021): its newly public container likewise exposes only the scalar df_survey channel (no per-row df source; all-NaN per-row column, identical to its fit-time surface) - the same TODO.md completion row names it. The qualifier EXTENDS to ContinuousDiD (2(b) PR-3c, with M-025): its newly public container exposes only the scalar df_survey channel via the carrier's survey_metadata (no event_study_df/df_inference field, so _from_relative_dict publishes an all-NaN per-row df column on survey fits whose ES rows received a finite _survey_df - identical on the fit-time and post-fit routes); the same TODO.md completion row names it. Amended pre-cut a fourth time (2(b) PR-4, with M-027): an optional 'estimand' provenance field appended last plus a matching per-row 'estimand' column appended to the pinned to_dataframe schema - the per-row estimand discriminator ('att' for every ATT producer; the estimand label 'WAS'/'WAS_d_lower' where the att column is NOT an ATT, relayed by _from_had from target_parameter and honored by summary()'s column heading and to_dict()) - so neither the container nor a detached frame can silently relabel WAS-family numbers as ATT (the AggregationResult.target precedent). The qualifier EXTENDS to HeterogeneousAdoptionDiD (2(b) PR-4, with M-027): its newly public event-study container exposes only the scalar df_survey channel (the _from_had adapter passes no per-row df while survey ES fits pass a finite per-horizon df_infer into every safe_inference call); the same TODO.md completion row names it. Amended pre-cut a fifth time (Phase 3(a), with M-010): TWO optional provenance fields appended last - post_periods (the producer's AUTHORITATIVE calendar partition, an arbitrary subset being legal on MultiPeriodDiD, so consumers must never re-derive it positionally; threaded by _from_mpd and the TWFE event-study producer, None from every other builder; content-validated in __post_init__: nonempty, no duplicates, subset of event_time, disjoint from reference rows) and estimation_spec ('within'|'pooled', TWFE producer only, value-validated per the n_kind off-vocabulary precedent) - both routed through to_dict() with JSON-safe labels and consumed by the HonestDiD/PreTrendsPower calendar routes and the plotter's partition-aware split; same test_ref extended. QUALIFIERS RESOLVED (3.12, M-092 completion): the four SCOPE-QUALIFIER producers above (EfficientDiD, ImputationDiD, ContinuousDiD, HeterogeneousAdoptionDiD) now expose a results-level event_study_df scalar threaded into the container's per-row df column - finite on analytical survey fits (EDiD: the post-overall snapshot; Imputation: the FINAL survey df, level-matched on replicate replays, leads included; ContinuousDiD: the kit survey_df; HAD: the unit-level design df via _from_had), None on non-survey/bootstrapped/no-surface fits and for the replicate-undefined 0 sentinel. The formerly-named TODO.md completion row is CLOSED; per-row df pins live in tests/test_aggregate_contract.py (TestPerRowDfProvenanceCompletion)." - id: M-093 kind: behavior group: results-contract diff --git a/docs/v4-design.md b/docs/v4-design.md index 206494d3..fd035746 100644 --- a/docs/v4-design.md +++ b/docs/v4-design.md @@ -557,7 +557,8 @@ channel beside the per-row one - the per-row column cannot encode the replicate-undefined 0.0 sentinel - and `reference_event_times`, the distinct per-cohort positional-base event times whose multi-entry case fails the HonestDiD/PreTrendsPower common-reference guard on gapped -universal grids; amended into [M-092] pre-cut with the +universal grids (post-cut, `SunAbrahamResults` records its distinct +per-cohort omitted relative periods in the same field); amended into [M-092] pre-cut with the 2(b) consumer delivery), and `to_dataframe(level="event_study")` emitting the `EVENT_STUDY_SCHEMA` columns as an identical PREFIX from every estimator (amended at the 4.0 cut, item 8b [M-093]: a producer may append diff --git a/tests/test_sun_abraham.py b/tests/test_sun_abraham.py index 8eb60bdc..90ee5446 100644 --- a/tests/test_sun_abraham.py +++ b/tests/test_sun_abraham.py @@ -2228,3 +2228,772 @@ def test_summary_rejects_non_fit_alpha(self, alpha_fitted, bad_alpha): def test_summary_accepts_fit_alpha(self, alpha_fitted): assert alpha_fitted.summary(alpha=alpha_fitted.alpha) == alpha_fitted.summary() + + +# --------------------------------------------------------------------------- +# Per-cohort reference, cohorts without a pre-period, identification guard +# --------------------------------------------------------------------------- + +_ID_KW = dict(outcome="y", unit="unit", time="time", first_treat="g") + + +def _tau(e): + """True effect at relative period ``e`` (zero before treatment).""" + return 2.0 + 0.5 * e if e >= 0 else 0.0 + + +def _ident_panel(noise=0.0, seed=0, n_units=90, cohorts=(0, 3, 5), n_periods=8): + """Unit effect + linear time trend + effect ``2 + 0.5 e``; noise sd ``noise``.""" + rng = np.random.default_rng(seed) + rows = [] + for i in range(n_units): + g = cohorts[i % len(cohorts)] + alpha = rng.normal() + for t in range(1, n_periods + 1): + y = alpha + 0.3 * t + rng.normal(scale=noise) if noise else alpha + 0.3 * t + rows.append((i, t, g, y + (_tau(t - g) if g and t >= g else 0.0))) + return pd.DataFrame(rows, columns=["unit", "time", "g", "y"]) + + +def _fit_id(data, est=None, **fit_kwargs): + """Fit and return (results, list of UserWarning texts).""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + res = SunAbraham(**(est or {})).fit(data, **_ID_KW, **fit_kwargs) + texts = [str(w.message) for w in caught if issubclass(w.category, UserWarning)] + return res, texts + + +def _oracle_refs(data, anticipation=0): + """Independent re-derivation of the per-cohort reference rule.""" + comparison = set(data.loc[data["g"] == 0, "time"]) + e_ref = -1 - anticipation + refs = {} + for g in sorted(x for x in data["g"].unique() if x > 0): + rel = set((data.loc[data["g"] == g, "time"] - g).tolist()) + pre = sorted((e for e in rel if e < -anticipation), reverse=True) + candidates = ([e_ref] if e_ref in rel else []) + [e for e in pre if e != e_ref] + usable = [e for e in candidates if g + e in comparison] + refs[g] = (usable or candidates or [None])[0] + return refs + + +def _oracle_unidentified(data, refs): + """Cells with a nonzero entry in the null space of the explicit-dummy design.""" + d = data.reset_index(drop=True) + rel = d["time"] - d["g"] + # A cell is a (cohort, relative period) other than the cohort's reference + # and other than e = -1, which is never an estimated period. + cells = sorted( + {(int(g), int(e)) for g, e in zip(d["g"], rel) if g > 0 and e != refs[g] and e != -1} + ) + cell_cols = [((d["g"] == g) & (rel == e)).astype(float).values for g, e in cells] + X = np.column_stack( + cell_cols + + [pd.get_dummies(d["unit"], dtype=float).values] + + [pd.get_dummies(d["time"], dtype=float).values] + ) + # full_matrices=True: a sparse panel has fewer rows than columns, and the + # economy SVD would silently omit null directions. + _, s, vt = np.linalg.svd(X, full_matrices=True) + rank = int((s > 1e-9 * s.max()).sum()) + null = vt[rank:].T + return {c for c, row in zip(cells, null[: len(cells)]) if np.abs(row).max() > 1e-7}, cells + + +def _nan_cells(res): + return { + (int(g), int(e)) for (g, e), v in res.cohort_effects.items() if not np.isfinite(v["effect"]) + } + + +def _true_att(data, res): + """Truth for the overall ATT: post rows weighted by treated observations.""" + rel = (data["time"] - data["g"])[data["g"] > 0] + post = [e for e in res.event_study_effects if e >= 0] + n = np.array([(rel == e).sum() for e in post], dtype=float) + return float(np.sum(n * np.array([_tau(e) for e in post])) / n.sum()) + + +def _gap_panel(noise=0.0, seed=0): + d = _ident_panel(noise=noise, seed=seed) + return d[~((d["g"] == 5) & (d["time"] == 4))] # cohort 5 unobserved at e = -1 + + +def _nt_absent_panel(noise=0.0, seed=0, period=6): + d = _ident_panel(noise=noise, seed=seed) + return d[~((d["g"] == 0) & (d["time"] == period))] + + +def _split_cohort_panel(noise=0.0): + """Cohort 5's units are observed at two disjoint sets of periods.""" + d = _ident_panel(noise=noise) + even = d["unit"] % 2 == 0 + drop = (d["g"] == 5) & ((even & ~d["time"].isin([1, 3])) | (~even & d["time"].isin([1, 3, 4]))) + return d[~drop] + + +class TestSunAbrahamCohortReference: + """A cohort not observed at e = -1 - anticipation; cohorts with no pre-period.""" + + @pytest.mark.parametrize( + "case", + [ + "gap", + "treated_at_first_period", + "first_observed_at_zero", + "anticipation", + "no_comparison_at_reference", + ], + ) + def test_exact_recovery_noiseless(self, case): + d = _ident_panel() + est = {} + if case == "gap": + data, fitted = _gap_panel(), _gap_panel() + elif case == "treated_at_first_period": + data = pd.concat([d[d["g"] != 3], d[d["g"] == 3].assign(g=1)]) + # recompute outcomes for the relabelled cohort so the truth holds + data = data.assign( + y=lambda x: x["y"] + - np.where((x["g"] == 1) & (x["time"] >= 3), [_tau(t - 3) for t in x["time"]], 0.0) + + np.where(x["g"] == 1, [_tau(t - 1) for t in x["time"]], 0.0) + ) + fitted = data[data["g"] != 1] + elif case == "first_observed_at_zero": + data = d[~((d["g"] == 3) & (d["time"] < 3))] + fitted = data[data["g"] != 3] + elif case == "no_comparison_at_reference": + # Never-treated units are absent at t = 4, cohort 5's e = -1: the + # cohort is normalized at e = -2 (t = 3) instead, and everything + # stays identified. + data = fitted = _nt_absent_panel(period=4) + else: + est = {"anticipation": 1} + data = d[~((d["g"] == 3) & (d["time"] == 1))] # no row at e <= -2 + fitted = data[data["g"] != 3] + res, texts = _fit_id(data, est=est) + assert not any("rank" in t.lower() or "not identified by" in t for t in texts) + if case == "no_comparison_at_reference": + assert any("cohort 5: -2" in t for t in texts) + assert res.reference_event_times == (-2, -1) + assert np.isfinite(res.att) + for (g, e), v in res.cohort_effects.items(): + assert abs(v["effect"] - _tau(e)) < 1e-9, (g, e, v["effect"]) + for e, v in res.event_study_effects.items(): + assert abs(v["effect"] - _tau(e)) < 1e-9, (e, v["effect"]) + assert abs(res.att - _true_att(fitted, res)) < 1e-9 + + @pytest.mark.parametrize("n_bootstrap", [0, 40]) + @pytest.mark.parametrize("control_group", ["never_treated", "not_yet_treated"]) + def test_exclusion_equals_the_reduced_fit(self, n_bootstrap, control_group): + d = _ident_panel(noise=0.5) + full = d[~((d["g"] == 3) & (d["time"] < 3))] # cohort 3 has no pre-period + est = {"n_bootstrap": n_bootstrap, "seed": 11, "control_group": control_group} + res, texts = _fit_id(full, est=est) + ref, ref_texts = _fit_id(full[full["g"] != 3], est=est) + assert any("EXCLUDED" in t and "Cohort(s) 3" in t for t in texts) + assert not any("EXCLUDED" in t for t in ref_texts) + assert res.groups == ref.groups == [5] + assert res.n_obs == ref.n_obs and res.n_treated_units == ref.n_treated_units + np.testing.assert_allclose([res.att, res.se], [ref.att, ref.se], rtol=1e-12) + assert set(res.event_study_effects) == set(ref.event_study_effects) + for e, v in res.event_study_effects.items(): + w = ref.event_study_effects[e] + np.testing.assert_allclose([v["effect"], v["se"]], [w["effect"], w["se"]], rtol=1e-12) + assert set(res.cohort_effects) == set(ref.cohort_effects) + for k, v in res.cohort_effects.items(): + np.testing.assert_allclose(v["effect"], ref.cohort_effects[k]["effect"], rtol=1e-12) + + def test_fallback_reference_matches_an_independent_regression(self): + data = _gap_panel(noise=0.5) + res, texts = _fit_id(data) + assert any("cohort 5: -2" in t and "mix normalization bases" in t for t in texts) + refs = {3: -1, 5: -2} + d = data.reset_index(drop=True) + rel = d["time"] - d["g"] + cells = sorted({(int(g), int(e)) for g, e in zip(d["g"], rel) if g > 0 and e != refs[g]}) + X = np.column_stack( + [((d["g"] == g) & (rel == e)).astype(float).values for g, e in cells] + + [pd.get_dummies(d["unit"], dtype=float).values] + + [pd.get_dummies(d["time"], dtype=float).values[:, 1:]] + ) + beta = np.linalg.lstsq(X, d["y"].values, rcond=None)[0][: len(cells)] + assert {(int(g), int(e)) for g, e in res.cohort_effects} == set(cells) + for (g, e), b in zip(cells, beta): + np.testing.assert_allclose( + res.cohort_effects[(g, e)]["effect"], b, rtol=1e-8, atol=1e-10 + ) + # the pooled e = -2 row holds cohort 3 only: cohort 5's cell is its reference + assert set(res.cohort_weights[-2]) == {3} + + def test_fractional_pre_period_is_a_pre_period(self): + # Cohort treated at 3, observed at 2.5 but not at 2: e = -0.5 is before + # treatment, so the cohort is kept and normalized there. + d = _ident_panel(n_units=60, cohorts=(0, 3)) + half = d[d["time"] == 2].assign(time=2.5) + half = half.assign(y=half["y"] + 0.3 * 0.5) + data = pd.concat([d[~((d["g"] == 3) & (d["time"] == 2))], half[half["g"] == 3]]) + # never-treated units need the half period too, or its cells are unidentified + data = pd.concat([data, half[half["g"] == 0]]).sort_values(["unit", "time"]) + res, texts = _fit_id(data) + assert any("cohort 3: -0.5" in t for t in texts) + assert res.reference_event_times == (-0.5,) + assert res.reference_period == -0.5 and res.reference_observed + for (g, e), v in res.cohort_effects.items(): + assert abs(v["effect"] - _tau(e)) < 1e-9 + + def test_every_cohort_without_a_pre_period_raises(self): + d = _ident_panel() + data = d[~((d["g"] > 0) & (d["time"] < d["g"]))] + with pytest.raises(ValueError, match="only\\s+treated cohorts"): + SunAbraham().fit(data, **_ID_KW) + + def test_no_never_treated_error_keeps_precedence(self): + d = _ident_panel() + data = d[(d["g"] > 0) & (d["time"] >= d["g"])] # no controls AND no pre-period + with pytest.raises(ValueError, match="No never-treated units"): + SunAbraham().fit(data, **_ID_KW) + + @pytest.mark.parametrize("vcov_type", ["hc1", "hc2_bm", "classical"]) + def test_variance_families_agree_on_point_estimates(self, vcov_type): + base, _ = _fit_id(_gap_panel(noise=0.5)) + res, _ = _fit_id(_gap_panel(noise=0.5), est={"vcov_type": vcov_type}) + np.testing.assert_allclose(res.att, base.att, rtol=1e-9) + assert np.isfinite(res.se) and res.se > 0 + for e, v in res.event_study_effects.items(): + np.testing.assert_allclose( + v["effect"], base.event_study_effects[e]["effect"], atol=1e-8 + ) + assert np.isfinite(v["se"]) and v["se"] > 0 + + def test_conley_reads_coordinates_from_the_reduced_frame(self): + d = _ident_panel(noise=0.5) + rng = np.random.default_rng(4) + loc = {u: (rng.uniform(30, 45), rng.uniform(-100, -80)) for u in d["unit"].unique()} + d = d.assign(lat=d["unit"].map(lambda u: loc[u][0]), lon=d["unit"].map(lambda u: loc[u][1])) + full = d[~((d["g"] == 3) & (d["time"] < 3))] + est = dict( + vcov_type="conley", + conley_coords=("lat", "lon"), + conley_cutoff_km=500.0, + conley_lag_cutoff=1, + ) + res, texts = _fit_id(full, est=est) + ref, _ = _fit_id(full[full["g"] != 3], est=est) + assert any("EXCLUDED" in t for t in texts) + np.testing.assert_allclose([res.att, res.se], [ref.att, ref.se], rtol=1e-12) + + +class TestSunAbrahamReferenceFields: + """reference_event_times / reference_period and the pre-trends consumer.""" + + def test_balanced_fit_records_the_single_reference(self): + res, texts = _fit_id(_ident_panel(noise=0.5)) + assert res.reference_event_times == (-1,) + assert res.reference_period == -1 and res.reference_observed + assert not any("normalized at their latest" in t for t in texts) + frame = res.to_dataframe() + ref_rows = frame[frame["is_reference"]] + assert ref_rows["event_time"].tolist() == [-1] and ref_rows["att"].tolist() == [0.0] + + def test_mixed_references_are_recorded_and_refused_by_pretrends(self): + from diff_diff import DiagnosticReport, compute_pretrends_power + + res, _ = _fit_id(_gap_panel(noise=0.5)) + assert res.reference_event_times == (-2, -1) + assert res.reference_period == -1 and res.reference_observed + # e = -2 is an ESTIMATED row here (cohort 3), not a reference row + frame = res.to_dataframe() + assert frame.loc[frame["is_reference"], "event_time"].tolist() == [-1] + with pytest.raises(ValueError, match="DISTINCT normalization\\s+bases"): + compute_pretrends_power(res) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + section = DiagnosticReport(res).to_dict()["pretrends_power"] + assert section["status"] == "error" + assert "DISTINCT normalization" in section["reason"] + + def test_balanced_pretrends_is_unchanged_by_the_new_field(self): + import dataclasses + + from diff_diff import compute_pretrends_power + + res, _ = _fit_id(_ident_panel(noise=0.5)) + legacy = dataclasses.replace(res, reference_event_times=None) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + new, old = compute_pretrends_power(res), compute_pretrends_power(legacy) + # The deterministic inputs are identical; the MDV itself comes from a + # simulated box probability and is compared to its Monte Carlo noise. + np.testing.assert_array_equal(new.violation_weights, old.violation_weights) + np.testing.assert_array_equal(new.vcov, old.vcov) + np.testing.assert_array_equal(new.pre_period_effects, old.pre_period_effects) + assert new.covariance_source == old.covariance_source == "full_pre_period_vcov" + assert new.mdv == pytest.approx(old.mdv, rel=1e-3) + + @pytest.mark.parametrize("layout", ["single_cohort_gap", "biennial"]) + def test_shared_fallback_reference_becomes_the_anchor(self, layout): + from diff_diff import compute_pretrends_power + + if layout == "single_cohort_gap": + d = _ident_panel(noise=0.5, n_units=60, cohorts=(0, 5)) + data = d[~((d["g"] == 5) & (d["time"] == 4))] + else: # odd periods only: no cohort is observed at e = -1 + d = _ident_panel(noise=0.5, n_units=90, cohorts=(0, 5, 7), n_periods=11) + data = d[d["time"] % 2 == 1] + res, texts = _fit_id(data) + assert res.reference_event_times == (-2,) + assert res.reference_period == -2 and res.reference_observed + assert any("normalized at their latest" in t for t in texts) + assert not any("mix normalization bases" in t for t in texts) + assert -2 not in res.event_study_effects and -1 not in res.event_study_effects + frame = res.to_dataframe() + assert frame.loc[frame["is_reference"], "event_time"].tolist() == [-2] + # Roth's linear violation is anchored at the true base, -2 + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + pp = compute_pretrends_power(res) + pre = sorted(e for e in res.event_study_effects if e < 0) + np.testing.assert_allclose(np.abs(pp.violation_weights), [abs(e + 2) for e in pre]) + + +class TestSunAbrahamIdentificationGuard: + """Coefficients the observed rows do not identify are NaN, never a wrong number.""" + + @pytest.mark.parametrize("builder", [_nt_absent_panel, _split_cohort_panel]) + def test_structured_unidentified_cells_are_nan(self, builder): + data = builder() + res, texts = _fit_id(data) + expected, cells = _oracle_unidentified(data, _oracle_refs(data)) + assert expected # the panel does exercise the guard + assert _nan_cells(res) == expected + assert {(int(g), int(e)) for g, e in res.cohort_effects} == set(cells) + warning = [t for t in texts if "not identified by the observed rows" in t] + assert len(warning) == 1 + g, e = sorted(expected)[0] + assert f"({g}, {e})" in warning[0] + for (g, e), v in res.cohort_effects.items(): + if (int(g), int(e)) in expected: + assert np.isnan(v["effect"]) and np.isnan(v["se"]) + else: + assert abs(v["effect"] - _tau(e)) < 1e-9 + pooled_nan = {e for (_, e) in expected} + for e, v in res.event_study_effects.items(): + if e in pooled_nan: + assert np.isnan(v["effect"]) and np.isnan(v["se"]) + assert np.isnan(v["p_value"]) and np.all(np.isnan(v["conf_int"])) + else: + assert abs(v["effect"] - _tau(e)) < 1e-9 + if any(e >= 0 for e in pooled_nan): + assert np.isnan(res.att) and np.isnan(res.se) + + @staticmethod + def _random_panels(): + base = _ident_panel() + for seed in range(40): + rng = np.random.default_rng(seed) + yield base[rng.random(len(base)) > rng.choice([0.3, 0.6, 0.85])] + for seed in range(10): # every unit observed at two adjacent periods + rng = np.random.default_rng(100 + seed) + start = rng.integers(1, 8, size=42) + rows = [] + for i in range(42): + g = (0, 3, 4)[i % 3] + alpha = rng.normal() + for t in (start[i], start[i] + 1): + rows.append((i, t, g, alpha + 0.3 * t + (_tau(t - g) if g and t >= g else 0.0))) + yield pd.DataFrame(rows, columns=["unit", "time", "g", "y"]) + + def test_no_wrong_finite_number_on_random_missingness(self): + n_checked = n_flagged = 0 + for data in self._random_panels(): + refs = _oracle_refs(data) + data = data[~data["g"].isin([g for g, r in refs.items() if r is None])] + refs = {g: r for g, r in refs.items() if r is not None} + if not refs or not (data["g"] == 0).any(): + continue + res, _ = _fit_id(data) + expected, cells = _oracle_unidentified(data, refs) + assert _nan_cells(res) == expected + for (g, e), v in res.cohort_effects.items(): + if (int(g), int(e)) not in expected: + assert abs(v["effect"] - _tau(e)) < 1e-6, (g, e, v["effect"]) + for e, v in res.event_study_effects.items(): + if np.isfinite(v["effect"]): + assert abs(v["effect"] - _tau(e)) < 1e-6 + n_checked += 1 + n_flagged += bool(expected) + assert n_checked >= 40 and n_flagged >= 10 + + def test_full_dummy_path_flags_the_same_cells(self): + for period in (1, 6): + data = _nt_absent_panel(period=period) + within, _ = _fit_id(data) + for vcov_type in ("hc2_bm", "classical"): + res, _ = _fit_id(data, est={"vcov_type": vcov_type}) + assert _nan_cells(res) == _nan_cells(within) != set() + for k, v in res.cohort_effects.items(): + if np.isfinite(v["effect"]): + assert abs(v["effect"] - _tau(k[1])) < 1e-9 + + def test_rank_deficient_action(self): + data = _nt_absent_panel() + with pytest.raises(ValueError, match="rank-deficient.*\\(3, 3\\)"): + SunAbraham(rank_deficient_action="error").fit(data, **_ID_KW) + silent, texts = _fit_id(data, est={"rank_deficient_action": "silent"}) + assert not any("not identified" in t or "ank-deficient" in t for t in texts) + warned, texts = _fit_id(data) + assert sum("not identified by the observed rows" in t for t in texts) == 1 + assert _nan_cells(silent) == _nan_cells(warned) != set() + + def test_resampling_drops_draws_that_lose_the_reference(self): + # Cohort 5's reference cell is held by ONE unit: a draw without that + # unit cannot normalize the cohort. Such draws must be dropped, not + # entered into the distribution under an arbitrary baseline (which + # gives SEs of 0.5-0.8 on this nearly noiseless panel). + d = _ident_panel(noise=1e-6) + keeper = d.loc[d["g"] == 5, "unit"].min() + data = d[~((d["g"] == 5) & (d["time"] < 5) & (d["unit"] != keeper))] + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + res = SunAbraham(n_bootstrap=199, seed=7).fit(data, **_ID_KW) + assert any("non-finite bootstrap samples" in str(w.message) for w in caught) + assert np.isfinite(res.se) + for e, v in res.event_study_effects.items(): + assert np.isfinite(v["se"]) and v["se"] < 1e-4, (e, v["se"]) + + def test_resampling_never_substitutes_the_original_estimate(self): + # `rank_deficient_action` governs the FULL-SAMPLE fit. A draw that + # cannot identify a cell must come back NaN and be dropped under every + # setting; raising inside the draw would hand it to the bootstrap's + # exception fallback, which substitutes the original estimate and + # shrinks the SE (0.0751 instead of 0.0959 on this panel). + d = _ident_panel(noise=0.5) + keeper = d.loc[d["g"] == 5, "unit"].min() + data = d[~((d["g"] == 5) & (d["time"] < 5) & (d["unit"] != keeper))] + ses = {} + for action in ("warn", "silent", "error"): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + res = SunAbraham(n_bootstrap=199, seed=7, rank_deficient_action=action).fit( + data, **_ID_KW + ) + texts = [str(w.message) for w in caught] + assert not any("Using original estimate" in t for t in texts), action + assert any("non-finite bootstrap samples" in t for t in texts), action + ses[action] = (res.se, tuple(v["se"] for v in res.event_study_effects.values())) + assert ses["warn"] == ses["silent"] == ses["error"] + assert np.isfinite(ses["warn"][0]) and ses["warn"][0] > 0 + + @pytest.mark.parametrize("vcov_type", ["hc1", "hc2_bm"]) + def test_every_cell_unidentified_reports_nan(self, vcov_type): + # One treated cohort (g = 2) and never-treated units observed only at + # t = 1: the single cell (2, 0) has no comparison row, so no design + # column is left. That is reported, not raised as "no interactions". + data = pd.DataFrame( + { + "unit": [0, 1, 1, 2, 2], + "time": [1, 1, 2, 1, 2], + "g": [0, 2, 2, 2, 2], + "y": [0.0, 0.5, 3.0, 0.2, 2.9], + } + ) + res, texts = _fit_id(data, est={"vcov_type": vcov_type}) + assert sum("not identified by the observed rows" in t and "(2, 0)" in t for t in texts) == 1 + assert _nan_cells(res) == {(2, 0)} + assert np.isnan(res.cohort_effects[(2, 0)]["se"]) + row = res.event_study_effects[0] + assert np.isnan(row["effect"]) and np.isnan(row["se"]) and np.isnan(row["p_value"]) + assert np.isnan(res.att) and np.isnan(res.se) and np.isnan(res.p_value) + assert np.all(np.isnan(res.event_study_vcov)) + silent, texts = _fit_id( + data, est={"vcov_type": vcov_type, "rank_deficient_action": "silent"} + ) + assert not any("not identified" in t for t in texts) and np.isnan(silent.att) + # every inference field is undefined together, under both settings + from tests.conftest import assert_nan_inference + + for fitted in (res, silent): + assert_nan_inference(fitted.event_study_effects[0]) + assert_nan_inference( + { + "se": fitted.se, + "t_stat": fitted.t_stat, + "p_value": fitted.p_value, + "conf_int": fitted.conf_int, + } + ) + with pytest.raises(ValueError, match="rank-deficient.*\\(2, 0\\)"): + SunAbraham(vcov_type=vcov_type, rank_deficient_action="error").fit(data, **_ID_KW) + + def test_event_study_covariance_keeps_the_identified_block(self): + from diff_diff import compute_pretrends_power + + data = _nt_absent_panel(noise=0.5, period=1) # flags (3, -2) and (5, -4) + res, _ = _fit_id(data) + nan_rows = {e for e, v in res.event_study_effects.items() if np.isnan(v["effect"])} + assert nan_rows == {-4, -2} + index = list(res.event_study_vcov_index) + bad = [index.index(e) for e in sorted(nan_rows)] + good = [i for i in range(len(index)) if i not in bad] + vcov = res.event_study_vcov + assert np.all(np.isnan(vcov[bad, :])) and np.all(np.isnan(vcov[:, bad])) + block = vcov[np.ix_(good, good)] + assert np.all(np.isfinite(block)) + ses = np.array([res.event_study_effects[index[i]]["se"] for i in good]) + np.testing.assert_allclose(np.sqrt(np.diag(block)), ses, rtol=1e-10) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + pp = compute_pretrends_power(res, pre_periods=[-3]) + assert pp.covariance_source == "full_pre_period_vcov" + assert np.isfinite(pp.mdv) + + def test_undefined_variance_is_not_reported_as_zero(self): + # Full rank, zero residual df: the covariance is undefined (NaN) with + # no unidentified cell, and must stay NaN in the event-study block. + data = pd.DataFrame( + { + "unit": [0, 0, 1, 1], + "time": [1, 2, 1, 2], + "g": [0, 0, 2, 2], + "y": [0.0, 1.0, 0.5, 3.0], + } + ) + res, _ = _fit_id(data, est={"cluster": False}) + assert res.att == pytest.approx(1.5) + assert np.all(np.isnan(res.event_study_vcov)) + + +class TestStructuralIdentificationHelper: + """`_structural_identification` against the null space of the design.""" + + @staticmethod + def _call(data, refs, weights=None): + from diff_diff.sun_abraham import _structural_identification + + rel = sorted({e for g, e in zip(data["g"], data["time"] - data["g"]) if g > 0} - {-1}) + return _structural_identification( + data["unit"].values, data["time"].values, data["g"].values, rel, refs, -1, weights + ) + + def test_identified_design(self): + assert self._call(_ident_panel(), {3: -1, 5: -1}) == ([], []) + assert self._call(_gap_panel(), {3: -1, 5: -2}) == ([], []) + + @pytest.mark.parametrize("builder", [_nt_absent_panel, _split_cohort_panel]) + def test_unidentified_cells_and_minimal_omission(self, builder): + data = builder() + refs = _oracle_refs(data) + omit, unidentified = self._call(data, refs) + expected, cells = _oracle_unidentified(data, refs) + assert {(int(g), int(e)) for g, e in unidentified} == expected + assert len(omit) == 1 and set(omit) <= set(unidentified) + # leaving `omit` out makes the cell block full rank given the fixed effects + d = data.reset_index(drop=True) + rel = d["time"] - d["g"] + kept = [c for c in cells if c not in {(int(g), int(e)) for g, e in omit}] + fe = np.column_stack( + [ + pd.get_dummies(d["unit"], dtype=float).values, + pd.get_dummies(d["time"], dtype=float).values, + ] + ) + X = np.column_stack( + [((d["g"] == g) & (rel == e)).astype(float).values for g, e in kept] + [fe] + ) + assert np.linalg.matrix_rank(X) == np.linalg.matrix_rank(fe) + len(kept) + + def test_zero_weight_rows_are_not_observed(self): + data = _ident_panel() + weights = np.where(data["g"] == 0, np.where(data["time"] == 4, 0.0, 1.0), 1.0) + dropped = data[weights > 0] + refs = {3: -1, 5: -1} + assert self._call(data, refs, weights) == self._call(dropped, refs) + assert self._call(data, refs, weights)[1] != [] + + def test_matches_the_null_space_on_random_panels(self): + n_flagged = 0 + for seed in range(200): + rng = np.random.default_rng(seed) + cohorts = [(0, 3, 5), (0, 2, 4, 6), (0, 5)][seed % 3] + base = _ident_panel(n_units=60, cohorts=cohorts) + data = base[rng.random(len(base)) > rng.choice([0.2, 0.5, 0.8, 0.9, 0.95])] + refs = _oracle_refs(data) + data = data[~data["g"].isin([g for g, r in refs.items() if r is None])] + refs = {g: r for g, r in refs.items() if r is not None} + if not refs or not (data["g"] == 0).any(): + continue + _, unidentified = self._call(data, refs) + expected, _ = _oracle_unidentified(data, refs) + assert {(int(g), int(e)) for g, e in unidentified} == expected, seed + n_flagged += bool(expected) + assert n_flagged >= 40 + + +class TestSunAbrahamIdentificationSurvey: + """Survey designs: refusal, zero weights, replicate weights.""" + + @staticmethod + def _with_design(data): + data = data.copy() + data["w"] = 1.0 + (data["unit"] % 5) * 0.2 + data["stratum"] = data["unit"] % 4 + return data + + @staticmethod + def _add_replicates(data, n_rep=12, seed=3): + rng = np.random.default_rng(seed) + data = data.copy() + cols = [] + for j in range(n_rep): + jitter = {u: rng.uniform(0.5, 1.5) for u in data["unit"].unique()} + data[f"rw{j}"] = data["unit"].map(jitter) * data["w"] + cols.append(f"rw{j}") + return data, cols + + def test_cohort_without_a_pre_period_is_refused(self): + from diff_diff.survey import SurveyDesign + + d = self._with_design(_ident_panel(noise=0.5)) + data = d[~((d["g"] == 3) & (d["time"] < 3))] + with pytest.raises(NotImplementedError, match="Cohort\\(s\\) 3 .*domain estimation"): + SunAbraham().fit(data, survey_design=SurveyDesign(weights="w"), **_ID_KW) + + def test_zero_weight_pre_periods_count_as_unobserved(self): + from diff_diff.survey import SurveyDesign + + # Cohort 3's units observed before treatment all have weight 0; the + # positive-weight units of the cohort are observed from e = 0 only. + d = self._with_design(_ident_panel(noise=0.5)) + late = (d["g"] == 3) & (d["unit"] % 2 == 0) + data = d[~(late & (d["time"] < 3))].copy() + data.loc[(data["g"] == 3) & (data["unit"] % 2 == 1), "w"] = 0.0 + with pytest.raises(NotImplementedError, match="Cohort\\(s\\) 3 "): + SunAbraham().fit(data, survey_design=SurveyDesign(weights="w"), **_ID_KW) + + def test_fallback_reference_under_tsl_and_replicate_designs(self): + from diff_diff.survey import SurveyDesign + + data = self._with_design(_gap_panel(noise=0.5)) + tsl, texts = _fit_id( + data, survey_design=SurveyDesign(weights="w", strata="stratum", psu="unit") + ) + assert any("cohort 5: -2" in t for t in texts) + assert np.isfinite(tsl.se) and tsl.se > 0 + data, cols = self._add_replicates(data) + rep, _ = _fit_id( + data, + survey_design=SurveyDesign(weights="w", replicate_weights=cols, replicate_method="JK1"), + ) + np.testing.assert_allclose(rep.att, tsl.att, rtol=1e-10) + assert np.isfinite(rep.se) and rep.se > 0 + assert all(np.isfinite(v["se"]) and v["se"] > 0 for v in rep.event_study_effects.values()) + + def test_single_cohort_fallback_under_replicate_weights(self): + from diff_diff.survey import SurveyDesign + + # The reference period (-2) holds no estimated cell: it must not sit in + # the replicate vector as a structural NaN. + d = self._with_design(_ident_panel(noise=0.5, n_units=60, cohorts=(0, 5))) + data, cols = self._add_replicates(d[~((d["g"] == 5) & (d["time"] == 4))]) + res, _ = _fit_id( + data, + survey_design=SurveyDesign(weights="w", replicate_weights=cols, replicate_method="JK1"), + ) + assert -2 not in res.event_study_effects + assert np.isfinite(res.se) and res.se > 0 + assert all(np.isfinite(v["se"]) and v["se"] > 0 for v in res.event_study_effects.values()) + + def test_zero_weight_cohort_does_not_poison_pooled_rows(self): + from diff_diff.survey import SurveyDesign + + d = self._with_design(_ident_panel(noise=0.5)) + zeroed = d.copy() + zeroed.loc[zeroed["g"] == 5, "w"] = 0.0 + res, _ = _fit_id(zeroed, survey_design=SurveyDesign(weights="w")) + ref, _ = _fit_id(d[d["g"] != 5], survey_design=SurveyDesign(weights="w")) + np.testing.assert_allclose(res.att, ref.att, rtol=1e-10) + assert set(res.event_study_effects) == set(ref.event_study_effects) + for e, v in res.event_study_effects.items(): + np.testing.assert_allclose(v["effect"], ref.event_study_effects[e]["effect"], rtol=1e-9) + # SEs are not compared: the zero-weight units stay in the design. + assert np.isfinite(v["se"]) and v["se"] > 0 + assert all(g == 3 for g, _ in res.cohort_effects) + + def test_zero_weight_cell_beside_an_observed_cohort(self): + from diff_diff.survey import SurveyDesign + + # The only cohort-5 units observed at t = 8 (e = 3) are zero-weight + # units; cohort 3 is observed there (e = 5 for cohort 3, so e = 3 is + # pooled from cohort 3's t = 6 cell alone). + d = self._with_design(_ident_panel(noise=0.5)) + odd5 = (d["g"] == 5) & (d["unit"] % 2 == 1) + data = d[~((d["g"] == 5) & ~odd5 & (d["time"] == 8))].copy() + data.loc[(data["g"] == 5) & (data["unit"] % 2 == 1), "w"] = 0.0 + res, _ = _fit_id(data, survey_design=SurveyDesign(weights="w")) + assert (5, 3) not in res.cohort_effects + row = res.event_study_effects[3] + assert np.isfinite(row["effect"]) and np.isfinite(row["se"]) + np.testing.assert_allclose(row["effect"], res.cohort_effects[(3, 3)]["effect"], rtol=1e-12) + assert np.isfinite(res.att) + + def test_guard_under_replicate_weights_keeps_identified_inference(self): + from diff_diff.survey import SurveyDesign + + d = self._with_design(_nt_absent_panel(noise=0.5, period=1)) + data, cols = self._add_replicates(d) + res, _ = _fit_id( + data, + survey_design=SurveyDesign(weights="w", replicate_weights=cols, replicate_method="JK1"), + ) + assert _nan_cells(res) == {(3, -2), (5, -4)} + for e, v in res.event_study_effects.items(): + if e in (-4, -2): + assert np.isnan(v["effect"]) and np.isnan(v["se"]) + else: + assert np.isfinite(v["se"]) and v["se"] > 0, e + assert np.isfinite(res.att) and np.isfinite(res.se) and res.se > 0 + for k, v in res.cohort_effects.items(): + assert np.isfinite(v["se"]) == np.isfinite(v["effect"]) + + +class TestSunAbrahamBootstrapRowPositions: + """Both bootstrap paths index rows by POSITION, whatever the frame's index.""" + + def _relabelled(self, data): + shifted = data.copy() + shifted.index = shifted.index + 1000 + reversed_ = data.copy() + reversed_.index = np.arange(len(data))[::-1].copy() + return shifted, reversed_ + + def test_pairs_bootstrap_ignores_index_labels(self): + data = _ident_panel(noise=0.5) + base, _ = _fit_id(data, est={"n_bootstrap": 40, "seed": 3}) + for other in self._relabelled(data): + res, _ = _fit_id(other, est={"n_bootstrap": 40, "seed": 3}) + assert res.se == base.se + for e, v in res.event_study_effects.items(): + assert v["se"] == base.event_study_effects[e]["se"] + + def test_rao_wu_bootstrap_ignores_index_labels(self): + from diff_diff.survey import SurveyDesign + + data = _ident_panel(noise=0.5) + data["w"] = 1.0 + (data["unit"] % 5) * 0.2 + data["stratum"] = data["unit"] % 4 + sd = SurveyDesign(weights="w", strata="stratum", psu="unit") + base, _ = _fit_id(data, est={"n_bootstrap": 40, "seed": 3}, survey_design=sd) + for other in self._relabelled(data): + res, _ = _fit_id(other, est={"n_bootstrap": 40, "seed": 3}, survey_design=sd) + assert res.se == base.se + + def test_bootstrap_with_a_filtered_out_unit(self): + # A unit with a negative first_treat is neither treated nor a control; + # under the default control group its rows are filtered out, leaving a + # frame whose index is no longer 0..n-1. + data = _ident_panel(noise=0.5) + data.loc[data["unit"] == 4, "g"] = -1 + res, _ = _fit_id(data, est={"n_bootstrap": 40, "seed": 3}) + assert np.isfinite(res.se) and res.se > 0 diff --git a/tests/test_v4_cluster_policy.py b/tests/test_v4_cluster_policy.py index b3df0f7b..60dc99a7 100644 --- a/tests/test_v4_cluster_policy.py +++ b/tests/test_v4_cluster_policy.py @@ -879,7 +879,9 @@ def test_sun_abraham_results_field_is_appended_last(self): from diff_diff.sun_abraham import SunAbrahamResults names = [f.name for f in dataclasses.fields(SunAbrahamResults)] - assert names[-1] == "n_clusters" and names[-2] == "inference_df" + # Fields are only ever APPENDED (the positional layout of the earlier + # ones never moves): n_clusters at 4.0, then reference_event_times. + assert names[-3:] == ["inference_df", "n_clusters", "reference_event_times"] # --------------------------------------------------------------------------- #