Causal inference / E135

Where spend stops paying: shape-constrained confidence bands for a confounded dose-response curve

Type
Advanced worked example - read, run, modify
Data
Simulated, with a known truth: 2,000 market-weeks of media spend and sales, built on the simulation design of Doss & VandenBerg (2026) with stronger confounding. The data are simulated because the question is whether a band covers the true spend-response curve, and no public media data set comes with that curve
You will learn
Why a spend-vs-sales curve from planned media is biased, and which way · the doubly robust pseudo-outcome for a continuous treatment (Kennedy et al. 2017), cross-fitted · why averaging over the fold's own markets makes pseudo-outcomes dependent, and what that does to the uncertainty · shape-constrained simultaneous confidence bands from one-sided kernels whose bias has a known sign (Dümbgen 2003; Doss & VandenBerg 2026) · the multiscale penalty, a Monte Carlo critical value and the Makarov combination · adaptivity: wide bandwidths where the curve is flat · a Bayesian analogue in PyMC: monotone splines, a fold-level random curve for the dependence, the bias a positive-increment prior adds on a flat stretch, and the projection posterior · simultaneous credible bands · coverage over repeated data sets
import os

for v_ in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ[v_] = "1"  # nutpie runs chains as threads: a BLAS pool per chain would fight over the cores

import logging
import sys
import time
import warnings

import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import nutpie
import pandas as pd
import pymc as pm
import pytensor.tensor as pt
from scipy import optimize, stats
from scipy.optimize import isotonic_regression

RANDOM_SEED = 135
rng = np.random.default_rng(RANDOM_SEED)
az.style.use("arviz-variat")
logging.getLogger("pymc").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
sys.modules.pop("jax", None)  # arviz leaves a lazy jax stub that makes matplotlib import all of JAX
pd.set_option("display.width", 160)
T_START = time.time()

BLUE, ORANGE, AQUA, PURPLE, RED = "#2a78d6", "#eb6834", "#1baf7a", "#8c5ac8", "#c8384e"
INK, MUTED, LIGHT = "#222222", "#8a8984", "#d9d8d3"
print(f"PyMC {pm.__version__}, ArviZ {az.__version__}, nutpie {nutpie.__version__}")
PyMC 6.3.2, ArviZ 1.3.0, nutpie 0.16.11

The setting

A grocery chain runs local TV and online video in 40 markets. Every week a planner sets each market's budget, from nothing to \$50k, and the media lead has a year of those decisions next to weekly sales. The proposal on the table: lift the weekly cap from \$30k to \$47.5k in every market, \$700k a week in all. The extra \$17.5k per market pays for itself in sales revenue only if weekly sales rise by more than \$17.5k, and it is wasted outright if the spend-response curve is already flat at \$30k. The lead wants to know where the curve stops rising.

Two things stand in the way. The planner did not spend at random: markets with a strong demand forecast got more money, and those markets sell more anyway. And the answer will be read off a whole curve, comparing \$20k with \$30k with \$45k, so pointwise intervals are not enough: the lead needs a simultaneous band, one that holds the entire curve with 95% confidence.

Doss & VandenBerg (2026), "Adaptive confidence bands for a continuous treatment effect curve under shape constraints" (arXiv 2611.33440), build exactly that object. The target is the dose-response curve $\theta(a) = E[Y^a]$, the mean sales if every market were given spend $a$. They start from the doubly robust pseudo-outcome of Kennedy et al. (2017), a transformed outcome whose regression on the dose is $\theta$ itself, cross-fitted as in Chernozhukov et al. (2018). They then borrow a device from Dümbgen (2003), who built shape-constrained bands in the white-noise model from Dümbgen & Spokoiny's (2001) multiscale statistics. If the curve is nondecreasing, a kernel average that only looks to the left of $t$ can only be biased downward, and one that only looks to the right can only be biased upward. A lower bound built from the left-looking average and an upper bound from the right-looking one stay valid at every bandwidth, so the band may take the best bandwidth at every point. Where the curve is flat, wide windows carry no bias and the band tightens at the parametric rate; where it rises, only narrow windows are usable. That is the sense in which the band is adaptive. The new work extends the construction to random, uneven designs with unequal noise, handles the dependence that cross-fitting creates between pseudo-outcomes, and combines two Gaussian limits by a Makarov (1982) bound.

We simulate the lead's data with a known curve, flat from \$30k, build the paper's monotone band in NumPy and a Bayesian analogue in PyMC, and repeat everything on ten fresh data sets.

part question tool
A What does the naive curve say, and why is it wrong? simulated market-weeks; sales by spend bin
B Can we remove the planner's influence? cross-fitted doubly robust pseudo-outcomes
C What does the paper's band say about the flat stretch? one-sided kernels, multiscale penalty, Monte Carlo critical values, Makarov bound
D Can a Bayesian model do the same job? monotone splines in PyMC, a fold-level random curve, the projection posterior, simultaneous credible bands
E Do the bands hold up on new data? ten replicate data sets: coverage, width and the spending decision

A · The planner's data

Each of the 2,000 rows is one market-week (40 markets over 50 weeks). We follow the simulation of Doss & VandenBerg's section 5 with one deliberate change. Four standardised market traits $L$ feed a demand score $\lambda(L) = s(L_1 + L_2 - L_3 - L_4)$. The planner sets spend $A$ (in \$10k) from a normal distribution centred on $2.5 + \lambda(L)$ with sd 2, truncated to $[0, 5]$. Sales (in \$100k, relative to a market's usual level) are $Y = 2\lambda(L) - sA(L_1 + L_3) + \theta(A) + \varepsilon$ with $\varepsilon \sim N(0, 0.5^2)$, so high-demand markets sell more whatever they spend, and markets respond to spend unevenly. The paper uses $s = 0.05$, under which confounding barely moves anything; we use $s = 0.5$, enough to mislead. The true curve rises with diminishing returns to \$200k of weekly sales at \$30k of spend and stays there: $\theta(a) = 2\,(1 - (1 - a/3)^2)$ for $a < 3$ and $\theta(a) = 2$ beyond. We treat market-weeks as independent draws, with no carryover from one week to the next and no market effects; a real media panel has both.

B_, C_ = 0.0, 5.0      # spend range, in $10k per market-week
S_CONF = 0.5           # confounding strength (the paper uses 0.05)
N = 2000               # 40 markets x 50 weeks, treated as independent market-weeks
A_SAT = 3.0            # spend at which the true curve goes flat
TOP = 2.0              # incremental sales at saturation, in $100k per week


def theta_true(a):
    """True spend-response curve E[Y^a]: rising with diminishing returns, flat from A_SAT on."""
    a = np.asarray(a, float)
    return np.where(a < A_SAT, TOP * (1 - (1 - a / A_SAT) ** 2), TOP)


def simulate(n, rng, s=S_CONF):
    L = rng.normal(size=(n, 4))                         # four standardised market traits
    lam = s * (L[:, 0] + L[:, 1] - L[:, 2] - L[:, 3])   # the planner's demand score
    m = 2.5 + lam
    A = stats.truncnorm.rvs((B_ - m) / 2.0, (C_ - m) / 2.0, loc=m, scale=2.0, random_state=rng)
    mu = 2 * lam - s * A * (L[:, 0] + L[:, 2]) + theta_true(A)
    Y = mu + 0.5 * rng.normal(size=n)
    return L, A, Y, lam


L, A, Y, LAM = simulate(N, rng)
grp = pd.qcut(LAM, 3, labels=["low", "middle", "high"])
tab = pd.DataFrame({"demand score": grp, "spend": A, "sales": Y}).groupby("demand score", observed=True)
print(tab.agg(markets_weeks=("spend", "size"), mean_spend=("spend", "mean"), mean_sales=("sales", "mean")).round(2))
print(f"\ncorrelation of spend with the demand score: {np.corrcoef(A, LAM)[0, 1]:.2f}")

BINS = np.linspace(B_, C_, 11)
MID = 0.5 * (BINS[1:] + BINS[:-1])


def binned(x, y):
    idx = np.clip(np.digitize(x, BINS) - 1, 0, MID.size - 1)
    return np.array([y[idx == b].mean() for b in range(MID.size)]), np.array(
        [y[idx == b].std() / np.sqrt((idx == b).sum()) for b in range(MID.size)])


naive_mean, naive_se = binned(A, Y)
print("\nspend bin   naive mean sales   true curve")
for mid, nm, ns in zip(MID, naive_mean, naive_se):
    print(f"  {mid:4.2f}      {nm:6.2f} ({ns:.2f})      {theta_true(mid):5.2f}")
              markets_weeks  mean_spend  mean_sales
