pysynthcon 0.1.0b2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pysynth/__init__.py +83 -0
- pysynth/_mscmt_qp.py +45 -0
- pysynth/_nested.py +285 -0
- pysynth/_optim.py +106 -0
- pysynth/_r.py +125 -0
- pysynth/_r_synth.py +180 -0
- pysynth/backends.py +835 -0
- pysynth/classic.py +45 -0
- pysynth/conformal.py +260 -0
- pysynth/conformal_plotting.py +193 -0
- pysynth/datasets.py +206 -0
- pysynth/evaluation_plotting.py +256 -0
- pysynth/fonts/STIXTwoText-OFL.txt +92 -0
- pysynth/fonts/STIXTwoText-SemiBold.ttf +0 -0
- pysynth/fonts/SourceSans3-LICENSE.md +93 -0
- pysynth/fonts/SourceSans3-Regular.ttf +0 -0
- pysynth/fonts/SourceSans3-Semibold.ttf +0 -0
- pysynth/individual.py +541 -0
- pysynth/inference.py +332 -0
- pysynth/panel.py +198 -0
- pysynth/placebo_plotting.py +240 -0
- pysynth/plotting.py +1998 -0
- pysynth/py.typed +0 -0
- pysynth/replication.py +505 -0
- pysynth/results.py +265 -0
- pysynth/scul.py +255 -0
- pysynth/sdid.py +532 -0
- pysynth/sensitivity.py +204 -0
- pysynth/validation.py +260 -0
- pysynthcon-0.1.0b2.dist-info/METADATA +187 -0
- pysynthcon-0.1.0b2.dist-info/RECORD +37 -0
- pysynthcon-0.1.0b2.dist-info/WHEEL +5 -0
- pysynthcon-0.1.0b2.dist-info/licenses/LICENSE +674 -0
- pysynthcon-0.1.0b2.dist-info/licenses/THIRD_PARTY_NOTICES.md +93 -0
- pysynthcon-0.1.0b2.dist-info/licenses/src/pysynth/fonts/STIXTwoText-OFL.txt +92 -0
- pysynthcon-0.1.0b2.dist-info/licenses/src/pysynth/fonts/SourceSans3-LICENSE.md +93 -0
- pysynthcon-0.1.0b2.dist-info/top_level.txt +1 -0
pysynth/__init__.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
"""Synthetic control methods with a shared, explicit panel interface."""
|
|
2
|
+
|
|
3
|
+
from .backends import (
|
|
4
|
+
SCM,
|
|
5
|
+
AugmentedSyntheticControl,
|
|
6
|
+
DifferencedSyntheticControl,
|
|
7
|
+
PenalizedSyntheticControl,
|
|
8
|
+
PredictorSyntheticControl,
|
|
9
|
+
PySyncon,
|
|
10
|
+
RobustSyntheticControl,
|
|
11
|
+
)
|
|
12
|
+
from .classic import SyntheticControl
|
|
13
|
+
from .conformal import ConformalResult, conformal_confidence_set, conformal_test
|
|
14
|
+
from .conformal_plotting import plot_conformal_set
|
|
15
|
+
from .evaluation_plotting import plot_backtest, plot_donor_sensitivity
|
|
16
|
+
from .individual import IndividualEstimate, IndividualSC, TwoStageIndividualSC
|
|
17
|
+
from .inference import PlaceboResult, placebo_test
|
|
18
|
+
from .panel import Panel
|
|
19
|
+
from .placebo_plotting import plot_assignment_sensitivity, plot_placebo_gaps
|
|
20
|
+
from .plotting import (
|
|
21
|
+
LiteratureBenchmark,
|
|
22
|
+
ReferenceComparison,
|
|
23
|
+
plot_comparison,
|
|
24
|
+
plot_effects,
|
|
25
|
+
plot_paths,
|
|
26
|
+
publication_style,
|
|
27
|
+
publication_title_font,
|
|
28
|
+
reference_comparison_table,
|
|
29
|
+
save_figure,
|
|
30
|
+
)
|
|
31
|
+
from .results import Estimate, Estimator, compare
|
|
32
|
+
from .scul import SCUL
|
|
33
|
+
from .sdid import DifferenceInDifferences, SDIDInference, SyntheticDID
|
|
34
|
+
from .sensitivity import DonorSensitivityResult, donor_sensitivity
|
|
35
|
+
from .validation import BacktestResult, SelectionResult, backtest, select_estimator
|
|
36
|
+
|
|
37
|
+
__version__ = "0.1.0b2"
|
|
38
|
+
__all__ = [
|
|
39
|
+
"Panel",
|
|
40
|
+
"Estimate",
|
|
41
|
+
"Estimator",
|
|
42
|
+
"SyntheticControl",
|
|
43
|
+
"PredictorSyntheticControl",
|
|
44
|
+
"AugmentedSyntheticControl",
|
|
45
|
+
"DifferencedSyntheticControl",
|
|
46
|
+
"PenalizedSyntheticControl",
|
|
47
|
+
"RobustSyntheticControl",
|
|
48
|
+
"SCUL",
|
|
49
|
+
"IndividualSC",
|
|
50
|
+
"TwoStageIndividualSC",
|
|
51
|
+
"IndividualEstimate",
|
|
52
|
+
"SyntheticDID",
|
|
53
|
+
"SDIDInference",
|
|
54
|
+
"DifferenceInDifferences",
|
|
55
|
+
"PySyncon",
|
|
56
|
+
"SCM",
|
|
57
|
+
"compare",
|
|
58
|
+
"placebo_test",
|
|
59
|
+
"PlaceboResult",
|
|
60
|
+
"ConformalResult",
|
|
61
|
+
"conformal_test",
|
|
62
|
+
"conformal_confidence_set",
|
|
63
|
+
"plot_placebo_gaps",
|
|
64
|
+
"plot_assignment_sensitivity",
|
|
65
|
+
"plot_conformal_set",
|
|
66
|
+
"plot_paths",
|
|
67
|
+
"plot_effects",
|
|
68
|
+
"plot_comparison",
|
|
69
|
+
"publication_style",
|
|
70
|
+
"publication_title_font",
|
|
71
|
+
"save_figure",
|
|
72
|
+
"LiteratureBenchmark",
|
|
73
|
+
"ReferenceComparison",
|
|
74
|
+
"reference_comparison_table",
|
|
75
|
+
"backtest",
|
|
76
|
+
"select_estimator",
|
|
77
|
+
"BacktestResult",
|
|
78
|
+
"SelectionResult",
|
|
79
|
+
"donor_sensitivity",
|
|
80
|
+
"DonorSensitivityResult",
|
|
81
|
+
"plot_backtest",
|
|
82
|
+
"plot_donor_sensitivity",
|
|
83
|
+
]
|
pysynth/_mscmt_qp.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Checked numerical repair for a failed original MSCMT inner quadratic.
|
|
2
|
+
|
|
3
|
+
This process worker is invoked only after WNNLS reports failure. Its input
|
|
4
|
+
is exactly sqrt(V) times MSCMT's donor-minus-treated design, after MSCMT's
|
|
5
|
+
own scaling. Neither predictor weights nor the statistical objective change.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ._optim import simplex_fit
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def solve(x):
|
|
18
|
+
x = np.asarray(x, dtype=float)
|
|
19
|
+
if x.ndim != 2 or not all(x.shape) or not np.isfinite(x).all():
|
|
20
|
+
raise ValueError("MSCMT quadratic design must be a nonempty finite matrix")
|
|
21
|
+
scale = float(np.max(np.abs(x)))
|
|
22
|
+
p = x.shape[1]
|
|
23
|
+
if scale == 0:
|
|
24
|
+
return np.full(p, 1 / p), {"dual_gap": 0.0, "iterations": 0, "objective": 0.0}
|
|
25
|
+
a = x / scale
|
|
26
|
+
# A zero target makes this exactly MSCMT's supplied donor-minus-treated
|
|
27
|
+
# quadratic. The common solver also checks the attainable improvement
|
|
28
|
+
# between active donors, even when an unused donor dominates the scale.
|
|
29
|
+
w, diagnostics = simplex_fit(a, np.zeros(len(a)), max_iter=100000, tol=1e-14)
|
|
30
|
+
gap = diagnostics["scaled_optimality_gap"]
|
|
31
|
+
if gap > 1e-8:
|
|
32
|
+
raise RuntimeError(f"MSCMT inner quadratic repair has excessive KKT gap {gap:g}")
|
|
33
|
+
# Report the objective in the original units after checking its scaled gap.
|
|
34
|
+
residual = (a @ w) * scale
|
|
35
|
+
rms = np.linalg.norm(residual / np.sqrt(len(residual)))
|
|
36
|
+
objective = float(rms * rms)
|
|
37
|
+
if not np.isfinite(objective):
|
|
38
|
+
raise RuntimeError("MSCMT weighted residual objective exceeds floating-point range")
|
|
39
|
+
return w, {"dual_gap": gap, "iterations": diagnostics["iterations"], "objective": objective}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
if __name__ == "__main__":
|
|
43
|
+
matrix = np.loadtxt(sys.argv[1], delimiter=",", ndmin=2)
|
|
44
|
+
weights, diagnostics = solve(matrix)
|
|
45
|
+
Path(sys.argv[2]).write_text(json.dumps({"weights": weights.tolist(), **diagnostics}))
|
pysynth/_nested.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Numerically checked nested optimization for the SCMethods adapter.
|
|
2
|
+
|
|
3
|
+
The statistical objective, bounds, and uniform/Dirichlet starts are those of
|
|
4
|
+
SyntheticControlMethods. Solver precision and failure recovery are explicit.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from scipy.optimize import OptimizeResult, minimize
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class _DerivativeUnavailable(RuntimeError):
|
|
12
|
+
"""The inner optimum does not admit a numerically reliable derivative."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _polish_weights(a, pairwise, v, pen, weights):
|
|
16
|
+
"""Certify an active-set QP solution; return its KKT system and dual slack.
|
|
17
|
+
|
|
18
|
+
An interior-point solver can leave tiny positive weights on inactive
|
|
19
|
+
donors. Starting from its support, remove negative active weights and add
|
|
20
|
+
donors with negative reduced gradients until the QP's KKT conditions hold.
|
|
21
|
+
This solves the same constrained quadratic objective; it adds no penalty.
|
|
22
|
+
"""
|
|
23
|
+
support = set(np.flatnonzero(weights > 1e-7).tolist()) or {int(np.argmax(weights))}
|
|
24
|
+
visited = set()
|
|
25
|
+
for _ in range(3 * len(weights)):
|
|
26
|
+
key = tuple(sorted(support))
|
|
27
|
+
if key in visited:
|
|
28
|
+
raise _DerivativeUnavailable("active-set polishing cycled")
|
|
29
|
+
visited.add(key)
|
|
30
|
+
active = np.array(key, dtype=int)
|
|
31
|
+
design = a[:, active]
|
|
32
|
+
hessian = 2 * (design.T * v) @ design
|
|
33
|
+
linear = pen * (pairwise[:, active].T @ v)
|
|
34
|
+
kkt = np.block(
|
|
35
|
+
[[hessian, np.ones((len(active), 1))], [np.ones((1, len(active))), np.zeros((1, 1))]]
|
|
36
|
+
)
|
|
37
|
+
if np.linalg.cond(kkt) > 1e12:
|
|
38
|
+
raise _DerivativeUnavailable("singular or ill-conditioned active-set KKT system")
|
|
39
|
+
try:
|
|
40
|
+
solution = np.linalg.solve(kkt, np.r_[-linear, 1.0])
|
|
41
|
+
except np.linalg.LinAlgError as exc:
|
|
42
|
+
raise _DerivativeUnavailable("singular active-set KKT system") from exc
|
|
43
|
+
if solution[:-1].min() < 1e-12:
|
|
44
|
+
support.remove(int(active[np.argmin(solution[:-1])]))
|
|
45
|
+
continue
|
|
46
|
+
polished = np.zeros(len(weights))
|
|
47
|
+
polished[active] = solution[:-1]
|
|
48
|
+
dual = 2 * a.T @ (v * (a @ polished)) + pen * (pairwise.T @ v) + solution[-1]
|
|
49
|
+
inactive = np.ones(len(weights), dtype=bool)
|
|
50
|
+
inactive[active] = False
|
|
51
|
+
if inactive.any() and dual[inactive].min() < -1e-9:
|
|
52
|
+
support.add(int(np.flatnonzero(inactive)[np.argmin(dual[inactive])]))
|
|
53
|
+
continue
|
|
54
|
+
if (
|
|
55
|
+
not np.isfinite(polished).all()
|
|
56
|
+
or abs(polished.sum() - 1) > 1e-8
|
|
57
|
+
or np.max(np.abs(dual[active])) > 1e-8
|
|
58
|
+
):
|
|
59
|
+
raise _DerivativeUnavailable("active-set KKT residual exceeds tolerance")
|
|
60
|
+
return polished, active, kkt, dual, inactive
|
|
61
|
+
raise _DerivativeUnavailable("active-set polishing reached its iteration limit")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _outer_derivative(a, pairwise, pen, z, residual, weights, active, kkt, dual, inactive):
|
|
65
|
+
"""Differentiate outer SSE through a regular inner QP using an adjoint solve."""
|
|
66
|
+
if weights[active].min() < 1e-12 or (inactive.any() and dual[inactive].min() < 1e-12):
|
|
67
|
+
raise _DerivativeUnavailable("inner QP lies on a nondifferentiable active-set boundary")
|
|
68
|
+
try:
|
|
69
|
+
adjoint = np.linalg.solve(kkt, np.r_[-2 * z[:, active].T @ residual, 0.0])[:-1]
|
|
70
|
+
except np.linalg.LinAlgError as exc:
|
|
71
|
+
raise _DerivativeUnavailable("singular adjoint KKT system") from exc
|
|
72
|
+
derivative = -(
|
|
73
|
+
2 * (a[:, active] @ adjoint) * (a @ weights) + pen * (pairwise[:, active] @ adjoint)
|
|
74
|
+
)
|
|
75
|
+
if not np.isfinite(derivative).all():
|
|
76
|
+
raise _DerivativeUnavailable("nonfinite implicit derivative")
|
|
77
|
+
return derivative
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class StableNestedOptimizer:
|
|
81
|
+
"""Local mixin; never modifies the installed upstream package."""
|
|
82
|
+
|
|
83
|
+
outer_max_iter = 10000
|
|
84
|
+
|
|
85
|
+
def optimize(
|
|
86
|
+
self,
|
|
87
|
+
treated_outcome,
|
|
88
|
+
treated_covariates,
|
|
89
|
+
control_outcome,
|
|
90
|
+
control_covariates,
|
|
91
|
+
pairwise_difference,
|
|
92
|
+
data,
|
|
93
|
+
placebo,
|
|
94
|
+
pen,
|
|
95
|
+
steps=10,
|
|
96
|
+
verbose=False,
|
|
97
|
+
):
|
|
98
|
+
import cvxpy as cp
|
|
99
|
+
|
|
100
|
+
if placebo:
|
|
101
|
+
raise NotImplementedError("Use pysynth.placebo_test to refit the checked adapter")
|
|
102
|
+
target = np.asarray(treated_covariates).reshape(-1)
|
|
103
|
+
x = np.asarray(control_covariates)
|
|
104
|
+
z = np.asarray(control_outcome)
|
|
105
|
+
y = np.asarray(treated_outcome).reshape(-1)
|
|
106
|
+
n_predictors, n_donors = x.shape
|
|
107
|
+
v = cp.Parameter(n_predictors, nonneg=True)
|
|
108
|
+
w = cp.Variable(n_donors)
|
|
109
|
+
# On sum(w)=1 this is algebraically identical to target-Xw,
|
|
110
|
+
# but it avoids cancellation between large outcome levels in the QP.
|
|
111
|
+
a = x - target[:, None]
|
|
112
|
+
discrepancy = cp.square(a @ w)
|
|
113
|
+
pairwise = np.asarray(pairwise_difference) ** 2
|
|
114
|
+
problem = cp.Problem(
|
|
115
|
+
cp.Minimize(v @ discrepancy + pen * (v @ pairwise @ w)),
|
|
116
|
+
[w >= 0, cp.sum(w) == 1],
|
|
117
|
+
)
|
|
118
|
+
# Simplex weights permit subtracting the treated outcome from every
|
|
119
|
+
# donor. This prevents cancellation after large common level shifts.
|
|
120
|
+
# Keep the original variance scaling without an absolute outcome-unit
|
|
121
|
+
# floor. Use donor discrepancies only for a constant treated pre-path.
|
|
122
|
+
loss_scale = float(np.var(y)) * len(y)
|
|
123
|
+
z = z - y[:, None]
|
|
124
|
+
if loss_scale == 0:
|
|
125
|
+
loss_scale = float(np.max(np.abs(z))) ** 2 * len(y) or 1.0
|
|
126
|
+
best = {"loss": np.inf}
|
|
127
|
+
cache = {}
|
|
128
|
+
evaluations = 0
|
|
129
|
+
|
|
130
|
+
def objective(candidate):
|
|
131
|
+
nonlocal evaluations
|
|
132
|
+
candidate = np.clip(np.asarray(candidate), 0, 1)
|
|
133
|
+
if "candidate" in cache and np.array_equal(candidate, cache["candidate"]):
|
|
134
|
+
return cache["loss"] / loss_scale
|
|
135
|
+
evaluations += 1
|
|
136
|
+
if candidate.sum() <= np.finfo(float).eps:
|
|
137
|
+
cache.clear()
|
|
138
|
+
cache.update(
|
|
139
|
+
candidate=candidate.copy(),
|
|
140
|
+
loss=1e30 * loss_scale,
|
|
141
|
+
unavailable="all predictor weights are zero",
|
|
142
|
+
)
|
|
143
|
+
return 1e30
|
|
144
|
+
v.value = candidate
|
|
145
|
+
problem.solve(
|
|
146
|
+
solver="CLARABEL",
|
|
147
|
+
warm_start=False,
|
|
148
|
+
tol_gap_abs=1e-10,
|
|
149
|
+
tol_gap_rel=1e-10,
|
|
150
|
+
tol_feas=1e-10,
|
|
151
|
+
max_iter=500,
|
|
152
|
+
)
|
|
153
|
+
if problem.status != cp.OPTIMAL or w.value is None:
|
|
154
|
+
raise RuntimeError(f"SCM inner quadratic program failed: {problem.status}")
|
|
155
|
+
weights = np.asarray(w.value).reshape(-1)
|
|
156
|
+
if weights.min() < -1e-8 or abs(weights.sum() - 1) > 1e-8:
|
|
157
|
+
raise RuntimeError("SCM inner quadratic program returned infeasible weights")
|
|
158
|
+
weights = np.maximum(weights, 0)
|
|
159
|
+
weights /= weights.sum()
|
|
160
|
+
cache.clear()
|
|
161
|
+
cache["candidate"] = candidate.copy()
|
|
162
|
+
try:
|
|
163
|
+
weights, active, kkt, dual, inactive = _polish_weights(
|
|
164
|
+
a, pairwise, candidate, pen, weights
|
|
165
|
+
)
|
|
166
|
+
cache.update(active=active, kkt=kkt, dual=dual, inactive=inactive)
|
|
167
|
+
except _DerivativeUnavailable as exc:
|
|
168
|
+
# The original convex QP remains solved and feasible. It can
|
|
169
|
+
# still be evaluated by a derivative-free outer optimizer.
|
|
170
|
+
cache["unavailable"] = str(exc)
|
|
171
|
+
residual = -z @ weights
|
|
172
|
+
loss = float(residual @ residual)
|
|
173
|
+
cache.update(loss=loss, weights=weights.copy(), residual=residual)
|
|
174
|
+
if loss < best["loss"]:
|
|
175
|
+
best.update(loss=loss, weights=weights.copy(), v=candidate.copy())
|
|
176
|
+
return loss / loss_scale
|
|
177
|
+
|
|
178
|
+
def gradient(candidate):
|
|
179
|
+
objective(candidate)
|
|
180
|
+
if "unavailable" in cache:
|
|
181
|
+
raise _DerivativeUnavailable(cache["unavailable"])
|
|
182
|
+
# Exact outer fit is its global lower bound, including a redundant
|
|
183
|
+
# active constraint where strict complementarity need not hold.
|
|
184
|
+
if cache["loss"] <= np.finfo(float).eps * loss_scale:
|
|
185
|
+
return np.zeros(n_predictors)
|
|
186
|
+
return (
|
|
187
|
+
_outer_derivative(
|
|
188
|
+
a,
|
|
189
|
+
pairwise,
|
|
190
|
+
pen,
|
|
191
|
+
z,
|
|
192
|
+
cache["residual"],
|
|
193
|
+
cache["weights"],
|
|
194
|
+
cache["active"],
|
|
195
|
+
cache["kkt"],
|
|
196
|
+
cache["dual"],
|
|
197
|
+
cache["inactive"],
|
|
198
|
+
)
|
|
199
|
+
/ loss_scale
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
diagnostics = []
|
|
203
|
+
for start in range(steps):
|
|
204
|
+
initial = (
|
|
205
|
+
np.full(n_predictors, 1 / n_predictors)
|
|
206
|
+
if start == 0
|
|
207
|
+
else self.original_data.rng.dirichlet(np.ones(n_predictors)).reshape(-1)
|
|
208
|
+
)
|
|
209
|
+
bounds = [(0, 1)] * n_predictors
|
|
210
|
+
initial_loss = objective(initial)
|
|
211
|
+
before = evaluations
|
|
212
|
+
try:
|
|
213
|
+
solved = minimize(
|
|
214
|
+
objective,
|
|
215
|
+
initial,
|
|
216
|
+
jac=gradient,
|
|
217
|
+
method="L-BFGS-B",
|
|
218
|
+
bounds=bounds,
|
|
219
|
+
options={
|
|
220
|
+
"maxiter": self.outer_max_iter,
|
|
221
|
+
"maxls": 50,
|
|
222
|
+
"ftol": 1e-10,
|
|
223
|
+
"gtol": 1e-7,
|
|
224
|
+
},
|
|
225
|
+
)
|
|
226
|
+
except _DerivativeUnavailable as exc:
|
|
227
|
+
solved = OptimizeResult(
|
|
228
|
+
x=cache["candidate"].copy(),
|
|
229
|
+
fun=cache["loss"] / loss_scale,
|
|
230
|
+
success=False,
|
|
231
|
+
nfev=evaluations - before,
|
|
232
|
+
message=str(exc),
|
|
233
|
+
)
|
|
234
|
+
attempts = [
|
|
235
|
+
{
|
|
236
|
+
"solver": "L-BFGS-B",
|
|
237
|
+
"derivative": "active-set KKT adjoint",
|
|
238
|
+
"success": bool(solved.success),
|
|
239
|
+
"message": str(solved.message),
|
|
240
|
+
"evaluations": int(solved.nfev),
|
|
241
|
+
}
|
|
242
|
+
]
|
|
243
|
+
if not solved.success:
|
|
244
|
+
# At a changing or singular active set an implicit derivative
|
|
245
|
+
# need not exist. Powell solves the same full objective without
|
|
246
|
+
# accepting an unreliable gradient or discarding this start.
|
|
247
|
+
solved = minimize(
|
|
248
|
+
objective,
|
|
249
|
+
solved.x,
|
|
250
|
+
method="Powell",
|
|
251
|
+
bounds=bounds,
|
|
252
|
+
options={
|
|
253
|
+
"maxiter": self.outer_max_iter,
|
|
254
|
+
"maxfev": 1000000,
|
|
255
|
+
"xtol": 1e-6,
|
|
256
|
+
"ftol": 1e-10,
|
|
257
|
+
},
|
|
258
|
+
)
|
|
259
|
+
attempts.append(
|
|
260
|
+
{
|
|
261
|
+
"solver": "Powell",
|
|
262
|
+
"success": bool(solved.success),
|
|
263
|
+
"message": str(solved.message),
|
|
264
|
+
"evaluations": int(solved.nfev),
|
|
265
|
+
}
|
|
266
|
+
)
|
|
267
|
+
if not solved.success or not np.isfinite(solved.fun):
|
|
268
|
+
raise RuntimeError(f"SCM optimization start {start + 1} failed: {solved.message}")
|
|
269
|
+
diagnostics.append(
|
|
270
|
+
{
|
|
271
|
+
"start": start + 1,
|
|
272
|
+
"initial_loss": initial_loss * loss_scale,
|
|
273
|
+
"final_loss": float(solved.fun * loss_scale),
|
|
274
|
+
"attempts": attempts,
|
|
275
|
+
}
|
|
276
|
+
)
|
|
277
|
+
self.optimization_diagnostics_ = diagnostics
|
|
278
|
+
data.min_loss = best["loss"]
|
|
279
|
+
data.w = best["weights"][:, None]
|
|
280
|
+
data.v = best["v"] / best["v"].sum()
|
|
281
|
+
data.pen = pen
|
|
282
|
+
data.synth_outcome = data.w.T @ data.control_outcome_all.T
|
|
283
|
+
data.synth_covariates = data.control_covariates @ data.w
|
|
284
|
+
if self.method == "DSC":
|
|
285
|
+
self._update_original_data(placebo)
|
pysynth/_optim.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Constrained least squares with analytic gradients and explicit failures."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from scipy.optimize import minimize
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _improving_transfer(a, penalty, weights, tolerance):
|
|
8
|
+
"""Find a feasible donor-to-donor transfer that materially improves the same loss."""
|
|
9
|
+
residual = a @ weights
|
|
10
|
+
# The initial SLSQP solve is scaled to the most extreme eligible donor.
|
|
11
|
+
# Check the achieved fit on the scale of donors actually used, otherwise
|
|
12
|
+
# one distant, zero-weight donor can make a bad active-face fit look exact.
|
|
13
|
+
local_scale = max(np.max(np.abs(a) @ weights) ** 2, penalty)
|
|
14
|
+
best_gain = tolerance * local_scale
|
|
15
|
+
gradient = a.T @ residual / len(a) + penalty * weights # half gradient
|
|
16
|
+
best = None
|
|
17
|
+
# For a transfer of size s from i to j the exact decrease is
|
|
18
|
+
# 2 s (g_i - g_j) - s² (mean((a_i-a_j)²) + 2*penalty).
|
|
19
|
+
# The linear part alone bounds every possible gain out of donor i.
|
|
20
|
+
for i in np.flatnonzero(2 * weights * (gradient - gradient.min()) > best_gain):
|
|
21
|
+
slope = gradient[i] - gradient
|
|
22
|
+
targets = np.flatnonzero(2 * weights[i] * slope > best_gain)
|
|
23
|
+
if not len(targets):
|
|
24
|
+
continue
|
|
25
|
+
delta = a[:, targets] - a[:, i, None]
|
|
26
|
+
curvature = np.einsum("ij,ij->j", delta, delta) / len(a) + 2 * penalty
|
|
27
|
+
step = np.full(len(targets), weights[i])
|
|
28
|
+
positive = curvature > 0
|
|
29
|
+
step[positive] = np.minimum(step[positive], slope[targets][positive] / curvature[positive])
|
|
30
|
+
gains = step * (2 * slope[targets] - curvature * step)
|
|
31
|
+
k = int(np.argmax(gains))
|
|
32
|
+
if gains[k] > best_gain:
|
|
33
|
+
best_gain = gains[k]
|
|
34
|
+
best = i, targets[k], step[k]
|
|
35
|
+
return best
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def simplex_fit(x, y, *, ridge=0.0, max_iter=10000, tol=1e-12):
|
|
39
|
+
"""Minimise mean squared error + ridge * squared norm on the simplex."""
|
|
40
|
+
x, y = np.asarray(x, float), np.asarray(y, float)
|
|
41
|
+
if x.ndim != 2 or y.shape != (x.shape[0],) or not all(x.shape):
|
|
42
|
+
raise ValueError("x must be a nonempty matrix and y a matching outcome vector")
|
|
43
|
+
if not np.isfinite(x).all() or not np.isfinite(y).all():
|
|
44
|
+
raise ValueError("x and y must be finite")
|
|
45
|
+
if not np.isfinite(ridge) or ridge < 0:
|
|
46
|
+
raise ValueError("ridge must be finite and nonnegative")
|
|
47
|
+
# On the simplex, (X-y1')w = Xw-y. Scaling these differences instead
|
|
48
|
+
# of outcome levels preserves the fit after any common time-varying shift
|
|
49
|
+
# and avoids false convergence when the original units are very small.
|
|
50
|
+
differences = x - y[:, None]
|
|
51
|
+
scale = max(float(np.max(np.abs(differences))), float(np.sqrt(ridge)))
|
|
52
|
+
if scale == 0:
|
|
53
|
+
return np.full(x.shape[1], 1 / x.shape[1]), {
|
|
54
|
+
"iterations": 0,
|
|
55
|
+
"donor_transfers": 0,
|
|
56
|
+
"objective": 0.0,
|
|
57
|
+
"optimality_gap": 0.0,
|
|
58
|
+
"scaled_optimality_gap": 0.0,
|
|
59
|
+
}
|
|
60
|
+
a, penalty = differences / scale, (np.sqrt(ridge) / scale) ** 2
|
|
61
|
+
n, p = a.shape
|
|
62
|
+
|
|
63
|
+
def fun(w):
|
|
64
|
+
e = a @ w
|
|
65
|
+
return e @ e / n + penalty * (w @ w)
|
|
66
|
+
|
|
67
|
+
def jac(w):
|
|
68
|
+
return 2 * (a.T @ (a @ w) / n + penalty * w)
|
|
69
|
+
|
|
70
|
+
sol = minimize(
|
|
71
|
+
fun,
|
|
72
|
+
np.full(p, 1 / p),
|
|
73
|
+
jac=jac,
|
|
74
|
+
method="SLSQP",
|
|
75
|
+
bounds=[(0, 1)] * p,
|
|
76
|
+
constraints={"type": "eq", "fun": lambda w: w.sum() - 1, "jac": lambda w: np.ones(p)},
|
|
77
|
+
options={"maxiter": max_iter, "ftol": tol},
|
|
78
|
+
)
|
|
79
|
+
if not sol.success or not np.isfinite(sol.x).all():
|
|
80
|
+
raise RuntimeError(f"Synthetic control optimisation failed: {sol.message}")
|
|
81
|
+
if sol.x.min() < -1e-8 or abs(sol.x.sum() - 1) > 1e-8:
|
|
82
|
+
raise RuntimeError("Synthetic control optimisation returned infeasible weights")
|
|
83
|
+
w = np.maximum(sol.x, 0)
|
|
84
|
+
w /= w.sum()
|
|
85
|
+
transfers = 0
|
|
86
|
+
while (transfer := _improving_transfer(a, penalty, w, tol)) is not None:
|
|
87
|
+
if sol.nit + transfers >= max_iter:
|
|
88
|
+
raise RuntimeError(
|
|
89
|
+
"Synthetic control optimisation exhausted max_iter with an improving donor transfer"
|
|
90
|
+
)
|
|
91
|
+
donor, recipient, step = transfer
|
|
92
|
+
w[donor] -= step
|
|
93
|
+
w[recipient] += step
|
|
94
|
+
transfers += 1
|
|
95
|
+
residual = differences @ w
|
|
96
|
+
# For a convex differentiable objective over the simplex, this
|
|
97
|
+
# Frank--Wolfe gap bounds f(w)-min(f), independently of solver status.
|
|
98
|
+
gradient = jac(w)
|
|
99
|
+
scaled_gap = max(0.0, float(gradient @ w - gradient.min()))
|
|
100
|
+
return w, {
|
|
101
|
+
"iterations": sol.nit + transfers,
|
|
102
|
+
"donor_transfers": transfers,
|
|
103
|
+
"objective": float(residual @ residual / n + ridge * (w @ w)),
|
|
104
|
+
"optimality_gap": scaled_gap * scale * scale,
|
|
105
|
+
"scaled_optimality_gap": scaled_gap,
|
|
106
|
+
}
|
pysynth/_r.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Isolated execution of separately provisioned, local R reference resources."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import warnings
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _checkout_root():
|
|
16
|
+
"""Find this checkout from its root or a notebook subdirectory."""
|
|
17
|
+
working = Path.cwd().resolve()
|
|
18
|
+
for directory in (working, *working.parents):
|
|
19
|
+
if (directory / "pyproject.toml").is_file() and (directory / "src/pysynth").is_dir():
|
|
20
|
+
return directory
|
|
21
|
+
return working
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def reference_directory(*required):
|
|
25
|
+
"""Locate local runtime resources, rejecting missing or incomplete sets.
|
|
26
|
+
|
|
27
|
+
An explicit environment setting is authoritative. No installed package,
|
|
28
|
+
remote URL, Git history, or alternative implementation is searched.
|
|
29
|
+
"""
|
|
30
|
+
configured = os.environ.get("PYSYNTH_REFERENCE_DIR")
|
|
31
|
+
directory = (
|
|
32
|
+
Path(configured).expanduser().resolve()
|
|
33
|
+
if configured
|
|
34
|
+
else _checkout_root() / ".local/reference/runtime"
|
|
35
|
+
)
|
|
36
|
+
missing = [name for name in required if not (directory / name).is_file()]
|
|
37
|
+
if not directory.is_dir() or missing:
|
|
38
|
+
detail = f" Missing files: {', '.join(missing)}." if missing else ""
|
|
39
|
+
raise ImportError(
|
|
40
|
+
f"Local R reference resources are unavailable in {directory}.{detail} "
|
|
41
|
+
"They are not distributed with this repository or its Python packages. "
|
|
42
|
+
"Provision the local reference resources separately and set "
|
|
43
|
+
"PYSYNTH_REFERENCE_DIR to their runtime directory; see "
|
|
44
|
+
"docs/reference_backends.md. No resources are downloaded and no "
|
|
45
|
+
"approximation is substituted."
|
|
46
|
+
)
|
|
47
|
+
return directory
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def reference_library(r_library=None):
|
|
51
|
+
"""Use the explicit library or the checkout's existing local installation."""
|
|
52
|
+
library = r_library or os.environ.get("PYSYNTH_R_LIBRARY")
|
|
53
|
+
if library:
|
|
54
|
+
selected = Path(library).expanduser().resolve()
|
|
55
|
+
if not selected.is_dir():
|
|
56
|
+
# R silently drops nonexistent directories from .libPaths().
|
|
57
|
+
raise ImportError(f"Selected R library directory does not exist: {selected}")
|
|
58
|
+
return str(selected)
|
|
59
|
+
local = _checkout_root() / ".r-library"
|
|
60
|
+
return str(local) if local.is_dir() else None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def require_rscript():
|
|
64
|
+
executable = shutil.which("Rscript")
|
|
65
|
+
if executable is None:
|
|
66
|
+
raise ImportError(
|
|
67
|
+
"The local reference backend requires Rscript. Install base R and "
|
|
68
|
+
"provision the required local reference resources and pinned R packages; "
|
|
69
|
+
"see docs/reference_backends.md. There is no automatic approximation fallback."
|
|
70
|
+
)
|
|
71
|
+
return executable
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run_reference(name, matrices, options, *, r_library=None):
|
|
75
|
+
"""Run a separately provisioned R script with numeric files and JSON arguments.
|
|
76
|
+
|
|
77
|
+
No packages or code are downloaded during estimation. R is a separate
|
|
78
|
+
process, so reference package loading and random seeds cannot alter the
|
|
79
|
+
Python process or another fit. Failures retain the R error message.
|
|
80
|
+
"""
|
|
81
|
+
required = {
|
|
82
|
+
"scul": ("scul.R", "common.R", "scul/SCUL.R", "scul/getOptcv.scul.R", "scul/mysd.R"),
|
|
83
|
+
"isc": ("isc.R", "common.R"),
|
|
84
|
+
}
|
|
85
|
+
if name not in required:
|
|
86
|
+
raise ValueError(f"Unknown local reference backend: {name}")
|
|
87
|
+
directory_reference = reference_directory(*required[name])
|
|
88
|
+
executable = require_rscript()
|
|
89
|
+
library = reference_library(r_library)
|
|
90
|
+
with tempfile.TemporaryDirectory(prefix=f"pysynth-{name}-") as temporary:
|
|
91
|
+
directory = Path(temporary)
|
|
92
|
+
for key, value in matrices.items():
|
|
93
|
+
np.savetxt(directory / f"{key}.csv", np.asarray(value), delimiter=",")
|
|
94
|
+
arguments = dict(
|
|
95
|
+
options,
|
|
96
|
+
r_library=str(library) if library else None,
|
|
97
|
+
python_executable=sys.executable,
|
|
98
|
+
)
|
|
99
|
+
(directory / "options.json").write_text(json.dumps(arguments), encoding="utf-8")
|
|
100
|
+
result = subprocess.run(
|
|
101
|
+
[
|
|
102
|
+
executable,
|
|
103
|
+
"--vanilla",
|
|
104
|
+
str(directory_reference / f"{name}.R"),
|
|
105
|
+
str(directory),
|
|
106
|
+
str(directory_reference),
|
|
107
|
+
],
|
|
108
|
+
env=dict(os.environ, PYSYNTH_R_LIBRARY=str(library)) if library else None,
|
|
109
|
+
capture_output=True,
|
|
110
|
+
text=True,
|
|
111
|
+
check=False,
|
|
112
|
+
)
|
|
113
|
+
if result.returncode:
|
|
114
|
+
raise RuntimeError(
|
|
115
|
+
f"The {name} reference backend failed:\n{result.stderr.strip()}\n"
|
|
116
|
+
"Check the separately provisioned resources and pinned dependencies; "
|
|
117
|
+
"select the R library with PYSYNTH_R_LIBRARY or r_library. "
|
|
118
|
+
"See docs/reference_backends.md."
|
|
119
|
+
)
|
|
120
|
+
output = json.loads((directory / "result.json").read_text(encoding="utf-8"))
|
|
121
|
+
if result.stderr.strip():
|
|
122
|
+
warnings.warn(
|
|
123
|
+
f"{name} reference backend: {result.stderr.strip()}", RuntimeWarning, stacklevel=2
|
|
124
|
+
)
|
|
125
|
+
return output
|