Estimating excess deaths during COVID-19 in England and Wales#

This interrupted time series uses monthly deaths in England and Wales to estimate the difference from a modelled counterfactual path during the COVID-19 pandemic. We keep deaths in their original count units: before fitting to pre-2020 data, we check whether the default priors generate plausible monthly counts, revise them, and check again. Interpreting the post-2020 difference as caused by COVID-19 requires the counterfactual trend and absence of other relevant changes to be credible.

import matplotlib.pyplot as plt
import pandas as pd
from pymc_extras.prior import Prior

import causalpy as cp
%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'

Load data#

df = (
    cp.load_data("covid")
    .assign(date=lambda x: pd.to_datetime(x["date"]))
    .set_index("date")
)

treatment_time = pd.to_datetime("2020-01-01")
df.head()
temp deaths year month t pre
date
2006-01-01 3.8 49124 2006 1 0 True
2006-02-01 3.4 42664 2006 2 1 True
2006-03-01 3.9 49207 2006 3 2 True
2006-04-01 7.4 40645 2006 4 3 True
2006-05-01 10.7 42425 2006 5 4 True

The date is the time index. deaths is the monthly count, t is elapsed months, month is a seasonal category, and temp is temperature in °C. The data also contain year and a pre indicator. We choose 1 January 2020 as the analysis boundary between fitting and comparison periods; it is not a verified onset date for a single intervention. Every later deviation from the modelled baseline enters the comparison, whatever its cause.

Model 1: Bayesian linear regression#

Build the experiment#

The formula keeps deaths, elapsed months, and temperature in their original units. Each month gets its own baseline coefficient; the trend and temperature coefficients therefore need priors on different scales. Constructing an experiment prepares its design matrices but does not sample a posterior, so we can inspect prior predictions before committing to a fit.

seed = 42
formula = "deaths ~ 0 + C(month) + t + temp"
model = cp.pymc_models.LinearRegression(sample_kwargs={"random_seed": seed})
experiment = cp.InterruptedTimeSeries(
    df,
    treatment_time,
    formula=formula,
    model=model,
)
print(f"Posterior fitted: {experiment.is_fitted}")
print(f"Coefficients: {experiment.labels}")
Posterior fitted: False
Coefficients: ['C(month)[1]', 'C(month)[2]', 'C(month)[3]', 'C(month)[4]', 'C(month)[5]', 'C(month)[6]', 'C(month)[7]', 'C(month)[8]', 'C(month)[9]', 'C(month)[10]', 'C(month)[11]', 'C(month)[12]', 't', 'temp']

Check the default prior predictive#

The default LinearRegression priors put every coefficient near zero (Normal(0, 50)) and give residual noise a HalfNormal(1) scale. With deaths measured in tens of thousands, those priors imply implausibly small monthly counts. Sampling the prior phase produces draws before posterior fitting; plot(group="prior") compares prior-implied expected counterfactual paths with observed deaths. Use the pre-2020 observations to judge the scale. Later observations are shown for orientation, but should not be used to tune priors for this counterfactual analysis.

experiment.sample_prior_predictive(random_seed=seed)
fig, ax = experiment.plot(group="prior", figsize=(9, 4), show=False)
ax[0].set(title="Default prior: expected monthly deaths", ylabel="Monthly deaths")
plt.show()
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
../_images/bedeebbd652ed656f69032dbb2625390f416faebab039a3bcc1f756c9e7cc87d.png

The default expected path sits far below the observed pre-2020 death counts. That is a prior-scale problem, not evidence from a fitted posterior. We will replace the model with coefficient-specific priors expressed in deaths, deaths per month, and deaths per degree Celsius.

Revise the priors and check again#

With this formula, each month coefficient is the expected death count at t=0 and temp=0, before adding trend and temperature terms. We center those intercepts at 45,000 with a standard deviation of 8,000. The trend prior is Normal(0, 30) deaths per month and the temperature prior is Normal(0, 300) deaths per °C. Residual variation gets a HalfNormal(3,000) prior. These broad starting assumptions use the pre-2020 scale; they are not fitted to post-2020 outcomes. Assigning a fresh model clears the first prior draw set.

prior_specs = {
    "t": (0, 30),
    "temp": (0, 300),
}
prior_specs.update(
    {name: (45_000, 8_000) for name in experiment.labels if name.startswith("C(month)")}
)
beta_mu = [prior_specs[name][0] for name in experiment.labels]
beta_sigma = [prior_specs[name][1] for name in experiment.labels]

experiment.model = cp.pymc_models.LinearRegression(
    sample_kwargs={"random_seed": seed},
    priors={
        "beta": Prior(
            "Normal",
            mu=beta_mu,
            sigma=beta_sigma,
            dims=["treated_units", "coeffs"],
        ),
        "y_hat": Prior(
            "Normal",
            sigma=Prior("HalfNormal", sigma=3_000, dims=["treated_units"]),
            dims=["obs_ind", "treated_units"],
        ),
    },
)
print(f"Prior sampled after model replacement: {experiment.has_prior_predictive}")
Prior sampled after model replacement: False
experiment.sample_prior_predictive(random_seed=seed)
fig, ax = experiment.plot(group="prior", figsize=(9, 4), show=False)
ax[0].set(title="Revised prior: expected monthly deaths", ylabel="Monthly deaths")
plt.show()
Sampling: [beta, y_hat, y_hat_sigma]
Sampling: [y_hat]
Sampling: [y_hat]
../_images/2e2cca8a75f57307e74d6adfa022d432a1f44f6f14d99ecd1e21fa607494b67b.png

The revised expected-path band spans the scale of the pre-2020 observations instead of sitting near zero. This is a coarse check of the coefficient priors in death-count units: the built-in plot shows uncertainty in the mean path mu, not the observation-level noise prior. It does not validate the seasonal model or post-2020 extrapolation. Pre-2020 observations informed this revision; post-2020 outcomes were not used to tune the priors.

Fit and inspect the posterior#

The prior checks establish a plausible count scale, so we can now call fit() to sample the posterior using pre-2020 data. Whether the fitted relationship remains a credible counterfactual after 2020 is a separate assumption.

experiment.fit()
fig, axes = experiment.plot(show=False)
axes[0].set_ylabel("Monthly deaths")
axes[1].set(title="Observed minus modelled counterfactual", ylabel="Deaths")
axes[2].set(title="Cumulative observed minus modelled counterfactual", ylabel="Deaths")
for label in axes[0].get_legend().get_texts():
    if label.get_text() == "Causal impact":
        label.set_text("Modelled difference")
plt.show()
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]
../_images/3fb1a0dde44dc6cb6c6faddadda061168cd76252a95af8cf9337bd9cc295bc67.png

The top panel compares observed deaths with the fitted pre-2020 path and its extrapolation. The lower panels show observed deaths minus that modelled counterfactual, then the cumulative difference. These differences depend on the chosen trend, seasonality, temperature adjustment, priors, and continuation of the pre-2020 relationship. The panels do not independently identify deaths caused by COVID-19.

experiment.summary()
==================================Pre-Post Fit==================================
Formula: deaths ~ 0 + C(month) + t + temp
Model coefficients:
  C(month)[1]   52442, 94% HDI [50842, 54224]
  C(month)[2]   43936, 94% HDI [42217, 45611]
  C(month)[3]   46048, 94% HDI [44242, 47845]
  C(month)[4]   44396, 94% HDI [42163, 46527]
  C(month)[5]   43635, 94% HDI [40824, 46263]
  C(month)[6]   43085, 94% HDI [39954, 46272]
  C(month)[7]   43831, 94% HDI [40178, 47385]
  C(month)[8]   42005, 94% HDI [38654, 45534]
  C(month)[9]   42040, 94% HDI [39002, 45159]
  C(month)[10]  44127, 94% HDI [41504, 46707]
  C(month)[11]  42967, 94% HDI [41012, 44921]
  C(month)[12]  45232, 94% HDI [43488, 46899]
  t             22, 94% HDI [15, 30]
  temp          -411, 94% HDI [-640, -201]

