Algorithm Search⌘K

Algorithmadvanced

Synthetic control method

Also called Abadie synthetic control.

Builds a weighted mix of control units that matches the treated unit before the intervention, and estimates the effect by the gap after it.

Time
Θ(t (k J^2 + J^3)) worstΘ(k J^2 + J^3) best
Space
Θ(k J + J^2) extra
Where
J = the number of donor units; k = the number of pre-period features; t = the number of gradient iterations
Properties
convex problemdeterministicexact kkt certificate in rational arithmeticplacebo pvalue valid under exchangeabilityweights nonnegative and sum to one
Origin
Alberto Abadie, Javier Gardeazabal, Alexis Diamond, Jens Hainmueller, 2003

The synthetic control method estimates the effect of an intervention on one unit, such as a state that passes a law, when no single untreated unit is a good comparison. It looks for nonnegative weights, summing to one, on the untreated units (the donor pool) so that the weighted average of their outcomes before the intervention tracks the treated unit's outcomes. This weighted average is the synthetic control. After the intervention, the gap between the treated unit and its synthetic control estimates the effect, period by period. The weights solve a small convex quadratic program over the simplex. This page solves it by projected gradient descent, stops with the Frank-Wolfe gap, which bounds the error, and finishes by solving the KKT conditions on the support exactly, which certifies the answer. Inference comes from placebo runs that treat each donor in turn as if it were treated.

In plain words

California raised its cigarette tax in 1988. To see what the law did to cigarette sales, we need California's sales without the law, which never happened. No other state looks like California. But a blend of several states might. If that blend matched California's sales year by year for the years before 1988, it is a fair guess for what California would have done after 1988 without the law. The difference after 1988 is the estimate.

The weights are nonnegative and add to one, so the blend is an average of real states and never extrapolates outside them. They are found by fitting the past, without looking at the outcomes after the intervention.

The problem

Identification. Unit 1 is treated from period T0+1T_0 + 1 on; units 2,…,J+12, \dots, J + 1 are never treated. For t>T0t > T_0 the target is the effect on the treated unit, τ1t=Y1t(1)−Y1t(0)\tau_{1t} = Y_{1t}(1) - Y_{1t}(0), of which Y1t(1)=Y1tY_{1t}(1) = Y_{1t} is observed. The missing Y1t(0)Y_{1t}(0) is estimated by ∑jwjYjt\sum_j w_jY_{jt}. Abadie, Diamond and Hainmueller (2010) justify this with a linear factor model, Yit(0)=δt+θt⊤Zi+λt⊤μi+εitY_{it}(0) = \delta_t + \theta_t^\top Z_i + \lambda_t^\top\mu_i + \varepsilon_{it}, with observed covariates ZiZ_i and unobserved factor loadings μi\mu_i. If weights reproduce the treated unit's Z1Z_1 and its whole pre-period path, they must also roughly reproduce its μ1\mu_1, so the bias after T0T_0 is small, and it shrinks as the number of pre-periods grows relative to the noise. Unlike difference in differences, the factor model allows different units to load differently on common trends. This argument is cited, not proved here.

Estimation. Collect kk pre-period features of the treated unit in x1x_1: the outcomes in some or all of the pre-periods, and covariates. Collect the same features of the donors in the columns of the k×Jk \times J matrix X0X_0. With feature weights v>0v > 0, V=diag⁡(v)V = \operatorname{diag}(v), the weights are

w∗∈arg⁡min⁡w∈Δ(x1−X0w)⊤V(x1−X0w),Δ={w:wj≥0, ∑jwj=1}.w^* \in \arg\min_{w \in \Delta}(x_1 - X_0w)^\top V(x_1 - X_0w), \qquad \Delta = \{w : w_j \ge 0,\ \textstyle\sum_jw_j = 1\}.

The estimate for t>T0t > T_0 is τ^1t=Y1t−∑jwj∗Yjt\hat\tau_{1t} = Y_{1t} - \sum_jw_j^*Y_{jt}. Choosing vv is a separate outer problem: Abadie and coauthors pick vv to minimize the pre-period prediction error of the outcome, or by cross-validation over an early and a late part of the pre-period. This page takes vv as given, all ones by default.

The algorithm

The problem is a quadratic program with JJ variables, one equality and JJ bounds. Projected gradient descent fits it well, because projection onto the simplex is cheap:

  1. SYNTH(x₁, X₀, v, ε)
  2. 1w ← (1/J, …, 1/J); L ← 2 Σ_r Σ_j v_r X₀[r][j]²
  3. 2repeat
  4. 3g ← -2 X₀ᵀ V (x₁ - X₀ w) ▷ the gradient
  5. 4γ ← gᵀw - min_j g_j ▷ Frank-Wolfe gap, at least f(w) - min f
  6. 5if γ ≤ ε(1 + f(w)) or (every 20th pass) the KKT system on the support of w has a valid solution then exit the loop
  7. 6w ← Π_Δ(w - g/L) ▷ projection: sort, shift, clip at 0
  8. 7solve 2AᵀVA w_S - ν1 = 2AᵀV x₁, 1ᵀw_S = 1 exactly on S = {j : w_j > 0}, A = X₀[:, S]; keep it if w_S > 0 and g_j ≥ ν off S
  9. 8return w

