Skip to content

Synthetic control

Build a weighted stand-in for one treated unit from untreated donors, then ask how unusual its gap is.

Advanced ~11 min8 steps

What runs in CodeSplash

You will be able to

  • Explain how weights on donors build a comparison for one treated unit
  • Judge pre-period fit before reading the gap
  • Read placebo-in-space inference and its smallest possible p-value

Read first

01

One treated unit

Read

A single state raises its cigarette tax. Difference-in-differences needs a comparison group, but no other state looks quite like it.

A synthetic controlSynthetic controlA weighted mix of untreated units that tracks a treated unit before the intervention and stands in for it after. builds one: a weighted mix of untreated donor states whose past tracks the treated state. Weights are non-negative and add up to 1. After the tax, the gap between the state and its synthetic copy estimates the effect.

The simulated data have 24 donors, 20 years before and 10 after.

02

Read the gap

In the app
Synthetic controlRecorded · Python and R agreeRecorded 2026-11-17 · 59 values compared
R

After 2001, Treated State's packs was on average -5.08 away from its synthetic control (pre-period RMSPE 0.349, built from 7 of 24 donors). Its post/pre RMSPE ratio ranks 1 of 25 units (placebo p = 0.040).

Average post-period gap
−5.084
Pre-period RMSPE
0.3488
Post/pre RMSPE ratio
14.776
Placebo p
.040

Plots

Treated State and its synthetic controlWhere is the series heading, and how uncertain is the forecast?
View data
kindyearpacks
actual1,981110.98
actual1,982112.28
actual1,983112.35
actual1,984112.22
actual1,985113.34
actual1,986113.09
actual1,987114.25
actual1,988113.64
actual1,989113.33
actual1,990113.71
actual1,991113.02
actual1,992112.89
actual1,993112.65
actual1,994111.46
actual1,995110.89
actual1,996112.01
actual1,997109.98
actual1,998110.11
actual1,999109.68
actual2,000109.78
actual2,001105.66
actual2,002106.15
actual2,003107.31
actual2,004107.28
actual2,005106.92
actual2,006107.23
actual2,007107.84
actual2,008108.64
actual2,009107.81
actual2,010109.06
fitted1,981111.17
fitted1,982111.89
fitted1,983112.19
fitted1,984112.76
fitted1,985113.04
fitted1,986113.67
fitted1,987114.14
fitted1,988113.69
fitted1,989113.29
fitted1,990113.27
fitted1,991112.94
fitted1,992113.07
fitted1,993112.26
fitted1,994111.87
fitted1,995111.41
fitted1,996111.27
fitted1,997109.79
fitted1,998110.10
fitted1,999109.85
fitted2,000110.01
fitted2,001110.43
fitted2,002110.03
fitted2,003111.12
fitted2,004111.72
fitted2,005112.45
fitted2,006112.09
fitted2,007113.50
fitted2,008114.18
fitted2,009114.48
fitted2,010114.75
Gap between each unit and its synthetic controlDid the treated unit diverge from its synthetic control more than placebo units did?
View data
Gapyeartreatedstate
−0.19461,981trueTreated State
0.39371,982trueTreated State
0.15911,983trueTreated State
−0.54251,984trueTreated State
0.29551,985trueTreated State
−0.58591,986trueTreated State
0.10351,987trueTreated State
−0.05171,988trueTreated State
0.04241,989trueTreated State
0.44631,990trueTreated State
0.07571,991trueTreated State
−0.18401,992trueTreated State
0.39141,993trueTreated State
−0.40421,994trueTreated State
−0.51801,995trueTreated State
0.73531,996trueTreated State
0.18691,997trueTreated State
0.01121,998trueTreated State
−0.16511,999trueTreated State
−0.22092,000trueTreated State
−4.7682,001trueTreated State
−3.8822,002trueTreated State
−3.8122,003trueTreated State
−4.4432,004trueTreated State
−5.5232,005trueTreated State
−4.8582,006trueTreated State
−5.6622,007trueTreated State
−5.5422,008trueTreated State
−6.6642,009trueTreated State
−5.6852,010trueTreated State
−7.8601,981falseState 01
−1.0871,982falseState 01
2.3091,983falseState 01
8.0941,984falseState 01
14.3321,985falseState 01
17.8421,986falseState 01
20.1011,987falseState 01
17.7981,988falseState 01
17.4881,989falseState 01
16.8701,990falseState 01
11.5721,991falseState 01
9.0861,992falseState 01
3.2511,993falseState 01
−1.4101,994falseState 01
−7.0191,995falseState 01
−9.5381,996falseState 01
−14.3841,997falseState 01
−15.9371,998falseState 01
−16.9381,999falseState 01
−17.2842,000falseState 01
−14.9842,001falseState 01
−12.7652,002falseState 01
−6.7192,003falseState 01
−2.6702,004falseState 01
3.5012,005falseState 01
10.0512,006falseState 01
17.0212,007falseState 01
22.0142,008falseState 01
28.2142,009falseState 01
32.4582,010falseState 01