Summarize the estimated effect#

The effect_summary() method reports average and cumulative post-2020 differences in deaths, uncertainty intervals, posterior probabilities, and relative differences against the count-scale counterfactual. The table describes all deviations from the extrapolated baseline after our chosen boundary; it is not a direct count of deaths caused solely by COVID-19.

stats = experiment.effect_summary()
stats.table
mean median hdi_lower hdi_upper p_gt_0 relative_mean relative_hdi_lower relative_hdi_upper
average 4433.772029 4423.046628 3483.210373 5346.405413 1.0 9.837796 7.559911 12.092777
cumulative 128579.388831 128268.352201 101013.100804 155045.756968 1.0 9.837796 7.559911 12.092777

Across January 2020 to May 2022, observed deaths averaged about 49,558 per month, compared with a modelled counterfactual of 45,124. The estimated average difference is 4,434 deaths per month (95% interval 3,483 to 5,346), or about 9.8% of the count-scale counterfactual; the cumulative difference is about 128,579 deaths. The reported p_gt_0 is close to 1: posterior draws overwhelmingly favor a positive average difference under this model. The coefficient summary above uses CausalPy’s 94% HDI default, while effect_summary() uses a 95% interval from its default alpha=0.05.

stats_window = experiment.effect_summary(
    window=(pd.to_datetime("2020-01-01"), pd.to_datetime("2020-06-30"))
)
stats_window.table
mean median hdi_lower hdi_upper p_gt_0 relative_mean relative_hdi_lower relative_hdi_upper
average 9576.376874 9558.351152 8570.377039 10487.732925 1.0 20.851539 18.249552 23.282911
cumulative 57458.261243 57350.106912 51422.262236 62926.397549 1.0 20.851539 18.249552 23.282911

For January to June 2020, the estimated average difference is about 9,576 deaths per month (95% interval 8,570 to 10,488), larger than the average across the full comparison period. The window includes every deviation from the modelled baseline during those months, whatever its cause. Both estimates depend on the extrapolated pre-2020 relationship.

Model 2: Bayesian structural time series with pymc-forecast#

Mortality has annual patterns, gradual demographic changes, and shocks that can persist across months. We can express these mechanisms in a Bayesian structural time-series model: a changing level and slope, monthly seasonal effects, temperature regression, and an autoregressive deviation. The existing PyMCForecastModel wrapper lets this generative model supply CausalPy’s counterfactual.

Install the optional dependency before running this section:

python -m pip install "causalpy[forecast]"

The distribution is named pymc-forecast and the import is pymc_forecast. CausalPy uses its 0.3 release line here. The January 2020 analysis boundary and original death-count outcome remain unchanged.

from functools import partial

import arviz as az
import numpy as np
import preliz as pz
import pymc as pm
import pymc_forecast as pf
import pytensor.tensor as pt
from arviz_stats import hdi
from IPython.display import display
from matplotlib.dates import DateFormatter
from matplotlib.ticker import MaxNLocator, StrMethodFormatter
from pytensor import scan

from causalpy.pymc_forecast_models import PyMCForecastModel

FIG_WIDTH = 9
FIG_HEIGHT = 4
COLOR_FORECAST = "C1"
COLOR_OBSERVED = "black"
COLOR_REGRESSION = "C0"
COLOR_RESIDUAL_PRIOR = "C2"

Combine a damped trend, seasonality, regression, and persistence#

The expected monthly count is

\[ \mu_t = \ell_t + s_{m(t)} + \beta_{\mathrm{temp}}\,T_t + r_t. \]

A local linear trend already allows historical curvature: both its level and its slope change through random innovations. Its extrapolation assumption is stronger than it first appears, however. In expectation, the latest slope continues indefinitely. A damped stochastic slope gradually shrinks that inherited growth or decline:

\[ b_t = \phi b_{t-1} + \sigma_b z_{b,t}, \qquad \ell_t = \ell_{t-1} + b_t + \sigma_\ell z_{\ell,t}, \qquad \phi \sim \operatorname{Beta}(20,2). \]

The innovations are independent standard Normals. With \(\phi=1\) this becomes the undamped local linear trend; with \(0<\phi<1\), the influence of the last fitted slope decays. Damping can stabilize long forecasts, but can also understate sustained demographic growth. We compare these assumptions on historical holdouts below; improvement is not guaranteed.

Twelve sum-zero month effects \(s_{m(t)}\) capture a fixed annual pattern. The AR(1) deviation follows \(r_t=\rho r_{t-1}+\sigma_r z_{r,t}\) with \(|\rho|<0.95\), so a short-term shock decays rather than permanently shifting the baseline. The AR deviation and the damped slope describe different mechanisms, but can still be weakly distinguished by this dataset.

innovations() creates separate fitted and future trend innovations. A deterministic scan propagates the damped slope through the fitted history and the fresh future innovations. markov_series() handles the AR recursion. Forecasts continue from each posterior draw’s fitted state without feeding later observed deaths into the baseline. Random transition parameters are explicit in non_sequences or params.

The initial level prior is Normal(45,000, 8,000) deaths and the initial slope prior is Normal(0, 30) deaths per month. Level and slope innovation standard deviations have HalfNormal(100) and HalfNormal(2) priors, respectively. Month effects have a sum-zero Normal prior with scale 5,000 deaths; the temperature coefficient has a Normal(0, 300) prior in deaths per °C. AR innovations have a LogNormal(log(1,000), 0.5) scale prior in deaths, \(\rho\) has a Normal(0.5, 0.2) prior truncated to (-0.95, 0.95), and observation noise has a HalfNormal(3,000) prior. The damping prior favors persistence while allowing its influence to decay. These fixed, regularizing priors use the historical count scale; no full-series centering, normalization, or post-2020 tuning is applied.

def mortality_forecast(covariates, data=None, *, damped=False):
    h = pf.Horizon.from_data(covariates, data)
    initial_level = pm.Normal("initial_level", mu=45_000, sigma=8_000)
    initial_slope = pm.Normal("initial_slope", mu=0, sigma=30)
    level_scale = pm.HalfNormal("level_scale", sigma=100)
    slope_scale = pm.HalfNormal("slope_scale", sigma=2)
    level_z = pf.innovations(h, "level_z", pm.Normal.dist(0, 1))
    slope_z = pf.innovations(h, "slope_z", pm.Normal.dist(0, 1))
    if damped:
        damping = pm.Beta("damping", alpha=20, beta=2)
        slope = scan(
            fn=lambda innovation, previous, damping, scale: (
                damping * previous + scale * innovation
            ),
            sequences=[slope_z],
            outputs_info=[initial_slope],
            non_sequences=[damping, slope_scale],
            strict=True,
            return_updates=False,
        )
    else:
        slope = initial_slope + slope_scale * pt.cumsum(slope_z)
    level = initial_level + pt.cumsum(slope) + level_scale * pt.cumsum(level_z)

    pm.modelcontext(None).add_coord("month_of_year", np.arange(1, 13))
    month_effect = pm.ZeroSumNormal("month_effect", sigma=5_000, dims="month_of_year")
    month_index = pd.DatetimeIndex(covariates.time.values).month.to_numpy() - 1
    beta_temp = pm.Normal("beta_temp", mu=0, sigma=300)
    temperature = covariates.sel(covariate="temp").values

    rho = pm.TruncatedNormal("rho", mu=0.5, sigma=0.2, lower=-0.95, upper=0.95)
    ar_scale = pm.LogNormal("ar_scale", mu=np.log(1_000), sigma=0.5)
    ar_initial = pm.Normal("ar_initial", mu=0, sigma=1 / pt.sqrt(1 - rho**2))
    ar_z = pf.markov_series(
        h,
        "ar_z",
        ar_initial,
        lambda previous, rho: pm.Normal.dist(rho * previous, 1),
        params=(rho,),
    )
    expected_deaths = (
        level + month_effect[month_index] + beta_temp * temperature + ar_scale * ar_z
    )
    observation_scale = pm.HalfNormal("observation_scale", sigma=3_000)
    pf.predict(
        h,
        pm.Normal.dist(0, observation_scale),
        expected_deaths,
        expected_observation=expected_deaths,
    )