The projection ΠΔ(u)\Pi_\Delta(u) sorts uu, finds the largest ρ\rho with u(ρ)>1ρ(∑l≤ρu(l)−1)=θu_{(\rho)} > \frac1\rho(\sum_{l \le \rho}u_{(l)} - 1) = \theta, and returns max⁡(uj−θ,0)\max(u_j - \theta, 0) (Duchi et al. 2008). The gradient loop runs in floating point. Line L7 runs in the input arithmetic, so with fractions it returns exact rational weights, together with the multiplier ν\nu that certifies them.

Example

Three donors, three pre-periods and one post-period; columns are donors:

period treated donor 1 donor 2 donor 3
1 (pre) 7 5 7 8
2 (pre) 4 5 9 6
3 (pre) 4 3 0 3
4 (post) 10 6 8 7

In period 2 the treated value 4 is below every donor, so no blend can fit exactly. SYNTH stops at its first KKT check after 19 gradient steps and returns w=(1/2,0,1/2)w = (1/2, 0, 1/2). Check by hand: on the edge w=(a,0,1−a)w = (a, 0, 1 - a) the synthetic path is (8−3a,6−a,3)(8 - 3a, 6 - a, 3), the residuals are (3a−1,a−2,1)(3a - 1, a - 2, 1), and the loss (3a−1)2+(a−2)2+1(3a - 1)^2 + (a - 2)^2 + 1 has derivative 20a−1020a - 10, zero at a=1/2a = 1/2, where the loss is 1/4+9/4+1=7/21/4 + 9/4 + 1 = 7/2. To see that leaving donor 2 out is right, compute the gradient at ww: with residual e=(1/2,−3/2,1)e = (1/2, -3/2, 1), g=−2X0⊤e=(4,20,4)g = -2X_0^\top e = (4, 20, 4). The donors in use share the value ν=4\nu = 4, and donor 2 has the larger value 20, so moving weight to it raises the loss: the KKT conditions hold, and by the certificate theorem ww is optimal. The post-period synthetic value is (6+7)/2=6.5(6 + 7)/2 = 6.5, so the estimated effect is 10−6.5=3.510 - 6.5 = 3.5.

Correctness

The proof is in proofs/correctness.md. The objective is convex, so for any feasible ww with gradient gg, f(w)−min⁡f≤g⊤w−min⁡jgjf(w) - \min f \le g^\top w - \min_jg_j: the gap of line L4 is a computable bound on the error. When the KKT system of line L7 has a solution with positive weights and no off-support gradient entry below ν\nu, the gap is zero and ww is a minimizer. The projection formula is proved from the KKT conditions of the projection problem. The trace bound L≥λmax⁡(2X0⊤VX0)L \ge \lambda_{\max}(2X_0^\top VX_0) makes 1/L1/L a safe step, and the O(L/t)O(L/t) rate of projected gradient is cited (Beck and Teboulle 2009). The minimizer is unique when X0X_0 has full column rank, and in every case some minimizer has at most k+1k + 1 positive weights.

The placebo p-value #{u:Ru≥R0}/(J+1)\#\{u : R_u \ge R_0\}/(J + 1), where RuR_u is the ratio of post-period to pre-period root mean squared prediction error with unit uu treated as the treated one, is valid when the units are exchangeable under the null; the proof is the usual rank argument of a permutation test.

The tests check the KKT conditions exactly in fractions on 60 random problems, compare the loss against every point of a simplex grid with step 1/120 for three donors, check the gap bound exactly at random feasible points, check the projection against random points of the simplex, and run the placebo test. In the placebo test, 8 units load on one common trend with 10 pre-periods and 4 post-periods (seed 2026). With an effect of 5 on unit 1, its ratio is 12.2 against at most 6.8 for the placebos, so p=1/8p = 1/8, the smallest possible value. With no effect, 9 of 40 samples (0.225) gave p≤0.25p \le 0.25, against 0.25 expected. Here the units are exchangeable by construction, so the expected share is exactly 0.25 and the difference is sampling noise.

Proof: The synthetic control solver returns a minimizer over the simplex, with an exact certificatefull

Let x1∈Rkx_1 \in \mathbb{R}^k, let X0X_0 be a k×Jk \times J matrix, and let v∈Rkv \in \mathbb{R}^k have positive entries, V=diag⁡(v)V = \operatorname{diag}(v). The problem is

min⁡w∈Δf(w),f(w)=(x1−X0w)⊤V(x1−X0w),Δ={w∈RJ:w≥0, ∑jwj=1}.\min_{w \in \Delta} f(w), \qquad f(w) = (x_1 - X_0w)^\top V(x_1 - X_0w), \qquad \Delta = \{w \in \mathbb{R}^J : w \ge 0,\ \textstyle\sum_j w_j = 1\}.