First 60 of 750 rows.

Assumptions

  • Pre-treatment fit — The synthetic unit tracks the treated unit before treatment (RMSPE 0.349, 25% of its pre-period SD).
  • Placebo-in-space — The treated unit's post/pre RMSPE ratio ranks 1 of 25 (p = 0.040): few placebo units show a gap as large.
  • Donor pool — 24 donor units, 7 with positive weight.
  • Leave-one-donor-out — Dropping any weighted donor leaves the effect between -5.21 and -4.89.

Donor weights

stateWeight
State 040.2238
State 020.2030
State 120.1627
State 070.1517
State 010.1119
State 210.1033
State 100.0437
  • Predictors: 20 pre-period outcomes, each standardized across units (V = I).
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic control
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.synth 1.0.2 · spec f63985dc05aaaee8
# Dataset: c1_synth (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c1_synth.parquet", col_select = c("packs", "state", "year")))
n_input <- nrow(df)
df[["state"]] <- factor(df[["state"]], levels = c("Treated State", "State 01", "State 02", "State 03", "State 04", "State 05", "State 06", "State 07", "State 08", "State 09", "State 10", "State 11", "State 12", "State 13", "State 14", "State 15", "State 16", "State 17", "State 18", "State 19", "State 20", "State 21", "State 22", "State 23", "State 24"))  # stored level order
df <- df[stats::complete.cases(df[c("packs", "state", "year")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("packs", "state", "year"))  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y <- "packs"
UNIT <- "state"
TIME <- "year"
COVARIATES <- c()
treated_unit <- "Treated State"
start <- 2001
do_placebos <- TRUE
do_loo <- TRUE
if (is.null(treated_unit)) stop("Choose the treated unit.")
if (is.null(start)) stop("Set the first treated period.")
units <- levels(df[[UNIT]])
if (!(treated_unit %in% units)) cs_error("CS_E_NOT_A_LEVEL", level = treated_unit, column = UNIT)
times <- sort(unique(as.numeric(df[[TIME]])))
widen <- function(col) {
  m <- matrix(NA_real_, length(times), length(units))
  agg <- aggregate(df[[col]], by = list(t = as.numeric(df[[TIME]]), u = as.character(df[[UNIT]])), FUN = mean)
  m[cbind(match(agg$t, times), match(agg$u, units))] <- agg$x
  m
}
wide <- widen(Y)
complete <- units[colSums(is.na(wide)) == 0]
dropped <- setdiff(units, complete)
if (treated_unit %in% dropped) stop(sprintf("%s is missing %s in some periods; synthetic control needs every period.", treated_unit, Y))
if (length(dropped)) warnings <- c(warnings, sprintf("%d donor unit(s) without data in every period were left out: %s%s.", length(dropped),
                                                      paste(head(dropped, 5), collapse = ", "), if (length(dropped) > 5) "…" else ""))
keep_u <- match(complete, units)
Ym <- wide[, keep_u, drop = FALSE]
C <- lapply(COVARIATES, function(cv) widen(cv)[, keep_u, drop = FALSE])
units <- complete
pre <- times < start
if (sum(pre) < 2 || sum(!pre) < 1) {
  cs_error("CS_E_UNDEFINED", what = "Synthetic control", reason = "it needs at least two periods before treatment and one after")
}
# The treated unit and at least two donors (the role's 3-level minimum; placebos need it).
if (length(units) < 3) cs_error("CS_E_TOO_FEW_GROUPS", column = UNIT, min = 3, k = length(units))
tr <- match(treated_unit, units)
pool <- setdiff(seq_along(units), tr)
P <- cs_causal_synth_predictors(Ym, pre, C)

# %% Fit: weights, gaps, placebo-in-space and leave-one-donor-out
main <- cs_causal_synth_fit(Ym, P, tr, pool, pre)
att <- main$att
pl <- if (do_placebos) cs_causal_synth_placebos(Ym, P, tr, pre) else list()
if (length(pl)) {
  ratios <- vapply(pl, function(r) r$ratio, numeric(1))
  rank <- as.integer(1 + sum(ratios > main$ratio))
  placebo_p <- (1 + sum(ratios >= main$ratio)) / (1 + length(pl))
} else {
  rank <- NULL
  placebo_p <- NULL
}
loo <- if (do_loo) cs_causal_synth_leave_one_out(Ym, P, tr, pool, main$w, pre) else list()

# %% Checks
checks <- list()
add_check <- function(...) checks[[length(checks) + 1]] <<- list(...)
g3 <- function(v) formatC(v, digits = 3, format = "g")
sd_pre <- if (sum(pre) > 1) stats::sd(Ym[pre, tr]) else 0
fit_ratio <- if (sd_pre > 0) main$pre_rmspe / sd_pre else 0
if (fit_ratio > 0.25) {
  add_check(id = "pre_fit", label = "Pre-treatment fit", status = "concern", downgrade_to = "L2",
            detail = sprintf("The synthetic unit misses the treated unit before treatment (RMSPE %s is %.0f%% of its pre-period SD): the post-period gap is not a credible counterfactual.", g3(main$pre_rmspe), 100 * fit_ratio))
} else {
  add_check(id = "pre_fit", label = "Pre-treatment fit", status = "pass",
            detail = sprintf("The synthetic unit tracks the treated unit before treatment (RMSPE %s, %.0f%% of its pre-period SD).", g3(main$pre_rmspe), 100 * fit_ratio))
}
lo_d <- apply(Ym[pre, pool, drop = FALSE], 1, min)
hi_d <- apply(Ym[pre, pool, drop = FALSE], 1, max)
outside <- sum(Ym[pre, tr] < lo_d | Ym[pre, tr] > hi_d)
if (outside > 0) {
  add_check(id = "convex_hull", label = "Within the donors' range", status = "concern",
            detail = sprintf("In %d pre-treatment period(s) the treated unit lies outside every donor's value: weights cannot reproduce it without extrapolation.", outside))
}
if (!is.null(placebo_p)) {
  add_check(id = "placebo", label = "Placebo-in-space", status = if (placebo_p <= 0.1) "pass" else "info",
            detail = if (placebo_p <= 0.1) sprintf("The treated unit's post/pre RMSPE ratio ranks %d of %d (p = %.3f): few placebo units show a gap as large.", rank, length(pl) + 1, placebo_p)
                     else sprintf("The treated unit's post/pre RMSPE ratio ranks %d of %d (p = %.3f): the gap is not unusual among placebo units.", rank, length(pl) + 1, placebo_p))
}
if (length(pool) < 5) {
  add_check(id = "donors", label = "Donor pool", status = "concern", detail = sprintf("Only %d donor units: placebo inference has little resolution.", length(pool)))
} else {
  add_check(id = "donors", label = "Donor pool", status = "pass", detail = sprintf("%d donor units, %d with positive weight.", length(pool), sum(main$w > 1e-6)))
}
if (length(loo)) {
  loo_atts <- vapply(loo, function(r) r$att, numeric(1))
  flips <- sum(sign(loo_atts) != sign(att))
  add_check(id = "leave_one_out", label = "Leave-one-donor-out", status = if (flips > 0) "concern" else "pass",
            detail = if (flips > 0) sprintf("Dropping a donor flips the sign of the effect in %d of %d refits.", flips, length(loo))
                     else sprintf("Dropping any weighted donor leaves the effect between %s and %s.", g3(min(loo_atts)), g3(max(loo_atts))))
}

# %% Result
out <- cs_ml_out_dir("target/academy-parity/run-953/causal.synth/outcomes-only/out-r")
wdf <- data.frame(unit = units[pool], weight = main$w)
wdf <- wdf[order(-wdf$weight, method = "radix"), ]
nanoparquet::write_parquet(wdf, file.path(out, "synth_weights.parquet"))
paths <- data.frame(time = times, treated = Ym[, tr], synthetic = main$synthetic, gap = main$gap)
nanoparquet::write_parquet(paths, file.path(out, "synth_paths.parquet"))
artifacts <- list(list(key = "weights", path = file.path(out, "synth_weights.parquet"), format = "parquet", title = "Donor weights"),
                  list(key = "paths", path = file.path(out, "synth_paths.parquet"), format = "parquet", title = "Treated and synthetic paths"))
gap_t <- times; gap_v <- main$gap; gap_u <- rep(treated_unit, length(times)); gap_tr <- rep(TRUE, length(times))
for (r in pl) {
  gap_t <- c(gap_t, times); gap_v <- c(gap_v, r$gap); gap_u <- c(gap_u, rep(units[r$unit], length(times))); gap_tr <- c(gap_tr, rep(FALSE, length(times)))
}
charts <- list(
  cs_chart("paths", "forecast-fan", sprintf("%s and its synthetic control", treated_unit), list(
    time = cs_col(TIME, c(times, times), kind = "numeric"),
    value = cs_col(Y, c(Ym[, tr], main$synthetic), kind = "numeric"),
    kind = cs_col("kind", c(rep("actual", length(times)), rep("fitted", length(times))), kind = "categorical", levels = c("actual", "fitted"))
  )),
  cs_chart("gaps", "synth-gap", "Gap between each unit and its synthetic control", list(
    time = cs_col(TIME, gap_t, kind = "numeric"),
    gap = cs_col("Gap", gap_v, kind = "numeric"),
    unit = cs_col(UNIT, gap_u, kind = "categorical"),
    treated = cs_col("treated", gap_tr, kind = "boolean")
  ), controls = list(intervention = start))
)
summary <- sprintf("After %s, %s's %s was on average %s away from its synthetic control (pre-period RMSPE %s, built from %d of %d donors).",
                   format(start), treated_unit, Y, g3(att), g3(main$pre_rmspe), sum(main$w > 1e-6), length(pool))
if (!is.null(placebo_p)) summary <- paste(summary, sprintf("Its post/pre RMSPE ratio ranks %d of %d units (placebo p = %.3f).", rank, length(pl) + 1, placebo_p))
values <- list(
  estimate = att, se = NULL, ci_low = NULL, ci_high = NULL, p_value = placebo_p, n = length(units),
  pre_rmspe = main$pre_rmspe, post_rmspe = main$post_rmspe, rmspe_ratio = main$ratio,
  placebo_p = placebo_p, placebo_rank = rank, n_donors = length(pool), treated_unit = treated_unit,
  treatment_start = start, n_pre = sum(pre), n_post = sum(!pre),
  loo_min = if (length(loo)) min(vapply(loo, function(r) r$att, numeric(1))) else NULL,
  loo_max = if (length(loo)) max(vapply(loo, function(r) r$att, numeric(1))) else NULL,
  estimand = "ATT for the treated unit (post-period average)",
  effect_label = sprintf("Average post-treatment difference in %s between %s and its synthetic control", Y, treated_unit),
  claim_level_max = "L3"
)
for (i in seq_along(pool)) values[[sprintf("weight[%s]", units[pool[i]])]] <- main$w[i]
for (i in seq_along(times)) if (times[i] >= start) values[[sprintf("gap[%s]", format(times[i]))]] <- main$gap[i]
for (c in checks) values[[sprintf("check[%s]", c$id)]] <- c$status
statistics <- list(
  list(key = "estimate", label = "Average post-period gap", value = att),
  list(key = "pre_rmspe", label = "Pre-period RMSPE", value = main$pre_rmspe),
  list(key = "rmspe_ratio", label = "Post/pre RMSPE ratio", value = main$ratio)
)
if (!is.null(placebo_p)) statistics[[length(statistics) + 1]] <- list(key = "placebo_p", label = "Placebo p", value = placebo_p, format = "p")
cs_publish(list(
  method = "causal.synth",
  methodVersion = "1.0.2",
  title = "Synthetic control",
  engine = cs_engine_info("nnls", "nanoparquet"),
  n = length(units),
  summary = summary,
  statistics = statistics,
  tables = list(list(key = "weights", title = "Donor weights",
                     columns = list(list(key = "unit", label = UNIT, type = "string"), list(key = "weight", label = "Weight", type = "number")),
                     rows = wdf[wdf$weight > 1e-6, , drop = FALSE])),
  assumptions = lapply(checks, function(c) list(key = c$id, label = c$label, status = if (c$status == "concern") "warn" else c$status, detail = c$detail)),
  checks = checks,
  warnings = warnings,
  notes = list(paste0(sprintf("Predictors: %d pre-period outcomes", sum(pre)),
                      if (length(COVARIATES)) sprintf(" and pre-period means of %s", paste(COVARIATES, collapse = ", ")) else "",
                      ", each standardized across units (V = I).")),
  values = values,
  artifacts = artifacts,
  charts = charts
))
Python

After 2001, Treated State's packs was on average -5.08 away from its synthetic control (pre-period RMSPE 0.349, built from 7 of 24 donors). Its post/pre RMSPE ratio ranks 1 of 25 units (placebo p = 0.040).

Average post-period gap
−5.084
Pre-period RMSPE
0.3488
Post/pre RMSPE ratio
14.776
Placebo p
.040

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Pre-treatment fit — The synthetic unit tracks the treated unit before treatment (RMSPE 0.349, 25% of its pre-period SD).
  • Placebo-in-space — The treated unit's post/pre RMSPE ratio ranks 1 of 25 (p = 0.040): few placebo units show a gap as large.
  • Donor pool — 24 donor units, 7 with positive weight.
  • Leave-one-donor-out — Dropping any weighted donor leaves the effect between -5.21 and -4.89.

Donor weights

stateWeight
State 040.2238
State 020.2030
State 120.1627
State 070.1517
State 010.1119
State 210.1033
State 100.0437
  • Predictors: 20 pre-period outcomes, each standardized across units (V = I).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic control
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method causal.synth 1.0.2 · spec f63985dc05aaaee8
# Dataset: c1_synth (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.causal import synth as cssynth

# %% Data
df = pd.read_parquet("tests/parity/fixtures/c1_synth.parquet", columns=["packs", "state", "year"])
n_input = len(df)
df["state"] = pd.Categorical(df["state"], categories=["Treated State", "State 01", "State 02", "State 03", "State 04", "State 05", "State 06", "State 07", "State 08", "State 09", "State 10", "State 11", "State 12", "State 13", "State 14", "State 15", "State 16", "State 17", "State 18", "State 19", "State 20", "State 21", "State 22", "State 23", "State 24"])  # stored level order
df = df.dropna(subset=["packs", "state", "year"])  # listwise deletion over the analysis columns
df["state"] = df["state"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["packs", "state", "year"])  # infinite values stop the run (registry/errors.yaml)

# %% Design
Y, UNIT, TIME = "packs", "state", "year"
COVARIATES = []
treated_unit = "Treated State"
start = 2001
do_placebos, do_loo = True, True
if treated_unit is None:
    raise ValueError("Choose the treated unit.")
if start is None:
    raise ValueError("Set the first treated period.")
units = [str(u) for u in df[UNIT].cat.categories]
if treated_unit not in units:
    cs.cs_error("CS_E_NOT_A_LEVEL", level=treated_unit, column=UNIT)
times = np.sort(df[TIME].astype(float).unique())
wide = df.pivot_table(index=TIME, columns=UNIT, values=Y, aggfunc="mean", observed=False).reindex(index=times, columns=units)
complete = [u for u in units if wide[u].notna().all()]
dropped = [u for u in units if u not in complete]
if treated_unit in dropped:
    raise ValueError(f"{treated_unit} is missing {Y} in some periods; synthetic control needs every period.")
if dropped:
    warnings.append(f"{len(dropped)} donor unit(s) without data in every period were left out: {', '.join(dropped[:5])}{'…' if len(dropped) > 5 else ''}.")
units = complete
Ym = wide[units].to_numpy(dtype=float)
C = [df.pivot_table(index=TIME, columns=UNIT, values=c, aggfunc="mean", observed=False).reindex(index=times, columns=units).to_numpy(dtype=float)
     for c in COVARIATES]
pre = times < float(start)
if pre.sum() < 2 or (~pre).sum() < 1:
    cs.cs_error("CS_E_UNDEFINED", what="Synthetic control", reason="it needs at least two periods before treatment and one after")
if len(units) < 3:  # the treated unit and at least two donors (the role's 3-level minimum; placebos need it)
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=UNIT, min=3, k=len(units))
tr = units.index(treated_unit)
pool = [j for j in range(len(units)) if j != tr]
P = cssynth.predictors(Ym, pre, C)

# %% Fit: weights, gaps, placebo-in-space and leave-one-donor-out
main = cssynth.fit(Ym, P, tr, pool, pre)
att = main["att"]
pl = cssynth.placebos(Ym, P, tr, pre) if do_placebos else []
if pl:
    ratios = np.array([r["ratio"] for r in pl])
    rank = int(1 + (ratios > main["ratio"]).sum())  # 1 = largest post/pre RMSPE ratio
    placebo_p = float((1 + (ratios >= main["ratio"]).sum()) / (1 + len(pl)))
else:
    rank, placebo_p = None, None
loo = cssynth.leave_one_out(Ym, P, tr, pool, main["w"], pre) if do_loo else []

# %% Checks
checks = []
sd_pre = float(np.std(Ym[pre, tr], ddof=1)) if pre.sum() > 1 else 0.0
fit_ratio = main["pre_rmspe"] / sd_pre if sd_pre > 0 else 0.0
if fit_ratio > 0.25:
    checks.append({"id": "pre_fit", "label": "Pre-treatment fit", "status": "concern", "downgrade_to": "L2",
                   "detail": f"The synthetic unit misses the treated unit before treatment (RMSPE {main['pre_rmspe']:.3g} is {fit_ratio:.0%} of its pre-period SD): the post-period gap is not a credible counterfactual."})
else:
    checks.append({"id": "pre_fit", "label": "Pre-treatment fit", "status": "pass",
                   "detail": f"The synthetic unit tracks the treated unit before treatment (RMSPE {main['pre_rmspe']:.3g}, {fit_ratio:.0%} of its pre-period SD)."})
lo_d, hi_d = Ym[pre][:, pool].min(axis=1), Ym[pre][:, pool].max(axis=1)
outside = int(((Ym[pre, tr] < lo_d) | (Ym[pre, tr] > hi_d)).sum())
if outside:
    checks.append({"id": "convex_hull", "label": "Within the donors' range", "status": "concern",
                   "detail": f"In {outside} pre-treatment period(s) the treated unit lies outside every donor's value: weights cannot reproduce it without extrapolation."})
if placebo_p is not None:
    checks.append({"id": "placebo", "label": "Placebo-in-space", "status": "pass" if placebo_p <= 0.1 else "info",
                   "detail": (f"The treated unit's post/pre RMSPE ratio ranks {rank} of {len(pl) + 1} (p = {placebo_p:.3f}): few placebo units show a gap as large." if placebo_p <= 0.1
                              else f"The treated unit's post/pre RMSPE ratio ranks {rank} of {len(pl) + 1} (p = {placebo_p:.3f}): the gap is not unusual among placebo units.")})
if len(pool) < 5:
    checks.append({"id": "donors", "label": "Donor pool", "status": "concern", "detail": f"Only {len(pool)} donor units: placebo inference has little resolution."})
else:
    checks.append({"id": "donors", "label": "Donor pool", "status": "pass", "detail": f"{len(pool)} donor units, {int((main['w'] > 1e-6).sum())} with positive weight."})
if loo:
    loo_atts = [r["att"] for r in loo]
    flips = sum(np.sign(a) != np.sign(att) for a in loo_atts)
    checks.append({"id": "leave_one_out", "label": "Leave-one-donor-out", "status": "concern" if flips else "pass",
                   "detail": (f"Dropping a donor flips the sign of the effect in {flips} of {len(loo)} refits." if flips
                              else f"Dropping any weighted donor leaves the effect between {min(loo_atts):.3g} and {max(loo_atts):.3g}.")})

# %% Result
tl = [float(t) for t in times]
out = csml.out_dir("target/academy-parity/run-953/causal.synth/outcomes-only/out-python")
wdf = pd.DataFrame({"unit": [units[j] for j in pool], "weight": main["w"]}).sort_values("weight", ascending=False, kind="mergesort")
wdf.to_parquet(os.path.join(out, "synth_weights.parquet"), index=False)
paths = pd.DataFrame({"time": tl, "treated": Ym[:, tr], "synthetic": main["synthetic"], "gap": main["gap"]})
paths.to_parquet(os.path.join(out, "synth_paths.parquet"), index=False)
artifacts = [{"key": "weights", "path": os.path.join(out, "synth_weights.parquet"), "format": "parquet", "title": "Donor weights"},
             {"key": "paths", "path": os.path.join(out, "synth_paths.parquet"), "format": "parquet", "title": "Treated and synthetic paths"}]
gap_rows = [(t, g, treated_unit, True) for t, g in zip(tl, main["gap"])]
for r in pl:
    gap_rows += [(t, g, units[r["unit"]], False) for t, g in zip(tl, r["gap"])]
charts = [
    cs.chart("paths", "forecast-fan", f"{treated_unit} and its synthetic control", {
        "time": cs.col(TIME, tl + tl, kind="numeric"),
        "value": cs.col(Y, list(Ym[:, tr]) + list(main["synthetic"]), kind="numeric"),
        "kind": cs.col("kind", ["actual"] * len(tl) + ["fitted"] * len(tl), kind="categorical", levels=["actual", "fitted"]),
    }),
    cs.chart("gaps", "synth-gap", "Gap between each unit and its synthetic control", {
        "time": cs.col(TIME, [r[0] for r in gap_rows], kind="numeric"),
        "gap": cs.col("Gap", [r[1] for r in gap_rows], kind="numeric"),
        "unit": cs.col(UNIT, [r[2] for r in gap_rows], kind="categorical"),
        "treated": cs.col("treated", [r[3] for r in gap_rows], kind="boolean"),
    }, controls={"intervention": float(start)}),
]
summary = (
    f"After {start:g}, {treated_unit}'s {Y} was on average {att:.3g} away from its synthetic control "
    f"(pre-period RMSPE {main['pre_rmspe']:.3g}, built from {int((main['w'] > 1e-6).sum())} of {len(pool)} donors)."
)
if placebo_p is not None:
    summary += f" Its post/pre RMSPE ratio ranks {rank} of {len(pl) + 1} units (placebo p = {placebo_p:.3f})."
values = {
    "estimate": att, "se": None, "ci_low": None, "ci_high": None, "p_value": placebo_p, "n": len(units),
    "pre_rmspe": main["pre_rmspe"], "post_rmspe": main["post_rmspe"], "rmspe_ratio": main["ratio"],
    "placebo_p": placebo_p, "placebo_rank": rank, "n_donors": len(pool), "treated_unit": treated_unit,
    "treatment_start": float(start), "n_pre": int(pre.sum()), "n_post": int((~pre).sum()),
    "loo_min": min(r["att"] for r in loo) if loo else None, "loo_max": max(r["att"] for r in loo) if loo else None,
    "estimand": "ATT for the treated unit (post-period average)",
    "effect_label": f"Average post-treatment difference in {Y} between {treated_unit} and its synthetic control",
    "claim_level_max": "L3",
}
for j, w in zip(pool, main["w"]):
    values[f"weight[{units[j]}]"] = float(w)
for t, g in zip(tl, main["gap"]):
    if t >= float(start):
        values[f"gap[{t:g}]"] = float(g)
for c in checks:
    values[f"check[{c['id']}]"] = c["status"]
cs.publish({
    "method": "causal.synth",
    "methodVersion": "1.0.2",
    "title": "Synthetic control",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(units),
    "summary": summary,
    "statistics": [
        {"key": "estimate", "label": "Average post-period gap", "value": att},
        {"key": "pre_rmspe", "label": "Pre-period RMSPE", "value": main["pre_rmspe"]},
        {"key": "rmspe_ratio", "label": "Post/pre RMSPE ratio", "value": main["ratio"]},
    ] + ([{"key": "placebo_p", "label": "Placebo p", "value": placebo_p, "format": "p"}] if placebo_p is not None else []),
    "tables": [{"key": "weights", "title": "Donor weights",
                "columns": [{"key": "unit", "label": UNIT, "type": "string"}, {"key": "weight", "label": "Weight", "type": "number"}],
                "rows": [r for r in wdf.to_dict("records") if r["weight"] > 1e-6]}],
    "assumptions": [{"key": c["id"], "label": c["label"], "status": {"concern": "warn"}.get(c["status"], c["status"]), "detail": c["detail"]} for c in checks],
    "checks": checks,
    "warnings": warnings,
    "notes": [f"Predictors: {int(pre.sum())} pre-period outcomes" + (f" and pre-period means of {', '.join(COVARIATES)}" if COVARIATES else "") + ", each standardized across units (V = I)."],
    "values": values,
    "artifacts": artifacts,
    "charts": charts,
})

Before treatment, the typical gap (the root mean squared prediction error, RMSPE) is only 0.349 packs. Afterward, sales sit −5.08 packs from the synthetic copy, on average.

Most donors get zero weight, so the copy is a sparse mix of a few states you can name and argue about.

03

How do you test a sample of one?

Predict

Predict first

Pretend each donor was treated instead, and compute each one's post/pre RMSPE ratio. Suppose the real state's ratio is the largest of the 25 units. What p-value does that rank give?

About p = 0.5About p = 0.2About p = 0.04
Reveal

The rank is 1 of 25, so 1 / 25 gives p = .040, the smallest this design can produce. Its ratio is 14.8. This placebo testPlacebo testRerun the analysis where no effect should exist. An "effect" there means your method finds things that aren't real. asks how unusual the gap is among units that weren't treated.

04

A bad fit, for contrast

Predict

Predict first

Now pretend a different state was treated in 1996. Its gap averages 11.1 packs. Its pre-period RMSPE is 2.93, up from 0.349 earlier. Would you report an effect?

Yes: the gap is largeNo: the fit before treatment is poor
Reveal

No. The placebo test gives p = .200, and the run raises concerns about pre-period fit and about whether donors can reproduce this state at all. If it sits outside the donors' range, no weighted average can match it. A copy that didn't track before can't be trusted after.

05

Assumptions and checks

Read
  • No spillovers. The tax mustn't affect donors. If smokers cross the border to buy cheaper cigarettes, nearby states gain sales, and the gap is too large.
  • Good pre-period fit. Check this first.
  • Within the donors' range. No extrapolation.
  • No single donor decides it. Leave-one-out estimates range from −5.21 to −4.89 here, so the result holds up.

Adding predictors barely moves this estimate: −5.21.

06

Check your understanding

Checkpoint

Check yourself

Put a synthetic control study in order.

  1. 1Fit weights on the pre-period only.
  2. 2Read the post-period gap.
  3. 3Choose donors that were not affected by the intervention.
  4. 4Check the pre-period fit.
  5. 5Refit with each donor as a placebo.

Show the answer

The order:

  1. Choose donors that were not affected by the intervention.
  2. Fit weights on the pre-period only.
  3. Check the pre-period fit.
  4. Read the post-period gap.
  5. Refit with each donor as a placebo.

Fit comes before the gap, because a poor fit makes the gap meaningless. Placebos then tell you how unusual that gap is.

Check yourself

You have 9 donors and one treated unit, so 10 units. The treated unit has the largest ratio. What is the placebo p-value?

Show the answer

Answer: 0.1

1 / 10 = 0.1. With so few units, you can't reach 0.05 however large the effect, so report the rank as well as p.

Check yourself

A city bans a product, and shoppers go to neighboring towns, which are in your donor pool. What happens to the estimate?

Show the answer

Answer: b

Spillovers contaminate the donors. Drop nearby units from the pool, and say that you did.

07

Try it

In the app

In the Causal studio's Design step, answer that the same units were observed before and after, and that only one or a few were treated. The studio then recommends a synthetic control.

Method guide · causal.synthSynthetic controlWhat would have happened to one treated unit (a state, a country, a store) without the intervention?
08

Recap

Recap
  • A synthetic control is a weighted mix of donors that tracks one treated unit before the intervention.
  • Check the fit first. A gap only means something if the copy tracked well.
  • Placebos ask how unusual the gap is, and the number of units limits the p-value.
  • Keep affected units out of the donor pool.

Concepts in this lesson