damped_mortality_forecast = partial(mortality_forecast, damped=True)

The standardized AR state is multiplied by ar_scale, so its stationary initial standard deviation in deaths is ar_scale / sqrt(1 - rho**2). Noncentered trend innovations separate their standardized paths from their scales. The AR priors favor short-lived positive persistence and scales around 1,000 deaths, regularizing the weak distinction between AR variation and observation noise. These choices followed training-period sampling diagnostics; the held-out forecasts below are internal validation after that development, not an untouched external test. The Gaussian identity-link likelihood approximates large monthly counts; it does not enforce nonnegative integer observations.

Passing expected_observation= explicitly tells the wrapper which death-count expectation to use for impacts. CausalPy exposes it as canonical mu and retains noisy observations separately as y_hat. For a linked likelihood, the explicit expectation would need the inverse link. See Prediction contract for causal impact.

Note

This forecasting backend does not support CausalPy’s sample_prior_predictive() method or design-matrix coefficient summaries. Instead, the next section samples the structural model’s priors directly with pf.build_model() and pm.sample_prior_predictive() before fitting any outcomes. The latent-state model uses the supported HMCForecaster; StatespaceForecaster remains unsupported because it does not yet expose the separate expected-observation output required for impacts.

Inspect the structural priors with PreliZ#

Before fitting, ask what each prior implies in monthly death-count units. PreliZ lets us inspect the distributions and their quantiles. The definitions below mirror the fixed priors in mortality_forecast; if you change that specification, update these displays as well. They are illustrations of those priors, not additional priors passed to the model.

The initial level is centered at 45,000 deaths with an 8,000-death standard deviation. It is a baseline before the first trend update and before temperature, seasonality and AR contributions: it is not the marginal prior mean of every monthly count. The initial slope is centered at zero with a 30-death-per-month standard deviation. level_scale controls fresh monthly level changes; slope_scale controls fresh changes in the slope. Their HalfNormal parameters set the width of a distribution over scales, rather than fixing either scale.

For the damped model, damping multiplies the inherited slope each month. Without fresh slope innovations, its contribution after \(k\) months is \(\phi^k b_0\). The Beta(20, 2) prior favors persistence below one; damping does not remove uncertainty from new innovations. The temperature coefficient allows either sign, with a 300-death-per-degree standard deviation. Temperature uses the dataset’s native °C scale, so this contribution is measured relative to 0 °C.

Hide code cell source
trend_priors = {
    "initial_level": (pz.Normal(mu=45_000, sigma=8_000), "Baseline deaths"),
    "initial_slope": (pz.Normal(mu=0, sigma=30), "Deaths per month"),
    "level_scale": (pz.HalfNormal(sigma=100), "Deaths"),
    "slope_scale": (pz.HalfNormal(sigma=2), "Deaths per month"),
    "damping": (pz.Beta(alpha=20, beta=2), "Monthly slope multiplier"),
    "beta_temp": (pz.Normal(mu=0, sigma=300), "Deaths per °C"),
}

fig, axes = plt.subplots(3, 2, figsize=(FIG_WIDTH, 2.5 * FIG_HEIGHT))
for ax, (name, (prior, units)) in zip(axes.flat, trend_priors.items(), strict=True):
    prior.plot_pdf(ax=ax, color=COLOR_FORECAST, legend=None)
    lower, upper = prior.ppf([0.03, 0.97])
    x = np.linspace(lower, upper, 300)
    ax.fill_between(x, 0, prior.pdf(x), color=COLOR_FORECAST, alpha=0.2)
    ax.set(title=name, xlabel=units, ylabel="Prior density")
    ax.xaxis.set_major_locator(MaxNLocator(4))
    ax.xaxis.set_major_formatter(
        StrMethodFormatter(
            "{x:,.2f}"
            if units in {"AR coefficient", "Monthly slope multiplier"}
            else "{x:,.0f}"
        )
    )
fig.tight_layout()
plt.show()
../_images/7878f121221a83b728f6b46c1636bbd3e1f2a8caef9af4f443fcfaa3a74fba0e.png

The orange curves are the scalar trend and temperature prior densities; shading marks each central 94% equal-tailed interval. These are parameter distributions, not predictive intervals for deaths. In particular, a small slope innovation scale can accumulate into substantial uncertainty over many years.

Hide code cell source
residual_priors = {
    "month_effect (one month's marginal)": (
        pz.Normal(mu=0, sigma=5_000 * np.sqrt(11 / 12)),
        "Deaths",
    ),
    "rho": (
        pz.TruncatedNormal(mu=0.5, sigma=0.2, lower=-0.95, upper=0.95),
        "AR coefficient",
    ),
    "ar_scale": (pz.LogNormal(mu=np.log(1_000), sigma=0.5), "Deaths"),
    "observation_scale": (pz.HalfNormal(sigma=3_000), "Deaths"),
}

fig, axes = plt.subplots(2, 2, figsize=(FIG_WIDTH, 1.8 * FIG_HEIGHT))
for ax, (name, (prior, units)) in zip(axes.flat, residual_priors.items(), strict=True):
    prior.plot_pdf(ax=ax, color=COLOR_RESIDUAL_PRIOR, legend=None)
    lower, upper = prior.ppf([0.03, 0.97])
    x = np.linspace(lower, upper, 300)
    ax.fill_between(x, 0, prior.pdf(x), color=COLOR_RESIDUAL_PRIOR, alpha=0.2)
    ax.set(title=name, xlabel=units, ylabel="Prior density")
    ax.xaxis.set_major_locator(MaxNLocator(4))
    ax.xaxis.set_major_formatter(
        StrMethodFormatter(
            "{x:,.2f}"
            if units in {"AR coefficient", "Monthly slope multiplier"}
            else "{x:,.0f}"
        )
    )
fig.tight_layout()
plt.show()
../_images/a3059681a23922644f1796b6c0df6008640954ee7ba02bc8dac661076ddd4cef.png

The green curves show the remaining scalar marginals, again with central 94% equal-tailed intervals. The 12 seasonal effects jointly sum to zero. Their displayed marginal standard deviation is \(5{,}000\sqrt{11/12}\); they are correlated, not 12 independent Normal draws. rho favors positive persistence but permits negative values, with truncation keeping \(|\rho|<0.95\). The median of ar_scale is 1,000 deaths; it is not the stationary AR standard deviation, which also depends on rho. observation_scale has a HalfNormal prior with scale 3,000 deaths, rather than being fixed at 3,000.