demand score                                       
low                     667        2.05       -0.60
middle                  666        2.53        1.76
high                    667        2.98        3.86

correlation of spend with the demand score: 0.32

spend bin   naive mean sales   true curve
  0.25       -0.66 (0.16)       0.32
  0.75       -0.12 (0.15)       0.88
  1.25        1.06 (0.15)       1.32
  1.75        1.51 (0.14)       1.65
  2.25        1.71 (0.17)       1.88
  2.75        2.23 (0.19)       1.99
  3.25        2.33 (0.20)       2.00
  3.75        2.79 (0.23)       2.00
  4.25        2.52 (0.24)       2.00
  4.75        2.64 (0.30)       2.00
fig, axes = plt.subplots(1, 2, figsize=(12, 4.3))
ax = axes[0]
for g_, c_ in zip(["low", "middle", "high"], [BLUE, MUTED, ORANGE]):
    sel = np.asarray(grp == g_)
    ax.hist(A[sel], bins=25, range=(0, 5), histtype="step", lw=2, color=c_, label=f"{g_} demand score")
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel("market-weeks")
ax.set_title("The planner spends more where demand is high")
ax.legend()
ax = axes[1]
ax.scatter(A, Y, s=4, color=LIGHT, alpha=0.6, rasterized=True)
gg = np.linspace(0, 5, 201)
ax.plot(gg, theta_true(gg), color=INK, lw=2.5, label=r"true curve $\theta(a)=E[Y^a]$")
ax.errorbar(MID, naive_mean, yerr=2 * naive_se, fmt="o-", color=RED, label="naive: mean sales by spend bin")
ax.set_ylim(-3, 5.5)
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel("weekly sales ($100k, relative)")
ax.set_title("Sales against spend: the naive curve never flattens")
ax.legend(loc="upper left");
Figure

The planner's rule shows in the first table: weeks in the top third of the demand score got \$29.8k on average against \$20.5k in the bottom third, and they sold about \$450k a week more, almost none of it because of the spend. The correlation of spend with the demand score is only 0.32, and that is enough. The naive curve starts a full \$100k below the truth at the low end (the cheap weeks are the weak markets) and runs \$30k to \$80k above it past \$30k. Most damaging for the decision, it keeps climbing after \$30k: from 2.33 at \$32.5k to 2.79 at \$37.5k and 2.64 at \$47.5k, against a true curve that is flat. Read naively, the data say the cap increase pays.

B · Pseudo-outcomes that remove the confounding

If we knew the outcome regression $\mu(l, a) = E[Y \mid L = l, A = a]$ we could average it over markets, $\theta(a) = \int \mu(l, a)\, dP(l)$. If we knew the generalised propensity score $\pi(a \mid l)$ we could reweight. Kennedy et al. (2017) combine the two in a pseudo-outcome

$$\xi = \frac{Y - \mu(L, A)}{g(A \mid L)} + \int \mu(l, A)\, dP(l), \qquad g(a \mid l) = \frac{\pi(a \mid l)}{\omega(a)},$$

where $\omega$ is the marginal density of spend, and $E[\xi \mid A = a] = \theta(a)$. The identity holds if either nuisance is right, but the paper's Remark 4.1 is candid that for its bands both must in effect be estimated consistently, and calls the doubly robust reading "essentially a theoretical trick". We fit both in the right families: a linear spline in spend with traits and spend-by-trait interactions for sales, and a truncated normal with a mean linear in the traits for spend, by maximum likelihood.

One detail of the paper's cross-fitting matters later. With $K$ folds (we use two), fold $v$ takes its nuisances from the other fold and replaces the integral over markets by an average over the fold's own markets, $\frac{1}{n_v} \sum_k \hat\mu_{-v}(L_k, A_i)$; $\hat\omega$ is the in-fold average of $\hat\pi_{-v}(a \mid L_k)$. Averaging over the other fold's markets gives narrower bands that, the authors report, lose coverage where the curve is flat. The in-fold average has its own price: every pseudo-outcome in a fold shares one estimate of the market mix, so they are dependent. Rows with $\hat g < 0.1$ are dropped, as in the paper.

KNOTS_MU = np.linspace(0.5, 4.5, 9)   # spline knots in spend for the outcome model
KN = np.linspace(B_, C_, 21)          # knot grid of the Bayesian curves (part D), every $2.5k
K_FOLDS = 2
TRIM = 0.1


def mu_features(L, a):
    """Outcome-model design: a linear spline in spend, the traits, and spend x trait interactions."""
    a = np.asarray(a, float)
    cols = [np.ones_like(a), a] + [np.maximum(a - k, 0.0) for k in KNOTS_MU]
    cols += [L[:, j] for j in range(4)] + [a * L[:, j] for j in range(4)]
    return np.column_stack(cols)


def fit_gps(L, A):
    """Generalised propensity score: A | L ~ Normal(X b, sd) truncated to [B_, C_], by maximum likelihood."""
    X = np.column_stack([np.ones(len(A)), L])
    b0 = np.linalg.lstsq(X, A, rcond=None)[0]

    def nll(p):
        m, sd = X @ p[:-1], np.exp(p[-1])
        z = stats.norm.cdf((C_ - m) / sd) - stats.norm.cdf((B_ - m) / sd)
        return -(stats.norm.logpdf(A, m, sd) - np.log(z)).sum()

    return optimize.minimize(nll, np.r_[b0, np.log(np.std(A - X @ b0))], method="BFGS").x


def gps_density(p, L, a):
    """pi(a_j | L_k) for every pair: rows are markets L_k, columns are doses a_j."""
    X = np.column_stack([np.ones(len(L)), L])
    m, sd = (X @ p[:-1])[:, None], np.exp(p[-1])
    z = stats.norm.cdf((C_ - m) / sd) - stats.norm.cdf((B_ - m) / sd)
    return stats.norm.pdf(np.atleast_1d(a)[None, :], m, sd) / z


def pseudo_outcomes(L, A, Y, rng, K=K_FOLDS, trim=TRIM):
    """Cross-fitted pseudo-outcomes of Kennedy et al. (2017), averaging mu over the fold's own markets."""
    n = len(A)
    fold = rng.permutation(np.arange(n) % K)
    out = []
    for v in range(K):
        tr, te = fold != v, fold == v
        beta = np.linalg.lstsq(mu_features(L[tr], A[tr]), Y[tr], rcond=None)[0]
        p = fit_gps(L[tr], A[tr])
        Lv, Av, Yv = L[te], A[te], Y[te]
        nv = len(Av)
        Pi = gps_density(p, Lv, Av)
        g = np.diag(Pi) / Pi.mean(axis=0)             # pi(A_i|L_i) / omega(A_i), omega from in-fold L
        U = np.column_stack([mu_features(Lv, np.full(nv, a_)) @ beta for a_ in Av])  # U[k, i] = mu(L_k, A_i)
        xi = (Yv - np.diag(U)) / g + U.mean(axis=0)
        Uc = U - U.mean(axis=0, keepdims=True)
        Ukn = np.column_stack([mu_features(Lv, np.full(nv, k_)) @ beta for k_ in KN])
        Ukn -= Ukn.mean(axis=0, keepdims=True)
        keep = g >= trim
        out.append(dict(A=Av[keep], xi=xi[keep], Y=Yv[keep], g=g[keep], Uc=Uc[:, keep], nv=nv,
                        Sig_kn=Ukn.T @ Ukn / nv**2, ntrim=int((~keep).sum()), beta=beta, gps=p,
                        full=dict(A=Av, xi=xi, Y=Yv, keep=keep.astype(float))))
    return out


def stack(folds):
    """All rows of all folds, with a 0/1 weight that drops trimmed rows (keeps shapes fixed for refits)."""
    cat = lambda k: np.concatenate([f["full"][k] for f in folds])  # noqa: E731
    fid = np.concatenate([np.full(f["nv"], v) for v, f in enumerate(folds)])
    return cat("A"), cat("xi"), cat("Y"), fid, cat("keep")


FOLDS = pseudo_outcomes(L, A, Y, rng)
a_all, xi_all, y_all, fid_all, wt_all = stack(FOLDS)
kept = wt_all > 0
g_all = np.concatenate([f["g"] for f in FOLDS])
for v, f in enumerate(FOLDS):
    print(f"fold {v}: {f['nv']} market-weeks, {f['ntrim']} trimmed (g < {TRIM}), "
          f"spend model slope on the traits {np.round(f['gps'][1:5], 2)}, sd {np.exp(f['gps'][5]):.2f}")
