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,1392 @@
1
+ """``merge`` / ``interpolate`` / ``extrapolate`` (M26).
2
+
3
+ ``merge(fps, weights)`` builds a *modeled mixture* of compatible fingerprints (same columns,
4
+ logical types, roles and disclosure policy): a row of the merged population comes from
5
+ component ``k`` with probability ``w_k`` and then follows that component's full model
6
+ (marginals *and* dependence).
7
+
8
+ How it is stored (and why the unmodified :class:`~ectype.generation.Generator`
9
+ runs it):
10
+
11
+ * ``manifest.model.joint`` is a registered joint kind ``"mixture_of_fingerprints"``. Its params
12
+ embed every component's model section (column schemas, marginal/encoding/missingness specs
13
+ and joint spec); the components' arrays are copied into the merged store under namespaced
14
+ names (``mix<k>.<name>``) and all of them are listed in the joint spec's ``arrays`` so
15
+ container reference checks cover them. Its ``sample(n, rng)`` draws component labels by
16
+ weight, samples each component's latent scores and decodes them with the component's own
17
+ encoder, shuffles the rows, and **re-encodes** them with the merged (top-level) encoder.
18
+ A component's own hard constraints that another component violates are *scoped* to it
19
+ (``components[k]["constraints"]``): they are enforced by rejection inside that component's
20
+ sampling, so its rows always satisfy them and the component weights are unchanged.
21
+ * The top-level marginals are the exact mixtures of the component marginals: ``"mixture"``
22
+ (continuous/datetime; quantile by bisection), ``"discrete_mixture"`` (discrete; quantile on
23
+ the union support grid) and a plain ``categorical`` over the union of labels. Top-level
24
+ encodings are plain (unconditional) PIT / randomized PIT / frequency intervals with the
25
+ identity category order, so the generator's decode inverts the re-encoding exactly.
26
+ * ``manifest.population`` (a reserved section) describes the mixture for humans and tools:
27
+ ``kind="mixture_of_fingerprints"``, the weights and the component hashes.
28
+
29
+ Because the top-level marginals are separate from the joint's internal ones, a merged
30
+ fingerprint can still be mutated (``shift``, ``scale``, ``category_probs``, ``missing_rate`` on
31
+ an existing indicator); ``correlation`` changes need a Gaussian copula and are refused.
32
+
33
+ Structural transforms (format 0.3, ADR-0005)
34
+ --------------------------------------------
35
+ Every component is generated by its own model, *including its own transforms*: a component
36
+ section embeds them (``components[k]["transforms"]``, with the schemas of their targets), the
37
+ component's rows are decoded through them (``end = start + delta``, ``total = qty * price``)
38
+ and its hidden latents never leave it. Components may use different transforms; what the
39
+ merged (top-level) model does with a computed column depends on whether they agree:
40
+
41
+ * A transform that **every** component applies in the same way (same target, inputs, sign or
42
+ operator and unit; for an ``identity`` also the same precision) is kept at the top level.
43
+ For a ``difference`` the top-level latent is the exact mixture of the components' latents,
44
+ so the ordering holds by construction in the merged fingerprint as well; an ``identity``
45
+ target stays derived.
46
+ * A column that only **some** components compute (or compute differently) is modeled directly
47
+ at the top level, like any other column. A component that computes it has no marginal for
48
+ it, so that component's part of the mixture marginal (and its null rate) is *measured* on a
49
+ sample generated from the component and stored in its section
50
+ (``components[k]["measured"]``). The top-level encoding of such a column is exact up to
51
+ floating-point precision, like that of every directly modeled column.
52
+
53
+ A hard constraint that holds by construction in one component (through a transform) while
54
+ another component declares it and enforces it by rejection is enforced inside the latter's
55
+ sampling too (it is listed in ``merge_scoped_constraints`` and stays a constraint of the whole
56
+ mixture). Otherwise the merged generator would reject only that component's rows, and the
57
+ component shares would drift away from the weights.
58
+
59
+ ``interpolate(a, b, t)`` is ``merge([a, b], [1 - t, t])``: **population interpolation** (a
60
+ mixture in which a share ``t`` of the rows comes from ``b``), *not* parameter interpolation.
61
+ The mean of every column interpolates linearly, but a bimodal mixture is not "halfway between"
62
+ two unimodal populations.
63
+
64
+ ``extrapolate(fp, ...)`` is only defined for fingerprints with a temporal section; it delegates
65
+ to that section's model with a :class:`~ectype.temporal.TemporalRequest` in mode
66
+ ``"new_period"`` and returns the data together with the recorded extrapolation assumptions.
67
+ """
68
+
69
+ from __future__ import annotations
70
+
71
+ import math
72
+ import warnings
73
+ from collections.abc import Sequence
74
+ from dataclasses import dataclass, field
75
+ from typing import Any
76
+
77
+ import numpy as np
78
+ import polars as pl
79
+
80
+ from ectype.errors import EctypeError, ScenarioError
81
+ from ectype.fingerprint.core import ArrayStore, Fingerprint
82
+ from ectype.fingerprint.schema import (
83
+ CalendarSpec,
84
+ ColumnSchema,
85
+ ConstraintSpec,
86
+ DatasetInfo,
87
+ Manifest,
88
+ ModelSection,
89
+ ModelSpec,
90
+ Provenance,
91
+ ReservedSection,
92
+ TargetsSection,
93
+ TransformSpec,
94
+ )
95
+ from ectype.models.base import (
96
+ JOINTS,
97
+ MARGINALS,
98
+ JointModel,
99
+ MarginalModel,
100
+ joint_from_spec,
101
+ marginal_from_spec,
102
+ )
103
+ from ectype.models.copulas import IndependentJoint
104
+ from ectype.scenarios.feasibility import Structure, generated_columns
105
+ from ectype.scenarios.mutate import (
106
+ DEFAULT_SAMPLE,
107
+ AffineMarginal,
108
+ json_safe,
109
+ retarget,
110
+ sample_seed,
111
+ untargeted,
112
+ )
113
+ from ectype.types import LogicalType
114
+
115
+ MISSING_PREFIX = "__missing__"
116
+ _CATEGORY = (LogicalType.CATEGORICAL, LogicalType.BOOLEAN)
117
+ _BISECT = 64
118
+ MAX_GRID = 5_000_000
119
+ #: quantile levels of a marginal measured on a component sample (see ``measured_marginal``)
120
+ MEASURED_LEVELS = 2001
121
+ #: widest integer range a measured discrete marginal covers value by value
122
+ MEASURED_GRID = 200_000
123
+ #: total probability a measured discrete marginal spreads over the values the sample missed
124
+ MEASURED_FLOOR = 1e-6
125
+ #: smallest null rate recorded for a measured column that can be null (below it the top-level
126
+ #: missingness indicator could not be told from "observed" after the encoder's clipping)
127
+ MIN_NULL_RATE = 1e-6
128
+ #: transform parameters that do not change what a transform computes
129
+ _INFORMATIONAL = ("source", "constraint", "strict")
130
+
131
+
132
+ # ---------------------------------------------------------------------------------------------
133
+ # mixture marginals
134
+ # ---------------------------------------------------------------------------------------------
135
+
136
+
137
+ def _component_arrays(spec: ModelSpec, k: int) -> dict[str, str]:
138
+ pre = f"c{k}."
139
+ return {name[len(pre):]: ref for name, ref in spec.arrays.items() if name.startswith(pre)}
140
+
141
+
142
+ def mixture_spec(kind: str, components: Sequence[ModelSpec], weights: Sequence[float]
143
+ ) -> ModelSpec:
144
+ """Spec of a mixture built from existing component specs (no array copies)."""
145
+ arrays: dict[str, str] = {}
146
+ for k, c in enumerate(components):
147
+ arrays.update({f"c{k}.{n}": r for n, r in c.arrays.items()})
148
+ return ModelSpec(kind=kind, params={
149
+ "weights": [float(w) for w in weights],
150
+ "components": [{"kind": c.kind, "params": dict(c.params)} for c in components]},
151
+ arrays=arrays)
152
+
153
+
154
+ @MARGINALS.register()
155
+ class MixtureMarginal(MarginalModel):
156
+ """``F(x) = sum_k w_k F_k(x)`` over continuous components; quantiles by bisection between
157
+ the smallest and largest component quantile (which bracket the mixture quantile)."""
158
+
159
+ kind = "mixture"
160
+
161
+ def __init__(self, components: Sequence[MarginalModel],
162
+ weights: Sequence[float] | np.ndarray) -> None:
163
+ w = np.asarray(weights, dtype=np.float64)
164
+ if len(components) == 0 or w.shape != (len(components),) or np.any(w < 0) \
165
+ or not np.isfinite(w).all() or w.sum() <= 0:
166
+ raise ValueError("mixture marginal needs components and matching weights >= 0")
167
+ self.components = list(components)
168
+ self.weights = w / w.sum()
169
+
170
+ @classmethod
171
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> MixtureMarginal: # noqa: D102
172
+ raise NotImplementedError("mixture marginals are built by scenarios.merge, not fitted")
173
+
174
+ def cdf(self, x):
175
+ x = np.asarray(x, dtype=np.float64)
176
+ return sum(w * np.asarray(c.cdf(x), dtype=np.float64)
177
+ for w, c in zip(self.weights, self.components) if w > 0)
178
+
179
+ def cdf_left(self, x):
180
+ x = np.asarray(x, dtype=np.float64)
181
+ return sum(w * np.asarray(c.cdf_left(x), dtype=np.float64)
182
+ for w, c in zip(self.weights, self.components) if w > 0)
183
+
184
+ def ppf(self, u):
185
+ u = np.clip(np.asarray(u, dtype=np.float64), 1e-12, 1 - 1e-12)
186
+ qs = np.stack([np.asarray(c.ppf(u), dtype=np.float64)
187
+ for w, c in zip(self.weights, self.components) if w > 0])
188
+ lo, hi = qs.min(axis=0), qs.max(axis=0)
189
+ for _ in range(_BISECT):
190
+ mid = 0.5 * (lo + hi)
191
+ below = self.cdf(mid) < u
192
+ lo = np.where(below, mid, lo)
193
+ hi = np.where(below, hi, mid)
194
+ return hi
195
+
196
+ def logpdf(self, x):
197
+ parts = []
198
+ for w, c in zip(self.weights, self.components):
199
+ if w <= 0:
200
+ continue
201
+ lp = c.logpdf(x)
202
+ if lp is None:
203
+ return None
204
+ parts.append(np.log(w) + np.asarray(lp, dtype=np.float64))
205
+ return np.logaddexp.reduce(np.stack(parts), axis=0)
206
+
207
+ @property
208
+ def n_parameters(self) -> int:
209
+ return sum(c.n_parameters for c in self.components) + len(self.components)
210
+
211
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
212
+ specs = [c.to_spec(store, f"{prefix}c{k}.") for k, c in enumerate(self.components)]
213
+ return mixture_spec(self.kind, specs, self.weights)
214
+
215
+ @classmethod
216
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> MixtureMarginal:
217
+ comps = []
218
+ for k, c in enumerate(spec.params["components"]): # type: ignore[arg-type]
219
+ cs = ModelSpec(kind=str(c["kind"]), params=dict(c.get("params", {})),
220
+ arrays=_component_arrays(spec, k))
221
+ comps.append(marginal_from_spec(cs, store))
222
+ return cls(comps, [float(w) for w in spec.params["weights"]]) # type: ignore[union-attr]
223
+
224
+
225
+ def support_grid(m: MarginalModel) -> np.ndarray:
226
+ """Sorted support points of a discrete marginal (finite or truncated at 1e-12 tails)."""
227
+ if isinstance(m, AffineMarginal):
228
+ return m.a + m.b * support_grid(m.inner)
229
+ if isinstance(m, MixtureMarginal):
230
+ return np.unique(np.concatenate([support_grid(c) for w, c in
231
+ zip(m.weights, m.components) if w > 0]))
232
+ vals = getattr(m, "values", None)
233
+ if vals is not None:
234
+ return np.unique(np.asarray(vals, dtype=np.float64))
235
+ lo = float(np.asarray(m.ppf(np.array([1e-12])))[0])
236
+ hi = float(np.asarray(m.ppf(np.array([1 - 1e-12])))[0])
237
+ if not (math.isfinite(lo) and math.isfinite(hi)) or hi - lo > MAX_GRID:
238
+ raise ScenarioError(f"cannot build the support of discrete marginal {m.kind!r} for a "
239
+ f"mixture (range {lo}..{hi})")
240
+ return np.arange(math.floor(lo), math.ceil(hi) + 1, dtype=np.float64)
241
+
242
+
243
+ @MARGINALS.register()
244
+ class DiscreteMixtureMarginal(MixtureMarginal):
245
+ """Mixture of discrete marginals; the quantile is a lookup on the union support grid."""
246
+
247
+ kind = "discrete_mixture"
248
+ discrete = True
249
+
250
+ def __init__(self, components: Sequence[MarginalModel],
251
+ weights: Sequence[float] | np.ndarray) -> None:
252
+ super().__init__(components, weights)
253
+ self._grid = support_grid(self)
254
+ cum = np.asarray(self.cdf(self._grid), dtype=np.float64)
255
+ cum = np.maximum.accumulate(cum)
256
+ cum[-1] = 1.0
257
+ self._cum = cum
258
+
259
+ def ppf(self, u):
260
+ u = np.clip(np.asarray(u, dtype=np.float64), 1e-12, 1 - 1e-12)
261
+ j = np.searchsorted(self._cum, u, side="left")
262
+ return self._grid[np.minimum(j, self._grid.size - 1)]
263
+
264
+
265
+ # ---------------------------------------------------------------------------------------------
266
+ # top-level (merged) column models
267
+ # ---------------------------------------------------------------------------------------------
268
+
269
+
270
+ def _labels_probs(m: MarginalModel) -> tuple[list[str], np.ndarray]:
271
+ labels = [str(x) for x in m.labels] # type: ignore[attr-defined]
272
+ p = np.clip(np.asarray(m.probs, dtype=np.float64), 0, None) # type: ignore[attr-defined]
273
+ return labels, p / p.sum()
274
+
275
+
276
+ def _union_categorical(models: Sequence[MarginalModel], weights: np.ndarray
277
+ ) -> tuple[list[str], np.ndarray]:
278
+ from ectype.io.values import OTHER
279
+
280
+ labels: list[str] = []
281
+ for m in models:
282
+ for label in _labels_probs(m)[0]:
283
+ if label not in labels:
284
+ labels.append(label)
285
+ if OTHER in labels:
286
+ labels.remove(OTHER)
287
+ labels.append(OTHER)
288
+ probs = np.zeros(len(labels))
289
+ for w, m in zip(weights, models):
290
+ lab, p = _labels_probs(m)
291
+ for x, v in zip(lab, p):
292
+ probs[labels.index(x)] += w * v
293
+ return labels, probs / probs.sum()
294
+
295
+
296
+ def _top_marginal(col: ColumnSchema, models: Sequence[MarginalModel], weights: np.ndarray
297
+ ) -> MarginalModel:
298
+ from ectype.models.marginals import CategoricalMarginal
299
+
300
+ if col.logical_type in _CATEGORY:
301
+ labels, probs = _union_categorical(models, weights)
302
+ return CategoricalMarginal(np.asarray(labels), probs)
303
+ if col.logical_type == LogicalType.DISCRETE:
304
+ return DiscreteMixtureMarginal(models, weights)
305
+ return MixtureMarginal(models, weights)
306
+
307
+
308
+ def _encoding_spec(col: ColumnSchema, marginal: MarginalModel) -> ModelSpec:
309
+ from ectype.models.encoding import (
310
+ EPS,
311
+ KIND_FREQUENCY,
312
+ KIND_PIT,
313
+ KIND_RANDOMIZED,
314
+ )
315
+
316
+ params: dict[str, Any] = {"column": col.name, "logical_type": str(col.logical_type),
317
+ "eps": EPS, "attenuation": 1.0}
318
+ if col.logical_type in _CATEGORY:
319
+ k = len(marginal.labels) # type: ignore[attr-defined]
320
+ params.update({"n_categories": k, "category_order": list(range(k))})
321
+ return ModelSpec(kind=KIND_FREQUENCY, params=params)
322
+ kind = KIND_RANDOMIZED if col.logical_type == LogicalType.DISCRETE else KIND_PIT
323
+ return ModelSpec(kind=kind, params=params)
324
+
325
+
326
+ def _missing_rate(model: dict[str, Any], col: str) -> float:
327
+ spec = model["missingness"].get(col)
328
+ return 0.0 if spec is None else float(spec["params"].get("rate", 0.0))
329
+
330
+
331
+ def _merged_schema(schemas: Sequence[ColumnSchema], rate: float) -> ColumnSchema:
332
+ """The first component's schema of a column with the mixture's null rate and the union of
333
+ the components' support bounds."""
334
+ mins = [s.min_value for s in schemas]
335
+ maxs = [s.max_value for s in schemas]
336
+ return schemas[0].model_copy(update={
337
+ "null_fraction": min(max(rate, 0.0), 1.0),
338
+ "nullable": any(s.nullable for s in schemas) or rate > 0,
339
+ "min_value": None if any(v is None for v in mins) else min(mins), # type: ignore[type-var]
340
+ "max_value": None if any(v is None for v in maxs) else max(maxs), # type: ignore[type-var]
341
+ "n_unique": None,
342
+ })
343
+
344
+
345
+ def _component_models(comp: dict[str, Any], store: ArrayStore) -> dict[str, MarginalModel]:
346
+ """The marginals of a component: of its encoded columns and, measured on a sample, of the
347
+ transform targets the mixture models directly."""
348
+ specs = {**comp["marginals"],
349
+ **{c: m["marginal"] for c, m in comp.get("measured", {}).items()}}
350
+ return {c: marginal_from_spec(ModelSpec.model_validate(s), store) for c, s in specs.items()}
351
+
352
+
353
+ # ---------------------------------------------------------------------------------------------
354
+ # structural transforms in a mixture
355
+ # ---------------------------------------------------------------------------------------------
356
+
357
+
358
+ def _transforms(comp: dict[str, Any]) -> list[TransformSpec]:
359
+ return [TransformSpec.model_validate(t) for t in comp.get("transforms", [])]
360
+
361
+
362
+ def _core(t: TransformSpec) -> tuple[Any, ...]:
363
+ """What a transform computes, without its informational parameters. The precision of a
364
+ ``difference`` latent is left out too: it only rounds the decoded gap, and the mixture
365
+ can always use the finest one (see ``shared_transforms``)."""
366
+ skip = (*_INFORMATIONAL, *(("decimals",) if t.kind == "difference" else ()))
367
+ params = {k: v for k, v in t.params.items() if k not in skip}
368
+ return t.kind, t.target, tuple(t.inputs), sorted(params.items(), key=lambda kv: kv[0])
369
+
370
+
371
+ def shared_transforms(components: Sequence[dict[str, Any]]) -> list[TransformSpec]:
372
+ """The transforms every component applies in the same way (in the first component's
373
+ topological order): the mixture keeps these. The latent of a kept ``difference`` gets the
374
+ finest of the components' precisions (none at all if one of them does not round), so no
375
+ component's gaps are coarsened. The ``constraint`` parameter, an id in the component's own
376
+ manifest, is dropped."""
377
+ per = [{t.target: t for t in _transforms(c)} for c in components]
378
+ out = []
379
+ for t in _transforms(components[0]):
380
+ same = [p.get(t.target) for p in per]
381
+ if any(u is None or _core(u) != _core(t) for u in same):
382
+ continue
383
+ params = {k: v for k, v in t.params.items() if k != "constraint"}
384
+ if t.kind == "difference":
385
+ decimals = [u.params.get("decimals") for u in same if u is not None]
386
+ params["decimals"] = (None if any(d is None for d in decimals)
387
+ else max(int(d) for d in decimals if d is not None))
388
+ out.append(t.model_copy(update={"params": params}))
389
+ return out
390
+
391
+
392
+ def _source_columns(comp: dict[str, Any]) -> list[str]:
393
+ """The source columns a component generates, in manifest order."""
394
+ return list(comp.get("source_columns") or [c["name"] for c in comp["columns"]])
395
+
396
+
397
+ def _column_schemas(comp: dict[str, Any]) -> dict[str, ColumnSchema]:
398
+ """Schemas of a component's encoded columns (hidden latents included) and of its transform
399
+ targets."""
400
+ return {c["name"]: ColumnSchema.model_validate(c)
401
+ for c in [*comp["columns"], *comp.get("targets", [])]}
402
+
403
+
404
+ def _can_be_null(comp: dict[str, Any], col: str) -> bool:
405
+ """Whether a component can generate a null in ``col``: its own indicator or, for a column
406
+ a transform computes, a null input or a missing gap."""
407
+ t = next((t for t in _transforms(comp) if t.target == col), None)
408
+ if t is None:
409
+ return _missing_rate(comp, col) > 0
410
+ own = t.kind == "difference" and _missing_rate(comp, Structure.latent(t)) > 0
411
+ return own or any(_can_be_null(comp, c) for c in t.inputs)
412
+
413
+
414
+ def measured_marginal(values: np.ndarray, col: ColumnSchema) -> MarginalModel:
415
+ """The distribution of a column as a component generates it, measured on a sample of its
416
+ rows: what the mixture uses for a column the component computes through a transform (it
417
+ has no marginal of its own) but the mixture models directly.
418
+
419
+ The marginal has to cover every value the component can generate, not only those in the
420
+ sample, because the mixture re-encodes the component's rows with it and a value outside its
421
+ support would be moved. A continuous or datetime column gets a dense quantile grid with
422
+ wide exponential tails on both sides; a discrete one gets its sample frequencies over
423
+ every integer of a padded range, with a little mass (``MEASURED_FLOOR`` in total) spread
424
+ over the values the sample missed.
425
+ """
426
+ from ectype.models.marginals import DiscreteEmpiricalMarginal, EmpiricalMarginal
427
+
428
+ v = np.sort(np.asarray(values, dtype=np.float64)[np.isfinite(values)])
429
+ if v.size < 2:
430
+ raise ScenarioError(f"merge: a component generated fewer than two values of "
431
+ f"{col.name!r}; its distribution cannot be measured")
432
+ if col.logical_type == LogicalType.DISCRETE:
433
+ lo, hi = math.floor(v[0]), math.ceil(v[-1])
434
+ pad = max(10, math.ceil(0.5 * (hi - lo)))
435
+ if hi - lo + 2 * pad < MEASURED_GRID:
436
+ grid = np.arange(lo - pad, hi + pad + 1, dtype=np.float64)
437
+ counts = np.bincount((np.rint(v) - grid[0]).astype(np.int64), minlength=grid.size)
438
+ probs = (1.0 - MEASURED_FLOOR) * counts / v.size + MEASURED_FLOOR / grid.size
439
+ else: # too wide to enumerate: the values seen
440
+ grid, counts = np.unique(v, return_counts=True)
441
+ probs = counts / v.size
442
+ return DiscreteEmpiricalMarginal(grid, probs)
443
+ m = min(int(v.size), MEASURED_LEVELS)
444
+ levels = (np.arange(m, dtype=np.float64) + 0.5) / m
445
+ q = np.quantile(v, levels)
446
+ span = float(q[-1] - q[0]) or max(abs(float(q[0])), 1.0)
447
+ return EmpiricalMarginal(levels, q, lower_scale=span, upper_scale=span)
448
+
449
+
450
+ @dataclass
451
+ class _Top:
452
+ """The merged (top-level) model of a mixture, derived from its component sections alone
453
+ (so the manifest written by ``merge`` and the joint's own copy always agree)."""
454
+
455
+ #: encoded columns: the directly modeled source columns and, in place of their targets,
456
+ #: the latents of the shared ``difference`` transforms
457
+ columns: list[ColumnSchema]
458
+ marginals: dict[str, MarginalModel]
459
+ encodings: dict[str, ModelSpec]
460
+ missing: dict[str, ModelSpec]
461
+ #: the transforms every component shares (kept by the mixture)
462
+ transforms: list[TransformSpec]
463
+ #: merged schemas of the generated source columns
464
+ schemas: dict[str, ColumnSchema]
465
+ #: the generated source columns, in order
466
+ source: list[str]
467
+
468
+
469
+ def _top_level(components: Sequence[dict[str, Any]], weights: np.ndarray, store: ArrayStore
470
+ ) -> _Top:
471
+ from ectype.profiling.structure import latent_schema
472
+
473
+ transforms = shared_transforms(components)
474
+ shared = {t.target: t for t in transforms}
475
+ source = _source_columns(components[0])
476
+ comp_models = [_component_models(c, store) for c in components]
477
+ comp_schemas = [_column_schemas(c) for c in components]
478
+
479
+ def null_rate(k: int, name: str) -> float:
480
+ """Null rate of a source column in component ``k``."""
481
+ comp = components[k]
482
+ if name in comp["marginals"]:
483
+ return _missing_rate(comp, name)
484
+ if name in comp.get("measured", {}):
485
+ return float(comp["measured"][name]["missing_rate"])
486
+ return float(comp_schemas[k][name].null_fraction) # a shared transform target
487
+
488
+ top = _Top([], {}, {}, {}, transforms, {}, source)
489
+ for name in source:
490
+ missing_in = [k for k, s in enumerate(comp_schemas) if name not in s]
491
+ if missing_in:
492
+ raise ScenarioError(f"mixture component {missing_in[0]} does not generate column "
493
+ f"{name!r}")
494
+ rate = float(sum(w * null_rate(k, name) for k, w in enumerate(weights)))
495
+ top.schemas[name] = _merged_schema([s[name] for s in comp_schemas], rate)
496
+ t = shared.get(name)
497
+ if t is None: # modeled directly
498
+ encoded, col = name, top.schemas[name]
499
+ unmodeled = [k for k, cm in enumerate(comp_models) if name not in cm]
500
+ if unmodeled:
501
+ raise ScenarioError(
502
+ f"mixture component {unmodeled[0]} computes column {name!r} through a "
503
+ f"transform the other components do not share, but carries no measured "
504
+ f"marginal for it")
505
+ elif t.kind == "difference": # its latent, in its place
506
+ encoded = Structure.latent(t)
507
+ gap_rate = float(sum(w * _missing_rate(c, encoded)
508
+ for w, c in zip(weights, components)))
509
+ col = latent_schema(t).model_copy(update={
510
+ "null_fraction": min(max(gap_rate, 0.0), 1.0), "nullable": gap_rate > 0})
511
+ else: # an identity target stays derived
512
+ continue
513
+ m = _top_marginal(col, [cm[encoded] for cm in comp_models], weights)
514
+ top.columns.append(col)
515
+ top.marginals[encoded] = m
516
+ top.encodings[encoded] = _encoding_spec(col, m)
517
+ if col.null_fraction > 0:
518
+ top.missing[encoded] = ModelSpec(kind="bernoulli_indicator", params={
519
+ "column": encoded, "rate": float(col.null_fraction),
520
+ "latent_column": f"{MISSING_PREFIX}{encoded}"})
521
+ return top
522
+
523
+
524
+ def _encoder(columns: list[ColumnSchema], marginals: dict[str, MarginalModel],
525
+ encodings: dict[str, ModelSpec], missing: dict[str, ModelSpec],
526
+ store: ArrayStore | None) -> Any:
527
+ from ectype.models.encoding import MixedEncoder
528
+
529
+ specs = dict(encodings)
530
+ for col, spec in missing.items():
531
+ specs[f"{MISSING_PREFIX}{col}"] = spec
532
+ return MixedEncoder.from_specs(specs, marginals, columns, store)
533
+
534
+
535
+ class _TopEncoder:
536
+ """Re-encodes the rows of a mixture (source columns) with the merged encoder. For the
537
+ ``difference`` transforms the mixture keeps, the hidden gap is derived from the row first
538
+ (``sign * (target - base)``, never clamped). Where the base is null the gap says nothing
539
+ (the target is null whatever it is), so it gets a value of the latent's support: its
540
+ missingness indicator then keeps the meaning it has in a fitted fingerprint, "target
541
+ missing although its base is present"."""
542
+
543
+ def __init__(self, top: _Top, store: ArrayStore | None) -> None:
544
+ self.inner = _encoder(top.columns, top.marginals, top.encodings, top.missing, store)
545
+ self.transforms = list(top.transforms)
546
+ self.schemas = dict(top.schemas)
547
+ self.latent_columns = list(self.inner.latent_columns)
548
+ self._gaps = [(t, float(np.asarray(top.marginals[Structure.latent(t)].ppf(
549
+ np.array([0.5])))[0])) for t in top.transforms if t.kind == "difference"]
550
+
551
+ def encode(self, df: pl.DataFrame, rng: np.random.Generator) -> np.ndarray:
552
+ if self._gaps:
553
+ from ectype.io.values import column_to_values
554
+ from ectype.profiling.structure import forward
555
+
556
+ df, _ = forward(df, self.transforms, self.schemas, clamp=False)
557
+ for t, fill in self._gaps:
558
+ name, base = Structure.latent(t), t.inputs[0]
559
+ gap = df.get_column(name).to_numpy()
560
+ lost = ~np.isfinite(gap) & ~np.isfinite(
561
+ column_to_values(df.get_column(base), self.schemas[base]))
562
+ if lost.any():
563
+ df = df.with_columns(pl.Series(name, np.where(lost, fill, gap),
564
+ dtype=pl.Float64).fill_nan(None))
565
+ return self.inner.encode(df, rng)
566
+
567
+
568
+ # ---------------------------------------------------------------------------------------------
569
+ # the mixture joint
570
+ # ---------------------------------------------------------------------------------------------
571
+
572
+
573
+ @dataclass
574
+ class _Component:
575
+ encoder: Any
576
+ joint: JointModel
577
+ perm: np.ndarray | None
578
+ #: ``(id, enforced expression)`` of the hard constraints scoped to this component
579
+ constraints: list[tuple[str, Any]] = field(default_factory=list)
580
+
581
+
582
+ #: rounds of rejection sampling for a component's scoped hard constraints
583
+ SCOPED_MAX_ROUNDS = 50
584
+
585
+
586
+ @JOINTS.register()
587
+ class MixtureOfFingerprints(JointModel):
588
+ """Population mixture of fingerprint models (see the module docstring)."""
589
+
590
+ kind = "mixture_of_fingerprints"
591
+
592
+ def __init__(self, spec: ModelSpec, store: ArrayStore) -> None:
593
+ p = spec.params
594
+ comps: list[dict[str, Any]] = list(p["components"]) # type: ignore[arg-type]
595
+ self.weights = np.asarray(p["weights"], dtype=np.float64) # type: ignore[arg-type]
596
+ self.weights = self.weights / self.weights.sum()
597
+ self._cum = np.cumsum(self.weights)
598
+ self._cum[-1] = 1.0
599
+ self._spec = spec
600
+ self._components: list[_Component] = []
601
+ for comp in comps:
602
+ columns = [ColumnSchema.model_validate(c) for c in comp["columns"]]
603
+ marg = _component_models(comp, store)
604
+ enc_specs = {c: ModelSpec.model_validate(s) for c, s in comp["encodings"].items()}
605
+ miss_specs = {c: ModelSpec.model_validate(s) for c, s in comp["missingness"].items()}
606
+ encoder = _encoder(columns, marg, enc_specs, miss_specs, store)
607
+ joint = joint_from_spec(ModelSpec.model_validate(comp["joint"]), store)
608
+ latent = list(encoder.latent_columns)
609
+ perm = None
610
+ if list(joint.columns) != latent:
611
+ pos = {c: j for j, c in enumerate(joint.columns)}
612
+ if sorted(pos) != sorted(latent):
613
+ raise ScenarioError("mixture component joint columns do not match its "
614
+ "encoder")
615
+ perm = np.array([pos[c] for c in latent], dtype=np.int64)
616
+ transforms = _transforms(comp)
617
+ if transforms:
618
+ # the component's own transforms run inside its sampling: its rows come out in
619
+ # source columns, and its hidden latents never leave it
620
+ from ectype.profiling.structure import StructuredEncoder
621
+
622
+ encoder = StructuredEncoder(encoder, transforms, _column_schemas(comp))
623
+ self._components.append(_Component(encoder, joint, perm,
624
+ _scoped_nodes(comp.get("constraints", []))))
625
+ top = _top_level(comps, self.weights, store)
626
+ self._top = _TopEncoder(top, store)
627
+ self._schemas = top.schemas
628
+ self._source = top.source
629
+ self.columns = list(self._top.latent_columns)
630
+ declared = [str(c) for c in p.get("columns", [])] # type: ignore[union-attr]
631
+ if declared and declared != self.columns:
632
+ raise ScenarioError(f"mixture joint columns {declared} do not match the merged "
633
+ f"latent columns {self.columns}")
634
+
635
+ @classmethod
636
+ def fit(cls, z, columns, *, policy, rng=None) -> MixtureOfFingerprints: # noqa: D102
637
+ raise NotImplementedError("mixture joints are built by scenarios.merge, not fitted")
638
+
639
+ def component_labels(self, n: int, rng: np.random.Generator) -> np.ndarray:
640
+ k = np.searchsorted(self._cum, rng.random(n), side="right")
641
+ return np.minimum(k, len(self._components) - 1)
642
+
643
+ def sample_rows(self, n: int, rng: np.random.Generator) -> pl.DataFrame:
644
+ """Rows of the mixture (in source dtypes) with a ``__component__`` column."""
645
+ labels = self.component_labels(n, rng)
646
+ frames = []
647
+ for k, comp in enumerate(self._components):
648
+ nk = int(np.sum(labels == k))
649
+ if nk == 0:
650
+ continue
651
+ df = self._component_rows(k, comp, nk, rng)
652
+ frames.append(df.with_columns(pl.lit(k, dtype=pl.Int32).alias("__component__")))
653
+ df = pl.concat(frames, how="vertical_relaxed")
654
+ return df[rng.permutation(n)]
655
+
656
+ def _draw(self, comp: _Component, n: int, rng: np.random.Generator) -> pl.DataFrame:
657
+ z = comp.joint.sample(n, rng)
658
+ if comp.perm is not None:
659
+ z = z[:, comp.perm]
660
+ df = comp.encoder.decode(z, rng)
661
+ # components with different transforms decode their columns in different orders
662
+ return df if df.columns == self._source else df.select(self._source)
663
+
664
+ def _component_rows(self, k: int, comp: _Component, n: int,
665
+ rng: np.random.Generator) -> pl.DataFrame:
666
+ """``n`` decoded rows of component ``k`` that satisfy its scoped hard constraints
667
+ (rejection sampling; without scoped constraints a single draw, as before)."""
668
+ df = self._draw(comp, n, rng)
669
+ if not comp.constraints:
670
+ return df
671
+ from ectype.fingerprint import expressions
672
+
673
+ def ok_mask(frame: pl.DataFrame) -> np.ndarray:
674
+ good = np.ones(frame.height, dtype=bool)
675
+ for _, node in comp.constraints:
676
+ res = expressions.evaluate(node, frame)
677
+ if res.dtype != pl.Boolean:
678
+ res = res.cast(pl.Boolean)
679
+ good &= res.fill_null(True).to_numpy().astype(bool)
680
+ return good
681
+
682
+ good = ok_mask(df)
683
+ kept = [df.filter(pl.Series(good))]
684
+ have = int(good.sum())
685
+ rate = max(have / max(n, 1), 0.05)
686
+ for _ in range(SCOPED_MAX_ROUNDS):
687
+ if have >= n:
688
+ break
689
+ extra = self._draw(comp, max(int(math.ceil((n - have) / rate * 1.1)), 16), rng)
690
+ g = ok_mask(extra)
691
+ kept.append(extra.filter(pl.Series(g)))
692
+ have += int(g.sum())
693
+ rate = max(float(g.mean()), 0.01)
694
+ if have < n:
695
+ raise ScenarioError(
696
+ f"merge: component {k} could not satisfy its scoped hard constraint(s) "
697
+ f"{[c for c, _ in comp.constraints]} after {SCOPED_MAX_ROUNDS} rounds of "
698
+ f"rejection")
699
+ return pl.concat(kept, how="vertical_relaxed").head(n)
700
+
701
+ def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
702
+ if n == 0:
703
+ return np.zeros((0, len(self.columns)))
704
+ df = self.sample_rows(n, rng).drop("__component__")
705
+ return self._top.encode(df, rng)
706
+
707
+ @property
708
+ def n_parameters(self) -> int:
709
+ return sum(getattr(c.joint, "n_parameters", 0) for c in self._components)
710
+
711
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
712
+ missing = [r for r in self._spec.arrays.values() if r not in store]
713
+ if missing:
714
+ raise ScenarioError("a mixture_of_fingerprints joint can only be re-serialised "
715
+ "into the store that holds its component arrays")
716
+ return self._spec
717
+
718
+ @classmethod
719
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> MixtureOfFingerprints:
720
+ return cls(spec, store)
721
+
722
+
723
+ def _scoped_nodes(specs: Sequence[dict[str, Any]]) -> list[tuple[str, Any]]:
724
+ from ectype.compiler.plan import enforced_node
725
+
726
+ out = []
727
+ for d in specs:
728
+ spec = ConstraintSpec.model_validate(d)
729
+ out.append((spec.id, enforced_node(spec)))
730
+ return out
731
+
732
+
733
+ # ---------------------------------------------------------------------------------------------
734
+ # merge
735
+ # ---------------------------------------------------------------------------------------------
736
+
737
+
738
+ def _refs_in(obj: Any, known: ArrayStore) -> set[str]:
739
+ if isinstance(obj, dict):
740
+ return set().union(*(_refs_in(v, known) for v in obj.values())) if obj else set()
741
+ if isinstance(obj, list):
742
+ return set().union(*(_refs_in(v, known) for v in obj)) if obj else set()
743
+ if isinstance(obj, str) and obj.startswith("arrays/") and obj in known:
744
+ return {obj}
745
+ return set()
746
+
747
+
748
+ def _remap(obj: Any, mapping: dict[str, str]) -> Any:
749
+ if isinstance(obj, dict):
750
+ return {k: _remap(v, mapping) for k, v in obj.items()}
751
+ if isinstance(obj, list):
752
+ return [_remap(v, mapping) for v in obj]
753
+ if isinstance(obj, str) and obj in mapping:
754
+ return mapping[obj]
755
+ return obj
756
+
757
+
758
+ def _merged_references(fps: Sequence[Fingerprint]) -> dict[str, Any]:
759
+ """The surrogate-key specs of a mixture's reference columns (ADR-0013): integer keys
760
+ start above every component's source keys; text keys take the first component's prefix."""
761
+ out = {c: s.model_copy(deep=True) for c, s in fps[0].manifest.model.references.items()}
762
+ for i, fp in enumerate(fps[1:], start=1):
763
+ for col, spec in fp.manifest.model.references.items():
764
+ mine = out.get(col)
765
+ if mine is None or mine.kind != spec.kind:
766
+ raise ScenarioError(f"cannot merge: fingerprint {i} writes the reference keys "
767
+ f"of {col!r} in another way than fingerprint 0")
768
+ if "start" in spec.params:
769
+ mine.params["start"] = max(int(mine.params["start"]), # type: ignore[call-overload]
770
+ int(spec.params["start"])) # type: ignore[call-overload]
771
+ return out
772
+
773
+
774
+ def _check_compatible(fps: Sequence[Fingerprint]) -> None:
775
+ base = fps[0].manifest
776
+ grouped = [i for i, fp in enumerate(fps) if fp.manifest.model.entities]
777
+ if grouped:
778
+ raise ScenarioError(
779
+ f"cannot merge: fingerprint(s) {grouped} have entity groups (model.entities, "
780
+ f"ADR-0013), whose tables belong to one source; fit the fingerprints with "
781
+ f"structure='off' to merge them")
782
+ sig = [(c.name, str(c.logical_type), str(c.role)) for c in base.columns]
783
+ for i, fp in enumerate(fps[1:], start=1):
784
+ m = fp.manifest
785
+ other = [(c.name, str(c.logical_type), str(c.role)) for c in m.columns]
786
+ if other != sig:
787
+ diff = sorted(set(map(str, other)) ^ set(map(str, sig)))
788
+ raise ScenarioError(f"cannot merge: fingerprint {i} has a different schema than "
789
+ f"fingerprint 0 (columns, logical types or roles differ: "
790
+ f"{diff[:6]})")
791
+ if m.disclosure_policy != base.disclosure_policy:
792
+ raise ScenarioError(f"cannot merge: fingerprint {i} uses disclosure policy "
793
+ f"{m.disclosure_policy.profile!r}, fingerprint 0 uses "
794
+ f"{base.disclosure_policy.profile!r} (policies must match)")
795
+ if [(d.column, d.expression) for d in m.model.derived] != \
796
+ [(d.column, d.expression) for d in base.model.derived]:
797
+ raise ScenarioError(f"cannot merge: fingerprint {i} has different derived columns")
798
+ if m.model.sums or base.model.sums:
799
+ which = i if m.model.sums else 0
800
+ raise ScenarioError(
801
+ f"cannot merge: fingerprint {which} computes totals or parts "
802
+ f"(model.sums, {len(fps[which].manifest.model.sums)} sum(s)); a mixture of "
803
+ f"compositions is not supported. Fit the fingerprints with structure='off' to "
804
+ f"merge them")
805
+ # the generated source columns: components may reach them through different
806
+ # structural transforms (a hidden latent in one, the column itself in another)
807
+ if generated_columns(m) != generated_columns(base):
808
+ raise ScenarioError(f"cannot merge: fingerprint {i} models a different set of "
809
+ f"columns")
810
+ if m.model.constants != base.model.constants:
811
+ raise ScenarioError(f"cannot merge: fingerprint {i} has different constant columns "
812
+ f"({m.model.constants} vs {base.model.constants})")
813
+
814
+
815
+ def _component_section(fp: Fingerprint, k: int, store: ArrayStore) -> dict[str, Any]:
816
+ model = fp.manifest.model
817
+ transforms: list[TransformSpec] = []
818
+ if model.transforms:
819
+ # the encoded columns as the component's own generator sees them: each hidden latent
820
+ # where its target sits (the compiler also validates the transforms)
821
+ from ectype.compiler.plan import compile_plan
822
+
823
+ try:
824
+ plan = compile_plan(fp)
825
+ except EctypeError as exc:
826
+ raise ScenarioError(f"cannot merge: fingerprint {k} cannot be compiled: "
827
+ f"{exc}") from exc
828
+ features = [plan.schema_of(c) for c in plan.feature_columns]
829
+ transforms = list(plan.transforms)
830
+ else:
831
+ features = [c for c in fp.manifest.columns if c.name in model.encodings]
832
+ joint = model.joint
833
+ if joint is None:
834
+ names = [c.name for c in features]
835
+ latent = names + [f"{MISSING_PREFIX}{c}" for c in names if c in model.missingness]
836
+ joint = IndependentJoint(latent).to_spec(store, "unused")
837
+ raw = {
838
+ "columns": [c.model_dump(mode="json") for c in features],
839
+ "marginals": {c.name: model.marginals[c.name].model_dump(mode="json")
840
+ for c in features},
841
+ "encodings": {c.name: model.encodings[c.name].model_dump(mode="json")
842
+ for c in features},
843
+ "missingness": {c: s.model_dump(mode="json") for c, s in model.missingness.items()},
844
+ "joint": joint.model_dump(mode="json"),
845
+ }
846
+ if transforms:
847
+ schemas = {c.name: c for c in fp.manifest.columns}
848
+ generated = generated_columns(fp.manifest)
849
+ raw["transforms"] = [t.model_dump(mode="json") for t in transforms]
850
+ raw["targets"] = [schemas[t.target].model_dump(mode="json") for t in transforms]
851
+ raw["source_columns"] = [c.name for c in fp.manifest.columns if c.name in generated]
852
+ mapping = {}
853
+ for ref in sorted(_refs_in(raw, fp.arrays)):
854
+ name = ref.removeprefix("arrays/").removesuffix(".npy")
855
+ mapping[ref] = store.put(f"mix{k}.{name}", fp.arrays.get(ref))
856
+ return _remap(raw, mapping)
857
+
858
+
859
+ #: largest tolerated gap between a requested component weight and its achieved share
860
+ SHARE_TOLERANCE = 0.02
861
+
862
+
863
+ class _Samples:
864
+ """One sample generated from each component, on demand (each at most once)."""
865
+
866
+ def __init__(self, fps: Sequence[Fingerprint], *, seed: int, n: int, op: str) -> None:
867
+ self._fps, self._seed, self._n, self._op = fps, seed, n, op
868
+ self._cache: dict[int, pl.DataFrame] = {}
869
+
870
+ def __getitem__(self, k: int) -> pl.DataFrame:
871
+ from ectype.generation.generator import Generator
872
+ from ectype.profiling.reference import model_view
873
+
874
+ if k not in self._cache:
875
+ try:
876
+ self._cache[k] = model_view(Generator(self._fps[k]).generate(
877
+ max(int(self._n), 1),
878
+ seed=sample_seed(self._seed, self._op, "component", str(k))),
879
+ self._fps[k].manifest)
880
+ except Exception as exc: # noqa: BLE001
881
+ raise ScenarioError(f"merge: component {k} cannot generate data: {exc}") from exc
882
+ return self._cache[k]
883
+
884
+
885
+ def _shared_constraints(fps: Sequence[Fingerprint], samples: _Samples
886
+ ) -> tuple[list[ConstraintSpec], list[dict[str, Any]],
887
+ list[dict[str, Any]]]:
888
+ """Constraints of the merged fingerprint: ``(shared, scoped, dropped)``.
889
+
890
+ *Shared*: the union of the components' constraints, minus the *hard* ones that some
891
+ component's population violates (checked on a sample generated from every component). A
892
+ shared hard constraint applies to every merged row.
893
+
894
+ *Scoped*: a hard constraint that another component violates applies only to the rows of
895
+ the components that declare it (applying it to the whole mixture would reject the other
896
+ component's rows and distort the weights; dropping it would let the declaring component's
897
+ rows break it). It is enforced inside those components' sampling
898
+ (``MixtureOfFingerprints``). Each entry is ``{"id", "expression", "severity",
899
+ "tolerance", "components", "violated_by"}``.
900
+
901
+ A hard constraint that no component violates is also scoped (and stays shared) when it
902
+ holds by construction in one component, through a structural transform, while another
903
+ component declares it and enforces it by rejection. That component's candidate rows break
904
+ it and the first one's never do, so enforcing it only on the mixture would shift the
905
+ component shares; enforced inside the rejecting component's sampling, its rows follow
906
+ that component's own generator and the weights are kept.
907
+
908
+ *Dropped*: a hard constraint that cannot be scoped because it refers to columns the
909
+ component's model does not generate (derived, identifier or constant columns).
910
+ """
911
+ from ectype.compiler.plan import enforced_node
912
+ from ectype.fingerprint import expressions
913
+ from ectype.types import Enforcement, Severity
914
+
915
+ candidates: list[tuple[int, ConstraintSpec]] = []
916
+ owners: dict[str, list[int]] = {}
917
+ declared: dict[tuple[str, int], ConstraintSpec] = {}
918
+ for k, fp in enumerate(fps):
919
+ for c in fp.manifest.constraints.confirmed:
920
+ if c.expression not in owners:
921
+ owners[c.expression] = []
922
+ candidates.append((k, c))
923
+ if k not in owners[c.expression]:
924
+ owners[c.expression].append(k)
925
+ declared.setdefault((c.expression, k), c)
926
+ checked: list[pl.DataFrame] = []
927
+ if any(c.severity == Severity.HARD for _, c in candidates):
928
+ checked = [samples[k] for k in range(len(fps))]
929
+ # the source columns each component's model generates (through a transform or not)
930
+ generates = [generated_columns(fp.manifest) for fp in fps]
931
+ structures = [Structure(fp.manifest) for fp in fps]
932
+
933
+ kept: list[ConstraintSpec] = []
934
+ scoped: list[dict[str, Any]] = []
935
+ dropped: list[dict[str, Any]] = []
936
+ ids: set[str] = set()
937
+ for k, c in candidates:
938
+ rejecting: list[int] = []
939
+ if c.severity == Severity.HARD:
940
+ violated: list[dict[str, Any]] = []
941
+ for j, sample in enumerate(checked):
942
+ try:
943
+ res = expressions.evaluate(enforced_node(c), sample)
944
+ if res.dtype != pl.Boolean:
945
+ res = res.cast(pl.Boolean)
946
+ nv = int((~res.fill_null(True)).sum())
947
+ except Exception as exc: # noqa: BLE001
948
+ violated.append({"component": j, "error": f"{type(exc).__name__}: {exc}"})
949
+ continue
950
+ if nv:
951
+ violated.append({"component": j,
952
+ "violation_rate": nv / max(sample.height, 1)})
953
+ try:
954
+ refs = expressions.referenced_columns(c.expression)
955
+ except Exception: # noqa: BLE001
956
+ refs = {"<unparseable>"}
957
+ if violated:
958
+ comps = owners[c.expression]
959
+ generated = set.intersection(*(generates[j] for j in comps))
960
+ if refs <= generated:
961
+ scoped.append({"id": c.id, "expression": c.expression,
962
+ "severity": str(c.severity), "tolerance": float(c.tolerance),
963
+ "components": comps, "violated_by": violated,
964
+ "reason": "hard constraint of component(s) "
965
+ f"{comps} only; enforced on their rows"})
966
+ else:
967
+ dropped.append({"id": c.id, "expression": c.expression,
968
+ "from_component": k, "violated_by": violated,
969
+ "reason": "hard constraint not satisfied by every "
970
+ "component population and it refers to columns "
971
+ f"{sorted(refs - generated)} that are not "
972
+ "generated by the component model, so it "
973
+ "cannot be scoped to its component"})
974
+ continue
975
+ built = [j for j in range(len(fps)) if structures[j].implies(c.expression)]
976
+ if built:
977
+ rejecting = [j for j in owners[c.expression]
978
+ if j not in built and refs <= generates[j] and
979
+ declared[(c.expression, j)].enforcement != Enforcement.NONE]
980
+ cid = c.id if c.id not in ids else f"m{k}_{c.id}"
981
+ ids.add(cid)
982
+ kept.append(c.model_copy(update={"id": cid}))
983
+ if rejecting:
984
+ scoped.append({"id": cid, "expression": c.expression, "severity": str(c.severity),
985
+ "tolerance": float(c.tolerance), "components": rejecting,
986
+ "violated_by": [], "shared": True,
987
+ "reason": f"holds by construction (a structural transform) in "
988
+ f"component(s) {built} and is enforced by rejection in "
989
+ f"component(s) {rejecting}: enforced inside the latter's "
990
+ f"sampling so the component weights are kept, and still "
991
+ f"checked on every merged row"})
992
+ return kept, scoped, dropped
993
+
994
+
995
+ def _measure_direct_targets(fps: Sequence[Fingerprint], comps: list[dict[str, Any]],
996
+ samples: _Samples, store: ArrayStore) -> dict[int, list[str]]:
997
+ """For every component, measure the columns it computes through a transform that not every
998
+ component shares (see ``measured_marginal``) on a sample generated from it, and record the
999
+ marginal and null rate in its section. Returns those columns per component."""
1000
+ from ectype.io.values import column_to_values
1001
+
1002
+ shared = {t.target for t in shared_transforms(comps)}
1003
+ out: dict[int, list[str]] = {}
1004
+ for k, comp in enumerate(comps):
1005
+ names = [t.target for t in _transforms(comp) if t.target not in shared]
1006
+ if not names:
1007
+ continue
1008
+ sample, schemas = samples[k], _column_schemas(comp)
1009
+ measured: dict[str, Any] = {}
1010
+ for name in names:
1011
+ values = np.asarray(column_to_values(sample.get_column(name), schemas[name]),
1012
+ dtype=np.float64)
1013
+ rate = float(np.mean(~np.isfinite(values))) if values.size else 0.0
1014
+ if _can_be_null(comp, name):
1015
+ rate = max(rate, MIN_NULL_RATE)
1016
+ spec = measured_marginal(values, schemas[name]).to_spec(
1017
+ store, f"mix{k}.measured.{name}.")
1018
+ measured[name] = {"marginal": spec.model_dump(mode="json"),
1019
+ "missing_rate": min(rate, 1.0 - MIN_NULL_RATE),
1020
+ "n": int(values.size)}
1021
+ comp["measured"] = measured
1022
+ out[k] = names
1023
+ return out
1024
+
1025
+
1026
+ def _verify_shares(fp: Fingerprint, w: np.ndarray, *, seed: int, n: int, op: str
1027
+ ) -> dict[str, Any]:
1028
+ """Component shares the merged generator achieves after constraint rejection.
1029
+
1030
+ Rows are drawn from the mixture with their component labels; the share of component ``k``
1031
+ is ``w_k a_k / sum_j w_j a_j`` where ``a_k`` is the acceptance rate of its rows under the
1032
+ merged hard constraints. Raises :class:`ScenarioError` if any share deviates from its
1033
+ weight by more than ``SHARE_TOLERANCE``.
1034
+ """
1035
+ from ectype.generation.generator import Generator
1036
+ from ectype.rng import stream
1037
+
1038
+ gen = Generator(fp)
1039
+ joint = gen.joint
1040
+ if not isinstance(joint, MixtureOfFingerprints): # pragma: no cover - defensive
1041
+ return {}
1042
+ rows = joint.sample_rows(int(n), stream(seed, "scenario", op, "shares"))
1043
+ labels = rows.get_column("__component__").to_numpy()
1044
+ if gen.plan.constraints:
1045
+ bad = gen.rejection_mask(rows.drop("__component__"))
1046
+ else:
1047
+ bad = np.zeros(rows.height, dtype=bool)
1048
+ acc = np.ones(len(w))
1049
+ for k in range(len(w)):
1050
+ mk = labels == k
1051
+ if mk.any():
1052
+ acc[k] = 1.0 - float(bad[mk].mean())
1053
+ mass = w * acc
1054
+ if mass.sum() <= 0:
1055
+ raise ScenarioError("merge: the merged constraints reject every row of every "
1056
+ "component")
1057
+ achieved = mass / mass.sum()
1058
+ out = {"requested": [float(x) for x in w], "achieved": [float(x) for x in achieved],
1059
+ "acceptance": [float(x) for x in acc], "n": int(n),
1060
+ "tolerance": SHARE_TOLERANCE}
1061
+ gap = np.abs(achieved - w)
1062
+ if np.any(gap > SHARE_TOLERANCE):
1063
+ k = int(np.argmax(gap))
1064
+ raise ScenarioError(
1065
+ f"merge: constraint rejection changes the component shares: component {k} was "
1066
+ f"requested at {w[k]:.4f} but would make up {achieved[k]:.4f} of the rows "
1067
+ f"(acceptance per component {np.round(acc, 4).tolist()}; tolerance "
1068
+ f"{SHARE_TOLERANCE}). The hard constraints shared by all components reject one "
1069
+ f"component's rows much more often than another's.")
1070
+ return out
1071
+
1072
+
1073
+ def merge(fps: Sequence[Fingerprint], weights: Sequence[float] | None = None, *,
1074
+ seed: int = 0, n_sample: int = DEFAULT_SAMPLE, name: str | None = None,
1075
+ _op: str = "merge", _extra: dict[str, Any] | None = None) -> Fingerprint:
1076
+ """Weighted population mixture of compatible fingerprints (see the module docstring).
1077
+
1078
+ Targets of the result are recomputed on a sample generated from the merged model (seed
1079
+ stream ``"scenario"``); ``provenance.lineage`` records ``{"op": "merge", "parents": [...],
1080
+ "weights": [...]}``.
1081
+
1082
+ Constraints: the hard constraints that every component's population satisfies (checked
1083
+ on a generated sample of each component) apply to the whole mixture. A component-specific
1084
+ hard constraint is *scoped* to the component(s) that declare it: it is enforced inside
1085
+ their sampling, so their rows never violate it, and listed in
1086
+ ``manifest.diagnostics["merge_scoped_constraints"]``. One that cannot be scoped (it refers
1087
+ to derived, identifier or constant columns) is dropped with a warning and listed in
1088
+ ``manifest.diagnostics["merge_dropped_constraints"]``. The component
1089
+ shares achieved after constraint rejection are recorded in
1090
+ ``manifest.diagnostics["merge_component_shares"]``; a :class:`ScenarioError` is raised if
1091
+ one deviates from its weight by more than ``SHARE_TOLERANCE`` (2 percentage points).
1092
+
1093
+ Structural transforms (format 0.3): every component keeps its own and applies them inside
1094
+ its own sampling, and components may use different ones (or none). A transform every
1095
+ component shares is kept by the merged fingerprint, so its relationship holds by
1096
+ construction there too. A column only some components compute is modeled directly by the
1097
+ mixture; where a component computes it, its marginal is measured on a sample generated from
1098
+ that component (``n_sample`` rows, at most 4000). A hard constraint that holds by
1099
+ construction in one component and is enforced by rejection in another is enforced inside
1100
+ the latter's sampling as well, which keeps the weights.
1101
+ ``manifest.diagnostics["merge_transforms"]`` lists the kept transforms (``shared``) and the
1102
+ measured columns per component (``measured``).
1103
+ """
1104
+ fps = list(fps)
1105
+ if not fps:
1106
+ raise ScenarioError("merge needs at least one fingerprint")
1107
+ w = np.full(len(fps), 1.0 / len(fps)) if weights is None else \
1108
+ np.asarray([float(x) for x in weights], dtype=np.float64)
1109
+ if w.shape != (len(fps),):
1110
+ raise ScenarioError(f"merge: {len(fps)} fingerprints but {w.size} weights")
1111
+ if not np.all(np.isfinite(w)) or np.any(w < 0) or w.sum() <= 0:
1112
+ raise ScenarioError(f"merge: weights must be finite, >= 0 and not all zero; got "
1113
+ f"{w.tolist()}")
1114
+ w = w / w.sum()
1115
+ _check_compatible(fps)
1116
+ base = fps[0].manifest
1117
+ notes: list[str] = []
1118
+ if any(fp.manifest.temporal is not None for fp in fps):
1119
+ notes.append("temporal sections are not merged; the merged fingerprint has none")
1120
+
1121
+ store = ArrayStore()
1122
+ comps = [_component_section(fp, k, store) for k, fp in enumerate(fps)]
1123
+ samples = _Samples(fps, seed=seed, n=min(int(n_sample), 4000), op=_op)
1124
+ constraints, scoped, dropped = _shared_constraints(fps, samples)
1125
+ for entry in scoped:
1126
+ for k in entry["components"]:
1127
+ comps[k].setdefault("constraints", []).append(
1128
+ {"id": entry["id"], "expression": entry["expression"],
1129
+ "severity": entry["severity"], "tolerance": entry["tolerance"]})
1130
+ if scoped:
1131
+ notes.append(f"{len(scoped)} component-specific hard constraint(s) scoped to their "
1132
+ f"component's rows: {[(d['id'], d['components']) for d in scoped]}")
1133
+ # structural transforms: a column that only some components compute through a transform
1134
+ # is modeled directly by the mixture, from a marginal measured on those components
1135
+ measured = _measure_direct_targets(fps, comps, samples, store)
1136
+ top = _top_level(comps, w, store)
1137
+ top_cols, top_marg, top_enc, top_miss = top.columns, top.marginals, top.encodings, \
1138
+ top.missing
1139
+ if top.transforms:
1140
+ notes.append(f"{len(top.transforms)} structural transform(s) shared by every component "
1141
+ f"are kept: {[Structure.formula(t) for t in top.transforms]}")
1142
+ if measured:
1143
+ notes.append(f"column(s) computed through a transform in some components only are "
1144
+ f"modeled directly in the mixture (their marginal there is measured on a "
1145
+ f"sample generated from the component): {dict(sorted(measured.items()))}")
1146
+
1147
+ model = ModelSection()
1148
+ for col in top_cols:
1149
+ m = top_marg[col.name]
1150
+ if isinstance(m, MixtureMarginal):
1151
+ specs = [ModelSpec.model_validate(
1152
+ c["marginals"][col.name] if col.name in c["marginals"]
1153
+ else c["measured"][col.name]["marginal"]) for c in comps]
1154
+ model.marginals[col.name] = mixture_spec(m.kind, specs, w)
1155
+ else:
1156
+ model.marginals[col.name] = m.to_spec(store, f"marginal.{col.name}.")
1157
+ model.encodings = top_enc
1158
+ model.missingness = top_miss
1159
+ # a kept transform names the constraint it came from only if the mixture kept that one
1160
+ kept_ids = {c.expression: c.id for c in constraints}
1161
+ own = {c.id: c.expression for c in base.constraints.confirmed}
1162
+ origin = {t.target: t.params.get("constraint") for t in base.model.transforms}
1163
+ for t in top.transforms:
1164
+ cid = kept_ids.get(own.get(str(origin.get(t.target)), ""))
1165
+ model.transforms.append(t if cid is None else t.model_copy(
1166
+ update={"params": {**t.params, "constraint": cid}}))
1167
+ # an ordering enforced without a transform (format 0.4) is kept when every component
1168
+ # enforces the same one and the mixture models its target directly
1169
+ computed = {t.target for t in model.transforms}
1170
+ lost: list[str] = []
1171
+ for o in base.model.orderings:
1172
+ core = (o.target, sorted(o.lower), sorted(o.upper), o.method, o.strict)
1173
+ shared = all(any((x.target, sorted(x.lower), sorted(x.upper), x.method, x.strict) == core
1174
+ for x in fp.manifest.model.orderings) for fp in fps)
1175
+ usable = o.target in model.marginals and o.target not in computed and all(
1176
+ b in model.marginals or b in computed for b in [*o.lower, *o.upper])
1177
+ if shared and usable:
1178
+ model.orderings.append(o.model_copy(update={"constraints": [
1179
+ kept_ids[own[c]] for c in o.constraints if own.get(c) in kept_ids]}))
1180
+ else:
1181
+ lost.append(o.target)
1182
+ lost += [o.target for fp in fps[1:] for o in fp.manifest.model.orderings
1183
+ if o.target not in lost and all(o.target != k.target for k in model.orderings)]
1184
+ if model.orderings:
1185
+ notes.append(f"{len(model.orderings)} ordering(s) every component enforces by "
1186
+ f"redrawing the target are kept: {[o.target for o in model.orderings]}")
1187
+ if lost:
1188
+ notes.append(f"ordering(s) enforced by redrawing {sorted(set(lost))} in some "
1189
+ f"component are not enforced in the mixture (not shared by every "
1190
+ f"component, or the mixture does not model the column directly)")
1191
+ # a calendar (format 0.4, ADR-0012) is kept for a column every component has one for: the
1192
+ # mixture's rows are decoded once more at the top level, where the weekly pattern is
1193
+ # restored with the weighted mean of the components' kernels
1194
+ generated = set(model.marginals) | computed
1195
+ no_calendar: list[str] = []
1196
+ for cal in base.model.calendars:
1197
+ peers = [next((x for x in fp.manifest.model.calendars if x.column == cal.column), None)
1198
+ for fp in fps]
1199
+ same = [x for x in peers if x is not None
1200
+ and (x.period, x.unit, x.method) == (cal.period, cal.unit, cal.method)]
1201
+ if cal.column not in generated or len(same) != len(fps):
1202
+ no_calendar.append(cal.column)
1203
+ continue
1204
+ anchors = [a for a in cal.anchors if a in generated and all(a in x.anchors for x in same)]
1205
+ if all(x.kernel for x in same):
1206
+ kernel = sum(wk * np.asarray(x.kernel, dtype=np.float64) for wk, x in zip(w, same))
1207
+ profile = sum(wk * np.asarray(x.profile, dtype=np.float64) for wk, x in zip(w, same))
1208
+ model.calendars.append(cal.model_copy(update={
1209
+ "anchors": anchors, "base": cal.base if cal.base in anchors else None,
1210
+ "kernel": [[float(v) for v in row] for row in np.asarray(kernel)],
1211
+ "profile": [float(v) for v in np.asarray(profile)]}))
1212
+ else:
1213
+ model.calendars.append(CalendarSpec(column=cal.column, period=cal.period,
1214
+ unit=cal.unit, method=cal.method,
1215
+ anchors=anchors,
1216
+ base=cal.base if cal.base in anchors else None))
1217
+ no_calendar += [x.column for fp in fps[1:] for x in fp.manifest.model.calendars
1218
+ if x.column not in no_calendar
1219
+ and all(x.column != k.column for k in model.calendars)]
1220
+ if model.calendars:
1221
+ notes.append(f"{len(model.calendars)} calendar(s) every component has are kept, with "
1222
+ f"the weighted mean of the components' kernels: "
1223
+ f"{[c.column for c in model.calendars]}")
1224
+ if no_calendar:
1225
+ notes.append(f"the weekly pattern of {sorted(set(no_calendar))} is not restored in the "
1226
+ f"mixture (not every component has a calendar for the column, or the "
1227
+ f"mixture does not generate it by decoding)")
1228
+ latent = [c.name for c in top_cols] + [f"{MISSING_PREFIX}{c}" for c in
1229
+ [x.name for x in top_cols] if c in top_miss]
1230
+ joint_arrays: dict[str, str] = {}
1231
+ for k, comp in enumerate(comps):
1232
+ for i, ref in enumerate(sorted(_refs_in(comp, store))):
1233
+ joint_arrays[f"c{k}.{i}"] = ref
1234
+ model.joint = ModelSpec(kind=MixtureOfFingerprints.kind, params={
1235
+ "columns": latent, "weights": [float(x) for x in w], "components": comps},
1236
+ arrays=joint_arrays)
1237
+ model.identifiers = dict(base.model.identifiers)
1238
+ model.references = _merged_references(fps)
1239
+ model.constants = dict(base.model.constants)
1240
+ model.derived = list(base.model.derived)
1241
+ model.column_order = list(base.model.column_order)
1242
+
1243
+ if dropped:
1244
+ msg = (f"merge: {len(dropped)} component-specific hard constraint(s) dropped (not "
1245
+ f"satisfied by every component and not scopable to one): "
1246
+ f"{[d['id'] for d in dropped]}")
1247
+ notes.append(msg)
1248
+ warnings.warn(msg, UserWarning, stacklevel=2)
1249
+
1250
+ columns = [top.schemas.get(c.name, c) for c in base.columns]
1251
+ hashes = [fp.content_hash() for fp in fps]
1252
+ lineage = {"op": _op, "parents": hashes, "weights": [float(x) for x in w],
1253
+ **(_extra or {})}
1254
+ config = {"mode": _op, "weights": [float(x) for x in w], "components": hashes,
1255
+ "seed": int(seed), "n_sample": int(n_sample),
1256
+ "max_pairs": base.provenance.config.get("max_pairs", 200)}
1257
+ manifest = Manifest(
1258
+ dataset=DatasetInfo(
1259
+ name=name or f"{_op}(" + ", ".join(fp.manifest.dataset.name for fp in fps) + ")",
1260
+ source_records=int(sum(fp.manifest.dataset.source_records for fp in fps)),
1261
+ source_columns=base.dataset.source_columns,
1262
+ description=f"population mixture of {len(fps)} fingerprints"),
1263
+ columns=columns,
1264
+ disclosure_policy=base.disclosure_policy,
1265
+ model=model,
1266
+ targets=TargetsSection(seal_hash="0" * 64, sealed_fraction=base.targets.sealed_fraction,
1267
+ partition_seed=base.targets.partition_seed),
1268
+ provenance=Provenance(config=json_safe(config), fit_seed=int(seed),
1269
+ lineage=[json_safe(lineage)]),
1270
+ generation=base.generation.model_copy(),
1271
+ population=ReservedSection(
1272
+ enabled=True, kind=MixtureOfFingerprints.kind,
1273
+ interpretation="population mixture: each row comes from one component with "
1274
+ "probability equal to its weight (not parameter interpolation)",
1275
+ weights=[float(x) for x in w],
1276
+ components=[{"index": k, "dataset": fp.manifest.dataset.name, "hash": h,
1277
+ "source_records": fp.manifest.dataset.source_records}
1278
+ for k, (fp, h) in enumerate(zip(fps, hashes))]),
1279
+ )
1280
+ manifest.constraints.confirmed = constraints
1281
+ manifest.diagnostics["merge_dropped_constraints"] = json_safe(dropped)
1282
+ manifest.diagnostics["merge_scoped_constraints"] = json_safe(scoped)
1283
+ if top.transforms or measured:
1284
+ manifest.diagnostics["merge_transforms"] = json_safe({
1285
+ "shared": [Structure.formula(t) for t in top.transforms],
1286
+ "measured": {str(k): v for k, v in sorted(measured.items())}})
1287
+ draft = untargeted(manifest, store, {"scenario": {"op": _op, "notes": notes}})
1288
+ shares = _verify_shares(draft, w, seed=seed, n=max(int(n_sample), 2000), op=_op)
1289
+ manifest.diagnostics["merge_component_shares"] = json_safe(shares)
1290
+ draft = untargeted(manifest, store, {"scenario": {"op": _op, "notes": notes}})
1291
+ gen_seed = sample_seed(seed, _op)
1292
+ try:
1293
+ out, _ = retarget(draft, n=n_sample, seed=gen_seed, op=_op)
1294
+ except ScenarioError:
1295
+ raise
1296
+ except Exception as exc: # noqa: BLE001
1297
+ raise ScenarioError(f"the merged fingerprint cannot generate data: {exc}") from exc
1298
+ return out
1299
+
1300
+
1301
+ def interpolate(a: Fingerprint, b: Fingerprint, t: float, **kwargs: Any) -> Fingerprint:
1302
+ """Population interpolation: ``merge([a, b], [1 - t, t])``.
1303
+
1304
+ This is a *mixture* (a share ``t`` of rows comes from ``b``), not an interpolation of model
1305
+ parameters; means interpolate linearly but shapes become mixtures.
1306
+ """
1307
+ t = float(t)
1308
+ if not (math.isfinite(t) and 0.0 <= t <= 1.0):
1309
+ raise ScenarioError(f"interpolate: t must be in [0, 1], got {t}")
1310
+ return merge([a, b], [1.0 - t, t], _op="interpolate",
1311
+ _extra={"t": t, "assumption": "population mixture, not parameter "
1312
+ "interpolation"}, **kwargs)
1313
+
1314
+
1315
+ def generate_merged(fp: Fingerprint, n: int, seed: int | None = None) -> pl.DataFrame:
1316
+ """Generate from a merged fingerprint. The standard generator handles the registered
1317
+ ``mixture_of_fingerprints`` joint, so this is ``Generator(fp).generate(n, seed)``."""
1318
+ from ectype.generation.generator import Generator
1319
+
1320
+ return Generator(fp).generate(int(n), seed=seed)
1321
+
1322
+
1323
+ def component_proportions(fp: Fingerprint, n: int, seed: int = 0) -> np.ndarray:
1324
+ """Empirical component shares of ``n`` mixture draws (diagnostic)."""
1325
+ from ectype.rng import stream
1326
+
1327
+ spec = fp.manifest.model.joint
1328
+ if spec is None or spec.kind != MixtureOfFingerprints.kind:
1329
+ raise ScenarioError("not a merged fingerprint")
1330
+ joint = MixtureOfFingerprints.from_spec(spec, fp.arrays)
1331
+ labels = joint.component_labels(int(n), stream(seed, "scenario", "proportions"))
1332
+ return np.bincount(labels, minlength=len(joint.weights)) / max(int(n), 1)
1333
+
1334
+
1335
+ # ---------------------------------------------------------------------------------------------
1336
+ # extrapolate
1337
+ # ---------------------------------------------------------------------------------------------
1338
+
1339
+
1340
+ @dataclass
1341
+ class ExtrapolationResult:
1342
+ data: pl.DataFrame
1343
+ request: dict[str, Any]
1344
+ model_kind: str
1345
+ assumptions: list[str] = field(default_factory=list)
1346
+
1347
+
1348
+ def _temporal_model(section: dict[str, Any], store: ArrayStore) -> Any:
1349
+ kind = section.get("kind")
1350
+ if kind == "regular_series":
1351
+ from ectype.temporal.regular import RegularSeriesModel
1352
+ return RegularSeriesModel.from_section(section, store)
1353
+ if kind == "panel":
1354
+ from ectype.temporal.panel import PanelModel
1355
+ return PanelModel.from_section(section, store)
1356
+ raise ScenarioError(f"extrapolate: not supported for this temporal model (section kind "
1357
+ f"{kind!r})")
1358
+
1359
+
1360
+ def extrapolate(fp: Fingerprint, *, seed: int = 0, **request: Any) -> ExtrapolationResult:
1361
+ """Simulate a future period from the fingerprint's temporal section.
1362
+
1363
+ ``request`` holds :class:`~ectype.temporal.TemporalRequest` fields (``periods``,
1364
+ ``start``, ``end``, ``n_entities``, ...); the mode is always ``"new_period"``. Trend
1365
+ extrapolation is an explicit modeling assumption, returned in ``assumptions``.
1366
+ """
1367
+ from ectype.temporal.contract import TemporalRequest
1368
+
1369
+ sec = fp.manifest.temporal
1370
+ if sec is None or not sec.enabled:
1371
+ raise ScenarioError("extrapolate needs a temporal section; this fingerprint has none "
1372
+ "(use mutate/merge for cross-sectional scenarios)")
1373
+ if request.get("mode", "new_period") != "new_period":
1374
+ raise ScenarioError("extrapolate always uses mode='new_period'")
1375
+ request = {k: v for k, v in request.items() if k != "mode"}
1376
+ section = sec.model_dump()
1377
+ model = _temporal_model(section, fp.arrays)
1378
+ req = TemporalRequest(mode="new_period", **request)
1379
+ data = model.generate(req, int(seed))
1380
+ assumptions = [str(a) for a in (getattr(model, "assumptions", None) or
1381
+ section.get("assumptions") or [])]
1382
+ assumptions.append("extrapolate: the fitted trend and seasonality are projected beyond the "
1383
+ "observed window; this is a modeling assumption, not a forecast "
1384
+ "guarantee")
1385
+ return ExtrapolationResult(data=data, request=req.model_dump(mode="json"),
1386
+ model_kind=str(section.get("kind")), assumptions=assumptions)
1387
+
1388
+
1389
+ __all__ = ["SHARE_TOLERANCE", "DiscreteMixtureMarginal", "ExtrapolationResult", "MixtureMarginal",
1390
+ "MixtureOfFingerprints", "component_proportions", "extrapolate", "generate_merged",
1391
+ "interpolate", "measured_marginal", "merge", "mixture_spec", "shared_transforms",
1392
+ "support_grid"]