The standardized AR initial state is conditional on rho, with standard deviation \(1/\sqrt{1-\rho^2}\). The joint predictive simulation below respects that dependency, the seasonal constraint and all the latent innovations; marginal density plots alone cannot check their combined consequences.

Generate prior predictive mortality paths#

Now combine these priors using the same damped mortality_forecast function that we will fit below. Passing data=None leaves the death observations unconditioned. We supply only pre-2020 dates and temperatures, then call PyMC’s prior predictive sampler. No posterior sampler is involved and no death observations are passed into this model.

expected_observation is the expected death count including the latent trend, seasonality, temperature and AR contribution. obs additionally includes independent observation noise. Because this model has no observed outcome variable, PyMC stores both in the prior group.

prior_frame = df.loc[df.index < treatment_time].rename_axis("time")
prior_model = pf.build_model(
    damped_mortality_forecast,
    data=None,
    covariates=prior_frame[["temp"]],
)
with prior_model:
    structural_prior = pm.sample_prior_predictive(draws=1_000, random_seed=seed)

prior_paths = structural_prior.prior
print(f"Observed outcome variables in prior model: {len(prior_model.observed_RVs)}")
print(f"Prior draws: {prior_paths.sizes['draw']:,}")
/Users/benjamv/.codex/worktrees/0c14/CausalPy-worktrees/issue-1258/.venv/lib/python3.12/site-packages/pytensor/link/numba/dispatch/basic.py:234: UserWarning: Numba will use object mode to run truncated_normal_rv{"(),(),(),()->()"}'s perform method. Set `pytensor.config.compiler_verbose = True` to see more details.
Sampling: [ar_initial, ar_scale, ar_z, beta_temp, damping, initial_level, initial_slope, level_scale, level_z, month_effect, obs, observation_scale, rho, slope_scale, slope_z]
Observed outcome variables in prior model: 0
Prior draws: 1,000
Hide code cell source
fig, ax = plt.subplots(figsize=(FIG_WIDTH, FIG_HEIGHT))
draws = prior_paths["expected_observation"]
interval = hdi(draws, prob=0.94, dim=["chain", "draw"])
ax.fill_between(
    prior_frame.index,
    interval.sel(ci_bound="lower"),
    interval.sel(ci_bound="upper"),
    color=COLOR_FORECAST,
    alpha=0.2,
    label="94% pointwise prior HDI",
)
for draw in range(6):
    ax.plot(
        prior_frame.index,
        draws.isel(chain=0, draw=draw),
        color=COLOR_FORECAST,
        alpha=0.35,
        linewidth=0.8,
        label="Example prior paths" if draw == 0 else None,
    )
ax.plot(
    prior_frame.index,
    draws.mean(["chain", "draw"]),
    color=COLOR_FORECAST,
    label="Prior mean",
)
ax.scatter(
    prior_frame.index,
    prior_frame["deaths"],
    color=COLOR_OBSERVED,
    s=8,
    label="Pre-2020 observed deaths",
)
ax.axhline(0, color="0.6", linewidth=0.8, linestyle=":")
ax.set(
    title="Prior expected monthly deaths",
    ylabel="Monthly deaths (count)",
    xlabel="Date",
)
ax.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
ax.xaxis.set_major_formatter(DateFormatter("%Y"))
ax.legend(loc="upper left", fontsize="small")
fig.tight_layout()
plt.show()
../_images/8531e5933a87788d1980e553c53108ae5d0ca4d0fa9f373797f32b8a584e4f21.png

Caption: Prior expected monthly deaths across the pre-2020 covariate history. The orange line shows the prior mean, shading marks the 94% pointwise highest-density interval (HDI), and six thin orange lines show joint prior paths. Black points provide an observed reference on the same count scale and were not used to condition these draws. The band excludes independent observation noise and is not a 94% simultaneous band for an entire path.

Individual paths reveal seasonal and time-varying behavior even though the prior mean is nearly flat. Inspect both the scale and the behavior: do simulated levels resemble plausible national monthly totals, are winter-to-summer differences credible, and does uncertainty grow reasonably with elapsed time? A wide band covering the observations is not sufficient evidence of a good prior. The Gaussian likelihood can generate negative counts, so the following check uses the sampled noisy observations (obs) to measure how much prior predictive mass falls below zero.

negative_fraction = float((prior_paths["obs"] < 0).mean())
mean_monthly_deaths = prior_paths["expected_observation"].mean("time")
mean_count_interval = mean_monthly_deaths.quantile([0.03, 0.97], dim=["chain", "draw"])
print(
    f"Negative prior predictive observations: {negative_fraction:.1%} of draw-month pairs"
)
print(
    "Central 94% prior interval for the time-averaged expected monthly count: "
    f"{float(mean_count_interval.isel(quantile=0)):,.0f} to "
    f"{float(mean_count_interval.isel(quantile=1)):,.0f} deaths"
)
Negative prior predictive observations: 0.0% of draw-month pairs
Central 94% prior interval for the time-averaged expected monthly count: 29,326 to 60,931 deaths

The simulated levels are on the scale of national monthly totals, but the bands are broad: the initial-level and seasonal priors allow much more variation than the typical observed fluctuations. The printed negative fraction is a finite Monte Carlo estimate over these dates and covariates, not a guarantee that negative counts are impossible. This check exposes the implications of the specification; it does not certify the model or identify a COVID-19 effect.

If the implied levels, negative-count mass or long-run variation conflict with domain knowledge, revise the relevant priors or likelihood and repeat this simulation before inspecting held-out outcomes. We retain the stated specification here and next assess its forecasts using historical pre-2020 holdouts.

Compare extrapolation assumptions before the pandemic#

A flexible state model can improve in-sample fit without improving extrapolation. We compare the undamped and damped specifications with two expanding-window forecasts, both matching the final 29-month horizon. The first trains on January 2006–December 2014 and forecasts January 2015–May 2017; the second trains through December 2016 and forecasts January 2017–May 2019. pf.backtest() refits each fixed specification on each training prefix and forecasts recursively. Within a fold, held-out deaths enter only the evaluation.

The holdouts overlap by five months and were available during model development. These are internal, descriptive checks rather than independent tests or an untouched model-selection dataset. Both specifications retain identical priors, seasonal effects, AR dynamics, and temperature treatment; damping is the sole structural difference.

Temperature remains in its native units and is supplied as a known weather scenario throughout each holdout. The final ITS comparison similarly conditions on recorded post-2020 temperature, assuming that using it does not import a consequence of the pandemic into the untreated scenario. This is conditional forecasting, rather than a forecast of unknown future weather.

Each validation fit uses two chains, 1,000 tuning steps and 500 retained draws per chain, with 500 draws used for prediction. Inspect the retained sampling logs for convergence or divergence warnings; this smaller budget is a demonstration, not a thorough calibration study. The final damped fit below uses four chains and 1,000 retained draws per chain.

