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 @@
1
+
@@ -0,0 +1,678 @@
1
+ """Compile a fingerprint into a deterministic generation plan (§5.1).
2
+
3
+ ``compile_plan(fp)``:
4
+
5
+ 1. validates that every model kind in the manifest is registered (marginals, joint, encodings,
6
+ missingness, identifiers);
7
+ 2. topologically sorts derived columns by the columns their expressions reference and fails
8
+ with :class:`ConstraintError` on a cycle;
9
+ 3. type-checks every derived expression and hard constraint (``expressions.check``) and
10
+ compiles it to a native Polars expression;
11
+ 4. classifies constraints by the enforcement the generator will actually use;
12
+ 5. records the output column order (``model.column_order``; derived columns stay where the
13
+ source had them, derived columns unknown to the source are appended);
14
+ 6. validates the structural transforms (``model.transforms``, format 0.3, ADR-0005) and orders
15
+ them topologically. A ``difference`` target is modeled through its hidden latent
16
+ (``params["latent"]``, an encoded feature that never appears in the output); an
17
+ ``identity`` target is derived. Both are produced columns that derived expressions and
18
+ constraints may reference; the latents are not. A transform this engine does not fully
19
+ understand (unknown kind or parameter) is a :class:`FingerprintError`;
20
+ 7. validates the orderings enforced without a transform (``model.orderings``, format 0.4,
21
+ ADR-0009) and merges them with the transforms into the steps that run after decoding
22
+ (``Plan.steps``): the target of an ordering is a modeled feature that keeps its marginal,
23
+ and rows that break the ordering get a new value from that marginal truncated at the
24
+ bound. An ordering with a method this engine does not know is a :class:`FingerprintError`;
25
+ 8. validates the calendars (``model.calendars``, format 0.4, ADR-0012): the weekly pattern of
26
+ date columns, restored on the decoded rows after the transforms and orderings
27
+ (``Plan.calendars``, in the order they run). A calendar with a method or period this
28
+ engine does not know is a :class:`FingerprintError`;
29
+ 9. validates the entity groups (``model.entities``, format 0.4, ADR-0013) and loads their
30
+ tables (``Plan.entities``, in the order they run): the key and the attributes are decoded
31
+ columns, and after decoding (and after the calendars) an attribute of a row is replaced by
32
+ the entry of its key. A group with a method this engine does not know is a
33
+ :class:`FingerprintError`;
34
+ 10. validates the reference keys (``model.references``, format 0.4, ADR-0013): a
35
+ ``reference`` column is an encoded feature holding group sizes until the generator writes
36
+ fresh keys for the accepted rows, so, like an identifier, it cannot be an input of a
37
+ derived column or a constraint;
38
+ 11. validates the sums (``model.sums``, format 0.4, ADR-0014) and orders them: the parts of a
39
+ ``split`` are computed from their total and the hidden shares (encoded features that never
40
+ appear in the output, like the latent of a difference), the total of a ``sum`` from its
41
+ parts, after the calendars and before the entity groups (``Plan.sums``). A sum with a
42
+ mode or rounding this engine does not know is a :class:`FingerprintError`.
43
+
44
+ Enforcement semantics (recorded per constraint in ``Plan.enforcement``):
45
+
46
+ * ``rejection`` -- rows whose expression evaluates to ``false`` are dropped and replaced.
47
+ * ``repair`` -- supported for simple bounds on a sampled numeric column (``col >= c``,
48
+ ``col <= c``, ``col > c``, ``col < c``, mirrored forms, and ``and``-conjunctions of them):
49
+ values are clamped to the bound. Any other repair constraint falls back to ``rejection``.
50
+ * ``derivation`` -- the constraint is expected to hold by construction because it involves a
51
+ derived column; if it references no derived column it falls back to ``rejection``.
52
+ * ``support`` -- expected to hold by the model's support.
53
+
54
+ Every *hard* constraint is additionally checked on every generated row whatever its
55
+ enforcement, and violating rows are rejected (a safety net, so hard constraints hold on 100% of
56
+ output rows; residual violations are counted in the generation manifest). Soft constraints and
57
+ ``enforcement == none`` are measured only and never enforced.
58
+
59
+ **Null semantics:** like SQL ``CHECK``, a constraint whose expression evaluates to ``null`` for
60
+ a row (for example because an operand is null) counts as *satisfied*.
61
+
62
+ A non-zero ``tolerance`` on a constraint of the form ``a == b`` is compiled to
63
+ ``abs(a - b) <= tolerance``; tolerance is ignored for other forms.
64
+ """
65
+
66
+ from __future__ import annotations
67
+
68
+ from dataclasses import dataclass, field
69
+ from typing import Any
70
+
71
+ import polars as pl
72
+
73
+ from ectype.errors import ConstraintError, ExpressionError, FingerprintError
74
+ from ectype.fingerprint import expressions as ex
75
+ from ectype.fingerprint.core import Fingerprint
76
+ from ectype.fingerprint.schema import (
77
+ CalendarSpec,
78
+ ColumnSchema,
79
+ ConstraintSpec,
80
+ ModelSpec,
81
+ OrderingSpec,
82
+ SumSpec,
83
+ TransformSpec,
84
+ )
85
+ from ectype.profiling.calendar import check_calendars
86
+ from ectype.profiling.entity import EntityTable, array_refs, check_entities, load_tables
87
+ from ectype.profiling.reference import check_references
88
+ from ectype.profiling.structure import (
89
+ check_orderings,
90
+ check_transforms,
91
+ latent_schema,
92
+ order_steps,
93
+ order_transforms,
94
+ )
95
+ from ectype.profiling.sums import (
96
+ check_sums,
97
+ computed_columns,
98
+ order_sums,
99
+ scaled_columns,
100
+ share_schemas,
101
+ sum_text,
102
+ )
103
+ from ectype.types import Enforcement, LogicalType, Role, Severity
104
+
105
+ ENCODING_KINDS = {"pit", "randomized_pit", "frequency_interval"}
106
+ MISSINGNESS_KINDS = {"bernoulli_indicator"}
107
+
108
+ _FLIP = {">=": "<=", "<=": ">=", ">": "<", "<": ">"}
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class Bound:
113
+ """One clamp: ``column (op) value`` with ``op`` in ``>= <= > <``."""
114
+
115
+ column: str
116
+ op: str
117
+ value: float
118
+
119
+
120
+ @dataclass
121
+ class CompiledConstraint:
122
+ spec: ConstraintSpec
123
+ expr: pl.Expr
124
+ columns: set[str]
125
+ enforcement: Enforcement # effective enforcement used by the generator
126
+ bounds: list[Bound] = field(default_factory=list) # repair only
127
+
128
+ @property
129
+ def id(self) -> str:
130
+ return self.spec.id
131
+
132
+
133
+ @dataclass
134
+ class CompiledDerived:
135
+ column: str
136
+ expression: str
137
+ expr: pl.Expr
138
+ depends_on: set[str]
139
+
140
+
141
+ @dataclass
142
+ class Plan:
143
+ fingerprint_hash: str
144
+ schemas: dict[str, ColumnSchema]
145
+ feature_columns: list[str] # encoded columns (incl. hidden latents)
146
+ identifiers: dict[str, ModelSpec]
147
+ constants: dict[str, Any]
148
+ unmodeled: list[str] # in column_order but no generator: null-filled
149
+ derived: list[CompiledDerived] # topological order
150
+ constraints: list[CompiledConstraint] # all hard constraints, checked on every row
151
+ measured: list[ConstraintSpec] # soft / enforcement none: never enforced
152
+ output_columns: list[str]
153
+ notes: list[str] = field(default_factory=list)
154
+ #: structural transforms in topological order (applied right after decoding)
155
+ transforms: list[TransformSpec] = field(default_factory=list)
156
+ #: schemas of the hidden latent columns of ``difference`` transforms (never output)
157
+ latent_schemas: dict[str, ColumnSchema] = field(default_factory=dict)
158
+ #: orderings enforced by a truncated redraw of their target (format 0.4)
159
+ orderings: list[OrderingSpec] = field(default_factory=list)
160
+ #: transforms and orderings in the order they run right after decoding
161
+ steps: list[TransformSpec | OrderingSpec] = field(default_factory=list)
162
+ #: weekly patterns restored on the decoded rows after the steps, in the order they run
163
+ calendars: list[CalendarSpec] = field(default_factory=list)
164
+ #: entity groups with their tables, in the order they run after decoding (format 0.4)
165
+ entities: list[EntityTable] = field(default_factory=list)
166
+ #: surrogate-key specs of the ``reference`` columns (format 0.4)
167
+ references: dict[str, ModelSpec] = field(default_factory=dict)
168
+ #: totals and parts computed last, in the order they run (format 0.4, ADR-0014); the
169
+ #: schemas of their hidden shares are in ``latent_schemas``
170
+ sums: list[SumSpec] = field(default_factory=list)
171
+
172
+ @property
173
+ def hidden_columns(self) -> list[str]:
174
+ """Encoded latent columns that never appear in the output."""
175
+ return list(self.latent_schemas)
176
+
177
+ @property
178
+ def decoded_columns(self) -> list[str]:
179
+ """Source columns produced by decoding: encoded features (without the hidden latents)
180
+ plus the transform targets and the columns the sums compute."""
181
+ out = [c for c in self.feature_columns if c not in self.latent_schemas]
182
+ out += [t.target for t in self.transforms if t.target not in out]
183
+ return out + [c for c in computed_columns(self.sums) if c not in out]
184
+
185
+ def schema_of(self, column: str) -> ColumnSchema:
186
+ """The schema of a source column or of a hidden latent."""
187
+ return self.schemas[column] if column in self.schemas else self.latent_schemas[column]
188
+
189
+ @property
190
+ def enforcement(self) -> dict[str, str]:
191
+ out = {c.id: c.enforcement.value for c in self.constraints}
192
+ out.update({c.id: Enforcement.NONE.value for c in self.measured})
193
+ return out
194
+
195
+ def by_enforcement(self, e: Enforcement) -> list[CompiledConstraint]:
196
+ return [c for c in self.constraints if c.enforcement == e]
197
+
198
+ @property
199
+ def repairs(self) -> list[CompiledConstraint]:
200
+ return self.by_enforcement(Enforcement.REPAIR)
201
+
202
+ def describe(self) -> dict[str, Any]:
203
+ return {
204
+ "fingerprint_hash": self.fingerprint_hash,
205
+ "feature_columns": list(self.feature_columns),
206
+ "identifiers": {k: v.kind for k, v in self.identifiers.items()},
207
+ "constants": sorted(self.constants),
208
+ "unmodeled": list(self.unmodeled),
209
+ "derived_order": [d.column for d in self.derived],
210
+ "transforms": [{"kind": t.kind, "target": t.target, "inputs": list(t.inputs)}
211
+ for t in self.transforms],
212
+ "orderings": [{"target": o.target, "lower": list(o.lower), "upper": list(o.upper),
213
+ "method": o.method} for o in self.orderings],
214
+ "calendars": [{"column": c.column, "anchors": list(c.anchors),
215
+ "moves": bool(c.kernel)} for c in self.calendars],
216
+ "entities": [{"key": g.key, "attributes": [a.column for a in g.attributes],
217
+ "anchor": g.anchor.column if g.anchor is not None else None}
218
+ for g in self.entities],
219
+ "references": {c: s.kind for c, s in self.references.items()},
220
+ "sums": [{"mode": x.mode, "total": x.total if x.total is not None else x.constant,
221
+ "parts": list(x.parts)} for x in self.sums],
222
+ "constraints": self.enforcement,
223
+ "output_columns": list(self.output_columns),
224
+ "notes": list(self.notes),
225
+ }
226
+
227
+
228
+ # ---------------------------------------------------------------------------------------------
229
+
230
+
231
+ def _ensure_registered() -> None:
232
+ # Registration side effects for every built-in plug-in kind.
233
+ from ectype.plugins import load_builtin_plugins
234
+
235
+ load_builtin_plugins()
236
+
237
+
238
+ def _validate_kinds(fp: Fingerprint) -> None:
239
+ from ectype.generation.identifiers import IDENTIFIERS
240
+ from ectype.models.base import JOINTS, MARGINALS
241
+
242
+ _ensure_registered()
243
+ model = fp.manifest.model
244
+ problems: list[str] = []
245
+ for col, spec in model.marginals.items():
246
+ if spec.kind not in MARGINALS:
247
+ problems.append(f"marginal {col!r}: unknown kind {spec.kind!r}")
248
+ if model.joint is not None and model.joint.kind not in JOINTS:
249
+ problems.append(f"joint: unknown kind {model.joint.kind!r}")
250
+ for col, spec in model.encodings.items():
251
+ if spec.kind not in ENCODING_KINDS:
252
+ problems.append(f"encoding {col!r}: unknown kind {spec.kind!r}")
253
+ for col, spec in model.missingness.items():
254
+ if spec.kind not in MISSINGNESS_KINDS:
255
+ problems.append(f"missingness {col!r}: unknown kind {spec.kind!r}")
256
+ for col, spec in model.identifiers.items():
257
+ if spec.kind not in IDENTIFIERS:
258
+ problems.append(f"identifier {col!r}: unknown kind {spec.kind!r}")
259
+ for col in model.encodings:
260
+ if col not in model.marginals:
261
+ problems.append(f"encoding {col!r} has no marginal")
262
+ if model.conditional:
263
+ problems.append("conditional models are not supported by this engine version")
264
+ for ref in _all_array_refs(fp):
265
+ if ref not in fp.arrays:
266
+ problems.append(f"missing array {ref!r}")
267
+ if problems:
268
+ raise FingerprintError("fingerprint cannot be compiled: " + "; ".join(problems))
269
+
270
+
271
+ def _all_array_refs(fp: Fingerprint) -> list[str]:
272
+ m = fp.manifest.model
273
+ specs = [*m.marginals.values(), *m.encodings.values(), *m.missingness.values(),
274
+ *m.identifiers.values()] + ([m.joint] if m.joint is not None else [])
275
+ return [ref for s in specs for ref in s.arrays.values()] + array_refs(m.entities)
276
+
277
+
278
+ def _output_schema(col: ColumnSchema) -> ColumnSchema:
279
+ numeric = col.physical_dtype.startswith(("Int", "UInt", "Float"))
280
+ if col.logical_type == LogicalType.CATEGORICAL and numeric:
281
+ return col.model_copy(update={"logical_type": (LogicalType.DISCRETE if
282
+ col.physical_dtype[0] in "IU" else
283
+ LogicalType.CONTINUOUS)})
284
+ return col
285
+
286
+
287
+ def _toposort(derived: dict[str, set[str]]) -> list[str]:
288
+ """Depth-first order over derived->derived edges; stable in declaration order."""
289
+ order: list[str] = []
290
+ state: dict[str, int] = {}
291
+
292
+ def visit(node: str, path: list[str]) -> None:
293
+ s = state.get(node, 0)
294
+ if s == 2:
295
+ return
296
+ if s == 1:
297
+ cyc = " -> ".join([*path[path.index(node):], node])
298
+ raise ConstraintError(f"derived columns form a cycle: {cyc}")
299
+ state[node] = 1
300
+ for dep in sorted(derived[node] & derived.keys()):
301
+ visit(dep, [*path, node])
302
+ state[node] = 2
303
+ order.append(node)
304
+
305
+ for node in derived:
306
+ visit(node, [])
307
+ return order
308
+
309
+
310
+ def _numeric_literal(node: ex.Node) -> float | None:
311
+ if isinstance(node, ex.Literal) and node.kind in ("int", "float"):
312
+ return float(node.value) # type: ignore[arg-type]
313
+ if isinstance(node, ex.Unary) and node.op == "-":
314
+ v = _numeric_literal(node.operand)
315
+ return None if v is None else -v
316
+ return None
317
+
318
+
319
+ def _bounds(node: ex.Node) -> list[Bound] | None:
320
+ """Clamp bounds equivalent to ``node``, or ``None`` if it is not a simple bound."""
321
+ if isinstance(node, ex.Binary) and node.op == "and":
322
+ left, right = _bounds(node.left), _bounds(node.right)
323
+ return None if left is None or right is None else left + right
324
+ if isinstance(node, ex.Binary) and node.op in _FLIP:
325
+ if isinstance(node.left, ex.Column):
326
+ v = _numeric_literal(node.right)
327
+ if v is not None:
328
+ return [Bound(node.left.name, node.op, v)]
329
+ if isinstance(node.right, ex.Column):
330
+ v = _numeric_literal(node.left)
331
+ if v is not None:
332
+ return [Bound(node.right.name, _FLIP[node.op], v)]
333
+ return None
334
+
335
+
336
+ def _with_tolerance(node: ex.Node, tol: float) -> ex.Node:
337
+ if tol > 0 and isinstance(node, ex.Binary) and node.op == "==":
338
+ diff = ex.Binary("-", node.left, node.right)
339
+ return ex.Binary("<=", ex.Call("abs", (diff,)), ex.Literal(float(tol), "float"))
340
+ return node
341
+
342
+
343
+ def enforced_node(spec: ConstraintSpec) -> ex.Node:
344
+ """The expression the generator enforces for ``spec`` (hard constraints: ``a == b`` with a
345
+ non-zero tolerance becomes ``abs(a - b) <= tolerance``). Shared with the validator so both
346
+ check exactly the same predicate."""
347
+ node = ex.parse(spec.expression)
348
+ if spec.severity == Severity.SOFT:
349
+ return node
350
+ return _with_tolerance(node, float(spec.tolerance))
351
+
352
+
353
+ def enum_downgrades(fp: Fingerprint) -> dict[str, list[str]]:
354
+ """Enum columns whose generated labels do not all fit the recorded ``Enum`` categories.
355
+
356
+ Maps column -> labels outside the categories (typically the pooled ``"__other__"``
357
+ bucket). Those columns are generated as ``String`` instead of ``Enum`` (a documented
358
+ downgrade: recorded in the plan notes and accepted by the validator's dtype check).
359
+ """
360
+ from ectype.generation.enforce import enum_categories
361
+
362
+ out: dict[str, list[str]] = {}
363
+ model = fp.manifest.model
364
+ for col in fp.manifest.columns:
365
+ cats = enum_categories(col.physical_dtype)
366
+ if cats is None:
367
+ continue
368
+ spec = model.marginals.get(col.name)
369
+ labels: list[str] = []
370
+ ref = spec.arrays.get("labels") if spec is not None else None
371
+ if ref is not None and ref in fp.arrays:
372
+ labels = [str(x) for x in fp.arrays.get(ref).tolist()]
373
+ extra = [lb for lb in labels if lb not in set(cats)]
374
+ if extra:
375
+ out[col.name] = extra
376
+ return out
377
+
378
+
379
+ def compile_plan(fp: Fingerprint) -> Plan:
380
+ """Compile ``fp`` into a :class:`Plan` (see the module docstring)."""
381
+ _validate_kinds(fp)
382
+ manifest = fp.manifest
383
+ model = manifest.model
384
+ schemas = {c.name: c for c in manifest.columns}
385
+ notes: list[str] = []
386
+
387
+ # -- structural transforms ----------------------------------------------------------------
388
+ problems = check_transforms(model.transforms, schemas)
389
+ excluded = {c.name for c in manifest.columns if c.role == Role.EXCLUDED}
390
+ transforms = order_transforms(model.transforms) if not problems else []
391
+ latents: dict[str, ColumnSchema] = {}
392
+ for t in transforms:
393
+ if t.target in excluded:
394
+ problems.append(f"transform target {t.target!r} is an excluded column")
395
+ if t.kind == "difference":
396
+ lat = latent_schema(t)
397
+ latents[lat.name] = lat
398
+ if lat.name not in model.encodings or lat.name not in model.marginals:
399
+ problems.append(f"transform for {t.target!r}: its latent {lat.name!r} has no "
400
+ f"marginal and encoding (the model does not generate it)")
401
+ if t.target in model.encodings or t.target in model.marginals:
402
+ problems.append(f"transform target {t.target!r} also has a marginal or encoding; "
403
+ f"it must be produced by the transform only")
404
+ # -- sums: computed last; their hidden shares are encoded features ---------------------
405
+ sums: list[SumSpec] = []
406
+ if not problems:
407
+ problems += check_sums(model.sums, schemas, [
408
+ *[t.target for t in transforms], *[d.column for d in model.derived],
409
+ *model.identifiers, *model.constants])
410
+ if not problems:
411
+ sums = order_sums(model.sums)
412
+ shares = share_schemas(sums)
413
+ for name in shares:
414
+ if name not in model.encodings or name not in model.marginals:
415
+ problems.append(f"sum share column {name!r} has no marginal and encoding (the "
416
+ f"model does not generate it)")
417
+ latents.update(shares)
418
+ redrawn = {o.target for o in model.orderings}
419
+ moved = {c.column for c in model.calendars}
420
+ scaled = scaled_columns(sums)
421
+ for c in scaled:
422
+ if c not in model.encodings or c not in model.marginals:
423
+ problems.append(f"column {c!r} is scaled to its total by a sum but has no "
424
+ f"marginal and encoding (the model does not generate it)")
425
+ for c in [*computed_columns(sums), *scaled]:
426
+ if c in excluded:
427
+ problems.append(f"sum column {c!r} is an excluded column")
428
+ if c not in scaled and (c in model.encodings or c in model.marginals):
429
+ problems.append(f"column {c!r} is computed by a sum and also has a marginal or "
430
+ f"encoding; it must be produced by the sum only")
431
+ if c in redrawn or c in moved:
432
+ problems.append(f"column {c!r} is computed by a sum and cannot be the target "
433
+ f"of an ordering or a calendar")
434
+ used = [t.target for t in transforms if c in t.inputs]
435
+ used += [o.target for o in model.orderings if c in [*o.lower, *o.upper]]
436
+ if used:
437
+ problems.append(f"column {c!r} is computed by a sum, after the transforms and "
438
+ f"orderings run: it cannot be an input of {used}")
439
+ orphans = [c for c in model.encodings if c not in schemas and c not in latents]
440
+ if orphans and not problems:
441
+ problems.append(f"encoded column(s) {orphans} are neither source columns nor the "
442
+ f"latent of a transform (a 0.3 manifest whose model.transforms was "
443
+ f"removed?)")
444
+ if not problems:
445
+ problems += check_orderings(model.orderings, transforms, schemas)
446
+ for o in model.orderings:
447
+ if o.target not in model.encodings or o.target not in model.marginals:
448
+ problems.append(f"ordering for {o.target!r}: the column has no marginal and "
449
+ f"encoding of its own to redraw from")
450
+ if problems:
451
+ raise FingerprintError("fingerprint cannot be compiled: " + "; ".join(problems))
452
+ targets = {t.target: t for t in transforms}
453
+ orderings = list(model.orderings)
454
+
455
+ # -- what each column comes from ------------------------------------------------------
456
+ order = list(model.column_order) or [c.name for c in manifest.columns
457
+ if c.role != Role.EXCLUDED]
458
+ # encoded features in source order, each latent where its target sits
459
+ latent_of = {t.target: str(t.params["latent"]) for t in transforms
460
+ if t.kind == "difference"}
461
+ latent_of.update({part: latent for x in sums for latent, part in zip(x.latents, x.parts)})
462
+ features: list[str] = []
463
+ for col_schema in manifest.columns:
464
+ name = col_schema.name
465
+ if name in model.encodings:
466
+ features.append(name)
467
+ elif latent_of.get(name) in model.encodings:
468
+ features.append(latent_of[name])
469
+ features += [c for c in model.encodings if c not in features]
470
+ derived_specs = {d.column: d for d in model.derived}
471
+ summed = computed_columns(sums)
472
+ if len(derived_specs) != len(model.derived):
473
+ raise ConstraintError("a derived column is declared more than once")
474
+ produced: dict[str, str] = {}
475
+ for kind, cols in (("feature", [f for f in features if f not in latents]),
476
+ ("transform", list(targets)), ("sum", summed),
477
+ ("identifier", list(model.identifiers)),
478
+ ("constant", list(model.constants)), ("derived", list(derived_specs))):
479
+ for c in cols:
480
+ if c in produced:
481
+ raise FingerprintError(f"column {c!r} is both {produced[c]} and {kind}")
482
+ produced[c] = kind
483
+ for t in transforms:
484
+ bad = [c for c in t.inputs if produced.get(c) not in ("feature", "transform")]
485
+ if bad:
486
+ raise FingerprintError(
487
+ f"transform for {t.target!r}: input(s) {bad} are not generated before the "
488
+ f"transforms run (inputs must be modeled features or transform targets)")
489
+ for o in orderings:
490
+ bad = [c for c in [*o.lower, *o.upper] if produced.get(c) not in ("feature", "transform")]
491
+ if bad:
492
+ raise FingerprintError(
493
+ f"ordering for {o.target!r}: bound column(s) {bad} are not generated before "
494
+ f"the orderings run (bounds must be modeled features or transform targets)")
495
+ problems = check_calendars(model.calendars, schemas, [
496
+ c for c, kind in produced.items() if kind in ("feature", "transform")])
497
+ problems += check_entities(model.entities, schemas, [
498
+ c for c, kind in produced.items() if kind in ("feature", "transform")])
499
+ problems += check_references(model.references, schemas)
500
+ for c in model.references:
501
+ if produced.get(c) != "feature":
502
+ problems.append(f"reference {c!r}: the column has no marginal and encoding (the "
503
+ f"model does not generate its group sizes)")
504
+ for col_schema in schemas.values():
505
+ if col_schema.role == Role.REFERENCE and col_schema.name not in model.references:
506
+ problems.append(f"reference column {col_schema.name!r} has no entry in "
507
+ f"model.references")
508
+ if problems:
509
+ raise FingerprintError("fingerprint cannot be compiled: " + "; ".join(problems))
510
+ entities = load_tables(model.entities, fp.arrays)
511
+ for x in sums:
512
+ needed = ([x.total] if x.total is not None else []) + list(x.parts)
513
+ bad = [c for c in needed if produced.get(c) not in ("feature", "transform", "sum")]
514
+ if bad:
515
+ raise FingerprintError(
516
+ f"sum {sum_text(x)!r}: column(s) {bad} are not generated before the sums run "
517
+ f"(they must be modeled features, transform targets or computed by a sum)")
518
+ for c in order:
519
+ if c in excluded and c not in produced:
520
+ raise FingerprintError(f"excluded column {c!r} appears in model.column_order")
521
+ order = [c for c in order if c not in excluded or c in produced]
522
+ unmodeled = [c for c in order if c not in produced]
523
+ for c in unmodeled:
524
+ produced[c] = "unmodeled"
525
+ notes.append(f"column {c!r} has no generator; emitted as nulls of its source dtype")
526
+ for c in derived_specs:
527
+ if c not in order:
528
+ order.append(c)
529
+ notes.append(f"derived column {c!r} is not in column_order; appended")
530
+ for c in features + list(targets) + summed + list(model.identifiers) \
531
+ + list(model.constants):
532
+ if c not in order and c not in latents:
533
+ order.append(c)
534
+
535
+ # Schemas for type checking and compilation: everything generated, typed as it appears in
536
+ # the *output* (integer-coded categoricals are integers there, so they compare and
537
+ # compute as numbers).
538
+ check_schemas = {c: _output_schema(schemas[c]) for c in produced if c in schemas}
539
+
540
+ # -- derived columns ---------------------------------------------------------------------
541
+ deps: dict[str, set[str]] = {}
542
+ nodes: dict[str, ex.Node] = {}
543
+ for col, d in derived_specs.items():
544
+ node = ex.parse(d.expression)
545
+ refs = ex.referenced_columns(node)
546
+ missing = sorted(refs - produced.keys())
547
+ if missing:
548
+ raise ConstraintError(f"derived column {col!r} references columns that are not "
549
+ f"generated: {missing}")
550
+ ids = sorted(refs & model.identifiers.keys())
551
+ if ids:
552
+ raise ConstraintError(f"derived column {col!r} references identifier columns "
553
+ f"{ids}; identifiers are regenerated and cannot be inputs")
554
+ keys = sorted(refs & model.references.keys())
555
+ if keys:
556
+ raise ConstraintError(f"derived column {col!r} references reference-key columns "
557
+ f"{keys}; their keys are regenerated and cannot be inputs")
558
+ if col in refs:
559
+ raise ConstraintError(f"derived columns form a cycle: {col} -> {col}")
560
+ deps[col] = refs
561
+ nodes[col] = node
562
+ topo = _toposort(deps)
563
+ derived: list[CompiledDerived] = []
564
+ for col in topo:
565
+ d = derived_specs[col]
566
+ known = {k: v for k, v in check_schemas.items() if k in deps[col]}
567
+ if set(deps[col]) <= known.keys():
568
+ ex.check(d.expression, known)
569
+ expr = ex.to_polars(nodes[col], known)
570
+ else: # references derived columns with no schema: check by literals only
571
+ expr = ex.to_polars(nodes[col])
572
+ derived.append(CompiledDerived(col, d.expression, expr, deps[col]))
573
+
574
+ # -- constraints -------------------------------------------------------------------------
575
+ compiled: list[CompiledConstraint] = []
576
+ measured: list[ConstraintSpec] = []
577
+ seen_ids: set[str] = set()
578
+ # difference targets are sampled (through their latent); identity targets are derived
579
+ sampled = features + [t.target for t in transforms if t.kind == "difference"]
580
+ sampled_numeric = {c for c in sampled if c in check_schemas and
581
+ check_schemas[c].logical_type in
582
+ (LogicalType.CONTINUOUS, LogicalType.DISCRETE)}
583
+ computed = derived_specs.keys() | {t.target for t in transforms if t.kind == "identity"} \
584
+ | set(summed)
585
+ for spec in manifest.constraints.confirmed:
586
+ if spec.id in seen_ids:
587
+ raise ConstraintError(f"duplicate constraint id {spec.id!r}")
588
+ seen_ids.add(spec.id)
589
+ try:
590
+ node = ex.parse(spec.expression)
591
+ refs = ex.referenced_columns(node)
592
+ missing = sorted(refs - produced.keys())
593
+ if missing:
594
+ raise ConstraintError(f"constraint {spec.id!r} references columns that are "
595
+ f"not generated: {missing}")
596
+ ids = sorted(refs & (model.identifiers.keys() | model.references.keys()))
597
+ if ids:
598
+ raise ConstraintError(f"constraint {spec.id!r} references identifier columns "
599
+ f"{ids}; identifiers are regenerated after enforcement")
600
+ if refs <= check_schemas.keys():
601
+ ex.check(spec.expression, {k: check_schemas[k] for k in refs})
602
+ except ExpressionError as exc:
603
+ raise ConstraintError(f"constraint {spec.id!r} is invalid: {exc}") from exc
604
+ if spec.severity == Severity.SOFT or spec.enforcement == Enforcement.NONE:
605
+ measured.append(spec)
606
+ continue
607
+ node_t = enforced_node(spec)
608
+ kinds = {k: check_schemas[k] for k in refs if k in check_schemas}
609
+ expr = ex.to_polars(node_t, kinds if refs <= kinds.keys() else None)
610
+ eff = spec.enforcement
611
+ bounds: list[Bound] = []
612
+ if eff == Enforcement.REPAIR:
613
+ b = _bounds(node)
614
+ if b is not None and all(x.column in sampled_numeric for x in b):
615
+ bounds = b
616
+ else:
617
+ eff = Enforcement.REJECTION
618
+ notes.append(f"constraint {spec.id!r}: repair is only implemented for simple "
619
+ f"bounds on sampled numeric columns; using rejection")
620
+ elif eff == Enforcement.DERIVATION and not (refs & computed):
621
+ eff = Enforcement.REJECTION
622
+ notes.append(f"constraint {spec.id!r}: derivation requested but it references no "
623
+ f"derived column; using rejection")
624
+ compiled.append(CompiledConstraint(spec, expr, refs, eff, bounds))
625
+
626
+ by_id = {c.id: c for c in compiled}
627
+ for t in transforms:
628
+ src = by_id.get(str(t.params.get("constraint")))
629
+ if src is None:
630
+ continue
631
+ how = (f"{t.target} = {t.inputs[0]} {'+' if t.params['sign'] == 1 else '-'} "
632
+ f"{t.params['latent']}" if t.kind == "difference"
633
+ else f"{t.target} = {t.inputs[0]} {t.params['op']} {t.inputs[1]}")
634
+ if t.params.get("signed") is True:
635
+ continue # a signed difference guarantees nothing
636
+ notes.append(f"constraint {src.id!r} holds by construction ({t.kind} transform "
637
+ f"{how}); still checked on every row")
638
+ for x in sums:
639
+ if x.constraint is not None and x.constraint in by_id:
640
+ notes.append(f"constraint {x.constraint!r} holds by construction (the sum "
641
+ f"{sum_text(x)} is computed, mode {x.mode}); still checked on every "
642
+ f"row")
643
+ for o in orderings:
644
+ for cid in o.constraints:
645
+ if cid in by_id:
646
+ notes.append(f"constraint {cid!r} is enforced by redrawing {o.target!r} from "
647
+ f"its marginal truncated at its bound ({o.method}); still "
648
+ f"checked on every row")
649
+
650
+ for col, extra in enum_downgrades(fp).items():
651
+ notes.append(f"dtype downgrade: column {col!r} is Enum in the source but the model can "
652
+ f"emit labels outside its categories ({extra[:5]}); generated as String")
653
+
654
+ return Plan(
655
+ fingerprint_hash=fp.content_hash(),
656
+ schemas=schemas,
657
+ feature_columns=features,
658
+ identifiers=dict(model.identifiers),
659
+ constants=dict(model.constants),
660
+ unmodeled=unmodeled,
661
+ derived=derived,
662
+ constraints=compiled,
663
+ measured=measured,
664
+ output_columns=order,
665
+ notes=notes,
666
+ transforms=transforms,
667
+ latent_schemas=latents,
668
+ orderings=orderings,
669
+ steps=order_steps(transforms, orderings),
670
+ calendars=list(model.calendars),
671
+ entities=entities,
672
+ references=dict(model.references),
673
+ sums=sums,
674
+ )
675
+
676
+
677
+ __all__ = ["Bound", "CompiledConstraint", "CompiledDerived", "Plan", "compile_plan",
678
+ "enforced_node", "enum_downgrades"]