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.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,539 @@
1
+ """Low-dimensional, analytic calibration adjustments (design §6.2, M25).
2
+
3
+ Every adjustment acts on a *copy* of a model section and returns an :class:`Adjustment` record
4
+ that says which parameter moved, from what to what, and which calibration targets it addressed.
5
+ Four kinds exist:
6
+
7
+ * ``latent_correlation`` -- one off-diagonal entry of a ``gaussian_copula`` correlation matrix,
8
+ updated by a secant step (multiplicative when no secant history exists) toward the target
9
+ correlation, then re-projected to the nearest positive-definite correlation matrix.
10
+ * ``missing_rate`` -- the ``rate`` of a ``bernoulli_indicator`` missingness spec (i.e. the
11
+ indicator's latent threshold ``Phi^-1(1 - rate)``), secant or multiplicative step.
12
+ * ``marginal_affine`` -- an affine pre-distortion of a continuous marginal's quantile function,
13
+ stored as the wrapper marginal kind ``"calibrated"`` (:class:`CalibratedMarginal`). It offsets
14
+ the location/scale drift that constraint rejection causes by thinning one tail.
15
+ * ``delta_affine`` -- the same pre-distortion applied to the hidden latent of a ``difference``
16
+ transform (format 0.3, ADR-0005). A column computed as ``base + sign * delta`` has no
17
+ marginal of its own, so a drift of *its* mean and standard deviation is corrected through
18
+ the location and scale of ``delta`` (:func:`adjust_delta_affine`), keeping ``delta >= 0``.
19
+
20
+ A target on a computed column is mapped to the model column that stands for it
21
+ (:func:`latent_slot`): its ``delta`` for a ``difference`` target, also for its missing rate and
22
+ its correlations; an ``identity`` target (``a op b``) has none and cannot be adjusted.
23
+
24
+ The ``"calibrated"`` marginal
25
+ -----------------------------
26
+ ``x' = center + scale * (x - center) + shift`` where ``x`` is the inner marginal's value. The
27
+ spec is::
28
+
29
+ ModelSpec(kind="calibrated",
30
+ params={"inner_kind": ..., "inner_params": {...},
31
+ "center": c, "scale": a, "shift": b},
32
+ arrays={"inner.<name>": "arrays/..."})
33
+
34
+ Inner arrays are hoisted into the outer ``arrays`` map (prefixed ``inner.``) so the container's
35
+ and the compiler's reference checks see them. The inner model is rebuilt through the
36
+ ``MARGINALS`` registry, so any registered marginal can be wrapped; ``ppf``/``cdf``/``cdf_left``
37
+ are transformed exactly, so the mixed-type encoder works with it unchanged. Re-calibrating an
38
+ already calibrated marginal updates the affine parameters rather than nesting wrappers.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import math
44
+ from dataclasses import dataclass, field
45
+ from typing import Any
46
+
47
+ import numpy as np
48
+
49
+ from ectype.fingerprint.core import ArrayStore
50
+ from ectype.fingerprint.disclosure import coarsen, coarsen_array
51
+ from ectype.fingerprint.schema import (
52
+ ColumnSchema,
53
+ DisclosurePolicySpec,
54
+ Manifest,
55
+ ModelSpec,
56
+ TransformSpec,
57
+ )
58
+ from ectype.models import marginals as _register_marginals # noqa: F401
59
+ from ectype.models.base import MARGINALS, MarginalModel, marginal_from_spec
60
+ from ectype.models.copulas import MIN_EIGENVALUE, nearest_correlation
61
+
62
+ KIND_CALIBRATED = "calibrated"
63
+ _INNER = "inner."
64
+ #: smallest quantile level the encoder decodes (``models.encoding.EPS``): the lower end of
65
+ #: what a latent can generate, used to keep the delta of a difference transform non-negative
66
+ _SUPPORT_LEVEL = 1e-9
67
+
68
+ #: Bounds on a single step, so one noisy measurement cannot throw a parameter far away.
69
+ MAX_SCALE_STEP = 2.0
70
+ MAX_RATE_STEP = 4.0
71
+ MAX_CORR_STEP = 0.25
72
+ #: Bounds on the *cumulative* affine pre-distortion of a marginal: scale in
73
+ #: [1 / MAX_AFFINE_SCALE, MAX_AFFINE_SCALE], shift within +-MAX_AFFINE_SHIFT_STD target std.
74
+ #: Beyond them the drift is not "post-processing distortion" any more (typically a truncating
75
+ #: constraint), and widening the marginal only feeds more rows to rejection.
76
+ MAX_AFFINE_SCALE = 2.0
77
+ MAX_AFFINE_SHIFT_STD = 1.0
78
+ CORR_LIMIT = 0.995
79
+ RATE_LIMIT = 1e-6
80
+
81
+
82
+ # ---------------------------------------------------------------------------------------------
83
+ # The "calibrated" wrapper marginal
84
+ # ---------------------------------------------------------------------------------------------
85
+
86
+
87
+ @MARGINALS.register()
88
+ class CalibratedMarginal(MarginalModel):
89
+ """Affine pre-distortion of an inner marginal's quantile function (see module doc)."""
90
+
91
+ kind = KIND_CALIBRATED
92
+
93
+ def __init__(self, inner: MarginalModel, center: float = 0.0, scale: float = 1.0,
94
+ shift: float = 0.0) -> None:
95
+ if not (math.isfinite(scale) and scale > 0):
96
+ raise ValueError(f"calibrated marginal scale must be positive, got {scale!r}")
97
+ if not (math.isfinite(center) and math.isfinite(shift)):
98
+ raise ValueError("calibrated marginal center/shift must be finite")
99
+ self.inner = inner
100
+ self.center = float(center)
101
+ self.scale = float(scale)
102
+ self.shift = float(shift)
103
+ self.discrete = bool(getattr(inner, "discrete", False)) # type: ignore[misc]
104
+
105
+ # -- transform -----------------------------------------------------------------------
106
+ def _forward(self, x: np.ndarray) -> np.ndarray:
107
+ return self.center + self.scale * (np.asarray(x, dtype=float) - self.center) + self.shift
108
+
109
+ def _inverse(self, y: np.ndarray) -> np.ndarray:
110
+ return (np.asarray(y, dtype=float) - self.center - self.shift) / self.scale + self.center
111
+
112
+ # -- MarginalModel -------------------------------------------------------------------
113
+ @classmethod
114
+ def fit(cls, x: np.ndarray, *, column: ColumnSchema, policy: DisclosurePolicySpec,
115
+ rng: np.random.Generator) -> CalibratedMarginal:
116
+ raise NotImplementedError("calibrated marginals are produced by calibrate(), not fit")
117
+
118
+ def cdf(self, x: np.ndarray) -> np.ndarray:
119
+ return np.asarray(self.inner.cdf(self._inverse(x)), dtype=float)
120
+
121
+ def cdf_left(self, x: np.ndarray) -> np.ndarray:
122
+ return np.asarray(self.inner.cdf_left(self._inverse(x)), dtype=float)
123
+
124
+ def ppf(self, u: np.ndarray) -> np.ndarray:
125
+ return self._forward(self.inner.ppf(u))
126
+
127
+ def logpdf(self, x: np.ndarray) -> np.ndarray | None:
128
+ lp = self.inner.logpdf(self._inverse(x))
129
+ if lp is None:
130
+ return None
131
+ return np.asarray(lp, dtype=float) - math.log(self.scale)
132
+
133
+ @property
134
+ def n_parameters(self) -> int:
135
+ return self.inner.n_parameters + 3
136
+
137
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
138
+ inner = self.inner.to_spec(store, prefix)
139
+ return wrap_spec(inner, center=self.center, scale=self.scale, shift=self.shift)
140
+
141
+ @classmethod
142
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> CalibratedMarginal:
143
+ p = spec.params
144
+ return cls(marginal_from_spec(inner_spec(spec), store),
145
+ center=float(p.get("center", 0.0)), # type: ignore[arg-type]
146
+ scale=float(p.get("scale", 1.0)), # type: ignore[arg-type]
147
+ shift=float(p.get("shift", 0.0))) # type: ignore[arg-type]
148
+
149
+ def __getattr__(self, name: str) -> Any:
150
+ # Only reached for attributes not set on the wrapper: expose the inner model's extras.
151
+ if name == "inner":
152
+ raise AttributeError(name)
153
+ return getattr(self.inner, name)
154
+
155
+
156
+ def wrap_spec(inner: ModelSpec, *, center: float, scale: float = 1.0,
157
+ shift: float = 0.0) -> ModelSpec:
158
+ """Wrap ``inner`` in a ``"calibrated"`` spec (inner arrays hoisted with ``inner.``)."""
159
+ if inner.kind == KIND_CALIBRATED:
160
+ raise ValueError("refusing to nest calibrated marginals; update the existing wrapper")
161
+ return ModelSpec(kind=KIND_CALIBRATED,
162
+ params={"inner_kind": inner.kind,
163
+ "inner_params": dict(inner.params),
164
+ "center": float(center), "scale": float(scale),
165
+ "shift": float(shift)},
166
+ arrays={f"{_INNER}{k}": v for k, v in inner.arrays.items()})
167
+
168
+
169
+ def inner_spec(spec: ModelSpec) -> ModelSpec:
170
+ """The wrapped model's spec of a ``"calibrated"`` spec."""
171
+ if spec.kind != KIND_CALIBRATED:
172
+ raise ValueError(f"not a calibrated marginal spec: {spec.kind!r}")
173
+ p = spec.params
174
+ return ModelSpec(kind=str(p["inner_kind"]),
175
+ params=dict(p.get("inner_params") or {}), # type: ignore[arg-type]
176
+ arrays={k[len(_INNER):]: v for k, v in spec.arrays.items()
177
+ if k.startswith(_INNER)})
178
+
179
+
180
+ # ---------------------------------------------------------------------------------------------
181
+ # Adjustment records
182
+ # ---------------------------------------------------------------------------------------------
183
+
184
+
185
+ @dataclass
186
+ class Adjustment:
187
+ """One accepted (or proposed) parameter change."""
188
+
189
+ kind: str # latent_correlation | missing_rate | marginal_affine
190
+ parameter: str # manifest path, e.g. "model.missingness.y.rate"
191
+ columns: list[str]
192
+ before: dict[str, Any]
193
+ after: dict[str, Any]
194
+ targets: list[str] # calibration target ids this adjustment addresses
195
+ drift: dict[str, Any] = field(default_factory=dict) # measured vs target before the step
196
+ method: str = ""
197
+ step: float = 1.0 # damping factor actually used
198
+ iteration: int = 0
199
+ objective_before: float | None = None
200
+ objective_after: float | None = None
201
+
202
+ def key(self) -> str:
203
+ return f"{self.kind}:{'|'.join(self.columns)}"
204
+
205
+ def to_dict(self) -> dict[str, Any]:
206
+ return {"iteration": self.iteration, "kind": self.kind, "parameter": self.parameter,
207
+ "columns": list(self.columns), "before": _json(self.before),
208
+ "after": _json(self.after), "targets": list(self.targets),
209
+ "drift": _json(self.drift), "method": self.method, "step": self.step,
210
+ "objective_before": self.objective_before,
211
+ "objective_after": self.objective_after}
212
+
213
+
214
+ def _json(d: dict[str, Any]) -> dict[str, Any]:
215
+ out: dict[str, Any] = {}
216
+ for k, v in d.items():
217
+ if isinstance(v, (np.floating, np.integer)):
218
+ v = v.item()
219
+ out[k] = v
220
+ return out
221
+
222
+
223
+ @dataclass
224
+ class State:
225
+ """A candidate model: a manifest plus its array store (both owned, never shared)."""
226
+
227
+ manifest: Manifest
228
+ arrays: ArrayStore
229
+
230
+ def clone(self) -> State:
231
+ return State(self.manifest.model_copy(deep=True), ArrayStore(self.arrays.as_dict()))
232
+
233
+
234
+ # ---------------------------------------------------------------------------------------------
235
+ # Update rules
236
+ # ---------------------------------------------------------------------------------------------
237
+
238
+
239
+ def secant_step(history: list[tuple[float, float]], current: float, measured: float,
240
+ target: float, *, fallback: float) -> tuple[float, str]:
241
+ """Next parameter value aiming ``measured -> target``.
242
+
243
+ Uses the last two distinct ``(param, measured)`` points when their slope is positive (all
244
+ adjustable parameters here increase the statistic they drive); otherwise ``fallback``.
245
+ """
246
+ pts = [(p, m) for p, m in history if math.isfinite(p) and math.isfinite(m)]
247
+ pts.append((current, measured))
248
+ if len(pts) >= 2:
249
+ (p0, m0), (p1, m1) = pts[-2], pts[-1]
250
+ if abs(p1 - p0) > 1e-9:
251
+ slope = (m1 - m0) / (p1 - p0)
252
+ if math.isfinite(slope) and slope > 1e-6:
253
+ return p1 + (target - m1) / slope, "secant"
254
+ return fallback, "multiplicative"
255
+
256
+
257
+ def _damp(old: float, new: float, step: float) -> float:
258
+ return old + step * (new - old)
259
+
260
+
261
+ def adjust_correlation(state: State, a: str, b: str, measured: float, target: float,
262
+ history: list[tuple[float, float]], policy: DisclosurePolicySpec,
263
+ step: float = 1.0, *, sign: float = 1.0, proportional: bool = True,
264
+ columns: list[str] | None = None) -> Adjustment | None:
265
+ """Move the latent correlation of ``(a, b)`` so the measured correlation hits ``target``.
266
+
267
+ For a pair that involves a column computed by a ``difference`` transform, ``a`` / ``b``
268
+ are the model columns that stand for the measured ones (:func:`latent_slot`), ``sign``
269
+ the product of their directions (the measured correlation then grows with
270
+ ``sign * latent``) and ``columns`` the measured columns, for the record. The measured
271
+ correlation of a computed column also carries what it inherits from its base, so it is
272
+ not proportional to the latent one: pass ``proportional=False`` to start from an additive
273
+ step instead of the multiplicative one.
274
+ """
275
+ joint = state.manifest.model.joint
276
+ if joint is None or joint.kind != "gaussian_copula" or "correlation" not in joint.arrays:
277
+ return None
278
+ cols = [str(c) for c in joint.params.get("columns", [])] # type: ignore[union-attr]
279
+ if a not in cols or b not in cols:
280
+ return None
281
+ i, j = cols.index(a), cols.index(b)
282
+ ref = joint.arrays["correlation"]
283
+ r = np.array(state.arrays.get(ref), dtype=np.float64)
284
+ raw = float(r[i, j])
285
+ old = sign * raw
286
+ if proportional and abs(measured) > 0.05 and measured * target > 0:
287
+ fb = old * float(np.clip(target / measured, 1 / MAX_SCALE_STEP, MAX_SCALE_STEP))
288
+ else:
289
+ fb = old + (target - measured)
290
+ points = history if sign == 1.0 else [(sign * p, m) for p, m in history]
291
+ new, method = secant_step(points, old, measured, target, fallback=fb)
292
+ if not proportional and method == "multiplicative":
293
+ method = "additive"
294
+ new = float(np.clip(new, old - MAX_CORR_STEP, old + MAX_CORR_STEP))
295
+ new = float(np.clip(_damp(old, new, step), -CORR_LIMIT, CORR_LIMIT))
296
+ if abs(new - old) < 1e-6:
297
+ return None
298
+ r[i, j] = r[j, i] = sign * new
299
+ r = nearest_correlation(r)
300
+ r = coarsen_array(r, policy)
301
+ np.fill_diagonal(r, 1.0)
302
+ r = 0.5 * (r + r.T)
303
+ if np.min(np.linalg.eigvalsh(r)) < MIN_EIGENVALUE * 0.5:
304
+ r = nearest_correlation(r)
305
+ arrays = state.arrays.as_dict()
306
+ arrays[ref] = r # same ref, so the joint spec stays valid
307
+ state.arrays = ArrayStore(arrays)
308
+ return Adjustment(kind="latent_correlation", parameter=f"model.joint.correlation[{a},{b}]",
309
+ columns=list(columns or [a, b]), before={"latent": raw},
310
+ after={"latent": float(r[i, j])},
311
+ targets=[], drift={"measured": measured, "target": target},
312
+ method=f"{method}+nearest_pd", step=step)
313
+
314
+
315
+ def adjust_missing_rate(state: State, column: str, measured: float, target: float,
316
+ history: list[tuple[float, float]], policy: DisclosurePolicySpec,
317
+ step: float = 1.0) -> Adjustment | None:
318
+ """Move the indicator rate (latent threshold) of ``column``'s missingness spec."""
319
+ spec = _missing_spec(state.manifest, column)
320
+ if spec is None or "rate" not in spec.params:
321
+ return None
322
+ old = float(spec.params["rate"]) # type: ignore[arg-type]
323
+ if measured > 1e-9:
324
+ fb = old * float(np.clip(target / measured, 1 / MAX_RATE_STEP, MAX_RATE_STEP))
325
+ else:
326
+ fb = old + (target - measured)
327
+ new, method = secant_step(history, old, measured, target, fallback=fb)
328
+ new = float(np.clip(new, old / MAX_RATE_STEP, min(1.0, old * MAX_RATE_STEP)))
329
+ new = _damp(old, new, step)
330
+ new = float(np.clip(coarsen(new, policy), RATE_LIMIT, 1.0 - RATE_LIMIT))
331
+ if abs(new - old) < 1e-9:
332
+ return None
333
+ spec.params["rate"] = new
334
+ return Adjustment(kind="missing_rate", parameter=f"model.missingness.{column}.rate",
335
+ columns=[column], before={"rate": old}, after={"rate": new}, targets=[],
336
+ drift={"measured": measured, "target": target}, method=method, step=step)
337
+
338
+
339
+ def _missing_spec(manifest: Manifest, column: str) -> ModelSpec | None:
340
+ for key, spec in manifest.model.missingness.items():
341
+ if str(spec.params.get("column", key)) == column or key == column:
342
+ return spec
343
+ return None
344
+
345
+
346
+ def adjust_marginal_affine(state: State, column: str, measured: dict[str, float],
347
+ target: dict[str, float], policy: DisclosurePolicySpec,
348
+ step: float = 1.0) -> Adjustment | None:
349
+ """Affine pre-distortion of ``column``'s marginal so the post-processing mean/std land on
350
+ the target. First-order model: the post-processing distortion is invariant to the step."""
351
+ spec = state.manifest.model.marginals.get(column)
352
+ if spec is None:
353
+ return None
354
+ m, s = float(measured["mean"]), float(measured["std"])
355
+ tm, ts = float(target["mean"]), float(target["std"])
356
+ if not all(math.isfinite(v) for v in (m, s, tm, ts)) or s <= 0 or ts <= 0:
357
+ return None
358
+ if spec.kind == KIND_CALIBRATED:
359
+ c = float(spec.params.get("center", tm)) # type: ignore[arg-type]
360
+ a = float(spec.params.get("scale", 1.0)) # type: ignore[arg-type]
361
+ b = float(spec.params.get("shift", 0.0)) # type: ignore[arg-type]
362
+ base = inner_spec(spec)
363
+ else:
364
+ c, a, b, base = coarsen(tm, policy), 1.0, 0.0, spec
365
+ a_new = a * float(np.clip(ts / s, 1 / MAX_SCALE_STEP, MAX_SCALE_STEP))
366
+ # Effective inner mean after post-processing: m = c + a (mu - c) + b.
367
+ mu_minus_c = (m - c - b) / a
368
+ b_new = tm - c - a_new * mu_minus_c
369
+ a_new = _damp(a, a_new, step)
370
+ b_new = _damp(b, b_new, step)
371
+ a_cap = float(np.clip(a_new, 1.0 / MAX_AFFINE_SCALE, MAX_AFFINE_SCALE))
372
+ b_lim = MAX_AFFINE_SHIFT_STD * ts
373
+ b_cap = float(np.clip(b_new, -b_lim, b_lim))
374
+ capped = a_cap != a_new or b_cap != b_new
375
+ a_new = coarsen(a_cap, policy)
376
+ b_new = coarsen(b_cap, policy)
377
+ if a_new <= 0 or (abs(a_new - a) < 1e-9 and abs(b_new - b) < 1e-9 * max(1.0, abs(tm))):
378
+ return None
379
+ state.manifest.model.marginals[column] = wrap_spec(base, center=c, scale=a_new,
380
+ shift=b_new)
381
+ return Adjustment(kind="marginal_affine", parameter=f"model.marginals.{column}",
382
+ columns=[column], before={"center": c, "scale": a, "shift": b},
383
+ after={"center": c, "scale": a_new, "shift": b_new}, targets=[],
384
+ drift={"measured_mean": m, "measured_std": s, "target_mean": tm,
385
+ "target_std": ts, "capped": bool(capped)},
386
+ method="affine_ppf" + ("+capped" if capped else ""), step=step)
387
+
388
+
389
+ # ---------------------------------------------------------------------------------------------
390
+ # Columns computed by a structural transform (format 0.3, ADR-0005)
391
+ # ---------------------------------------------------------------------------------------------
392
+
393
+
394
+ def transform_of(manifest: Manifest, column: str) -> TransformSpec | None:
395
+ """The structural transform that computes ``column`` (``None`` for a modeled column)."""
396
+ return next((t for t in manifest.model.transforms if t.target == column), None)
397
+
398
+
399
+ def latent_slot(manifest: Manifest, column: str) -> tuple[str, float] | None:
400
+ """The column of the joint model that stands for ``column``, and the direction in which
401
+ ``column`` moves with it: ``(column, 1.0)`` for a modeled column, ``(latent, sign)`` for
402
+ the target of a ``difference`` transform (``target = base + sign * latent``), ``None`` for
403
+ a column that has no model of its own (the target of an ``identity`` transform)."""
404
+ t = transform_of(manifest, column)
405
+ if t is None:
406
+ return column, 1.0
407
+ if t.kind == "difference" and "latent" in t.params:
408
+ return str(t.params["latent"]), float(t.params.get("sign", 1)) # type: ignore[arg-type]
409
+ return None
410
+
411
+
412
+ def adjust_delta_affine(state: State, transform: TransformSpec, target: dict[str, float],
413
+ moments: dict[str, float], policy: DisclosurePolicySpec,
414
+ step: float = 1.0, why: list[str] | None = None) -> Adjustment | None:
415
+ """Affine pre-distortion of the hidden latent ``delta`` of a ``difference`` transform so
416
+ that the post-processing mean/std of its *target column* land on ``target``.
417
+
418
+ The column is ``base + sign * delta``. With the base left alone its mean and variance are
419
+ ``E[base] + sign E[delta']`` and ``V[base] + V[delta'] + 2 sign Cov(base, delta')``, so
420
+ ``delta' = alpha + beta * delta`` is solved from the two requirements, with the moments of
421
+ base and delta measured on the calibration sample (``moments``: ``mean_base``,
422
+ ``mean_delta``, ``var_base``, ``var_delta``, ``cov``). Same first-order model as
423
+ :func:`adjust_marginal_affine`: the post-processing distortion is invariant to the step.
424
+
425
+ ``delta >= 0`` has to survive: it is what makes the transform's ordering hold by
426
+ construction. When the solved map would push the lower end of the latent below zero, only
427
+ the mean is corrected, by rescaling delta (``delta' = beta * delta``), which cannot. When
428
+ even that is impossible (the target mean lies on the wrong side of the base's mean) nothing
429
+ is adjusted, and the reason is appended to ``why``.
430
+ """
431
+ def skip(reason: str) -> None:
432
+ if why is not None:
433
+ why.append(reason)
434
+
435
+ name = transform.target
436
+ latent = str(transform.params.get("latent"))
437
+ sign = float(transform.params.get("sign", 1)) # type: ignore[arg-type]
438
+ spec = state.manifest.model.marginals.get(latent)
439
+ if spec is None:
440
+ skip(f"the latent {latent!r} of {name!r} has no marginal")
441
+ return None
442
+ tm, ts = float(target["mean"]), float(target["std"])
443
+ try:
444
+ mb, md = float(moments["mean_base"]), float(moments["mean_delta"])
445
+ vb, vd, cv = (float(moments[k]) for k in ("var_base", "var_delta", "cov"))
446
+ except (KeyError, TypeError, ValueError):
447
+ skip(f"too few rows with both {name!r} and {transform.inputs[0]!r} present to "
448
+ f"measure how they vary together")
449
+ return None
450
+ if not all(math.isfinite(v) for v in (tm, ts, mb, md, vb, vd, cv)) or vd <= 0 or ts <= 0:
451
+ skip(f"the gap between {name!r} and {transform.inputs[0]!r} does not vary, so "
452
+ f"its location and scale are not identified")
453
+ return None
454
+ if spec.kind == KIND_CALIBRATED:
455
+ c = float(spec.params.get("center", 0.0)) # type: ignore[arg-type]
456
+ a = float(spec.params.get("scale", 1.0)) # type: ignore[arg-type]
457
+ b = float(spec.params.get("shift", 0.0)) # type: ignore[arg-type]
458
+ base = inner_spec(spec)
459
+ else:
460
+ c, a, b, base = 0.0, 1.0, 0.0, spec
461
+ inner = marginal_from_spec(base, state.arrays)
462
+ low = float(np.asarray(inner.ppf(np.array([_SUPPORT_LEVEL])), dtype=np.float64)[0])
463
+
464
+ def lower_end(scale: float, shift: float) -> float:
465
+ return c + scale * (low - c) + shift
466
+
467
+ floor = min(0.0, lower_end(a, b)) # never below what the model already allows
468
+ if transform.params.get("signed") is True:
469
+ floor = -math.inf # a signed gap guarantees no ordering
470
+ b_lim = MAX_AFFINE_SHIFT_STD * ts
471
+
472
+ def settle(alpha: float, beta: float) -> tuple[float, float, bool] | None:
473
+ """Compose ``delta' = alpha + beta * delta`` with the current wrapper, apply the
474
+ cumulative caps, and refuse a result whose lower end falls below the floor."""
475
+ a_new, b_new = beta * a, alpha + beta * (c + b) - c
476
+ a_cap = float(np.clip(a_new, 1.0 / MAX_AFFINE_SCALE, MAX_AFFINE_SCALE))
477
+ b_cap = float(np.clip(b_new, -b_lim, b_lim))
478
+ capped = a_cap != a_new or b_cap != b_new
479
+ a_new, b_new = coarsen(a_cap, policy), coarsen(b_cap, policy)
480
+ if a_new <= 0 or lower_end(a_new, b_new) < floor - 1e-9 * max(abs(low), abs(b_new), 1.0):
481
+ return None
482
+ return a_new, b_new, capped
483
+
484
+ # mean and standard deviation: beta from the variance, alpha from the mean
485
+ beta = 1.0
486
+ disc = cv * cv - vd * (vb - ts * ts)
487
+ if disc >= 0:
488
+ root = (-sign * cv + math.sqrt(disc)) / vd
489
+ if root > 0:
490
+ beta = float(np.clip(root, 1.0 / MAX_SCALE_STEP, MAX_SCALE_STEP))
491
+ alpha = sign * (tm - mb) - beta * md
492
+ method = "affine_ppf"
493
+ done = settle(step * alpha, 1.0 + step * (beta - 1.0))
494
+ if done is None:
495
+ # the mean alone, by rescaling the gap: delta stays non-negative whatever the factor
496
+ k = sign * (tm - mb) / md if md > 0 else -1.0
497
+ if not k > 0:
498
+ side = "below" if sign > 0 else "above"
499
+ skip(f"the target mean of {name!r} ({tm:g}) lies {side} the mean of its "
500
+ f"base {transform.inputs[0]!r} ({mb:g}); no non-negative gap gives it")
501
+ return None
502
+ k = float(np.clip(k, 1.0 / MAX_SCALE_STEP, MAX_SCALE_STEP))
503
+ method = "scale_ppf"
504
+ done = settle(0.0, 1.0 + step * (k - 1.0))
505
+ if done is None:
506
+ skip(f"no change of the gap between {name!r} and "
507
+ f"{transform.inputs[0]!r} keeps it non-negative")
508
+ return None
509
+ a_new, b_new, capped = done
510
+ if abs(a_new - a) < 1e-9 and abs(b_new - b) < 1e-9 * max(1.0, abs(tm)):
511
+ return None
512
+ state.manifest.model.marginals[latent] = wrap_spec(base, center=c, scale=a_new,
513
+ shift=b_new)
514
+ return Adjustment(kind="delta_affine", parameter=f"model.marginals.{latent}",
515
+ columns=[name], before={"center": c, "scale": a, "shift": b},
516
+ after={"center": c, "scale": a_new, "shift": b_new}, targets=[],
517
+ drift={"measured_mean": mb + sign * md,
518
+ "measured_std": math.sqrt(max(vb + vd + 2.0 * sign * cv, 0.0)),
519
+ "target_mean": tm, "target_std": ts, "capped": bool(capped)},
520
+ method=method + ("+capped" if capped else ""), step=step)
521
+
522
+
523
+ __all__ = [
524
+ "KIND_CALIBRATED",
525
+ "MAX_AFFINE_SCALE",
526
+ "MAX_AFFINE_SHIFT_STD",
527
+ "Adjustment",
528
+ "CalibratedMarginal",
529
+ "State",
530
+ "adjust_correlation",
531
+ "adjust_delta_affine",
532
+ "adjust_marginal_affine",
533
+ "adjust_missing_rate",
534
+ "inner_spec",
535
+ "latent_slot",
536
+ "secant_step",
537
+ "transform_of",
538
+ "wrap_spec",
539
+ ]