pre_frame = df.loc[df.index < treatment_time].rename_axis("time")
validation_results = {
    name: pf.backtest(
        pre_frame["deaths"],
        pre_frame[["temp"]],
        model_fn,
        forecaster_cls=pf.HMCForecaster,
        min_train_window=108,
        test_window=29,
        min_test_window=29,
        stride=24,
        num_samples=500,
        forecaster_options={
            "chains": 2,
            "draws": 500,
            "tune": 1_000,
            "progressbar": False,
            "sample_kwargs": {"target_accept": 0.99},
        },
        metrics={
            "MAE": pf.eval_mae,
            "RMSE": pf.eval_rmse,
            "94% coverage": partial(pf.eval_coverage, alpha=0.94),
            "Interval score": partial(pf.eval_interval_score, alpha=0.94),
        },
        keep_predictions=True,
        random_seed=seed,
    )
    for name, model_fn in {
        "Undamped": mortality_forecast,
        "Damped": damped_mortality_forecast,
    }.items()
}
Hide code cell output
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 2 chains for 1_000 tune and 500 draw iterations (2_000 + 1_000 draws total) took 8 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 2 chains for 1_000 tune and 500 draw iterations (2_000 + 1_000 draws total) took 11 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 2 chains for 1_000 tune and 500 draw iterations (2_000 + 1_000 draws total) took 18 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 2 chains for 1_000 tune and 500 draw iterations (2_000 + 1_000 draws total) took 20 seconds.
We recommend running at least 4 chains for robust computation of convergence diagnostics
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
validation_rows = []
for model_name, folds in validation_results.items():
    for fold in folds:
        samples = fold.prediction.transpose("chain", "draw", "time_future").values
        samples = samples.reshape(-1, fold.t2 - fold.t1)
        observed = pre_frame.deaths.iloc[fold.t1 : fold.t2].to_numpy()
        lower, upper = np.quantile(samples, [0.03, 0.97], axis=0)
        validation_rows.append(
            {
                "Model": model_name,
                "Holdout start": pre_frame.index[fold.t1].strftime("%Y-%m"),
                **fold.metrics,
                "Mean difference": float((observed - samples.mean(axis=0)).mean()),
                "94% width": float((upper - lower).mean()),
            }
        )
validation_table = pd.DataFrame(validation_rows).set_index(["Model", "Holdout start"])
validation_table[
    ["MAE", "RMSE", "Mean difference", "94% coverage", "94% width", "Interval score"]
].style.format("{:,.0f}").format("{:.1%}", subset=["94% coverage"])
    MAE RMSE Mean difference 94% coverage 94% width Interval score
Model Holdout start            
Undamped 2015-01 3,057 3,701 2,388 89.7% 10,242 18,588
2017-01 2,535 3,343 891 93.1% 10,490 18,009
Damped 2015-01 3,159 3,785 2,506 86.2% 9,944 19,987
2017-01 2,828 3,575 1,638 89.7% 10,243 19,062

Damping does not improve the point forecasts in either holdout. MAE rises from 3,057 to 3,159 deaths for the January 2015 start and from 2,535 to 2,828 for January 2017; RMSE and interval score also increase. Both variants tend to underpredict deaths over these windows. The damped intervals are slightly narrower, with lower coverage in both holdouts. We retain damping as an explicit alternative extrapolation assumption for this showcase, without claiming that it wins this comparison.

MAE measures absolute error of the predictive median; RMSE measures error of the predictive mean. The signed mean difference is observed minus predicted deaths averaged over the full window, so opposing monthly errors can cancel. These quantities, interval widths, and interval scores are in deaths per month. The interval score penalizes both width and observations falling outside the central 94% interval; lower is better.

Coverage is the fraction of held-out monthly counts inside the central 94% observation-predictive interval. Read it alongside interval width: wider intervals can increase coverage without improving point forecasts. With 29 months per fold and overlapping windows, these numbers are coarse, dependent estimates. The retained sampler warnings further limit any model ranking.

Hide code cell source
fig, axes = plt.subplots(2, 1, sharey=True, figsize=(FIG_WIDTH, FIG_HEIGHT * 2))
for fold_index, axis in enumerate(axes):
    reference = validation_results["Damped"][fold_index]
    dates = pd.DatetimeIndex(reference.prediction.time_future.values)
    context = pre_frame.iloc[reference.t1 - 24 : reference.t1]
    axis.plot(context.index, context.deaths, color=COLOR_OBSERVED, alpha=0.4)
    axis.plot(
        dates,
        pre_frame.deaths.iloc[reference.t1 : reference.t2],
        color=COLOR_OBSERVED,
        label="Observed",
    )
    for model_name, opacity, line_style in [
        ("Undamped", 0.65, ":"),
        ("Damped", 1.0, "--"),
    ]:
        forecast = validation_results[model_name][fold_index].prediction
        samples = forecast.transpose("chain", "draw", "time_future").values
        samples = samples.reshape(-1, len(dates))
        lower, upper = np.quantile(samples, [0.03, 0.97], axis=0)
        axis.fill_between(
            dates, lower, upper, color=COLOR_FORECAST, alpha=0.12 * opacity
        )
        axis.plot(
            dates,
            samples.mean(axis=0),
            linestyle=line_style,
            color=COLOR_FORECAST,
            alpha=opacity,
            label=model_name,
        )
    axis.axvline(dates[0], color="black", linestyle="--", linewidth=1)
    axis.set(
        title=f"Holdout: {dates[0]:%b %Y}–{dates[-1]:%b %Y}",
        ylabel="Monthly deaths (count)",
    )
    axis.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
axes[0].legend(ncol=3)
axes[-1].set_xlabel("Date")
fig.set_layout_engine("constrained")
plt.show()
../_images/5e96fca7cce5be464056575472e1375745c5b01cbf6307f1e4c201776afc3817.png

Caption: Two 29-month pre-pandemic forecasts from expanding training windows. Black lines show observed monthly counts, with the preceding 24 training months faded. Orange dotted (undamped) and dashed (damped) lines show predictive means and shaded bands are central 94% observation-predictive intervals; the darker variant uses a damped slope. Vertical black dashed lines mark each training/holdout boundary. Both panels share a death-count scale.

These bands include observation noise because they assess forecasts of actual counts. The ITS plot below instead shows uncertainty in the expected untreated path and derived differences, excluding observation-level noise. A successful pre-period forecast would support extrapolation, but would not establish causal identification.

Fit the damped structural counterfactual#

The damped model is the showcase specification. Its damping assumption is explicit and its validation results remain visible even when they do not improve. The formula deaths ~ 0 + temp supplies the outcome, time index, and temperature covariate; the level and month effects live inside the forecasting model. We fit to the same 168 pre-2020 months as the regression, then forecast all 29 comparison months. Future trend and AR states are generated from their fitted history without conditioning on post-2020 deaths. We retain the forecaster’s default 1,000 tuning and 1,000 retained draws per chain, use four chains and seed 42, and set target_accept=0.99 for the latent model.

forecast_model = PyMCForecastModel(
    damped_mortality_forecast,
    forecaster=pf.HMCForecaster,
    forecaster_kwargs={
        "chains": 4,
        "progressbar": False,
        "sample_kwargs": {"target_accept": 0.99},
    },
    num_samples=1_000,
    random_seed=seed,
)
forecast_experiment = cp.InterruptedTimeSeries(
    df,
    treatment_time,
    formula="deaths ~ 0 + temp",
    model=forecast_model,
).fit()
Hide code cell output
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 40 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]

Inspect fit_idata, which retains all fitting chains and sampler statistics. The wrapper’s idata is the shared subsample used for predictions, so it is not the place to assess convergence across the original chains. The following table includes the structural parameters and monthly effects; the second cell checks all innovation/state paths.