The gradient is g(w)=∇f(w)=−2X0⊤V(x1−X0w)g(w) = \nabla f(w) = -2X_0^\top V(x_1 - X_0w) and the Hessian is H=2X0⊤VX0H = 2X_0^\top VX_0, which is positive semidefinite. So ff is convex. SYNTH starts at the centre of Δ\Delta (line L1), computes gg (line L3) and the Frank-Wolfe gap γ(w)=g(w)⊤w−min⁡jgj(w)\gamma(w) = g(w)^\top w - \min_j g_j(w) (line L4), stops when the gap is small or the KKT check succeeds (line L5), and otherwise takes the step w←ΠΔ(w−g/L)w \leftarrow \Pi_\Delta(w - g/L) (line L6), where ΠΔ\Pi_\Delta is the Euclidean projection onto Δ\Delta. Line L7 solves the KKT system on the support.

Lemma 1 (existence). ff has a minimizer on Δ\Delta. It is unique if X0X_0 has full column rank.

Proof. Δ\Delta is compact and ff is continuous, so the minimum is attained. If X0X_0 has rank JJ, then HH is positive definite and ff is strictly convex, and a strictly convex function has at most one minimizer on a convex set. □\square

When J>kJ > k, as is usual with many donors and few pre-periods, the minimizer need not be unique. The fitted point X0w∗X_0w^* is always unique, because it is the point of the convex hull of the donor columns nearest to x1x_1 in the norm of VV, and by Carathéodory's theorem it is a convex combination of at most k+1k + 1 donors. So some minimizer has at most k+1k + 1 positive weights. The solver returns one minimizer in every case.

Lemma 2 (projection onto the simplex). For u∈RJu \in \mathbb{R}^J let u(1)≥⋯≥u(J)u_{(1)} \ge \dots \ge u_{(J)} be its sorted entries, ρ\rho the largest ii with u(i)−1i(∑l≤iu(l)−1)>0u_{(i)} - \frac{1}{i}(\sum_{l \le i}u_{(l)} - 1) > 0, and θ=1ρ(∑l≤ρu(l)−1)\theta = \frac{1}{\rho}(\sum_{l \le \rho}u_{(l)} - 1). Then ΠΔ(u)j=max⁡(uj−θ,0)\Pi_\Delta(u)_j = \max(u_j - \theta, 0).

