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,1733 @@
1
+ """Structural relationships modeled in value space (format 0.3, ADR-0005; orderings represented
2
+ by dependence, format 0.4, ADR-0009).
3
+
4
+ Real tables are full of relationships such as ``end = start + duration``,
5
+ ``last_order >= signup`` or ``total = qty * price``. Modeling both sides separately and enforcing
6
+ the rule by *rejecting* rows distorts the distributions the rule acts on (design section 6.2).
7
+ This module models such relationships directly, so they hold by construction:
8
+
9
+ ``difference``
10
+ ``target = base + sign * delta`` with ``delta >= 0``. The latent ``delta`` (a hidden column
11
+ named :func:`delta_name`, ``__delta__<target>``) is modeled *in place of* the target: it
12
+ has the marginal, the encoding and the slot in the joint model; the target has no marginal.
13
+ ``sign`` is ``+1`` when the target is the larger side (``end = start + delta``) and ``-1``
14
+ when it is the smaller one (``start = end - delta``), so the latent always has support
15
+ ``[0, inf)``. Numeric and datetime columns are supported; datetimes are differenced in the
16
+ epoch units of :mod:`ectype.io.values` (days for dates, microseconds otherwise) and the
17
+ target is converted back with ``values_to_column`` and its own schema. With the parameter
18
+ ``signed`` the latent keeps its sign: the source has a few out-of-order rows, they are
19
+ part of the model, and no ordering is guaranteed.
20
+ ``identity``
21
+ ``target = a op b`` with ``op`` in ``+ - *``. The target is derived, not modeled, and is
22
+ rounded to its source precision (``decimals``).
23
+
24
+ A transform is recorded in ``manifest.model.transforms`` as a
25
+ :class:`~ectype.fingerprint.schema.TransformSpec` (``kind``, ``target``, ``inputs``, ``params``);
26
+ the parameters of each kind are closed (:data:`PARAMS`), so a reader rejects a transform it does
27
+ not fully understand instead of generating something else.
28
+
29
+ An ordering can also be enforced *without* a transform (``manifest.model.orderings``,
30
+ :class:`~ectype.fingerprint.schema.OrderingSpec`): its target keeps its own marginal, and a
31
+ generated row that breaks the ordering gets a new target value from that marginal truncated at
32
+ the bound (:func:`redraw`).
33
+
34
+ Which representation an ordering gets
35
+ -------------------------------------
36
+ A difference stores the marginal of the gap and leaves the dependence between base and gap to
37
+ the joint model. That is the right model when the gap has little to do with the base, and a bad
38
+ one when the gap is made of it (``status = max(issue, c) + lag``): what the joint model misses
39
+ of the dependence lands in the target. :func:`gap_dependence` measures it: the target is
40
+ rebuilt from gaps that keep only their rank correlation with the base, and its
41
+ Kolmogorov-Smirnov distance to the real target must stay within :func:`target_ks_limit`
42
+ (``MAX_TARGET_KS`` plus sampling noise). This decides for confirmed orderings too.
43
+
44
+ * A difference that passes is used: guaranteed (``delta >= 0``; source rows that break a
45
+ confirmed ordering are clamped) for a confirmed ordering and for one no source row breaks,
46
+ ``signed`` for an unconfirmed ordering that a few rows break.
47
+ * An ordering that holds (confirmed, or on every source row) and gets no difference is
48
+ enforced by redraw.
49
+ * An unconfirmed ordering with out-of-order rows and a dependent gap is left alone.
50
+
51
+ Detection (:func:`plan_transforms`)
52
+ -----------------------------------
53
+ * A confirmed hard ordering constraint between two numeric or two datetime feature columns
54
+ (``a <= b``, ``a < b``, ``b - a >= 0`` and mirrored forms), whether user-declared or a
55
+ confirmed suggestion, is **always** guaranteed: by a ``difference`` when one passes the
56
+ dependence test above, by redraw otherwise.
57
+ * ``identity`` is applied for a confirmed hard identity constraint (``c == a op b`` or the
58
+ tolerance form ``abs(c - a op b) <= tol`` of the suggestions).
59
+ * In mode ``"auto"`` (the default), suggestions are used too: an ordering with confidence
60
+ ``>= AUTO_MIN_CONFIDENCE``, no violations and ``|Spearman| >= AUTO_MIN_SPEARMAN``, and an
61
+ identity with no violations and confidence ``>= AUTO_MIN_CONFIDENCE``. A suggested ordering
62
+ must also be one the separate models would actually break: when the columns barely overlap
63
+ (``P(lo > hi) < AUTO_MIN_NULL_VIOLATION`` for independent draws, e.g. ``debt <= income``
64
+ with debt a quarter of income) it is nearly implied by the marginals, so a transform buys
65
+ little and would cost the target its own marginal (it could no longer be mutated or
66
+ calibrated). Confirmed constraints are applied whatever these statistics.
67
+ * In mode ``"auto"`` an ordering that a few rows break is a candidate for a ``signed``
68
+ difference, on the same evidence (:func:`_scan_orderings`; the suggestions themselves stop
69
+ at 0.1% of violations). "A few" is the rule every relationship is held to
70
+ (:mod:`ectype.profiling.tolerance`, ADR-0015): more than none and at most
71
+ ``AUTO_MAX_VIOLATION`` of the rows wherever they are, or up to ``tolerance.DIRTY`` of them
72
+ when the out-of-order rows are isolated (not gathered in a stretch of either column, such
73
+ as a placeholder date, or in a category of another column).
74
+ * Identities are planned before orderings (an exact formula is the stronger structure), confirmed
75
+ before suggested. Orderings are planned shortest span first (the transitive reduction of the
76
+ ordering graph), so a chain ``a <= b <= c`` becomes ``b = a + d1``, ``c = b + d2`` and the
77
+ implied ``a <= c`` holds by construction. A target gets at most one transform, the
78
+ dependency graph stays acyclic, and both columns must be modeled features (internal ``__*``
79
+ columns are never transformed).
80
+ * A direction is not used, with a diagnostic, when the null patterns are incompatible: more
81
+ than :data:`MAX_NULL_MISMATCH` of the rows have a null base (any null input) but a present
82
+ target, or, for an identity, a null target with every input present (a derived column cannot
83
+ carry its own missingness).
84
+ * When no direction of an ordering is free and fits, the difference that occupies its target
85
+ is turned around (``issue = applied + gap`` becomes ``applied = issue - gap``) if that frees
86
+ the target and both differences still pass every check: a chain is rooted where each of its
87
+ orderings can be modeled (``_Planner._turn``).
88
+ * Orderings by redraw are planned after every transform, so a column is never both computed and
89
+ redrawn. The larger side is redrawn, or the smaller one when the larger is computed.
90
+
91
+ What was applied, enforced by redraw, implied, skipped or not selected, and why, is returned as
92
+ diagnostics (recorded by the profiler in ``manifest.diagnostics["structure"]``).
93
+
94
+ Fit and generation
95
+ ------------------
96
+ At fit time :func:`working_frame` adds the latent columns (``delta = sign * (target - base)``;
97
+ source rows that violate the ordering are clamped to ``delta = 0``, a minimal repair that is
98
+ counted in the diagnostics, unless the transform is ``signed``); marginals, encoder and joint
99
+ are fitted on the working columns. Targets and validation stay on the original columns. At
100
+ generation time :func:`apply_structure` recomputes the targets and enforces the orderings, in
101
+ dependency order (:func:`order_steps`), and :class:`StructuredEncoder` wraps the fitted encoder
102
+ so that every consumer of ``Generator.encoder`` sees the original columns only: hidden latents
103
+ never leave it.
104
+ """
105
+
106
+ from __future__ import annotations
107
+
108
+ import math
109
+ from collections.abc import Callable, Mapping, Sequence
110
+ from dataclasses import dataclass, field
111
+ from typing import TYPE_CHECKING, Any
112
+
113
+ import numpy as np
114
+ import polars as pl
115
+ from scipy import special, stats
116
+
117
+ from ectype.errors import FingerprintError
118
+ from ectype.fingerprint.disclosure import clip_bounds, coarsen, resolve_policy
119
+ from ectype.fingerprint.expressions import Binary, Call, Column, Literal, Node, Unary, parse
120
+ from ectype.fingerprint.expressions import referenced_columns as _refs
121
+ from ectype.fingerprint.schema import (
122
+ CalendarSpec,
123
+ ColumnSchema,
124
+ ConstraintSpec,
125
+ DisclosurePolicySpec,
126
+ OrderingSpec,
127
+ SuggestedConstraint,
128
+ SumSpec,
129
+ TransformSpec,
130
+ )
131
+ from ectype.io.values import column_to_values, values_to_column
132
+ from ectype.profiling import tolerance
133
+ from ectype.profiling.calendar import apply_calendars
134
+ from ectype.types import Enforcement, LogicalType, Role, Severity
135
+
136
+ if TYPE_CHECKING:
137
+ from ectype.models.base import MarginalModel
138
+ from ectype.models.encoding import MixedEncoder
139
+
140
+ __all__ = [
141
+ "AUTO_MAX_VIOLATION",
142
+ "AUTO_MIN_CONFIDENCE",
143
+ "AUTO_MIN_NULL_VIOLATION",
144
+ "AUTO_MIN_SPEARMAN",
145
+ "KINDS",
146
+ "LATENT_PREFIX",
147
+ "MAX_NULL_MISMATCH",
148
+ "MAX_TARGET_KS",
149
+ "MODES",
150
+ "ORDERING_METHODS",
151
+ "PARAMS",
152
+ "StructurePlan",
153
+ "StructuredEncoder",
154
+ "WorkingFrame",
155
+ "apply_inverse",
156
+ "apply_structure",
157
+ "check_orderings",
158
+ "check_transforms",
159
+ "delta_name",
160
+ "forward",
161
+ "gap_dependence",
162
+ "identity_form",
163
+ "latent_schema",
164
+ "order_steps",
165
+ "order_transforms",
166
+ "ordering_form",
167
+ "plan_structure",
168
+ "plan_transforms",
169
+ "redraw",
170
+ "target_ks_limit",
171
+ "working_frame",
172
+ ]
173
+
174
+ #: prefix of the hidden latent column of a ``difference`` transform
175
+ LATENT_PREFIX = "__delta__"
176
+ KINDS = ("difference", "identity")
177
+ MODES = ("auto", "confirmed", "off")
178
+ #: auto mode: minimum suggestion confidence (the "high" label) and |Spearman| for an ordering
179
+ AUTO_MIN_CONFIDENCE = 0.99
180
+ AUTO_MIN_SPEARMAN = 0.3
181
+ #: auto mode: minimum P(lo > hi) for independent draws of the two columns (marginal overlap)
182
+ AUTO_MIN_NULL_VIOLATION = 0.1
183
+ #: largest share of rows with a null base (input) but a present target that is still accepted
184
+ MAX_NULL_MISMATCH = 0.01
185
+ #: auto mode: largest share of out-of-order rows, wherever they are, with which an
186
+ #: unconfirmed ordering is still modeled as a (signed) difference: the shared rule of
187
+ #: ``profiling.tolerance``, which also allows ``tolerance.DIRTY`` of isolated rows
188
+ AUTO_MAX_VIOLATION = tolerance.STRAY
189
+ #: a difference is used only when the target it implies stays this close to the real one
190
+ #: (Kolmogorov-Smirnov distance; the bound of ``profiling.univariate`` for a marginal model),
191
+ #: plus ``TARGET_KS_NOISE / sqrt(rows)`` of sampling noise, and at most ``TARGET_KS_CAP``
192
+ MAX_TARGET_KS = 0.03
193
+ TARGET_KS_NOISE = 1.0
194
+ TARGET_KS_CAP = 0.15
195
+ #: the implied target is simulated on at most this many rows, this many times
196
+ DEPENDENCE_MAX_ROWS = 50_000
197
+ DEPENDENCE_REPLICATES = 4
198
+ #: auto mode: at most this many column pairs are scanned for orderings with a few
199
+ #: out-of-order rows (the budget of the constraint suggestions)
200
+ MAX_SCAN_PAIRS = 1250
201
+ #: how an ordering without a transform is enforced (``OrderingSpec.method``)
202
+ ORDERING_METHODS = ("reflect",)
203
+
204
+ #: the closed parameter set of each kind: (required, optional)
205
+ PARAMS: dict[str, tuple[frozenset[str], frozenset[str]]] = {
206
+ "difference": (frozenset({"latent", "sign", "unit", "latent_type"}),
207
+ frozenset({"strict", "decimals", "source", "constraint", "signed"})),
208
+ "identity": (frozenset({"op"}), frozenset({"decimals", "source", "constraint"})),
209
+ }
210
+ _UNITS = ("num", "d", "us")
211
+ _IDENTITY_OPS = ("+", "-", "*")
212
+ _NUMERIC = (LogicalType.CONTINUOUS, LogicalType.DISCRETE)
213
+ _ORDER_OPS = ("<", "<=", ">", ">=")
214
+
215
+
216
+ def delta_name(target: str) -> str:
217
+ """Name of the hidden latent column that models ``target`` (``__delta__<target>``)."""
218
+ return f"{LATENT_PREFIX}{target}"
219
+
220
+
221
+ # ---------------------------------------------------------------------------------------------
222
+ # Expression forms
223
+ # ---------------------------------------------------------------------------------------------
224
+
225
+
226
+ def _col(node: Node) -> str | None:
227
+ return node.name if isinstance(node, Column) else None
228
+
229
+
230
+ def _is_zero(node: Node) -> bool:
231
+ if isinstance(node, Unary) and node.op == "-":
232
+ return _is_zero(node.operand)
233
+ return (isinstance(node, Literal) and node.kind in ("int", "float")
234
+ and float(node.value) == 0.0) # type: ignore[arg-type]
235
+
236
+
237
+ def ordering_form(node: Node | str) -> tuple[str, str, bool] | None:
238
+ """``(lo, hi, strict)`` when ``node`` states ``lo <= hi`` (``lo < hi`` if strict) between
239
+ two columns: ``a <= b``, ``b >= a``, ``b - a >= 0``, ``0 <= b - a``, ``a - b <= 0`` and the
240
+ strict variants. ``None`` otherwise."""
241
+ if isinstance(node, str):
242
+ node = parse(node)
243
+ if not (isinstance(node, Binary) and node.op in _ORDER_OPS):
244
+ return None
245
+ op, left, right = node.op, node.left, node.right
246
+ a, b = _col(left), _col(right)
247
+ if a is not None and b is not None and a != b:
248
+ return (a, b, op == "<") if op in ("<", "<=") else (b, a, op == ">")
249
+ # normalise "0 op (x - y)" to "(x - y) op' 0"
250
+ if _is_zero(left) and isinstance(right, Binary):
251
+ op = {"<": ">", "<=": ">=", ">": "<", ">=": "<="}[op]
252
+ left, right = right, left
253
+ if _is_zero(right) and isinstance(left, Binary) and left.op == "-":
254
+ x, y = _col(left.left), _col(left.right)
255
+ if x is not None and y is not None and x != y:
256
+ # x - y >= 0 <=> y <= x ; x - y <= 0 <=> x <= y
257
+ return (y, x, op == ">") if op in (">", ">=") else (x, y, op == "<")
258
+ return None
259
+
260
+
261
+ def _formula(node: Node) -> tuple[str, str, str] | None:
262
+ if isinstance(node, Binary) and node.op in _IDENTITY_OPS:
263
+ a, b = _col(node.left), _col(node.right)
264
+ if a is not None and b is not None and a != b:
265
+ return node.op, a, b
266
+ return None
267
+
268
+
269
+ def identity_form(node: Node | str) -> tuple[str, str, str, str] | None:
270
+ """``(target, op, a, b)`` when ``node`` states ``target == a op b`` (``op`` in ``+ - *``):
271
+ the exact form ``c == a op b`` (either side) or the tolerance form of the suggestions,
272
+ ``abs(c - a op b) <= tol`` (``tol`` may reference only ``c``). ``None`` otherwise."""
273
+ if isinstance(node, str):
274
+ node = parse(node)
275
+ if isinstance(node, Binary) and node.op == "==":
276
+ for lhs, rhs in ((node.left, node.right), (node.right, node.left)):
277
+ c, f = _col(lhs), _formula(rhs)
278
+ if c is not None and f is not None and c not in f[1:]:
279
+ return c, f[0], f[1], f[2]
280
+ return None
281
+ if isinstance(node, Binary) and node.op in ("<=", "<"):
282
+ lhs = node.left
283
+ if not (isinstance(lhs, Call) and lhs.name == "abs" and len(lhs.args) == 1):
284
+ return None
285
+ inner = lhs.args[0]
286
+ if not (isinstance(inner, Binary) and inner.op == "-"):
287
+ return None
288
+ for x, y in ((inner.left, inner.right), (inner.right, inner.left)):
289
+ c, f = _col(x), _formula(y)
290
+ if c is not None and f is not None and c not in f[1:] \
291
+ and _refs(node.right) <= {c}:
292
+ return c, f[0], f[1], f[2]
293
+ return None
294
+
295
+
296
+ # ---------------------------------------------------------------------------------------------
297
+ # Schemas and units
298
+ # ---------------------------------------------------------------------------------------------
299
+
300
+
301
+ def _unit(col: ColumnSchema) -> str | None:
302
+ """Epoch unit of a modelable numeric/datetime column (``io.values`` conventions)."""
303
+ if col.logical_type in _NUMERIC:
304
+ return "num"
305
+ if col.logical_type == LogicalType.DATETIME:
306
+ return "d" if (col.is_date or col.datetime_unit == "d") else "us"
307
+ return None
308
+
309
+
310
+ def _eligible(col: ColumnSchema | None) -> str | None:
311
+ """Why ``col`` cannot take part in a transform (``None`` when it can)."""
312
+ if col is None:
313
+ return "not a source column"
314
+ if col.name.startswith("__"):
315
+ return "internal column"
316
+ if col.role != Role.FEATURE:
317
+ return f"role {col.role.value}"
318
+ if _unit(col) is None:
319
+ return f"logical type {col.logical_type.value}"
320
+ return None
321
+
322
+
323
+ def _decimals(col: ColumnSchema) -> int | None:
324
+ if col.integer_valued:
325
+ return 0
326
+ return col.decimals
327
+
328
+
329
+ def latent_schema(spec: TransformSpec) -> ColumnSchema:
330
+ """The :class:`ColumnSchema` of a ``difference`` transform's hidden latent, rebuilt from its
331
+ parameters alone (the generator needs nothing else): a ``Float64`` feature whose support
332
+ starts at 0, or has no lower bound when the transform is ``signed``."""
333
+ p = spec.params
334
+ discrete = str(p.get("latent_type")) == LogicalType.DISCRETE.value
335
+ dec = p.get("decimals")
336
+ signed = _signed(spec)
337
+ return ColumnSchema(
338
+ name=str(p["latent"]),
339
+ logical_type=LogicalType.DISCRETE if discrete else LogicalType.CONTINUOUS,
340
+ role=Role.FEATURE,
341
+ physical_dtype="Float64",
342
+ integer_valued=discrete,
343
+ decimals=0 if discrete else (None if dec is None else int(dec)), # type: ignore[arg-type]
344
+ min_value=None if signed else 0.0,
345
+ notes=[f"hidden latent of the {'signed ' if signed else ''}difference transform for "
346
+ f"{spec.target!r}"],
347
+ )
348
+
349
+
350
+ def _signed(spec: TransformSpec) -> bool:
351
+ """Whether a ``difference`` transform models the source's out-of-order rows (its latent may
352
+ be negative) instead of guaranteeing the ordering."""
353
+ return spec.kind == "difference" and spec.params.get("signed") is True
354
+
355
+
356
+ # ---------------------------------------------------------------------------------------------
357
+ # Validation and ordering of recorded transforms
358
+ # ---------------------------------------------------------------------------------------------
359
+
360
+
361
+ def order_transforms(transforms: Sequence[TransformSpec]) -> list[TransformSpec]:
362
+ """Topological order (inputs before the targets computed from them), stable in the given
363
+ order. Raises :class:`FingerprintError` on a cycle."""
364
+ by_target = {t.target: t for t in transforms}
365
+ out: list[TransformSpec] = []
366
+ state: dict[str, int] = {}
367
+
368
+ def visit(t: TransformSpec, path: list[str]) -> None:
369
+ s = state.get(t.target, 0)
370
+ if s == 2:
371
+ return
372
+ if s == 1:
373
+ cyc = " -> ".join([*path[path.index(t.target):], t.target])
374
+ raise FingerprintError(f"transforms form a cycle: {cyc}")
375
+ state[t.target] = 1
376
+ for name in t.inputs:
377
+ dep = by_target.get(name)
378
+ if dep is not None:
379
+ visit(dep, [*path, t.target])
380
+ state[t.target] = 2
381
+ out.append(t)
382
+
383
+ for t in transforms:
384
+ visit(t, [])
385
+ return out
386
+
387
+
388
+ def check_transforms(transforms: Sequence[TransformSpec], schemas: Mapping[str, ColumnSchema]
389
+ ) -> list[str]:
390
+ """Problems with recorded transforms that make a fingerprint unusable by this engine: an
391
+ unknown kind, missing or unknown parameters (the parameter set of each kind is closed),
392
+ wrong arity, unknown or incompatible columns, a target used twice, a latent name that
393
+ collides with a column, or a cycle. Empty when everything is understood."""
394
+ problems: list[str] = []
395
+ seen: set[str] = set()
396
+ latents: set[str] = set()
397
+ for t in transforms:
398
+ what = f"transform for {t.target!r}"
399
+ if t.kind not in PARAMS:
400
+ problems.append(f"{what}: unknown kind {t.kind!r} (this engine supports "
401
+ f"{list(KINDS)})")
402
+ continue
403
+ required, optional = PARAMS[t.kind]
404
+ missing = sorted(required - set(t.params))
405
+ unknown = sorted(set(t.params) - required - optional)
406
+ if missing:
407
+ problems.append(f"{what}: missing parameter(s) {missing}")
408
+ if unknown:
409
+ problems.append(f"{what}: parameter(s) {unknown} are not understood by this "
410
+ f"engine version")
411
+ if t.target in seen:
412
+ problems.append(f"{what}: the column is the target of more than one transform")
413
+ seen.add(t.target)
414
+ dec = t.params.get("decimals")
415
+ if dec is not None and (isinstance(dec, bool) or not isinstance(dec, int) or dec < 0):
416
+ problems.append(f"{what}: decimals must be null or a non-negative integer")
417
+ for flag in ("strict", "signed"):
418
+ if not isinstance(t.params.get(flag, False), bool):
419
+ problems.append(f"{what}: {flag} must be a boolean")
420
+ arity = 1 if t.kind == "difference" else 2
421
+ if len(t.inputs) != arity or len(set(t.inputs)) != arity or t.target in t.inputs:
422
+ problems.append(f"{what}: {t.kind} needs {arity} distinct input column(s) other "
423
+ f"than the target, got {t.inputs}")
424
+ continue
425
+ for name in [t.target, *t.inputs]:
426
+ if name not in schemas:
427
+ problems.append(f"{what}: unknown column {name!r}")
428
+ if any(name not in schemas for name in [t.target, *t.inputs]) or missing:
429
+ continue
430
+ units = {_unit(schemas[name]) for name in [t.target, *t.inputs]}
431
+ if t.kind == "difference":
432
+ unit = t.params.get("unit")
433
+ if units != {unit} or unit not in _UNITS:
434
+ problems.append(f"{what}: unit {unit!r} does not match the columns' value "
435
+ f"domain {sorted(str(u) for u in units)}")
436
+ if t.params.get("sign") not in (1, -1):
437
+ problems.append(f"{what}: sign must be 1 or -1")
438
+ if t.params.get("latent_type") not in (LogicalType.CONTINUOUS.value,
439
+ LogicalType.DISCRETE.value):
440
+ problems.append(f"{what}: latent_type must be 'continuous' or 'discrete'")
441
+ latent = str(t.params.get("latent"))
442
+ if latent in schemas or latent in latents or not latent.startswith(LATENT_PREFIX):
443
+ problems.append(f"{what}: latent column name {latent!r} must be unique, start "
444
+ f"with {LATENT_PREFIX!r} and not name a source column")
445
+ latents.add(latent)
446
+ else:
447
+ if t.params.get("op") not in _IDENTITY_OPS:
448
+ problems.append(f"{what}: identity op must be one of {list(_IDENTITY_OPS)}")
449
+ if units != {"num"}:
450
+ problems.append(f"{what}: identity transforms need numeric columns")
451
+ if not problems:
452
+ try:
453
+ order_transforms(transforms)
454
+ except FingerprintError as exc:
455
+ problems.append(str(exc))
456
+ return problems
457
+
458
+
459
+ def check_orderings(orderings: Sequence[OrderingSpec], transforms: Sequence[TransformSpec],
460
+ schemas: Mapping[str, ColumnSchema]) -> list[str]:
461
+ """Problems with recorded orderings (``model.orderings``, format 0.4) that make a
462
+ fingerprint unusable by this engine: an unknown method, no bound, unknown or incompatible
463
+ columns, a target that a transform computes (it has no marginal to redraw from) or that is
464
+ listed twice, or a cycle with the transforms. Empty when everything is understood."""
465
+ problems: list[str] = []
466
+ computed = {t.target for t in transforms}
467
+ seen: set[str] = set()
468
+ for o in orderings:
469
+ what = f"ordering for {o.target!r}"
470
+ if o.method not in ORDERING_METHODS:
471
+ problems.append(f"{what}: unknown method {o.method!r} (this engine supports "
472
+ f"{list(ORDERING_METHODS)})")
473
+ bounds = [*o.lower, *o.upper]
474
+ if not bounds or len(set(bounds)) != len(bounds) or o.target in bounds:
475
+ problems.append(f"{what}: needs at least one bound column, each listed once and "
476
+ f"none of them the target, got lower={o.lower}, upper={o.upper}")
477
+ continue
478
+ if o.target in seen:
479
+ problems.append(f"{what}: the column is the target of more than one ordering")
480
+ seen.add(o.target)
481
+ unknown = [name for name in [o.target, *bounds] if name not in schemas]
482
+ if unknown:
483
+ problems.append(f"{what}: unknown column(s) {unknown}")
484
+ continue
485
+ if o.target in computed:
486
+ problems.append(f"{what}: the column is computed by a transform and has no "
487
+ f"marginal of its own to redraw from")
488
+ units = {_unit(schemas[name]) for name in [o.target, *bounds]}
489
+ if len(units) != 1 or None in units:
490
+ problems.append(f"{what}: the columns' value domains differ "
491
+ f"({sorted(str(u) for u in units)})")
492
+ if not problems:
493
+ try:
494
+ order_steps(transforms, orderings)
495
+ except FingerprintError as exc:
496
+ problems.append(str(exc))
497
+ return problems
498
+
499
+
500
+ def order_steps(transforms: Sequence[TransformSpec], orderings: Sequence[OrderingSpec]
501
+ ) -> list[TransformSpec | OrderingSpec]:
502
+ """The transforms and orderings in the order they run after decoding: a transform after the
503
+ transforms that compute its inputs and after the orderings that redraw them; an ordering
504
+ after whatever produces its bounds. Stable in the given order (transforms first). Raises
505
+ :class:`FingerprintError` on a cycle."""
506
+ steps: list[TransformSpec | OrderingSpec] = [*transforms, *orderings]
507
+ made_by: dict[str, list[int]] = {}
508
+ for i, step in enumerate(steps):
509
+ made_by.setdefault(step.target, []).append(i)
510
+ out: list[TransformSpec | OrderingSpec] = []
511
+ state: dict[int, int] = {}
512
+
513
+ def needs(step: TransformSpec | OrderingSpec) -> list[str]:
514
+ return list(step.inputs) if isinstance(step, TransformSpec) else [*step.lower,
515
+ *step.upper]
516
+
517
+ def visit(i: int, path: list[str]) -> None:
518
+ step = steps[i]
519
+ if state.get(i, 0) == 2:
520
+ return
521
+ if state.get(i, 0) == 1:
522
+ cyc = " -> ".join([*path[path.index(step.target):], step.target])
523
+ raise FingerprintError(f"transforms and orderings form a cycle: {cyc}")
524
+ state[i] = 1
525
+ for name in needs(step):
526
+ for j in made_by.get(name, ()):
527
+ visit(j, [*path, step.target])
528
+ state[i] = 2
529
+ out.append(step)
530
+
531
+ for i in range(len(steps)):
532
+ visit(i, [])
533
+ return out
534
+
535
+
536
+ # ---------------------------------------------------------------------------------------------
537
+ # Value-space application
538
+ # ---------------------------------------------------------------------------------------------
539
+
540
+
541
+ def _values(df: pl.DataFrame, name: str, schemas: Mapping[str, ColumnSchema]) -> np.ndarray:
542
+ return np.asarray(column_to_values(df.get_column(name), schemas[name]), dtype=np.float64)
543
+
544
+
545
+ def _latent_values(df: pl.DataFrame, name: str) -> np.ndarray:
546
+ return np.asarray(df.get_column(name).cast(pl.Float64).fill_null(np.nan).to_numpy(),
547
+ dtype=np.float64)
548
+
549
+
550
+ def _identity_values(t: TransformSpec, df: pl.DataFrame,
551
+ schemas: Mapping[str, ColumnSchema]) -> np.ndarray:
552
+ a, b = (_values(df, name, schemas) for name in t.inputs)
553
+ op = t.params["op"]
554
+ with np.errstate(all="ignore"):
555
+ out = a + b if op == "+" else (a - b if op == "-" else a * b)
556
+ dec = t.params.get("decimals")
557
+ if dec is not None:
558
+ out = np.round(out, int(dec)) # type: ignore[call-overload]
559
+ return np.asarray(out, dtype=np.float64)
560
+
561
+
562
+ def apply_inverse(df: pl.DataFrame, transforms: Sequence[TransformSpec],
563
+ schemas: Mapping[str, ColumnSchema]) -> pl.DataFrame:
564
+ """Compute each transform's target from its inputs, in the given (topological) order:
565
+ ``target = base + sign * delta`` (converted back through ``values_to_column`` with the
566
+ target's schema) and ``target = a op b`` rounded to ``decimals``. A target that is already a
567
+ column of ``df``, or whose inputs are not, is left alone; latent columns are kept (drop
568
+ them by name, as :meth:`StructuredEncoder.decode` does)."""
569
+ for t in transforms:
570
+ needed = [*t.inputs, *([str(t.params["latent"])] if t.kind == "difference" else [])]
571
+ if t.target in df.columns or any(c not in df.columns for c in needed):
572
+ continue
573
+ if t.kind == "difference":
574
+ base = _values(df, t.inputs[0], schemas)
575
+ delta = _latent_values(df, str(t.params["latent"]))
576
+ vals = base + float(t.params["sign"]) * delta # type: ignore[arg-type]
577
+ else:
578
+ vals = _identity_values(t, df, schemas)
579
+ df = df.with_columns(values_to_column(vals, schemas[t.target]).alias(t.target))
580
+ return df
581
+
582
+
583
+ def forward(df: pl.DataFrame, transforms: Sequence[TransformSpec],
584
+ schemas: Mapping[str, ColumnSchema], *, clamp: bool = True
585
+ ) -> tuple[pl.DataFrame, dict[str, int]]:
586
+ """Add every ``difference`` latent ``delta = sign * (target - base)`` as a ``Float64`` column
587
+ (null where either side is null). Identity targets missing from ``df`` but needed as a base
588
+ are derived first. With ``clamp`` negative deltas (rows violating the ordering) become 0,
589
+ except for a ``signed`` transform, whose latent keeps them. Returns the frame and the
590
+ number of clamped rows per target."""
591
+ clamped: dict[str, int] = {}
592
+ for t in transforms:
593
+ if t.kind == "identity":
594
+ if t.target not in df.columns and all(c in df.columns for c in t.inputs):
595
+ vals = _identity_values(t, df, schemas)
596
+ df = df.with_columns(values_to_column(vals, schemas[t.target]).alias(t.target))
597
+ continue
598
+ base, target = t.inputs[0], t.target
599
+ if base not in df.columns or target not in df.columns:
600
+ delta = np.full(df.height, np.nan) # unknown: the latent is missing
601
+ else:
602
+ delta = float(t.params["sign"]) * ( # type: ignore[arg-type]
603
+ _values(df, target, schemas) - _values(df, base, schemas))
604
+ neg = np.isfinite(delta) & (delta < 0) & (not _signed(t))
605
+ if clamp and neg.any():
606
+ delta = np.where(neg, 0.0, delta)
607
+ clamped[target] = int(neg.sum())
608
+ s = pl.Series(str(t.params["latent"]), delta, dtype=pl.Float64).fill_nan(None)
609
+ df = df.with_columns(s)
610
+ return df, clamped
611
+
612
+
613
+ def _value_step(col: ColumnSchema) -> float | None:
614
+ """Spacing of the values the column's codec writes (``io.values``): 1 for integers and
615
+ datetimes, ``10^-decimals`` for a rounded column, ``None`` when it does not round."""
616
+ if col.integer_valued or col.logical_type in (LogicalType.DATETIME, LogicalType.DISCRETE):
617
+ return 1.0
618
+ if col.decimals is not None and 0 <= int(col.decimals) <= 12:
619
+ return float(10.0 ** -int(col.decimals))
620
+ return None
621
+
622
+
623
+ def _snap(bound: np.ndarray, step: float | None, *, up: bool, strict: bool) -> np.ndarray:
624
+ """The nearest value the target can take on the allowed side of ``bound``: at or above it
625
+ (``up``) or at or below it, on the lattice the target is written on; with ``strict`` the
626
+ bound itself is excluded."""
627
+ b = np.asarray(bound, dtype=np.float64)
628
+ if step is None:
629
+ return np.nextafter(b, np.inf if up else -np.inf) if strict else b
630
+ k = b / step
631
+ # a bound that is a lattice value up to float noise is that value, not the next one
632
+ near = np.rint(k)
633
+ on = np.abs(k - near) <= np.minimum(np.maximum(1e-9, 4e-15 * np.abs(near)), 0.25)
634
+ k = np.where(on, near, np.ceil(k) if up else np.floor(k))
635
+ if strict:
636
+ k = np.where(on, k + (1.0 if up else -1.0), k)
637
+ return np.asarray(k * step, dtype=np.float64)
638
+
639
+
640
+ def redraw(values: np.ndarray, lower: np.ndarray | None, upper: np.ndarray | None,
641
+ marginal: MarginalModel, column: ColumnSchema, *, strict: bool = False
642
+ ) -> tuple[np.ndarray, int]:
643
+ """Enforce ``lower <= values <= upper`` row by row with new values from ``marginal``
644
+ truncated to the allowed side of the bound (the ``reflect`` method of an
645
+ :class:`~ectype.fingerprint.schema.OrderingSpec`). Returns the values and the number of
646
+ rows changed.
647
+
648
+ A row below its lower bound ``L`` sits at level ``u = F(value)`` under ``h = P(X < L)``.
649
+ Its new level is ``h + s (h - u)``: the violation is reflected about the bound in the
650
+ target's own probability scale, with ``s = min(1, (1 - h) / h)`` so that the image of
651
+ ``[0, h)`` fits in the room above the bound. The new value is the quantile at that level,
652
+ hence a value of the marginal truncated to ``[L, max]`` that is as far inside as the old
653
+ one was outside: a row that was slightly out of order lands slightly on the right side
654
+ instead of on the bound (no pile of ties) or anywhere in the truncated range (which moves
655
+ far more mass than the ordering asks for). Rows that satisfy the bound are not touched, so
656
+ applying the function twice changes nothing, and it uses no random numbers. An upper
657
+ bound is the mirror image. NaN (null) values and bounds are left alone, and so is a row
658
+ whose bounds leave no value (``lower > upper``).
659
+ """
660
+ v = np.asarray(values, dtype=np.float64)
661
+ out = v.copy()
662
+ step = _value_step(column)
663
+ n = v.size
664
+ lo = np.full(n, np.nan) if lower is None else _snap(lower, step, up=True, strict=strict)
665
+ hi = np.full(n, np.nan) if upper is None else _snap(upper, step, up=False, strict=strict)
666
+ has_lo, has_hi = np.isfinite(lo), np.isfinite(hi)
667
+ feasible = np.isfinite(v) & ~(has_lo & has_hi & (lo > hi))
668
+ tiny = 1e-300
669
+ below = feasible & has_lo & (v < lo)
670
+ if below.any():
671
+ bound = lo[below]
672
+ h = np.asarray(marginal.cdf_left(bound), dtype=np.float64)
673
+ u = np.asarray(marginal.cdf(v[below]), dtype=np.float64)
674
+ top = np.where(has_hi[below], np.asarray(marginal.cdf(np.where(
675
+ has_hi[below], hi[below], bound)), dtype=np.float64), 1.0)
676
+ room = np.clip(top - h, 0.0, None)
677
+ scale = np.minimum(1.0, room / np.maximum(h, tiny))
678
+ new = np.asarray(marginal.ppf(np.clip(h + scale * np.clip(h - u, 0.0, None), 0.0, 1.0)),
679
+ dtype=np.float64)
680
+ new = np.maximum(new, bound)
681
+ out[below] = np.where(has_hi[below], np.minimum(new, hi[below]), new)
682
+ above = feasible & has_hi & (v > hi)
683
+ if above.any():
684
+ bound = hi[above]
685
+ h = np.asarray(marginal.cdf(bound), dtype=np.float64)
686
+ u = np.asarray(marginal.cdf_left(v[above]), dtype=np.float64)
687
+ bottom = np.where(has_lo[above], np.asarray(marginal.cdf_left(np.where(
688
+ has_lo[above], lo[above], bound)), dtype=np.float64), 0.0)
689
+ room = np.clip(h - bottom, 0.0, None)
690
+ scale = np.minimum(1.0, room / np.maximum(1.0 - h, tiny))
691
+ new = np.asarray(marginal.ppf(np.clip(h - scale * np.clip(u - h, 0.0, None), 0.0, 1.0)),
692
+ dtype=np.float64)
693
+ new = np.minimum(new, bound)
694
+ out[above] = np.where(has_lo[above], np.maximum(new, lo[above]), new)
695
+ return out, int(below.sum() + above.sum())
696
+
697
+
698
+ def _bound(df: pl.DataFrame, names: Sequence[str], schemas: Mapping[str, ColumnSchema], *,
699
+ lower: bool) -> np.ndarray | None:
700
+ """The tightest of several bound columns per row (NaN where every one is null)."""
701
+ cols = [_values(df, name, schemas) for name in names if name in df.columns]
702
+ if not cols:
703
+ return None
704
+ stacked = np.vstack(cols)
705
+ some = np.isfinite(stacked).any(axis=0)
706
+ best = np.where(np.isfinite(stacked), stacked, -np.inf if lower else np.inf)
707
+ best = best.max(axis=0) if lower else best.min(axis=0)
708
+ return np.asarray(np.where(some, best, np.nan), dtype=np.float64)
709
+
710
+
711
+ def apply_ordering(df: pl.DataFrame, spec: OrderingSpec, schemas: Mapping[str, ColumnSchema],
712
+ marginal: MarginalModel | None) -> tuple[pl.DataFrame, int]:
713
+ """Enforce one :class:`~ectype.fingerprint.schema.OrderingSpec` on ``df`` (see
714
+ :func:`redraw`). Nothing happens when the target, its marginal or every bound column is
715
+ missing. Returns the frame and the number of rows changed."""
716
+ if marginal is None or spec.target not in df.columns:
717
+ return df, 0
718
+ lower = _bound(df, spec.lower, schemas, lower=True)
719
+ upper = _bound(df, spec.upper, schemas, lower=False)
720
+ if lower is None and upper is None:
721
+ return df, 0
722
+ vals = _values(df, spec.target, schemas)
723
+ new, changed = redraw(vals, lower, upper, marginal, schemas[spec.target],
724
+ strict=spec.strict)
725
+ if not changed:
726
+ return df, 0
727
+ col = values_to_column(new, schemas[spec.target]).alias(spec.target)
728
+ return df.with_columns(col.cast(df.schema[spec.target], strict=False)), changed
729
+
730
+
731
+ def apply_structure(df: pl.DataFrame, steps: Sequence[TransformSpec | OrderingSpec],
732
+ schemas: Mapping[str, ColumnSchema],
733
+ marginals: Mapping[str, MarginalModel] | None = None) -> pl.DataFrame:
734
+ """Run transforms and orderings in the given order (:func:`order_steps`) on decoded
735
+ columns: each transform computes its target (:func:`apply_inverse`) and each ordering
736
+ redraws the rows of its target that break it (:func:`apply_ordering`, from
737
+ ``marginals[target]``)."""
738
+ for step in steps:
739
+ if isinstance(step, TransformSpec):
740
+ df = apply_inverse(df, [step], schemas)
741
+ else:
742
+ df, _ = apply_ordering(df, step, schemas, (marginals or {}).get(step.target))
743
+ return df
744
+
745
+
746
+ @dataclass
747
+ class WorkingFrame:
748
+ """The fit-time view of a source table under its transforms (:func:`working_frame`).
749
+
750
+ ``frame`` holds the latents with nulls wherever the base or the target is null (marginals
751
+ are fitted on its observed values). ``encoded`` is what the encoder is fitted on: a latent
752
+ whose base is null carries no information (the target is null whatever it is), so those
753
+ rows get a value drawn from the latent's observed values. The latent's missingness
754
+ indicator then means "target missing although its base is present", and the joint model
755
+ reproduces the target's null rate (a missing base makes the target missing by itself).
756
+ ``columns`` are the modeled columns (each ``difference`` target replaced in place by its
757
+ latent, ``identity`` targets removed); ``clamped`` counts the source rows per target that
758
+ violated the ordering and were clamped to ``delta = 0``."""
759
+
760
+ frame: pl.DataFrame
761
+ encoded: pl.DataFrame
762
+ columns: list[ColumnSchema]
763
+ clamped: dict[str, int]
764
+
765
+
766
+ def _null(s: pl.Series) -> np.ndarray:
767
+ m = s.is_null()
768
+ if s.dtype.is_float():
769
+ m = m | s.is_nan().fill_null(True)
770
+ return np.asarray(m.to_numpy(), dtype=bool)
771
+
772
+
773
+ def working_frame(df: pl.DataFrame, features: Sequence[ColumnSchema],
774
+ transforms: Sequence[TransformSpec], policy: DisclosurePolicySpec | str | None,
775
+ seed: int = 0) -> WorkingFrame:
776
+ """The fit-time working frame of ``df`` (see :class:`WorkingFrame`)."""
777
+ from ectype.rng import stream
778
+
779
+ pol = resolve_policy(policy)
780
+ schemas = {c.name: c for c in features}
781
+ by_target = {t.target: t for t in transforms}
782
+ work, clamped = forward(df, transforms, schemas)
783
+ encoded = work
784
+ modeled: list[ColumnSchema] = []
785
+ for c in features:
786
+ t = by_target.get(c.name)
787
+ if t is None:
788
+ modeled.append(c)
789
+ continue
790
+ if t.kind != "difference":
791
+ continue
792
+ lat = latent_schema(t)
793
+ vals = _latent_values(work, lat.name)
794
+ obs = vals[np.isfinite(vals)]
795
+ fill = _null(work.get_column(t.inputs[0])) & ~np.isfinite(vals)
796
+ if fill.any() and obs.size:
797
+ rng = stream(seed, "structure", "fill", t.target)
798
+ filled = vals.copy()
799
+ filled[fill] = rng.choice(obs, size=int(fill.sum()), replace=True)
800
+ encoded = encoded.with_columns(
801
+ pl.Series(lat.name, filled, dtype=pl.Float64).fill_nan(None))
802
+ nulls = int(_null(encoded.get_column(lat.name)).sum())
803
+ hi = None
804
+ if obs.size:
805
+ upper = clip_bounds(obs, pol)[1]
806
+ hi = float(upper) if math.isfinite(upper) else None
807
+ modeled.append(lat.model_copy(update={
808
+ "nullable": nulls > 0,
809
+ "null_fraction": float(nulls / max(work.height, 1)),
810
+ "max_value": hi}))
811
+ return WorkingFrame(work, encoded, modeled, clamped)
812
+
813
+
814
+ # ---------------------------------------------------------------------------------------------
815
+ # Encoder facade
816
+ # ---------------------------------------------------------------------------------------------
817
+
818
+
819
+ class StructuredEncoder:
820
+ """The original-column view of a :class:`~ectype.models.encoding.MixedEncoder` fitted on a
821
+ working frame. ``decode`` returns the source columns (targets recomputed, orderings
822
+ enforced by :func:`redraw`, hidden latents dropped) and ``encode`` accepts them (latents
823
+ derived with :func:`forward`, unclamped), so every consumer of ``Generator.encoder`` keeps
824
+ working with source columns only. ``latent_columns`` are the inner encoder's (they match
825
+ the joint model).
826
+
827
+ With ``calendars`` (format 0.4, ADR-0012) ``decode`` then restores the weekly pattern of
828
+ the date columns (:func:`~ectype.profiling.calendar.apply_calendars`). That step draws
829
+ one uniform number per row and calendar from the ``rng`` given to ``decode``; nothing else
830
+ in decoding is random. ``complete`` does not run it.
831
+
832
+ With ``sums`` (format 0.4, ADR-0014) the columns a sum computes are computed last, from
833
+ the final value of their total or parts (:func:`~ectype.profiling.sums.apply_sums`); the
834
+ hidden shares are handled like the latents of a difference (``schemas`` must hold
835
+ theirs)."""
836
+
837
+ def __init__(self, inner: MixedEncoder, transforms: Sequence[TransformSpec],
838
+ schemas: Mapping[str, ColumnSchema],
839
+ orderings: Sequence[OrderingSpec] = (),
840
+ calendars: Sequence[CalendarSpec] = (),
841
+ sums: Sequence[SumSpec] = ()) -> None:
842
+ from ectype.profiling.sums import computed_columns, order_sums
843
+
844
+ self.inner = inner
845
+ self.transforms = order_transforms(transforms)
846
+ self.orderings = list(orderings)
847
+ self.calendars = list(calendars)
848
+ self.sums = order_sums(sums)
849
+ #: transforms and orderings in the order they run after decoding
850
+ self.steps = order_steps(self.transforms, self.orderings)
851
+ self.schemas = dict(schemas)
852
+ to_target = {str(t.params["latent"]): t.target for t in self.transforms
853
+ if t.kind == "difference"}
854
+ to_target.update({latent: part for spec in self.sums
855
+ for latent, part in zip(spec.latents, spec.parts)})
856
+ self.hidden = set(to_target)
857
+ #: source columns the encoder consumes (each latent replaced by its target)
858
+ self.columns = [to_target.get(c, c) for c in inner.columns]
859
+ self._derived = [t.target for t in self.transforms if t.kind == "identity"]
860
+ self._derived += [c for c in computed_columns(self.sums) if c not in self.columns]
861
+
862
+ @property
863
+ def latent_columns(self) -> list[str]:
864
+ return list(self.inner.latent_columns)
865
+
866
+ @property
867
+ def conditional_parents(self) -> dict[str, str]:
868
+ return self.inner.conditional_parents
869
+
870
+ @property
871
+ def missing_rates(self) -> dict[str, float]:
872
+ return self.inner.missing_rates
873
+
874
+ @property
875
+ def missing_columns(self) -> list[str]:
876
+ return self.inner.missing_columns
877
+
878
+ def encode(self, df: pl.DataFrame, rng: np.random.Generator) -> np.ndarray:
879
+ work, _ = forward(df, self.transforms, self.schemas, clamp=False)
880
+ if self.sums:
881
+ from ectype.profiling.sums import sums_forward
882
+ work, _ = sums_forward(work, self.sums, self.schemas)
883
+ return self.inner.encode(work, rng)
884
+
885
+ def complete(self, df: pl.DataFrame) -> pl.DataFrame:
886
+ """Compute the transform targets that ``df`` lacks, enforce the orderings, in step
887
+ order, and compute what the sums compute. Idempotent on a frame that went through it.
888
+ (Calendars are not applied here: they move rows at random, once, in
889
+ :meth:`decode`.)"""
890
+ out = apply_structure(df, self.steps, self.schemas, self.inner.marginals)
891
+ return self._sums(out)
892
+
893
+ def _sums(self, df: pl.DataFrame) -> pl.DataFrame:
894
+ if not self.sums:
895
+ return df
896
+ from ectype.profiling.sums import apply_sums
897
+ return apply_sums(df, self.sums, self.schemas)
898
+
899
+ def decode(self, z: np.ndarray, rng: np.random.Generator | None = None) -> pl.DataFrame:
900
+ out = apply_structure(self.inner.decode(z, rng), self.steps, self.schemas,
901
+ self.inner.marginals)
902
+ if self.calendars:
903
+ out = apply_calendars(out, self.calendars, self.schemas, rng)
904
+ out = self._sums(out)
905
+ order = [*self.columns, *[c for c in self._derived if c not in self.columns]]
906
+ return out.select(order)
907
+
908
+
909
+ # ---------------------------------------------------------------------------------------------
910
+ # Detection
911
+ # ---------------------------------------------------------------------------------------------
912
+
913
+
914
+ def target_ks_limit(rows: int) -> float:
915
+ """Largest distance :func:`gap_dependence` may report for a difference to be used:
916
+ ``MAX_TARGET_KS`` plus the sampling noise of the statistic on ``rows`` rows."""
917
+ return float(min(MAX_TARGET_KS + TARGET_KS_NOISE / math.sqrt(max(int(rows), 1)),
918
+ TARGET_KS_CAP))
919
+
920
+
921
+ def _normal_scores(x: np.ndarray, rng: np.random.Generator) -> np.ndarray:
922
+ """Normal scores of the ranks of ``x``, ties broken at random (a randomized PIT)."""
923
+ n = x.size
924
+ rank = np.empty(n, dtype=np.float64)
925
+ rank[np.lexsort((rng.random(n), x))] = np.arange(n)
926
+ return np.asarray(special.ndtri((rank + 0.5) / n), dtype=np.float64)
927
+
928
+
929
+ def _ks_distance(a: np.ndarray, b: np.ndarray) -> float:
930
+ a, b = np.sort(a), np.sort(b)
931
+ grid = np.concatenate([a, b])
932
+ return float(np.max(np.abs(np.searchsorted(a, grid, side="right") / a.size
933
+ - np.searchsorted(b, grid, side="right") / b.size)))
934
+
935
+
936
+ def _spearman(x: np.ndarray, y: np.ndarray) -> float:
937
+ if x.size < 3 or np.ptp(x) == 0 or np.ptp(y) == 0:
938
+ return 0.0
939
+ rho = float(stats.spearmanr(x, y).statistic)
940
+ return rho if math.isfinite(rho) else 0.0
941
+
942
+
943
+ def gap_dependence(base: np.ndarray, target: np.ndarray, sign: int = 1, *, clamp: bool = False,
944
+ rng: np.random.Generator | None = None) -> dict[str, float]:
945
+ """What modeling ``target = base + sign * gap`` would do to the target's distribution.
946
+
947
+ A difference transform stores the marginal of the gap and leaves the dependence between
948
+ base and gap to the joint model. When the gap is (nearly) independent of the base that is
949
+ all there is to know, and the target comes out right. When the gap depends strongly on the
950
+ base, e.g. ``target = max(base, c) + lag``, whatever the joint model misses of that
951
+ dependence lands in the target, on the scale of the gap.
952
+
953
+ The statistic measures exactly that. The pair ``(base, gap)`` is given the dependence a
954
+ rank correlation can carry (a bivariate Gaussian copula fitted to the normal scores of
955
+ the two, the least any joint model here keeps), gaps are drawn from it for the observed
956
+ bases, and ``target_ks`` is the Kolmogorov-Smirnov distance between the rebuilt targets
957
+ ``base + sign * gap'`` and the real ones. It is 0 when gap and base are independent, stays
958
+ small when the gap is small against the spread of the target however dependent it is, and
959
+ is large exactly when the transform would visibly distort the target. Two rank
960
+ correlations are returned for the record (``gap_spearman`` between base and gap,
961
+ ``target_spearman`` between base and target), with the rows used and the ``limit`` of
962
+ :func:`target_ks_limit`. With ``clamp`` negative gaps count as 0, as they are modeled for
963
+ a confirmed ordering. NaN rows are ignored; at most ``DEPENDENCE_MAX_ROWS`` rows are
964
+ used.
965
+ """
966
+ rng = np.random.default_rng(0) if rng is None else rng
967
+ b = np.asarray(base, dtype=np.float64)
968
+ t = np.asarray(target, dtype=np.float64)
969
+ ok = np.isfinite(b) & np.isfinite(t)
970
+ b, t = b[ok], t[ok]
971
+ if b.size > DEPENDENCE_MAX_ROWS:
972
+ keep = np.sort(rng.choice(b.size, size=DEPENDENCE_MAX_ROWS, replace=False))
973
+ b, t = b[keep], t[keep]
974
+ n = int(b.size)
975
+ gap = float(sign) * (t - b)
976
+ if clamp:
977
+ gap = np.maximum(gap, 0.0)
978
+ t = b + float(sign) * gap
979
+ out = {"rows": float(n), "gap_spearman": 0.0, "target_spearman": 0.0, "target_ks": 0.0,
980
+ "limit": target_ks_limit(n)}
981
+ if n < 3 or np.ptp(gap) == 0 or np.ptp(b) == 0:
982
+ return out # a constant gap (or base) leaves nothing to get wrong
983
+ out["gap_spearman"] = _spearman(b, gap)
984
+ out["target_spearman"] = _spearman(b, t)
985
+ zb, zg = _normal_scores(b, rng), _normal_scores(gap, rng)
986
+ rho = float(np.corrcoef(zb, zg)[0, 1])
987
+ rho = float(np.clip(rho, -1.0, 1.0)) if math.isfinite(rho) else 0.0
988
+ resid = math.sqrt(max(1.0 - rho * rho, 0.0))
989
+ ordered = np.sort(gap)
990
+ rebuilt = []
991
+ for _ in range(DEPENDENCE_REPLICATES):
992
+ u = special.ndtr(rho * zb + resid * rng.standard_normal(n))
993
+ rebuilt.append(b + float(sign) * ordered[np.minimum((u * n).astype(np.int64), n - 1)])
994
+ out["target_ks"] = _ks_distance(t, np.concatenate(rebuilt))
995
+ return out
996
+
997
+
998
+ @dataclass
999
+ class StructurePlan:
1000
+ """What :func:`plan_structure` chose for a source table: the transforms in topological
1001
+ order, the orderings enforced without a transform, and the diagnostics."""
1002
+
1003
+ transforms: list[TransformSpec]
1004
+ orderings: list[OrderingSpec]
1005
+ diagnostics: dict[str, Any]
1006
+ #: a note for the target of each ordering modeled with its out-of-order rows: the share of
1007
+ #: source rows that break it and that about that share is generated
1008
+ notes: dict[str, str] = field(default_factory=dict)
1009
+
1010
+
1011
+ @dataclass
1012
+ class _Cand:
1013
+ kind: str # "difference" | "identity"
1014
+ source: str # "confirmed" | "suggested"
1015
+ ref: str # constraint or suggestion id
1016
+ expression: str
1017
+ confirmed: bool
1018
+ lo: str = "" # ordering lo <= hi
1019
+ hi: str = ""
1020
+ strict: bool = False
1021
+ target: str = "" # identity target = a op b
1022
+ op: str = ""
1023
+ a: str = ""
1024
+ b: str = ""
1025
+ confidence: float | None = None
1026
+ spearman: float | None = None
1027
+ null_rate: float | None = None
1028
+ violation_rate: float | None = None # share of out-of-order rows (signed candidates)
1029
+ signed: bool = False # model the out-of-order rows instead of guaranteeing lo <= hi
1030
+ index: int = 0 # declaration (or suggestion) order: the final tie-breaker
1031
+ #: how the out-of-order rows were judged (``profiling.tolerance``)
1032
+ verdict: tolerance.Verdict | None = None
1033
+
1034
+ def record(self) -> dict[str, Any]:
1035
+ out: dict[str, Any] = {"expression": self.expression, "source": self.source,
1036
+ "constraint": self.ref}
1037
+ if self.violation_rate is not None:
1038
+ out["violation_rate"] = self.violation_rate
1039
+ if self.verdict is not None and self.verdict.exceptions:
1040
+ out["tolerance"] = self.verdict.tier
1041
+ if self.confidence is not None:
1042
+ out["confidence"] = self.confidence
1043
+ if self.spearman is not None:
1044
+ out["spearman"] = self.spearman
1045
+ if self.null_rate is not None:
1046
+ out["null_violation_rate"] = self.null_rate
1047
+ return out
1048
+
1049
+
1050
+ class _Planner:
1051
+ def __init__(self, df: pl.DataFrame, columns: Sequence[ColumnSchema],
1052
+ policy: DisclosurePolicySpec, seed: int = 0) -> None:
1053
+ self.df = df
1054
+ self.policy = policy
1055
+ self.seed = int(seed)
1056
+ self.context = tolerance.Context(df, columns, policy)
1057
+ self.notes: dict[str, str] = {}
1058
+ self.by_name = {c.name: c for c in columns if c.name in df.columns}
1059
+ self.n = df.height
1060
+ self._values: dict[str, np.ndarray] = {}
1061
+ self._dependence: dict[tuple[str, str, int, bool], dict[str, float]] = {}
1062
+ self.specs: list[TransformSpec] = []
1063
+ self.orderings: dict[str, OrderingSpec] = {} # target -> ordering without a transform
1064
+ self.deps: dict[str, set[str]] = {} # target -> inputs
1065
+ self.le: dict[str, set[str]] = {} # x -> {y: x <= y by construction}
1066
+ self.le_soft: dict[str, set[str]] = {} # ... or but for the out-of-order rows
1067
+ self.applied: list[dict[str, Any]] = []
1068
+ self.enforced: list[dict[str, Any]] = []
1069
+ self.implied: list[dict[str, Any]] = []
1070
+ self.skipped: list[dict[str, Any]] = []
1071
+ self.not_selected: list[dict[str, Any]] = []
1072
+ self.pending: list[tuple[_Cand, list[str]]] = []
1073
+ self.planned: dict[str, _Cand] = {} # difference target -> its candidate
1074
+
1075
+ # -- data ---------------------------------------------------------------------------------
1076
+ def values(self, name: str) -> np.ndarray:
1077
+ if name not in self._values:
1078
+ self._values[name] = np.asarray(
1079
+ column_to_values(self.df.get_column(name), self.by_name[name]), dtype=float)
1080
+ return self._values[name]
1081
+
1082
+ def spearman(self, a: str, b: str) -> float:
1083
+ x, y = self.values(a), self.values(b)
1084
+ ok = np.isfinite(x) & np.isfinite(y)
1085
+ return _spearman(x[ok], y[ok])
1086
+
1087
+ def dependence(self, base: str, target: str, sign: int, clamp: bool) -> dict[str, float]:
1088
+ """:func:`gap_dependence` of ``target = base + sign * gap`` (cached)."""
1089
+ from ectype.rng import stream
1090
+
1091
+ key = (base, target, sign, clamp)
1092
+ if key not in self._dependence:
1093
+ self._dependence[key] = gap_dependence(
1094
+ self.values(base), self.values(target), sign, clamp=clamp,
1095
+ rng=stream(self.seed, "structure", "dependence", base, target))
1096
+ return self._dependence[key]
1097
+
1098
+ def null_violation(self, lo: str, hi: str) -> float:
1099
+ """``P(lo > hi)`` for independent draws of the two columns' observed values (how
1100
+ often separate models with no dependence would break ``lo <= hi``)."""
1101
+ x, y = self.values(lo), self.values(hi)
1102
+ x, y = x[np.isfinite(x)], np.sort(y[np.isfinite(y)])
1103
+ if x.size == 0 or y.size == 0:
1104
+ return 0.0
1105
+ return float(np.mean(np.searchsorted(y, x, side="left")) / y.size)
1106
+
1107
+ def null_mismatch(self, inputs: Sequence[str], target: str) -> float:
1108
+ """Share of rows with a null input but a present target."""
1109
+ if self.n == 0:
1110
+ return 0.0
1111
+ tnull = ~np.isfinite(self.values(target))
1112
+ inull = np.zeros(self.n, dtype=bool)
1113
+ for name in inputs:
1114
+ inull |= ~np.isfinite(self.values(name))
1115
+ return float(np.mean(inull & ~tnull))
1116
+
1117
+ def target_only_nulls(self, inputs: Sequence[str], target: str) -> float:
1118
+ """Share of rows with every input present but a null target."""
1119
+ if self.n == 0:
1120
+ return 0.0
1121
+ present = np.ones(self.n, dtype=bool)
1122
+ for name in inputs:
1123
+ present &= np.isfinite(self.values(name))
1124
+ return float(np.mean(present & ~np.isfinite(self.values(target))))
1125
+
1126
+ def c(self, x: float) -> float:
1127
+ return coarsen(float(x), self.policy)
1128
+
1129
+ # -- graph --------------------------------------------------------------------------------
1130
+ def depends_on(self, x: str, y: str) -> bool:
1131
+ """Whether ``x`` is (transitively) computed from ``y``."""
1132
+ stack, seen = [x], set()
1133
+ while stack:
1134
+ node = stack.pop()
1135
+ for dep in self.deps.get(node, ()):
1136
+ if dep == y:
1137
+ return True
1138
+ if dep not in seen:
1139
+ seen.add(dep)
1140
+ stack.append(dep)
1141
+ return False
1142
+
1143
+ def ordered(self, lo: str, hi: str, *, soft: bool = False) -> list[str] | None:
1144
+ """A chain ``lo <= ... <= hi`` guaranteed by what is planned, if any. With ``soft``
1145
+ the chain may also use signed differences, which hold but for the out-of-order rows
1146
+ they model."""
1147
+ graph = self.le_soft if soft else self.le
1148
+ prev: dict[str, str] = {}
1149
+ stack = [lo]
1150
+ while stack:
1151
+ node = stack.pop()
1152
+ for nxt in sorted(graph.get(node, ())):
1153
+ if nxt in prev or nxt == lo:
1154
+ continue
1155
+ prev[nxt] = node
1156
+ if nxt == hi:
1157
+ path = [hi]
1158
+ while path[-1] != lo:
1159
+ path.append(prev[path[-1]])
1160
+ return path[::-1]
1161
+ stack.append(nxt)
1162
+ return None
1163
+
1164
+ def skip(self, cand: _Cand, reason: str) -> None:
1165
+ self.skipped.append({**cand.record(), "kind": cand.kind, "reason": reason})
1166
+
1167
+ # -- planning -----------------------------------------------------------------------------
1168
+ def plan_identity(self, cand: _Cand) -> None:
1169
+ names = [cand.target, cand.a, cand.b]
1170
+ for name in names:
1171
+ why = _eligible(self.by_name.get(name))
1172
+ if why is None and _unit(self.by_name[name]) != "num":
1173
+ why = "not numeric"
1174
+ if why is not None:
1175
+ return self.skip(cand, f"column {name!r} cannot take part ({why})")
1176
+ if any(t.target == cand.target for t in self.specs):
1177
+ return self.skip(cand, f"{cand.target!r} is already the target of a transform")
1178
+ if any(self.depends_on(x, cand.target) for x in (cand.a, cand.b)):
1179
+ return self.skip(cand, "would create a cycle")
1180
+ mismatch = self.null_mismatch([cand.a, cand.b], cand.target)
1181
+ if mismatch > MAX_NULL_MISMATCH:
1182
+ return self.skip(cand, f"incompatible nulls: {mismatch:.2%} of rows have a null "
1183
+ f"input but a present {cand.target!r}")
1184
+ own = self.target_only_nulls([cand.a, cand.b], cand.target)
1185
+ if own > MAX_NULL_MISMATCH:
1186
+ return self.skip(cand, f"incompatible nulls: {cand.target!r} is null in {own:.2%} "
1187
+ f"of the rows where every input is present")
1188
+ dec = _decimals(self.by_name[cand.target])
1189
+ params: dict[str, Any] = {"op": cand.op, "decimals": dec, "source": cand.source,
1190
+ "constraint": cand.ref}
1191
+ self.specs.append(TransformSpec(kind="identity", target=cand.target,
1192
+ inputs=[cand.a, cand.b], params=params))
1193
+ self.deps[cand.target] = {cand.a, cand.b}
1194
+ rec = {**cand.record(), "kind": "identity", "target": cand.target,
1195
+ "inputs": [cand.a, cand.b],
1196
+ "reason": f"{'confirmed' if cand.confirmed else 'suggested'} identity "
1197
+ f"{cand.target} = {cand.a} {cand.op} {cand.b}: {cand.target!r} is "
1198
+ f"derived (rounded to {dec if dec is not None else 'full'} decimals),"
1199
+ f" not modeled"}
1200
+ if mismatch:
1201
+ rec["null_mismatch_rate"] = self.c(mismatch)
1202
+ self.applied.append(rec)
1203
+
1204
+ def plan_ordering(self, cand: _Cand) -> None:
1205
+ lo, hi = cand.lo, cand.hi
1206
+ for name in (lo, hi):
1207
+ why = _eligible(self.by_name.get(name))
1208
+ if why is not None:
1209
+ return self.skip(cand, f"column {name!r} cannot take part ({why})")
1210
+ ulo, uhi = _unit(self.by_name[lo]), _unit(self.by_name[hi])
1211
+ if ulo != uhi:
1212
+ return self.skip(cand, f"incompatible value domains ({ulo} vs {uhi})")
1213
+ if self._implied(cand):
1214
+ return None
1215
+ reasons: list[str] = []
1216
+ taken: list[tuple[str, str, int]] = []
1217
+ for target, base, sign in ((hi, lo, 1), (lo, hi, -1)):
1218
+ if any(t.target == target for t in self.specs):
1219
+ reasons.append(f"{target!r} is already the target of a transform")
1220
+ taken.append((target, base, sign))
1221
+ continue
1222
+ if self.depends_on(base, target):
1223
+ reasons.append(f"{target} = {base} {'+' if sign > 0 else '-'} delta would "
1224
+ f"create a cycle")
1225
+ continue
1226
+ fit = self._fits(cand, target, base, sign)
1227
+ if isinstance(fit, str):
1228
+ reasons.append(fit)
1229
+ continue
1230
+ self._add_difference(cand, target, base, sign, ulo or "num", *fit)
1231
+ return None
1232
+ # no direction is free and fits: one may fit once the difference in its way is turned
1233
+ for target, base, sign in taken:
1234
+ if self._turn(cand, target, base, sign, ulo or "num"):
1235
+ return None
1236
+ if cand.signed:
1237
+ # not an ordering the data keeps on every row: nothing to enforce without a model
1238
+ self.not_selected.append({**cand.record(), "kind": "difference",
1239
+ "reason": "; ".join(reasons)})
1240
+ return None
1241
+ self.pending.append((cand, reasons))
1242
+ return None
1243
+
1244
+ def _fits(self, cand: _Cand, target: str, base: str, sign: int
1245
+ ) -> tuple[float, Mapping[str, float]] | str:
1246
+ """Whether ``target = base + sign * delta`` can stand for ``cand``: the null patterns
1247
+ allow it and it does not distort the target (:func:`gap_dependence`). The null
1248
+ mismatch rate and the dependence record, or the reason it is refused."""
1249
+ mismatch = self.null_mismatch([base], target)
1250
+ if mismatch > MAX_NULL_MISMATCH:
1251
+ return (f"incompatible nulls: {mismatch:.2%} of rows have a null {base!r} but a "
1252
+ f"present {target!r}")
1253
+ dep = self.dependence(base, target, sign, cand.confirmed)
1254
+ if dep["target_ks"] > dep["limit"]:
1255
+ return (f"{target} = {base} {'+' if sign > 0 else '-'} delta would distort "
1256
+ f"{target!r}: the gap depends on {base!r} (Spearman "
1257
+ f"{dep['gap_spearman']:+.2f}, against {dep['target_spearman']:+.2f} for "
1258
+ f"{target!r} itself), and rebuilt from gaps with that rank dependence "
1259
+ f"{target!r} is at KS distance {dep['target_ks']:.3g} from the source "
1260
+ f"(limit {dep['limit']:.3g})")
1261
+ return mismatch, dep
1262
+
1263
+ def _turn(self, cand: _Cand, target: str, base: str, sign: int, unit: str) -> bool:
1264
+ """``target = base + sign * delta`` is refused only because ``target`` is already
1265
+ computed, as ``target = root +/- delta``. Turn that difference around
1266
+ (``root = target -/+ delta``), which frees ``target`` for ``cand``, when both
1267
+ differences fit that way and ``root`` is not computed itself.
1268
+
1269
+ Without this a chain is rooted wherever its first ordering was planned. For
1270
+ ``applied <= issue <= expires``, ``issue = applied + gap`` comes first; when
1271
+ ``expires = issue + gap`` would distort ``expires`` (expiry dates that follow a
1272
+ calendar of their own) nothing ties ``issue`` to ``expires`` any more, and the longer
1273
+ ordering ``applied <= expires`` then makes ``applied`` or ``expires`` a function of the
1274
+ other: the two gaps are modeled apart and ``issue <= expires`` breaks in the output.
1275
+ Rooted at ``expires`` (``issue = expires - gap``, ``applied = issue - gap``) every
1276
+ ordering of the chain is modeled."""
1277
+ old = next((t for t in self.specs if t.target == target), None)
1278
+ first = self.planned.get(target)
1279
+ if old is None or old.kind != "difference" or first is None:
1280
+ return False
1281
+ root, old_sign = old.inputs[0], int(old.params["sign"]) # type: ignore[call-overload]
1282
+ if (root == base or any(t.target == root for t in self.specs)
1283
+ or self.depends_on(base, target) or self.depends_on(base, root)):
1284
+ return False
1285
+ new_fit = self._fits(cand, target, base, sign)
1286
+ old_fit = self._fits(first, root, target, -old_sign)
1287
+ if isinstance(new_fit, str) or isinstance(old_fit, str):
1288
+ return False
1289
+ self.specs = [t for t in self.specs if t.target != target]
1290
+ self.applied = [r for r in self.applied if r.get("target") != target]
1291
+ del self.deps[target]
1292
+ self._add_difference(first, root, target, -old_sign, str(old.params["unit"]), *old_fit,
1293
+ note=f"turned around, so that {target!r} can be computed from "
1294
+ f"{base!r}")
1295
+ self._add_difference(cand, target, base, sign, unit, *new_fit)
1296
+ return True
1297
+
1298
+ def _implied(self, cand: _Cand) -> bool:
1299
+ """Record ``cand`` as implied when what is planned already gives its ordering."""
1300
+ chain = self.ordered(cand.lo, cand.hi)
1301
+ if chain is not None:
1302
+ self.implied.append({**cand.record(), "kind": "difference",
1303
+ "reason": "holds by construction through "
1304
+ + " <= ".join(chain)})
1305
+ return True
1306
+ if cand.signed:
1307
+ chain = self.ordered(cand.lo, cand.hi, soft=True)
1308
+ if chain is not None:
1309
+ self.implied.append({**cand.record(), "kind": "difference",
1310
+ "reason": "modeled, with its out-of-order rows, through "
1311
+ + " <= ".join(chain)})
1312
+ return True
1313
+ return False
1314
+
1315
+ def plan_enforcement(self, cand: _Cand, reasons: list[str]) -> None:
1316
+ """An ordering that holds (confirmed, or on every source row) but got no transform:
1317
+ enforce it at generation by a truncated redraw of one side from its own marginal."""
1318
+ if self._implied(cand):
1319
+ return None
1320
+ lo, hi = cand.lo, cand.hi
1321
+ why = list(reasons)
1322
+ computed = {t.target for t in self.specs}
1323
+ for target, bound, side in ((hi, lo, "lower"), (lo, hi, "upper")):
1324
+ if target in computed:
1325
+ continue # no marginal of its own to redraw from
1326
+ if self.depends_on(bound, target):
1327
+ why.append(f"redrawing {target!r} against {bound!r} would create a cycle")
1328
+ continue
1329
+ old = self.orderings.get(target)
1330
+ spec = old if old is not None else OrderingSpec(
1331
+ target=target, strict=cand.strict, source=cand.source)
1332
+ names = [*getattr(spec, side), bound]
1333
+ update: dict[str, Any] = {
1334
+ side: names, "strict": spec.strict and cand.strict,
1335
+ "constraints": [*spec.constraints, *([cand.ref] if cand.ref else [])]}
1336
+ if cand.confirmed:
1337
+ update["source"] = cand.source
1338
+ self.orderings[target] = spec.model_copy(update=update)
1339
+ self.deps.setdefault(target, set()).add(bound)
1340
+ for graph in (self.le, self.le_soft):
1341
+ graph.setdefault(lo, set()).add(hi)
1342
+ rel = ">=" if side == "lower" else "<="
1343
+ self.enforced.append({
1344
+ **cand.record(), "kind": "ordering", "target": target, side: [bound],
1345
+ "method": "reflect",
1346
+ "reason": f"{'confirmed' if cand.confirmed else 'suggested'} ordering "
1347
+ f"{lo} {'<' if cand.strict else '<='} {hi}: {target!r} keeps its own "
1348
+ f"marginal, and a generated row that breaks {target} {rel} {bound} "
1349
+ f"gets a new {target!r} from that marginal truncated at {bound!r}",
1350
+ "no_transform": "; ".join(reasons)})
1351
+ return None
1352
+ return self.skip(cand, "; ".join(why) or "both columns are computed by a transform")
1353
+
1354
+ def _add_difference(self, cand: _Cand, target: str, base: str, sign: int, unit: str,
1355
+ mismatch: float, dep: Mapping[str, float], note: str = "") -> None:
1356
+ tcol, bcol = self.by_name[target], self.by_name[base]
1357
+ dec: int | None
1358
+ if unit == "d" or (unit == "num" and tcol.integer_valued and bcol.integer_valued):
1359
+ ltype, dec = LogicalType.DISCRETE.value, 0
1360
+ else:
1361
+ ltype = LogicalType.CONTINUOUS.value
1362
+ dt, db = _decimals(tcol), _decimals(bcol)
1363
+ dec = None if unit == "us" or dt is None or db is None else max(dt, db)
1364
+ latent = delta_name(target)
1365
+ params: dict[str, Any] = {"latent": latent, "sign": sign, "strict": cand.strict,
1366
+ "unit": unit, "latent_type": ltype, "decimals": dec,
1367
+ "source": cand.source, "constraint": cand.ref}
1368
+ if cand.signed:
1369
+ params["signed"] = True
1370
+ self.specs.append(TransformSpec(kind="difference", target=target, inputs=[base],
1371
+ params=params))
1372
+ self.deps[target] = {base}
1373
+ self.planned[target] = cand
1374
+ lo, hi = (base, target) if sign > 0 else (target, base)
1375
+ for graph in ((self.le_soft,) if cand.signed else (self.le, self.le_soft)):
1376
+ graph.setdefault(lo, set()).add(hi)
1377
+ op = "+" if sign > 0 else "-"
1378
+ if cand.signed:
1379
+ reason = (f"ordering {cand.lo} <= {cand.hi} with "
1380
+ f"{cand.violation_rate or 0.0:.3g} of the rows out of order: {target} = "
1381
+ f"{base} {op} {latent}, with the signed {latent} modeled in place of "
1382
+ f"{target!r} (the out-of-order rows are part of the model, not repaired)")
1383
+ else:
1384
+ reason = (f"{'confirmed' if cand.confirmed else 'suggested'} ordering "
1385
+ f"{cand.lo} {'<' if cand.strict else '<='} {cand.hi}: {target} = "
1386
+ f"{base} {op} {latent} with {latent} >= 0 modeled in place of "
1387
+ f"{target!r}")
1388
+ if note:
1389
+ reason += f" ({note})"
1390
+ if cand.signed and cand.verdict is not None:
1391
+ self.notes[target] = (
1392
+ f"modeled as {base} {op} a signed gap (detected ordering {cand.lo} <= "
1393
+ f"{cand.hi}); " + tolerance.note(cand.verdict, self.policy,
1394
+ breaks="are out of order", reproduced=True))
1395
+ rec = {**cand.record(), "kind": "difference", "target": target, "inputs": [base],
1396
+ "latent": latent, "reason": reason,
1397
+ "gap_spearman": self.c(dep["gap_spearman"]),
1398
+ "target_spearman": self.c(dep["target_spearman"]),
1399
+ "target_ks": self.c(dep["target_ks"])}
1400
+ if mismatch:
1401
+ rec["null_mismatch_rate"] = self.c(mismatch)
1402
+ self.applied.append(rec)
1403
+
1404
+
1405
+ def _confirmed_candidates(constraints: Sequence[ConstraintSpec]) -> list[_Cand]:
1406
+ out: list[_Cand] = []
1407
+ for spec in constraints:
1408
+ if spec.severity != Severity.HARD or spec.enforcement == Enforcement.NONE:
1409
+ continue
1410
+ try:
1411
+ node = parse(spec.expression)
1412
+ except Exception: # noqa: BLE001 - invalid expressions are reported by the profiler
1413
+ continue
1414
+ ident = identity_form(node)
1415
+ if ident is not None:
1416
+ c, op, a, b = ident
1417
+ out.append(_Cand("identity", "confirmed", spec.id, spec.expression, True,
1418
+ target=c, op=op, a=a, b=b))
1419
+ continue
1420
+ order = ordering_form(node)
1421
+ if order is not None:
1422
+ lo, hi, strict = order
1423
+ out.append(_Cand("difference", "confirmed", spec.id, spec.expression, True,
1424
+ lo=lo, hi=hi, strict=strict))
1425
+ return out
1426
+
1427
+
1428
+ def _suggested_candidates(planner: _Planner, suggestions: Sequence[SuggestedConstraint],
1429
+ ) -> tuple[list[_Cand], list[dict[str, Any]]]:
1430
+ """Suggestions that meet the auto-mode criteria, the orderings with a few out-of-order
1431
+ rows found by :func:`_scan_orderings`, and a record of the orderings and identities
1432
+ between modelable columns that did not qualify (``not_selected``)."""
1433
+ out: list[_Cand] = []
1434
+ passed_over: list[dict[str, Any]] = []
1435
+ soft: dict[tuple[str, str], SuggestedConstraint] = {}
1436
+ for s in suggestions:
1437
+ if s.family not in ("ordering", "identity"):
1438
+ continue
1439
+ try:
1440
+ node = parse(s.expression)
1441
+ except Exception: # noqa: BLE001 - suggestions always parse; be defensive anyway
1442
+ continue
1443
+ ident = identity_form(node) if s.family == "identity" else None
1444
+ order = ordering_form(node) if s.family == "ordering" else None
1445
+ if ident is not None:
1446
+ names = [ident[0], ident[2], ident[3]]
1447
+ elif order is not None:
1448
+ names = [order[0], order[1]]
1449
+ else:
1450
+ continue
1451
+ if any(_eligible(planner.by_name.get(x)) is not None for x in names):
1452
+ continue # e.g. a user-derived column: nothing to model
1453
+ conf = float(s.confidence)
1454
+ rec = {"expression": s.expression, "source": "suggested", "constraint": s.id,
1455
+ "kind": "identity" if ident is not None else "difference",
1456
+ "confidence": planner.c(conf)}
1457
+ if order is not None and s.violations > 0:
1458
+ soft.setdefault((order[0], order[1]), s) # the scan below measures the pair
1459
+ continue
1460
+ if s.violations > 0 or conf < AUTO_MIN_CONFIDENCE:
1461
+ passed_over.append({**rec, "reason": f"auto mode needs 0 violations and confidence"
1462
+ f" >= {AUTO_MIN_CONFIDENCE} (got "
1463
+ f"{s.violations} violations, confidence "
1464
+ f"{conf:.3g})"})
1465
+ continue
1466
+ if ident is not None:
1467
+ c, op, a, b = ident
1468
+ out.append(_Cand("identity", "suggested", s.id, s.expression, False, target=c,
1469
+ op=op, a=a, b=b, confidence=planner.c(conf)))
1470
+ continue
1471
+ assert order is not None
1472
+ lo, hi, strict = order
1473
+ rho = planner.spearman(lo, hi)
1474
+ if abs(rho) < AUTO_MIN_SPEARMAN:
1475
+ passed_over.append({**rec, "spearman": planner.c(rho),
1476
+ "reason": f"|Spearman| {abs(rho):.3g} < {AUTO_MIN_SPEARMAN}: "
1477
+ f"the ordering may be a coincidence of the "
1478
+ f"marginals"})
1479
+ continue
1480
+ p0 = planner.null_violation(lo, hi)
1481
+ if p0 < AUTO_MIN_NULL_VIOLATION:
1482
+ passed_over.append({**rec, "spearman": planner.c(rho),
1483
+ "null_violation_rate": planner.c(p0),
1484
+ "reason": f"the columns barely overlap: independent draws give "
1485
+ f"{lo} > {hi} in {p0:.3g} of pairs (< "
1486
+ f"{AUTO_MIN_NULL_VIOLATION}), so separate models "
1487
+ f"rarely break the ordering"})
1488
+ continue
1489
+ out.append(_Cand("difference", "suggested", s.id, s.expression, False, lo=lo, hi=hi,
1490
+ strict=strict, confidence=planner.c(conf), spearman=planner.c(rho),
1491
+ null_rate=planner.c(p0)))
1492
+ screened = max([int(s.candidates_screened) for s in suggestions], default=1)
1493
+ found, more = _scan_orderings(planner, soft, {(c.lo, c.hi) for c in out}, screened)
1494
+ for pair, s in soft.items():
1495
+ if not any((c.lo, c.hi) == pair for c in found) and \
1496
+ not any(r.get("constraint") == s.id for r in more):
1497
+ more.append({"expression": s.expression, "source": "suggested", "constraint": s.id,
1498
+ "kind": "difference", "confidence": planner.c(float(s.confidence)),
1499
+ "reason": f"auto mode needs 0 violations and confidence >= "
1500
+ f"{AUTO_MIN_CONFIDENCE}, or at most {AUTO_MAX_VIOLATION:.1%} "
1501
+ f"of the rows out of order ({tolerance.DIRTY:.0%} when "
1502
+ f"they are isolated; got {s.violations} violations "
1503
+ f"on {s.support} rows)"})
1504
+ return out + found, passed_over + more
1505
+
1506
+
1507
+ def _where(planner: _Planner, broken: np.ndarray, both: np.ndarray, lo: str, hi: str,
1508
+ x: np.ndarray, y: np.ndarray) -> Callable[[], tolerance.Isolation]:
1509
+ """The test of where the out-of-order rows of ``lo <= hi`` are, for ``tolerance.judge``:
1510
+ scattered, or gathered in a stretch of either column or a category of another one."""
1511
+ def test() -> tolerance.Isolation:
1512
+ return planner.context.scattered(broken, [lo, hi], scope=both, ranges={lo: x, hi: y})
1513
+ return test
1514
+
1515
+
1516
+ def _scan_orderings(planner: _Planner, soft: Mapping[tuple[str, str], SuggestedConstraint],
1517
+ taken: set[tuple[str, str]], screened: int
1518
+ ) -> tuple[list[_Cand], list[dict[str, Any]]]:
1519
+ """Orderings ``lo <= hi`` between modelable columns that hold on all but a few rows of
1520
+ those where both are present: more than none, and few by the shared rule of
1521
+ ``profiling.tolerance`` (at most ``AUTO_MAX_VIOLATION`` of them anywhere, or up to
1522
+ ``tolerance.DIRTY`` when the out-of-order rows are isolated).
1523
+
1524
+ Such a pair is a candidate for a *signed* difference when the same evidence as for a
1525
+ suggestion is there: the chance of so few out-of-order rows if the columns were unrelated
1526
+ (independent draws of their values; Bonferroni over the candidates screened) is below
1527
+ ``1 - AUTO_MIN_CONFIDENCE``, ``|Spearman| >= AUTO_MIN_SPEARMAN``, and the columns
1528
+ overlap (``AUTO_MIN_NULL_VIOLATION``). ``soft`` maps a pair to its suggestion, when the
1529
+ profiler made one with violations (it only does for at most 0.1% of them); ``taken`` are
1530
+ pairs that are candidates already. A suggested pair without a single out-of-order row is
1531
+ the strict ordering ``lo < hi`` with a few ties: ``lo <= hi`` holds on every row, and it
1532
+ is a candidate like any other suggestion that does (not signed). Returns the candidates
1533
+ and the pairs passed over, with reasons (a pair without that evidence is only recorded
1534
+ when the profiler suggested it)."""
1535
+ from ectype.fingerprint.expressions import unparse
1536
+
1537
+ names = [n for n, c in planner.by_name.items() if _eligible(c) is None]
1538
+ pairs = [(a, b) for i, a in enumerate(names) for b in names[i + 1:]
1539
+ if _unit(planner.by_name[a]) == _unit(planner.by_name[b])][:MAX_SCAN_PAIRS]
1540
+ m = max(int(screened), 2 * len(pairs), 1)
1541
+ out: list[_Cand] = []
1542
+ passed_over: list[dict[str, Any]] = []
1543
+ for a, b in pairs:
1544
+ x, y = planner.values(a), planner.values(b)
1545
+ ok = np.isfinite(x) & np.isfinite(y)
1546
+ n = int(ok.sum())
1547
+ allowed = tolerance.dirty_limit(n) # the most any tier of the rule allows
1548
+ for lo, hi, v in ((a, b, int(np.sum(x[ok] > y[ok]))), (b, a, int(np.sum(y[ok] > x[ok])))):
1549
+ s = soft.get((lo, hi))
1550
+ if v > allowed or (lo, hi) in taken or (v == 0 and s is None) or n < 3:
1551
+ continue
1552
+ expr = unparse(Binary("<=", Column(lo), Column(hi)))
1553
+ p0 = planner.null_violation(lo, hi)
1554
+ log_p = float(stats.binom.logcdf(v, n, min(max(p0, 1e-300), 1.0)))
1555
+ conf = max(float(-math.expm1(min(0.0, math.log(m) + log_p))), 0.0)
1556
+ if conf < AUTO_MIN_CONFIDENCE and s is None:
1557
+ continue # unrelated columns that happen to overlap a little
1558
+ rho = planner.spearman(lo, hi)
1559
+ rec = {"expression": expr, "source": "suggested" if s is not None else "detected",
1560
+ "constraint": s.id if s is not None else "", "kind": "difference",
1561
+ "confidence": planner.c(conf), "spearman": planner.c(rho),
1562
+ "null_violation_rate": planner.c(p0)}
1563
+ if v:
1564
+ rec["violation_rate"] = planner.c(v / n)
1565
+ if conf < AUTO_MIN_CONFIDENCE:
1566
+ why = (f"confidence {conf:.3g} < {AUTO_MIN_CONFIDENCE} that so few "
1567
+ f"out-of-order rows are not a coincidence")
1568
+ elif abs(rho) < AUTO_MIN_SPEARMAN:
1569
+ why = (f"|Spearman| {abs(rho):.3g} < {AUTO_MIN_SPEARMAN}: the ordering may be "
1570
+ f"a coincidence of the marginals")
1571
+ elif p0 < AUTO_MIN_NULL_VIOLATION:
1572
+ why = (f"the columns barely overlap: independent draws give {lo} > {hi} in "
1573
+ f"{p0:.3g} of pairs (< {AUTO_MIN_NULL_VIOLATION}), so separate models "
1574
+ f"rarely break the ordering")
1575
+ else:
1576
+ # the evidence is there: are the out-of-order rows few enough, and where?
1577
+ vx, vy = (x, y) if lo == a else (y, x)
1578
+ broken = ok & (vx > vy)
1579
+ verdict = tolerance.judge(v, n, _where(planner, broken, ok, lo, hi, vx, vy))
1580
+ if verdict.holds:
1581
+ out.append(_Cand("difference", str(rec["source"]), str(rec["constraint"]),
1582
+ expr, False, lo=lo, hi=hi, strict=False,
1583
+ confidence=planner.c(conf), spearman=planner.c(rho),
1584
+ null_rate=planner.c(p0),
1585
+ violation_rate=planner.c(v / n) if v else None,
1586
+ signed=v > 0, verdict=verdict))
1587
+ continue
1588
+ why = verdict.reason("are out of order")
1589
+ rec.update({k: val for k, val in verdict.record(planner.policy).items()
1590
+ if k != "exception_rate"})
1591
+ passed_over.append({**rec, "reason": why})
1592
+ return out, passed_over
1593
+
1594
+
1595
+ def _spans(edges: Sequence[tuple[str, str]]) -> dict[tuple[str, str], int]:
1596
+ """Length of the longest path ``lo -> ... -> hi`` for every edge of a DAG (edges in a
1597
+ cycle get 0)."""
1598
+ succ: dict[str, set[str]] = {}
1599
+ for lo, hi in edges:
1600
+ succ.setdefault(lo, set()).add(hi)
1601
+
1602
+ def reach(src: str, dst: str) -> bool:
1603
+ stack, seen = [src], {src}
1604
+ while stack:
1605
+ node = stack.pop()
1606
+ for nxt in succ.get(node, ()):
1607
+ if nxt == dst:
1608
+ return True
1609
+ if nxt not in seen:
1610
+ seen.add(nxt)
1611
+ stack.append(nxt)
1612
+ return False
1613
+
1614
+ cyclic = {e for e in edges if reach(e[1], e[0])}
1615
+ dag = {lo: {hi for hi in his if (lo, hi) not in cyclic} for lo, his in succ.items()}
1616
+ memo: dict[tuple[str, str], int] = {}
1617
+
1618
+ def longest(src: str, dst: str) -> int:
1619
+ """Longest path length src -> dst in the DAG (-1 if unreachable)."""
1620
+ key = (src, dst)
1621
+ if key not in memo:
1622
+ best = -1
1623
+ for nxt in dag.get(src, ()):
1624
+ if nxt == dst:
1625
+ best = max(best, 1)
1626
+ else:
1627
+ sub = longest(nxt, dst)
1628
+ if sub >= 0:
1629
+ best = max(best, sub + 1)
1630
+ memo[key] = best
1631
+ return memo[key]
1632
+
1633
+ return {e: (0 if e in cyclic else max(longest(*e), 1)) for e in edges}
1634
+
1635
+
1636
+ def plan_structure(df: pl.DataFrame, columns: Sequence[ColumnSchema],
1637
+ policy: DisclosurePolicySpec | str | None,
1638
+ confirmed_constraints: Sequence[ConstraintSpec],
1639
+ suggestions: Sequence[SuggestedConstraint] | None,
1640
+ mode: str = "auto", seed: int = 0) -> StructurePlan:
1641
+ """Choose how the structural relationships of a source table are modeled (see the module
1642
+ docstring): the transforms in topological order, the orderings enforced without a
1643
+ transform, and a JSON-safe record of what was applied, enforced, what holds by
1644
+ construction through other transforms (``implied``), and what was skipped or not selected
1645
+ and why. ``suggestions=None`` (no screening was done) leaves auto mode with the confirmed
1646
+ constraints only. ``seed`` keys the random numbers of :func:`gap_dependence`.
1647
+ """
1648
+ if mode not in MODES:
1649
+ raise ValueError(f"structure must be one of {list(MODES)}, got {mode!r}")
1650
+ pol = resolve_policy(policy)
1651
+ diag: dict[str, Any] = {"mode": mode, "applied": [], "enforced": [], "implied": [],
1652
+ "skipped": []}
1653
+ if mode == "off":
1654
+ return StructurePlan([], [], diag)
1655
+ planner = _Planner(df, columns, pol, seed)
1656
+ cands = _confirmed_candidates(confirmed_constraints)
1657
+ if mode == "auto":
1658
+ sugg, passed_over = (_suggested_candidates(planner, suggestions)
1659
+ if suggestions is not None else ([], []))
1660
+ planner.not_selected = passed_over
1661
+ cands += sugg
1662
+ for i, cand in enumerate(cands):
1663
+ cand.index = i
1664
+ if cands:
1665
+ diag["thresholds"] = {"min_confidence": AUTO_MIN_CONFIDENCE,
1666
+ "min_abs_spearman": AUTO_MIN_SPEARMAN,
1667
+ "min_null_violation_rate": AUTO_MIN_NULL_VIOLATION,
1668
+ "max_null_mismatch": MAX_NULL_MISMATCH,
1669
+ "max_violation_rate": AUTO_MAX_VIOLATION,
1670
+ "max_dirty_rate": tolerance.DIRTY,
1671
+ "dense_rate": tolerance.DENSE_RATE,
1672
+ "systematic_share": tolerance.SYSTEMATIC_SHARE,
1673
+ "max_target_ks": MAX_TARGET_KS}
1674
+
1675
+ # identities first (exact formulas), confirmed before suggested
1676
+ idents = [c for c in cands if c.kind == "identity"]
1677
+ seen_ident: set[tuple[str, str, frozenset[str]]] = set()
1678
+ for cand in sorted(idents, key=lambda c: (not c.confirmed, -(c.confidence or 1.0),
1679
+ c.index)):
1680
+ ikey = (cand.target, cand.op, frozenset((cand.a, cand.b)))
1681
+ if ikey in seen_ident:
1682
+ continue
1683
+ seen_ident.add(ikey)
1684
+ planner.plan_identity(cand)
1685
+
1686
+ # orderings: one candidate per pair (confirmed wins), shortest span first; among equals
1687
+ # an ordering that holds before one that is modeled with its out-of-order rows
1688
+ by_pair: dict[tuple[str, str], _Cand] = {}
1689
+ for cand in (c for c in cands if c.kind == "difference"):
1690
+ key = (cand.lo, cand.hi)
1691
+ old = by_pair.get(key)
1692
+ if old is None or (cand.confirmed and not old.confirmed):
1693
+ by_pair[key] = cand
1694
+ spans = _spans(list(by_pair))
1695
+ order = sorted(by_pair.values(), key=lambda c: (
1696
+ spans[(c.lo, c.hi)] == 0, spans[(c.lo, c.hi)], not c.confirmed, c.signed,
1697
+ -abs(c.spearman if c.spearman is not None else 1.0), c.index))
1698
+ for cand in order:
1699
+ if spans[(cand.lo, cand.hi)] == 0:
1700
+ planner.skip(cand, "cyclic orderings: the columns are equal on every row or the "
1701
+ "orderings contradict each other")
1702
+ continue
1703
+ planner.plan_ordering(cand)
1704
+ # an ordering that holds but got no transform is enforced by redrawing one of its sides;
1705
+ # only now, so that a column is never both redrawn and computed
1706
+ for cand, reasons in planner.pending:
1707
+ planner.plan_enforcement(cand, reasons)
1708
+
1709
+ transforms = order_transforms(planner.specs)
1710
+ orderings = list(planner.orderings.values())
1711
+ order_steps(transforms, orderings) # raises on a cycle (a planner bug)
1712
+ diag["applied"] = planner.applied
1713
+ diag["enforced"] = planner.enforced
1714
+ diag["implied"] = planner.implied
1715
+ diag["skipped"] = planner.skipped
1716
+ if mode == "auto":
1717
+ diag["not_selected"] = planner.not_selected
1718
+ kept = {t.target for t in transforms}
1719
+ return StructurePlan(transforms, orderings, diag,
1720
+ {k: v for k, v in planner.notes.items() if k in kept})
1721
+
1722
+
1723
+ def plan_transforms(df: pl.DataFrame, columns: Sequence[ColumnSchema],
1724
+ policy: DisclosurePolicySpec | str | None,
1725
+ confirmed_constraints: Sequence[ConstraintSpec],
1726
+ suggestions: Sequence[SuggestedConstraint] | None,
1727
+ mode: str = "auto", seed: int = 0
1728
+ ) -> tuple[list[TransformSpec], dict[str, Any]]:
1729
+ """``(transforms, diagnostics)`` of :func:`plan_structure`, for callers that only need the
1730
+ transforms. The orderings enforced without a transform are listed in
1731
+ ``diagnostics["enforced"]``; use :func:`plan_structure` to get their specs."""
1732
+ plan = plan_structure(df, columns, policy, confirmed_constraints, suggestions, mode, seed)
1733
+ return plan.transforms, plan.diagnostics