az.summary(
    forecast_model.fit_idata,
    var_names=[
        "initial_level",
        "initial_slope",
        "damping",
        "level_scale",
        "slope_scale",
        "month_effect",
        "beta_temp",
        "rho",
        "ar_scale",
        "observation_scale",
    ],
    ci_kind="hdi",
    ci_prob=0.94,
)
mean sd hdi94_lb hdi94_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
initial_level 4.65e+04 1.49e+03 44000 49000 976 1315 1.00 48 28
initial_slope -1 28.5 -55 51 7013 3217 1.00 0.34 0.49
damping 0.913 0.059 0.81 1 2624 1629 1.00 0.00091 0.0011
level_scale 167 53 70 270 1035 897 1.00 1.7 1.5
slope_scale 1.79 1.34 0.00055 4.2 2074 1520 1.00 0.026 0.021
month_effect[1] 7.41e+03 9.59e+02 5600 9200 1201 1668 1.00 28 15
month_effect[2] -9.96e+02 9.52e+02 -2800 710 1233 1711 1.00 27 14
month_effect[3] 1.23e+03 8.07e+02 -210 2800 1725 2069 1.00 19 13
month_effect[4] -1.88e+02 6.54e+02 -1500 950 4829 3394 1.00 9.4 9.9
month_effect[5] -7.22e+02 6.84e+02 -2000 530 3405 2616 1.00 12 11
month_effect[6] -1.02e+03 8.70e+02 -2600 630 1529 2095 1.00 22 13
month_effect[7] -1.06e+02 1.04e+03 -2100 1800 1045 1697 1.00 32 17
month_effect[8] -1.97e+03 9.86e+02 -3800 -87 1185 1857 1.00 29 15
month_effect[9] -2.08e+03 8.11e+02 -3600 -560 1470 1844 1.00 21 13
month_effect[10] -2.53e+02 6.57e+02 -1500 1000 4992 2989 1.00 9.3 10
month_effect[11] -1.69e+03 7.23e+02 -3100 -360 2217 2503 1.00 15 11
month_effect[12] 3.85e+02 9.11e+02 -1300 2100 1375 1840 1.00 25 15
beta_temp -494 137 -760 -240 889 1259 1.00 4.6 2.7
rho 0.43 0.189 0.095 0.78 266 258 1.01 0.011 0.0049
ar_scale 7.34e+02 2.71e+02 290 1300 884 1073 1.01 9.4 6.7
observation_scale 2390 175 2100 2700 1577 1741 1.00 4.4 3.2
sampler_stats = forecast_model.fit_idata.sample_stats
latent_diagnostics = az.summary(
    forecast_model.fit_idata,
    var_names=["level_z", "slope_z", "ar_z", "ar_initial"],
    kind="diagnostics",
)
print(f"Divergences: {int(sampler_stats.diverging.sum())}")
print(f"Maximum latent R-hat: {latent_diagnostics.r_hat.max():.2f}")
print(f"Minimum latent bulk ESS: {latent_diagnostics.ess_bulk.min():.0f}")
Divergences: 0
Maximum latent R-hat: 1.01
Minimum latent bulk ESS: 1138

The final damped fit has zero divergences. Its latent paths have a maximum displayed R-hat of 1.01 and minimum bulk ESS of 1,138; the AR coefficient has R-hat 1.01 and bulk ESS 266. The damping posterior has mean about 0.913, with a 94% HDI approximately 0.81–1.00 at the displayed precision; it remains broad and close to its regularizing prior. The retained logs flag effective-sample-size limitations. Zero divergences alone does not establish reliable inference, and these samples do not justify a precise interpretation of the separate temporal components.

Hide code cell source
fig, axes = forecast_experiment.plot(
    ci_prob=0.94, figsize=(FIG_WIDTH, FIG_HEIGHT * 2), show=False
)
axes[0].set_ylabel("Monthly deaths (count)")
axes[1].set(title="Observed minus structural baseline", ylabel="Difference (deaths)")
axes[2].set(title="Cumulative difference", ylabel="Difference (deaths)")
for axis in axes:
    axis.yaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
    for line in axis.get_lines():
        if line.get_color() == COLOR_FORECAST:
            line.set_linestyle("--")
            line.set_zorder(3)
for label in axes[0].get_legend().get_texts():
    if label.get_text() == "Causal impact":
        label.set_text("Modelled difference")
axes[-1].set_xlabel("Date")
fig.set_layout_engine("constrained")
plt.show()
../_images/f382542d32a5c1aa881e9f1b9e07ed8b9dca230dfea2960f50d8590afa7a6a2f.png

Caption: Observed monthly deaths, the structural expected baseline, observed-minus-baseline differences, and their cumulative sum. Lines show posterior means and shaded bands are 94% HDIs, excluding observation-level noise. Dashed orange lines mark the counterfactual and post-boundary differences; the vertical black dashed line marks the January 2020 analysis boundary.

Future level/slope innovations and AR innovations contribute to forecast uncertainty. Damping reduces the persistence of the inherited slope, but future innovations still accumulate uncertainty over the 29-month horizon; a close fit before 2020 does not constrain every plausible future trajectory.

forecast_stats = forecast_experiment.effect_summary()
forecast_stats.table
mean median hdi_lower hdi_upper p_gt_0 relative_mean relative_hdi_lower relative_hdi_upper
average 4851.473504 4862.229878 2915.816312 6764.332434 0.999 10.90532 6.251462 15.806866
cumulative 140692.731614 141004.666469 84558.673042 196165.640593 0.999 10.90532 6.251462 15.806866

The damped structural model estimates an average observed-minus-baseline difference of about 4,851 deaths per month (95% HDI: 2,916–6,764) and a cumulative difference of about 140,693 deaths (84,559–196,166). The original regression reports about 4,434 per month and 128,579 cumulatively. These are model-dependent deviations from the specified baselines, not identified counts caused solely by COVID-19. The table uses 95% HDIs; the plots use 94%.

The regression extrapolates a fixed linear trend and month coefficients while adjusting for temperature. The structural model allows its level and slope to evolve, damps the inherited slope, and separates persistent AR deviations from observation noise. Both use temperature and fixed month effects, but the priors and temporal assumptions differ, so this is not an equivalence check. Slow trend changes and persistent deviations can be weakly distinguished; full-fit diagnostics and pre-period forecasts expose that uncertainty. A larger in-sample Bayesian R² would not establish a better counterfactual forecast.

pymc-forecast supplies fitting, recursive state propagation, and backtesting. CausalPy supplies the ITS split, the observed-minus-expected comparison, impact plot, summaries, and reporting. Post-2020 deaths have not selected the specification or tuned its priors. January 2020 remains an analysis choice, and deviations from either baseline cannot automatically be attributed solely to COVID-19.

Compare the models at yearly placebo dates#

Does a richer time-series baseline avoid the historical discrepancies produced by a fixed trend? A placebo-in-time diagnostic moves the analysis boundary to earlier dates and asks what each model reports before the pandemic. Slow trend misspecification or temporally correlated errors could produce runs of similarly signed regression differences. The structural model might reduce those discrepancies, but we must check.

For the underlying method and the hierarchical calibration workflow, see Placebo-in-time and falsification: a UK CO₂ case study. Here we use PlaceboInTime for eight yearly fake starts from January 2010 through January 2017, each followed by 29 comparison months, matching the final January 2020–May 2022 comparison. The data provide 14 pre-intervention years, January 2006–December 2019. The first fit has four years of training data; the last comparison ends in May 2019. Both models use identical dates and observed counts.

Note

Yearly starts do not mean 12-month comparison windows. Shortening the windows would change the forecasting task. These 29-month windows overlap heavily and share training observations. Set allow_overlap=True and calibrate=False to request descriptive historical fits without a hierarchical null, a calibrated probability, or a causal supported/not-supported verdict. Explicitly scheduled overlap is rejected in calibrated mode.

The pre-pandemic period has real shocks and changing mortality conditions; its true intervention effects are not known to be zero. This is a stress test of historical forecast discrepancies and uncertainty, not a controlled experiment with a known null.

Configure fresh historical refits#

