Skip to content
Open
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
1 change: 0 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ Related tracking surfaces:
| Conley bandwidth diagnostic: when `conley_cutoff_km` covers the whole treated set (one treated spatial cluster inside the bandwidth), the spatial-HAC meat collapses and the SE falls far below HC1 on data with no spatial correlation (tutorial 23's panel: HC1 0.117; Conley 0.117 at 0.5 km, 0.090 at 25 km, 0.062 at 100 km). This is the usual large-bandwidth HAC degeneracy, not a variance bug, but nothing warns. Candidate: a `UserWarning` when the share of treated-treated pairs inside the cutoff exceeds a threshold; the threshold needs a small simulation to choose. | `conley.py`, `spillover.py` | 4.0 tutorial review | Mid | Low |
| No public idiom for a static staggered TWFE with a time-varying covariate (`Y ~ D_it + X_it` with unit and calendar fixed effects): `TwoWayFixedEffects.fit` is 2x2-shaped in static mode and `decompose()` takes no covariates, so tutorial 33's "include the bad control" benchmark builds it from `within_transform` plus `solve_ols`. Either document that route as the supported one or add a staggered static mode. | `twfe.py`, `docs/tutorials/33_bad_controls.ipynb` | 4.0 tutorial review | Mid | Low |
| `SyntheticDiD` Frank-Wolfe convergence on an ordinary panel (tutorial 03: 3 treated and 40 control units, 14 periods, outcomes 30-80, noise sd 0.5): (1) `variance_method="bootstrap"` warns "Frank-Wolfe did not converge on 199 of 199 valid bootstrap draws" on the Rust backend, so the refit bootstrap cannot be shown warning-free and the tutorial demonstrates placebo and jackknife only; (2) on the pure-Python backend the placebo and jackknife fits warn "Frank-Wolfe SC weight solver did not converge in 100 iterations" and "... in 10000 iterations" where the Rust backend is silent on the same data and returns the same ATT. Establish whether the iteration cap or tolerance is too tight for refits, and why the two backends differ in what they report. Same family as the tutorial-18 row below. | `synthetic_did.py`, `utils.py`, `rust/src/` | 4.0 tutorial review | Mid | Low |
| `PreTrendsPower().fit(results)` with the default `M=None` evaluates power at the MDV itself, where it equals the target up to the integration error of the NIS box probability (`scipy.stats.multivariate_normal.cdf`, randomised Genz integration, about 1e-6, unseeded). `PreTrendsPowerResults.power_adequate` is `power >= target_power` with no tolerance, so on identical calls it comes out True or False at random (tutorial-07 panel: True in 14 of 30 fits, power 0.799991 to 0.800007), and `summary()` prints either "Power (80%) meets target" or "Power (80%) below target. Would need violations of 0.208" for the same fit. The MDV and every NIS power also jitter at that scale. Compare with a tolerance no smaller than the integration error (or treat the at-MDV evaluation as adequate by construction), and seed the integration so repeated calls agree. The Wald form is deterministic and unaffected. | `pretrends.py` | 4.0 tutorial review | Quick | Medium |

### Performance

Expand Down
7 changes: 7 additions & 0 deletions changelog.d/20261126-pretrends-nis-determinism.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### Fixed
- **PreTrendsPower NIS determinism and `power_adequate` tolerance**: seeded
`scipy.stats.multivariate_normal.cdf` in `_compute_nis_acceptance_prob` (when
supported by SciPy) so repeated NIS power and MDV calls return identical
values, and applied the integration error tolerance (`1e-5` for NIS, `1e-12`
for Wald) in `PreTrendsPowerResults.power_adequate` so evaluating at `M=None`
(the MDV) consistently reports adequate power instead of flipping randomly.
42 changes: 32 additions & 10 deletions diff_diff/pretrends.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
diff_diff.honest_did - Sensitivity analysis for parallel trends violations
"""

import inspect
import warnings
from dataclasses import dataclass, field
from typing import Any, Dict, List, Literal, Optional, Tuple
Expand All @@ -36,6 +37,12 @@
from diff_diff._base import BaseEstimator
from diff_diff.results_base import Diagnostic, _validate_vcov_subblock

# Absolute error tolerance for scipy.stats.multivariate_normal.cdf (randomized
# Genz QMC integration in scipy >= 1.15). Shared with power_adequate so an
# at-MDV evaluation does not flip below target_power due to integration noise.
_NIS_CDF_ABSEPS = 1e-5
_MVN_CDF_SUPPORTS_RNG = "rng" in inspect.signature(stats.multivariate_normal.cdf).parameters


def _compute_nis_acceptance_prob(
M: float,
Expand Down Expand Up @@ -64,15 +71,29 @@ def _compute_nis_acceptance_prob(

accept_prob: float
try:
accept_prob = float(
stats.multivariate_normal.cdf(
upper,
lower_limit=lower,
mean=np.zeros(len(weights)),
cov=vcov,
allow_singular=True,
if _MVN_CDF_SUPPORTS_RNG:
accept_prob = float(
stats.multivariate_normal.cdf(
upper,
lower_limit=lower,
mean=np.zeros(len(weights)),
cov=vcov,
allow_singular=True,
abseps=_NIS_CDF_ABSEPS,
rng=np.random.default_rng(0),
)
)
else:
accept_prob = float(
stats.multivariate_normal.cdf(
upper,
lower_limit=lower,
mean=np.zeros(len(weights)),
cov=vcov,
allow_singular=True,
abseps=_NIS_CDF_ABSEPS,
)
)
)
except (ValueError, np.linalg.LinAlgError):
accept_prob = float("nan")

Expand Down Expand Up @@ -514,8 +535,9 @@ def max_abs_pre_violation(self) -> float:

@property
def power_adequate(self) -> bool:
"""Check if power meets the target threshold."""
return bool(self.power >= self.target_power)
"""Check if power meets the target threshold (within numerical tolerance)."""
tol = _NIS_CDF_ABSEPS if self.pretest_form == "nis" else 1e-12
return bool(self.power + tol >= self.target_power)

def summary(self) -> str:
"""
Expand Down
65 changes: 65 additions & 0 deletions tests/test_pretrends.py
Original file line number Diff line number Diff line change
Expand Up @@ -974,3 +974,68 @@ def test_declared_post_label_is_rejected_as_pre(self, twfe_long_pre_results):
pt = PreTrendsPower()
with pytest.raises(ValueError):
pt.fit(twfe_long_pre_results, pre_periods=[4, 6])


class TestNISDeterminismAndPowerAdequate:
"""NIS box integration is deterministic and at-MDV fits report adequate power."""

def test_nis_fit_and_power_at_are_deterministic(self, twfe_long_pre_results):
pt = PreTrendsPower(alpha=0.05, power=0.80, pretest_form="nis")
runs = [pt.fit(twfe_long_pre_results) for _ in range(5)]

mdvs = [r.mdv for r in runs]
powers = [r.power for r in runs]
probs = [r.nis_box_probability for r in runs]
assert len(set(mdvs)) == 1
assert len(set(powers)) == 1
assert len(set(probs)) == 1

at_vals = [runs[0].power_at(0.2) for _ in range(5)]
assert len(set(at_vals)) == 1

def test_default_fit_at_mdv_is_consistently_adequate(self, twfe_long_pre_results):
pt = PreTrendsPower(alpha=0.05, power=0.80, pretest_form="nis")
for _ in range(10):
res = pt.fit(twfe_long_pre_results)
assert res.power_adequate is True
assert "meets target" in res.summary()
assert "below target" not in res.summary()

# Explicit underpowered M stays inadequate
under = pt.fit(twfe_long_pre_results, M=0.5 * res.mdv)
assert under.power_adequate is False
assert "below target" in under.summary()

def test_power_adequate_respects_tolerance_bounds(self):
base = dict(
mdv=0.5,
violation_magnitude=0.5,
violation_type="linear",
alpha=0.05,
target_power=0.80,
n_pre_periods=2,
test_statistic=float("nan"),
critical_value=1.96,
noncentrality=float("nan"),
pre_period_effects=np.zeros(2),
pre_period_ses=np.ones(2),
vcov=np.eye(2),
pretest_form="nis",
)
# Within NIS integration error (1e-5) -> adequate
assert PreTrendsPowerResults(power=0.80 - 5e-6, **base).power_adequate is True
# Clearly below target -> not adequate
assert PreTrendsPowerResults(power=0.799, **base).power_adequate is False
# Non-finite power -> not adequate
assert PreTrendsPowerResults(power=float("nan"), **base).power_adequate is False

def test_unreachable_mdv_fallback_is_not_adequate(self):
# Huge SE so MDV=inf and M=None falls back to max(ses) with low power
rows = {
0: (0.0, 1e4, 0.0, 1.0, (-2e4, 2e4)),
2: (1.0, 1.0, 1.0, 0.3, (-1.0, 3.0)),
}
surface = calendar_surface(rows, reference=1, post_periods=[2], vcov=np.diag([1e8, 1.0]))
res = PreTrendsPower(alpha=0.05, power=0.99, pretest_form="nis").fit(surface)
assert np.isinf(res.mdv)
assert res.power_adequate is False