print(f"generalised propensity ratio g: min {g_all.min():.2f}, 1% {np.quantile(g_all, 0.01):.2f}, "
      f"median {np.median(g_all):.2f}, max {g_all.max():.2f}")
print(f"pseudo-outcome sd {xi_all[kept].std():.2f} against raw sales sd {y_all.std():.2f}")

xi_mean, xi_se = binned(a_all[kept], xi_all[kept])
print("\nspend bin   pseudo-outcome mean   naive mean   true curve")
for mid, xm, xs, nm in zip(MID, xi_mean, xi_se, naive_mean):
    print(f"  {mid:4.2f}        {xm:5.2f} ({xs:.2f})         {nm:6.2f}       {theta_true(mid):5.2f}")
fold 0: 1000 market-weeks, 0 trimmed (g < 0.1), spend model slope on the traits [ 0.84  0.53 -0.47 -0.53], sd 2.02
fold 1: 1000 market-weeks, 0 trimmed (g < 0.1), spend model slope on the traits [ 0.58  0.3  -0.5  -0.69], sd 2.01
generalised propensity ratio g: min 0.14, 1% 0.38, median 1.06, max 3.51
pseudo-outcome sd 0.76 against raw sales sd 2.94

spend bin   pseudo-outcome mean   naive mean   true curve
  0.25         0.33 (0.05)          -0.66        0.32
  0.75         0.90 (0.04)          -0.12        0.88
  1.25         1.37 (0.04)           1.06        1.32
  1.75         1.74 (0.03)           1.51        1.65
  2.25         1.99 (0.03)           1.71        1.88
  2.75         2.06 (0.04)           2.23        1.99
  3.25         2.03 (0.03)           2.33        2.00
  3.75         2.12 (0.04)           2.79        2.00
  4.25         2.20 (0.04)           2.52        2.00
  4.75         2.05 (0.05)           2.64        2.00
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2))
ax = axes[0]
ax.plot(gg, theta_true(gg), color=INK, lw=2.5, label="true curve")
ax.errorbar(MID, naive_mean, yerr=2 * naive_se, fmt="o-", color=RED, label="naive bin means of sales")
ax.errorbar(MID + 0.04, xi_mean, yerr=2 * xi_se, fmt="s-", color=BLUE, label="bin means of pseudo-outcomes")
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel("$100k per week")
ax.set_title("Pseudo-outcomes put the curve back")
ax.legend(loc="lower right")
ax = axes[1]
ax.scatter(a_all[kept], xi_all[kept], s=4, color=LIGHT, alpha=0.7, rasterized=True)
ax.plot(gg, theta_true(gg), color=INK, lw=2)
ax.set_ylim(np.quantile(xi_all[kept], [0.002, 0.998]))
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel("pseudo-outcome")
ax.set_title("The pseudo-outcomes themselves");
Figure

Nothing needed trimming: the smallest propensity ratio is 0.14 and 99% exceed 0.38, so every spend level was plausible for every kind of market. The fitted spend models recover the planner's rule (slopes of the right signs, 0.3 to 0.8 in size against a true 0.5, and sd 2.0). The pseudo-outcomes have an sd of 0.76, a quarter of the raw sales' 2.94, because $\hat\mu$ removes each market's demand level before the residual is reweighted.

Their bin means sit on the true curve in the rising part: 0.33 against 0.32 at \$2.5k, 1.37 against 1.32 at \$12.5k. In the flat stretch all four bins sit a little above 2 (2.03, 2.12, 2.20, 2.05), and they sit there together. That shared offset is what the in-fold average produces: every pseudo-outcome in a fold inherits the same error in the fold's estimate of the market mix, so neighbouring bins move together. Keep that in mind; it decides the width of everything that follows.

C · The paper's band

For a bandwidth $h$ and a dose $t$, each fold gives a density-reweighted Nadaraya-Watson average of its pseudo-outcomes,

$$\hat m_v(h, t) = \frac{\sum_i \psi\big(\tfrac{A_i - t}{h}\big)\, \xi_i / \hat\omega(A_i)} {\sum_i \psi\big(\tfrac{A_i - t}{h}\big) / \hat\omega(A_i)},$$

averaged over folds. With the lower kernel $\psi_\ell(x) = 1 + x$ on $[-1, 0]$ the average uses only spend levels at or below $t$, so for a nondecreasing $\theta$ its expectation is at most $\theta(t)$; the upper kernel $\psi_u(x) = 1 - x$ on $[0, 1]$ looks right and errs upward. The band is

$$\hat\ell(t) = \sup_h \big\{\hat m_\ell(h, t) - [\Gamma(h/(c-b)) + \kappa]\,\widehat{se}\big\}, \qquad \hat u(t) = \inf_h \big\{\hat m_u(h, t) + [\Gamma(h/(c-b)) + \kappa]\,\widehat{se}\big\},$$

with $\Gamma(u) = \sqrt{2 \log(e/u)}$, the multiscale penalty of Dümbgen & Spokoiny (2001): small bandwidths are many and nearly independent, so they pay a larger premium, and the critical value $\kappa$ stays bounded however fine the grid.

The standard error has two parts: a weighted sum of the pseudo-outcomes' variances $\sigma^2(a)$ (a monotone least-squares fit, then a kernel smooth of squared residuals), and the shared in-fold average, whose covariance between two doses is $\eta(a_1, a_2)/n_v$ with $\eta(a_1, a_2) = \mathrm{Cov}(\mu(L, a_1), \mu(L, a_2))$, the extra nuisance the paper introduces, estimated from $\hat\mu_{-v}$ over the fold's markets. The critical value comes from two Gaussian processes, an "oracle" one driven by $\sigma^2$ and a "nuisance" one driven by $\eta$. The paper can prove that each limit exists but not that they are jointly Gaussian, so it adds their quantiles with a Makarov bound, $\kappa = \inf_{p + q = \alpha} F_1^{-1}(1 - q) + F_2^{-1}(1 - p)$. Its Remark 4.2 reports that simulating their sum as if independent also kept coverage in all its simulations. We compute both.

Our version is simplified in these places. We simulate the two processes conditional on the observed doses with the estimated $\sigma^2$ and $\eta$ (2,000 draws), where the paper simulates the limiting processes (its Remark 3.2 notes that such a bootstrap is natural). The grid is 93 doses by 40 bandwidths from 0.02 to 5 (the paper uses 200 by 200 from $1/n$). A pair $(h, t)$ is used only if every fold has at least five points under the kernel. The variance smooth has a fixed bandwidth of 0.4. We use two folds, and a truncated-normal propensity fitted by maximum likelihood where the paper's simulation uses a normal around a linear regression. Only the monotone band is built; the paper's local-linear band for convex curves is not.

T_GRID = np.round(np.linspace(0.2, 4.8, 93), 3)   # doses where the band is reported
H_GRID = np.geomspace(0.02, 5.0, 40)               # bandwidths
TT, HH = (x.ravel() for x in np.meshgrid(T_GRID, H_GRID, indexing="ij"))
GAM = np.sqrt(2 * np.log(np.e * (C_ - B_) / HH))   # multiscale penalty Gamma(h / (c - b))
TH = theta_true(T_GRID)
FLAT = (T_GRID >= 3.25) & (T_GRID <= 4.75)
RISE = (T_GRID >= 0.5) & (T_GRID <= 2.5)
I30, I475 = int(np.argmin(abs(T_GRID - 3.0))), int(np.argmin(abs(T_GRID - 4.75)))
BREAK_EVEN = 0.175   # the extra $17.5k a week pays for itself in sales only above $17.5k = 0.175 x $100k


def psi_lower(x):
    return np.where((x >= -1) & (x <= 0), 1 + x, 0.0)   # looks only to the left of t


def psi_upper(x):
    return np.where((x >= 0) & (x <= 1), 1 - x, 0.0)    # looks only to the right of t


def var_function(a, xi, bw=0.4):
    """sigma^2(a) = Var(xi | A = a): monotone least squares, then a kernel smooth of squared residuals."""
    o = np.argsort(a)
    fit = np.empty_like(xi)
    fit[o] = isotonic_regression(xi[o]).x
    Kw = stats.norm.pdf((a[:, None] - a[None, :]) / bw)
    return Kw @ (xi - fit) ** 2 / Kw.sum(axis=1)