The public PipelineContext supplies an unfitted model template for each configuration. PlaceboInTime clones these templates, fits each training prefix, and forecasts its comparison window; it reuses the already fitted final experiments as context without fitting them again. Comparison deaths do not update forecast states. The regression keeps its revised priors, and the structural model keeps the damped specification above. Both were developed using pre-2020 information, including some of these windows, so this remains internal validation.

There are 16 historical fits, run serially. Both configurations use four chains, 2,000 tuning steps and 1,000 retained draws per chain, with target_accept=0.995. The forecasting wrapper uses 4,000 shared posterior draws. This larger computational budget follows sampling difficulties in earlier exploratory fits; it does not select a model using its placebo differences. Seeds follow 42 + original_fold_index; a failed fit does not shift later seeds. Shared seeds support reproducibility, but do not pair the models’ posterior draws. Raw sampler warnings remain in the expandable output.

PLACEBO_MONTHS = 29
placebo_dates = pd.date_range("2010-01-01", "2017-01-01", freq="YS")
assert df.index.equals(pd.date_range(df.index.min(), df.index.max(), freq="MS"))
placebo_sampler = {
    "chains": 4,
    "cores": 4,
    "tune": 2_000,
    "draws": 1_000,
    "target_accept": 0.995,
    "progressbar": False,
}
regression_placebo_template = cp.pymc_models.LinearRegression(
    sample_kwargs=placebo_sampler,
    priors={
        "beta": Prior(
            "Normal",
            mu=beta_mu,
            sigma=beta_sigma,
            dims=["treated_units", "coeffs"],
        ),
        "y_hat": Prior(
            "Normal",
            sigma=Prior("HalfNormal", sigma=3_000, dims=["treated_units"]),
            dims=["obs_ind", "treated_units"],
        ),
    },
)
forecast_placebo_template = PyMCForecastModel(
    damped_mortality_forecast,
    forecaster=pf.HMCForecaster,
    forecaster_kwargs={
        "chains": placebo_sampler["chains"],
        "tune": placebo_sampler["tune"],
        "draws": placebo_sampler["draws"],
        "progressbar": False,
        "sample_kwargs": {
            "cores": placebo_sampler["cores"],
            "target_accept": placebo_sampler["target_accept"],
        },
    },
    num_samples=4_000,
    random_seed=seed,
)
placebo_check = cp.checks.PlaceboInTime(
    n_folds=len(placebo_dates),
    treatment_times=placebo_dates,
    intervention_length=pd.DateOffset(months=PLACEBO_MONTHS),
    min_training_rows=48,
    comparison_frequency="MS",
    allow_overlap=True,
    calibrate=False,
    hdi_prob=0.95,
    random_seed=seed,
)
regression_context = cp.PipelineContext(
    data=df,
    experiment=experiment,
    experiment_config={
        "method": cp.InterruptedTimeSeries,
        "formula": formula,
        "model": regression_placebo_template,
    },
)
forecast_context = cp.PipelineContext(
    data=df,
    experiment=forecast_experiment,
    experiment_config={
        "method": cp.InterruptedTimeSeries,
        "formula": "deaths ~ 0 + temp",
        "model": forecast_placebo_template,
    },
)
regression_placebos = placebo_check.run(experiment, context=regression_context)
forecast_placebos = placebo_check.run(forecast_experiment, context=forecast_context)
paired_placebos = {
    "Regression": regression_placebos,
    "Damped structural forecast": forecast_placebos,
}
Hide code cell output
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [beta, y_hat_sigma]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 4 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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 4 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 5 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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 4 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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 4 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 4 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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 5 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 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 5 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: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 23 seconds.
There were 2 divergences after tuning. Increase `target_accept` or reparameterize.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 23 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 27 seconds.
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 31 seconds.
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 51 seconds.
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 39 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 40 seconds.
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [initial_level, initial_slope, level_scale, slope_scale, level_z, slope_z, damping, month_effect, beta_temp, rho, ar_scale, ar_initial, ar_z, observation_scale]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 49 seconds.
The rhat statistic is larger than 1.01 for some parameters. This indicates problems during sampling. See https://arxiv.org/abs/1903.08008 for details
The effective sample size per chain is smaller than 100 for some parameters.  A higher number is needed for reliable rhat and ess computation. See https://arxiv.org/abs/1903.08008 for details
Sampling: [obs]
Sampling: [ar_z_future, forecast, level_z_future, slope_z_future]
Sampling: [obs]

Inspect sampling before comparing discrepancies#

The library retains every requested date, including failed fits and completed fits with weak diagnostics. Its result table reports divergences, worst R-hat, and smallest bulk effective sample size across all posterior variables, including latent paths. Diagnostics come from the full fitting chains rather than the forecasting wrapper’s prediction subsample. Missing information is explicitly marked unavailable or partial; it is never replaced by a reassuring zero. Expand the sampling output above for the original warnings.

Hide code cell source
placebo_diagnostics = pd.concat(
    {
        model_name: check_result.table.set_index("pseudo_treatment_time")[
            [
                "status",
                "divergences",
                "max_rhat",
                "min_bulk_ess",
                "diagnostics_status",
            ]
        ]
        for model_name, check_result in paired_placebos.items()
    },
    names=["Model", "Fake start"],
)
placebo_diagnostics = placebo_diagnostics.rename(
    columns={
        "status": "Fit",
        "divergences": "Divergences",
        "max_rhat": "Worst R-hat",
        "min_bulk_ess": "Min. bulk ESS",
        "diagnostics_status": "Diagnostics",
    }
)
placebo_diagnostics.style.format(
    {"Divergences": "{:,.0f}", "Worst R-hat": "{:.2f}", "Min. bulk ESS": "{:,.0f}"},
    na_rep="Unavailable",
).format_index(lambda value: value.strftime("%Y"), axis=0, level="Fake start")
    Fit Divergences Worst R-hat Min. bulk ESS Diagnostics