Proof. The projection minimizes 12∥p−u∥2\frac12\lVert p - u\rVert^2 over Δ\Delta. This is strictly convex, so the KKT conditions characterize the unique solution: there are θ\theta and μ≥0\mu \ge 0 with pj−uj+θ−μj=0p_j - u_j + \theta - \mu_j = 0 and μjpj=0\mu_jp_j = 0. Hence pj=max⁡(uj−θ,0)p_j = \max(u_j - \theta, 0), and θ\theta is fixed by ∑jmax⁡(uj−θ,0)=1\sum_j\max(u_j - \theta, 0) = 1. The left side is continuous and strictly decreasing in θ\theta where it is positive, so this θ\theta is unique. If exactly the ρ′\rho' largest entries are positive after the shift, then θ=1ρ′(∑l≤ρ′u(l)−1)\theta = \frac{1}{\rho'}(\sum_{l \le \rho'}u_{(l)} - 1) and u(ρ′)>θ≥u(ρ′+1)u_{(\rho')} > \theta \ge u_{(\rho' + 1)}. Write ti=1i(∑l≤iu(l)−1)t_i = \frac1i(\sum_{l \le i}u_{(l)} - 1) and φ(i)=i(u(i)−ti)=1−∑l≤i(u(l)−u(i))\varphi(i) = i(u_{(i)} - t_i) = 1 - \sum_{l \le i}(u_{(l)} - u_{(i)}). The test of the lemma is φ(i)>0\varphi(i) > 0. The function φ\varphi is nonincreasing, since φ(i+1)−φ(i)=−i(u(i)−u(i+1))≤0\varphi(i + 1) - \varphi(i) = -i(u_{(i)} - u_{(i + 1)}) \le 0. At i=ρ′i = \rho' it is positive, because u(ρ′)>θu_{(\rho')} > \theta gives ∑l≤ρ′(u(l)−u(ρ′))<∑l≤ρ′(u(l)−θ)=1\sum_{l \le \rho'}(u_{(l)} - u_{(\rho')}) < \sum_{l \le \rho'}(u_{(l)} - \theta) = 1. At i=ρ′+1i = \rho' + 1 it is not positive, because u(ρ′+1)≤θu_{(\rho' + 1)} \le \theta gives ∑l≤ρ′+1(u(l)−u(ρ′+1))≥∑l≤ρ′(u(l)−θ)=1\sum_{l \le \rho' + 1}(u_{(l)} - u_{(\rho' + 1)}) \ge \sum_{l \le \rho'}(u_{(l)} - \theta) = 1. So the test holds exactly for i≤ρ′i \le \rho', ρ=ρ′\rho = \rho', and tρ=θt_\rho = \theta. □\square

This is the algorithm analyzed by Duchi et al. (2008); PROJECT-SIMPLEX in the code keeps the last tit_i for which the test holds, which is tρt_\rho.

Lemma 3 (the gap bounds the error). For every w∈Δw \in \Delta, f(w)−min⁡Δf≤γ(w)f(w) - \min_\Delta f \le \gamma(w), and γ(w)≥0\gamma(w) \ge 0.

Proof. Let w∗w^* be a minimizer. Convexity gives f(w∗)≥f(w)+g⊤(w∗−w)f(w^*) \ge f(w) + g^\top(w^* - w), so f(w)−f(w∗)≤g⊤w−g⊤w∗f(w) - f(w^*) \le g^\top w - g^\top w^*. Since w∗∈Δw^* \in \Delta, g⊤w∗g^\top w^* is a weighted mean of the gjg_j and is at least min⁡jgj\min_jg_j. So f(w)−f(w∗)≤g⊤w−min⁡jgj=γ(w)f(w) - f(w^*) \le g^\top w - \min_jg_j = \gamma(w). Also g⊤w≥min⁡jgjg^\top w \ge \min_j g_j for the same reason, so γ≥0\gamma \ge 0. □\square

Theorem 4 (the KKT certificate). Let w∈Δw \in \Delta, S={j:wj>0}S = \{j : w_j > 0\} and ν∈R\nu \in \mathbb{R} with gj(w)=νg_j(w) = \nu for j∈Sj \in S and gj(w)≥νg_j(w) \ge \nu for j∉Sj \notin S. Then ww minimizes ff on Δ\Delta.

Proof. g⊤w=∑j∈Swjν=νg^\top w = \sum_{j \in S}w_j\nu = \nu and min⁡jgj=ν\min_jg_j = \nu, so γ(w)=0\gamma(w) = 0, and Lemma 3 gives f(w)≤min⁡Δff(w) \le \min_\Delta f. □\square

Line L7 builds such a ww. With AA the columns of X0X_0 in SS, the conditions gS=ν1g_S = \nu\mathbf 1 and 1⊤wS=1\mathbf 1^\top w_S = 1 are the linear system

2A⊤VA wS−ν1=2A⊤Vx1,1⊤wS=1,2A^\top VA\,w_S - \nu\mathbf 1 = 2A^\top Vx_1, \qquad \mathbf 1^\top w_S = 1,

which the code solves by Gauss-Jordan elimination in the input arithmetic. It accepts the result only if wS>0w_S > 0 and gj≥ν−ϵ(1+∣ν∣)g_j \ge \nu - \epsilon(1 + \lvert\nu\rvert) off SS. With fractions the equalities on SS hold exactly, and the acceptance test then gives γ(w)≤ϵ(1+∣ν∣)\gamma(w) \le \epsilon(1 + \lvert\nu\rvert) by the computation in the proof, so f(w)−min⁡f≤ϵ(1+∣ν∣)f(w) - \min f \le \epsilon(1 + \lvert\nu\rvert) with ϵ=10−9\epsilon = 10^{-9}. If every off-support gradient entry is at least ν\nu, which the tests check exactly, ww is an exact minimizer. If the system is singular or the test fails, SYNTH returns the gradient iterate, whose error is at most its final gap by Lemma 3.

Theorem 5 (the step size). ∇f\nabla f is Lipschitz with constant λmax⁡(H)≤L=2∑r,jvrX0,rj2\lambda_{\max}(H) \le L = 2\sum_{r, j}v_rX_{0, rj}^2.

Proof. ∥g(w)−g(w′)∥=∥H(w−w′)∥≤λmax⁡(H)∥w−w′∥\lVert g(w) - g(w')\rVert = \lVert H(w - w')\rVert \le \lambda_{\max}(H)\lVert w - w'\rVert, and λmax⁡(H)≤tr⁡H=2∑rvr∑jX0,rj2\lambda_{\max}(H) \le \operatorname{tr}H = 2\sum_r v_r\sum_jX_{0, rj}^2 because HH is positive semidefinite. □\square

With a step 1/L1/L for an LL at least the Lipschitz constant, projected gradient descent satisfies f(wt)−min⁡f≤L∥w0−w∗∥2/(2t)f(w_t) - \min f \le L\lVert w_0 - w^*\rVert^2/(2t) (Beck and Teboulle 2009, for the basic proximal gradient method; cited, not proved here). From the centre of Δ\Delta, ∥w0−w∗∥2≤1−1/J<1\lVert w_0 - w^*\rVert^2 \le 1 - 1/J < 1, so t≥L/(2ε)t \ge L/(2\varepsilon) iterations give error f(wt)−min⁡ff(w_t) - \min f at most ε\varepsilon. This bounds the error, not the gap γ(wt)\gamma(w_t) that line L5 tests, so it is not a bound on the number of iterations before the stop. When the minimizer is unique and strictly complementary, projected gradient also finds the support after finitely many steps, after which the KKT check of line L5 succeeds. The code relies on this only for speed: correctness rests on Lemma 3 and Theorem 4. The measured counts are on the main page.

Theorem 6 (the placebo p-value). Let R0,…,RJR_0, \dots, R_J be the statistics of the treated unit and the JJ donors, each computed by refitting with that unit as treated. If under the null hypothesis the vector (R0,…,RJ)(R_0, \dots, R_J) is exchangeable, then p=#{u:Ru≥R0}/(J+1)p = \#\{u : R_u \ge R_0\}/(J + 1) satisfies Pr⁡[p≤m/(J+1)]≤m/(J+1)\Pr[p \le m/(J + 1)] \le m/(J + 1) for m=1,…,J+1m = 1, \dots, J + 1.

Proof. p≤m/(J+1)p \le m/(J + 1) means at most mm of the RuR_u are at least R0R_0, which places R0R_0 among the mm largest values counting ties against it. By exchangeability each position is equally likely to hold the unit called 0, and at most mm of the J+1J + 1 positions satisfy the condition. □\square

Exchangeability holds when the treated unit was picked at random, which is rarely true; otherwise the p-value is a description of how unusual the treated unit's gap is among the placebo gaps.

What is not proved here. The convergence rate of Theorem 5's step and the finite identification of the support are cited. The statistical properties of the estimate, that the gap after the intervention is close to the effect when the pre-period fit is good, rest on a model for the untreated outcomes. Abadie, Diamond and Hainmueller (2010) bound the bias under a linear factor model with a perfect pre-period fit, the bound shrinking as the number of pre-periods grows. That result is cited, and the simulation on the main page measures the behaviour only for one design.

Complexity

One gradient step costs Θ(kJ)\Theta(kJ) for the gradient and Θ(Jlog⁡J)\Theta(J\log J) for the projection. A KKT check costs Θ(ks2+s3)\Theta(ks^2 + s^3) for a support of size s≤Js \le J, and runs every 20 steps, so tt steps cost Θ(t(kJ2+J3))\Theta(t(kJ^2 + J^3)) in the worst case, and the final exact solve costs Θ(kJ2+J3)\Theta(kJ^2 + J^3) arithmetic operations. In practice ss is small. Measured on 100 random problems with k=30k = 30 features and J=20J = 20 donors: median 79 steps, maximum 319, total 2.1 s of CPU in pure Python. The worst case of the gradient phase is t=O(L/ε)t = O(L/\varepsilon) steps. Extra space is Θ(kJ)\Theta(kJ) for the copy of the data and Θ(J2)\Theta(J^2) for the KKT system. The placebo test repeats the fit J+1J + 1 times.

Properties

  • The weights are nonnegative and sum to one, so the synthetic control is a convex combination of donors and cannot extrapolate outside their range.
  • The weights are sparse: some minimizer uses at most k+1k + 1 donors, and in practice few donors get weight.
  • The weights are chosen without the post-period outcomes, which keeps the analyst from tuning the fit to the result.
  • Adding the same constant to the treated unit and to every donor does not change the weights, because they sum to one. A shift of one unit alone does change them, so a treated unit with a different level must be matched by level too; synthetic difference in differences removes that need.
  • With fraction inputs the polished weights are exact rationals and carry their own certificate ν\nu.

Variants and improvements

  • Predictor weights. Choosing vv by minimizing pre-period outcome fit is a bilevel problem; Abadie, Diamond and Hainmueller (2015) use cross-validation over two halves of the pre-period instead.
  • Penalized weights. Adding a penalty that favours donors close to the treated unit makes the solution unique and sparse.
  • Augmented synthetic control. Ben-Michael, Feller and Rothstein (2021) correct the bias of an imperfect fit with an outcome model, such as a ridge regression, allowing weights outside the simplex.
  • Synthetic difference in differences. Arkhangelsky et al. (2021) weight both units and pre-periods and add unit fixed effects, which removes level differences that the plain method must fit.
  • Several treated units. Fit a synthetic control for each and average, or fit one for the average of the treated units.
  • Solvers. Any quadratic programming method works: active set methods, interior point, or Frank-Wolfe steps, whose iterates are sparse by construction.

When to use it

Use it for comparative case studies: one or a few treated aggregate units, such as countries, states or cities, a long pre-period, and a donor pool of similar units that were not exposed. The pre-period fit must be good, and the treated unit must lie inside or near the range of the donors. With many treated units and short panels, difference in differences or regression methods are better. With large samples of individuals and measured confounders, use inverse probability weighting or related estimators instead.

Pitfalls

  • A poor pre-period fit. If the synthetic control does not track the treated unit before the intervention, the post-period gap is not credible. Report the pre-period root mean squared error and the plot.
  • Treated units outside the donors' range. A unit with the highest values of all cannot be matched by a convex combination; the fit will have a systematic gap.
  • Spillovers into the donor pool. If the law in California changed smoking in Nevada, Nevada is not a valid donor.
  • Matching on all pre-period outcomes and nothing else. Some authors put each pre-period outcome in x1x_1, which makes covariates irrelevant; this is a choice and should be reported.
  • Overfitting with many donors and few pre-periods. When JJ is large compared with the number of pre-periods, a close fit may come from noise. Use a smaller donor pool of similar units.
  • Reading the placebo p-value as a sampling p-value. It measures how unusual the treated gap is among placebo gaps; its validity needs exchangeability, and with JJ donors it cannot be below 1/(J+1)1/(J + 1).

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

synthetic_control_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/synthetic-control-method/. The authors are listed in prov/1N66SX.jsonl.

"""Synthetic control weights by projected gradient on the simplex.

The treated unit has k pre-period features x1 (outcomes or predictors). The J donors have
the k x J matrix X0 (row r holds feature r for every donor). The weights solve

    minimize f(w) = sum_r v_r (x1_r - sum_j X0[r][j] w_j)^2   subject to w_j >= 0, sum_j w_j = 1,

with feature weights v (all 1 by default). This is a convex quadratic program.

synth runs projected gradient descent with step 1/L in floating point and stops when the
Frank-Wolfe gap g.w - min_j g_j, an upper bound on f(w) - min f, is at most tol. It then
polishes: on the support of w it solves the equality-constrained least squares problem
exactly in the input arithmetic (Fractions stay exact) and keeps the result if it satisfies
the KKT conditions. placebo_pvalue gives the in-space placebo p-value.
"""

from collections.abc import Sequence
from typing import NamedTuple


class SynthResult(NamedTuple):
    w: list  # donor weights, nonnegative, summing to 1
    loss: object  # f(w)
    gap: float  # Frank-Wolfe gap at the end of the gradient phase
    iterations: int
    polished: bool  # True if the KKT polish succeeded


def project_simplex(v: Sequence) -> list:
    """Euclidean projection onto {w : w >= 0, sum w = 1}, by sorting. Exact for Fractions."""
    u = sorted(v, reverse=True)
    css, theta = 0, 0
    for i, a in enumerate(u):
        css += a
        t = (css - 1) / (i + 1)
        if a - t > 0:
            theta = t
    return [max(a - theta, a * 0) for a in v]


def residual(x1, x0, w):
    return [a - sum(r[j] * w[j] for j in range(len(w))) for a, r in zip(x1, x0)]


def loss(x1: Sequence, x0: list[list], w: Sequence, v: Sequence | None = None) -> object:
    v = v if v is not None else [1] * len(x1)
    return sum(vi * e * e for vi, e in zip(v, residual(x1, x0, w)))


def gradient(x1: Sequence, x0: list[list], w: Sequence, v: Sequence | None = None) -> list:
    v = v if v is not None else [1] * len(x1)
    e = residual(x1, x0, w)
    return [-2 * sum(vi * r[j] * ei for vi, r, ei in zip(v, x0, e)) for j in range(len(w))]


def fw_gap(g: Sequence, w: Sequence) -> object:
    """g.w - min_j g_j. For a convex f with gradient g at w, f(w) - min f <= this gap."""
    return sum(a * b for a, b in zip(g, w)) - min(g)


def _solve(a, b):
    k = len(a)
    m = [list(r) + [c] for r, c in zip(a, b)]
    for col in range(k):
        p = max(range(col, k), key=lambda r: abs(m[r][col]))
        if m[p][col] == 0:
            raise ValueError("singular")
        m[col], m[p] = m[p], m[col]
        for r in range(k):
            if r != col and m[r][col] != 0:
                f = m[r][col] / m[col][col]
                for j in range(col, k + 1):
                    m[r][j] -= f * m[col][j]
    return [m[r][k] / m[r][r] for r in range(k)]


def kkt_polish(x1, x0, w, v=None, tol=1e-9):
    """Solve 2 A'VA w_S - nu 1 = 2 A'V x1, 1'w_S = 1 on the support S of w (A = columns S of x0)
    in the input arithmetic. Return the full weight vector if w_S > 0 and every gradient
    entry off S is >= nu; otherwise None."""
    jn = len(w)
    v = v if v is not None else [1] * len(x1)
    one = x1[0] * 0 + 1
    s = [j for j in range(jn) if w[j] > tol]
    m = len(s)
    a = [[2 * sum(vi * r[i] * r[j] for vi, r in zip(v, x0)) for j in s] + [-one] for i in s]
    a.append([one] * m + [one - one])
    b = [2 * sum(vi * r[i] * xi for vi, r, xi in zip(v, x0, x1)) for i in s] + [one]
    try:
        sol = _solve(a, b)
    except ValueError:
        return None
    ws, nu = sol[:m], sol[m]
    if any(c <= 0 for c in ws):
        return None
    full = [one - one] * jn
    for j, c in zip(s, ws):
        full[j] = c
    g = gradient(x1, x0, full, v)
    if any(g[j] < nu - tol * (1 + abs(nu)) for j in range(jn) if j not in s):
        return None
    return full


def synth(
    x1: Sequence, x0: list[list], v: Sequence | None = None, tol: float = 1e-10, max_iter: int = 50000, check_every: int = 20
) -> SynthResult:
    """Synthetic control weights. Cost per iteration: Theta(k J + J log J). Every check_every
    iterations the KKT system on the current support is tried in floating point; once the
    support is right it succeeds and the loop stops before the gap reaches tol."""
    k, jn = len(x1), len(x0[0])
    if len(x0) != k or any(len(r) != jn for r in x0):
        raise ValueError("x0 must be k x J with k = len(x1)")
    vf = [float(a) for a in v] if v is not None else [1.0] * k
    xf1 = [float(a) for a in x1]
    xf0 = [[float(a) for a in r] for r in x0]
    w = [1.0 / jn] * jn  # @line L1
    lip = 2 * sum(vi * a * a for vi, r in zip(vf, xf0) for a in r) or 1.0
    it, gap = 0, float("inf")
    while it < max_iter:  # @line L2
        g = gradient(xf1, xf0, w, vf)  # @line L3
        gap = fw_gap(g, w)  # @line L4
        if gap <= tol * (1 + loss(xf1, xf0, w, vf)) or (it % check_every == check_every - 1 and kkt_polish(xf1, xf0, w, vf) is not None):  # @line L5
            break
        w = project_simplex([a - b / lip for a, b in zip(w, g)])  # @line L6
        it += 1
    exact = kkt_polish(x1, x0, w, v)  # @line L7
    if exact is not None:
        return SynthResult(exact, loss(x1, x0, exact, v), gap, it, True)  # @line L8
    return SynthResult(w, loss(xf1, xf0, w, vf), gap, it, False)


def gaps(y1: Sequence, y0: list[list], w: Sequence) -> list:
    """Treated minus synthetic outcome for each period (rows of y0 are periods)."""
    return residual(y1, y0, w)


def rmspe(e: Sequence) -> float:
    return (sum(float(a) ** 2 for a in e) / len(e)) ** 0.5


def placebo_pvalue(pre: list[list], post: list[list], v: Sequence | None = None) -> tuple:
    """In-space placebo test. pre[t][u] and post[t][u] are outcomes of unit u (unit 0 treated).
    Each unit in turn is fitted from the others on the pre periods; its statistic is post RMSPE
    over pre RMSPE. Returns (p, ratios) with p = #{u : ratio_u >= ratio_0} / (J + 1)."""
    units = len(pre[0])
    ratios = []
    for u in range(units):
        others = [j for j in range(units) if j != u]
        x1 = [r[u] for r in pre]
        x0 = [[r[j] for j in others] for r in pre]
        res = synth(x1, x0, v)
        e_pre = residual(x1, x0, res.w)
        e_post = residual([r[u] for r in post], [[r[j] for j in others] for r in post], res.w)
        rp = rmspe(e_pre)
        ratios.append(rmspe(e_post) / rp if rp > 0 else float("inf"))
    p = sum(1 for a in ratios if a >= ratios[0]) / units
    return p, ratios
test_synthetic_control_method.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/synthetic-control-method/. The authors are listed in prov/1N66SX.jsonl.

import random
from fractions import Fraction as Fr

import pytest

from synthetic_control_method import (
    fw_gap,
    gaps,
    gradient,
    loss,
    placebo_pvalue,
    project_simplex,
    synth,
)


def fr_matrix(rows):
    return [[Fr(a) for a in r] for r in rows]


def test_worked_example():
    x1 = [Fr(7), Fr(4), Fr(4)]
    x0 = fr_matrix([[5, 7, 8], [5, 9, 6], [3, 0, 3]])  # rows are periods, columns donors
    r = synth(x1, x0)
    assert r.polished and r.w == [Fr(1, 2), 0, Fr(1, 2)] and r.loss == Fr(7, 2)
    assert gradient(x1, x0, r.w) == [4, 20, 4]
    assert gaps([Fr(10)], fr_matrix([[6, 8, 7]]), r.w) == [Fr(7, 2)]


def kkt_holds(x1, x0, w):
    g = gradient(x1, x0, w)
    nu = min(g)
    return (
        all(a >= 0 for a in w)
        and sum(w) == 1
        and all(g[j] == nu for j in range(len(w)) if w[j] > 0)
        and all(g[j] >= nu for j in range(len(w)))
    )


def test_kkt_conditions_hold_exactly():
    rng = random.Random(1)
    polished = 0
    for _ in range(60):
        k, jn = rng.randint(2, 8), rng.randint(2, 7)
        x1 = [Fr(rng.randint(-10, 10)) for _ in range(k)]
        x0 = [[Fr(rng.randint(-10, 10)) for _ in range(jn)] for _ in range(k)]
        r = synth(x1, x0)
        if r.polished:
            polished += 1
            assert kkt_holds(x1, x0, r.w)
            assert fw_gap(gradient(x1, x0, r.w), r.w) == 0
    assert polished >= 55


def test_three_donors_against_a_simplex_grid():
    """No point of the grid {(a, b, c) / 120} has a smaller loss, and the grid minimum is close."""
    rng = random.Random(2)
    m = 120
    grid = [(a / m, b / m, (m - a - b) / m) for a in range(m + 1) for b in range(m + 1 - a)]
    for _ in range(12):
        k = rng.randint(3, 6)
        x1 = [rng.uniform(0, 10) for _ in range(k)]
        x0 = [[rng.uniform(0, 10) for _ in range(3)] for _ in range(k)]
        r = synth(x1, x0)
        best = min(loss(x1, x0, w) for w in grid)
        assert r.loss <= best + 1e-9
        g = gradient(x1, x0, r.w)
        # f(grid point) - f(w*) <= g.(q - w*) + L |q - w*|^2 / 2 with |q - w*| <= 1/m from the nearest grid point
        lip = 2 * sum(a * a for row in x0 for a in row)
        assert best - r.loss <= max(abs(a) for a in g) * 2 / m + lip / m**2


def test_gap_bounds_the_suboptimality_exactly():
    rng = random.Random(3)
    for _ in range(30):
        k, jn = rng.randint(2, 6), rng.randint(2, 6)
        x1 = [Fr(rng.randint(-5, 5)) for _ in range(k)]
        x0 = [[Fr(rng.randint(-5, 5)) for _ in range(jn)] for _ in range(k)]
        r = synth(x1, x0)
        if not r.polished:
            continue
        for _ in range(10):
            raw = [Fr(rng.randint(0, 9)) for _ in range(jn)]
            if sum(raw) == 0:
                continue
            w = [a / sum(raw) for a in raw]
            assert loss(x1, x0, w) - r.loss <= fw_gap(gradient(x1, x0, w), w)


def test_projection_onto_the_simplex():
    rng = random.Random(4)
    for _ in range(100):
        n = rng.randint(1, 6)
        v = [Fr(rng.randint(-20, 20), rng.randint(1, 5)) for _ in range(n)]
        p = project_simplex(v)
        assert sum(p) == 1 and all(a >= 0 for a in p)
        d = sum((a - b) ** 2 for a, b in zip(v, p))
        for _ in range(20):
            raw = [Fr(rng.randint(0, 9)) for _ in range(n)]
            if sum(raw) == 0:
                continue
            q = [a / sum(raw) for a in raw]
            assert sum((a - b) ** 2 for a, b in zip(v, q)) >= d


def test_placebo_pvalue():
    """Factor model: unit u has loading l_u on a common trend. The treated unit gets an effect of
    5 after the intervention: it ranks first, p = 1/(J+1). Without the effect, the units are
    exchangeable and p is uniform on {1, ..., J+1}/(J+1): over 40 samples the share with p <= 0.25
    is within 0.25 +- 4 SE."""
    rng = random.Random(2026)

    def panel(effect):
        units, t_pre, t_post = 8, 10, 4
        load = [rng.uniform(0.5, 1.5) for _ in range(units)]
        trend = [rng.gauss(0, 1) for _ in range(t_pre + t_post)]
        y = [[load[u] * trend[t] + rng.gauss(0, 0.3) for u in range(units)] for t in range(t_pre + t_post)]
        for t in range(t_pre, t_pre + t_post):
            y[t][0] += effect
        return y[:t_pre], y[t_pre:]

    p, ratios = placebo_pvalue(*panel(5.0))
    assert p == 1 / 8 and ratios[0] == max(ratios)
    small = 0
    for _ in range(40):
        p, _ = placebo_pvalue(*panel(0.0))
        small += p <= 0.25
    se = (0.25 * 0.75 / 40) ** 0.5
    assert abs(small / 40 - 0.25) < 4 * se


def test_input_checks():
    with pytest.raises(ValueError):
        synth([1, 2], [[1, 2], [3]])
    with pytest.raises(ValueError):
        synth([1, 2, 3], [[1, 2], [3, 4]])

History

Abadie and Gardeazabal (2003) estimated the economic cost of terrorism in the Basque Country by comparing it with a combination of other Spanish regions, mostly Catalonia and Madrid. Abadie, Diamond and Hainmueller (2010) made the method general. They studied California's Proposition 99 tobacco program of 1988 with a donor pool of 38 states, justified the estimator under a factor model, and introduced inference by placebo runs on every donor. Abadie, Diamond and Hainmueller (2015) applied it to German reunification and added cross-validation. Abadie (2021) reviewed when the method is appropriate. Later work combined it with outcome models (Ben-Michael, Feller and Rothstein 2021) and with difference in differences (Arkhangelsky et al. 2021).

References

  1. Alberto Abadie and Javier Gardeazabal, The economic costs of conflict, a case study of the Basque Country, American Economic Review 93(1), 2003, pp. 113 to 132 (the first synthetic control, built from other Spanish regions)
  2. Alberto Abadie, Alexis Diamond and Jens Hainmueller, Synthetic control methods for comparative case studies, estimating the effect of California's tobacco control program, Journal of the American Statistical Association 105(490), 2010, pp. 493 to 505 (the estimator, the bias bound under a factor model, placebo inference)
  3. Alberto Abadie, Alexis Diamond and Jens Hainmueller, Comparative politics and the synthetic control method, American Journal of Political Science 59(2), 2015, pp. 495 to 510 (German reunification, cross-validation of the predictor weights, leave-one-out checks)
  4. Alberto Abadie, Using synthetic controls, feasibility, data requirements, and methodological aspects, Journal of Economic Literature 59(2), 2021, pp. 391 to 425 (when the method is appropriate, the role of the pre-period fit, inference)
  5. John Duchi, Shai Shalev-Shwartz, Yoram Singer and Tushar Chandra, Efficient projections onto the l1-ball for learning in high dimensions, ICML 2008, pp. 272 to 279 (the sort-based projection onto the simplex)
  6. Amir Beck and Marc Teboulle, A fast iterative shrinkage-thresholding algorithm for linear inverse problems, SIAM Journal on Imaging Sciences 2(1), 2009, pp. 183 to 202 (the O(1/t) rate of the basic proximal gradient method, of which projected gradient is a case; general locator, the theorem number was not checked)
  7. Eli Ben-Michael, Avi Feller and Jesse Rothstein, The augmented synthetic control method, Journal of the American Statistical Association 116(536), 2021, pp. 1789 to 1803 (bias correction with an outcome model when the pre-period fit is imperfect)
  8. Dmitry Arkhangelsky, Susan Athey, David A. Hirshberg, Guido W. Imbens and Stefan Wager, Synthetic difference-in-differences, American Economic Review 111(12), 2021, pp. 4088 to 4118 (unit and time weights combined with two-way fixed effects)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example