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,1613 @@
1
+ """``mutate``: change selected statistical assumptions of a fingerprint (M26, design doc 4.5/7.3).
2
+
3
+ ``mutate(fp, **changes) -> ScenarioResult`` returns a *new* fingerprint plus diagnostics. The
4
+ parent is never modified. Supported changes (each a ``{column: value}`` mapping, or a scalar
5
+ together with ``column=...``):
6
+
7
+ ``shift={col: delta}``
8
+ Adds ``delta`` to every value (continuous, discrete or datetime; datetime deltas are in the
9
+ column's epoch unit, or a ``datetime.timedelta``). Implemented with the registered wrapper
10
+ marginal kind ``"affine"`` (``value = a + b * inner``), so the inner model is untouched and
11
+ the copula's rank dependence is preserved exactly.
12
+ ``scale={col: factor}``
13
+ Scales the *spread* about the current mean: ``x -> mu + factor * (x - mu)`` (mean kept).
14
+ ``mean_multiplier={col: m}``
15
+ Multiplies every value by ``m`` (``x -> m x``): the mean is multiplied by ``m`` and the shape
16
+ and coefficient of variation are preserved, so a positive column stays positive.
17
+ When several of these apply to one column they compose in the order mean_multiplier,
18
+ scale, shift.
19
+ ``correlation={(a, b): rho}``
20
+ Sets the *latent* (Gaussian copula) correlation of ``a`` and ``b``, re-projects the matrix
21
+ to the nearest positive-definite correlation and reports the achieved value. With
22
+ ``preserve_dependencies=True`` the requested entries are held fixed and the other entries
23
+ absorb the adjustment; otherwise the plain nearest correlation is used. Entries that cannot
24
+ be reached within 0.05 raise :class:`ScenarioError`; smaller compromises are listed in
25
+ ``ScenarioResult.infeasible``.
26
+ ``category_probs={col: {label: p}}``
27
+ Sets the probabilities of the named labels (which must exist) and rescales the others
28
+ proportionally so the total is 1. If the column is a child in the encoder's conditional
29
+ categorical tree, its conditional table is re-fitted to the new marginal by iterative
30
+ proportional fitting (the dependence on its parent is kept); if it is a parent, its
31
+ children's marginals shift accordingly (reported as expected collateral).
32
+ ``missing_rate={col: r}``
33
+ Sets the null rate (``0 <= r < 1``). A column without a missingness indicator gets one,
34
+ independent of everything else in the copula.
35
+ ``drift={col: {...}}``
36
+ Convenience for gradual drift. Keys: ``periods`` (default 1) and any of ``mean_rate``
37
+ (compounded relative mean change per period), ``shift_per_period``, ``scale_rate``
38
+ (compounded spread change per period) and ``missing_rate_per_period``. **In v1 the drift is
39
+ applied to the whole population**: the mutated fingerprint describes the population at the
40
+ end of the drift (there is no within-sample gradient, because the cross-sectional model has
41
+ no time axis).
42
+ ``seasonality_strength={col: factor}`` (or ``temporal=col, seasonality_strength=factor``)
43
+ Scales the Fourier coefficients of the temporal section's seasonal profiles. Only for
44
+ fingerprints with ``manifest.temporal`` in a section format whose seasonal coefficients are
45
+ stored as arrays (``regular_series`` and ``panel``); otherwise ``ScenarioError``.
46
+
47
+ ``preserve_dependencies=True`` (default) keeps the latent correlations unchanged (except the
48
+ requested ones); the Gaussian copula then preserves rank dependence automatically.
49
+ ``ScenarioResult.expected_to_move`` lists the measured calibration targets that are
50
+ nevertheless expected to move. It is a requested policy, not a guarantee (design doc 7.3).
51
+
52
+ Columns computed by a structural transform (format 0.3, ADR-0005)
53
+ -----------------------------------------------------------------
54
+ A ``difference`` target is generated as ``target = base + sign * delta`` with a hidden latent
55
+ ``delta >= 0`` (the *gap*) modeled in its place; an ``identity`` target is ``a op b``. A request
56
+ always describes the change of the column it names, relative to the parent, whether or not that
57
+ column is computed:
58
+
59
+ * **A column that is not requested moves with its inputs.** Shifting ``start`` shifts
60
+ ``end = start + delta`` by the same amount and leaves the gap alone. The computed columns
61
+ that move are named in ``notes``, listed in ``expected_to_move`` and, where a parent target
62
+ now fails, in ``collateral`` with ``"expected": True``.
63
+ * **A request on a difference target is met by changing its gap**, net of what the target
64
+ inherits from its base in the same request:
65
+
66
+ - ``shift`` adds the requested amount to every value of the target (``delta`` is shifted by
67
+ ``sign * (shift - shift of the base)``);
68
+ - ``mean_multiplier`` multiplies the gap so that the target's mean is multiplied as
69
+ requested (the gap keeps its shape and stays non-negative);
70
+ - ``scale`` rescales the gap about its mean so that the target's standard deviation is
71
+ scaled as requested (its mean is kept).
72
+
73
+ ``mean_multiplier`` and ``scale`` are solved on a sample generated from the parent, since
74
+ they depend on how base and gap vary together. The gap must stay non-negative, or the
75
+ ordering the transform guarantees would break: a request that needs a negative gap anywhere
76
+ (a shift towards the base beyond the smallest gap, a ``scale`` above 1 on a gap that starts
77
+ at 0, a mean on the wrong side of the base's mean) raises :class:`ScenarioError` with the
78
+ share of rows affected and what to request instead. Datetime targets support ``shift`` only,
79
+ like every datetime column.
80
+ * ``missing_rate`` on a difference target sets the rate of the gap's missingness indicator so
81
+ that the target's null rate is the requested one. The target is missing whenever its base
82
+ is, so a rate below the base's raises :class:`ScenarioError`.
83
+ * ``correlation`` with a difference target is translated to the latent that stands for it in
84
+ the copula, its gap (with the transform's sign): what the target inherits from its base is
85
+ left as it is. Between two structurally linked columns (a target and a column it is computed
86
+ from, or two targets sharing an input) the dependence is structural, not a correlation
87
+ parameter, and the request raises :class:`ScenarioError`. The hidden latent can still be
88
+ addressed by its own name (``correlation={("__delta__end", "start"): 0.3}``).
89
+ * **An identity target is derived**: it has no model of its own, and every request on it
90
+ raises :class:`ScenarioError` naming the inputs to change instead.
91
+
92
+ Targets: the parent's targets no longer describe the mutated population, so the calibration
93
+ *and* sealed targets of the result are **recomputed on a sample generated from the mutated
94
+ model** (seed stream ``"scenario"``). ``manifest.diagnostics["targets_source"]`` records this,
95
+ and ``provenance.lineage`` gets ``{"op": "mutate", "parent": <content hash>, "changes": ...}``.
96
+ """
97
+
98
+ from __future__ import annotations
99
+
100
+ import datetime as _dt
101
+ import math
102
+ from collections.abc import Callable, Mapping, Sequence
103
+ from dataclasses import dataclass, field
104
+ from typing import Any
105
+
106
+ import numpy as np
107
+ import polars as pl
108
+
109
+ from ectype.errors import ScenarioError
110
+ from ectype.fingerprint.core import ArrayStore, Fingerprint
111
+ from ectype.fingerprint.schema import (
112
+ ColumnSchema,
113
+ Manifest,
114
+ ModelSpec,
115
+ ReservedSection,
116
+ TargetSet,
117
+ TransformSpec,
118
+ )
119
+ from ectype.models import marginals as _marginals # noqa: F401 (registers kinds)
120
+ from ectype.models.base import MARGINALS, MarginalModel, marginal_from_spec
121
+ from ectype.models.copulas import GaussianCopula, IndependentJoint
122
+ from ectype.rng import stream
123
+ from ectype.scenarios.feasibility import (
124
+ PIN_RAISE,
125
+ PIN_REPORT,
126
+ Structure,
127
+ check_rho,
128
+ constraint_violation_share,
129
+ explain_not_pd,
130
+ marginal_mean,
131
+ pinned_correlation,
132
+ value_violation_share,
133
+ )
134
+ from ectype.types import LogicalType
135
+
136
+ MISSING_PREFIX = "__missing__"
137
+ _NUMERIC = (LogicalType.CONTINUOUS, LogicalType.DISCRETE)
138
+ _CATEGORY = (LogicalType.CATEGORICAL, LogicalType.BOOLEAN)
139
+
140
+ #: metrics unchanged by a positive affine change of one of their columns
141
+ AFFINE_INVARIANT = frozenset({
142
+ "bivariate.spearman", "bivariate.kendall", "bivariate.pearson",
143
+ "bivariate.correlation_ratio", "bivariate.mutual_info", "missingness.co_missing",
144
+ "univariate.missing_rate",
145
+ })
146
+ #: share of mass violating a single-column hard constraint above which a request is refused
147
+ VIOLATION_RAISE = 0.5
148
+ VIOLATION_REPORT = 0.005
149
+ DEFAULT_SAMPLE = 20_000
150
+ #: smallest quantile level the encoder decodes (``models.encoding.EPS``): the lower end of
151
+ #: what a marginal can generate, used to check that a changed gap stays non-negative
152
+ _SUPPORT_LEVEL = 1e-9
153
+ #: change kinds that are an exact positive-affine map of the column's values ...
154
+ _AFFINE_KINDS = frozenset({"affine", "shifted"})
155
+ #: ... and those that only change how often the column is null
156
+ _MISSING_KINDS = frozenset({"missing", "missing_dependent"})
157
+
158
+
159
+ def _missing_name(col: str) -> str:
160
+ return f"{MISSING_PREFIX}{col}"
161
+
162
+
163
+ # ---------------------------------------------------------------------------------------------
164
+ # the "affine" wrapper marginal
165
+ # ---------------------------------------------------------------------------------------------
166
+
167
+
168
+ @MARGINALS.register()
169
+ class AffineMarginal(MarginalModel):
170
+ """``value = a + b * inner`` with ``b > 0`` (a monotone wrapper around any marginal).
171
+
172
+ Spec: ``params = {"a", "b", "inner": {"kind", "params"}}`` and the inner model's arrays
173
+ under ``"inner.<name>"``. Nested affine wrappers are collapsed by :func:`compose_affine`.
174
+ """
175
+
176
+ kind = "affine"
177
+
178
+ def __init__(self, inner: MarginalModel, a: float = 0.0, b: float = 1.0) -> None:
179
+ if not (math.isfinite(a) and math.isfinite(b)) or b <= 0:
180
+ raise ValueError(f"affine marginal needs finite a and b > 0, got a={a}, b={b}")
181
+ self.inner = inner
182
+ self.a = float(a)
183
+ self.b = float(b)
184
+ self.discrete = bool(getattr(inner, "discrete", False))
185
+
186
+ @classmethod
187
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> AffineMarginal: # noqa: D102
188
+ raise NotImplementedError("affine marginals are built by scenarios.mutate, not fitted")
189
+
190
+ def _y(self, x: np.ndarray) -> np.ndarray:
191
+ return (np.asarray(x, dtype=np.float64) - self.a) / self.b
192
+
193
+ def cdf(self, x):
194
+ return self.inner.cdf(self._y(x))
195
+
196
+ def cdf_left(self, x):
197
+ return self.inner.cdf_left(self._y(x))
198
+
199
+ def ppf(self, u):
200
+ return self.a + self.b * np.asarray(self.inner.ppf(u), dtype=np.float64)
201
+
202
+ def logpdf(self, x):
203
+ lp = self.inner.logpdf(self._y(x))
204
+ if lp is None:
205
+ return None
206
+ return lp if self.discrete else lp - math.log(self.b)
207
+
208
+ @property
209
+ def n_parameters(self) -> int:
210
+ return self.inner.n_parameters + 2
211
+
212
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
213
+ inner = self.inner.to_spec(store, f"{prefix}inner.")
214
+ return affine_spec(inner, self.a, self.b)
215
+
216
+ @classmethod
217
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> AffineMarginal:
218
+ p = spec.params
219
+ inner = p["inner"]
220
+ if not isinstance(inner, dict):
221
+ raise ValueError("affine marginal spec has no inner model")
222
+ ispec = ModelSpec(kind=str(inner["kind"]), params=dict(inner.get("params", {})),
223
+ arrays={k[len("inner."):]: v for k, v in spec.arrays.items()
224
+ if k.startswith("inner.")})
225
+ return cls(marginal_from_spec(ispec, store), float(p["a"]), float(p["b"]))
226
+
227
+ def __repr__(self) -> str:
228
+ return f"AffineMarginal({self.a:.6g} + {self.b:.6g} * {self.inner!r})"
229
+
230
+
231
+ def affine_spec(inner: ModelSpec, a: float, b: float) -> ModelSpec:
232
+ """Spec of ``a + b * inner`` built from an existing spec (no array copies). An ``affine``
233
+ inner spec is collapsed: ``a + b (a0 + b0 y) = (a + b a0) + (b b0) y``."""
234
+ if inner.kind == AffineMarginal.kind:
235
+ a0, b0 = float(inner.params["a"]), float(inner.params["b"])
236
+ return ModelSpec(kind=AffineMarginal.kind,
237
+ params={"a": a + b * a0, "b": b * b0, "inner": inner.params["inner"]},
238
+ arrays=dict(inner.arrays))
239
+ return ModelSpec(kind=AffineMarginal.kind,
240
+ params={"a": float(a), "b": float(b),
241
+ "inner": {"kind": inner.kind, "params": dict(inner.params)}},
242
+ arrays={f"inner.{k}": v for k, v in inner.arrays.items()})
243
+
244
+
245
+ # ---------------------------------------------------------------------------------------------
246
+ # result
247
+ # ---------------------------------------------------------------------------------------------
248
+
249
+
250
+ @dataclass
251
+ class ScenarioResult:
252
+ """A mutated fingerprint plus the diagnostics of the mutation.
253
+
254
+ * ``requested``: the normalized request, keyed like ``"shift[income]"``.
255
+ * ``achieved``: the value measured on a sample generated from the mutated fingerprint.
256
+ * ``checks``: per key ``{"requested", "achieved", "tolerance", "within_tolerance"}``.
257
+ * ``collateral``: parent calibration targets that passed on a sample of the parent but fail
258
+ (moved beyond tolerance) on a sample of the mutated model, excluding the targets the
259
+ request changes on purpose. Each entry says whether the move was ``expected``.
260
+ * ``expected_to_move``: target ids the analysis expected to move (see
261
+ ``preserve_dependencies``). A column computed by a structural transform moves with its
262
+ inputs: when only an input is requested, the computed column's targets are listed here
263
+ (and in ``collateral``, as expected, where they now fail).
264
+ * ``infeasible``: empty, or explanations of requests that could only be met approximately
265
+ (requests that cannot be met at all raise :class:`ScenarioError`).
266
+ """
267
+
268
+ fingerprint: Fingerprint
269
+ requested: dict[str, Any]
270
+ achieved: dict[str, Any]
271
+ checks: dict[str, dict[str, Any]] = field(default_factory=dict)
272
+ collateral: list[dict[str, Any]] = field(default_factory=list)
273
+ expected_to_move: list[str] = field(default_factory=list)
274
+ infeasible: list[str] = field(default_factory=list)
275
+ notes: list[str] = field(default_factory=list)
276
+
277
+ @property
278
+ def ok(self) -> bool:
279
+ return not self.infeasible and all(c["within_tolerance"] for c in self.checks.values())
280
+
281
+ def to_dict(self) -> dict[str, Any]:
282
+ return json_safe({
283
+ "requested": self.requested, "achieved": self.achieved, "checks": self.checks,
284
+ "collateral": self.collateral, "expected_to_move": self.expected_to_move,
285
+ "infeasible": self.infeasible, "notes": self.notes,
286
+ })
287
+
288
+ def summary(self) -> str:
289
+ lines = ["scenario: " + ("all requested changes achieved" if self.ok else
290
+ "some requested changes were not fully achieved")]
291
+ for k, c in self.checks.items():
292
+ flag = "ok " if c["within_tolerance"] else "OFF"
293
+ lines.append(f" [{flag}] {k}: requested {c['requested']!r}, achieved "
294
+ f"{c['achieved']!r} (tolerance {c['tolerance']!r})")
295
+ if self.collateral:
296
+ lines.append(f" collateral: {len(self.collateral)} calibration target(s) moved "
297
+ f"beyond tolerance: " + ", ".join(t["id"] for t in self.collateral[:10]))
298
+ for msg in self.infeasible:
299
+ lines.append(f" infeasible: {msg}")
300
+ lines.append(" targets were recomputed on a sample generated from the mutated model")
301
+ return "\n".join(lines)
302
+
303
+
304
+ def json_safe(obj: Any) -> Any:
305
+ if isinstance(obj, Mapping):
306
+ return {(",".join(map(str, k)) if isinstance(k, tuple) else str(k)): json_safe(v)
307
+ for k, v in obj.items()}
308
+ if isinstance(obj, (list, tuple)):
309
+ return [json_safe(v) for v in obj]
310
+ if isinstance(obj, np.generic):
311
+ obj = obj.item()
312
+ if isinstance(obj, np.ndarray):
313
+ return json_safe(obj.tolist())
314
+ if isinstance(obj, float) and not math.isfinite(obj):
315
+ return str(obj)
316
+ if isinstance(obj, _dt.timedelta | _dt.date):
317
+ return str(obj)
318
+ return obj
319
+
320
+
321
+ # ---------------------------------------------------------------------------------------------
322
+ # target recomputation (shared with merge and authoring)
323
+ # ---------------------------------------------------------------------------------------------
324
+
325
+
326
+ def sample_seed(seed: int, *names: str) -> int:
327
+ return int(stream(int(seed), "scenario", *names).integers(0, 2**31 - 1))
328
+
329
+
330
+ def untargeted(manifest: Manifest, arrays: ArrayStore,
331
+ diagnostics: dict[str, Any] | None = None) -> Fingerprint:
332
+ """A fingerprint with empty target sets (only for generating its reference sample)."""
333
+ return Fingerprint.build(manifest, arrays, TargetSet(kind="calibration"),
334
+ TargetSet(kind="sealed"), diagnostics=diagnostics)
335
+
336
+
337
+ def retarget(fp: Fingerprint, *, n: int, seed: int, op: str,
338
+ sample: pl.DataFrame | None = None,
339
+ max_pairs: int | None = None) -> tuple[Fingerprint, pl.DataFrame]:
340
+ """Recompute calibration and sealed targets of ``fp`` on a sample generated from ``fp``
341
+ itself (``seed`` is the generation seed) and record that in
342
+ ``manifest.diagnostics["targets_source"]``."""
343
+ from ectype.fingerprint.targets import build_targets
344
+ from ectype.generation.generator import Generator
345
+ from ectype.profiling.reference import model_view
346
+
347
+ if sample is None:
348
+ # (measured as the targets are: reference keys as group sizes, ADR-0013; a sample a
349
+ # caller passes in is in that form already)
350
+ sample = model_view(Generator(fp).generate(int(n), seed=int(seed)), fp.manifest)
351
+ m = fp.manifest.model_copy(deep=True)
352
+ if max_pairs is None:
353
+ max_pairs = int(m.provenance.config.get("max_pairs", 200) or 200) # type: ignore[arg-type]
354
+ calib, sealed = build_targets(sample, m.columns, m.disclosure_policy,
355
+ seed=m.targets.partition_seed,
356
+ sealed_fraction=m.targets.sealed_fraction, max_pairs=max_pairs)
357
+ m.diagnostics["targets_source"] = {
358
+ "kind": "generated_sample", "op": op, "n": int(sample.height),
359
+ "generation_seed": int(seed), "seed_stream": "scenario",
360
+ "note": "targets describe the modeled (mutated/merged/authored) population, measured on "
361
+ "a sample generated from this fingerprint; they are not source measurements",
362
+ }
363
+ out = Fingerprint.build(m, fp.arrays, calib, sealed, diagnostics=fp.diagnostics)
364
+ return out, sample
365
+
366
+
367
+ # ---------------------------------------------------------------------------------------------
368
+ # normalisation of the request
369
+ # ---------------------------------------------------------------------------------------------
370
+
371
+
372
+ def _per_column(name: str, value: Any, column: str | None) -> dict[str, Any]:
373
+ if value is None:
374
+ return {}
375
+ if isinstance(value, Mapping):
376
+ return {str(k): v for k, v in value.items()}
377
+ if column is None:
378
+ raise ScenarioError(f"{name}={value!r} needs a column: pass {{column: value}} or "
379
+ f"column=...")
380
+ return {column: value}
381
+
382
+
383
+ def _number(x: Any, what: str) -> float:
384
+ if isinstance(x, bool):
385
+ raise ScenarioError(f"{what}: expected a number, got {x!r}")
386
+ try:
387
+ v = float(x)
388
+ except (TypeError, ValueError):
389
+ raise ScenarioError(f"{what}: expected a number, got {x!r}") from None
390
+ if not math.isfinite(v):
391
+ raise ScenarioError(f"{what}: must be finite, got {v}")
392
+ return v
393
+
394
+
395
+ def current_missing_rates(fp: Fingerprint) -> dict[str, float]:
396
+ """The null rate per column that ``drift`` starts from: the rate of the missingness
397
+ indicator for a modeled column and, for a column computed by a structural transform (it
398
+ has no indicator of its own), the null fraction recorded in its schema."""
399
+ out = {c: float(s.params.get("rate", 0.0)) # type: ignore[arg-type]
400
+ for c, s in fp.manifest.model.missingness.items()}
401
+ schemas = {c.name: c for c in fp.manifest.columns}
402
+ for t in fp.manifest.model.transforms:
403
+ if t.target in schemas:
404
+ out[t.target] = float(schemas[t.target].null_fraction)
405
+ return out
406
+
407
+
408
+ def linked_groups(fp: Fingerprint, columns: Sequence[str]) -> list[list[str]]:
409
+ """The requested ``columns`` split into the groups that have to be checked together:
410
+ structurally linked columns form one group, because a request on a computed column is met
411
+ net of what its inputs do in the same request. Without structural transforms every column
412
+ is its own group."""
413
+ structure = Structure(fp.manifest)
414
+ groups: list[list[str]] = []
415
+ for col in dict.fromkeys(columns):
416
+ linked = [g for g in groups if any(structure.related(col, other) for other in g)]
417
+ if not linked:
418
+ groups.append([col])
419
+ continue
420
+ for g in linked[1:]:
421
+ linked[0].extend(g)
422
+ groups.remove(g)
423
+ linked[0].append(col)
424
+ return groups
425
+
426
+
427
+ _DRIFT_KEYS = {"periods", "mean_rate", "shift_per_period", "scale_rate",
428
+ "missing_rate_per_period"}
429
+
430
+
431
+ def _expand_drift(drift: dict[str, Any], mm: dict[str, float], sc: dict[str, float],
432
+ sh: dict[str, Any], mr: dict[str, float], current_rate: dict[str, float],
433
+ notes: list[str]) -> None:
434
+ for col, spec in drift.items():
435
+ if not isinstance(spec, Mapping):
436
+ raise ScenarioError(f"drift[{col!r}] must be a mapping of {sorted(_DRIFT_KEYS)}")
437
+ bad = set(spec) - _DRIFT_KEYS
438
+ if bad:
439
+ raise ScenarioError(f"drift[{col!r}]: unknown keys {sorted(bad)}; allowed "
440
+ f"{sorted(_DRIFT_KEYS)}")
441
+ periods = _number(spec.get("periods", 1), f"drift[{col!r}].periods")
442
+ if periods < 0:
443
+ raise ScenarioError(f"drift[{col!r}].periods must be >= 0")
444
+ if "mean_rate" in spec:
445
+ r = _number(spec["mean_rate"], f"drift[{col!r}].mean_rate")
446
+ if r <= -1:
447
+ raise ScenarioError(f"drift[{col!r}].mean_rate must be > -1")
448
+ mm[col] = mm.get(col, 1.0) * (1.0 + r) ** periods
449
+ if "scale_rate" in spec:
450
+ r = _number(spec["scale_rate"], f"drift[{col!r}].scale_rate")
451
+ if r <= -1:
452
+ raise ScenarioError(f"drift[{col!r}].scale_rate must be > -1")
453
+ sc[col] = sc.get(col, 1.0) * (1.0 + r) ** periods
454
+ if "shift_per_period" in spec:
455
+ d = _number(spec["shift_per_period"], f"drift[{col!r}].shift_per_period")
456
+ sh[col] = _number(sh.get(col, 0.0), "shift") + d * periods
457
+ if "missing_rate_per_period" in spec:
458
+ if col in mr:
459
+ raise ScenarioError(f"missing_rate and drift both set the null rate of {col!r}")
460
+ d = _number(spec["missing_rate_per_period"], f"drift[{col!r}]")
461
+ mr[col] = current_rate.get(col, 0.0) + d * periods
462
+ if drift:
463
+ notes.append("drift is applied to the whole population in v1: the result describes the "
464
+ "population at the end of the drift (no within-sample time gradient)")
465
+
466
+
467
+ # ---------------------------------------------------------------------------------------------
468
+ # mutate
469
+ # ---------------------------------------------------------------------------------------------
470
+
471
+
472
+ @dataclass
473
+ class _GapMoments:
474
+ """What a request on a difference target is solved from: the mean of its base *after* the
475
+ changes applied so far, of its gap and of the target itself and, when measured on rows, the
476
+ second moments."""
477
+
478
+ mean_base: float
479
+ mean_gap: float
480
+ mean_target: float
481
+ var_base: float | None = None
482
+ var_gap: float | None = None
483
+ cov: float | None = None # of the changed base and the gap
484
+ std_target: float | None = None
485
+
486
+
487
+ class _Rows:
488
+ """A sample of the parent's rows in the value domain, and the values the same rows take
489
+ after the changes applied so far: ``a + b * value`` for a plain column, the new base plus
490
+ the changed gap for a difference target, the recomputed formula for an identity target.
491
+ That is exact (rounding aside) while the joint model is unchanged, which is what lets a
492
+ request on a computed column be solved on data."""
493
+
494
+ def __init__(self, st: _State, frame: pl.DataFrame) -> None:
495
+ self.st = st
496
+ self.frame = frame
497
+ self._parent: dict[str, np.ndarray] = {}
498
+
499
+ def parent(self, col: str) -> np.ndarray:
500
+ if col not in self._parent:
501
+ from ectype.io.values import column_to_values
502
+
503
+ self._parent[col] = np.asarray(
504
+ column_to_values(self.frame.get_column(col), self.st.columns[col]),
505
+ dtype=np.float64)
506
+ return self._parent[col]
507
+
508
+ def gap(self, t: TransformSpec) -> np.ndarray:
509
+ return Structure.sign(t) * (self.parent(t.target) - self.parent(t.inputs[0]))
510
+
511
+ def new(self, col: str) -> np.ndarray:
512
+ t = self.st.structure.transform(col)
513
+ if t is None:
514
+ a, b = self.st.affine.get(col, (0.0, 1.0))
515
+ return a + b * self.parent(col)
516
+ if t.kind == "difference":
517
+ a, b = self.st.affine.get(Structure.latent(t), (0.0, 1.0))
518
+ return self.new(t.inputs[0]) + Structure.sign(t) * (a + b * self.gap(t))
519
+ x, y = (self.new(c) for c in t.inputs)
520
+ op = t.params.get("op")
521
+ with np.errstate(all="ignore"):
522
+ return x + y if op == "+" else (x - y if op == "-" else x * y)
523
+
524
+
525
+ class _State:
526
+ """Mutable working copy of the fingerprint's model.
527
+
528
+ ``reference`` supplies a sample generated from the parent, for the requests that are
529
+ solved on data (``mean_multiplier`` / ``scale`` on a column computed by a transform). It is
530
+ called at most once, and only when such a request is made. Without it nothing is ever
531
+ generated (a dry run): those requests are then checked for form only.
532
+ """
533
+
534
+ def __init__(self, fp: Fingerprint,
535
+ reference: Callable[[], pl.DataFrame] | None = None) -> None:
536
+ self.parent = fp
537
+ self.manifest = fp.manifest.model_copy(deep=True)
538
+ self.arrays = ArrayStore(fp.arrays.as_dict())
539
+ self.model = self.manifest.model
540
+ self.columns = {c.name: c for c in self.manifest.columns}
541
+ self.notes: list[str] = []
542
+ self.infeasible: list[str] = []
543
+ self.requested: dict[str, Any] = {}
544
+ self.expected: dict[str, float] = {} # key -> expected measured value
545
+ self.changed: dict[str, set[str]] = {} # column -> change kinds
546
+ #: which columns are computed by a structural transform, and from what
547
+ self.structure = Structure(self.manifest)
548
+ #: the change ``value -> a + b * value`` this request applies, per column of the joint
549
+ #: model (plain columns and the hidden gaps of difference targets)
550
+ self.affine: dict[str, tuple[float, float]] = {}
551
+ #: correlation requests translated to a hidden gap: ``"a,b" -> (slot a, slot b, sign)``
552
+ self.translated: dict[str, tuple[str, str, float]] = {}
553
+ self._reference = reference
554
+ self._rows: _Rows | None = None
555
+
556
+ def feature(self, col: str, what: str) -> ColumnSchema:
557
+ """The schema of a column that can be mutated: a modeled feature, or a column computed
558
+ by a ``difference`` transform (modeled through its hidden gap)."""
559
+ if col not in self.columns:
560
+ raise ScenarioError(f"{what}: unknown column {col!r}; columns are "
561
+ f"{sorted(self.columns)}")
562
+ t = self.structure.transform(col)
563
+ if t is not None:
564
+ if t.kind == "identity":
565
+ raise ScenarioError(
566
+ f"{what}: column {col!r} is derived ({Structure.formula(t)}, an identity "
567
+ f"transform): it has no model of its own and cannot be mutated directly. "
568
+ f"Mutate its input(s) {', '.join(repr(c) for c in t.inputs)} instead; "
569
+ f"{col!r} is recomputed from them")
570
+ if t.kind != "difference" or Structure.latent(t) not in self.model.marginals:
571
+ raise ScenarioError(f"{what}: column {col!r} is computed by a {t.kind!r} "
572
+ f"transform that this engine cannot mutate")
573
+ return self.columns[col]
574
+ for spec in self.model.sums:
575
+ # a column a sum computes (ADR-0014) has no model of its own
576
+ made = (spec.parts if spec.mode == "split"
577
+ else [spec.total] if spec.mode == "sum" else [])
578
+ if col in made:
579
+ from ectype.profiling.sums import sum_text
580
+
581
+ hint = (f"Mutate its total {spec.total!r} instead: the parts keep their shares "
582
+ f"of it" if spec.mode == "split" and spec.total is not None
583
+ else "Mutate its parts instead" if spec.mode == "sum"
584
+ else "Its share of the constant total is modeled, not the column")
585
+ raise ScenarioError(
586
+ f"{what}: column {col!r} is computed by a sum ({sum_text(spec)}, mode "
587
+ f"{spec.mode}): it has no model of its own and cannot be mutated directly. "
588
+ f"{hint}, or fit with structure='off' to model the column itself")
589
+ if col not in self.model.marginals or col not in self.model.encodings:
590
+ raise ScenarioError(f"{what}: column {col!r} is not a modeled feature (role "
591
+ f"{self.columns[col].role!s}); only modeled columns can be "
592
+ f"mutated")
593
+ return self.columns[col]
594
+
595
+ def marginal(self, col: str) -> MarginalModel:
596
+ return marginal_from_spec(self.model.marginals[col], self.arrays)
597
+
598
+ def mark(self, col: str, kind: str) -> None:
599
+ self.changed.setdefault(col, set()).add(kind)
600
+
601
+ # -- structural transforms -----------------------------------------------------------------
602
+ def rows(self) -> _Rows | None:
603
+ """Parent rows to solve a request on, or ``None`` in a dry run (no ``reference``)."""
604
+ if self._rows is None and self._reference is not None:
605
+ self._rows = _Rows(self, self._reference())
606
+ return self._rows
607
+
608
+ def shift_of(self, col: str) -> float | None:
609
+ """The amount the request so far adds to every value of ``col`` (0.0 when it does not
610
+ move), or ``None`` when ``col`` changes in any other way."""
611
+ t = self.structure.transform(col)
612
+ if t is None:
613
+ a, b = self.affine.get(col, (0.0, 1.0))
614
+ return a if b == 1.0 else None
615
+ shifts = [self.shift_of(c) for c in t.inputs]
616
+ if any(s is None for s in shifts):
617
+ return None
618
+ if t.kind == "difference":
619
+ a, b = self.affine.get(Structure.latent(t), (0.0, 1.0))
620
+ return shifts[0] + Structure.sign(t) * a if b == 1.0 else None # type: ignore[operator]
621
+ op = t.params.get("op") if t.kind == "identity" else None
622
+ if op == "+":
623
+ return shifts[0] + shifts[1] # type: ignore[operator]
624
+ if op == "-":
625
+ return shifts[0] - shifts[1] # type: ignore[operator]
626
+ return 0.0 if all(s == 0.0 for s in shifts) else None
627
+
628
+ def model_mean(self, col: str, *, new: bool) -> float | None:
629
+ """Mean of ``col`` from the marginals alone (no data): of the parent, or with
630
+ ``new=True`` after the changes applied so far. ``None`` where it has no closed form (a
631
+ product)."""
632
+ t = self.structure.transform(col)
633
+ if t is None or t.kind == "difference":
634
+ name = col if t is None else Structure.latent(t)
635
+ spec = self.parent.manifest.model.marginals.get(name)
636
+ if spec is None:
637
+ return None
638
+ mu = marginal_mean(marginal_from_spec(spec, self.parent.arrays))
639
+ if new:
640
+ a, b = self.affine.get(name, (0.0, 1.0))
641
+ mu = a + b * mu
642
+ if t is None:
643
+ return mu
644
+ base = self.model_mean(t.inputs[0], new=new)
645
+ return None if base is None else base + Structure.sign(t) * mu
646
+ means = [self.model_mean(c, new=new) for c in t.inputs]
647
+ op = t.params.get("op") if t.kind == "identity" else None
648
+ if any(m is None for m in means) or op not in ("+", "-"):
649
+ return None
650
+ return means[0] + means[1] if op == "+" else means[0] - means[1] # type: ignore[operator]
651
+
652
+ def gap_moments(self, t: TransformSpec) -> _GapMoments | None:
653
+ """Moments for a request on the difference target of ``t``: measured on the parent rows
654
+ when there are any, else the means the marginals give (no second moments)."""
655
+ base, sign = t.inputs[0], Structure.sign(t)
656
+ rows = self.rows()
657
+ if rows is not None:
658
+ b_new, gap, target = rows.new(base), rows.gap(t), rows.parent(t.target)
659
+ ok = np.isfinite(b_new) & np.isfinite(gap) & np.isfinite(target)
660
+ if int(ok.sum()) < 3:
661
+ return None
662
+ b_new, gap, target = b_new[ok], gap[ok], target[ok]
663
+ c = np.cov(b_new, gap, bias=True)
664
+ return _GapMoments(float(b_new.mean()), float(gap.mean()), float(target.mean()),
665
+ float(c[0, 0]), float(c[1, 1]), float(c[0, 1]),
666
+ float(target.std()))
667
+ mean_new, mean_old = self.model_mean(base, new=True), self.model_mean(base, new=False)
668
+ spec = self.parent.manifest.model.marginals.get(Structure.latent(t))
669
+ if mean_new is None or mean_old is None or spec is None:
670
+ return None
671
+ mean_gap = marginal_mean(marginal_from_spec(spec, self.parent.arrays))
672
+ return _GapMoments(mean_new, mean_gap, mean_old + sign * mean_gap)
673
+
674
+
675
+ def _datetime_delta(delta: Any, col: ColumnSchema) -> float:
676
+ if isinstance(delta, _dt.timedelta):
677
+ if col.is_date or col.datetime_unit == "d":
678
+ return delta.total_seconds() / 86400.0
679
+ return delta.total_seconds() * 1e6
680
+ return _number(delta, f"shift[{col.name!r}]")
681
+
682
+
683
+ def _check_single_column_constraints(st: _State, col: str, shares: dict[str, float],
684
+ before: dict[str, float]) -> None:
685
+ """Refuse a change that makes most of ``col`` violate one of its single-column hard
686
+ constraints; report one that makes rejection truncate it."""
687
+ for cid, share in shares.items():
688
+ extra = share - before.get(cid, 0.0)
689
+ if share >= VIOLATION_RAISE:
690
+ raise ScenarioError(
691
+ f"infeasible: after the change {share:.0%} of {col!r}'s distribution "
692
+ f"violates hard constraint {cid!r}; rejection sampling would have to discard "
693
+ f"most of the population, so the requested change cannot be met. Relax or "
694
+ f"remove the constraint, or request a smaller change")
695
+ if extra > VIOLATION_REPORT:
696
+ st.infeasible.append(
697
+ f"{col}: {share:.1%} of the mutated distribution violates hard constraint "
698
+ f"{cid!r} and will be rejected at generation, so the achieved distribution "
699
+ f"is truncated relative to the request")
700
+
701
+
702
+ def _moved_bounds(cs: ColumnSchema, shift: float | None) -> dict[str, Any]:
703
+ """Support bounds of a computed column after a change: moved by an exact ``shift``, unknown
704
+ (``None``) after any other change."""
705
+ return {name: (None if shift is None else value + shift)
706
+ for name, value in (("min_value", cs.min_value), ("max_value", cs.max_value))
707
+ if value is not None}
708
+
709
+
710
+ def _lower_end(m: MarginalModel) -> float:
711
+ """The smallest value the generator can decode from ``m``."""
712
+ return float(np.asarray(m.ppf(np.array([_SUPPORT_LEVEL])), dtype=np.float64)[0])
713
+
714
+
715
+ def _apply_affine_target(st: _State, col: str, cs: ColumnSchema, t: TransformSpec,
716
+ shift: dict[str, Any], scale: dict[str, float],
717
+ mult: dict[str, float]) -> None:
718
+ """``shift`` / ``scale`` / ``mean_multiplier`` on the target of a ``difference`` transform:
719
+ the hidden gap is changed so that the *target* changes as requested, given what its base
720
+ does in the same request (see the module docstring)."""
721
+ from ectype.profiling.structure import latent_schema
722
+
723
+ base, latent, sign = t.inputs[0], Structure.latent(t), Structure.sign(t)
724
+ plain = Structure.formula(t, hidden=False)
725
+ spec0 = st.model.marginals[latent]
726
+ m0 = marginal_from_spec(spec0, st.arrays)
727
+ k = f = d = None
728
+ if col in mult:
729
+ k = _number(mult[col], f"mean_multiplier[{col!r}]")
730
+ if k <= 0:
731
+ raise ScenarioError(f"mean_multiplier[{col!r}] must be > 0, got {k}")
732
+ st.requested[f"mean_multiplier[{col}]"] = k
733
+ if col in scale:
734
+ f = _number(scale[col], f"scale[{col!r}]")
735
+ if f <= 0:
736
+ raise ScenarioError(f"scale[{col!r}] must be > 0, got {f}")
737
+ st.requested[f"scale[{col}]"] = f
738
+ if col in shift:
739
+ d = (_datetime_delta(shift[col], cs) if cs.logical_type == LogicalType.DATETIME
740
+ else _number(shift[col], f"shift[{col!r}]"))
741
+ st.requested[f"shift[{col}]"] = d
742
+ what = ", ".join(f"{name}[{col}] = {v:g}" for name, v in
743
+ (("mean_multiplier", k), ("scale", f), ("shift", d)) if v is not None)
744
+ base_shift = st.shift_of(base)
745
+ given = (f"with {base!r} unchanged" if base_shift == 0.0
746
+ else f"together with the requested change of {base!r}")
747
+ unit = {"d": " days", "us": " microseconds"}.get(str(t.params.get("unit")), "")
748
+
749
+ st.mark(col, "affine")
750
+ st.requested.setdefault("__affine_params__", {})[col] = {
751
+ "a": d or 0.0, "b": k or 1.0, "mean0": None}
752
+ gap_shift, gap_scale = 0.0, 1.0
753
+ exact = k is None and f is None and base_shift is not None # every value moves by d
754
+ if exact:
755
+ gap_shift = sign * (float(d or 0.0) - float(base_shift or 0.0))
756
+ else:
757
+ mom = st.gap_moments(t)
758
+ if mom is None or (f is not None and mom.var_gap is None):
759
+ if st.rows() is not None:
760
+ raise ScenarioError(
761
+ f"{what}: {col!r} is computed as {plain} and the request is solved on a "
762
+ f"sample generated from the fingerprint, but that sample has too few rows "
763
+ f"in which both {col!r} and {base!r} are present")
764
+ st.mark(col, "gap")
765
+ st.notes.append(f"{col}: computed as {plain}; the change of its gap that meets "
766
+ f"{what} is solved on a sample generated from the fingerprint when "
767
+ f"the request is applied")
768
+ return
769
+ st.requested["__affine_params__"][col]["mean0"] = mom.mean_target
770
+ wanted_mean = (k or 1.0) * mom.mean_target + (d or 0.0)
771
+ if k is not None and abs(mom.mean_target) < 1e-12:
772
+ raise ScenarioError(f"mean_multiplier[{col!r}]: the column's mean is 0, so a "
773
+ f"multiplier cannot change it; use shift")
774
+ if f is not None:
775
+ assert mom.var_base is not None and mom.var_gap is not None
776
+ assert mom.cov is not None and mom.std_target is not None
777
+ wanted_std = f * (k or 1.0) * mom.std_target
778
+ if mom.var_gap <= 0.0 or mom.std_target <= 0.0:
779
+ raise ScenarioError(f"scale[{col!r}]: the gap between {col!r} and {base!r} is "
780
+ f"constant, so its spread cannot be rescaled; use shift")
781
+ disc = mom.cov ** 2 - mom.var_gap * (mom.var_base - wanted_std ** 2)
782
+ root = (-sign * mom.cov + math.sqrt(disc)) / mom.var_gap if disc >= 0 else -1.0
783
+ if root <= 0:
784
+ floor = math.sqrt(max(mom.var_base - mom.cov ** 2 / mom.var_gap, 0.0))
785
+ raise ScenarioError(
786
+ f"infeasible: {what} asks for a standard deviation of {wanted_std:.6g} "
787
+ f"for {col!r}, but {col!r} is computed as {plain} and {given} its "
788
+ f"standard deviation cannot go below {floor:.6g} (a factor of "
789
+ f"{floor / ((k or 1.0) * mom.std_target):.4g}): that much comes from "
790
+ f"{base!r} alone. Scale {base!r} as well")
791
+ gap_scale = root
792
+ gap_shift = sign * (wanted_mean - mom.mean_base) - gap_scale * mom.mean_gap
793
+ elif k is not None:
794
+ if mom.mean_gap <= 1e-12 * max(abs(mom.mean_target), 1.0):
795
+ raise ScenarioError(f"mean_multiplier[{col!r}]: the gap between {col!r} and "
796
+ f"{base!r} is zero on average, so it cannot be "
797
+ f"multiplied; use shift")
798
+ gap_scale = sign * (k * mom.mean_target - mom.mean_base) / mom.mean_gap
799
+ if gap_scale <= 0:
800
+ side = "below" if sign > 0 else "above"
801
+ raise ScenarioError(
802
+ f"infeasible: {what} asks for a mean of {k * mom.mean_target:.6g} for "
803
+ f"{col!r}, but {col!r} is computed as {plain} with delta >= 0, so {given} "
804
+ f"its mean cannot go {side} the mean of {base!r} ({mom.mean_base:.6g}): "
805
+ f"the multiplier must stay {'above' if sign > 0 else 'below'} "
806
+ f"{mom.mean_base / mom.mean_target:.4g}. Change {base!r} as well")
807
+ gap_shift = sign * (d or 0.0)
808
+ else:
809
+ gap_shift = sign * (wanted_mean - mom.mean_base) - mom.mean_gap
810
+
811
+ # delta >= 0 is what makes the ordering hold by construction: it has to survive the change
812
+ # (a signed gap models out-of-order rows and guarantees no ordering: nothing to keep)
813
+ new_spec = affine_spec(spec0, gap_shift, gap_scale)
814
+ new = marginal_from_spec(new_spec, st.arrays)
815
+ low0, low = _lower_end(m0), _lower_end(new)
816
+ tolerance = 1e-9 * max(abs(low0), abs(gap_shift), 1e-300)
817
+ if not Structure.signed(t) and low < min(0.0, low0) - tolerance:
818
+ share = float(np.asarray(m0.cdf_left(np.array([-gap_shift / gap_scale])))[0])
819
+ wrong = f"{col} < {base}" if sign > 0 else f"{col} > {base}"
820
+ if exact:
821
+ limit = float(base_shift or 0.0) - sign * low0
822
+ hint = (f"The smallest gap the model generates is {low0:g}{unit}, so the largest "
823
+ f"shift in that direction is {limit:g}{unit}. Shift {base!r} by the same "
824
+ f"amount (the gap is then unchanged), or use mean_multiplier, which "
825
+ f"rescales the gap and keeps it non-negative")
826
+ elif f is not None:
827
+ hint = ("Widening the spread about the mean pushes the smallest gaps below zero. "
828
+ f"Scale {base!r} instead, or use mean_multiplier, which rescales the gap "
829
+ f"and keeps it non-negative")
830
+ else:
831
+ hint = (f"Request a change of {col!r} that leaves room for the gap, or change "
832
+ f"{base!r} to match")
833
+ rows_hit = f"{share:.1%} of the rows" if share >= 0.001 else "some rows"
834
+ raise ScenarioError(
835
+ f"infeasible: {what} {given} needs a negative gap between {col!r} and {base!r} "
836
+ f"for {rows_hit} ({wrong}). {col!r} is computed as {plain} with delta >= 0, and a "
837
+ f"request on {col!r} is met by changing delta. {hint}")
838
+ st.model.marginals[latent] = new_spec
839
+ st.affine[latent] = (gap_shift, gap_scale)
840
+ rows = st.rows()
841
+ if rows is not None: # the target's own hard constraints, on the rows it will take
842
+ hard = st.manifest.constraints.confirmed
843
+ after, before = rows.new(col), rows.parent(col)
844
+ _check_single_column_constraints(
845
+ st, col, value_violation_share(after[np.isfinite(after)], cs, hard),
846
+ value_violation_share(before[np.isfinite(before)], cs, hard))
847
+ moved = st.shift_of(col)
848
+ if moved is None:
849
+ st.mark(col, "gap")
850
+ bounds = _moved_bounds(cs, moved)
851
+ if bounds:
852
+ st.columns[col] = cs.model_copy(update=bounds)
853
+ change = (f"shifted by {gap_shift:g}{unit}" if gap_scale == 1.0 else
854
+ f"multiplied by {gap_scale:.6g}" if gap_shift == 0.0 else
855
+ f"mapped to {gap_shift:.6g} + {gap_scale:.6g} * delta")
856
+ st.notes.append(f"{col}: computed as {plain}; {what} {given} is met by changing its gap "
857
+ f"(the hidden column {latent}, {change})")
858
+ if latent_schema(t).integer_valued and (gap_scale != 1.0 or gap_shift != round(gap_shift)):
859
+ st.notes.append(f"{col}: its gap is integer-valued; mutated values are rounded to "
860
+ f"integers at generation")
861
+
862
+
863
+ def _propagate_moves(st: _State) -> None:
864
+ """Computed columns that were not requested themselves move with their inputs: say so,
865
+ mark them (``expected_to_move`` / ``collateral``) and move their support bounds."""
866
+ for t in st.structure.transforms:
867
+ col = t.target
868
+ if "affine" in st.changed.get(col, set()) or col not in st.columns:
869
+ continue
870
+ moved = st.shift_of(col)
871
+ if moved == 0.0:
872
+ continue
873
+ causes = [c for c in sorted(st.structure.inputs(col))
874
+ if "affine" in st.changed.get(c, set())]
875
+ st.mark(col, "shifted" if moved is not None else "dependent")
876
+ how = (f"every value shifts by {moved:g}" if moved is not None
877
+ else "its distribution changes")
878
+ keeps = "; its gap is unchanged" if t.kind == "difference" else ""
879
+ st.notes.append(f"{col}: computed as {Structure.formula(t, hidden=False)}; it moves "
880
+ f"with {', '.join(repr(c) for c in causes)} ({how}{keeps})")
881
+ bounds = _moved_bounds(st.columns[col], moved)
882
+ if bounds:
883
+ st.columns[col] = st.columns[col].model_copy(update=bounds)
884
+
885
+
886
+ def _apply_affine(st: _State, shift: dict[str, Any], scale: dict[str, float],
887
+ mult: dict[str, float]) -> None:
888
+ # plain columns first, then computed ones in dependency order: a request on a computed
889
+ # column is met net of what its base does in the same request
890
+ cols = st.structure.ordered(list(dict.fromkeys([*mult, *scale, *shift])))
891
+ for col in cols:
892
+ cs = st.feature(col, "shift/scale/mean_multiplier")
893
+ lt = cs.logical_type
894
+ if lt in _CATEGORY:
895
+ raise ScenarioError(f"cannot shift or scale {lt!s} column {col!r}; use "
896
+ f"category_probs")
897
+ if lt == LogicalType.DATETIME and (col in mult or col in scale):
898
+ raise ScenarioError(f"datetime column {col!r} supports shift only")
899
+ if lt not in (*_NUMERIC, LogicalType.DATETIME):
900
+ raise ScenarioError(f"column {col!r} of type {lt!s} cannot be shifted or scaled")
901
+ target = st.structure.transform(col)
902
+ if target is not None:
903
+ _apply_affine_target(st, col, cs, target, shift, scale, mult)
904
+ continue
905
+ m0 = st.marginal(col)
906
+ mu0 = marginal_mean(m0)
907
+ a, b = 0.0, 1.0
908
+ if col in mult:
909
+ k = _number(mult[col], f"mean_multiplier[{col!r}]")
910
+ if k <= 0:
911
+ raise ScenarioError(f"mean_multiplier[{col!r}] must be > 0, got {k}")
912
+ if abs(mu0) < 1e-12:
913
+ raise ScenarioError(f"mean_multiplier[{col!r}]: the column's mean is 0, so a "
914
+ f"multiplier cannot change it; use shift")
915
+ a, b = a * k, b * k
916
+ st.requested[f"mean_multiplier[{col}]"] = k
917
+ if col in scale:
918
+ f = _number(scale[col], f"scale[{col!r}]")
919
+ if f <= 0:
920
+ raise ScenarioError(f"scale[{col!r}] must be > 0, got {f}")
921
+ mu = a + b * mu0
922
+ a, b = mu + f * (a - mu), b * f
923
+ st.requested[f"scale[{col}]"] = f
924
+ if col in shift:
925
+ d = (_datetime_delta(shift[col], cs) if lt == LogicalType.DATETIME
926
+ else _number(shift[col], f"shift[{col!r}]"))
927
+ a += d
928
+ st.requested[f"shift[{col}]"] = d
929
+ spec = affine_spec(st.model.marginals[col], a, b)
930
+ new = marginal_from_spec(spec, st.arrays)
931
+ # feasibility against the single-column hard constraints
932
+ _check_single_column_constraints(
933
+ st, col, constraint_violation_share(new, cs, st.manifest.constraints.confirmed),
934
+ constraint_violation_share(m0, cs, st.manifest.constraints.confirmed))
935
+ st.model.marginals[col] = spec
936
+ st.affine[col] = (a, b)
937
+ # support bounds move with the affine map
938
+ upd: dict[str, Any] = {}
939
+ if cs.min_value is not None:
940
+ upd["min_value"] = a + b * cs.min_value
941
+ if cs.max_value is not None:
942
+ upd["max_value"] = a + b * cs.max_value
943
+ if upd:
944
+ st.columns[col] = cs.model_copy(update=upd)
945
+ if cs.integer_valued and (b != 1.0 or a != round(a)):
946
+ st.notes.append(f"{col}: integer-valued column; mutated values are rounded to "
947
+ f"integers at generation")
948
+ st.mark(col, "affine")
949
+ st.requested.setdefault("__affine_params__", {})[col] = {"a": a, "b": b, "mean0": mu0}
950
+ _propagate_moves(st)
951
+
952
+
953
+ def _probs(m: MarginalModel) -> np.ndarray:
954
+ p = np.clip(np.asarray(m.probs, dtype=np.float64), 0, None) # type: ignore[attr-defined]
955
+ return p / p.sum()
956
+
957
+
958
+ def _label_key(x: Any) -> str:
959
+ if isinstance(x, bool):
960
+ return "True" if x else "False"
961
+ return str(x)
962
+
963
+
964
+ def _ipf(cpt: np.ndarray, p_parent: np.ndarray, target: np.ndarray,
965
+ iters: int = 500) -> np.ndarray:
966
+ """Closest (KL) conditional table to ``cpt`` whose implied marginal is ``target``."""
967
+ t = np.clip(np.asarray(cpt, dtype=float), 0, None) + 1e-12
968
+ t = t / t.sum(axis=1, keepdims=True)
969
+ for _ in range(iters):
970
+ marg = p_parent @ t
971
+ ratio = np.where(marg > 0, target / np.where(marg > 0, marg, 1.0), 0.0)
972
+ t = t * ratio
973
+ s = t.sum(axis=1, keepdims=True)
974
+ t = np.where(s > 0, t / np.where(s > 0, s, 1.0), target)
975
+ if np.max(np.abs(p_parent @ t - target)) < 1e-10:
976
+ break
977
+ return t
978
+
979
+
980
+ def _conditional(spec: ModelSpec) -> dict[str, Any] | None:
981
+ cond = spec.params.get("conditional")
982
+ if isinstance(cond, dict) and cond.get("kind", "cpt_tree") == "cpt_tree" \
983
+ and "cpt" in spec.arrays:
984
+ return cond
985
+ return None
986
+
987
+
988
+ def _apply_category_probs(st: _State, req: dict[str, Any], preserve: bool) -> None:
989
+ from ectype.models.marginals import CategoricalMarginal
990
+
991
+ for col, probs in req.items():
992
+ cs = st.feature(col, "category_probs")
993
+ if cs.logical_type not in _CATEGORY:
994
+ raise ScenarioError(f"category_probs: column {col!r} is {cs.logical_type!s}, not "
995
+ f"categorical/boolean")
996
+ if not isinstance(probs, Mapping) or not probs:
997
+ raise ScenarioError(f"category_probs[{col!r}] must be a non-empty {{label: p}} "
998
+ f"mapping")
999
+ m = st.marginal(col)
1000
+ if not isinstance(m, CategoricalMarginal):
1001
+ raise ScenarioError(f"category_probs: marginal of {col!r} is {m.kind!r}, not "
1002
+ f"categorical")
1003
+ labels = [str(x) for x in m.labels]
1004
+ p_old = _probs(m)
1005
+ want: dict[int, float] = {}
1006
+ for lab, p in probs.items():
1007
+ key = _label_key(lab)
1008
+ if key not in labels:
1009
+ raise ScenarioError(f"category_probs[{col!r}]: label {key!r} does not exist; "
1010
+ f"labels are {labels}")
1011
+ v = _number(p, f"category_probs[{col!r}][{key!r}]")
1012
+ if not 0.0 <= v <= 1.0:
1013
+ raise ScenarioError(f"category_probs[{col!r}][{key!r}] must be in [0, 1], "
1014
+ f"got {v}")
1015
+ want[labels.index(key)] = v
1016
+ total = sum(want.values())
1017
+ if total > 1.0 + 1e-9:
1018
+ raise ScenarioError(f"category_probs[{col!r}]: requested probabilities sum to "
1019
+ f"{total:.6g} > 1")
1020
+ rest = [i for i in range(len(labels)) if i not in want]
1021
+ p_new = np.zeros(len(labels))
1022
+ for i, v in want.items():
1023
+ p_new[i] = v
1024
+ if not rest:
1025
+ if abs(total - 1.0) > 1e-6:
1026
+ raise ScenarioError(f"category_probs[{col!r}]: every label was given but the "
1027
+ f"probabilities sum to {total:.6g}, not 1")
1028
+ p_new = p_new / total
1029
+ else:
1030
+ rest_mass = float(p_old[rest].sum())
1031
+ if 1.0 - total > 1e-12:
1032
+ if rest_mass <= 0:
1033
+ raise ScenarioError(
1034
+ f"category_probs[{col!r}]: the unspecified labels have zero probability, "
1035
+ f"so the remaining mass {1 - total:.6g} cannot be distributed; specify "
1036
+ f"every label")
1037
+ p_new[rest] = p_old[rest] / rest_mass * (1.0 - total)
1038
+ elif rest_mass > 0:
1039
+ st.notes.append(f"{col}: the requested probabilities sum to 1, so the "
1040
+ f"unspecified labels get probability 0")
1041
+ if p_new.sum() <= 0:
1042
+ raise ScenarioError(f"category_probs[{col!r}]: all probabilities are zero")
1043
+ p_new = p_new / p_new.sum()
1044
+ new = CategoricalMarginal(np.asarray(labels), p_new)
1045
+ st.model.marginals[col] = new.to_spec(st.arrays, f"scenario.marginal.{col}.")
1046
+ for i, v in want.items():
1047
+ st.requested[f"category_probs[{col}][{labels[i]}]"] = v
1048
+ for i, lab in enumerate(labels):
1049
+ st.expected[f"__cat__[{col}][{lab}]"] = float(p_new[i])
1050
+ st.mark(col, "category")
1051
+ # conditional tree: refit this column's table, and move its children's marginals
1052
+ enc = st.model.encodings[col]
1053
+ cond = _conditional(enc)
1054
+ if cond is not None:
1055
+ parent = str(cond["parent"])
1056
+ p_par = _probs(st.marginal(parent))
1057
+ cpt = np.asarray(st.arrays.get(enc.arrays["cpt"]), dtype=float)
1058
+ if cpt.shape == (p_par.size, p_new.size):
1059
+ new_cpt = _ipf(cpt, p_par, p_new)
1060
+ arrays = dict(enc.arrays)
1061
+ arrays["cpt"] = st.arrays.put(f"scenario.encoding.{col}.cpt", new_cpt)
1062
+ st.model.encodings[col] = enc.model_copy(update={"arrays": arrays})
1063
+ st.notes.append(f"{col}: conditional table given {parent!r} re-fitted to the new "
1064
+ f"marginal (iterative proportional fitting)")
1065
+ else:
1066
+ st.notes.append(f"{col}: conditional table shape {cpt.shape} does not match; "
1067
+ f"left unchanged")
1068
+ elif enc.params.get("conditional") is not None:
1069
+ st.notes.append(f"{col}: encoding has an unrecognised conditional model; passed "
1070
+ f"through unchanged")
1071
+ for child, cspec in st.model.encodings.items():
1072
+ ccond = _conditional(cspec)
1073
+ if ccond is None or str(ccond["parent"]) != col:
1074
+ continue
1075
+ cpt = np.asarray(st.arrays.get(cspec.arrays["cpt"]), dtype=float)
1076
+ if cpt.shape[0] != p_new.size:
1077
+ continue
1078
+ cm = st.marginal(child)
1079
+ implied = p_new @ (cpt / np.clip(cpt.sum(axis=1, keepdims=True), 1e-300, None))
1080
+ if preserve and isinstance(cm, CategoricalMarginal):
1081
+ st.model.marginals[child] = CategoricalMarginal(cm.labels, implied).to_spec(
1082
+ st.arrays, f"scenario.marginal.{child}.")
1083
+ st.mark(child, "category_collateral")
1084
+ st.notes.append(f"{child}: depends on {col!r} through the conditional tree; its "
1085
+ f"category frequencies move with {col!r}")
1086
+
1087
+
1088
+ def _propagate_missing(st: _State, before: dict[str, float]) -> None:
1089
+ """A computed column is missing whenever one of its inputs is: after a change of an
1090
+ input's null rate, update the null rate of the computed columns that were not requested
1091
+ themselves (``before`` holds every column's null fraction before the request)."""
1092
+ for t in st.structure.transforms:
1093
+ col = t.target
1094
+ if col not in st.columns or "missing" in st.changed.get(col, set()):
1095
+ continue
1096
+ keep = 1.0
1097
+ for name in t.inputs:
1098
+ old, new = before.get(name, 0.0), float(st.columns[name].null_fraction)
1099
+ keep *= (1.0 - new) / (1.0 - old) if old < 1.0 else 1.0
1100
+ if abs(keep - 1.0) < 1e-12:
1101
+ continue
1102
+ cs = st.columns[col]
1103
+ rate = min(max(1.0 - (1.0 - before.get(col, 0.0)) * keep, 0.0), 1.0)
1104
+ st.columns[col] = cs.model_copy(
1105
+ update={"null_fraction": rate, "nullable": rate > 0 or cs.nullable})
1106
+ st.mark(col, "missing_dependent")
1107
+ st.notes.append(f"{col}: computed as {Structure.formula(t, hidden=False)}, so it is "
1108
+ f"missing whenever an input is; its null rate moves to about "
1109
+ f"{rate:.4g}")
1110
+
1111
+
1112
+ def _apply_missing(st: _State, req: dict[str, Any]) -> None:
1113
+ before = {name: float(c.null_fraction) for name, c in st.columns.items()}
1114
+ for col in st.structure.ordered(list(req)): # a base before what is computed from it
1115
+ r = req[col]
1116
+ cs = st.feature(col, "missing_rate")
1117
+ rate = _number(r, f"missing_rate[{col!r}]")
1118
+ if not 0.0 <= rate < 1.0:
1119
+ raise ScenarioError(f"missing_rate[{col!r}] must be in [0, 1), got {rate}")
1120
+ t = st.structure.transform(col)
1121
+ # the column of the model that carries the indicator, and the rate it needs
1122
+ name, model_rate = col, rate
1123
+ if t is not None:
1124
+ base, name = t.inputs[0], Structure.latent(t)
1125
+ base_rate = float(st.columns[base].null_fraction)
1126
+ if rate < base_rate - 1e-9:
1127
+ raise ScenarioError(
1128
+ f"infeasible: missing_rate[{col!r}] = {rate:g} is below the null rate of "
1129
+ f"{base!r} ({base_rate:g}). {col!r} is computed as "
1130
+ f"{Structure.formula(t, hidden=False)}, so it is missing whenever "
1131
+ f"{base!r} is; lower missing_rate[{base!r}] as well")
1132
+ # missing = base missing, or the gap's own indicator (independent of it)
1133
+ model_rate = min(max((rate - base_rate) / (1.0 - base_rate), 0.0), 1.0 - 1e-12)
1134
+ spec = st.model.missingness.get(name)
1135
+ if spec is not None:
1136
+ st.model.missingness[name] = spec.model_copy(
1137
+ update={"params": {**spec.params, "rate": model_rate}})
1138
+ elif t is None or model_rate > 0.0:
1139
+ joint = st.model.joint
1140
+ latent = _missing_name(name)
1141
+ if joint is None:
1142
+ pass
1143
+ elif joint.kind == GaussianCopula.kind:
1144
+ cop = GaussianCopula.from_spec(joint, st.arrays)
1145
+ d = len(cop.columns)
1146
+ r_new = np.eye(d + 1)
1147
+ r_new[:d, :d] = cop.corr
1148
+ st.model.joint = GaussianCopula([*cop.columns, latent], r_new,
1149
+ cop.shrinkage).to_spec(st.arrays,
1150
+ "scenario.joint.")
1151
+ elif joint.kind == IndependentJoint.kind:
1152
+ cols = [str(c) for c in joint.params.get("columns", [])] # type: ignore[union-attr]
1153
+ st.model.joint = IndependentJoint([*cols, latent]).to_spec(st.arrays, "joint")
1154
+ else:
1155
+ raise ScenarioError(f"missing_rate[{col!r}]: the column has no missingness "
1156
+ f"indicator and the joint model {joint.kind!r} cannot be "
1157
+ f"extended with one (a Gaussian copula can: fit with "
1158
+ f"effort='fast' or joint='gaussian_copula')")
1159
+ st.model.missingness[name] = ModelSpec(
1160
+ kind="bernoulli_indicator",
1161
+ params={"column": name, "rate": model_rate, "latent_column": latent})
1162
+ st.notes.append(f"{col}: new missingness indicator, independent of all other "
1163
+ f"columns")
1164
+ if t is not None:
1165
+ st.notes.append(
1166
+ f"{col}: computed as {Structure.formula(t, hidden=False)}; its null rate is "
1167
+ f"set through the missingness indicator of its gap (the hidden column {name}, "
1168
+ f"rate {model_rate:.4g}), on top of the rows where {t.inputs[0]!r} is missing")
1169
+ st.columns[col] = st.columns[col].model_copy(
1170
+ update={"null_fraction": rate, "nullable": rate > 0 or cs.nullable})
1171
+ st.requested[f"missing_rate[{col}]"] = rate
1172
+ st.expected[f"__miss__[{col}]"] = rate
1173
+ st.mark(col, "missing")
1174
+ _propagate_missing(st, before)
1175
+
1176
+
1177
+ def _apply_correlation(st: _State, req: Any, preserve: bool) -> dict[str, float]:
1178
+ items: list[tuple[str, str, Any]] = []
1179
+ if isinstance(req, Mapping):
1180
+ for k, v in req.items():
1181
+ if isinstance(k, str):
1182
+ parts = [p.strip() for p in k.split(",")]
1183
+ if len(parts) != 2:
1184
+ raise ScenarioError(f"correlation key {k!r} must be a pair (a, b)")
1185
+ k = tuple(parts)
1186
+ if not isinstance(k, tuple) or len(k) != 2:
1187
+ raise ScenarioError(f"correlation key {k!r} must be a pair (a, b)")
1188
+ items.append((str(k[0]), str(k[1]), v))
1189
+ else:
1190
+ for it in req:
1191
+ a, b, v = it
1192
+ items.append((str(a), str(b), v))
1193
+ joint = st.model.joint
1194
+ if joint is None or joint.kind != GaussianCopula.kind:
1195
+ raise ScenarioError(f"correlation changes need a gaussian_copula joint model; this "
1196
+ f"fingerprint has {None if joint is None else joint.kind!r} "
1197
+ f"(fit with effort='fast' or joint='gaussian_copula' to change "
1198
+ f"correlations)")
1199
+ cop = GaussianCopula.from_spec(joint, st.arrays)
1200
+ pos = {c: i for i, c in enumerate(cop.columns)}
1201
+ structure = st.structure
1202
+
1203
+ def slot(c: str) -> tuple[str, float]:
1204
+ """The copula column that stands for ``c`` and the direction ``c`` moves with it."""
1205
+ t = structure.transform(c)
1206
+ if c in pos or t is None:
1207
+ if c not in pos:
1208
+ raise ScenarioError(f"correlation: column {c!r} is not in the copula; latent "
1209
+ f"columns are {list(cop.columns)}")
1210
+ return c, 1.0
1211
+ st.feature(c, "correlation") # an identity target has no model: explains why
1212
+ return Structure.latent(t), Structure.sign(t)
1213
+
1214
+ pinned: dict[tuple[int, int], float] = {}
1215
+ spec_pairs: dict[tuple[str, str], float] = {}
1216
+ slots: dict[tuple[str, str], tuple[str, str, float]] = {}
1217
+ for a, b, v in items:
1218
+ (pa, sa), (pb, sb) = slot(a), slot(b)
1219
+ for c in (pa, pb):
1220
+ if c not in pos:
1221
+ raise ScenarioError(f"correlation: column {c!r} is not in the copula; latent "
1222
+ f"columns are {list(cop.columns)}")
1223
+ if a == b:
1224
+ raise ScenarioError(f"correlation: ({a}, {b}) is a diagonal entry")
1225
+ if (pa, pb) != (a, b) and structure.related(a, b):
1226
+ why = "; ".join(Structure.formula(t, hidden=False)
1227
+ for t in (structure.transform(a), structure.transform(b))
1228
+ if t is not None)
1229
+ raise ScenarioError(
1230
+ f"correlation: ({a}, {b}) cannot be set: the two columns are structurally "
1231
+ f"linked ({why}), so their dependence follows from the transform and is not a "
1232
+ f"correlation parameter of the model. What the model does have is the "
1233
+ f"dependence of a gap on the other columns of the copula: address the hidden "
1234
+ f"latent by name, e.g. correlation={{({pa!r}, {pb!r}): rho}}")
1235
+ rho = check_rho(v, f"correlation[({a}, {b})]")
1236
+ pinned[(pos[pa], pos[pb])] = sa * sb * rho
1237
+ spec_pairs[(a, b)] = rho
1238
+ slots[(a, b)] = (pa, pb, sa * sb)
1239
+ new = pinned_correlation(cop.corr, pinned, preserve=preserve)
1240
+ achieved: dict[str, float] = {}
1241
+ naive = cop.corr.copy()
1242
+ for (i, j), v in pinned.items():
1243
+ naive[i, j] = naive[j, i] = v
1244
+ slot_pairs = {(pa, pb): sign * spec_pairs[key] for key, (pa, pb, sign) in slots.items()}
1245
+ for (a, b), rho in spec_pairs.items():
1246
+ pa, pb, sign = slots[(a, b)]
1247
+ got = sign * float(new[pos[pa], pos[pb]])
1248
+ achieved[f"{a},{b}"] = got
1249
+ st.requested[f"correlation[{a},{b}]"] = rho
1250
+ if abs(got - rho) > PIN_RAISE:
1251
+ raise ScenarioError(
1252
+ f"infeasible: correlation ({a}, {b}) = {rho:+.3f} cannot be reached together "
1253
+ f"with the {'requested' if len(spec_pairs) > 1 else 'existing'} dependence "
1254
+ f"(nearest valid value {got:+.3f}). "
1255
+ + explain_not_pd(naive, cop.columns, slot_pairs))
1256
+ if abs(got - rho) > PIN_REPORT:
1257
+ st.infeasible.append(f"correlation ({a}, {b}): requested {rho:+.4f}, achieved "
1258
+ f"{got:+.4f} after projection to a valid correlation matrix")
1259
+ st.mark(a, "correlation")
1260
+ st.mark(b, "correlation")
1261
+ if (pa, pb) != (a, b):
1262
+ st.translated[f"{a},{b}"] = (pa, pb, sign)
1263
+ for c, p in ((a, pa), (b, pb)):
1264
+ t = structure.transform(c)
1265
+ if t is not None and p != c:
1266
+ st.notes.append(
1267
+ f"correlation ({a}, {b}): {c!r} is computed as "
1268
+ f"{Structure.formula(t, hidden=False)}, so the request sets the latent "
1269
+ f"correlation of its gap (the hidden column {p}); what {c!r} inherits "
1270
+ f"from {t.inputs[0]!r} is unchanged")
1271
+ # computed columns fed by the changed entry: their dependence on other columns moves,
1272
+ # and their own distribution too when both ends feed them
1273
+ for t in structure.transforms:
1274
+ feeds = structure.feeds(t.target)
1275
+ if {pa, pb} <= feeds and "gap" in st.changed.get(t.target, set()):
1276
+ st.notes.append(
1277
+ f"{t.target}: its mean_multiplier / scale request was solved with the "
1278
+ f"parent's dependence between {pa!r} and {pb!r}, which this request also "
1279
+ f"changes; see the achieved value")
1280
+ if t.target in (a, b) or not {pa, pb} & feeds:
1281
+ continue
1282
+ st.mark(t.target, "dependent" if {pa, pb} <= feeds else "correlation")
1283
+ moved = np.abs(new - cop.corr)
1284
+ for (i, j) in pinned:
1285
+ moved[i, j] = moved[j, i] = 0.0
1286
+ if float(moved.max(initial=0.0)) > 1e-6:
1287
+ k = int(np.sum(np.triu(moved, 1) > 1e-6))
1288
+ st.notes.append(f"correlation: {k} other latent correlation(s) adjusted to keep the "
1289
+ f"matrix positive definite (max change {float(moved.max()):.4f})")
1290
+ st.model.joint = GaussianCopula(cop.columns, new, cop.shrinkage).to_spec(
1291
+ st.arrays, "scenario.joint.")
1292
+ return achieved
1293
+
1294
+
1295
+ def _apply_seasonality(st: _State, req: dict[str, Any]) -> dict[str, float]:
1296
+ sec = st.manifest.temporal
1297
+ if sec is None or not sec.enabled:
1298
+ raise ScenarioError("seasonality_strength needs a temporal section; this fingerprint "
1299
+ "has none (manifest.temporal is absent)")
1300
+ data = sec.model_dump()
1301
+ kind = data.get("kind")
1302
+ applied: dict[str, float] = {}
1303
+ for col, f in req.items():
1304
+ factor = _number(f, f"seasonality_strength[{col!r}]")
1305
+ if factor < 0:
1306
+ raise ScenarioError(f"seasonality_strength[{col!r}] must be >= 0, got {factor}")
1307
+ if kind == "regular_series":
1308
+ holder = data.get("columns", {}).get(col)
1309
+ elif kind == "panel":
1310
+ holder = data.get("global", {}).get(col)
1311
+ else:
1312
+ raise ScenarioError(f"seasonality_strength: not supported for this temporal model "
1313
+ f"(section kind {kind!r})")
1314
+ if holder is None:
1315
+ raise ScenarioError(f"seasonality_strength: {col!r} is not a temporal value column "
1316
+ f"of this {kind} section")
1317
+ seasonal = holder.get("seasonal") or []
1318
+ if not seasonal:
1319
+ st.notes.append(f"{col}: no seasonal component; seasonality_strength has no effect")
1320
+ for s in seasonal:
1321
+ ref = s.get("coefficients")
1322
+ if not isinstance(ref, str) or ref not in st.arrays:
1323
+ raise ScenarioError("seasonality_strength: not supported for this temporal "
1324
+ "model (seasonal coefficients are not stored as arrays)")
1325
+ coef = np.asarray(st.arrays.get(ref), dtype=np.float64) * factor
1326
+ name = ref.removeprefix("arrays/").removesuffix(".npy")
1327
+ s["coefficients"] = st.arrays.put(f"scenario.{name}", coef)
1328
+ if isinstance(s.get("amplitude"), int | float):
1329
+ s["amplitude"] = float(s["amplitude"]) * factor
1330
+ applied[col] = factor
1331
+ st.requested[f"seasonality_strength[{col}]"] = factor
1332
+ st.manifest.temporal = ReservedSection.model_validate(data)
1333
+ return applied
1334
+
1335
+
1336
+ # ---------------------------------------------------------------------------------------------
1337
+ # measurement
1338
+ # ---------------------------------------------------------------------------------------------
1339
+
1340
+
1341
+ def _values(df: pl.DataFrame, cs: ColumnSchema) -> np.ndarray:
1342
+ from ectype.io.values import column_to_values
1343
+
1344
+ v = column_to_values(df[cs.name], cs) if cs.logical_type not in _CATEGORY else np.array([])
1345
+ return v[np.isfinite(v)]
1346
+
1347
+
1348
+ def _normal_scores(x: np.ndarray) -> np.ndarray:
1349
+ from scipy import special, stats
1350
+
1351
+ return special.ndtri(stats.rankdata(x) / (x.size + 1.0))
1352
+
1353
+
1354
+ def _measure(st: _State, base: pl.DataFrame, new: pl.DataFrame,
1355
+ corr_achieved: dict[str, float], seasonal: dict[str, float]
1356
+ ) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
1357
+ from ectype.io.values import category_labels
1358
+
1359
+ achieved: dict[str, Any] = {}
1360
+ checks: dict[str, dict[str, Any]] = {}
1361
+ n = max(new.height, 1)
1362
+
1363
+ def check(key: str, req: Any, got: Any, tol: float) -> None:
1364
+ achieved[key] = got
1365
+ ok = got is not None and abs(float(got) - float(req)) <= tol
1366
+ checks[key] = {"requested": req, "achieved": got, "tolerance": tol,
1367
+ "within_tolerance": bool(ok)}
1368
+
1369
+ for col, p in st.requested.get("__affine_params__", {}).items():
1370
+ cs = st.columns[col]
1371
+ xb, xn = _values(base, cs), _values(new, cs)
1372
+ if xb.size == 0 or xn.size == 0:
1373
+ continue
1374
+ mb, mn = float(xb.mean()), float(xn.mean())
1375
+ sb, sn = float(xb.std()), float(xn.std())
1376
+ se = 3.0 * max(sb, sn) / math.sqrt(xn.size)
1377
+ k = st.requested.get(f"mean_multiplier[{col}]")
1378
+ d = st.requested.get(f"shift[{col}]")
1379
+ f = st.requested.get(f"scale[{col}]")
1380
+ if k is not None:
1381
+ got = (mn - (d or 0.0)) / mb if abs(mb) > 1e-12 else None
1382
+ check(f"mean_multiplier[{col}]", k, got, 0.01 * k + se / max(abs(mb), 1e-12))
1383
+ if f is not None:
1384
+ got = sn / (sb * (k or 1.0)) if sb > 0 else None
1385
+ check(f"scale[{col}]", f, got, 0.02 * f + 3.0 / math.sqrt(xn.size))
1386
+ if d is not None:
1387
+ expected_mean = p["a"] + p["b"] * mb
1388
+ got = mn - (expected_mean - d)
1389
+ check(f"shift[{col}]", d, got, max(0.01 * abs(d), se, 1e-9))
1390
+ for key, rho in corr_achieved.items():
1391
+ a, b = key.split(",")
1392
+ req = st.requested[f"correlation[{a},{b}]"]
1393
+ ca, cb = st.columns.get(a), st.columns.get(b)
1394
+ measured = None
1395
+ if ca is not None and cb is not None and all(
1396
+ c.logical_type in (LogicalType.CONTINUOUS, LogicalType.DATETIME)
1397
+ for c in (ca, cb)):
1398
+ from ectype.io.values import column_to_values
1399
+ va, vb = column_to_values(new[a], ca), column_to_values(new[b], cb)
1400
+ ok = np.isfinite(va) & np.isfinite(vb)
1401
+ if ok.sum() > 10:
1402
+ measured = float(np.corrcoef(_normal_scores(va[ok]),
1403
+ _normal_scores(vb[ok]))[0, 1])
1404
+ if key in st.translated:
1405
+ # the request was translated to a hidden gap: what was set, and is checked, is the
1406
+ # latent correlation; the correlation of the computed column itself also carries
1407
+ # what it inherits from its base, so it is reported but not compared
1408
+ pa, pb, sign = st.translated[key]
1409
+ check(f"correlation[{a},{b}]", req, rho, PIN_REPORT)
1410
+ achieved[f"correlation[{a},{b}]"] = {"latent": rho,
1411
+ "measured_normal_scores": measured}
1412
+ checks[f"correlation[{a},{b}]"].update(
1413
+ {"latent": rho, "translated_to": [pa, pb], "sign": sign,
1414
+ "measured_normal_scores": measured})
1415
+ elif measured is None:
1416
+ check(f"correlation[{a},{b}]", req, rho, PIN_REPORT)
1417
+ achieved[f"correlation[{a},{b}]"] = {"latent": rho, "measured_normal_scores": None}
1418
+ else:
1419
+ tol = 0.03 + 3.0 * (1 - rho * rho) / math.sqrt(n)
1420
+ check(f"correlation[{a},{b}]", req, measured, tol)
1421
+ achieved[f"correlation[{a},{b}]"] = measured
1422
+ checks[f"correlation[{a},{b}]"]["latent"] = rho
1423
+ for key, v in st.requested.items():
1424
+ if key.startswith("category_probs["):
1425
+ col, lab = key[len("category_probs["):-1].split("][", 1)
1426
+ s = new[col].drop_nulls()
1427
+ m = max(s.len(), 1)
1428
+ got = float((category_labels(s) == lab).sum()) / m
1429
+ target = st.expected[f"__cat__[{col}][{lab}]"]
1430
+ check(key, v, got, 0.005 + 3.0 * math.sqrt(target * (1 - target) / m))
1431
+ elif key.startswith("missing_rate["):
1432
+ col = key[len("missing_rate["):-1]
1433
+ got = float(new[col].null_count()) / n
1434
+ check(key, v, got, 0.005 + 3.0 * math.sqrt(v * (1 - v) / n))
1435
+ for col, f in seasonal.items():
1436
+ check(f"seasonality_strength[{col}]", f, f, 0.0)
1437
+ return achieved, checks
1438
+
1439
+
1440
+ def _intended(target: Any, st: _State) -> bool:
1441
+ """Targets the request changes on purpose (never collateral)."""
1442
+ cols = list(target.columns)
1443
+ if len(cols) == 1 and st.changed.get(cols[0], set()) & {"affine", "category", "missing"}:
1444
+ return True
1445
+ if target.metric == "univariate.missing_rate" and "missing" in st.changed.get(cols[0], set()):
1446
+ return True
1447
+ if len(cols) == 2:
1448
+ key = {f"correlation[{cols[0]},{cols[1]}]", f"correlation[{cols[1]},{cols[0]}]"}
1449
+ if key & st.requested.keys():
1450
+ return True
1451
+ return False
1452
+
1453
+
1454
+ def _expected_to_move(st: _State) -> list[str]:
1455
+ out = []
1456
+ for t in st.parent.calibration.targets:
1457
+ if _intended(t, st):
1458
+ continue
1459
+ kinds = set().union(*(st.changed.get(c, set()) for c in t.columns))
1460
+ if not kinds:
1461
+ continue
1462
+ # "shifted" / "dependent" / "missing_dependent": a computed column that moves with an
1463
+ # input (an exact shift, any other change, or only its null rate)
1464
+ if kinds <= _AFFINE_KINDS and t.metric in AFFINE_INVARIANT:
1465
+ continue
1466
+ if t.metric == "univariate.missing_rate" and not kinds & _MISSING_KINDS:
1467
+ continue
1468
+ if kinds <= {"correlation"} and len(t.columns) == 1:
1469
+ continue
1470
+ if kinds <= _MISSING_KINDS and (
1471
+ (len(t.columns) == 2 and t.metric not in ("missingness.co_missing",))
1472
+ or (len(t.columns) == 1 and t.metric != "univariate.missing_rate")):
1473
+ continue
1474
+ out.append(t.id)
1475
+ return out
1476
+
1477
+
1478
+ def _collateral(st: _State, base: pl.DataFrame, new: pl.DataFrame,
1479
+ expected: list[str]) -> list[dict[str, Any]]:
1480
+ from ectype.fingerprint.targets import evaluate_target
1481
+
1482
+ policy = st.parent.manifest.disclosure_policy
1483
+ cols = {c.name: c for c in st.parent.manifest.columns}
1484
+ out = []
1485
+ exp = set(expected)
1486
+ for t in st.parent.calibration.targets:
1487
+ if _intended(t, st):
1488
+ continue
1489
+ try:
1490
+ d0, ok0 = evaluate_target(t, base, cols, policy)
1491
+ d1, ok1 = evaluate_target(t, new, cols, policy)
1492
+ except Exception: # noqa: BLE001 - a metric that cannot be evaluated is skipped
1493
+ continue
1494
+ if ok0 and not ok1:
1495
+ out.append({"id": t.id, "metric": t.metric, "columns": list(t.columns),
1496
+ "distance_before": d0, "distance_after": d1,
1497
+ "tolerance": t.tolerance, "expected": t.id in exp})
1498
+ return out
1499
+
1500
+
1501
+ # ---------------------------------------------------------------------------------------------
1502
+ # public API
1503
+ # ---------------------------------------------------------------------------------------------
1504
+
1505
+
1506
+ def mutate(fp: Fingerprint, *, column: str | None = None, shift: Any = None, scale: Any = None,
1507
+ mean_multiplier: Any = None, correlation: Any = None, category_probs: Any = None,
1508
+ missing_rate: Any = None, drift: Any = None, seasonality_strength: Any = None,
1509
+ temporal: str | None = None, preserve_dependencies: bool = True, seed: int = 0,
1510
+ n_sample: int = DEFAULT_SAMPLE) -> ScenarioResult:
1511
+ """Return a mutated copy of ``fp`` with diagnostics (see the module docstring)."""
1512
+ from ectype.generation.generator import Generator
1513
+ from ectype.profiling.reference import model_view
1514
+
1515
+ if n_sample < 100:
1516
+ raise ScenarioError(f"n_sample must be >= 100, got {n_sample}")
1517
+ gen_seed = sample_seed(seed)
1518
+ # the parent sample the result is measured against; a request on a column computed by a
1519
+ # structural transform is also solved on it, so it is generated on first use
1520
+ st = _State(fp, reference=lambda: model_view(
1521
+ Generator(fp).generate(int(n_sample), seed=gen_seed), fp.manifest))
1522
+ sh = _per_column("shift", shift, column)
1523
+ sc = _per_column("scale", scale, column)
1524
+ mm = _per_column("mean_multiplier", mean_multiplier, column)
1525
+ mr = _per_column("missing_rate", missing_rate, column)
1526
+ if drift is None:
1527
+ dr: dict[str, Any] = {}
1528
+ elif isinstance(drift, Mapping) and all(isinstance(v, Mapping) for v in drift.values()):
1529
+ dr = {str(k): v for k, v in drift.items()}
1530
+ elif column is not None:
1531
+ dr = {column: drift}
1532
+ else:
1533
+ raise ScenarioError("drift needs {column: {...}} or column=...")
1534
+ if category_probs is None:
1535
+ cp: dict[str, Any] = {}
1536
+ elif column is not None and isinstance(category_probs, Mapping) and not any(
1537
+ isinstance(v, Mapping) for v in category_probs.values()):
1538
+ cp = {column: category_probs}
1539
+ else:
1540
+ cp = _per_column("category_probs", category_probs, column)
1541
+ seas_col = temporal or column
1542
+ if seasonality_strength is None:
1543
+ ss: dict[str, Any] = {}
1544
+ elif isinstance(seasonality_strength, Mapping):
1545
+ ss = {str(k): v for k, v in seasonality_strength.items()}
1546
+ elif seas_col is not None:
1547
+ ss = {seas_col: seasonality_strength}
1548
+ else:
1549
+ sec = fp.manifest.temporal
1550
+ cols = list((sec.model_dump().get("value_cols") or []) if sec is not None else [])
1551
+ if not cols:
1552
+ raise ScenarioError("seasonality_strength needs a temporal section; this "
1553
+ "fingerprint has none (manifest.temporal is absent)")
1554
+ ss = {c: seasonality_strength for c in cols}
1555
+
1556
+ if dr:
1557
+ _expand_drift(dr, mm, sc, sh, mr, current_missing_rates(fp), st.notes)
1558
+ st.requested["drift"] = json_safe(dr)
1559
+ if not any((sh, sc, mm, mr, cp, correlation, ss)):
1560
+ raise ScenarioError("mutate: no change requested")
1561
+
1562
+ _apply_affine(st, sh, sc, mm)
1563
+ _apply_category_probs(st, cp, preserve_dependencies)
1564
+ _apply_missing(st, mr)
1565
+ corr_achieved = _apply_correlation(st, correlation, preserve_dependencies) \
1566
+ if correlation else {}
1567
+ seasonal = _apply_seasonality(st, ss) if ss else {}
1568
+
1569
+ st.manifest.columns = [st.columns[c.name] for c in st.manifest.columns]
1570
+ affine_params = st.requested.pop("__affine_params__", {})
1571
+ requested_public = json_safe({k: v for k, v in st.requested.items()})
1572
+ st.requested["__affine_params__"] = affine_params
1573
+ parent_hash = fp.content_hash()
1574
+ st.manifest.provenance.lineage = [*fp.manifest.provenance.lineage, {
1575
+ "op": "mutate", "parent": parent_hash, "changes": requested_public,
1576
+ "preserve_dependencies": bool(preserve_dependencies), "seed": int(seed)}]
1577
+
1578
+ draft = untargeted(st.manifest, st.arrays, fp.diagnostics)
1579
+ try:
1580
+ new_sample = model_view(Generator(draft).generate(int(n_sample), seed=gen_seed),
1581
+ draft.manifest)
1582
+ except Exception as exc: # noqa: BLE001
1583
+ raise ScenarioError(f"infeasible: the mutated fingerprint cannot generate data: "
1584
+ f"{exc}") from exc
1585
+ rows = st.rows()
1586
+ assert rows is not None
1587
+ base_sample = rows.frame
1588
+ achieved, checks = _measure(st, base_sample, new_sample, corr_achieved, seasonal)
1589
+ expected = _expected_to_move(st) if preserve_dependencies else []
1590
+ collateral = _collateral(st, base_sample, new_sample, expected)
1591
+ for key, c in checks.items():
1592
+ if not c["within_tolerance"] and not any(key in msg for msg in st.infeasible):
1593
+ st.infeasible.append(f"{key}: requested {c['requested']!r}, achieved "
1594
+ f"{c['achieved']!r} (tolerance {c['tolerance']:.4g}); the "
1595
+ f"generated population does not meet the request (constraints "
1596
+ f"or discretisation interfere)")
1597
+ st.notes.append("calibration and sealed targets were recomputed on a sample generated from "
1598
+ "the mutated model (seed stream 'scenario'); the parent's targets no longer "
1599
+ "describe this population")
1600
+ result = ScenarioResult(fingerprint=draft, requested=requested_public, achieved=achieved,
1601
+ checks=checks, collateral=collateral, expected_to_move=expected,
1602
+ infeasible=list(st.infeasible), notes=list(st.notes))
1603
+ diags = dict(fp.diagnostics)
1604
+ diags["scenario"] = result.to_dict()
1605
+ draft = untargeted(st.manifest, st.arrays, diags)
1606
+ out, _ = retarget(draft, n=n_sample, seed=gen_seed, op="mutate", sample=new_sample)
1607
+ result.fingerprint = out
1608
+ return result
1609
+
1610
+
1611
+ __all__ = ["AFFINE_INVARIANT", "AffineMarginal", "ScenarioResult", "affine_spec",
1612
+ "current_missing_rates", "json_safe", "linked_groups", "mutate", "retarget",
1613
+ "sample_seed", "untargeted"]