Sharp regression discontinuity with PyMC: check priors before fitting#
This example estimates the jump in an outcome at a treatment threshold. The built-in rd data have a running variable x, an outcome y, and treatment that begins at x = 0.5. We will construct an experiment, inspect what its priors predict, revise them, and only then sample the posterior with fit(). After fitting, we will check predictions against observations before interpreting the discontinuity.
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import display
from pymc_extras.prior import Prior
import causalpy as cp
%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'
seed = 42
Load the data#
The running variable spans roughly \(-1\) to \(1\), while the observed outcome is roughly between \(-1\) and \(2\). These scales will help us judge prior predictions.
df = cp.load_data("rd")
df.head()
| x | y | treated | |
|---|---|---|---|
| 0 | -0.989008 | -0.252433 | False |
| 1 | -0.984119 | -0.050974 | False |
| 2 | -0.964955 | -0.216572 | False |
| 3 | -0.962408 | -0.204497 | False |
| 4 | -0.944821 | -0.354276 | False |
Build the experiment without fitting#
We start with a linear model that allows different slopes on either side of the threshold. The formula centers the running variable at \(x=0.5\), so its treated coefficient is the jump at the cutoff and its interaction coefficient is the change in slope. Constructing RegressionDiscontinuity prepares the design but does not draw from the posterior. The default LinearRegression prior gives every coefficient a Normal(0, 50) distribution; we will inspect its implications before choosing more meaningful scales.
result = cp.RegressionDiscontinuity(
df,
formula="y ~ 1 + I(x - 0.5) * treated",
model=cp.pymc_models.LinearRegression(sample_kwargs={"random_seed": seed}),
treatment_threshold=0.5,
)
result.is_fitted
False
Check the default prior predictions#
sample_prior_predictive() draws possible outcomes from the model before conditioning on y. plot(group="prior") compares the prior-implied regression curves with the observed points. A prior check asks whether the model permits plausible outcomes; it cannot tell us whether the fitted model explains these data.
result.sample_prior_predictive()
fig, ax = result.plot(group="prior", show=False)
display(fig)
plt.close(fig)
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
The default band is enormous relative to the observed outcome range. Its Normal(0, 50) prior allows implausibly large intercepts, jumps, and slopes for this scale. We will use separate scales for the four coefficients rather than apply the same amount of regularization to every part of the curve.
Revise the prior and check again#
The centered design columns are Intercept, treated, centered x, and centered x:treated in that order. The right-hand slope equals the left slope plus the interaction coefficient; the interaction is a slope change, not the right slope itself. We use one-unit standard deviations for the outcome level, jump, and left slope, and three units for the slope change. With independent zero-centered priors, the right slope is also centered at zero but has standard deviation \(\sqrt{1^2 + 3^2} \approx 3.2\) outcome units per \(x\) unit. This leaves room for a steep right-hand trend while retaining some regularization. We use outcome units to set rough scales for this synthetic example; in an applied analysis, substantive knowledge should set plausible effect and slope ranges before looking at the outcome pattern. Assigning a fresh model clears the old prior draws, so we can check this specification before fit().
rd_priors = {
"beta": Prior(
"Normal",
mu=0,
sigma=[1, 1, 1, 3], # level, jump, left slope, change in slope
dims=["treated_units", "coeffs"],
)
}
result.model = cp.pymc_models.LinearRegression(
priors=rd_priors,
sample_kwargs={"random_seed": seed},
)
result.sample_prior_predictive()
fig, ax = result.plot(group="prior", kind="spaghetti", num_samples=30, show=False)
for line in ax.lines:
if line.get_alpha() == 0.1: # Sampled curves, not the solid prior mean.
line.set(alpha=0.4, linewidth=1.3)
ax.set_facecolor("white")
ax.grid(color="#dddddd", linewidth=0.6)
display(fig)
plt.close(fig)
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
The spaghetti curves are individual prior draws, while the solid line is their average. Because all four coefficient priors are centered at zero, that average is nearly flat; it is not a fitted slope. A few draws still reach outcomes well beyond the observations. We accept those tails here because the synthetic outcome has no stated hard bounds and we do not want to rule out a steep right-hand slope with only 17 treated observations. For a bounded or well-understood outcome, these draws would be a reason to tighten the prior before fitting. This is a deliberate prior plausibility decision, not evidence that the treatment effect is causal.
Fit and check posterior predictions#
fit() now samples the posterior and generates posterior predictive draws. result.plot() shows the fitted conditional mean, its uncertainty, the observations, and the estimated discontinuity. We use this plot to inspect whether the trend on each side follows the data. A short check of replicated outcomes then assesses the spread of individual observations, which includes observation noise and therefore answers a different question.
result.fit()
fig, ax = result.plot(show=False)
display(fig)
plt.close(fig)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
The fitted regression is a global straight-line approximation on each side of the threshold. The right-hand slope is informed by the 17 treated observations and the wider interaction prior; its steepness should not be inferred from the flat prior mean in the spaghetti plot. The shape of the observations, particularly left of the cutoff, remains a concern for this global model.
replicated_y = result.idata["posterior_predictive"]["y_hat"].values.squeeze(-1)
lower, upper = np.quantile(replicated_y, [0.03, 0.97], axis=(0, 1))
inside = (df["y"].to_numpy() >= lower) & (df["y"].to_numpy() <= upper)
print(
f"{inside.mean():.0%} of observed outcomes fall in the 94% posterior predictive intervals"
)
93% of observed outcomes fall in the 94% posterior predictive intervals
The pointwise coverage check uses replicated outcomes, including observation noise; it is distinct from the conditional-mean band in result.plot(). Even if most points fall inside these intervals, the built-in plot shows a curved pattern left of the cutoff that two global straight lines cannot follow. Broad coverage alone does not validate the mean shape or the regression discontinuity assumptions. We next try local fits and a spline.
Using a bandwidth#
One way how we could deal with this is to use the bandwidth kwarg. This will only fit the model to data within a certain bandwidth of the threshold. If \(x\) is the running variable, then the model will only be fitted to data where \(threshold - bandwidth \le x \le threshold + bandwidth\).
result = cp.RegressionDiscontinuity(
df,
formula="y ~ 1 + I(x - 0.5) * treated",
model=cp.pymc_models.LinearRegression(
priors=rd_priors, sample_kwargs={"random_seed": seed, "target_accept": 0.95}
),
treatment_threshold=0.5,
bandwidth=0.3,
).fit()
fig, ax = result.plot(show=False)
display(fig)
plt.close(fig)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
An even more local option fits only a separate intercept on each side of the cutoff. It uses fewer observations, so its estimate is less precise. This two-coefficient model needs a prior matched to its own design rather than the four-coefficient prior above.
result = cp.RegressionDiscontinuity(
df,
formula="y ~ 1 + treated",
model=cp.pymc_models.LinearRegression(
priors={
"beta": Prior("Normal", mu=0, sigma=1, dims=["treated_units", "coeffs"])
},
sample_kwargs={"random_seed": seed, "target_accept": 0.95},
),
treatment_threshold=0.5,
bandwidth=0.2,
).fit()
fig, ax = result.plot(show=False)
display(fig)
plt.close(fig)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
Using basis splines#
A spline can represent curvature while using all the data. Its basis has more coefficients than the linear model, so we give those coefficients their own Normal(0, 1) prior. Compare the fitted curve with the observations before interpreting its discontinuity.
result = cp.RegressionDiscontinuity(
df,
formula="y ~ 1 + bs(x, df=6) + treated",
model=cp.pymc_models.LinearRegression(
priors={
"beta": Prior("Normal", mu=0, sigma=1, dims=["treated_units", "coeffs"])
},
sample_kwargs={"random_seed": seed, "target_accept": 0.95},
),
treatment_threshold=0.5,
).fit()
fig, ax = result.plot(show=False)
display(fig)
plt.close(fig)
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 2 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
As with all of the models in this notebook, we can ask for a summary of the model coefficients.
result.summary()
Regression Discontinuity experiment
Formula: y ~ 1 + bs(x, df=6) + treated
Running variable: x
Threshold on running variable: 0.5
Bandwidth: inf
Donut hole: 0.0
Observations used for fit: 100
Results:
Discontinuity at threshold = 0.51$CI_{94\%}$[0.35, 0.67]
Model coefficients:
Intercept -0.16, 94% HDI [-0.26, -0.063]
treated[T.True] 0.51, 94% HDI [0.35, 0.67]
bs(x, df=6)[0] -0.41, 94% HDI [-0.59, -0.21]
bs(x, df=6)[1] -1.4, 94% HDI [-1.6, -1.3]
bs(x, df=6)[2] 0.26, 94% HDI [0.1, 0.41]
bs(x, df=6)[3] 1.5, 94% HDI [1.4, 1.7]
bs(x, df=6)[4] 0.87, 94% HDI [0.53, 1.2]
bs(x, df=6)[5] 0.32, 94% HDI [0.1, 0.54]
We can get nicely formatted tables from our integration with the maketables package.
from maketables import ETable
result.set_maketables_options(hdi_prob=0.95)
ETable(result, coef_fmt="b:.3f \n [ci95l:.3f, ci95u:.3f]")
| y | |
|---|---|
| (1) | |
| coef | |
| treated=True | 0.514 [0.344, 0.680] |
| bs(x, df=6)=0 | -0.412 [-0.603, -0.206] |
| bs(x, df=6)=1 | -1.421 [-1.575, -1.262] |
| bs(x, df=6)=2 | 0.259 [0.100, 0.419] |
| bs(x, df=6)=3 | 1.505 [1.353, 1.665] |
| bs(x, df=6)=4 | 0.868 [0.534, 1.251] |
| bs(x, df=6)=5 | 0.322 [0.083, 0.540] |
| Intercept | -0.160 [-0.267, -0.063] |
| stats | |
| N | 100 |
| Bayesian R2 | 0.984 |
| Format of coefficient cell: Coefficient [95% CI Lower, 95% CI Upper] | |
Effect Summary Reporting#
For decision-making, you often need a concise summary of the causal effect. The effect_summary() method provides a decision-ready report with key statistics. Note that for Regression Discontinuity, the effect is a single scalar (the discontinuity at the threshold), similar to Difference-in-Differences.
# Generate effect summary
stats = result.effect_summary()
stats.table
| mean | median | hdi_lower | hdi_upper | p_gt_0 | |
|---|---|---|---|---|---|
| discontinuity | 0.5139 | 0.514928 | 0.345544 | 0.678658 | 1.0 |
print(stats.text)
The discontinuity at threshold was 0.51 (95% HDI [0.35, 0.68]). The posterior probability of an increase is 1.000.
You can customize the summary with different directions and ROPE thresholds:
Direction: Test for increase, decrease, or two-sided effect
Alpha: Set the HDI confidence level (default 95%)
ROPE: Specify a minimal effect size threshold
# Example: Two-sided test with ROPE
stats = result.effect_summary(
direction="two-sided",
alpha=0.05,
min_effect=0.2, # Region of Practical Equivalence
)
stats.table
| mean | median | hdi_lower | hdi_upper | p_two_sided | prob_of_effect | p_rope | |
|---|---|---|---|---|---|---|---|
| discontinuity | 0.5139 | 0.514928 | 0.345544 | 0.678658 | 0.0 | 1.0 | 0.99975 |
print("\n" + stats.text)
The discontinuity at threshold was 0.51 (95% HDI [0.35, 0.68]). The posterior two-sided tail probability is 0.000. Using the closed ROPE [-0.2, 0.2], the 95% HDI is entirely outside the ROPE; the effect is practically significant. Posterior mass is 0.000 below, 0.000 inside, and 1.000 above the ROPE.
Sensitivity analysis#
This section walks through the Regression discontinuity design sensitivity diagnostics that ship with the pipeline API (EstimateEffect → SensitivityAnalysis → GenerateReport). For the shared workflow concepts—Pipeline, pluggable checks, and HTML reports—see Pipeline Workflow. For the matrix of which checks apply to which experiment type, see Sensitivity Checks in Pipeline Workflows.
Walkthrough#
Fit a baseline model so you have a reference effect estimate (the linear interaction model fitted at the top of this notebook plays that role).
Run the pipeline cell below. It refits the experiment using
cp.RegressionDiscontinuityinsideEstimateEffect, then runs bothBandwidthSensitivityandMcCraryDensityTest. EachCheckResultexposestext(a human-readable verdict), an optionaltable(per-bandwidth estimates or density counts), andmetadata.Inspect the per-check tables to compare the discontinuity estimate across bandwidths and to read off the McCrary statistic and p-value.
Open the HTML report (iframe below) for a consolidated view alongside the main estimate.
Note
The bandwidth sweep starts at 0.2 because the 0.1 window has too few observations for a reliable Bayesian fit. It holds the revised coefficient prior fixed across refits. The bandwidth sweep below uses the centered linear interaction model y ~ 1 + I(x - 0.5) * treated rather than the basis-spline specification. This is intentional: when basis splines like bs(x, df=6) are fit on the full data, the knot positions are baked in and patsy raises an error if a narrower bandwidth subset asks the model to evaluate observations that are inside the bandwidth window but where some training rows would now sit outside the original outer knots. The linear interaction formula has no such constraint and is the most common reference specification for bandwidth sensitivity studies in any case.
sensitivity_result = cp.Pipeline(
data=df,
steps=[
cp.EstimateEffect(
method=cp.RegressionDiscontinuity,
formula="y ~ 1 + I(x - 0.5) * treated",
model=cp.pymc_models.LinearRegression(
priors=rd_priors,
sample_kwargs={"random_seed": seed, "target_accept": 0.95},
),
treatment_threshold=0.5,
),
cp.SensitivityAnalysis(
checks=[
cp.checks.BandwidthSensitivity(bandwidths=[0.2, 0.3, 0.5, 1.0]),
cp.checks.McCraryDensityTest(n_bins=20),
],
),
cp.GenerateReport(include_plots=True),
],
).run()
for cr in sensitivity_result.sensitivity_results:
print(f"[{cr.check_name}] {cr.text}")
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 1 seconds.
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [y_hat]
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
[BandwidthSensitivity] Bandwidth sensitivity analysis: compared 4 bandwidth values. Examine the table for consistency of effect estimates across bandwidths.
[McCraryDensityTest] McCrary density test: possible manipulation detected at threshold 0.5 (z=8.785, p=0.000). Observations below: 83, above: 17.
import html as html_module
import warnings
from IPython.display import HTML
with warnings.catch_warnings():
warnings.filterwarnings(
"ignore", "Consider using IPython.display.IFrame", UserWarning
)
display(
HTML(
f'<iframe srcdoc="{html_module.escape(sensitivity_result.report)}" '
f'width="100%" height="600" style="border:1px solid #ccc;"></iframe>'
)
)
Interpreting pass and fail#
BandwidthSensitivity is informational (passed=None): it returns a table of estimates rather than a binary verdict. Read the column of effect estimates and HDIs across bandwidths and ask:
Are the point estimates broadly consistent in sign and magnitude across plausible bandwidths?
Do the HDIs overlap substantially?
Does the estimate flip or change order of magnitude at extreme bandwidths only, or also at moderate ones?
A result that is stable across moderate bandwidths is more credible than one that depends on a single narrow window.
McCraryDensityTest returns a binary verdict. It passes when the counts of observations on each side of the threshold are consistent with a smooth density at the conventional significance level (default alpha=0.05). It fails when the proportions differ enough to suggest sorting around the threshold. In either case, treat the verdict as a screening signal rather than a definitive answer; the test in CausalPy is histogram-based and does not implement the local-polynomial density estimator from [McCrary, 2008] exactly.
Important
On the built-in rd dataset the McCrary check fails simply because the running variable is generated on [-1, 1] while the threshold sits at 0.5. The histogram-based test reads the resulting global imbalance as a discontinuity even though no manipulation occurred. Real diagnostics should be paired with knowledge of the data-generating process: if you know assignment is exogenous, a McCrary failure may reflect asymmetric ranges of the running variable rather than sorting. When manipulation is plausible, follow up with a donut RD design.
If these checks fail#
Concrete steps when one or both checks raise concerns:
Bandwidth dependence. If the estimate changes sign or magnitude across bandwidths, plot the running variable and outcome together and look for non-linear structure away from the threshold that the model is absorbing. Try a richer functional form (basis splines, see Using basis splines above) or restrict to a more local bandwidth and report both.
Sparse data near the threshold. A narrow bandwidth with very few observations gives noisy estimates regardless of design quality. The
BandwidthSensitivityrows surface this directly via missing or very wide HDIs. Consider whether the design supports a wider effective window.Density discontinuity. A failed
McCraryDensityTestsuggests possible manipulation of the running variable. Investigate the data-generating process: are units close to the threshold able to influence their own assignment? When manipulation is plausible, a donut RD design that excludes observations immediately around the threshold is a standard robustness response.Compare under alternative priors with
PriorSensitivity. If both diagnostics raise concerns, re-fitting under tighter or more diffuse priors helps separate prior-data conflict from genuine design weakness.
See also
Sensitivity Checks in Pipeline Workflows — full check matrix and interpretation guidance
Pipeline Workflow — end-to-end pipeline tutorial
HTML Report Generation — HTML report generation
Donut Regression Discontinuity — donut RDD as a robustness response to suspected manipulation