Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
29 changes: 29 additions & 0 deletions changelog.d/20261122-per-cell-design-se.md
Original file line number Diff line number Diff line change
@@ -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.
46 changes: 32 additions & 14 deletions diff_diff/_staggered_triple_diff_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand All @@ -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()))

Expand Down
2 changes: 1 addition & 1 deletion diff_diff/dml_did.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
Loading
Loading