ectype-data 0.1.0__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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,781 @@
|
|
|
1
|
+
"""Post-processing distortion calibration (design §6.2, M25).
|
|
2
|
+
|
|
3
|
+
``calibrate(fp)`` corrects the drift that post-processing (constraint rejection and repair,
|
|
4
|
+
missingness injection, rounding, categorical encoding) adds on top of the joint sampler, using
|
|
5
|
+
the analytic, low-dimensional adjustments of :mod:`ectype.calibration.adjustments`.
|
|
6
|
+
|
|
7
|
+
Visibility
|
|
8
|
+
The calibrator works from ``fp.calibration_view()`` only: the model and the *calibration*
|
|
9
|
+
targets. It never opens the seal. The returned fingerprint is ``fp.copy()`` with the adjusted
|
|
10
|
+
model section and arrays swapped in, so the sealed bytes and the committed seal hash are
|
|
11
|
+
carried over untouched (the content hash changes, as it must).
|
|
12
|
+
|
|
13
|
+
Loop
|
|
14
|
+
0. Evaluate the starting model on the **evaluation** stream (``rng.stream(seed,
|
|
15
|
+
"evaluation")``); the objective is ``sum_i min(max(0, d_i / (tol_i * tolerance_scale)
|
|
16
|
+
- 1), 100)`` over the calibration targets (normalized exceedance; 0 iff all pass).
|
|
17
|
+
1. Generate a sample on the **calibration** stream (``rng.stream(seed, "calibration")``) and
|
|
18
|
+
measure every calibration target on it.
|
|
19
|
+
2. For targets failing on either stream, propose the linked adjustments:
|
|
20
|
+
``univariate.mean_std`` (plus ``wasserstein``/``ks`` on the same continuous column) ->
|
|
21
|
+
affine marginal pre-distortion; ``univariate.missing_rate`` -> indicator rate;
|
|
22
|
+
``bivariate.pearson``/``spearman`` on a numeric pair -> latent copula correlation. Step
|
|
23
|
+
sizes are computed from the calibration-stream measurements only.
|
|
24
|
+
|
|
25
|
+
Targets are measured on source columns. A column computed by a structural transform
|
|
26
|
+
(format 0.3, ADR-0005) has no marginal, indicator or copula column of its own, so a
|
|
27
|
+
failing target on it is mapped to the model column that stands for it: for the target
|
|
28
|
+
of a ``difference`` transform (``target = base + sign * delta``) the hidden ``delta``.
|
|
29
|
+
Its mean/std drift becomes a location/scale change of delta that keeps ``delta >= 0``
|
|
30
|
+
(``delta_affine``), its missing rate the rate of delta's indicator, and a correlation
|
|
31
|
+
with it the latent correlation of delta (with the transform's sign). Where there is
|
|
32
|
+
nothing well-defined to adjust -- the target of an ``identity`` transform is derived,
|
|
33
|
+
a non-continuous column has no affine pre-distortion, a mean on the wrong side of the
|
|
34
|
+
base cannot be reached with a non-negative delta -- the target is skipped and, if it is
|
|
35
|
+
still failing at the end, listed in ``CalibrationResult.diagnostics`` as
|
|
36
|
+
"transform target not adjustable".
|
|
37
|
+
3. Try the combined step, then each proposal alone (largest exceedance first), then each
|
|
38
|
+
at half step. A candidate is accepted only if it lowers the evaluation-stream objective.
|
|
39
|
+
A candidate that lowers the rejection acceptance rate by more than
|
|
40
|
+
``MAX_ACCEPTANCE_LOSS`` (10 points) below the starting model's is rejected whatever its
|
|
41
|
+
objective, and marginal affine adjustments are capped cumulatively (scale in [0.5, 2],
|
|
42
|
+
shift within +-1 std). Targets left failing because of either limit are reported as
|
|
43
|
+
"target unreachable under constraint" in ``CalibrationResult.diagnostics``.
|
|
44
|
+
4. Stop when every calibration target passes (``converged``), on ``iteration_budget``,
|
|
45
|
+
``time_budget``, ``stalled`` (nothing improved) or ``no_adjustable_parameters``.
|
|
46
|
+
|
|
47
|
+
Both streams use fixed seeds across iterations (common random numbers), so candidate
|
|
48
|
+
comparisons are not swamped by generation noise; keeping the evaluation stream separate from
|
|
49
|
+
the one the steps are computed on limits overfitting to a single sample. The result is
|
|
50
|
+
deterministic for a given fingerprint and arguments, unless the time budget cuts a run short.
|
|
51
|
+
Non-convergence still returns the best model found plus the explicit failing targets.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
from __future__ import annotations
|
|
55
|
+
|
|
56
|
+
import math
|
|
57
|
+
import time
|
|
58
|
+
from collections import defaultdict
|
|
59
|
+
from collections.abc import Callable
|
|
60
|
+
from dataclasses import dataclass, field
|
|
61
|
+
from typing import Any
|
|
62
|
+
|
|
63
|
+
import numpy as np
|
|
64
|
+
import polars as pl
|
|
65
|
+
|
|
66
|
+
from ectype.calibration.adjustments import (
|
|
67
|
+
Adjustment,
|
|
68
|
+
State,
|
|
69
|
+
adjust_correlation,
|
|
70
|
+
adjust_delta_affine,
|
|
71
|
+
adjust_marginal_affine,
|
|
72
|
+
adjust_missing_rate,
|
|
73
|
+
latent_slot,
|
|
74
|
+
)
|
|
75
|
+
from ectype.errors import ConstraintError, FingerprintError, GenerationError
|
|
76
|
+
from ectype.fingerprint.core import ArrayStore, CalibrationView, Fingerprint
|
|
77
|
+
from ectype.fingerprint.disclosure import resolve_policy
|
|
78
|
+
from ectype.fingerprint.schema import (
|
|
79
|
+
ColumnSchema,
|
|
80
|
+
DisclosurePolicySpec,
|
|
81
|
+
Manifest,
|
|
82
|
+
Target,
|
|
83
|
+
TransformSpec,
|
|
84
|
+
)
|
|
85
|
+
from ectype.rng import stream
|
|
86
|
+
from ectype.types import LogicalType
|
|
87
|
+
from ectype.validation.metrics import ( # noqa: F401 (registration side effects)
|
|
88
|
+
bivariate,
|
|
89
|
+
missingness,
|
|
90
|
+
univariate,
|
|
91
|
+
)
|
|
92
|
+
from ectype.validation.metrics.base import METRICS
|
|
93
|
+
|
|
94
|
+
EXCEEDANCE_CAP = 100.0
|
|
95
|
+
MAX_TRIALS_PER_ITERATION = 8
|
|
96
|
+
#: Steps aim at ``target + clip(measured - target, +-TARGET_AIM * tolerance)``: inside the
|
|
97
|
+
#: tolerance band with a margin, not at the exact target value. The smallest adjustment that
|
|
98
|
+
#: fixes a target disturbs unmeasured (e.g. sealed) structure least.
|
|
99
|
+
TARGET_AIM = 0.5
|
|
100
|
+
#: A candidate that lowers the constraint-rejection acceptance rate by more than this (absolute,
|
|
101
|
+
#: relative to the uncalibrated model) is rejected: past that point calibration is fighting a
|
|
102
|
+
#: truncating constraint, not correcting post-processing distortion.
|
|
103
|
+
MAX_ACCEPTANCE_LOSS = 0.10
|
|
104
|
+
_AFFINE_METRICS = ("univariate.mean_std", "univariate.wasserstein", "univariate.ks")
|
|
105
|
+
_CORR_METRICS = ("bivariate.pearson", "bivariate.spearman")
|
|
106
|
+
_NUMERIC = (LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.DATETIME)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------------------------
|
|
110
|
+
# Evaluation
|
|
111
|
+
# ---------------------------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@dataclass
|
|
115
|
+
class TargetEval:
|
|
116
|
+
id: str
|
|
117
|
+
metric: str
|
|
118
|
+
columns: list[str]
|
|
119
|
+
distance: float
|
|
120
|
+
tolerance: float
|
|
121
|
+
ratio: float # distance / (tolerance * tolerance_scale)
|
|
122
|
+
measured: Any = None
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def passed(self) -> bool:
|
|
126
|
+
return self.ratio <= 1.0 + 1e-12
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def exceedance(self) -> float:
|
|
130
|
+
if not math.isfinite(self.ratio):
|
|
131
|
+
return EXCEEDANCE_CAP
|
|
132
|
+
return min(max(0.0, self.ratio - 1.0), EXCEEDANCE_CAP)
|
|
133
|
+
|
|
134
|
+
def to_dict(self) -> dict[str, Any]:
|
|
135
|
+
return {"id": self.id, "metric": self.metric, "columns": list(self.columns),
|
|
136
|
+
"distance": _finite(self.distance), "tolerance": self.tolerance,
|
|
137
|
+
"ratio": _finite(self.ratio)}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@dataclass
|
|
141
|
+
class Evaluation:
|
|
142
|
+
targets: dict[str, TargetEval]
|
|
143
|
+
error: str | None = None
|
|
144
|
+
acceptance_rate: float | None = None # constraint-rejection acceptance of the sample
|
|
145
|
+
#: per target column of a ``difference`` transform: how its base and its hidden delta vary
|
|
146
|
+
#: on the sample (see :func:`_gap_moments`)
|
|
147
|
+
structure: dict[str, dict[str, float]] = field(default_factory=dict)
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def objective(self) -> float:
|
|
151
|
+
if self.error is not None:
|
|
152
|
+
return math.inf
|
|
153
|
+
return float(sum(t.exceedance for t in self.targets.values()))
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def failing(self) -> list[TargetEval]:
|
|
157
|
+
return sorted((t for t in self.targets.values() if not t.passed),
|
|
158
|
+
key=lambda t: (-_key(t.ratio), t.id))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _finite(x: float) -> float | None:
|
|
162
|
+
return float(x) if math.isfinite(x) else None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _aim(measured: float, target: float, residual: float) -> float:
|
|
166
|
+
return target + max(-residual, min(residual, measured - target))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _key(x: float) -> float:
|
|
170
|
+
return x if math.isfinite(x) else 1e300
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _measure_targets(targets: list[Target], df: pl.DataFrame,
|
|
174
|
+
columns: dict[str, ColumnSchema], policy: DisclosurePolicySpec,
|
|
175
|
+
tolerance_scale: float) -> dict[str, TargetEval]:
|
|
176
|
+
"""Same semantics as ``fingerprint.targets.evaluate_target``, keeping the measurement."""
|
|
177
|
+
out: dict[str, TargetEval] = {}
|
|
178
|
+
for t in targets:
|
|
179
|
+
try:
|
|
180
|
+
metric = METRICS.get(t.metric)()
|
|
181
|
+
except KeyError:
|
|
182
|
+
continue
|
|
183
|
+
if getattr(metric, "requires_data", False):
|
|
184
|
+
continue
|
|
185
|
+
tol = float(t.tolerance if t.tolerance is not None else metric.default_tolerance)
|
|
186
|
+
cand: Any = None
|
|
187
|
+
if any(c not in df.columns or c not in columns for c in t.columns):
|
|
188
|
+
d = math.inf
|
|
189
|
+
else:
|
|
190
|
+
try:
|
|
191
|
+
cand = metric.measure(df, [columns[c] for c in t.columns], policy)
|
|
192
|
+
d = float(metric.distance(t.value, cand))
|
|
193
|
+
except Exception: # a metric failure is a failed target, not a crash
|
|
194
|
+
d = math.inf
|
|
195
|
+
if math.isnan(d):
|
|
196
|
+
d = math.inf
|
|
197
|
+
denom = tol * tolerance_scale
|
|
198
|
+
ratio = d / denom if denom > 0 else (0.0 if d == 0 else math.inf)
|
|
199
|
+
out[t.id] = TargetEval(t.id, t.metric, list(t.columns), d, tol, ratio, cand)
|
|
200
|
+
return out
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _gap_moments(df: pl.DataFrame, manifest: Manifest, columns: dict[str, ColumnSchema]
|
|
204
|
+
) -> dict[str, dict[str, float]]:
|
|
205
|
+
"""For the target column of every ``difference`` transform: the null rate of its base and,
|
|
206
|
+
over the rows where both are present, the moments of the base and of the hidden
|
|
207
|
+
``delta = sign * (target - base)`` as generated (``mean_base``, ``mean_delta``,
|
|
208
|
+
``var_base``, ``var_delta``, ``cov``). They are what a drift of the *target's* mean, spread
|
|
209
|
+
or missing rate is translated into an adjustment of delta with."""
|
|
210
|
+
from ectype.io.values import column_to_values
|
|
211
|
+
|
|
212
|
+
out: dict[str, dict[str, float]] = {}
|
|
213
|
+
for t in manifest.model.transforms:
|
|
214
|
+
if t.kind != "difference" or len(t.inputs) != 1:
|
|
215
|
+
continue
|
|
216
|
+
target, base = t.target, t.inputs[0]
|
|
217
|
+
if any(c not in df.columns or c not in columns for c in (target, base)):
|
|
218
|
+
continue
|
|
219
|
+
try:
|
|
220
|
+
y = np.asarray(column_to_values(df[target], columns[target]), dtype=np.float64)
|
|
221
|
+
x = np.asarray(column_to_values(df[base], columns[base]), dtype=np.float64)
|
|
222
|
+
except Exception: # noqa: BLE001 - nothing to measure: the target is skipped later
|
|
223
|
+
continue
|
|
224
|
+
ok = np.isfinite(x) & np.isfinite(y)
|
|
225
|
+
rec = {"n": float(ok.sum()),
|
|
226
|
+
"null_base": float(np.mean(~np.isfinite(x))) if x.size else 0.0}
|
|
227
|
+
if ok.sum() >= 3:
|
|
228
|
+
delta = float(t.params.get("sign", 1)) * (y[ok] - x[ok]) # type: ignore[arg-type]
|
|
229
|
+
c = np.cov(x[ok], delta, bias=True)
|
|
230
|
+
rec.update(mean_base=float(x[ok].mean()), mean_delta=float(delta.mean()),
|
|
231
|
+
var_base=float(c[0, 0]), var_delta=float(c[1, 1]), cov=float(c[0, 1]))
|
|
232
|
+
out[target] = rec
|
|
233
|
+
return out
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
class _Evaluator:
|
|
237
|
+
def __init__(self, view: CalibrationView, n: int, tolerance_scale: float) -> None:
|
|
238
|
+
self.view = view
|
|
239
|
+
self.n = n
|
|
240
|
+
self.tolerance_scale = tolerance_scale
|
|
241
|
+
self.policy = resolve_policy(view.manifest.disclosure_policy)
|
|
242
|
+
self.n_generations = 0
|
|
243
|
+
|
|
244
|
+
def __call__(self, state: State, seed: int) -> Evaluation:
|
|
245
|
+
from ectype.generation.generator import Generator
|
|
246
|
+
from ectype.profiling.reference import model_view
|
|
247
|
+
|
|
248
|
+
self.n_generations += 1
|
|
249
|
+
# A candidate fingerprint built from the view only: no sealed bytes at all.
|
|
250
|
+
fp = Fingerprint(manifest=state.manifest, arrays=state.arrays,
|
|
251
|
+
calibration=self.view.calibration)
|
|
252
|
+
try:
|
|
253
|
+
gen = Generator(fp)
|
|
254
|
+
# (reference keys are measured as group sizes, like their targets: ADR-0013)
|
|
255
|
+
df = model_view(gen.generate(self.n, seed=seed), state.manifest)
|
|
256
|
+
except (GenerationError, FingerprintError, ConstraintError, ValueError) as exc:
|
|
257
|
+
return Evaluation({}, error=f"{type(exc).__name__}: {exc}")
|
|
258
|
+
columns = {c.name: c for c in state.manifest.columns}
|
|
259
|
+
acc = gen.last_manifest.acceptance_rate if gen.last_manifest is not None else None
|
|
260
|
+
return Evaluation(_measure_targets(list(self.view.calibration.targets), df, columns,
|
|
261
|
+
self.policy, self.tolerance_scale),
|
|
262
|
+
acceptance_rate=acc,
|
|
263
|
+
structure=_gap_moments(df, state.manifest, columns))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
# ---------------------------------------------------------------------------------------------
|
|
267
|
+
# Proposals
|
|
268
|
+
# ---------------------------------------------------------------------------------------------
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
@dataclass
|
|
272
|
+
class _Proposal:
|
|
273
|
+
key: str
|
|
274
|
+
targets: list[str]
|
|
275
|
+
priority: float
|
|
276
|
+
apply: Callable[[State, float], Adjustment | None]
|
|
277
|
+
history_key: str = ""
|
|
278
|
+
measured: float = math.nan
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _describe(t: TransformSpec) -> str:
|
|
282
|
+
"""``"end = start + delta"`` / ``"total = qty * price"``."""
|
|
283
|
+
if t.kind == "difference" and t.inputs:
|
|
284
|
+
op = "+" if float(t.params.get("sign", 1)) > 0 else "-" # type: ignore[arg-type]
|
|
285
|
+
return f"{t.target} = {t.inputs[0]} {op} delta"
|
|
286
|
+
if t.kind == "identity" and len(t.inputs) == 2:
|
|
287
|
+
return f"{t.target} = {t.inputs[0]} {t.params.get('op')} {t.inputs[1]}"
|
|
288
|
+
return f"{t.target} = {t.kind}({', '.join(t.inputs)})"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _proposals(state: State, cal: Evaluation, ev: Evaluation, targets: dict[str, Target],
|
|
292
|
+
history: dict[str, list[tuple[float, float]]],
|
|
293
|
+
policy: DisclosurePolicySpec, tolerance_scale: float,
|
|
294
|
+
skipped: dict[str, str] | None = None) -> list[_Proposal]:
|
|
295
|
+
"""Adjustments linked to the failing targets. ``skipped`` collects, per target id, why a
|
|
296
|
+
target on a column computed by a structural transform has nothing to adjust."""
|
|
297
|
+
model = state.manifest.model
|
|
298
|
+
skipped = {} if skipped is None else skipped
|
|
299
|
+
computed = {t.target: t for t in model.transforms}
|
|
300
|
+
|
|
301
|
+
def band(tid: str) -> float:
|
|
302
|
+
# Residual (in metric distance units) a step may leave: minimal-change calibration.
|
|
303
|
+
return TARGET_AIM * cal.targets[tid].tolerance * tolerance_scale
|
|
304
|
+
|
|
305
|
+
schemas = {c.name: c for c in state.manifest.columns}
|
|
306
|
+
failing = {t.id for t in cal.failing} | {t.id for t in ev.failing}
|
|
307
|
+
by_col: dict[str, list[str]] = defaultdict(list)
|
|
308
|
+
by_pair: dict[tuple[str, str], list[str]] = defaultdict(list)
|
|
309
|
+
for tid in sorted(failing):
|
|
310
|
+
t = targets.get(tid)
|
|
311
|
+
if t is None or tid not in cal.targets:
|
|
312
|
+
continue
|
|
313
|
+
if len(t.columns) == 1:
|
|
314
|
+
by_col[t.columns[0]].append(tid)
|
|
315
|
+
elif len(t.columns) == 2 and t.metric in _CORR_METRICS:
|
|
316
|
+
by_pair[(t.columns[0], t.columns[1])].append(tid)
|
|
317
|
+
|
|
318
|
+
def prio(ids: list[str]) -> float:
|
|
319
|
+
return sum(cal.targets[i].exceedance + (ev.targets[i].exceedance if i in ev.targets
|
|
320
|
+
else 0.0) for i in ids)
|
|
321
|
+
|
|
322
|
+
def skip(ids: list[str], reason: str) -> None:
|
|
323
|
+
for tid in ids:
|
|
324
|
+
skipped[tid] = reason
|
|
325
|
+
|
|
326
|
+
out: list[_Proposal] = []
|
|
327
|
+
summed = {c: spec for spec in model.sums
|
|
328
|
+
for c in (spec.parts if spec.mode == "split"
|
|
329
|
+
else [spec.total] if spec.mode == "sum" else [])}
|
|
330
|
+
for col in sorted(by_col):
|
|
331
|
+
ids = by_col[col]
|
|
332
|
+
schema = schemas.get(col)
|
|
333
|
+
if col in summed:
|
|
334
|
+
# computed by a sum (ADR-0014): no marginal or indicator of its own to adjust
|
|
335
|
+
skip(ids, f"{col!r} is computed by a sum (mode {summed[col].mode}): it has no "
|
|
336
|
+
f"parameter of its own")
|
|
337
|
+
continue
|
|
338
|
+
# (c) affine marginal pre-distortion, driven by the column's mean_std target.
|
|
339
|
+
aff = [i for i in ids if targets[i].metric in _AFFINE_METRICS]
|
|
340
|
+
ms_id = f"univariate.mean_std:{col}"
|
|
341
|
+
ms = targets.get(ms_id)
|
|
342
|
+
if not ms or ms_id not in cal.targets:
|
|
343
|
+
ms = next((t for t in targets.values()
|
|
344
|
+
if t.metric == "univariate.mean_std" and t.columns == [col]), None)
|
|
345
|
+
transform = computed.get(col)
|
|
346
|
+
if transform is not None:
|
|
347
|
+
# A computed column has no marginal or indicator of its own: adjust the hidden
|
|
348
|
+
# delta that stands for it, where that is well-defined.
|
|
349
|
+
mr = [i for i in ids if targets[i].metric == "univariate.missing_rate"]
|
|
350
|
+
rule = _describe(transform)
|
|
351
|
+
if transform.kind != "difference":
|
|
352
|
+
skip([*aff, *mr], f"{col!r} is derived ({rule}): it has no parameter of its "
|
|
353
|
+
f"own, only its inputs do")
|
|
354
|
+
continue
|
|
355
|
+
latent = str(transform.params.get("latent"))
|
|
356
|
+
moments = cal.structure.get(col, {})
|
|
357
|
+
if aff:
|
|
358
|
+
continuous = (schema is not None
|
|
359
|
+
and schema.logical_type == LogicalType.CONTINUOUS
|
|
360
|
+
and transform.params.get("latent_type") == "continuous")
|
|
361
|
+
if not continuous:
|
|
362
|
+
skip(aff, f"{col!r} is computed as {rule}; the location and scale of a "
|
|
363
|
+
f"latent are only adjusted for continuous columns")
|
|
364
|
+
elif (ms is None or ms.id not in cal.targets
|
|
365
|
+
or not isinstance(cal.targets[ms.id].measured, dict)
|
|
366
|
+
or not isinstance(ms.value, dict)):
|
|
367
|
+
skip(aff, f"{col!r} is computed as {rule}; adjusting its latent needs the "
|
|
368
|
+
f"column's mean/std calibration target, which is not available")
|
|
369
|
+
elif "var_delta" not in moments or latent not in model.marginals:
|
|
370
|
+
skip(aff, f"{col!r} is computed as {rule}, but too few generated rows have "
|
|
371
|
+
f"both columns present to measure the latent")
|
|
372
|
+
else:
|
|
373
|
+
meas = dict(cal.targets[ms.id].measured)
|
|
374
|
+
sref = float(ms.value["std"]) or 1.0
|
|
375
|
+
r = band(ms.id) * sref
|
|
376
|
+
tval = {k: _aim(float(meas[k]), float(ms.value[k]), r)
|
|
377
|
+
for k in ("mean", "std")}
|
|
378
|
+
|
|
379
|
+
def apply_delta(s: State, step: float, t: TransformSpec = transform,
|
|
380
|
+
tv: dict[str, float] = tval,
|
|
381
|
+
mo: dict[str, float] = moments,
|
|
382
|
+
ids: list[str] = aff) -> Adjustment | None:
|
|
383
|
+
why: list[str] = []
|
|
384
|
+
adj = adjust_delta_affine(s, t, tv, mo, policy, step, why)
|
|
385
|
+
if adj is None and why:
|
|
386
|
+
skip(ids, f"{t.target!r} is computed as {_describe(t)}: {why[-1]}")
|
|
387
|
+
return adj
|
|
388
|
+
|
|
389
|
+
out.append(_Proposal(key=f"delta_affine:{col}", targets=aff,
|
|
390
|
+
priority=prio(aff), apply=apply_delta))
|
|
391
|
+
for tid in mr:
|
|
392
|
+
meas_v = cal.targets[tid].measured
|
|
393
|
+
if meas_v is None:
|
|
394
|
+
continue
|
|
395
|
+
if latent not in model.missingness:
|
|
396
|
+
skip([tid], f"{col!r} is computed as {rule} and its latent has no "
|
|
397
|
+
f"missingness indicator: it is missing only where "
|
|
398
|
+
f"{transform.inputs[0]!r} is")
|
|
399
|
+
continue
|
|
400
|
+
# missing = base missing, or the latent's own indicator: work in the
|
|
401
|
+
# indicator's own rate
|
|
402
|
+
base_rate = min(float(moments.get("null_base", 0.0)), 1.0 - 1e-9)
|
|
403
|
+
mv = max((float(meas_v) - base_rate) / (1.0 - base_rate), 0.0)
|
|
404
|
+
aim = (_aim(float(meas_v), float(targets[tid].value), band(tid))
|
|
405
|
+
- base_rate) / (1.0 - base_rate)
|
|
406
|
+
if aim <= 0.0 and mv <= 1e-9:
|
|
407
|
+
skip([tid], f"{col!r} is computed as {rule}: its target missing rate is "
|
|
408
|
+
f"not above that of {transform.inputs[0]!r}, which it "
|
|
409
|
+
f"inherits")
|
|
410
|
+
continue
|
|
411
|
+
hk = f"missing_rate:{col}"
|
|
412
|
+
|
|
413
|
+
def apply_gap_missing(s: State, step: float, name: str = latent,
|
|
414
|
+
c: str = col, m: float = mv, tv: float = max(aim, 0.0),
|
|
415
|
+
hk: str = hk) -> Adjustment | None:
|
|
416
|
+
adj = adjust_missing_rate(s, name, m, tv, history[hk], policy, step)
|
|
417
|
+
if adj is not None:
|
|
418
|
+
adj.columns = [c]
|
|
419
|
+
return adj
|
|
420
|
+
|
|
421
|
+
out.append(_Proposal(key=hk, targets=[tid], priority=prio([tid]),
|
|
422
|
+
history_key=hk, measured=mv, apply=apply_gap_missing))
|
|
423
|
+
continue
|
|
424
|
+
if (aff and ms is not None and ms.id in cal.targets and schema is not None
|
|
425
|
+
and schema.logical_type == LogicalType.CONTINUOUS and col in model.marginals
|
|
426
|
+
and isinstance(cal.targets[ms.id].measured, dict)
|
|
427
|
+
and isinstance(ms.value, dict)):
|
|
428
|
+
meas = dict(cal.targets[ms.id].measured)
|
|
429
|
+
sref = float(ms.value["std"]) or 1.0
|
|
430
|
+
r = band(ms.id) * sref
|
|
431
|
+
tval = {k: _aim(float(meas[k]), float(ms.value[k]), r) for k in ("mean", "std")}
|
|
432
|
+
|
|
433
|
+
def apply_affine(s: State, step: float, c: str = col, m: dict[str, float] = meas,
|
|
434
|
+
tv: dict[str, float] = tval) -> Adjustment | None:
|
|
435
|
+
return adjust_marginal_affine(s, c, m, tv, policy, step)
|
|
436
|
+
|
|
437
|
+
out.append(_Proposal(
|
|
438
|
+
key=f"marginal_affine:{col}", targets=aff, priority=prio(aff),
|
|
439
|
+
apply=apply_affine))
|
|
440
|
+
# (b) missingness indicator rate.
|
|
441
|
+
mr = [i for i in ids if targets[i].metric == "univariate.missing_rate"]
|
|
442
|
+
for tid in mr:
|
|
443
|
+
meas_v = cal.targets[tid].measured
|
|
444
|
+
if meas_v is None:
|
|
445
|
+
continue
|
|
446
|
+
hk = f"missing_rate:{col}"
|
|
447
|
+
mv = float(meas_v)
|
|
448
|
+
aim = _aim(mv, float(targets[tid].value), band(tid))
|
|
449
|
+
|
|
450
|
+
def apply_missing(s: State, step: float, c: str = col, m: float = mv,
|
|
451
|
+
tv: float = aim, hk: str = hk) -> Adjustment | None:
|
|
452
|
+
return adjust_missing_rate(s, c, m, tv, history[hk], policy, step)
|
|
453
|
+
|
|
454
|
+
out.append(_Proposal(
|
|
455
|
+
key=hk, targets=[tid], priority=prio([tid]), history_key=hk, measured=mv,
|
|
456
|
+
apply=apply_missing))
|
|
457
|
+
joint = model.joint
|
|
458
|
+
if joint is not None and joint.kind == "gaussian_copula":
|
|
459
|
+
jcols = {str(c) for c in joint.params.get("columns", [])} # type: ignore[union-attr]
|
|
460
|
+
for (a, b) in sorted(by_pair):
|
|
461
|
+
sa, sb = schemas.get(a), schemas.get(b)
|
|
462
|
+
ids = by_pair[(a, b)]
|
|
463
|
+
# the joint-model columns that stand for the two measured ones: themselves, or the
|
|
464
|
+
# hidden delta of a difference transform (with its sign)
|
|
465
|
+
if a in summed or b in summed:
|
|
466
|
+
skip(ids, f"{a if a in summed else b!r} is computed by a sum: it has no column "
|
|
467
|
+
f"in the joint model whose correlation could be adjusted")
|
|
468
|
+
continue
|
|
469
|
+
slot_a, slot_b = latent_slot(state.manifest, a), latent_slot(state.manifest, b)
|
|
470
|
+
if slot_a is None or slot_b is None:
|
|
471
|
+
derived = a if slot_a is None else b
|
|
472
|
+
skip(ids, f"{derived!r} is derived ({_describe(computed[derived])}): it has no "
|
|
473
|
+
f"column in the joint model whose correlation could be adjusted")
|
|
474
|
+
continue
|
|
475
|
+
(la, ga), (lb, gb) = slot_a, slot_b
|
|
476
|
+
if (sa is None or sb is None or sa.logical_type not in _NUMERIC
|
|
477
|
+
or sb.logical_type not in _NUMERIC or la not in jcols or lb not in jcols):
|
|
478
|
+
continue
|
|
479
|
+
worst = max(ids, key=lambda i: (_key(cal.targets[i].ratio), i))
|
|
480
|
+
meas_v = cal.targets[worst].measured
|
|
481
|
+
if meas_v is None or not math.isfinite(float(meas_v)):
|
|
482
|
+
continue
|
|
483
|
+
hk = f"latent_correlation:{a}|{b}|{targets[worst].metric}"
|
|
484
|
+
mv = float(meas_v)
|
|
485
|
+
aim = _aim(mv, float(targets[worst].value), band(worst))
|
|
486
|
+
|
|
487
|
+
def apply_corr(s: State, step: float, a: str = la, b: str = lb, m: float = mv,
|
|
488
|
+
tv: float = aim, hk: str = hk, sign: float = ga * gb,
|
|
489
|
+
cols: tuple[str, str] = (a, b),
|
|
490
|
+
direct: bool = (la, lb) == (a, b)) -> Adjustment | None:
|
|
491
|
+
return adjust_correlation(s, a, b, m, tv, history[hk], policy, step,
|
|
492
|
+
sign=sign, proportional=direct, columns=list(cols))
|
|
493
|
+
|
|
494
|
+
out.append(_Proposal(
|
|
495
|
+
key=f"latent_correlation:{a}|{b}", targets=ids, priority=prio(ids),
|
|
496
|
+
history_key=hk, measured=mv, apply=apply_corr))
|
|
497
|
+
out.sort(key=lambda p: (-p.priority, p.key))
|
|
498
|
+
return out
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
# ---------------------------------------------------------------------------------------------
|
|
502
|
+
# Result
|
|
503
|
+
# ---------------------------------------------------------------------------------------------
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
@dataclass
|
|
507
|
+
class IterationRecord:
|
|
508
|
+
iteration: int
|
|
509
|
+
objective: float # evaluation-stream objective after the iteration
|
|
510
|
+
n_failing: int
|
|
511
|
+
n_targets: int
|
|
512
|
+
accepted: list[str] = field(default_factory=list)
|
|
513
|
+
trials: int = 0
|
|
514
|
+
elapsed_s: float = 0.0
|
|
515
|
+
acceptance_rate: float | None = None # rejection acceptance on the evaluation sample
|
|
516
|
+
|
|
517
|
+
def to_dict(self) -> dict[str, Any]:
|
|
518
|
+
return {"iteration": self.iteration, "objective": _finite(self.objective),
|
|
519
|
+
"n_failing": self.n_failing, "n_targets": self.n_targets,
|
|
520
|
+
"accepted": list(self.accepted), "trials": self.trials,
|
|
521
|
+
"acceptance_rate": self.acceptance_rate,
|
|
522
|
+
"elapsed_s": round(self.elapsed_s, 3)}
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
@dataclass
|
|
526
|
+
class CalibrationResult:
|
|
527
|
+
fingerprint: Fingerprint
|
|
528
|
+
parent_hash: str
|
|
529
|
+
history: list[IterationRecord]
|
|
530
|
+
adjustments: list[Adjustment]
|
|
531
|
+
failing_before: list[TargetEval]
|
|
532
|
+
failing_after: list[TargetEval]
|
|
533
|
+
n_targets: int
|
|
534
|
+
converged: bool
|
|
535
|
+
stopped_reason: str
|
|
536
|
+
config: dict[str, Any]
|
|
537
|
+
runtime_s: float
|
|
538
|
+
n_generations: int
|
|
539
|
+
diagnostics: list[dict[str, Any]] = field(default_factory=list)
|
|
540
|
+
|
|
541
|
+
@property
|
|
542
|
+
def objective_before(self) -> float:
|
|
543
|
+
return self.history[0].objective if self.history else math.nan
|
|
544
|
+
|
|
545
|
+
@property
|
|
546
|
+
def objective_after(self) -> float:
|
|
547
|
+
return self.history[-1].objective if self.history else math.nan
|
|
548
|
+
|
|
549
|
+
def to_dict(self) -> dict[str, Any]:
|
|
550
|
+
return {
|
|
551
|
+
"parent_hash": self.parent_hash,
|
|
552
|
+
"content_hash": self.fingerprint.content_hash(),
|
|
553
|
+
"converged": self.converged,
|
|
554
|
+
"stopped_reason": self.stopped_reason,
|
|
555
|
+
"n_calibration_targets": self.n_targets,
|
|
556
|
+
"objective_before": _finite(self.objective_before),
|
|
557
|
+
"objective_after": _finite(self.objective_after),
|
|
558
|
+
"history": [h.to_dict() for h in self.history],
|
|
559
|
+
"adjustments": [a.to_dict() for a in self.adjustments],
|
|
560
|
+
"failing_before": [t.to_dict() for t in self.failing_before],
|
|
561
|
+
"failing_after": [t.to_dict() for t in self.failing_after],
|
|
562
|
+
"config": dict(self.config),
|
|
563
|
+
"runtime_s": round(self.runtime_s, 3),
|
|
564
|
+
"n_generations": self.n_generations,
|
|
565
|
+
"diagnostics": [dict(d) for d in self.diagnostics],
|
|
566
|
+
"notes": ["Calibration targets only: sealed fidelity is measured by the validator "
|
|
567
|
+
"(see ValidationReport.fidelity_gap)."],
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
def convergence_rows(self) -> list[dict[str, Any]]:
|
|
571
|
+
n = max(self.n_targets, 1)
|
|
572
|
+
return [{"iteration": h.iteration, "objective": h.objective,
|
|
573
|
+
"normalized_error": h.objective / n, "n_failing": h.n_failing,
|
|
574
|
+
"acceptance_rate": h.acceptance_rate,
|
|
575
|
+
"accepted": ", ".join(h.accepted) or "-"} for h in self.history]
|
|
576
|
+
|
|
577
|
+
def convergence_table(self) -> str:
|
|
578
|
+
"""Markdown table in the shape of design §6.4 (iteration 0 is the uncalibrated model).
|
|
579
|
+
``normalized error`` is the objective divided by the number of calibration targets."""
|
|
580
|
+
lines = ["| Iteration | Objective | Normalized error | Failing targets | "
|
|
581
|
+
"Rejection acceptance | Accepted |",
|
|
582
|
+
"| ---: | ---: | ---: | ---: | ---: | --- |"]
|
|
583
|
+
for r in self.convergence_rows():
|
|
584
|
+
obj = r["objective"]
|
|
585
|
+
o = f"{obj:.4f}" if math.isfinite(obj) else "inf"
|
|
586
|
+
ne = f"{100 * r['normalized_error']:.1f}%" if math.isfinite(obj) else "inf"
|
|
587
|
+
acc = r["acceptance_rate"]
|
|
588
|
+
a = f"{100 * acc:.1f}%" if acc is not None else "-"
|
|
589
|
+
lines.append(f"| {r['iteration']} | {o} | {ne} | {r['n_failing']} | {a} | "
|
|
590
|
+
f"{r['accepted']} |")
|
|
591
|
+
return "\n".join(lines)
|
|
592
|
+
|
|
593
|
+
def summary(self) -> str:
|
|
594
|
+
status = "converged" if self.converged else f"not converged ({self.stopped_reason})"
|
|
595
|
+
out = [f"Calibration: {status} after {len(self.history) - 1} iteration(s), "
|
|
596
|
+
f"{len(self.adjustments)} adjustment(s), {self.runtime_s:.1f} s, "
|
|
597
|
+
f"{self.n_generations} generations",
|
|
598
|
+
f"Calibration-target failures: {len(self.failing_before)} -> "
|
|
599
|
+
f"{len(self.failing_after)} of {self.n_targets}; objective "
|
|
600
|
+
f"{self.objective_before:.4f} -> {self.objective_after:.4f}",
|
|
601
|
+
f"Parent {self.parent_hash[:12]} -> {self.fingerprint.content_hash()[:12]}",
|
|
602
|
+
"", self.convergence_table()]
|
|
603
|
+
if self.adjustments:
|
|
604
|
+
out += ["", "Adjustments:"]
|
|
605
|
+
for a in self.adjustments:
|
|
606
|
+
out.append(f" it{a.iteration} {a.parameter}: {a.before} -> {a.after} "
|
|
607
|
+
f"[{a.method}, step {a.step}] for {', '.join(a.targets)}")
|
|
608
|
+
if self.failing_after:
|
|
609
|
+
out += ["", "Still failing (calibration targets):"]
|
|
610
|
+
for t in self.failing_after:
|
|
611
|
+
r = f"{t.ratio:.2f}" if math.isfinite(t.ratio) else "inf"
|
|
612
|
+
out.append(f" {t.id}: distance/tolerance = {r}")
|
|
613
|
+
if self.diagnostics:
|
|
614
|
+
out += ["", "Diagnostics:"]
|
|
615
|
+
for d in self.diagnostics:
|
|
616
|
+
out.append(f" {d['kind']}: {d['target']}: {d['detail']}")
|
|
617
|
+
return "\n".join(out)
|
|
618
|
+
|
|
619
|
+
def __str__(self) -> str:
|
|
620
|
+
return self.summary()
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
# ---------------------------------------------------------------------------------------------
|
|
624
|
+
# Entry point
|
|
625
|
+
# ---------------------------------------------------------------------------------------------
|
|
626
|
+
|
|
627
|
+
|
|
628
|
+
def _seed(seed: int, name: str) -> int:
|
|
629
|
+
return int(stream(seed, name).integers(0, 2**31 - 1))
|
|
630
|
+
|
|
631
|
+
|
|
632
|
+
def calibrate(fp: Fingerprint, *, budget_iterations: int = 10, n_samples: int | None = None,
|
|
633
|
+
seed: int = 0, tolerance_scale: float = 1.0,
|
|
634
|
+
time_budget_s: float = 120.0) -> CalibrationResult:
|
|
635
|
+
"""Correct post-processing drift on calibration targets; see the module docstring.
|
|
636
|
+
|
|
637
|
+
Returns a :class:`CalibrationResult` whose ``fingerprint`` is a new fingerprint (the input
|
|
638
|
+
is not modified) carrying the adjusted specs and a ``provenance.lineage`` entry
|
|
639
|
+
``{"op": "calibrate", "parent": <content hash>, "adjustments": [...]}``.
|
|
640
|
+
"""
|
|
641
|
+
if budget_iterations < 0:
|
|
642
|
+
raise ValueError("budget_iterations must be >= 0")
|
|
643
|
+
if not tolerance_scale > 0:
|
|
644
|
+
raise ValueError("tolerance_scale must be > 0")
|
|
645
|
+
t0 = time.perf_counter()
|
|
646
|
+
view = fp.calibration_view()
|
|
647
|
+
parent_hash = fp.content_hash()
|
|
648
|
+
if n_samples is None:
|
|
649
|
+
n_samples = int(min(max(view.manifest.dataset.source_records, 2000), 10_000))
|
|
650
|
+
n_samples = int(n_samples)
|
|
651
|
+
if n_samples < 1:
|
|
652
|
+
raise ValueError("n_samples must be >= 1")
|
|
653
|
+
cal_seed, eval_seed = _seed(seed, "calibration"), _seed(seed, "evaluation")
|
|
654
|
+
targets = {t.id: t for t in view.calibration.targets}
|
|
655
|
+
evaluator = _Evaluator(view, n_samples, float(tolerance_scale))
|
|
656
|
+
policy = evaluator.policy
|
|
657
|
+
|
|
658
|
+
current = State(view.manifest.model_copy(deep=True), ArrayStore(view.arrays.as_dict()))
|
|
659
|
+
ev = evaluator(current, eval_seed)
|
|
660
|
+
if ev.error is not None:
|
|
661
|
+
raise GenerationError(f"calibration could not generate from the fingerprint: {ev.error}")
|
|
662
|
+
n_t = len(ev.targets)
|
|
663
|
+
failing_before = ev.failing
|
|
664
|
+
history = [IterationRecord(0, ev.objective, len(ev.failing), n_t,
|
|
665
|
+
elapsed_s=time.perf_counter() - t0,
|
|
666
|
+
acceptance_rate=ev.acceptance_rate)]
|
|
667
|
+
adjustments: list[Adjustment] = []
|
|
668
|
+
secant: dict[str, list[tuple[float, float]]] = defaultdict(list)
|
|
669
|
+
reason = "iteration_budget"
|
|
670
|
+
acc0 = ev.acceptance_rate
|
|
671
|
+
# target id -> why an adjustment for it was limited (acceptance loss or a cumulative cap)
|
|
672
|
+
limited: dict[str, str] = {}
|
|
673
|
+
# target id -> why a target on a column computed by a structural transform has no
|
|
674
|
+
# well-defined adjustment (it is skipped, never an error)
|
|
675
|
+
skipped: dict[str, str] = {}
|
|
676
|
+
|
|
677
|
+
for it in range(1, budget_iterations + 1):
|
|
678
|
+
if ev.objective <= 0.0:
|
|
679
|
+
reason = "converged"
|
|
680
|
+
break
|
|
681
|
+
if time.perf_counter() - t0 > time_budget_s:
|
|
682
|
+
reason = "time_budget"
|
|
683
|
+
break
|
|
684
|
+
cal = evaluator(current, cal_seed)
|
|
685
|
+
props = _proposals(current, cal, ev, targets, secant, policy, float(tolerance_scale),
|
|
686
|
+
skipped)
|
|
687
|
+
if not props:
|
|
688
|
+
reason = "no_adjustable_parameters"
|
|
689
|
+
break
|
|
690
|
+
trials: list[tuple[list[_Proposal], float]] = []
|
|
691
|
+
if len(props) > 1:
|
|
692
|
+
trials.append((props, 1.0))
|
|
693
|
+
trials += [([p], 1.0) for p in props] + [([p], 0.5) for p in props]
|
|
694
|
+
trials = trials[:MAX_TRIALS_PER_ITERATION]
|
|
695
|
+
accepted: list[Adjustment] = []
|
|
696
|
+
n_trials = 0
|
|
697
|
+
out_of_time = False
|
|
698
|
+
for group, step in trials:
|
|
699
|
+
if time.perf_counter() - t0 > time_budget_s:
|
|
700
|
+
out_of_time = True
|
|
701
|
+
break
|
|
702
|
+
cand = current.clone()
|
|
703
|
+
made: list[tuple[_Proposal, Adjustment]] = []
|
|
704
|
+
for p in group:
|
|
705
|
+
adj = p.apply(cand, step)
|
|
706
|
+
if adj is not None:
|
|
707
|
+
made.append((p, adj))
|
|
708
|
+
if not made:
|
|
709
|
+
continue
|
|
710
|
+
n_trials += 1
|
|
711
|
+
for p, adj in made:
|
|
712
|
+
if adj.drift.get("capped"):
|
|
713
|
+
for tid in p.targets:
|
|
714
|
+
limited.setdefault(tid, "the marginal adjustment reached its cumulative "
|
|
715
|
+
"cap (scale in [0.5, 2], shift within +-1 std)")
|
|
716
|
+
cev = evaluator(cand, eval_seed)
|
|
717
|
+
if (acc0 is not None and cev.acceptance_rate is not None
|
|
718
|
+
and cev.acceptance_rate < acc0 - MAX_ACCEPTANCE_LOSS):
|
|
719
|
+
for p in group:
|
|
720
|
+
for tid in p.targets:
|
|
721
|
+
limited[tid] = (f"the adjustment would lower the rejection acceptance "
|
|
722
|
+
f"rate from {acc0:.1%} to {cev.acceptance_rate:.1%} "
|
|
723
|
+
f"(more than {100 * MAX_ACCEPTANCE_LOSS:.0f} percentage points)")
|
|
724
|
+
continue
|
|
725
|
+
if cev.objective < ev.objective - 1e-12:
|
|
726
|
+
for p, adj in made:
|
|
727
|
+
adj.targets = list(p.targets)
|
|
728
|
+
adj.iteration = it
|
|
729
|
+
adj.objective_before = ev.objective
|
|
730
|
+
adj.objective_after = cev.objective
|
|
731
|
+
if p.history_key:
|
|
732
|
+
before = next(iter(adj.before.values()))
|
|
733
|
+
secant[p.history_key].append((float(before), p.measured))
|
|
734
|
+
accepted.append(adj)
|
|
735
|
+
current, ev = cand, cev
|
|
736
|
+
break
|
|
737
|
+
adjustments += accepted
|
|
738
|
+
history.append(IterationRecord(it, ev.objective, len(ev.failing), n_t,
|
|
739
|
+
[a.key() for a in accepted], n_trials,
|
|
740
|
+
time.perf_counter() - t0, ev.acceptance_rate))
|
|
741
|
+
if not accepted:
|
|
742
|
+
reason = "time_budget" if out_of_time else "stalled"
|
|
743
|
+
break
|
|
744
|
+
else:
|
|
745
|
+
if ev.objective <= 0.0:
|
|
746
|
+
reason = "converged"
|
|
747
|
+
if ev.objective <= 0.0:
|
|
748
|
+
reason = "converged"
|
|
749
|
+
|
|
750
|
+
config = {"budget_iterations": int(budget_iterations), "n_samples": n_samples,
|
|
751
|
+
"seed": int(seed), "calibration_seed": cal_seed, "evaluation_seed": eval_seed,
|
|
752
|
+
"tolerance_scale": float(tolerance_scale), "time_budget_s": float(time_budget_s)}
|
|
753
|
+
new = fp.copy()
|
|
754
|
+
new.manifest = current.manifest
|
|
755
|
+
new.arrays = current.arrays
|
|
756
|
+
new.manifest.provenance.lineage.append({
|
|
757
|
+
"op": "calibrate",
|
|
758
|
+
"parent": parent_hash,
|
|
759
|
+
"adjustments": [a.to_dict() for a in adjustments],
|
|
760
|
+
"converged": reason == "converged",
|
|
761
|
+
"stopped_reason": reason,
|
|
762
|
+
"objective": [_finite(h.objective) for h in history],
|
|
763
|
+
"failing_calibration_targets": [t.id for t in ev.failing],
|
|
764
|
+
"config": config,
|
|
765
|
+
})
|
|
766
|
+
diagnostics = [{"kind": "target unreachable under constraint", "target": t.id,
|
|
767
|
+
"detail": limited[t.id]} for t in ev.failing if t.id in limited]
|
|
768
|
+
diagnostics += [{"kind": "transform target not adjustable", "target": t.id,
|
|
769
|
+
"detail": skipped[t.id]} for t in ev.failing
|
|
770
|
+
if t.id in skipped and t.id not in limited]
|
|
771
|
+
if diagnostics:
|
|
772
|
+
new.manifest.provenance.lineage[-1]["diagnostics"] = [dict(d) for d in diagnostics]
|
|
773
|
+
return CalibrationResult(
|
|
774
|
+
fingerprint=new, parent_hash=parent_hash, history=history, adjustments=adjustments,
|
|
775
|
+
failing_before=failing_before, failing_after=ev.failing, n_targets=n_t,
|
|
776
|
+
converged=reason == "converged", stopped_reason=reason, config=config,
|
|
777
|
+
runtime_s=time.perf_counter() - t0, n_generations=evaluator.n_generations,
|
|
778
|
+
diagnostics=diagnostics)
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
__all__ = ["CalibrationResult", "IterationRecord", "TargetEval", "calibrate"]
|