def kernel_pieces(f, psi, omega_hat, t, h):
    """Weights, estimate and the two variance parts of one fold's reweighted Nadaraya-Watson estimator."""
    W = psi((f["A"][:, None] - t[None, :]) / h[None, :]) / omega_hat(f["A"])[:, None]
    sw = W.sum(axis=0)
    sws = np.where(sw > 0, sw, 1.0)
    m = W.T @ f["xi"] / sws
    sig2 = var_function(f["A"], f["xi"])
    UW = f["Uc"] @ W
    v_oracle = (W**2).T @ sig2 / sws**2
    v_eta = (UW**2).sum(axis=0) / f["nv"] ** 2 / sws**2    # the in-fold dependence term, eta / n_v
    return W, m, sig2, UW, v_oracle, v_eta, sws, (W > 0).sum(axis=0)


def dv_band(folds, rng, alpha=0.05, R=2000, min_pts=5):
    """Monotone band of Doss & VandenBerg (2026) on cross-fitted pseudo-outcomes, NW estimator (j = 0)."""
    K = len(folds)
    omega_hat = stats.gaussian_kde(np.concatenate([f["A"] for f in folds]))
    res = {}
    for side, psi, ok0, sgn in (("lower", psi_lower, TT - HH >= B_ - 1e-9, 1.0),
                                ("upper", psi_upper, TT + HH <= C_ + 1e-9, -1.0)):
        m_sum, v_sum, ok = np.zeros(TT.size), np.zeros(TT.size), ok0.copy()
        X, Yp = np.zeros((TT.size, R)), np.zeros((TT.size, R))
        for f in folds:
            W, m, sig2, UW, vo, ve, sws, cnt = kernel_pieces(f, psi, omega_hat, TT, HH)
            ok &= cnt >= min_pts
            m_sum += m
            v_sum += vo + ve
            X += (W * np.sqrt(sig2)[:, None]).T @ rng.normal(size=(len(f["A"]), R)) / sws[:, None]
            Yp += UW.T @ rng.normal(size=(f["nv"], R)) / f["nv"] / sws[:, None]
        m, se = m_sum / K, np.sqrt(v_sum) / K
        X, Yp = X / K, Yp / K
        z = lambda P: np.where(ok[:, None], sgn * P / se[:, None], -np.inf)  # noqa: E731
        res[side] = dict(m=m, se=se, ok=ok, T1=np.max(z(X) - GAM[:, None], axis=0),
                         T2=np.max(z(Yp), axis=0), Ts=np.max(z(X + Yp) - GAM[:, None], axis=0))
    F1 = np.maximum(res["lower"]["T1"], res["upper"]["T1"])   # oracle multiscale term
    F2 = np.maximum(res["lower"]["T2"], res["upper"]["T2"])   # nuisance (in-fold average) term
    Fs = np.maximum(res["lower"]["Ts"], res["upper"]["Ts"])   # the two summed (Remark 4.2)
    qs = np.linspace(0.0005, alpha - 0.0005, 99)
    kap = {"Makarov": min(np.quantile(F1, 1 - q) + np.quantile(F2, 1 - (alpha - q)) for q in qs),
           "joint Gaussian": np.quantile(Fs, 1 - alpha)}
    bands = {}
    for lab, k in kap.items():
        lo = res["lower"]["m"] - (GAM + k) * res["lower"]["se"]
        lo = np.where(res["lower"]["ok"], lo, -np.inf).reshape(T_GRID.size, H_GRID.size)
        up = res["upper"]["m"] + (GAM + k) * res["upper"]["se"]
        up = np.where(res["upper"]["ok"], up, np.inf).reshape(T_GRID.size, H_GRID.size)
        bands[lab] = dict(lo=lo.max(axis=1), up=up.min(axis=1), kappa=k,
                          h_lo=H_GRID[lo.argmax(axis=1)], h_up=H_GRID[up.argmin(axis=1)])
    return bands, dict(F1=F1, F2=F2)


t0 = time.time()
DV, DV_T = dv_band(FOLDS, np.random.default_rng(RANDOM_SEED + 1))
print(f"band built in {time.time() - t0:.1f} s on {T_GRID.size} doses x {H_GRID.size} bandwidths")
print(f"95% quantiles: oracle term {np.quantile(DV_T['F1'], 0.95):.2f}, nuisance term {np.quantile(DV_T['F2'], 0.95):.2f}")
for lab, b in DV.items():
    cover = np.all((b["lo"] <= TH) & (TH <= b["up"]))
    print(f"\n{lab}: kappa = {b['kappa']:.2f}, covers the true curve at every dose: {cover}")
    print(f"  median width: rising part (0.5-2.5) {np.median((b['up'] - b['lo'])[RISE]):.2f}, "
          f"flat part (3.25-4.75) {np.median((b['up'] - b['lo'])[FLAT]):.2f}")
    print(f"  largest gain from $30k to $47.5k allowed by the band: {b['up'][I475] - b['lo'][I30]:.2f}")
for t_ in (0.5, 1.0, 2.0, 3.0, 4.0, 4.75):
    i = int(np.argmin(abs(T_GRID - t_)))
    b = DV["Makarov"]
    print(f"  spend {t_:4.2f}: [{b['lo'][i]:5.2f}, {b['up'][i]:5.2f}] (truth {TH[i]:.2f}), "
          f"bandwidths used: lower {b['h_lo'][i]:.2f}, upper {b['h_up'][i]:.2f}")
band built in 4.4 s on 93 doses x 40 bandwidths
95% quantiles: oracle term 0.14, nuisance term 2.04

Makarov: kappa = 2.60, covers the true curve at every dose: True
  median width: rising part (0.5-2.5) 0.88, flat part (3.25-4.75) 0.80
  largest gain from $30k to $47.5k allowed by the band: 0.91

joint Gaussian: kappa = 0.77, covers the true curve at every dose: True
  median width: rising part (0.5-2.5) 0.63, flat part (3.25-4.75) 0.51
  largest gain from $30k to $47.5k allowed by the band: 0.54
  spend 0.50: [ 0.09,  1.12] (truth 0.61), bandwidths used: lower 0.39, upper 0.45
  spend 1.00: [ 0.70,  1.64] (truth 1.11), bandwidths used: lower 0.22, upper 0.45
  spend 2.00: [ 1.42,  2.29] (truth 1.78), bandwidths used: lower 0.52, upper 0.91
  spend 3.00: [ 1.77,  2.41] (truth 2.00), bandwidths used: lower 0.39, upper 1.05
  spend 4.00: [ 1.76,  2.58] (truth 2.00), bandwidths used: lower 2.14, upper 0.91
  spend 4.75: [ 1.78,  2.68] (truth 2.00), bandwidths used: lower 3.27, upper 0.22
fig, axes = plt.subplots(1, 2, figsize=(12, 4.4), gridspec_kw={"width_ratios": [1.6, 1]})
ax = axes[0]
for lab, c_, al in (("Makarov", BLUE, 0.18), ("joint Gaussian", AQUA, 0.35)):
    b = DV[lab]
    ax.fill_between(T_GRID, b["lo"], b["up"], color=c_, alpha=al, lw=0, label=f"95% band, {lab} ($\\kappa$ = {b['kappa']:.1f})")
ax.plot(gg, theta_true(gg), color=INK, lw=2.5, label="true curve")
ax.plot(MID, naive_mean, "o--", color=RED, label="naive bin means")
ax.set_ylim(-1, 3.6)
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel("$100k per week")
ax.set_title("Simultaneous monotone bands for the spend-response curve")
ax.legend(loc="upper left", fontsize=8.5)
ax = axes[1]
b = DV["Makarov"]
ax.semilogy(T_GRID, b["h_lo"], color=BLUE, lw=2, label="lower bound (looks left)")
ax.semilogy(T_GRID, b["h_up"], color=ORANGE, lw=2, label="upper bound (looks right)")
ax.axvline(A_SAT, color=MUTED, ls=":", lw=1)
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel("bandwidth that set the bound")
ax.set_title("Adaptivity: wide windows where it is flat")
ax.legend(fontsize=8.5);
Figure

Both bands contain the true curve at all 93 doses. The two pieces of the critical value tell the story. The oracle term's 95% quantile is 0.14: after the multiscale penalty, the noise of single pseudo-outcomes almost never pushes an average past its allowance. The nuisance term's is 2.04, with no penalty, because it is one smooth curve shared by every bandwidth. The Makarov bound adds the two, $\kappa = 2.6$, as if the worst oracle draw always came with the worst nuisance draw; simulating their sum gives $\kappa = 0.77$.

