From b651eb03d060b5ed4b4f4d7dd2b48b3d6f95e7b8 Mon Sep 17 00:00:00 2001 From: igerber Date: Sun, 22 Nov 2026 11:47:14 -0500 Subject: [PATCH] fix(survey): per-cell ATT(g,t) SEs honor replicate and PSU designs (CallawaySantAnna, staggered TripleDifference) Per-cell SEs ignored the survey design in three lanes while the aggregate SEs on the same fit were design-based: CallawaySantAnna under replicate weights, and staggered TripleDifference under replicate weights and under SurveyDesign(psu=...). One dispatch helper (staggered._design_se_for_cell) now routes every CS-family per-cell producer: replicate designs use IF reweighting with a cell-local df min(df_survey, n_valid - 1) (survey.cap_replicate_df), PSU designs use CR1 on the cell IF. Degenerate cells and non-finite influence functions fail closed to NaN. Measured on one-cell panels (cell == overall ATT): CS + JK1 cell SE 0.156789 -> 0.342755; staggered DDD 0.217289 -> 0.325258 under both JK1 and psu=. Point estimates and aggregate results are unchanged. --- TODO.md | 4 +- changelog.d/20261122-per-cell-design-se.md | 29 + diff_diff/_staggered_triple_diff_engine.py | 46 +- diff_diff/dml_did.py | 2 +- diff_diff/staggered.py | 358 ++++++---- diff_diff/survey.py | 27 +- docs/choosing_estimator.rst | 4 +- docs/methodology/REGISTRY.md | 64 +- tests/test_per_cell_design_se.py | 791 +++++++++++++++++++++ tests/test_survey_dml.py | 2 +- 10 files changed, 1162 insertions(+), 165 deletions(-) create mode 100644 changelog.d/20261122-per-cell-design-se.md create mode 100644 tests/test_per_cell_design_se.py diff --git a/TODO.md b/TODO.md index c493c87e6..618997ca1 100644 --- a/TODO.md +++ b/TODO.md @@ -29,14 +29,14 @@ Related tracking surfaces: | Expose cell-mass overall ATT (Stata `Post_avg` convention; = CS-simple on balanced panels) as an aggregate extra on LWDiD results — the fit's `.att` is the paper's `tau_omega` (cohort-mean-then-treated-weight, eq. 7.18); the authors' large-N display uses cell-mass weighting instead, and both are legitimate estimands (see the REGISTRY LWDiD Aggregation note). Lands only after PR #588 merges | `diff_diff/lwdid_results.py` | #588 | Quick | Low | | Staggered-DDD power support: `simulate_power`/`simulate_mde`/`simulate_sample_size` now REJECT a staggered-configured `TripleDifference` (both registered DDD generators emit 2x2x2 data and fit with `(group, partition, post)`, so a staggered config would be simulated under the wrong design). Support needs a staggered DDD DGP profile plus fit-kwargs builder, and a decision on whether the mode is selected by profile or by the estimator's own config | `diff_diff/power.py` | 3(b) | Mid | Low | | Bootstrap-`seed` provenance on multiplier-bootstrap results containers: neither `TripleDifferenceResults` (staggered design) nor `CallawaySantAnnaResults` carries the `seed` that generated its bootstrap SEs / p-values / sup-t bands, so a serialized result cannot report the random configuration behind its inference. NOT a 3(b) regression - `seed` reaches the engine and `get_params()` correctly (same seed reproduces the SE bit-exactly, a different seed moves it), the gap is results-object observability only, it predates the merge, and both containers inherit it from the shared `CallawaySantAnnaBootstrapMixin`. Add `seed` (and consider `n_bootstrap`/`bootstrap_weights`/`cband`) to BOTH containers plus `to_dict()`, with seeded and unseeded pins; the M-014 container unification (4.0, item 6) landed without it - the unified container records `n_bootstrap` / `inference_method` but not `seed` - so add it to BOTH containers in one PR. Precedent for exposing it: `ContinuousDiDResults`, `EfficientDiDResults`, `SyntheticDiDResults` already do | `diff_diff/triple_diff_results.py`, `diff_diff/staggered_results.py` | 3(b) | Quick | Low | -| Staggered-mode cluster-robust ANALYTICAL SEs: `cluster=` raises in `TripleDifference`'s staggered mode, so clustered inference there is bootstrap-only. Implementing a clustered analytical path for the GMM-combined influence function would let the raise become a real lane | `diff_diff/_staggered_triple_diff_engine.py` | 3(b) | Heavy | Low | +| Bare `cluster=` in `TripleDifference`'s staggered mode: `cluster=` raises there. A PSU declared through `survey_design=SurveyDesign(psu=...)` already gets design-based analytical SEs - aggregates via `compute_survey_if_variance()` and, since the per-cell design-SE fix, per-(g,t) CR1 on the GMM-combined influence function - so what remains is wiring bare `cluster=` onto that lane the way CallawaySantAnna does (synthesize `SurveyDesign(psu=cluster)`, reject `cluster=` + replicate weights, populate `cluster_name` / `n_clusters` / `df_inference`, PSU-level multiplier bootstrap), then lifting the raise and its tests | `diff_diff/triple_diff.py`, `diff_diff/_staggered_triple_diff_engine.py` | 3(b) | Mid | Low | | diagnostic_report admission for `EventStudyResults` surfaces (the TWFE event-study mode + `aggregate('event_study')` containers): DiagnosticReport/BusinessReport now REJECT the surface explicitly (Phase 3(a); previously a silent zero-check report / all-null headline) and practitioner_next_steps serves the generic fall-through - admission needs source-aware routing (the type-name-keyed `_APPLICABILITY`/`_HANDLERS` registries cannot discriminate the unified container's producers) and a scalar-vs-per-period headline design; MPD-native results received {parallel_trends, pretrends_power, sensitivity, bacon, design_effect}. PR 4c-ii (2026-10-25) DELETED the MPD-native branches that logic lived in (DiagnosticReport's `interaction_indices`+`vcov` joint-Wald covariance source, the `post_period_effects` heterogeneity source, the `pre_period_effects` Bonferroni/NaN-filter collector branch, the `avg_att` alias row, practitioner's `_handle_multi_period`) - recover them from git history (`git show 5a10b847^:diff_diff/diagnostic_report.py`) when admission lands; event-study results reach `_handle_generic` meanwhile | `diff_diff/diagnostic_report.py`, `diff_diff/business_report.py`, `diff_diff/practitioner.py` | 3(a) | Mid | Medium | | DiagnosticReport public skip bookkeeping omits RUNNER-level skips: `applicable_checks` reflects only gate outcomes, so a check whose runner returns `status="skipped"` (heterogeneity's empty/non-finite branches, `_pt_event_study`'s empty-coefs branch - a pre-existing pattern, now also reachable via a failed post-fit event-study derivation on bootstrapped / kit-less ImputationDiD/TwoStageDiD/ContinuousDiD fits) stays listed as applicable while `skipped_checks`/`schema["skipped"]` omit it, so automation reading the public fields can misclassify the check as completed; reconcile runner-returned skipped sections into the public bookkeeping (all checks, one convention) or resolve those availabilities at the gate | `diff_diff/diagnostic_report.py` | derived-ES review | Mid | Low | | Align the two pretrends container routes' `pre_periods=` contracts (the native MPD branch died in PR 4c-ii, so only the relative and calendar routes remain): the relative route silently collapses DUPLICATE requested labels (the calendar route rejects them, 3(a) R8), and it filters on SE only while the calendar route additionally requires a finite EFFECT (3(a) R9); one contract across both routes, with pinned rejection messages | `diff_diff/pretrends.py` | 3(a) R8 | Quick | Low | | `EventStudyResults` inference-provenance fields: the container records no `vcov_type`/`cluster_name`/`n_clusters`/`df_convention`/Conley metadata, so a serialized surface cannot distinguish unit auto-clustering from explicit clustering, survey, Conley, or the one-way carve-out (3(a) R9 review). Adding them is a cross-producer M-092 schema amendment (six builders, to_dict/summary rendering, surface-suite pins) - follow the pre-cut amendment convention (optional fields appended last, ledger note same-diff) rather than bolting onto one producer | `diff_diff/results_base.py` | 3(a) R9 | Mid | Low | | Opt-in singleton-group pruning for TwoWayFixedEffects (static + event-study mode; reghdfe parity): singleton units/periods are currently RETAINED class-wide - the within-demeaned row is zero so points are unchanged, but N/G/residual-df count it and CR1/finite-sample SEs shift (~0.41019 -> 0.40962 measured; REGISTRY "Deviation from R" Note, R5 review) - reghdfe iteratively drops singletons by default while fixest retains them (diff-diff matches fixest); an opt-in knob needs iterative unit+period pruning with consistent cluster/survey/replicate/Conley array subsetting and a default-flip decision protocol (moves published SEs) | `diff_diff/twfe.py`, `diff_diff/estimators.py`, `diff_diff/utils.py` | 3(a) R5 | Mid | Low | | Cohort-timing validation input for the simultaneous-adoption event-study family (TWFE `event_study=True`; MultiPeriodDiD through 3.9): an optional `first_treat=`/`cohort=` column so simultaneous adoption becomes checkable under the contract-valid time-invariant `D_i` indicator - today the staggered-adoption advisory derives timing from within-unit 0->1 transitions, so it can only fire on off-contract time-varying `D_it` input, and with valid `D_i` adoption timing is not observable in the inputs at all (REGISTRY "staggered-adoption detection limit" Notes, both sections); design questions: validate-only vs steering error (the M-011 removal shipped in PR 4c-ii, so only the TWFE surface is in play) | `diff_diff/twfe.py`, `diff_diff/estimators.py` | 3(a) R2 | Mid | Medium | -| CS parity with DMLDiD's replicate conventions: per-cell replicate SEs for `CallawaySantAnna` (CS leaves per-cell SEs on the weighted sqrt-sum under replicate designs; DMLDiD now computes them via `compute_replicate_if_variance`) AND flip the replace-style effective-df relays to min-cap (`min(df_survey, n_valid - 1)`) at all five sites: CS overall (`staggered.py` overall relay), the shared event-study/group aggregation sites (`staggered_aggregation.py` `df_survey_val = min(non_none_dfs)` x2), and the staggered-DDD engine twins (`_staggered_triple_diff_engine.py` overall + event-study) — the replace convention can RAISE df above the QR-rank design df (anti-conservative); latent, fires only when `n_valid < R` (all-zero/non-finite replicate column). DMLDiD's min-cap + the pinned inherited ES/group behavior are the templates (REGISTRY DMLDiD replicate Note) | `diff_diff/staggered.py`, `diff_diff/staggered_aggregation.py`, `diff_diff/_staggered_triple_diff_engine.py` | DML replicate PR | Mid | Low | +| Replicate effective-df min-cap, library-wide: when a replicate is dropped (`n_valid < R`) the design df is REPLACED by `n_valid - 1` instead of capped at `min(df_survey, n_valid - 1)`, which can RAISE df above the QR-rank design df (anti-conservative; latent - it needs a dropped replicate AND a rank-deficient replicate matrix) and turns an undefined design df (`df_survey=None`, QR rank <= 1) into t-inference at `n_valid - 1`. Replace-style sites: the shared CS-family source `staggered_aggregation.py::_se_from_psi` (feeding the CS overall relay in `staggered.py`, the event-study/group `min(non_none_dfs)` relays, the staggered-DDD overall relay in `_staggered_triple_diff_engine.py`, and the Eq. 4.14 relay in `triple_diff_results.py::_event_time_overall_result`), `efficient_did_aggregation.py`, `continuous_did.py`, `triple_diff.py` (2x2x2), `estimators.py` (x2), `twfe.py`, `sun_abraham.py`, `stacked_did.py` (x2), `imputation_aggregation.py`, `two_stage_aggregation.py`, and `linalg.py` (`LinearRegression._replicate_df`). Roll `survey.cap_replicate_df` (shipped with the per-cell design-SE fix; CS and staggered-DDD per-cell dfs already use it) through all of them, fixing `_se_from_psi` at the source; consolidate DMLDiD's inline rule and reconcile dCDH's `_effective_df_survey` (its docstring wrongly cites EfficientDiD and 2x2x2 TripleDifference as reduce-not-replace precedents); flip `tests/test_survey_dml.py::test_es_df_pins_inherited_replace_convention`; and update the REGISTRY Survey Data Support Notes that state the replace rule ("Survey df uses `n_valid - 1`", "df propagation is not needed") | `diff_diff/survey.py`, `diff_diff/staggered_aggregation.py` | DML replicate PR | Mid | Low | | `balance_e` replay on bootstrapped ImputationDiD/TwoStageDiD fits: the unrestricted ES/group surface is relayed since 4.0 PR 3c (computed at fit, `balance_e=None`; M-021/M-022), but `aggregate('event_study', balance_e=k)` still raises there - a balanced-window replay needs retained per-target psi (ImputationDiD: the panel-backed kit retains everything the psi precompute reads, so a seeded replay is tractable) / retained per-level GMM scores (TwoStageDiD: function-locals today) | `diff_diff/imputation_results.py`, `diff_diff/two_stage_results.py`, `diff_diff/aggregation.py` | 2(b) PR-3b | Mid | Low | | ContinuousDiD post-fit bootstrap-ES REPLAY: since 4.0 PR 3c a bootstrapped fit relays the event-study surface computed at fit (M-025), so the gap is a genuine post-fit replay (fresh draws, no fit-side cost, a route for pre-4.0 pickles); a seeded replay is tractable - the multiplier draws are seeded (`np.random.default_rng(self.seed)`) - but needs the FULL per-cell `_bootstrap_info` (bread/ee_treated/Psi_eval/dPsi_*/beta_pred) the pruned kit deliberately drops, so shipping it means a kit-payload change with its own memory contract | `diff_diff/continuous_did_aggregation.py`, `diff_diff/continuous_did_results.py` | 2(b) PR-3c | Mid | Low | | practitioner `step_name="heterogeneity"` producer-side collisions: three OTHER estimators' advice steps reuse the key with non-heterogeneity labels (`:975` ContinuousDiD dose-response, `:1022` Triple placebo-group, `:1413` LPDiD WAS arrays), so DiagnosticReport's heterogeneity completion silently drops that unrelated advice from `next_steps` via `_filter_steps` - the same latent collision fixed for StackedDiD in M-024 (renamed to `sub_experiment_balance`). Renaming these changes those estimators' report output; audit + rename with per-estimator pins. | `diff_diff/practitioner.py` | 2(b) PR-2 review R9 | Quick | Low | diff --git a/changelog.d/20261122-per-cell-design-se.md b/changelog.d/20261122-per-cell-design-se.md new file mode 100644 index 000000000..71d4d565c --- /dev/null +++ b/changelog.d/20261122-per-cell-design-se.md @@ -0,0 +1,29 @@ +### Fixed +- **Per-cell ATT(g,t) standard errors now honor replicate-weight and PSU survey + designs** (`CallawaySantAnna`, staggered `TripleDifference`). The aggregate SEs + (overall, event study, group) of these fits were already design-based, but the + per-cell `group_time_effects` SE, t-statistic, p-value and confidence interval + were silently those of a weights-only fit in three lanes: + - `CallawaySantAnna` with `SurveyDesign(replicate_weights=...)`; + - staggered `TripleDifference` with `SurveyDesign(replicate_weights=...)`; + - staggered `TripleDifference` with `SurveyDesign(psu=...)`. + + On a one-cell panel, where the cell is the overall ATT, the cell SE now equals + the overall SE: 0.3428 instead of 0.1568 for `CallawaySantAnna` under JK1 + replicates (cell p-value 0.016 instead of 4.9e-06), and 0.3253 instead of 0.2173 + for staggered `TripleDifference` under both JK1 replicates and a PSU design. + Per-cell SEs under those designs will generally be larger than before; point + estimates and all aggregate results are unchanged, as are fits with no survey + design or a weights-only, strata-only or FPC-only design. + - Replicate designs use IF reweighting on the cell's influence function with a + cell-local df `min(df_survey, n_valid - 1)` (new helper + `diff_diff.survey.cap_replicate_df`); PSU designs use CR1 on the PSU totals of + the cell's influence function. For staggered `TripleDifference` both are + applied to the GMM-combined influence function the aggregates consume. + - Fail-closed: a cell whose replicate variance is zero, negative or non-finite, + or whose influence function carries a non-finite value, reports a NaN SE with + NaN inference. The non-finite guard also applies to the existing + `CallawaySantAnna` and `DMLDiD` PSU per-cell lane, which could otherwise report + a finite clustered SE for a partly-NaN influence function. + - See the REGISTRY CallawaySantAnna and StaggeredTripleDifference per-cell + survey Notes. diff --git a/diff_diff/_staggered_triple_diff_engine.py b/diff_diff/_staggered_triple_diff_engine.py index 3123ea578..6b1f8d731 100644 --- a/diff_diff/_staggered_triple_diff_engine.py +++ b/diff_diff/_staggered_triple_diff_engine.py @@ -36,7 +36,7 @@ class said "eligibility") _rank_guarded_inv, solve_logit, ) -from diff_diff.staggered import _build_aggregation_kit +from diff_diff.staggered import _build_aggregation_kit, _design_se_for_cell from diff_diff.triple_diff_results import TripleDifferenceResults from diff_diff.utils import safe_inference, validate_anticipation @@ -463,13 +463,6 @@ def _fit_staggered_core( if len(gc_labels) == 1: se_gt = float(np.sqrt(np.sum(inf_gmm**2) / size_gt**2)) - if not np.isfinite(se_gt) or se_gt <= 0: - se_gt = np.nan - - t_stat, p_value, conf_int = safe_inference( - att_gmm, se_gt, alpha=self.alpha, df=df_survey - ) - # Rescale IF for mixin compatibility. # R stores IF * (n/size_gt) in inf_func_mat, then uses # SE = sqrt(sum(IF^2)/n^2) = sqrt(sum(psi^2)) with psi = IF/n. @@ -488,6 +481,36 @@ def _fit_staggered_core( control_idx = np.where(nonzero_mask)[0] control_inf = inf_gmm_scaled[control_idx] n_control = int(np.sum(nonzero_mask)) + inf_info_gt = { + "treated_idx": treated_idx, + "control_idx": control_idx, + "treated_inf": treated_inf, + "control_inf": control_inf, + } + + # Design-aware per-(g,t) SE - the CallawaySantAnna per-cell + # contract (staggered._design_se_for_cell). Under a + # replicate or PSU design the cell SE comes from the + # GMM-combined IF (the psi the aggregates consume) through + # the design variance: replicate IF variance with a + # cell-local df, or CR1 on the PSU totals (NaN = clustered + # variance unidentified, propagated). Every other fit + # keeps `se_gt` bit-identically - R's GMM formula for + # multi-comparison-group cells, sqrt(sum(IF^2))/size_gt + # for single-comparison-group ones. + se_gt, cell_df = _design_se_for_cell( + inf_info_gt, + precomputed.get("resolved_survey_unit"), + se_gt, + df_survey, + ) + + if not np.isfinite(se_gt) or se_gt <= 0: + se_gt = np.nan + + t_stat, p_value, conf_int = safe_inference( + att_gmm, se_gt, alpha=self.alpha, df=cell_df + ) group_time_effects[(g, t)] = { "effect": att_gmm, @@ -498,12 +521,7 @@ def _fit_staggered_core( "n_treated": n_treated, "n_control": n_control, } - influence_func_info[(g, t)] = { - "treated_idx": treated_idx, - "control_idx": control_idx, - "treated_inf": treated_inf, - "control_inf": control_inf, - } + influence_func_info[(g, t)] = inf_info_gt comparison_group_counts[(g, t)] = len(gc_labels) gmm_weights_store[(g, t)] = dict(zip(gc_labels, gmm_w.tolist())) diff --git a/diff_diff/dml_did.py b/diff_diff/dml_did.py index 291faf784..178e7fee8 100644 --- a/diff_diff/dml_did.py +++ b/diff_diff/dml_did.py @@ -3193,7 +3193,7 @@ def fit( # dropped replicates (n_valid < R). MIN-CAP, not CS's replace: the # QR-rank design df stays the ceiling (CS's replace convention can # RAISE df above the design df — anti-conservative; deliberate - # documented divergence, REGISTRY DMLDiD Note + CS-parity TODO row). + # documented divergence, REGISTRY DMLDiD Note + replicate-df min-cap TODO row). overall_att, overall_se, overall_effective_df = self._aggregate_simple( group_time_effects, influence_func_info, df, unit, precomputed ) diff --git a/diff_diff/staggered.py b/diff_diff/staggered.py index 41d19a392..135e2e754 100644 --- a/diff_diff/staggered.py +++ b/diff_diff/staggered.py @@ -110,6 +110,170 @@ def _linear_regression( return beta, residuals +def _scatter_per_gt_if(inf_info: Optional[Dict[str, Any]], n: int) -> Optional[np.ndarray]: + """Scatter a per-(g,t) influence payload into a length-``n`` vector. + + Returns ``None`` when the payload is malformed: ``inf_info`` is ``None``, + lacks one of ``treated_idx`` / ``control_idx`` / ``treated_inf`` / + ``control_inf``, or carries an index outside ``[0, n)``. ``n`` is the + length of the design's index space (units on the panel path, observations + on the RCS path). + """ + if ( + inf_info is None + or "treated_inf" not in inf_info + or "control_inf" not in inf_info + or "treated_idx" not in inf_info + or "control_idx" not in inf_info + ): + return None + treated_idx = np.asarray(inf_info["treated_idx"]) + control_idx = np.asarray(inf_info["control_idx"]) + treated_inf = np.asarray(inf_info["treated_inf"]) + control_inf = np.asarray(inf_info["control_inf"]) + if ( + treated_idx.size > 0 + and (treated_idx.max(initial=-1) >= n or treated_idx.min(initial=0) < 0) + ) or ( + control_idx.size > 0 + and (control_idx.max(initial=-1) >= n or control_idx.min(initial=0) < 0) + ): + return None + # Index arrays are unique within each cell by construction at every + # producer (np.where on disjoint masks), so fancy += is exact — same + # scatter contract as staggered_aggregation._combined_if_fast, without + # np.add.at's unbuffered-ufunc overhead (runs once per (g,t) cell under + # a PSU or replicate design). + psi_per_index = np.zeros(n) + if treated_idx.size: + psi_per_index[treated_idx] += treated_inf + if control_idx.size: + psi_per_index[control_idx] += control_inf + return psi_per_index + + +def _replicate_se_from_per_gt_if( + inf_info: Optional[Dict[str, Any]], + resolved_survey: "Any", +) -> Tuple[float, int]: + """Replicate-weight SE for a single (g,t) ATT; returns ``(se, n_valid)``. + + IF-reweighting (``compute_replicate_if_variance``) on the scattered cell + influence function - the same psi and the same variance routine the + aggregate ``_se_from_psi`` path consumes, so a cell's SE is coherent with + the overall / event-study / group SEs of the same fit. + + Fail-closed contract (no fallback to the unit-level SE - under a replicate + design that would silently report a different estimator's variance): + + * malformed payload or a non-finite influence value -> ``(NaN, 0)``; + * replicate variance non-finite or ``<= 0`` (e.g. a cell no replicate + column perturbs) -> NaN SE. This is stricter than the aggregate path, + which clamps a zero / negative variance to a ``0.0`` SE; inference is NaN + either way. + """ + psi = _scatter_per_gt_if(inf_info, len(resolved_survey.weights)) + if psi is None or not np.all(np.isfinite(psi)): + return float("nan"), 0 + from diff_diff.survey import compute_replicate_if_variance + + with np.errstate(over="ignore", invalid="ignore"): + variance, n_valid = compute_replicate_if_variance(psi, resolved_survey) + if not np.isfinite(variance) or variance <= 0.0: + return float("nan"), int(n_valid) + return float(np.sqrt(variance)), int(n_valid) + + +def _design_se_for_cell( + inf_info: Optional[Dict[str, Any]], + resolved_survey: "Any", + se_unit: float, + df: Optional[float], +) -> Tuple[float, Optional[float]]: + """Per-(g,t) SE and inference df under the fit's survey design. + + The single per-cell contract for every CS-family producer + (CallawaySantAnna's panel / RCS paths and the staggered TripleDifference + engine). ``se_unit`` is the producer's own unit-level SE and ``df`` the + fit's (sentinelled) survey df; returns the ``(se, df)`` the cell's + inference must use: + + * **replicate design** -> the replicate IF variance of the cell's + influence function, with the CELL-LOCAL df + ``cap_replicate_df(df, n_valid)`` (``min(design df, n_valid - 1)``; + never written back to the fit's survey df); + * **PSU present** (explicit or synthesized from bare ``cluster=``) -> the + CR1 helper's 3-valued contract (float = use, NaN = propagate, ``None`` = + keep ``se_unit``); df unchanged; + * **otherwise** (no design, weights-only, strata-only, FPC-only) -> + ``(se_unit, df)`` unchanged: the full design enters the aggregate SEs + only on those lanes (REGISTRY CallawaySantAnna per-cell Note). + """ + if resolved_survey is None: + return se_unit, df + if getattr(resolved_survey, "uses_replicate_variance", False): + from diff_diff.survey import cap_replicate_df + + se_rep, n_valid = _replicate_se_from_per_gt_if(inf_info, resolved_survey) + return se_rep, cap_replicate_df(df, n_valid) + if getattr(resolved_survey, "psu", None) is not None and inf_info is not None: + se_cluster = _cluster_robust_se_from_per_gt_if(inf_info, resolved_survey) + if se_cluster is not None: + return se_cluster, df + return se_unit, df + + +def _sentinelled_survey_df(precomputed: Any) -> Optional[float]: + """The fit's survey df for per-cell inference, with the replicate sentinel. + + ``precomputed["df_survey"]``, except that a replicate design whose df is + undefined (QR rank <= 1) maps to ``0`` so ``safe_inference`` returns NaN + inference instead of falling back to the normal reference. + """ + if precomputed is None: + return None + df_survey_val = precomputed.get("df_survey") + resolved = precomputed.get("resolved_survey_unit") + if ( + df_survey_val is None + and resolved is not None + and getattr(resolved, "uses_replicate_variance", False) + ): + return 0 + return df_survey_val + + +def _safe_inference_batch_by_df( + effects: np.ndarray, + ses: np.ndarray, + cell_dfs: Sequence[Optional[float]], + alpha: float, +) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """``safe_inference_batch`` with a per-cell df, grouped by distinct df. + + Cells are never pooled onto another cell's df: a degenerate cell carrying + the ``0`` sentinel cannot NaN the inference of its batch neighbours. With + finite influence functions every cell of a design carries the same df, so + this is a single ``safe_inference_batch`` call. + """ + n = len(effects) + t_stats = np.full(n, np.nan) + p_values = np.full(n, np.nan) + ci_lowers = np.full(n, np.nan) + ci_uppers = np.full(n, np.nan) + df_arr = np.array([np.nan if d is None else float(d) for d in cell_dfs], dtype=float) + none_mask = np.isnan(df_arr) + groups: List[Tuple[np.ndarray, Optional[float]]] = [] + if np.any(none_mask): + groups.append((np.where(none_mask)[0], None)) + for value in np.unique(df_arr[~none_mask]): + groups.append((np.where(df_arr == value)[0], float(value))) + for idx, df_value in groups: + t, p, lo, hi = safe_inference_batch(effects[idx], ses[idx], alpha=alpha, df=df_value) + t_stats[idx], p_values[idx], ci_lowers[idx], ci_uppers[idx] = t, p, lo, hi + return t_stats, p_values, ci_lowers, ci_uppers + + def _cluster_robust_se_from_per_gt_if( inf_info: Dict[str, Any], resolved_survey: "Any", @@ -153,41 +317,20 @@ def _cluster_robust_se_from_per_gt_if( these cases the helper cannot evaluate the contract; caller falls back to the unit-level SE returned by the underlying estimation method (no PSU is in play, so unit-level is the documented default). + * **NaN (non-finite IF)** — the scattered influence function carries a + non-finite entry. ``_compute_stratified_psu_meat`` sums per PSU with a + NaN-skipping ``groupby(...).sum()``, so without this guard a partly-NaN + cell IF would yield a FINITE clustered SE while every aggregate over the + same IF is NaN. """ - if ( - inf_info is None - or "treated_inf" not in inf_info - or "control_inf" not in inf_info - or "treated_idx" not in inf_info - or "control_idx" not in inf_info - ): - return None - treated_idx = np.asarray(inf_info["treated_idx"]) - control_idx = np.asarray(inf_info["control_idx"]) - treated_inf = np.asarray(inf_info["treated_inf"]) - control_inf = np.asarray(inf_info["control_inf"]) psu_array = getattr(resolved_survey, "psu", None) if psu_array is None: return None - n = len(psu_array) - if ( - treated_idx.size > 0 - and (treated_idx.max(initial=-1) >= n or treated_idx.min(initial=0) < 0) - ) or ( - control_idx.size > 0 - and (control_idx.max(initial=-1) >= n or control_idx.min(initial=0) < 0) - ): + psi_per_index = _scatter_per_gt_if(inf_info, len(psu_array)) + if psi_per_index is None: return None - # Index arrays are unique within each cell by construction at every - # producer (np.where on disjoint masks), so fancy += is exact — same - # scatter contract as staggered_aggregation._combined_if_fast, without - # np.add.at's unbuffered-ufunc overhead (runs once per (g,t) cell when - # cluster= is set). - psi_per_index = np.zeros(n) - if treated_idx.size: - psi_per_index[treated_idx] += treated_inf - if control_idx.size: - psi_per_index[control_idx] += control_inf + if not np.all(np.isfinite(psi_per_index)): + return float("nan") # Route through the shared survey helper so the per-cell variance # gets the same G/(G-1) finite-sample correction, PSU centering, # FPC handling, and lonely-PSU/G<2→NaN behavior as overall + @@ -1239,6 +1382,10 @@ def _compute_all_att_gt_vectorized( atts = [] ses = [] task_keys = [] + # Per-cell inference df (see _design_se_for_cell): the fit's + # sentinelled survey df, tightened cell-locally on replicate designs. + cell_dfs: List[Optional[float]] = [] + df_survey_val = _sentinelled_survey_df(precomputed) for g, t, base_col, post_col, base_period_val in tasks: treated_mask = cohort_masks[g] @@ -1363,43 +1510,28 @@ def _compute_all_att_gt_vectorized( } influence_func_info[(g, t)] = inf_info_gt - # Cluster-aware per-(g,t) SE: aggregate the per-(g,t) IF by - # PSU when a survey design (explicit OR synthesized from bare - # cluster=) provides one. Bit-equal to pre-PR when psu is None. - rsu_for_gt = precomputed.get("resolved_survey_unit") - if rsu_for_gt is not None and getattr(rsu_for_gt, "psu", None) is not None: - se_cluster = _cluster_robust_se_from_per_gt_if(inf_info_gt, rsu_for_gt) - # se_cluster is float (use), NaN (cluster-undefined, propagate), - # or None (malformed, keep unit-level). Per the helper's - # contract, NaN is a deliberate signal that the survey/PSU - # variance is unidentified (e.g., G<2, lonely-PSU removed - # all strata) — propagating NaN here causes safe_inference - # to NaN-out the full per-cell inference surface, which is - # the documented CS contract (feedback_no_silent_failures). - if se_cluster is not None: - se = se_cluster - group_time_effects[(g, t)]["se"] = se + # Design-aware per-(g,t) SE (see _design_se_for_cell): replicate + # designs -> replicate IF variance with a cell-local df; a PSU + # (explicit OR synthesized from bare cluster=) -> CR1 on the cell + # IF, where NaN is the deliberate "clustered variance + # unidentified" signal (e.g. G<2, lonely-PSU removed all strata) + # and propagates to NaN the cell's whole inference surface + # (feedback_no_silent_failures). Bit-equal to the unit-level SE + # on every other lane. + se, cell_df = _design_se_for_cell( + inf_info_gt, precomputed.get("resolved_survey_unit"), se, df_survey_val + ) + group_time_effects[(g, t)]["se"] = se atts.append(att) ses.append(se) + cell_dfs.append(cell_df) task_keys.append((g, t)) - # Batch inference for all (g,t) pairs at once + # Batch inference for all (g,t) pairs, each on its own df if task_keys: - df_survey_val = precomputed.get("df_survey") - # Guard: replicate design with undefined df → NaN inference - if ( - df_survey_val is None - and precomputed.get("resolved_survey_unit") is not None - and hasattr(precomputed["resolved_survey_unit"], "uses_replicate_variance") - and precomputed["resolved_survey_unit"].uses_replicate_variance - ): - df_survey_val = 0 - t_stats, p_values, ci_lowers, ci_uppers = safe_inference_batch( - np.array(atts), - np.array(ses), - alpha=self.alpha, - df=df_survey_val, + t_stats, p_values, ci_lowers, ci_uppers = _safe_inference_batch_by_df( + np.array(atts), np.array(ses), cell_dfs, self.alpha ) for idx, key in enumerate(task_keys): group_time_effects[key]["t_stat"] = float(t_stats[idx]) @@ -1447,6 +1579,10 @@ def _compute_all_att_gt_covariate_reg( atts = [] ses = [] task_keys = [] + # Per-cell inference df (see _design_se_for_cell): the fit's + # sentinelled survey df, tightened cell-locally on replicate designs. + cell_dfs: List[Optional[float]] = [] + df_survey_val = _sentinelled_survey_df(precomputed) n_nan_cells = 0 skipped_missing_period: List[Tuple] = [] skipped_empty_cell: List[Tuple] = [] @@ -1792,20 +1928,20 @@ def _compute_all_att_gt_covariate_reg( } influence_func_info[(g, t)] = inf_info_gt - # Cluster-aware per-(g,t) SE — see same pattern in - # _compute_all_att_gt_vectorized. - rsu_for_gt = precomputed.get("resolved_survey_unit") - if rsu_for_gt is not None and getattr(rsu_for_gt, "psu", None) is not None: - se_cluster = _cluster_robust_se_from_per_gt_if(inf_info_gt, rsu_for_gt) - # Propagate NaN (cluster-undefined) per the helper's - # contract — see _compute_all_att_gt_vectorized site - # for the same pattern. - if se_cluster is not None: - se = se_cluster - group_time_effects[(g, t)]["se"] = se + # Design-aware per-(g,t) SE — same contract as + # _compute_all_att_gt_vectorized. NOTE: this producer is + # routed only when the fit has NO survey design (fit()'s + # `not has_survey` gate; bare cluster= also resolves one), so + # today the call is a pass-through. It is kept so the per-cell + # contract holds if that routing gate is ever lifted. + se, cell_df = _design_se_for_cell( + inf_info_gt, precomputed.get("resolved_survey_unit"), se, df_survey_val + ) + group_time_effects[(g, t)]["se"] = se atts.append(att) ses.append(se) + cell_dfs.append(cell_df) task_keys.append((g, t)) if n_nan_cells > 0: @@ -1816,21 +1952,10 @@ def _compute_all_att_gt_covariate_reg( stacklevel=2, ) - # Batch inference + # Batch inference, each cell on its own df if task_keys: - # Use survey df for replicate designs (propagated from precomputed) - _ipw_dr_df = precomputed.get("df_survey") if precomputed is not None else None - # Guard: replicate design with undefined df → NaN inference - if ( - _ipw_dr_df is None - and precomputed is not None - and precomputed.get("resolved_survey_unit") is not None - and hasattr(precomputed["resolved_survey_unit"], "uses_replicate_variance") - and precomputed["resolved_survey_unit"].uses_replicate_variance - ): - _ipw_dr_df = 0 - t_stats, p_values, ci_lowers, ci_uppers = safe_inference_batch( - np.array(atts), np.array(ses), alpha=self.alpha, df=_ipw_dr_df + t_stats, p_values, ci_lowers, ci_uppers = _safe_inference_batch_by_df( + np.array(atts), np.array(ses), cell_dfs, self.alpha ) for idx, key in enumerate(task_keys): group_time_effects[key]["t_stat"] = float(t_stats[idx]) @@ -2432,31 +2557,20 @@ def fit( ), ) else: - # Cluster-aware per-(g,t) SE on the RCS path. RC - # IF indices are per-obs (vs per-unit on the panel - # path); the corresponding PSU array is - # ``resolved_survey.psu`` (length n_obs), not - # ``resolved_survey_unit.psu``. Bit-equal to pre-PR - # when psu is None. + # Design-aware per-(g,t) SE on the RCS path (see + # _design_se_for_cell). RC IF indices are per-obs + # (vs per-unit on the panel path); the matching + # design is the per-obs ``resolved_survey`` (length + # n_obs). Bit-equal to the unit-level SE when the + # design has neither a PSU nor replicate weights. rs_for_gt = precomputed.get("resolved_survey") if precomputed else None - if ( - rs_for_gt is not None - and getattr(rs_for_gt, "psu", None) is not None - and inf_info is not None - ): - se_cluster = _cluster_robust_se_from_per_gt_if(inf_info, rs_for_gt) - # Propagate NaN (cluster-undefined) per the - # helper's contract — see - # _compute_all_att_gt_vectorized for the - # pattern. - if se_cluster is not None: - se_gt = se_cluster + se_gt, cell_df = _design_se_for_cell(inf_info, rs_for_gt, se_gt, df_survey) t_stat, p_val, ci = safe_inference( att_gt, se_gt, alpha=self.alpha, - df=df_survey, + df=cell_df, ) gte_entry = { @@ -2542,31 +2656,25 @@ def fit( ), ) else: - # Cluster-aware per-(g,t) SE: when a survey PSU is - # in play (explicit OR synthesized from bare - # cluster=), aggregate the per-(g,t) IF by PSU - # and use CR1 Liang-Zeger SE instead of the - # unit-level diff-of-means SE returned by OR/IPW/DR. - # Preserves bit-equality when psu is None. - rsu_for_gt = precomputed.get("resolved_survey_unit") - if ( - rsu_for_gt is not None - and getattr(rsu_for_gt, "psu", None) is not None - and inf_info is not None - ): - se_cluster = _cluster_robust_se_from_per_gt_if(inf_info, rsu_for_gt) - # Propagate NaN (cluster-undefined) per the - # helper's contract — see - # _compute_all_att_gt_vectorized for the - # pattern. - if se_cluster is not None: - se_gt = se_cluster + # Design-aware per-(g,t) SE (see _design_se_for_cell): + # replicate designs -> replicate IF variance with a + # cell-local df; a survey PSU (explicit OR + # synthesized from bare cluster=) -> CR1 Liang-Zeger + # on the cell IF instead of the unit-level SE + # returned by OR/IPW/DR. Bit-equal to that + # unit-level SE on every other lane. + se_gt, cell_df = _design_se_for_cell( + inf_info, + precomputed.get("resolved_survey_unit"), + se_gt, + df_survey, + ) t_stat, p_val, ci = safe_inference( att_gt, se_gt, alpha=self.alpha, - df=df_survey, + df=cell_df, ) gte_entry = { diff --git a/diff_diff/survey.py b/diff_diff/survey.py index 622564b62..8889b1149 100644 --- a/diff_diff/survey.py +++ b/diff_diff/survey.py @@ -2417,8 +2417,11 @@ def compute_replicate_if_variance( Returns ------- - float - Replicate-based variance estimate. + variance : float + Replicate-based variance estimate (NaN when fewer than two replicate + estimates are finite). + n_valid : int + Number of replicate columns that produced a finite estimate. """ psi = np.asarray(psi, dtype=np.float64).ravel() rep_weights = resolved.replicate_weights @@ -2526,6 +2529,26 @@ def compute_replicate_if_variance( raise ValueError(f"Unknown replicate method: {method}") +def cap_replicate_df(base_df: Optional[float], n_valid: int) -> int: + """Inference df for one replicate-variance statistic: ``min(design df, n_valid - 1)``. + + ``base_df`` is the replicate design df (QR rank of the analysis-weight + matrix minus 1, :attr:`ResolvedSurveyDesign.df_survey`) and ``n_valid`` the + number of replicate columns that produced a finite estimate for this + statistic (second return value of :func:`compute_replicate_if_variance`). + The design df is a CEILING: a dropped replicate can only reduce it, never + replace it - on a rank-deficient replicate matrix ``n_valid - 1`` exceeds + the design df, and using it would be anti-conservative. + + Returns ``0`` - the ``safe_inference`` sentinel for NaN inference - when the + design df is undefined (``None``, QR rank <= 1), when it is already the + ``0`` sentinel, or when fewer than two replicates are valid. + """ + if base_df is None: + return 0 + return max(min(int(base_df), int(n_valid) - 1), 0) + + def compute_replicate_refit_variance( refit_fn: Callable[[np.ndarray], np.ndarray], full_sample_estimate: np.ndarray, diff --git a/docs/choosing_estimator.rst b/docs/choosing_estimator.rst index b8fce0b7d..d3356c572 100644 --- a/docs/choosing_estimator.rst +++ b/docs/choosing_estimator.rst @@ -704,8 +704,8 @@ prefer CS otherwise (fewer moving parts). Both handle declared repeated cross sections via ``panel=False``, and both carry pweight survey designs, replicate-weight designs, and ``cluster=`` there (DMLDiD's survey lane is a documented library extension of Chang's -i.i.d. theory; DMLDiD's replicate variance is per-cell AND aggregate, -exceeding CS's per-cell convention). +i.i.d. theory; both compute replicate variance per-cell AND in +aggregate). **Example**:: diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 7e4e10c51..3109e1daf 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -1362,7 +1362,7 @@ The multiplier bootstrap uses random weights w_i with E[w]=0 and Var(w)=1: - **Note (deviation from R):** Panel DR control augmentation is normalized by treated mass (`sw_t_sum` or `n_t`) rather than control IPW mass (`sum(w_cont)`). R's `DRDID::drdid_panel` uses `mean(w.cont)` as the control normalizer. Both are consistent asymptotically (under correct model specification, `E[w_cont] = E[D]` so the normalizers converge), but they differ in finite samples when IPW reweighting doesn't perfectly balance. The treated-mass normalization is simpler and matches the `did::att_gt` convention where ATT is defined per treated unit. Aligning to `DRDID::drdid_panel`'s exact `w.cont` normalization is deferred. - **Note:** PS nuisance IF corrections follow DRDID's M-estimation convention: `asy_lin_rep_psi` is computed on O(1) psi scale (matching R's `asy.lin.rep.ps = score %*% Hessian.ps`), then the correction `asy_lin_rep_psi @ M2` is converted to the library's O(1/n) phi convention via a single `/n` division. OR corrections use the same phi-scale pattern via `solve(X'WX)` (unnormalized Hessian). - **Note:** CallawaySantAnna panel reg+covariates per-cell IF (survey AND unweighted) carries `DRDID::reg_did_panel`'s full OLS estimation-effect term (v3.7). The treated IF is unchanged: `inf_treated_i = (sw_i/sum(sw_treated)) * (resid_i - ATT)` (unweighted collapse `(resid-ATT)/n_t`). The control IF is `inf_control_i = -(sw_i * wls_resid_i) * proj_i` where `proj_i = 1/sum(sw_control) + (x_i - x̄_c)' G^{-1} (x̄_t - x̄_c)` with `G` the centered (weighted) control Gram and `x̄_t`/`x̄_c` the (weighted) treated/control covariate means — algebraically identical to R's `asy.lin.rep.ols %*% M1 / mean(w.treat)` but evaluated in the centered basis, which is offset-invariant (the raw Gram squares the design's conditioning; a large constant covariate offset would otherwise push the equilibrated rank check below threshold and silently truncate a genuine direction). The intercept-only collapse is exactly `-resid_c/n_c`. HISTORY: the pre-v3.7 IF used the raw-residual plug-in (`-sw_c_norm * wls_resid_i`), documented at the time as "asymptotically valid but may be conservative" — that rationale was WRONG: the omitted term is mean-zero (WLS orthogonality), which is why point estimates always matched R at ~1e-11, but its variance contribution is first-order, leaving per-cell SEs 4-13% and aggregated SEs 3-20% from R, and ANTI-conservative on some fixtures (0.958x on the two-period golden). Per-cell parity vs R goldens is now ~5e-12 (`tests/test_csdid_ported.py`, `tests/test_methodology_callaway.py::TestDRDIDPanelIFParity`). SEs pass weight-scale-invariance tests (only weight ratios enter every term). -- **Note (deviation from R):** Per-cell ATT(g,t) SEs under survey weights use influence-function-based variance (matching R's `did::att_gt` analytical SE path) rather than full Taylor-series linearization. When strata/PSU/FPC are present, analytical aggregated SEs (`n_bootstrap=0`) use `compute_survey_if_variance()` on the combined IF/WIF; bootstrap aggregated SEs (`n_bootstrap>0`) use PSU-level multiplier weights. +- **Note (deviation from R):** Per-cell ATT(g,t) SEs under a survey design are computed from the cell's influence function (the same psi the aggregates consume), by lane (one dispatch, `staggered._design_se_for_cell`): (a) **weights-only, strata-only and FPC-only** designs use the weighted IF sqrt-sum `sqrt(sum(psi^2))` (matching R's `did::att_gt` analytical SE path rather than full Taylor-series linearization - on these lanes the full design enters the aggregated SEs only); (b) a **PSU** (explicit `SurveyDesign(psu=...)` or synthesized from bare `cluster=`) uses `compute_survey_if_variance()` on the cell IF - CR1 on the PSU totals, with strata/FPC when declared; (c) **replicate-weight** designs use `compute_replicate_if_variance()` on the cell IF, with the CELL-LOCAL inference df `min(df_survey, n_valid - 1)` (`survey.cap_replicate_df`; never written back to `survey_metadata.df_survey`; an undefined design df - QR rank <= 1 - gives NaN inference). R's `did` has no replicate-weight support, so (c) is a library extension; on a delete-one-PSU JK1 design (c) equals (b) on the same PSUs exactly (algebraic identity, pinned by `tests/test_per_cell_design_se.py`). Fail-closed rules on (b)/(c): a cell IF with a non-finite entry gives a NaN SE (the PSU variance routine sums per PSU with NaN-skipping, so without the guard it would report a finite SE); under (c) a zero, negative or non-finite replicate variance (e.g. a cell no replicate column perturbs) gives a NaN SE - stricter than the aggregate path, which clamps a zero or negative variance to a `0.0` SE (a NaN variance is NaN on both); inference is NaN either way. Before this convention (through 4.0.0) lane (c) reported the lane-(a) SE, so a replicate-design cell's SE/p-value/CI ignored the design while the aggregates on the same fit honored it. Aggregated SEs: when strata/PSU/FPC are present, analytical aggregated SEs (`n_bootstrap=0`) use `compute_survey_if_variance()` on the combined IF/WIF, and replicate designs use `compute_replicate_if_variance()` on it; bootstrap aggregated SEs (`n_bootstrap>0`) use PSU-level multiplier weights (replicate x bootstrap is rejected). - **Note:** Repeated cross-sections (`panel=False`, Phase 7b): supports surveys like BRFSS, ACS annual, and CPS monthly where units are not followed over time. Uses cross-sectional DRDID (Sant'Anna & Zhao 2020, Section 4): `reg` matches `DRDID::reg_did_rc` (Eq 2.2), `dr` matches `DRDID::drdid_rc` (locally efficient, Eq 3.3+3.4 with 4 OLS fits), `ipw` matches `DRDID::std_ipw_did_rc`. Per-observation influence functions instead of per-unit. All three estimation methods support covariates and survey weights. - **Note:** Panel and RCS influence functions use the library-wide `phi_i = psi_i / n` convention (SE = `sqrt(sum(phi^2))`, algebraically equivalent to R's `sd(psi)*sqrt(n-1)/n`). Leading IF terms are computed on psi scale and divided by n; PS nuisance corrections are computed on psi scale (`score @ solve(Hessian)`) with a single `/n` conversion to phi. @@ -3366,11 +3366,13 @@ the finite-dimensional `p_0` is handled by the variance correction below. flip, along with the inherited replace-style event-study/group aggregation sites in shared code (latent — they fire only when `n_valid < R`) and the staggered-DDD engine twins, is tracked in the - TODO.md CS-parity row. `df_survey is None` (rank ≤ 1) → NaN inference - (df=0 sentinel local to `safe_inference`; `survey_metadata.df_survey` - keeps `None`). PER-CELL replicate SEs EXCEED CS's per-cell convention - (CS leaves per-cell SEs on the weighted sqrt-sum under replicates) — - a deliberate documented divergence, same TODO row. Degenerate cells + TODO.md replicate-df min-cap row. `df_survey is None` (rank ≤ 1) → NaN + inference (df=0 sentinel local to `safe_inference`; + `survey_metadata.df_survey` keeps `None`). PER-CELL replicate SEs use + the same IF-reweighting convention as CallawaySantAnna's replicate lane + (CallawaySantAnna per-cell Note; CS's cells cap their df through + `survey.cap_replicate_df`, the same `min(df_survey, n_valid − 1)` + inference outcome as the inline rule here). Degenerate cells (zero or non-finite replicate variance, e.g. a cell no replicate column perturbs) fail closed to NaN inference PER-CELL — stricter than the shared aggregate path, which clamps negatives and can report a 0.0 @@ -4577,9 +4579,11 @@ confidence bands (sup-t) for event study. treated/control IF components, PS correction via logistic Hessian and score function, hessian = (X'WX)^{-1} * n_pair. Three-DiD IF combination weights use `w_j = n_cell / n_pair_j` (matching R's att_dr). GMM Omega estimated via - sample covariance (ddof=1). Per-(g,t) SE uses R's GMM formula + sample covariance (ddof=1). On fits WITHOUT a PSU or replicate-weight + survey design, the per-(g,t) SE uses R's GMM formula `sqrt(1 / (n * sum(Omega_inv)))` for multiple comparison groups, or - `sqrt(sum(IF^2) / n^2)` for single comparison group. + `sqrt(sum(IF^2) / n^2)` for single comparison group; under a PSU or + replicate design it is design-based (see the survey Note below). - **Deviation from R:** Propensity scores are clipped to `[pscore_trim, 1-pscore_trim]` (default 0.01). R's `triplediff` uses hard exclusion (`keep_ps`) for control units with `pscore >= 0.995` but does not apply a lower bound. The soft-clipping approach @@ -4588,14 +4592,32 @@ confidence bands (sup-t) for event study. - **Note:** On the surviving staggered surface `cluster=` raises (see the TripleDifference section); the removed class accepted it without wiring it to the analytical SE computation. The multiplier bootstrap provides unit-level - clustering. Full cluster-robust analytical SEs are deferred. + clustering. Cluster-robust analytical SEs through the bare `cluster=` + parameter are deferred; a PSU declared through + `survey_design=SurveyDesign(psu=...)` IS honored analytically, per cell and + in aggregate (next Note). - **Note:** Full survey design support (pweight only). Survey weights enter propensity score estimation (weighted IRLS), outcome regression (WLS), and Riesz representer computation. IF combination weights (w1/w2/w3) use survey-weighted cell sizes. Aggregated SEs use `compute_survey_if_variance()` - (TSL) or `compute_replicate_if_variance()` (replicate weights). Bootstrap - uses PSU-level multiplier weights. The R `triplediff` package does not - support survey weights. + (TSL) or `compute_replicate_if_variance()` (replicate weights). Per-(g,t) + SEs follow the CallawaySantAnna per-cell contract + (`staggered._design_se_for_cell`), applied to the GMM-combined influence + function - the psi the aggregates consume - for single- and + multi-comparison-group cells alike: a PSU design uses + `compute_survey_if_variance()` on the cell IF (CR1 on PSU totals; an + unidentified clustered variance, e.g. a single PSU, propagates as a NaN + SE), a replicate design uses `compute_replicate_if_variance()` with the + cell-local df `min(df_survey, n_valid - 1)`. Weights-only, strata-only and + FPC-only designs keep the non-design per-(g,t) formulas above (the full + design enters the aggregated SEs only). Fail-closed rules match + CallawaySantAnna: a non-finite cell IF, or a zero / negative / non-finite + replicate variance, gives a NaN SE where the aggregate path clamps a zero + or negative variance to `0.0`. Through 4.0.0 the per-(g,t) SE ignored PSU + and replicate designs (it stayed on the non-design formulas while the + aggregates were design-based). Bootstrap uses PSU-level multiplier + weights. The R `triplediff` package does not support survey weights, so the + design-based per-(g,t) SE is a library extension. *Edge cases:* - Single comparison group: GMM reduces to w=[1], no matrix inversion @@ -7916,9 +7938,13 @@ ContinuousDiD, EfficientDiD): - **Formula**: `V_design = sum_h (1-f_h) * (n_h/(n_h-1)) * sum_j (psi_hj - psi_h_bar)^2` where `psi_hj = sum_{i in PSU j} psi_i` and `psi_i` is the combined IF (standard + WIF). -- **Note:** Per-(g,t) cell SEs use the simpler IF-based formula `sqrt(sum(psi^2))` which - already incorporates survey weights. Only aggregated SEs (overall, event study, group) - use the full design-based variance. +- **Note:** Per-(g,t) cell SEs follow a three-lane convention on the cell's own IF + (CallawaySantAnna per-cell survey Note, `staggered._design_se_for_cell`): weights-only, + strata-only and FPC-only designs use the IF sqrt-sum `sqrt(sum(psi^2))`, which already + incorporates survey weights - on those lanes only the aggregated SEs (overall, event + study, group) use the full design-based variance; a declared PSU uses the design + variance above on the cell IF; a replicate-weight design uses the replicate IF + variance with the cell-local df `min(df_survey, n_valid - 1)`. **TROP Cross-Classified Strata**: @@ -7993,9 +8019,11 @@ variance from the distribution of replicate estimates. t-based inference. - **Note:** Replicate-weight support matrix (13 of 20 public estimators): - **Supported**: CallawaySantAnna (reg/ipw/dr with or without covariates, - no bootstrap; IF-based replicate variance is covariate-agnostic), + no bootstrap; IF-based replicate variance is covariate-agnostic, PER-CELL + and aggregate), ContinuousDiD (no bootstrap), EfficientDiD (no bootstrap), - TripleDifference (all methods; staggered mode IF-based), + TripleDifference (all methods; staggered mode IF-based, per-cell and + aggregate), DifferenceInDifferences (no-absorb via LinearRegression dispatch, absorb via estimator-level refit), the TwoWayFixedEffects event-study mode (`spec="pooled"` via `compute_replicate_vcov`, `spec="within"` via @@ -8008,7 +8036,7 @@ variance from the distribution of replicate estimates. multi-horizon and placebo paths; replicate + `n_bootstrap > 0` rejected — see the ChaisemartinDHaultfoeuille Notes for the allocator contract), DMLDiD (IF-reweighting on the augmented cross-fitted scores, PER-CELL - and aggregate — exceeds CS's per-cell convention; replicate + + and aggregate; replicate + `cluster=` and replicate + bootstrap rejected — see the DMLDiD replicate Note) - **Rejected with NotImplementedError**: SyntheticDiD, TROP diff --git a/tests/test_per_cell_design_se.py b/tests/test_per_cell_design_se.py new file mode 100644 index 000000000..e9675a464 --- /dev/null +++ b/tests/test_per_cell_design_se.py @@ -0,0 +1,791 @@ +"""Per-cell ATT(g,t) SEs honor replicate and PSU survey designs. + +Covers CallawaySantAnna (replicate lane) and the staggered TripleDifference +engine (replicate and PSU lanes). The invariant under test: under a replicate +or PSU design a per-cell SE comes from the same influence function and the +same design variance routine as the aggregate SEs of the same fit. + +Before this change the cell SE ignored the design (one-cell panels, where the +cell IS the overall ATT): CS + JK1 reported cell SE 0.156789 against an overall +SE of 0.342755; staggered DDD reported 0.217289 against 0.325258 under both +JK1 replicates and ``SurveyDesign(psu=...)``. +""" + +import warnings + +import numpy as np +import pandas as pd +import pytest +from scipy import stats + +import diff_diff.staggered as staggered_mod +import diff_diff.survey as survey_mod +from diff_diff import CallawaySantAnna, SurveyDesign, TripleDifference +from diff_diff.prep_dgp import generate_staggered_ddd_data +from diff_diff.staggered import ( + _cluster_robust_se_from_per_gt_if, + _design_se_for_cell, + _replicate_se_from_per_gt_if, +) +from diff_diff.survey import ( + cap_replicate_df, + compute_replicate_if_variance, + compute_survey_if_variance, +) +from tests.conftest import assert_nan_inference + +# --------------------------------------------------------------------------- +# DGPs +# --------------------------------------------------------------------------- + + +def _add_jk1(df, cluster_col="cl", weight_col="w"): + """Delete-one-cluster JK1 replicate columns (combined weights).""" + clusters = np.sort(df[cluster_col].unique()) + n_cl = len(clusters) + cols = { + f"rep_{r}": np.where(df[cluster_col] == c, 0.0, df[weight_col] * n_cl / (n_cl - 1)) + for r, c in enumerate(clusters) + } + return pd.concat([df, pd.DataFrame(cols, index=df.index)], axis=1), list(cols) + + +def _cs_panel(seed=7, n_clusters=20, per_cluster=6, n_periods=4): + """Multi-cohort panel: cohorts {3, 4, never}, cluster-level period shocks.""" + rng = np.random.default_rng(seed) + rows = [] + for c in range(n_clusters): + g = 3 if c < 6 else (4 if c < 12 else 0) + shocks = rng.normal(0.0, 0.8, n_periods) + for j in range(per_cluster): + u = c * per_cluster + j + a, x, w = rng.normal(), rng.normal(), rng.uniform(0.5, 2.0) + for t in range(1, n_periods + 1): + effect = 1.0 + 0.2 * (t - g) if (g and t >= g) else 0.0 + y = a + 0.3 * t + 0.4 * x * t + shocks[t - 1] + effect + rng.normal(0.0, 0.5) + rows.append((u, c, c % 2, t, g, y, x, w)) + df = pd.DataFrame(rows, columns=["unit", "cl", "stratum", "t", "g", "y", "x0", "w"]) + return _add_jk1(df) + + +def _cs_rcs(seed=11, n_obs=900): + """Genuine repeated cross-section: one row per unit, 20 PSUs.""" + rng = np.random.default_rng(seed) + obs = np.arange(n_obs) + cl = obs // 45 + g = rng.choice([0, 3, 4], size=n_obs, p=[0.5, 0.25, 0.25]) + t = rng.choice([1, 2, 3, 4], size=n_obs) + shock = rng.normal(0.0, 0.5, (20, 5))[cl, t] + y = 1.0 + 0.4 * t + shock + np.where((g > 0) & (t >= g), 1.5, 0.0) + rng.normal(0, 0.4, n_obs) + df = pd.DataFrame( + { + "unit": obs, + "cl": cl, + "stratum": cl % 2, + "t": t, + "g": g, + "y": y, + "w": rng.uniform(0.5, 2.0, n_obs), + } + ) + return _add_jk1(df) + + +def _cs_one_cell(): + """Single cohort, two periods: the one cell IS the overall ATT.""" + rng = np.random.default_rng(7) + n_cl, per = 30, 8 + rows = [] + for c in range(n_cl): + treated = c < 12 + shock = rng.normal(0, 1.0) + for j in range(per): + u = c * per + j + a = rng.normal(0, 1) + w = rng.uniform(0.5, 2.0) + for t in (1, 2): + y = ( + a + + 0.3 * t + + (shock if t == 2 else 0) + + (1.0 if (treated and t == 2) else 0) + + rng.normal(0, 0.5) + ) + rows.append((u, c, t, 2 if treated else 0, y, w)) + df = pd.DataFrame(rows, columns=["unit", "cl", "t", "g", "y", "w"]) + return _add_jk1(df) + + +def _ddd_frame(seed, n_periods, cohort_periods, never_enabled_frac, shock_seed, all_periods): + d = generate_staggered_ddd_data( + n_units=240, + n_periods=n_periods, + cohort_periods=cohort_periods, + never_enabled_frac=never_enabled_frac, + seed=seed, + ) + units = np.sort(d["unit"].unique()) + rng = np.random.default_rng(shock_seed) + n_cl = 30 + ft = d.groupby("unit")["first_treat"].first().sort_values(kind="stable") + cl_of = pd.Series(np.arange(len(ft)) // (len(ft) // n_cl), index=ft.index).clip(upper=n_cl - 1) + d["cl"] = d["unit"].map(cl_of) + d["stratum"] = d["cl"] % 2 + last = d["period"].max() + if all_periods: + periods = np.sort(d["period"].unique()) + shock = pd.DataFrame( + rng.normal(0, 0.6, (n_cl, len(periods))), index=range(n_cl), columns=periods + ) + per_row = shock.to_numpy()[ + d["cl"].to_numpy(), np.searchsorted(periods, d["period"].to_numpy()) + ] + d["outcome"] = d["outcome"] + np.where(d["eligibility"] == 1, per_row, 0.0) + else: + shock = pd.Series(rng.normal(0, 1.0, n_cl)) + d["outcome"] = d["outcome"] + np.where( + (d["period"] == last) & (d["eligibility"] == 1), d["cl"].map(shock), 0.0 + ) + wu = pd.Series(rng.uniform(0.5, 2.0, len(units)), index=units) + d["w"] = d["unit"].map(wu) + return _add_jk1(d) + + +def _ddd_one_cell(): + return _ddd_frame( + seed=3, + n_periods=2, + cohort_periods=[2], + never_enabled_frac=0.5, + shock_seed=11, + all_periods=False, + ) + + +def _ddd_panel(): + return _ddd_frame( + seed=5, + n_periods=5, + cohort_periods=[3, 4], + never_enabled_frac=0.3, + shock_seed=13, + all_periods=True, + ) + + +# --------------------------------------------------------------------------- +# Fit helpers +# --------------------------------------------------------------------------- + + +def _jk1(rep_cols): + return SurveyDesign(weights="w", replicate_weights=rep_cols, replicate_method="JK1") + + +def _fit_cs(df, survey=None, method="reg", covariates=None, panel=True, time="t"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return CallawaySantAnna(estimation_method=method, panel=panel).fit( + df, + outcome="y", + unit="unit", + time=time, + first_treat="g", + covariates=covariates, + survey_design=survey, + ) + + +def _fit_ddd(df, survey=None): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return TripleDifference().fit( + df, + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + partition="eligibility", + survey_design=survey, + ) + + +def _estimable_cells(res): + out = {} + for key, cell in res.group_time_effects.items(): + if cell.get("skip_reason") is not None or cell.get("is_reference"): + continue + if not np.isfinite(cell["effect"]): + continue + out[(float(key[0]), float(key[1]))] = cell + return out + + +def _cell_psi(res, key): + kit = res._aggregation_kit + resolved = kit.bookkeeping["resolved_survey_unit"] + info = kit.influence[key] + psi = np.zeros(len(resolved.weights)) + psi[info["treated_idx"]] = info["treated_inf"] + psi[info["control_idx"]] = info["control_inf"] + return psi, resolved + + +def _kit_cells(res): + kit = res._aggregation_kit + for key, cell in res.group_time_effects.items(): + if cell.get("skip_reason") is not None or cell.get("is_reference"): + continue + if key not in kit.influence or len(kit.influence[key]["treated_idx"]) == 0: + continue + yield key, cell + + +# Cell-count-preserving lane parametrization: each id names the per-cell +# producer the fit exercises under a survey design. +CS_LANES = { + "vectorized_reg": dict(method="reg", covariates=None), + "general_reg_cov": dict(method="reg", covariates=["x0"]), + "general_ipw": dict(method="ipw", covariates=["x0"]), + "general_dr": dict(method="dr", covariates=["x0"]), +} + + +@pytest.fixture(scope="module") +def cs_panel(): + return _cs_panel() + + +@pytest.fixture(scope="module") +def cs_rcs(): + return _cs_rcs() + + +@pytest.fixture(scope="module") +def ddd_panel(): + return _ddd_panel() + + +# --------------------------------------------------------------------------- +# 1. Exact match to the design variance routine +# --------------------------------------------------------------------------- + + +class TestExactMatchToVarianceRoutine: + @pytest.mark.parametrize("lane", sorted(CS_LANES)) + def test_cs_replicate_panel(self, cs_panel, lane): + df, rep_cols = cs_panel + res = _fit_cs(df, survey=_jk1(rep_cols), **CS_LANES[lane]) + checked = 0 + for key, cell in _kit_cells(res): + psi, resolved = _cell_psi(res, key) + variance, _ = compute_replicate_if_variance(psi, resolved) + np.testing.assert_allclose(cell["se"], np.sqrt(variance), rtol=1e-12) + checked += 1 + assert checked >= 4 + + def test_cs_replicate_rcs(self, cs_rcs): + df, rep_cols = cs_rcs + res = _fit_cs(df, survey=_jk1(rep_cols), panel=False) + checked = 0 + for key, cell in _kit_cells(res): + psi, resolved = _cell_psi(res, key) + variance, _ = compute_replicate_if_variance(psi, resolved) + np.testing.assert_allclose(cell["se"], np.sqrt(variance), rtol=1e-12) + checked += 1 + assert checked >= 4 + + def test_ddd_replicate(self, ddd_panel): + df, rep_cols = ddd_panel + res = _fit_ddd(df, survey=_jk1(rep_cols)) + checked = 0 + for key, cell in _kit_cells(res): + psi, resolved = _cell_psi(res, key) + variance, _ = compute_replicate_if_variance(psi, resolved) + np.testing.assert_allclose(cell["se"], np.sqrt(variance), rtol=1e-12) + checked += 1 + assert checked >= 4 + + def test_ddd_psu(self, ddd_panel): + df, _ = ddd_panel + res = _fit_ddd(df, survey=SurveyDesign(weights="w", psu="cl")) + checked = 0 + for key, cell in _kit_cells(res): + psi, resolved = _cell_psi(res, key) + variance = compute_survey_if_variance(psi, resolved) + np.testing.assert_allclose(cell["se"], np.sqrt(variance), rtol=1e-12) + checked += 1 + assert checked >= 4 + + +# --------------------------------------------------------------------------- +# 2. One-cell coherence: the cell IS the overall ATT +# --------------------------------------------------------------------------- + + +class TestOneCellCoherence: + def test_cs_replicate(self): + df, rep_cols = _cs_one_cell() + res = _fit_cs(df, survey=_jk1(rep_cols)) + weights_only = _fit_cs(df, survey=SurveyDesign(weights="w")) + (cell,) = _estimable_cells(res).values() + (cell_w,) = _estimable_cells(weights_only).values() + np.testing.assert_allclose(cell["effect"], res.att, rtol=1e-12) + np.testing.assert_allclose(cell["se"], res.se, rtol=1e-10) + # Measured: 0.342755 (design) vs 0.156789 (weights-only, the pre-fix + # cell SE under the replicate design). + np.testing.assert_allclose(cell["se"], 0.342755, rtol=1e-5) + np.testing.assert_allclose(cell_w["se"], 0.156789, rtol=1e-5) + np.testing.assert_allclose(cell["p_value"], res.p_value, rtol=1e-8) + + @pytest.mark.parametrize("design", ["replicate", "psu"]) + def test_ddd(self, design): + df, rep_cols = _ddd_one_cell() + survey = _jk1(rep_cols) if design == "replicate" else SurveyDesign(weights="w", psu="cl") + res = _fit_ddd(df, survey=survey) + weights_only = _fit_ddd(df, survey=SurveyDesign(weights="w")) + (cell,) = _estimable_cells(res).values() + (cell_w,) = _estimable_cells(weights_only).values() + np.testing.assert_allclose(cell["effect"], res.att, rtol=1e-12) + np.testing.assert_allclose(cell["se"], res.se, rtol=1e-10) + # Measured: 0.325258 (design) vs 0.217289 (the pre-fix cell SE under + # both designs). + np.testing.assert_allclose(cell["se"], 0.325258, rtol=1e-5) + np.testing.assert_allclose(cell_w["se"], 0.217289, rtol=1e-5) + np.testing.assert_allclose(cell["p_value"], res.p_value, rtol=1e-8) + + +# --------------------------------------------------------------------------- +# 3. JK1 (delete-one-PSU) == CR1 on the same PSUs +# --------------------------------------------------------------------------- + + +class TestJK1EqualsCR1: + """Algebraic identity: theta_r - theta = -G (psi_r - psi_bar) / (G - 1), so + the JK1 variance (G-1)/G * sum(...)^2 equals CR1's G/(G-1) * sum((psi_r - + psi_bar)^2) on the same cell influence function.""" + + @pytest.mark.parametrize("lane", sorted(CS_LANES)) + def test_cs_panel(self, cs_panel, lane): + df, rep_cols = cs_panel + rep = _estimable_cells(_fit_cs(df, survey=_jk1(rep_cols), **CS_LANES[lane])) + psu = _estimable_cells( + _fit_cs(df, survey=SurveyDesign(weights="w", psu="cl"), **CS_LANES[lane]) + ) + assert rep.keys() == psu.keys() and len(rep) >= 4 + for key in rep: + np.testing.assert_allclose(rep[key]["effect"], psu[key]["effect"], rtol=1e-10) + np.testing.assert_allclose(rep[key]["se"], psu[key]["se"], rtol=1e-10) + + def test_cs_rcs(self, cs_rcs): + df, rep_cols = cs_rcs + rep = _estimable_cells(_fit_cs(df, survey=_jk1(rep_cols), panel=False)) + psu = _estimable_cells(_fit_cs(df, survey=SurveyDesign(weights="w", psu="cl"), panel=False)) + assert rep.keys() == psu.keys() and len(rep) >= 4 + for key in rep: + np.testing.assert_allclose(rep[key]["se"], psu[key]["se"], rtol=1e-10) + + def test_ddd(self, ddd_panel): + df, rep_cols = ddd_panel + res_rep = _fit_ddd(df, survey=_jk1(rep_cols)) + res_psu = _fit_ddd(df, survey=SurveyDesign(weights="w", psu="cl")) + rep, psu = _estimable_cells(res_rep), _estimable_cells(res_psu) + assert rep.keys() == psu.keys() and len(rep) >= 4 + # The identity must be exercised on GMM-combined (multi-comparison-group) + # cells too, not only on single-comparison-group ones. + counts = set(res_rep.comparison_group_counts.values()) + assert 1 in counts and max(counts) > 1 + for key in rep: + np.testing.assert_allclose(rep[key]["effect"], psu[key]["effect"], rtol=1e-10) + np.testing.assert_allclose(rep[key]["se"], psu[key]["se"], rtol=1e-10) + + +# --------------------------------------------------------------------------- +# 4. Cell-local df: min(design df, n_valid - 1), never written back +# --------------------------------------------------------------------------- + + +def _spy_cell_n_valid(monkeypatch, n_valid): + """Rewrite n_valid on PER-CELL replicate calls only. + + Patching ``survey.compute_replicate_if_variance`` would also reach the + aggregate ``_se_from_psi`` path and move ``survey_metadata.df_survey`` + through the overall relay; wrapping the per-cell helper isolates the cell + df from the aggregate df. + """ + real = staggered_mod._replicate_se_from_per_gt_if + + def wrapped(inf_info, resolved_survey): + se, _ = real(inf_info, resolved_survey) + return se, n_valid + + monkeypatch.setattr(staggered_mod, "_replicate_se_from_per_gt_if", wrapped) + + +def _rank5(df, rep_cols): + """20 replicate columns of rank 5 (four copies of five distinct columns).""" + out = df.copy() + for i, col in enumerate(rep_cols): + out[col] = df[rep_cols[i % 5]] + return out + + +class TestCellLocalDf: + def _assert_cells_use_df(self, res, df_expected): + checked = 0 + for cell in _estimable_cells(res).values(): + expected = 2.0 * stats.t.sf(abs(cell["effect"] / cell["se"]), df_expected) + np.testing.assert_allclose(cell["p_value"], expected, rtol=1e-10) + checked += 1 + assert checked >= 4 + + @pytest.mark.parametrize("lane", ["vectorized_reg", "general_dr"]) + def test_cs_cap_slack_uses_n_valid(self, cs_panel, lane, monkeypatch): + df, rep_cols = cs_panel + _spy_cell_n_valid(monkeypatch, 7) + res = _fit_cs(df, survey=_jk1(rep_cols), **CS_LANES[lane]) + # Full-rank JK1 over 20 PSUs: design df 19, cell df min(19, 7 - 1) = 6. + self._assert_cells_use_df(res, 6) + assert res.survey_metadata.df_survey == 19 + + @pytest.mark.parametrize("lane", ["vectorized_reg", "general_dr"]) + def test_cs_cap_binds_at_design_df(self, cs_panel, lane, monkeypatch): + df, rep_cols = cs_panel + _spy_cell_n_valid(monkeypatch, 7) + res = _fit_cs(_rank5(df, rep_cols), survey=_jk1(rep_cols), **CS_LANES[lane]) + # Rank 5 -> design df 4; n_valid - 1 = 6 must NOT replace it. + self._assert_cells_use_df(res, 4) + assert res.survey_metadata.df_survey == 4 + + def test_ddd_cap(self, ddd_panel, monkeypatch): + df, rep_cols = ddd_panel + _spy_cell_n_valid(monkeypatch, 7) + res = _fit_ddd(df, survey=_jk1(rep_cols)) + self._assert_cells_use_df(res, 6) + assert res.survey_metadata.df_survey == len(rep_cols) - 1 + res5 = _fit_ddd(_rank5(df, rep_cols), survey=_jk1(rep_cols)) + self._assert_cells_use_df(res5, 4) + assert res5.survey_metadata.df_survey == 4 + + def test_rank_one_design_nan_inference(self, cs_panel, ddd_panel): + df, rep_cols = cs_panel + flat = df.copy() + for col in rep_cols: + flat[col] = df["w"] + res = _fit_cs(flat, survey=_jk1(rep_cols)) + cells = _estimable_cells(res) + assert len(cells) >= 4 + for cell in cells.values(): + assert_nan_inference(cell) + + ddf, drep = ddd_panel + dflat = ddf.copy() + for col in drep: + dflat[col] = ddf["w"] + dres = _fit_ddd(dflat, survey=_jk1(drep)) + dcells = _estimable_cells(dres) + assert len(dcells) >= 4 + for cell in dcells.values(): + assert_nan_inference(cell) + + +# --------------------------------------------------------------------------- +# 5/6. Degenerate cells fail closed and never contaminate other cells +# --------------------------------------------------------------------------- + + +def _spy_one_cell(monkeypatch, call_index, variance): + """Force ``variance`` on the ``call_index``-th per-cell replicate call.""" + real = staggered_mod._replicate_se_from_per_gt_if + real_var = survey_mod.compute_replicate_if_variance + state = {"n": 0} + + def wrapped(inf_info, resolved_survey): + hit = state["n"] == call_index + state["n"] += 1 + if not hit: + return real(inf_info, resolved_survey) + with monkeypatch.context() as m: + m.setattr( + survey_mod, + "compute_replicate_if_variance", + lambda psi, resolved: (variance, real_var(psi, resolved)[1]), + ) + return real(inf_info, resolved_survey) + + monkeypatch.setattr(staggered_mod, "_replicate_se_from_per_gt_if", wrapped) + + +class TestDegenerateCells: + @pytest.mark.parametrize("lane", ["vectorized_reg", "general_dr"]) + @pytest.mark.parametrize("variance", [0.0, np.nan, -1e-30]) + def test_cs_degenerate_cell_is_nan_and_isolated(self, cs_panel, lane, variance, monkeypatch): + df, rep_cols = cs_panel + base = _estimable_cells(_fit_cs(df, survey=_jk1(rep_cols), **CS_LANES[lane])) + _spy_one_cell(monkeypatch, 0, variance) + res = _fit_cs(df, survey=_jk1(rep_cols), **CS_LANES[lane]) + cells = _estimable_cells(res) + # The cell is retained (finite effect, no skip reason) with NaN inference. + assert cells.keys() == base.keys() + bad = [k for k, c in cells.items() if not np.isfinite(c["se"])] + assert len(bad) == 1 + assert_nan_inference(cells[bad[0]]) + assert res.group_time_effects # still a completed fit + for key in cells: + if key == bad[0]: + continue + np.testing.assert_array_equal(cells[key]["se"], base[key]["se"]) + np.testing.assert_array_equal(cells[key]["p_value"], base[key]["p_value"]) + np.testing.assert_array_equal(cells[key]["conf_int"], base[key]["conf_int"]) + + def test_ddd_degenerate_cell_is_nan_and_isolated(self, ddd_panel, monkeypatch): + df, rep_cols = ddd_panel + base = _estimable_cells(_fit_ddd(df, survey=_jk1(rep_cols))) + _spy_one_cell(monkeypatch, 0, 0.0) + cells = _estimable_cells(_fit_ddd(df, survey=_jk1(rep_cols))) + assert cells.keys() == base.keys() + bad = [k for k, c in cells.items() if not np.isfinite(c["se"])] + assert len(bad) == 1 + assert_nan_inference(cells[bad[0]]) + for key in cells: + if key != bad[0]: + np.testing.assert_array_equal(cells[key]["se"], base[key]["se"]) + np.testing.assert_array_equal(cells[key]["p_value"], base[key]["p_value"]) + + def test_ddd_single_psu_propagates_nan(self, ddd_panel): + df, _ = ddd_panel + one = df.assign(one_psu=0) + res = _fit_ddd(one, survey=SurveyDesign(weights="w", psu="one_psu")) + cells = _estimable_cells(res) + assert len(cells) >= 4 + for cell in cells.values(): + # Unidentified clustered variance: NaN, never the unit-level SE. + assert_nan_inference(cell) + + +# --------------------------------------------------------------------------- +# 7. Unchanged lanes (literals captured from the unmodified tree) +# --------------------------------------------------------------------------- + +# Captured on the tree BEFORE the per-cell dispatch landed (rtol 1e-10: lane +# misrouting moves these by more than 1e-2 relative; 1e-10 absorbs backend / +# BLAS rounding, so one literal set serves both backends). +_CS_WEIGHTED = { + (3.0, 2.0): 0.22824161596588807, + (3.0, 3.0): 0.3248858376303261, + (3.0, 4.0): 0.33702332799162515, + (4.0, 2.0): 0.28234200951533633, + (4.0, 3.0): 0.2798227207932187, + (4.0, 4.0): 0.38146007170016494, +} +UNCHANGED_CS = { + "none": { + (3.0, 2.0): 0.2287237602551264, + (3.0, 3.0): 0.27449135225445065, + (3.0, 4.0): 0.2845982302625901, + (4.0, 2.0): 0.26226113435289605, + (4.0, 3.0): 0.2488707412488824, + (4.0, 4.0): 0.33529556326941945, + }, + "weights": _CS_WEIGHTED, + # Strata-only: the per-cell SE is the weights-only one (documented + # convention - the full design enters the aggregate SEs only). + "strata": _CS_WEIGHTED, +} +_DDD_WEIGHTED = { + (3.0, 2.0): 0.24466409297412722, + (3.0, 3.0): 0.2848199127512167, + (3.0, 4.0): 0.32746875872510617, + (3.0, 5.0): 0.32042936473851963, + (4.0, 2.0): 0.27174596394847605, + (4.0, 3.0): 0.3503229202031343, + (4.0, 4.0): 0.3296421409836883, + (4.0, 5.0): 0.2940868008043224, +} +UNCHANGED_DDD = { + "none": { + (3.0, 2.0): 0.23861592308214064, + (3.0, 3.0): 0.2569313134463256, + (3.0, 4.0): 0.31485553592229476, + (3.0, 5.0): 0.31078126391929545, + (4.0, 2.0): 0.2558390475671242, + (4.0, 3.0): 0.3241892351948469, + (4.0, 4.0): 0.29590977121252926, + (4.0, 5.0): 0.27887271825120685, + }, + "weights": _DDD_WEIGHTED, + "strata": _DDD_WEIGHTED, +} + + +def _lane_fits(kind, df): + fit = _fit_cs if kind == "cs" else _fit_ddd + return { + "none": fit(df), + "weights": fit(df, survey=SurveyDesign(weights="w")), + "strata": fit(df, survey=SurveyDesign(weights="w", strata="stratum")), + } + + +class TestUnchangedLanes: + @pytest.mark.parametrize("design", ["none", "weights", "strata"]) + def test_cs(self, cs_panel, design): + df, _ = cs_panel + res = _lane_fits("cs", df)[design] + cells = _estimable_cells(res) + assert cells.keys() == UNCHANGED_CS[design].keys() + for key, cell in cells.items(): + np.testing.assert_allclose(cell["se"], UNCHANGED_CS[design][key], rtol=1e-10) + + def test_cs_strata_only_is_weighted_sqrt_sum(self, cs_panel): + df, _ = cs_panel + res = _fit_cs(df, survey=SurveyDesign(weights="w", strata="stratum")) + checked = 0 + for key, cell in _kit_cells(res): + psi, _ = _cell_psi(res, key) + np.testing.assert_allclose(cell["se"], np.sqrt(np.sum(psi**2)), rtol=1e-12) + checked += 1 + assert checked >= 4 + + @pytest.mark.parametrize("design", ["none", "weights", "strata"]) + def test_ddd(self, ddd_panel, design): + df, _ = ddd_panel + res = _lane_fits("ddd", df)[design] + cells = _estimable_cells(res) + assert cells.keys() == UNCHANGED_DDD[design].keys() + for key, cell in cells.items(): + np.testing.assert_allclose(cell["se"], UNCHANGED_DDD[design][key], rtol=1e-10) + + def test_ddd_strata_only_single_gc_is_sqrt_sum_multi_gc_is_gmm(self, ddd_panel): + df, _ = ddd_panel + res = _fit_ddd(df, survey=SurveyDesign(weights="w", strata="stratum")) + single = multi = 0 + for key, cell in _kit_cells(res): + psi, _ = _cell_psi(res, key) + sqrt_sum = np.sqrt(np.sum(psi**2)) + if res.comparison_group_counts[key] == 1: + np.testing.assert_allclose(cell["se"], sqrt_sum, rtol=1e-12) + single += 1 + else: + # Multi-comparison-group cells keep R's GMM formula + # sqrt(1 / (n * 1'Omega^-1 1)), which is NOT the IF sqrt-sum. + assert not np.isclose(cell["se"], sqrt_sum, rtol=1e-6) + multi += 1 + assert single >= 1 and multi >= 1 + + +# --------------------------------------------------------------------------- +# 8. Helper unit tests +# --------------------------------------------------------------------------- + + +class TestCapReplicateDf: + @pytest.mark.parametrize( + "base, n_valid, expected", + [ + (None, 20, 0), # undefined design df (QR rank <= 1) -> NaN sentinel + (0, 20, 0), # an already-sentinelled base stays 0 + (19, 20, 19), # cap slack: full replicate count + (19, 7, 6), # n_valid - 1 binds + (4, 7, 4), # design df binds (never raised to n_valid - 1) + (19, 1, 0), + (19, 0, 0), + (19.0, 7, 6), + ], + ) + def test_table(self, base, n_valid, expected): + out = cap_replicate_df(base, n_valid) + assert out == expected and isinstance(out, int) + + +def _hand_design(kind): + """10 units; cell payload on units 0-4, bystanders 5-9.""" + df = pd.DataFrame({"w": np.ones(10), "psu": np.repeat(np.arange(5), 2)}) + if kind == "psu": + return SurveyDesign(weights="w", psu="psu").resolve(df) + if kind == "weights": + return SurveyDesign(weights="w").resolve(df) + if kind == "replicate_bystander": + # Four columns perturbing only bystander units: the cell's replicate + # variance is exactly zero while the replicate matrix has rank > 1. + for r in range(4): + col = np.ones(10) + col[5 + r] = 0.0 + df[f"r{r}"] = col + else: + for r in range(5): + df[f"r{r}"] = np.where(df["psu"] == r, 0.0, 5.0 / 4.0) + cols = [c for c in df.columns if c.startswith("r")] + return SurveyDesign(weights="w", replicate_weights=cols, replicate_method="JK1").resolve(df) + + +def _payload(treated_inf=(0.3, -0.1), control_inf=(-0.2, 0.05, -0.05)): + return { + "treated_idx": np.array([0, 1]), + "control_idx": np.array([2, 3, 4]), + "treated_inf": np.array(treated_inf, dtype=float), + "control_inf": np.array(control_inf, dtype=float), + } + + +class TestDesignSeForCell: + def test_no_design_passthrough(self): + assert _design_se_for_cell(_payload(), None, 0.25, None) == (0.25, None) + assert _design_se_for_cell(_payload(), _hand_design("weights"), 0.25, 9) == (0.25, 9) + + def test_psu_branch_uses_cr1_and_keeps_df(self): + resolved = _hand_design("psu") + se, df = _design_se_for_cell(_payload(), resolved, 0.25, 4) + psi = np.zeros(10) + psi[:5] = [0.3, -0.1, -0.2, 0.05, -0.05] + np.testing.assert_allclose(se, np.sqrt(compute_survey_if_variance(psi, resolved))) + assert df == 4 and se != 0.25 + + def test_psu_malformed_payload_keeps_unit_se(self): + resolved = _hand_design("psu") + assert _design_se_for_cell({"treated_idx": np.array([0])}, resolved, 0.25, 4) == (0.25, 4) + + def test_replicate_branch(self): + resolved = _hand_design("replicate") + se, df = _design_se_for_cell(_payload(), resolved, 0.25, resolved.df_survey) + psi = np.zeros(10) + psi[:5] = [0.3, -0.1, -0.2, 0.05, -0.05] + variance, n_valid = compute_replicate_if_variance(psi, resolved) + np.testing.assert_allclose(se, np.sqrt(variance), rtol=1e-14) + assert n_valid == 5 and df == min(resolved.df_survey, 4) + + def test_replicate_malformed_payload_fails_closed(self): + resolved = _hand_design("replicate") + se, df = _design_se_for_cell({"treated_idx": np.array([0])}, resolved, 0.25, 4) + # Never the unit-level SE under a replicate design. + assert np.isnan(se) and df == 0 + se, n_valid = _replicate_se_from_per_gt_if(None, resolved) + assert np.isnan(se) and n_valid == 0 + + def test_replicate_zero_variance_is_nan_not_zero(self): + resolved = _hand_design("replicate_bystander") + assert resolved.df_survey is not None and resolved.df_survey >= 1 # rank > 1 + psi = np.zeros(10) + psi[:5] = [0.3, -0.1, -0.2, 0.05, -0.05] + variance, n_valid = compute_replicate_if_variance(psi, resolved) + assert variance == 0.0 and n_valid == 4 + se, df = _design_se_for_cell(_payload(), resolved, 0.25, resolved.df_survey) + assert np.isnan(se) + + @pytest.mark.parametrize("kind", ["psu", "replicate"]) + def test_non_finite_influence_value_is_nan(self, kind): + resolved = _hand_design(kind) + bad = _payload(treated_inf=(np.nan, -0.1)) + se, _ = _design_se_for_cell(bad, resolved, 0.25, 4) + # The PSU variance routine sums per PSU with NaN-skipping, so without + # the guard this cell would report a FINITE clustered SE. + assert np.isnan(se) + + def test_cluster_helper_finite_guard_direct(self): + resolved = _hand_design("psu") + assert np.isnan( + _cluster_robust_se_from_per_gt_if(_payload(treated_inf=(np.inf, -0.1)), resolved) + ) + # Contract unchanged for a finite payload and for a malformed one. + assert np.isfinite(_cluster_robust_se_from_per_gt_if(_payload(), resolved)) + assert _cluster_robust_se_from_per_gt_if(None, resolved) is None diff --git a/tests/test_survey_dml.py b/tests/test_survey_dml.py index 4377a64dc..d41f6d8cc 100644 --- a/tests/test_survey_dml.py +++ b/tests/test_survey_dml.py @@ -1193,7 +1193,7 @@ def test_es_df_pins_inherited_replace_convention(self, panel_replicate_df, monke # discriminate, the design must be rank-deficient (df_survey = 4) # with spy n_valid - 1 = 6 > 4: replace reports 6, a cap would # report 4. Pinned at 6 so the follow-up flip to min-cap (TODO.md - # CS-parity row: all five replace-style relay sites) is detectable; + # replicate-df min-cap row: every replace-style relay site) is detectable; # latent in practice (n_valid == R on well-formed designs). from diff_diff import survey as _survey_mod