Model Fake start          
Regression 2010 completed 0 1.01 514 available
2011 completed 0 1.01 545 available
2012 completed 0 1.01 565 available
2013 completed 0 1.00 585 available
2014 completed 0 1.01 448 available
2015 completed 0 1.00 684 available
2016 completed 0 1.01 534 available
2017 completed 0 1.00 531 available
Damped structural forecast 2010 completed 2 1.02 358 available
2011 completed 0 1.01 441 available
2012 completed 0 1.01 769 available
2013 completed 0 1.01 586 available
2014 completed 0 1.01 591 available
2015 completed 0 1.01 459 available
2016 completed 0 1.01 257 available
2017 completed 0 1.03 104 available
Hide code cell source
pd.concat(
    {
        model_name: check_result.table.set_index("pseudo_treatment_time")
        for model_name, check_result in paired_placebos.items()
    },
    names=["Model", "Fake start"],
)
Hide code cell output
fold comparison_end n_training n_comparison status reason mean hdi_lower hdi_upper hdi_prob divergences max_rhat min_bulk_ess diagnostics_status diagnostics_reason
Model Fake start
Regression 2010-01-01 1 2012-05-01 48 29 completed None -482.701767 -2302.906520 1096.070569 0.95 0 1.007398 513.717758 available None
2011-01-01 2 2013-05-01 60 29 completed None 948.554790 -552.998780 2447.513889 0.95 0 1.010022 544.985047 available None
2012-01-01 3 2014-05-01 72 29 completed None 1486.913110 92.319612 2762.844118 0.95 0 1.005321 564.796462 available None
2013-01-01 4 2015-05-01 84 29 completed None 2234.773756 985.049234 3480.240178 0.95 0 1.003648 584.912169 available None
2014-01-01 5 2016-05-01 96 29 completed None 2195.709772 1012.247133 3335.596703 0.95 0 1.011666 447.528274 available None
2015-01-01 6 2017-05-01 108 29 completed None 2887.757477 1767.756162 3976.502889 0.95 0 1.004523 683.932871 available None
2016-01-01 7 2018-05-01 120 29 completed None 2417.815084 1311.206616 3477.869214 0.95 0 1.005575 533.782174 available None
2017-01-01 8 2019-05-01 132 29 completed None 1658.943921 630.584014 2709.164270 0.95 0 1.004528 530.525010 available None
Damped structural forecast 2010-01-01 1 2012-05-01 48 29 completed None -921.617502 -2382.615550 723.505192 0.95 2 1.016941 358.462598 available None
2011-01-01 2 2013-05-01 60 29 completed None 170.331550 -1226.342227 1809.200736 0.95 0 1.010812 441.075042 available None
2012-01-01 3 2014-05-01 72 29 completed None 593.013247 -824.665031 2217.264678 0.95 0 1.005874 769.387981 available None
2013-01-01 4 2015-05-01 84 29 completed None 1518.099409 195.652534 2846.232601 0.95 0 1.007382 585.826960 available None
2014-01-01 5 2016-05-01 96 29 completed None 1792.243405 609.768410 3088.270174 0.95 0 1.008829 590.704126 available None
2015-01-01 6 2017-05-01 108 29 completed None 2524.963514 1238.331613 3780.931179 0.95 0 1.014957 458.963390 available None
2016-01-01 7 2018-05-01 120 29 completed None 2288.008588 387.243792 3865.604784 0.95 0 1.009128 256.705259 available None
2017-01-01 8 2019-05-01 132 29 completed None 1562.723365 -386.341984 3291.757727 0.95 0 1.030240 104.370019 available None

All 16 requested fits completed. The regression has no divergences, a worst displayed R-hat of 1.01, and minimum bulk ESS 448. The damped structural model has two divergences at the January 2010 start, worst displayed R-hat 1.03, and minimum bulk ESS 104. Low-ESS and R-hat warnings remain in the retained logs. “Available” means diagnostics could be calculated, not that the fit passed a quality threshold.

The larger budget has not fully resolved structural mixing difficulties. Every completed fit remains in the comparison, including the weak 2010 and 2017 fits; the resulting aggregates are provisional descriptive evidence rather than a reliable model ranking. Failed or ineligible dates would remain visible instead of silently changing the requested schedule.

Compare the paired placebo differences#

For each fit, the library first averages observed-minus-expected differences across its 29 months within each posterior draw, then summarizes those averages with a 95% HDI. It does not average monthly interval endpoints. The mean absolute placebo difference is the average across fake dates of the absolute posterior mean, rather than the average absolute monthly residual. It measures long-horizon average discrepancies; offsetting monthly errors can cancel.

The library’s descriptive_summary reports aggregates and their completed-fit denominator. Expected-path HDI width measures uncertainty separately from point-forecast accuracy. These intervals exclude observation-level noise; structural forecasts still propagate future state innovations.

Hide code cell source
comparison_display = pd.DataFrame(
    {
        model_name: check_result.metadata["descriptive_summary"]
        for model_name, check_result in paired_placebos.items()
    }
).rename(
    index={
        "n_requested": "Requested fits",
        "n_completed": "Completed fits",
        "mean_difference": "Mean difference (deaths/month)",
        "mean_absolute_difference": "Mean absolute difference (deaths/month)",
        "mean_interval_width": "Mean 95% HDI width (deaths/month)",
        "intervals_excluding_zero": "95% HDIs excluding zero",
    }
)
comparison_display.style.format("{:,.0f}", na_rep="Unavailable")
  Regression Damped structural forecast
Requested fits 8 8
Completed fits 8 8
Mean difference (deaths/month) 1,668 1,191
Mean absolute difference (deaths/month) 1,789 1,421
Mean 95% HDI width (deaths/month) 2,543 3,001
95% HDIs excluding zero 6 4

Across these eight windows, the damped structural model has a smaller mean absolute placebo difference: about 1,421 versus 1,789 deaths per month for the regression. The mean signed differences are positive for both, about 1,191 versus 1,668, indicating that both tend to forecast fewer deaths than were observed. This average-window metric allows monthly errors to cancel and does not contradict the worse damped-versus-undamped point forecasts in the earlier holdouts: the comparison model and error quantity differ.

The structural model has wider mean 95% HDIs, about 3,001 versus 2,543 deaths per month, with zero excluded at 4 of 8 dates versus 6 of 8 for regression. Fewer exclusions reflect both changed means and uncertainty; that count cannot establish improved accuracy or calibration. All eight fits per model contribute, including those with weak diagnostics.

Hide code cell source
fig = cp.checks.PlaceboInTime.plot_folds(
    paired_placebos,
    title="Historical placebo differences",
    figsize=(FIG_WIDTH, FIG_HEIGHT * 2),
)
for text in fig.findobj(match=plt.Text):
    if text.get_text() == "Average difference (outcome units)":
        text.set_text("Average difference (deaths/month)")
fig.axes[0].xaxis.set_major_formatter(StrMethodFormatter("{x:,.0f}"))
display(fig)
../_images/2351fe36562da2b1214addbf3786bf285ab86b47f38ac972ba08bc7f0fc9d550.png

Caption: Average monthly observed-minus-expected differences for eight yearly fake intervention dates, each forecast over the following 29 months. Points show posterior means and horizontal segments show 95% HDIs; the two models share a death-count scale. The black dashed line is a zero-difference reference, not known historical ground truth. Failed or ineligible dates are annotated. Overlapping windows do not represent independent replications.

Persistent signed differences are consistent with a baseline that misses slow mortality changes or temporally correlated errors, but historical shocks and overlapping windows can also contribute. Changes in damping, trend dynamics, AR persistence, regularization, and process uncertainty act together, so this comparison cannot isolate an AR effect or prove the cause of a regression discrepancy. Both configurations also condition on temperature.

A count of HDIs excluding zero is descriptive; it is neither an estimated false-positive rate nor a calibrated significance test. Overlapping windows, shared training history, internal model development, historical shocks, and sampling limitations all constrain the comparison. Good historical behavior would support forecasting assumptions in similar conditions; it would not establish that every deviation after January 2020 was caused by COVID-19. For the broader calibration argument and its assumptions, continue with Placebo-in-time and falsification: a UK CO₂ case study.

Takeaway#

The Bayesian workflow here is: construct the experiment, sample and inspect the prior phase, replace the model to revise priors, repeat the check, and then call fit(). The built-in prior plots examine the expected counterfactual path on a death-count scale. The posterior fit uses pre-2020 observations; effect plots and summaries then compare post-2020 observations with that fitted counterfactual in death-count units. Post-2020 outcomes were not used to tune the priors. A plausible prior and a fitted model do not, by themselves, establish that all post-2020 excess deaths were caused by COVID-19.

The structural forecasting extension combines a damped stochastic trend, seasonality, temperature regression, and AR persistence. Use PlaceboInTime with explicit dates, a minimum training history, a calendar grid, and calibrate=False for overlapping historical checks. Check its pre-period forecasts, fit on pre-2020 observations, inspect full-fit diagnostics, and interpret CausalPy’s impact summaries in original death-count units. Forecasting flexibility and a high in-sample R² do not establish a valid counterfactual. Inspect the structural priors with PreliZ and sample prior-only paths directly from the PyMC model before fitting; CausalPy’s wrapper method for the prior phase remains unavailable for this backend.