The right panel shows the adaptivity. Where the curve rises, both bounds are set by windows of \$2k to \$9k. Past \$30k the lower bound reaches back over ever wider windows, \$21k at \$40k and \$33k at \$47.5k, since a left-looking average over a flat stretch costs nothing in bias and averaging more weeks shrinks its error (the upper bound near the right edge has no spend above \$50k to look at). The gain is modest: the Makarov band is 0.88 wide in the rising part and 0.80 in the flat part, the summed version 0.63 and 0.51. In the paper's simulations, with confounding ten times weaker, the bands are visibly tighter where the curve is flat. Here the nuisance term sets a floor: a wide window averages away the noise of single weeks, but every week in a fold shares the same estimate of the market mix.

For the lead's decision this is a setback. The band holds the curve between about \$176k and \$268k anywhere past \$30k, so the largest gain from raising spend to \$47.5k that it allows is \$91k a week (\$54k with the summed critical value). Both are far above the \$17.5k break-even. The band is honest about the curve's level, and the level is where the uncertainty sits.

Does the standard error formula hold up?

The band rests on the standard error formula with its $\eta$ term, so we check it against repetition: 20 fresh data sets, each with its own pseudo-outcomes, and the lower-kernel estimate at four $(t, h)$ pairs. If the formula is right, the average plug-in standard error should match the spread of the estimates across data sets.

def point_and_se(folds, t, h, psi):
    omega_hat = stats.gaussian_kde(np.concatenate([f["A"] for f in folds]))
    parts = [kernel_pieces(f, psi, omega_hat, t, h) for f in folds]
    m = np.mean([p[1] for p in parts], axis=0)
    se_full = np.sqrt(sum(p[4] + p[5] for p in parts)) / len(folds)
    se_no_eta = np.sqrt(sum(p[4] for p in parts)) / len(folds)
    return m, se_full, se_no_eta


CHECK_T = np.array([1.0, 2.5, 4.0, 4.0])
CHECK_H = np.array([0.3, 0.5, 0.5, 1.0])
rng_se = np.random.default_rng(RANDOM_SEED + 2)
rows = []
for r in range(20):
    Lr, Ar, Yr, _ = simulate(N, rng_se)
    rows.append(point_and_se(pseudo_outcomes(Lr, Ar, Yr, rng_se), CHECK_T, CHECK_H, psi_lower))
est = np.array([r_[0] for r_ in rows])
se_f = np.array([r_[1] for r_ in rows])
se_n = np.array([r_[2] for r_ in rows])
se_tab = pd.DataFrame({"spend t": CHECK_T, "bandwidth h": CHECK_H, "sd over 20 data sets": est.std(axis=0, ddof=1),
                       "mean plug-in se": se_f.mean(axis=0), "mean se without eta": se_n.mean(axis=0)})
print(se_tab.round(3).to_string(index=False))
 spend t  bandwidth h  sd over 20 data sets  mean plug-in se  mean se without eta
     1.0          0.3                 0.072            0.074                0.057
     2.5          0.5                 0.052            0.069                0.037
     4.0          0.5                 0.068            0.087                0.045
     4.0          1.0                 0.061            0.079                0.031

The plug-in standard error is close to the spread or somewhat above it (0.074 against 0.072 at \$10k, 0.079 against 0.061 at \$40k with a wide window), which errs on the safe side; with 20 data sets an sd is itself uncertain by about 16%. Dropping $\eta$ would understate the error by a quarter in the rising part and by half in the flat part (0.031 against 0.061). In the flat stretch, the uncertainty about which markets we happened to observe is the larger part of the total. This is the dependence the paper insists on.

D · A Bayesian analogue in PyMC

An MMM team would more likely fit a Bayesian curve. Here the pseudo-outcomes become data for a shape-constrained regression on spend. That is a cut posterior in the sense of E130 (the nuisance fits feed the curve model, which does not feed back), with no frequentist guarantee of the paper's kind; whether its bands cover is a question for simulation.

The curve is piecewise linear on 21 knots, one every \$2.5k: $\theta$ at the first knot is $\alpha$, and each later knot adds a step $\tau\,\delta_j$. With half-normal steps $\delta_j \ge 0$ the curve is nondecreasing; with normal steps it is unconstrained. The noise is Student-t with a log scale quadratic in spend, because $\mathrm{Var}(\xi \mid A)$ grows where the propensity ratio is small, and a few weeks with small $\hat g$ give large pseudo-outcomes.

The fold dependence gets its own term. Within fold $v$ the pseudo-outcomes share an error curve $e_v(a) = (\mathbb{P}_{n_v} - P)\,\mu(\cdot, a)$, the difference between the fold's market mix and the population's. Its covariance is $\eta(a_1, a_2)/n_v$, which we have already estimated. We give each fold a random curve on the knot grid, $e_v = B_v \zeta_v$ with $\zeta_v \sim N(0, I)$, where $B_v B_v^\top$ is the top three eigencomponents of $\hat\eta/n_v$ (with an outcome model linear in the traits the rank is two, so three loses nothing).

A simultaneous credible band takes the 95% quantile $q$ of each posterior draw's largest standardised deviation, $\max_t |\theta^{(s)}(t) - \bar\theta(t)| / \mathrm{sd}(t)$, and reports $\bar\theta \pm q\,\mathrm{sd}$ (Ruppert, Wand & Carroll 2003). The likelihood is a weighted pm.Potential, so trimmed rows get weight zero without changing the data's shape and each model is compiled once and refitted with nutpie's with_data.

R_EIG = 3   # rank kept for each fold's shared error curve


def interp_idx(a):
    a = np.asarray(a, float)
    j = np.clip(np.searchsorted(KN, a, side="right") - 1, 0, KN.size - 2)
    return j.astype("int64"), (a - KN[j]) / (KN[j + 1] - KN[j])


def fold_basis(folds):
    """Square-root factors of each fold's covariance eta(a1, a2) / n_v on the knot grid."""
    Bs = []
    for f in folds:
        ev, V = np.linalg.eigh(f["Sig_kn"])
        o = np.argsort(ev)[::-1][:R_EIG]
        Bs.append(V[:, o] * np.sqrt(np.maximum(ev[o], 0.0)))
    return np.stack(Bs)


def curve_model(a, y, wt, fid=None, Bf=None, monotone=True):
    j, w = interp_idx(a)
    jg, wg = interp_idx(T_GRID)
    coords = {"step": KN[1:], "dose": T_GRID}
    with pm.Model(coords=coords) as m:
        j_d, w_d = pm.Data("j", j), pm.Data("w", w)
        z_d = pm.Data("z", (np.asarray(a) - 2.5) / 2.5)
        y_d, wt_d = pm.Data("y", y), pm.Data("wt", wt)
        alpha = pm.Normal("alpha", 0.0, 2.0)                  # curve at zero spend
        tau = pm.HalfNormal("tau", 0.3)                       # typical rise per $2.5k step
        if monotone:
            dr = pm.HalfNormal("dr", 1.0, dims="step")
        else:
            dr = pm.Normal("dr", 0.0, 1.0, dims="step")
        knots = pt.concatenate([pt.stack([alpha]), alpha + pt.cumsum(tau * dr)])
        s = pm.Normal("s", 0.0, 1.0, shape=3)                 # log noise scale, quadratic in spend
        nu = pm.Gamma("nu", 2.0, 0.1)
        mu = knots[j_d] * (1 - w_d) + knots[j_d + 1] * w_d
        if Bf is not None:                                    # the fold's shared error curve
            f_d, B_d = pm.Data("fid", fid), pm.Data("Bf", Bf)
            zeta = pm.Normal("zeta", 0.0, 1.0, shape=(Bf.shape[0], Bf.shape[2]))
            e_kn = (B_d * zeta[:, None, :]).sum(-1)
            mu = mu + e_kn[f_d, j_d] * (1 - w_d) + e_kn[f_d, j_d + 1] * w_d
        sig = pt.exp(s[0] + s[1] * z_d + s[2] * z_d**2)
        # Student-t likelihood, weighted so that trimmed rows (weight 0) drop out
        pm.Potential("lik", (wt_d * pm.logp(pm.StudentT.dist(nu=nu, mu=mu, sigma=sig), y_d)).sum())
        pm.Deterministic("theta", knots[jg] * (1 - wg) + knots[jg + 1] * wg, dims="dose")
    return m


