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.
A real result
Example “Outcomes only”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| kind | year | packs |
|---|---|---|
| actual | 1,981 | 110.98 |
| actual | 1,982 | 112.28 |
| actual | 1,983 | 112.35 |
| actual | 1,984 | 112.22 |
| actual | 1,985 | 113.34 |
| actual | 1,986 | 113.09 |
| actual | 1,987 | 114.25 |
| actual | 1,988 | 113.64 |
| actual | 1,989 | 113.33 |
| actual | 1,990 | 113.71 |
| actual | 1,991 | 113.02 |
| actual | 1,992 | 112.89 |
| actual | 1,993 | 112.65 |
| actual | 1,994 | 111.46 |
| actual | 1,995 | 110.89 |
| actual | 1,996 | 112.01 |
| actual | 1,997 | 109.98 |
| actual | 1,998 | 110.11 |
| actual | 1,999 | 109.68 |
| actual | 2,000 | 109.78 |
| actual | 2,001 | 105.66 |
| actual | 2,002 | 106.15 |
| actual | 2,003 | 107.31 |
| actual | 2,004 | 107.28 |
| actual | 2,005 | 106.92 |
| actual | 2,006 | 107.23 |
| actual | 2,007 | 107.84 |
| actual | 2,008 | 108.64 |
| actual | 2,009 | 107.81 |
| actual | 2,010 | 109.06 |
| fitted | 1,981 | 111.17 |
| fitted | 1,982 | 111.89 |
| fitted | 1,983 | 112.19 |
| fitted | 1,984 | 112.76 |
| fitted | 1,985 | 113.04 |
| fitted | 1,986 | 113.67 |
| fitted | 1,987 | 114.14 |
| fitted | 1,988 | 113.69 |
| fitted | 1,989 | 113.29 |
| fitted | 1,990 | 113.27 |
| fitted | 1,991 | 112.94 |
| fitted | 1,992 | 113.07 |
| fitted | 1,993 | 112.26 |
| fitted | 1,994 | 111.87 |
| fitted | 1,995 | 111.41 |
| fitted | 1,996 | 111.27 |
| fitted | 1,997 | 109.79 |
| fitted | 1,998 | 110.10 |
| fitted | 1,999 | 109.85 |
| fitted | 2,000 | 110.01 |
| fitted | 2,001 | 110.43 |
| fitted | 2,002 | 110.03 |
| fitted | 2,003 | 111.12 |
| fitted | 2,004 | 111.72 |
| fitted | 2,005 | 112.45 |
| fitted | 2,006 | 112.09 |
| fitted | 2,007 | 113.50 |
| fitted | 2,008 | 114.18 |
| fitted | 2,009 | 114.48 |
| fitted | 2,010 | 114.75 |
View data
| Gap | year | treated | state |
|---|---|---|---|
| −0.1946 | 1,981 | true | Treated State |
| 0.3937 | 1,982 | true | Treated State |
| 0.1591 | 1,983 | true | Treated State |
| −0.5425 | 1,984 | true | Treated State |
| 0.2955 | 1,985 | true | Treated State |
| −0.5859 | 1,986 | true | Treated State |
| 0.1035 | 1,987 | true | Treated State |
| −0.0517 | 1,988 | true | Treated State |
| 0.0424 | 1,989 | true | Treated State |
| 0.4463 | 1,990 | true | Treated State |
| 0.0757 | 1,991 | true | Treated State |
| −0.1840 | 1,992 | true | Treated State |
| 0.3914 | 1,993 | true | Treated State |
| −0.4042 | 1,994 | true | Treated State |
| −0.5180 | 1,995 | true | Treated State |
| 0.7353 | 1,996 | true | Treated State |
| 0.1869 | 1,997 | true | Treated State |
| 0.0112 | 1,998 | true | Treated State |
| −0.1651 | 1,999 | true | Treated State |
| −0.2209 | 2,000 | true | Treated State |
| −4.768 | 2,001 | true | Treated State |
| −3.882 | 2,002 | true | Treated State |
| −3.812 | 2,003 | true | Treated State |
| −4.443 | 2,004 | true | Treated State |
| −5.523 | 2,005 | true | Treated State |
| −4.858 | 2,006 | true | Treated State |
| −5.662 | 2,007 | true | Treated State |
| −5.542 | 2,008 | true | Treated State |
| −6.664 | 2,009 | true | Treated State |
| −5.685 | 2,010 | true | Treated State |
| −7.860 | 1,981 | false | State 01 |
| −1.087 | 1,982 | false | State 01 |
| 2.309 | 1,983 | false | State 01 |
| 8.094 | 1,984 | false | State 01 |
| 14.332 | 1,985 | false | State 01 |
| 17.842 | 1,986 | false | State 01 |
| 20.101 | 1,987 | false | State 01 |
| 17.798 | 1,988 | false | State 01 |
| 17.488 | 1,989 | false | State 01 |
| 16.870 | 1,990 | false | State 01 |
| 11.572 | 1,991 | false | State 01 |
| 9.086 | 1,992 | false | State 01 |
| 3.251 | 1,993 | false | State 01 |
| −1.410 | 1,994 | false | State 01 |
| −7.019 | 1,995 | false | State 01 |
| −9.538 | 1,996 | false | State 01 |
| −14.384 | 1,997 | false | State 01 |
| −15.937 | 1,998 | false | State 01 |
| −16.938 | 1,999 | false | State 01 |
| −17.284 | 2,000 | false | State 01 |
| −14.984 | 2,001 | false | State 01 |
| −12.765 | 2,002 | false | State 01 |
| −6.719 | 2,003 | false | State 01 |
| −2.670 | 2,004 | false | State 01 |
| 3.501 | 2,005 | false | State 01 |
| 10.051 | 2,006 | false | State 01 |
| 17.021 | 2,007 | false | State 01 |
| 22.014 | 2,008 | false | State 01 |
| 28.214 | 2,009 | false | State 01 |
| 32.458 | 2,010 | false | State 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
| state | Weight |
|---|---|
| State 04 | 0.2238 |
| State 02 | 0.2030 |
| State 12 | 0.1627 |
| State 07 | 0.1517 |
| State 01 | 0.1119 |
| State 21 | 0.1033 |
| State 10 | 0.0437 |
- Predictors: 20 pre-period outcomes, each standardized across units (V = I).
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
| state | Weight |
|---|---|
| State 04 | 0.2238 |
| State 02 | 0.2030 |
| State 12 | 0.1627 |
| State 07 | 0.1517 |
| State 01 | 0.1119 |
| State 21 | 0.1033 |
| State 10 | 0.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.
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,
})
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.