Skip to content

CCausal inference · causal.synth

Synthetic control

What would have happened to one treated unit (a state, a country, a store) without the intervention?

Builds a weighted combination of untreated donor units whose outcomes (and optional predictors) track the treated unit before the intervention; the gap afterwards is the estimated effect. Inference by placebo-in-space (each donor treated in turn, ranked by post/pre RMSPE), with leave-one-donor-out robustness.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Outcomes only”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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).
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).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Outcomes onlyc1_synth · outcome: packs · time: year · unit: state
  • Predictorsc1_synth · covariates: income, price · outcome: packs · time: year · unit: state
  • Other unit no looc1_synth · outcome: packs · time: year · unit: state
  • Degenerate n3c1_synth · outcome: packs · time: year · unit: state
  • Degenerate single levelc1_synth · outcome: packs · time: year · unit: state
  • Degenerate tiesc1_synth · outcome: packs · time: year · unit: state

In the guides

Where it sits in the decision guides

  • Causal inference (experiments, DiD, IV, RDD) · DS & ML Decision Guide · Explain — why is it happening?

What you need

Outcomenumeric · 1 column
The outcome series for every unit (treated and donors).
Unitcategorical · 1 column · 3–500 levels
The treated unit and the donor pool.
Timenumeric · 1 column
Period as a number (year, month index).
Predictorsnumeric · 0–10 columns
Optional predictors averaged over the pre-period and matched alongside the pre-period outcomes.

Choices you make

hypothesis

Treated unitdefault —

The unit that received the intervention.

First treated perioddefault —

First period in which the treated unit was affected.

statistics

Placebo-in-space inferencedefault on

Refit pretending each donor was treated, to see how unusual the treated unit's gap is.

Leave-one-donor-outdefault on

Refit leaving out each donor in turn, to check that no single donor drives the result.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • No spilloversNot checked from data: state why it holds

    The intervention did not affect the donor units.

  • Good pre-period fit

    The synthetic unit tracks the treated unit closely before the intervention.

  • Within the donors' range

    The treated unit's pre-period path can be reproduced by a weighted average of donors (no extrapolation).

  • Donor pool

    Enough comparable untreated units to build the synthetic unit from.

  • Placebo-in-space

    The same analysis with each donor as if treated; the real gap should stand out.

  • Leave-one-donor-out

    The estimate should not hinge on one donor.

What it reports

estimate
How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
ci_low
A range of effect values compatible with your data at the chosen confidence level.
ci_high
A range of effect values compatible with your data at the chosen confidence level.
p_value
How surprising your data would be if the null hypothesis were true, as a probability.
n
How many independent units the analysis used; it sets precision and power.
estimand
The exact quantity an analysis targets, such as a difference in means or a ratio of medians.
effect_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
claim_level_max
How strong a causal statement the design supports, from association up to a causal effect.
pre_rmspe
A weighted mix of untreated units that tracks a treated unit before the intervention and stands in for it after.
post_rmspe
A weighted mix of untreated units that tracks a treated unit before the intervention and stands in for it after.
rmspe_ratio
A weighted mix of untreated units that tracks a treated unit before the intervention and stands in for it after.
placebo_p
How surprising your data would be if the null hypothesis were true, as a probability.
placebo_rank
Rerun the analysis where no effect should exist. An "effect" there means your method finds things that aren't real.
n_donors
How many independent units the analysis used; it sets precision and power.
treated_unit
The unit that received the intervention and is compared with its synthetic control.
treatment_start
First period in which the treated unit was affected; earlier periods form the pre-period used to fit the weights.
n_pre
How many independent units the analysis used; it sets precision and power.
n_post
How many independent units the analysis used; it sets precision and power.

Per group, level or term: check[<id>], gap[<period>], weight[<donor>], loo_min, loo_max

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, codesplash; R uses nnls, nanoparquet, codesplashr.

Default traps between the two languages

  • Weights solve the synthetic-control QP with V = I over standardized predictors (pre-period outcomes, optional predictor means): non-negative least squares with the adding-up constraint as a heavily weighted row (Lawson–Hanson in both engines: scipy.optimize.nnls ↔ nnls::nnls). Synth's nested V optimization is not used — it is not reproducible across engines.
Python

The exact script CodeSplash ran for example “Outcomes only” · 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,
})
R

The exact script CodeSplash ran for example “Outcomes only” · 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
))

Sources

  • Abadie, A., Diamond, A., & Hainmueller, J. (2010). Synthetic control methods for comparative case studies. JASA, 105, 493–505.
  • Abadie, A. (2021). Using synthetic controls: feasibility, data requirements, and methodological aspects. Journal of Economic Literature, 59, 391–425.

From the CodeSplash method registry · causal.synth v1.0.2.