BF_ALL = fold_basis(FOLDS)
M_MONO = curve_model(a_all, xi_all, wt_all, monotone=True)
M_MONO_F = curve_model(a_all, xi_all, wt_all, fid_all, BF_ALL, monotone=True)
M_FREE_F = curve_model(a_all, xi_all, wt_all, fid_all, BF_ALL, monotone=False)
for v, Bv in enumerate(BF_ALL):
    print(f"fold {v}: sd of the shared error curve at spend 0, 2.5, 5: "
          f"{np.round(np.sqrt((Bv**2).sum(axis=1))[[0, 10, 20]], 3)}")

pri = {}
for lab, mod in (("monotone (half-normal steps)", M_MONO), ("unconstrained (normal steps)", M_FREE_F)):
    pri[lab] = pm.sample_prior_predictive(draws=500, model=mod, random_seed=RANDOM_SEED, var_names=["theta"])
    th_p = pri[lab].prior["theta"].values.reshape(-1, T_GRID.size)
    rise = th_p[:, I475] - th_p[:, int(np.argmin(abs(T_GRID - 0.2)))]
    print(f"{lab}: prior rise from $2k to $47.5k, 5/50/95%: {np.round(np.quantile(rise, [0.05, 0.5, 0.95]), 2)}")
fold 0: sd of the shared error curve at spend 0, 2.5, 5: [0.063 0.083 0.126]
fold 1: sd of the shared error curve at spend 0, 2.5, 5: [0.064 0.083 0.127]
monotone (half-normal steps): prior rise from $2k to $47.5k, 5/50/95%: [0.2  2.61 8.63]
unconstrained (normal steps): prior rise from $2k to $47.5k, 5/50/95%: [-1.89  0.01  2.02]
fig, axes = plt.subplots(1, 2, figsize=(12, 3.8), sharey=True)
for ax, (lab, pp) in zip(axes, pri.items()):
    th_p = pp.prior["theta"].values.reshape(-1, T_GRID.size)
    for i in range(40):
        ax.plot(T_GRID, th_p[i], color=PURPLE, alpha=0.35, lw=1)
    ax.plot(gg, theta_true(gg), color=INK, lw=2.5)
    ax.set_title(f"prior curves: {lab}")
    ax.set_xlabel("weekly spend ($10k)")
axes[0].set_ylabel("$100k per week")
axes[0].set_ylim(-6, 10);
Figure

The shared error curve has an sd of about 0.06 at zero spend, 0.08 at \$25k and 0.13 at \$50k in each fold. Averaged over two folds that is \$5k to \$9k of weekly sales, about the size of the offset we saw in the flat bins of part B.

The priors are weak where it matters. Under the monotone prior the curve rises by 0.2 to 8.6 (5% to 95%) from \$2k to \$47.5k, from nearly flat to four times the truth; the unconstrained prior is centred on no rise at all. Neither says where the curve flattens.

TIMES = {}
t0 = time.time()
COMP = {"mono": nutpie.compile_pymc_model(M_MONO), "mono_fold": nutpie.compile_pymc_model(M_MONO_F),
        "free_fold": nutpie.compile_pymc_model(M_FREE_F)}
TIMES["compile 3 models"] = time.time() - t0
print(f"compiled three models in {TIMES['compile 3 models']:.0f} s")


def fit(key, a, y, wt, fid=None, Bf=None, chains=4, tune=400, draws=1000, seed=RANDOM_SEED):
    j, w = interp_idx(a)
    dat = dict(j=j, w=w, z=(np.asarray(a) - 2.5) / 2.5, y=np.asarray(y, float), wt=np.asarray(wt, float))
    if fid is not None:
        dat.update(fid=fid.astype("int64"), Bf=Bf)
    return nutpie.sample(COMP[key].with_data(**dat), chains=chains, tune=tune, draws=draws, seed=seed,
                         progress_bar=False)


def sim_band(draws, prob=0.95):
    """Simultaneous credible band: mean +- q sd, q the prob-quantile of the largest standardised deviation."""
    mean, sd = draws.mean(axis=0), draws.std(axis=0)
    q = np.quantile(np.max(np.abs(draws - mean) / sd, axis=1), prob)
    return mean - q * sd, mean + q * sd, q


def project(draws):
    """Projection posterior: each draw replaced by its closest nondecreasing curve on the grid."""
    return np.stack([isotonic_regression(d).x for d in draws])


SPECS = {"naive: monotone fit to raw sales": ("mono", y_all, np.ones(N), False),
         "monotone, pseudo-outcomes": ("mono", xi_all, wt_all, False),
         "monotone + fold curves": ("mono_fold", xi_all, wt_all, True),
         "unconstrained + fold curves": ("free_fold", xi_all, wt_all, True)}
POST, diag_rows = {}, []
for lab, (key, resp, wts, use_fold) in SPECS.items():
    t0 = time.time()
    tr = fit(key, a_all, resp, wts, fid_all if use_fold else None, BF_ALL if use_fold else None)
    TIMES[lab] = time.time() - t0
    names = ["alpha", "tau", "s", "nu", "theta"]
    diag_rows.append({"fit": lab, "seconds": round(TIMES[lab]),
                      "divergences": int(tr.sample_stats["diverging"].sum()),
                      "max r_hat": round(max(float(az.rhat(tr.posterior[v]).max()) for v in names), 3),
                      "min bulk ESS": int(min(float(az.ess(tr.posterior[v]).min()) for v in names)),
                      "tuning steps": int(tr.warmup_posterior.sizes["draw"])
                      if "warmup_posterior" in tr.children else 400})
    POST[lab] = tr.posterior["theta"].values.reshape(-1, T_GRID.size)
    del tr
POST["projection of the unconstrained fit"] = project(POST["unconstrained + fold curves"])
print(pd.DataFrame(diag_rows).to_string(index=False))

BAY = {}
for lab, d in POST.items():
    lo, up, q = sim_band(d)
    inc = d[:, I475] - d[:, I30]
    BAY[lab] = dict(lo=lo, up=up, q=q, inc=inc)
    miss = T_GRID[(lo > TH) | (TH > up)]
    print(f"\n{lab}: q = {q:.2f}, covers at every dose: {miss.size == 0}"
          + (f" (misses at spend {miss.min():.2f}-{miss.max():.2f}, {miss.size} of {T_GRID.size} doses)" if miss.size else ""))
    print(f"  median width: rising part {np.median((up - lo)[RISE]):.2f}, flat part {np.median((up - lo)[FLAT]):.2f}")
    print(f"  gain from $30k to $47.5k: mean {inc.mean():.3f}, 90% interval [{np.quantile(inc, 0.05):.3f}, "
          f"{np.quantile(inc, 0.95):.3f}], P(gain > break-even {BREAK_EVEN}) {np.mean(inc > BREAK_EVEN):.3f}")
compiled three models in 21 s
                             fit  seconds  divergences  max r_hat  min bulk ESS  tuning steps
naive: monotone fit to raw sales        3            1      1.004          1040           400
       monotone, pseudo-outcomes       10            0      1.005           747           400
          monotone + fold curves       13            0      1.007          1110           400
     unconstrained + fold curves       13            1      1.004           689           400

naive: monotone fit to raw sales: q = 3.01, covers at every dose: False (misses at spend 0.20-4.80, 52 of 93 doses)
  median width: rising part 0.76, flat part 0.77
  gain from $30k to $47.5k: mean 0.832, 90% interval [0.509, 1.199], P(gain > break-even 0.175) 1.000

monotone, pseudo-outcomes: q = 3.13, covers at every dose: False (misses at spend 3.25-4.80, 32 of 93 doses)
  median width: rising part 0.24, flat part 0.13
  gain from $30k to $47.5k: mean 0.129, 90% interval [0.079, 0.183], P(gain > break-even 0.175) 0.079

monotone + fold curves: q = 2.82, covers at every dose: False (misses at spend 4.25-4.80, 12 of 93 doses)
  median width: rising part 0.36, flat part 0.43
  gain from $30k to $47.5k: mean 0.145, 90% interval [0.087, 0.210], P(gain > break-even 0.175) 0.212

unconstrained + fold curves: q = 2.98, covers at every dose: True
  median width: rising part 0.40, flat part 0.52
  gain from $30k to $47.5k: mean 0.012, 90% interval [-0.120, 0.145], P(gain > break-even 0.175) 0.021

projection of the unconstrained fit: q = 2.88, covers at every dose: True
  median width: rising part 0.38, flat part 0.47
  gain from $30k to $47.5k: mean 0.081, 90% interval [0.015, 0.152], P(gain > break-even 0.175) 0.018
fig, axes = plt.subplots(2, 2, figsize=(12, 7.6), sharex=True, sharey=True)
panels = ["naive: monotone fit to raw sales", "monotone, pseudo-outcomes", "monotone + fold curves",
          "projection of the unconstrained fit"]
for ax, lab, c_ in zip(axes.ravel(), panels, [RED, ORANGE, PURPLE, AQUA]):
    b = BAY[lab]
    d = DV["Makarov"]
    ax.fill_between(T_GRID, d["lo"], d["up"], color=LIGHT, alpha=0.7, lw=0, label="paper's band (Makarov)")
    ax.fill_between(T_GRID, b["lo"], b["up"], color=c_, alpha=0.4, lw=0, label="95% simultaneous credible band")
    ax.plot(T_GRID, POST[lab].mean(axis=0), color=c_, lw=1.5)
    ax.plot(gg, theta_true(gg), color=INK, lw=2)
    miss = (b["lo"] > TH) | (TH > b["up"])
    ax.plot(T_GRID[miss], TH[miss], "x", color=RED, ms=5)
    ax.set_title(lab, fontsize=10)
axes[0, 0].legend(loc="upper left", fontsize=8)
axes[0, 0].set_ylim(-1.5, 4)
for ax in axes[1]:
    ax.set_xlabel("weekly spend ($10k)")
for ax in axes[:, 0]:
    ax.set_ylabel("$100k per week");
Figure

All four fits sampled cleanly under nutpie (default 400 warm-up steps, four chains of 1,000 draws): at most one divergence, r_hat at most 1.007, and the smallest bulk ESS near 700. The bands are another matter.

The naive fit to raw sales is monotone and confidently wrong. It misses the true curve at more than half the doses: too low below \$12k, too high past \$30k, and it says the move from \$30k to \$47.5k adds about \$83k a week (90% interval \$51k to \$120k), with posterior probability 1.00 that it beats the break-even. The shape constraint cannot repair confounding.

The monotone fit to the pseudo-outcomes has the right shape and a band so narrow, 0.13 in the flat stretch, that the true curve falls outside it at every dose from \$32.5k on. The model treats 2,000 pseudo-outcomes as independent and cannot know about the offset that every week in a fold shares.

Adding the fold curves widens the band to 0.43 in the flat stretch, close to the paper's summed band, and it now misses only above \$42.5k. What remains is a bias, and it comes from the prior. Each half-normal step is positive with probability one, so on a flat stretch eight small positive steps add up to a slope that is not there. The posterior puts the gain from \$30k to \$47.5k at \$14.5k (90% interval \$8.7k to \$21k) when the truth is zero, and gives a 21% chance that the extra spend pays for itself.

The projection posterior removes that bias by a different route (Lin & Dunson 2014; Chakraborty & Ghosal 2021). We fit the unconstrained model with fold curves, then replace each posterior draw by its closest nondecreasing curve on the grid (an isotonic regression per draw). A draw that wobbles on a flat stretch is projected onto a flat or nearly flat curve rather than a steady climb. The unconstrained band covers the truth and is 0.52 wide in the flat stretch; its projection also covers and is 0.47 wide, against 0.80 for the paper's Makarov band and 0.51 for its summed version.

fig, axes = plt.subplots(1, 2, figsize=(12, 4.0))
ax = axes[0]
for lab, c_ in (("monotone + fold curves", PURPLE), ("projection of the unconstrained fit", AQUA)):
    ax.hist(BAY[lab]["inc"], bins=60, range=(-0.05, 0.6), color=c_, alpha=0.6, density=True, label=lab)
for lab, ls in (("Makarov", "-"), ("joint Gaussian", "--")):
    ax.axvline(DV[lab]["up"][I475] - DV[lab]["lo"][I30], color=INK, ls=ls, lw=1.2, label=f"largest gain the band allows ({lab})")
ax.axvline(0, color=RED, lw=2, label="truth: 0")
ax.axvline(BREAK_EVEN, color=ORANGE, lw=2, ls=":", label="break-even: 0.175")
ax.set_xlabel("gain in weekly sales from $30k to $47.5k ($100k)")
ax.set_title("What does the last $17.5k buy?")
ax.legend(fontsize=7.5, loc="upper right", bbox_to_anchor=(0.9, 1.0))
ax = axes[1]
A0 = T_GRID[T_GRID <= 4.75]
ax.plot(A0, theta_true(4.75) - theta_true(A0), color=INK, lw=2.5, label="truth")
d = DV["Makarov"]
ax.plot(A0, d["up"][I475] - d["lo"][: A0.size], color=BLUE, lw=2, label="bound from the paper's band (Makarov)")
pp = POST["projection of the unconstrained fit"]
gain = pp[:, [I475]] - pp[:, : A0.size]
ax.fill_between(A0, np.quantile(gain, 0.025, axis=0), np.quantile(gain, 0.975, axis=0), color=AQUA, alpha=0.4, lw=0,
                label="projection posterior, 95% pointwise")
ax.set_xlabel("current weekly spend a ($10k)")
ax.set_ylabel(r"$\theta(4.75) - \theta(a)$")
ax.set_title("Gain still available by raising spend to $47.5k")
ax.legend(fontsize=8);
Figure

The left panel is the lead's question in one picture. The projection posterior puts the gain from the last \$17.5k at \$8k a week (90% interval \$1.5k to \$15k), with a 2% chance of clearing the break-even. The monotone fit with positive steps sits to its right at \$14.5k and gives the extra spend a 21% chance. The paper's band, read as a bound on the gain, allows up to \$91k (or \$54k), five times the break-even.

Most of the gap comes from what each is built to describe. The band describes the curve's level, which carries the market-mix error, here a nearly constant offset plus a small tilt. A difference $\theta(4.75) - \theta(3)$ cancels the offset, and the joint posterior lets that happen; a band on the level cannot. The right panel shows it for every starting spend $a$: the band's bound on the gain still available stays near \$90k from \$30k on, while the posterior falls toward zero with the truth. Even the projection posterior leans upward on the flat stretch (mean gain \$8k where the truth is zero), because projecting noise onto increasing curves can only add steps.

E · Over repeated data sets

One data set shows what each method does; it cannot show how often. We draw ten new data sets from the same planner and the same market, rebuild the pseudo-outcomes, the paper's two bands (1,000 Monte Carlo draws each) and three of the Bayesian fits (two chains of 250 draws after 250 warm-up steps, refitting the compiled models with new data). For each method we record whether the band holds the whole curve on the grid, its median width in the rising and the flat parts, and whether its 95% upper bound on the gain from \$30k to \$47.5k falls below the break-even, which is the right call in this world. Ten data sets give coverage in steps of 10 points, enough to separate 10% from 90% and not enough to separate 90% from 95%.

N_REP = 10
rng_rep = np.random.default_rng(RANDOM_SEED + 3)
rep_rows, width_curves, n_trim = [], {}, 0
t0 = time.time()
for r in range(N_REP):
    Lr, Ar, Yr, _ = simulate(N, rng_rep)
    fr = pseudo_outcomes(Lr, Ar, Yr, rng_rep)
    ar, xr, _, fidr, wtr = stack(fr)
    n_trim += int((wtr == 0).sum())
    Bfr = fold_basis(fr)
    bands, _ = dv_band(fr, rng_rep, R=1000)
    out = {f"paper, {k}": (b["lo"], b["up"], None) for k, b in bands.items()}
    for lab, key, use_fold in (("Bayes, monotone, no fold curves", "mono", False),
                               ("Bayes, monotone + fold curves", "mono_fold", True),
                               ("Bayes, projection + fold curves", "free_fold", True)):
        tr = fit(key, ar, xr, wtr, fidr if use_fold else None, Bfr if use_fold else None, chains=2, tune=250,
                 draws=250, seed=RANDOM_SEED + r)
        dr_ = tr.posterior["theta"].values.reshape(-1, T_GRID.size)
        n_div = int(tr.sample_stats["diverging"].sum())
        del tr
        if "projection" in lab:
            dr_ = project(dr_)
        lo, up, _ = sim_band(dr_)
        out[lab] = (lo, up, dr_[:, I475] - dr_[:, I30], n_div)
    for lab, o in out.items():
        lo, up = o[0], o[1]
        row = {"rep": r, "method": lab, "covers": bool(np.all((lo <= TH) & (TH <= up))),
               "width rising": np.median((up - lo)[RISE]), "width flat": np.median((up - lo)[FLAT]),
               "gain bound": (up[I475] - lo[I30]) if o[2] is None else np.quantile(o[2], 0.95)}
        row["says it does not pay"] = bool(row["gain bound"] < BREAK_EVEN)
        if o[2] is not None:
            row["divergences"] = o[3]
        rep_rows.append(row)
        width_curves.setdefault(lab, []).append(up - lo)
TIMES["replication"] = time.time() - t0
REP = pd.DataFrame(rep_rows)
summary = REP.groupby("method", sort=False).agg(
    coverage=("covers", "mean"), width_rising=("width rising", "median"), width_flat=("width flat", "median"),
    gain_bound=("gain bound", "median"), says_no_pay=("says it does not pay", "mean"), divergences=("divergences", "sum"))
print(f"{N_REP} data sets in {TIMES['replication']:.0f} s; {n_trim} market-weeks trimmed in all\n")
print(summary.round(2).to_string())
10 data sets in 168 s; 1 market-weeks trimmed in all

                                 coverage  width_rising  width_flat  gain_bound  says_no_pay  divergences
method                                                                                                   
paper, Makarov                        1.0          0.85        0.75        1.09          0.0          0.0
paper, joint Gaussian                 0.9          0.62        0.49        0.74          0.0          0.0
Bayes, monotone, no fold curves       0.1          0.23        0.12        0.16          0.7          0.0
Bayes, monotone + fold curves         0.7          0.35        0.40        0.20          0.2          0.0
Bayes, projection + fold curves       0.9          0.37        0.45        0.12          0.8          0.0
fig, axes = plt.subplots(1, 2, figsize=(12, 4.2), gridspec_kw={"width_ratios": [1.5, 1]})
ax = axes[0]
cols = {"paper, Makarov": BLUE, "paper, joint Gaussian": AQUA, "Bayes, monotone, no fold curves": ORANGE,
        "Bayes, monotone + fold curves": PURPLE, "Bayes, projection + fold curves": INK}
for lab, c_ in cols.items():
    wc = np.median(np.array(width_curves[lab]), axis=0)
    ax.plot(T_GRID, wc, color=c_, lw=2, label=f"{lab} (covered {REP[REP.method == lab].covers.mean():.0%})")
ax.axvline(A_SAT, color=MUTED, ls=":", lw=1)
ax.set_ylim(0, 1.6)
ax.set_xlabel("weekly spend ($10k)")
ax.set_ylabel(f"median band width over {N_REP} data sets")
ax.set_title("Width of the 95% simultaneous bands")
ax.legend(fontsize=7.5, loc="upper right")
ax = axes[1]
labs = list(cols)
ax.barh(range(len(labs)), [summary.loc[k, "coverage"] for k in labs], color=[cols[k] for k in labs], alpha=0.8)
ax.axvline(0.95, color=RED, ls="--", lw=1.5, label="nominal 95%")
ax.set_yticks(range(len(labs)), [k.replace(", ", ",\n", 1) for k in labs], fontsize=8)
ax.set_xlim(0, 1.05)
ax.set_xlabel(f"share of {N_REP} data sets where the band holds the whole curve")
ax.set_title("Simultaneous coverage")
ax.legend(fontsize=8);
Figure

The pattern of the single data set holds. The Makarov band covered the curve in all ten data sets, the summed version in nine, with median widths in the flat stretch of 0.75 and 0.49. The monotone Bayesian fit without fold curves covered once in ten: a band of width 0.12 is an illusion of precision. With fold curves it covered seven times in ten. The projection posterior covered nine times in ten with a width of 0.45 in the flat part, close to the summed band. No replicate fit had a divergence.

On the decision, the paper's bands never ruled out that the extra spend pays: their median bound on the gain is \$109k and \$74k. The projection posterior's 95% upper bound fell below \$17.5k in eight data sets out of ten (median \$12k). The monotone fit without fold curves did so in seven, but from a band that misses the curve nine times in ten, so it is right for the wrong reason. The positive-step fit with fold curves got it right twice. One caveat weighs on all of this: we tested only a world where the right answer is "it does not pay". A method that always said no would score perfectly here; the second extension below tests the other world.

On the left, the paper's bands are widest at the edges, where few weeks sit and windows can only extend one way, and narrowest around \$30k. The Bayesian bands are nearly level, since their width is mostly the fold curves' offset (the sawtooth comes from the knot grid).

F · What this means for response curves in an MMM

Response curves in a marketing mix model are shape-constrained by construction: a Hill or logistic saturation curve is nondecreasing and, past its inflection, concave. Three lessons carry over.

The constraint does real work only on unbiased inputs. Monotonicity let the paper's band use wide windows on the flat stretch and let the projection posterior flatten noise; neither helped the naive fit. Spend planned from a demand forecast makes a curve steeper and later to saturate than the truth, and the same happens in an MMM whose controls miss the planner's inputs (seasonality, last year's sales, a regional forecast). The pseudo-outcome route needs those inputs and assumes nothing else drives both spend and sales.

How a prior encodes the constraint decides what it says about flat stretches. Positive increments, and Hill curves that approach their ceiling only asymptotically, lean toward "a bit more spend still helps". On a flat stretch that lean becomes a small, confident, positive marginal return, which is exactly the number a budget optimiser acts on. Projecting an unconstrained posterior onto the constraint, or a prior with real mass on zero steps, is cheap.

Ask the question as a contrast. Marginal return is a difference between two points of the curve, and the uncertainty about the population of markets (the paper's $\eta$ term) largely cancels in it. The paper's band is the right tool for "show me the curve with an honest error bar", with coverage to spare; for "what does the next \$17.5k buy" the joint posterior of the contrast, or a band built for it, answers more sharply. In a real geo panel the dependence also runs within markets over time, and carryover has to be modelled too.

Summary

  • Planned spend biases the naive curve toward the costly answer. With spend correlated 0.32 with a demand score, sales by spend bin ran \$100k below the truth at low spend and \$30k to \$80k above it past \$30k, still climbing where the truth is flat; a monotone fit to raw sales gave the last \$17.5k a gain of \$83k a week. Limit: one confounding strength, ten times the paper's.
  • Cross-fitted doubly robust pseudo-outcomes put the curve back, to within about \$10k in the rising part. Limit: both nuisance models were in the right family, and as the paper's Remark 4.1 says, double robustness protects a band very little.
  • The paper's monotone band covered the whole curve in 10 of 10 data sets with the Makarov critical value (2.6) and 9 of 10 with the summed one (0.77), with median widths of 0.85 and 0.62 where the curve rises and 0.75 and 0.49 where it is flat. Limit: simplified grids, a plug-in Monte Carlo critical value, and ten data sets cannot separate 90% from 95%.
  • The in-fold average makes pseudo-outcomes dependent, and that is most of the error on the flat stretch. The standard error with the $\eta$ term matched or slightly exceeded the spread over 20 data sets; without it the error was understated by up to half, and a Bayesian fit that ignored it covered once in ten. Limit: it also caps what adaptivity can gain.
  • Fold curves plus a projection posterior gave a Bayesian band that covered 9 of 10 times at the summed band's width (0.45 on the flat stretch) and put the gain from the last \$17.5k at \$8k (90% interval \$1.5k to \$15k), below break-even in 8 of 10 data sets. Positive half-normal steps instead invented a slope (gain \$14.5k, coverage 7 of 10). Limit: a cut posterior with no guarantee, tested only in a world where the spend does not pay.
  • A band on the level answers a contrast conservatively. Read as a bound on the gain, the paper's band allowed \$91k (\$54k summed) and never ruled out that the spend pays, because the market-mix offset that cancels in a difference stays in the level. Limit: we did not build the paper's construction for a contrast.

Try it yourself

  1. The paper's world. Set S_CONF = 0.05 and rerun parts C and E. How much narrower is the paper's band on the flat stretch once the $\eta$ term is small, and does the Makarov bound still cost a factor of three in $\kappa$? Then try S_CONF = 1.0 and watch the propensity ratios and the trimming.
  2. A world where the spend pays. Move the saturation point to A_SAT = 4.5 (and adjust FLAT), so the gain from \$30k to \$47.5k is above the break-even. Which methods now say it pays, and how often does the projection posterior's 95% upper bound still fall below \$17.5k?
  3. Out-of-fold averaging. In pseudo_outcomes, average $\hat\mu_{-v}(L_k, A_i)$ over the other fold's markets instead of the fold's own, and use the same markets for $\hat\omega$. The paper reports narrower bands that lose coverage on flat regions; measure both in part E, for the paper's band and for the projection posterior with and without fold curves.
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 248 s