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,352 @@
1
+ """Target construction, sealing partition and evaluation (M8).
2
+
3
+ ``build_targets`` measures a broad set of properties of the source (one ``Target`` per metric x
4
+ column group), attaches a tolerance and a bootstrap CI, and partitions them into calibration and
5
+ sealed sets.
6
+
7
+ Pair selection
8
+ Bivariate targets are built for at most ``max_pairs`` column pairs: half the budget goes to
9
+ the strongest associations found by ``profiling.bivariate.association_matrix``; the rest is a
10
+ deterministic random sample (``rng.stream(seed, "pairs")``) of the other pairs so that
11
+ independence is verified too. ``missingness.co_missing`` targets are built for pairs of
12
+ columns that both contain nulls (same cap).
13
+
14
+ Partition (deterministic from ``seed``)
15
+ * Family-level seal: every target of ``SEALED_FAMILIES`` (kendall, mutual_info, contingency,
16
+ co_missing, univariate.tail and univariate.granularity) is sealed.
17
+ * Never sealed: the other univariate families (wasserstein, ks, mean_std, frequencies,
18
+ missing_rate) stay in calibration.
19
+ * The remaining pair-level targets are grouped by column pair, and ``sealed_fraction`` of the
20
+ pairs (chosen with ``rng.stream(seed, "seal")``) are sealed as a whole group.
21
+
22
+ Tolerances
23
+ ``tolerance = max(metric.default_tolerance, noise_floor)`` where the noise floor is the 95%
24
+ quantile of the distance between the full-data summary and ``n_boot <= 10`` bootstrap
25
+ resamples of size ``m = min(n, 10000)`` drawn from a subsample of at most 20000 rows
26
+ (``max(n_boot, metric.n_boot_min)`` resamples: Pearson asks for ``N_BOOT_HEAVY`` because
27
+ under heavy tails a handful of extreme rows dominate it and 10 resamples miss most of that
28
+ variability; the first ``n_boot`` resamples are shared by all metrics), inflated
29
+ by ``sqrt(1 + m / n)`` to account for the reference's own sampling noise (an independent
30
+ sample of size ``m`` compared to a reference of size ``n``). Scalar targets also get a 95%
31
+ bootstrap CI (rescaled to the full sample size).
32
+
33
+ Rare levels (re-identification guard)
34
+ A pair statistic involving a column with a level held by very few rows reveals those rows'
35
+ values: with a boolean true for one row out of ``n``, ``pearson(flag, x)`` together with the
36
+ stored ``mean_std(x)`` gives that row's exact ``x``. Categorical metrics already pool levels
37
+ below ``min_category_support`` into ``"__other__"``, so a categorical column is safe when
38
+ that pool is empty or itself holds at least ``min_category_support`` rows. A boolean column
39
+ (used as 0/1, never pooled), a categorical column whose pool is smaller than that support,
40
+ or a low-cardinality discrete code (at most ``RARE_DISCRETE_MAX_LEVELS`` values, used as
41
+ numbers, never pooled) with a value held by fewer than that support is *rare-level*: no pairwise target (pearson, spearman, kendall, cramers_v,
42
+ correlation_ratio, mutual_info, contingency) is built for any pair containing it, and the
43
+ column is left out of pair selection. Its univariate targets remain (frequencies pool and
44
+ round rare counts up to the support). Likewise ``univariate.missing_rate`` is not stored for
45
+ a column with between 1 and ``min_category_support - 1`` nulls (it would reveal that a
46
+ handful of rows lack the value); ``co_missing`` suppresses rare counts already.
47
+
48
+ Data-requiring metrics (``requires_data = True``: multivariate energy, c2st) are never stored.
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import math
54
+ from collections.abc import Sequence
55
+ from itertools import combinations
56
+ from typing import Any
57
+
58
+ import numpy as np
59
+ import polars as pl
60
+
61
+ from ectype.fingerprint.disclosure import OTHER, coarsen, resolve_policy
62
+ from ectype.fingerprint.schema import (
63
+ ColumnSchema,
64
+ DisclosurePolicySpec,
65
+ Target,
66
+ TargetSet,
67
+ )
68
+ from ectype.profiling.bivariate import association_matrix
69
+ from ectype.rng import stream
70
+ from ectype.types import MODELED_ROLES, LogicalType, Role
71
+ from ectype.validation.metrics import ( # noqa: F401 (registration side effects)
72
+ bivariate,
73
+ missingness,
74
+ multivariate,
75
+ univariate,
76
+ )
77
+ from ectype.validation.metrics.base import METRICS, Metric
78
+ from ectype.validation.metrics.missingness import null_mask
79
+ from ectype.validation.metrics.univariate import (
80
+ is_category,
81
+ is_numeric_like,
82
+ label_series,
83
+ )
84
+
85
+ SEALED_FAMILIES: tuple[str, ...] = (
86
+ "bivariate.kendall",
87
+ "bivariate.mutual_info",
88
+ "bivariate.contingency",
89
+ "missingness.co_missing",
90
+ "univariate.tail",
91
+ "univariate.granularity",
92
+ )
93
+ CALIBRATION_FAMILIES: tuple[str, ...] = (
94
+ "univariate.wasserstein",
95
+ "univariate.ks",
96
+ "univariate.mean_std",
97
+ "univariate.frequencies",
98
+ "univariate.missing_rate",
99
+ )
100
+
101
+ N_BOOT = 10
102
+ BOOT_SAMPLE_SIZE = 10_000
103
+ BOOT_MAX_ROWS = 20_000
104
+
105
+
106
+ def target_id(metric: str, columns: Sequence[str]) -> str:
107
+ return f"{metric}:{'|'.join(columns)}"
108
+
109
+
110
+ def _requires_data(cls: type[Metric]) -> bool:
111
+ return bool(getattr(cls, "requires_data", False))
112
+
113
+
114
+ def _feature_columns(df: pl.DataFrame, columns: list[ColumnSchema]) -> list[ColumnSchema]:
115
+ out = []
116
+ for c in columns:
117
+ if c.role not in MODELED_ROLES or c.name not in df.columns:
118
+ continue
119
+ if not (is_numeric_like(c) or is_category(c)):
120
+ continue
121
+ if df[c.name].drop_nulls().n_unique() <= 1:
122
+ continue # constant
123
+ out.append(c)
124
+ return out
125
+
126
+
127
+ #: discrete columns with at most this many distinct values are checked for rare levels
128
+ RARE_DISCRETE_MAX_LEVELS = 20
129
+
130
+
131
+ def rare_level_columns(df: pl.DataFrame, columns: list[ColumnSchema],
132
+ policy: DisclosurePolicySpec) -> set[str]:
133
+ """Names of category and low-cardinality discrete columns whose pairwise statistics could
134
+ single out a few rows.
135
+
136
+ A boolean column is rare-level when either value is held by fewer than
137
+ ``min_category_support`` rows (but at least one). A categorical column is rare-level when the
138
+ levels below that support (pooled into ``"__other__"`` by the metrics) together hold between
139
+ 1 and ``min_category_support - 1`` rows. A discrete column with at most
140
+ ``RARE_DISCRETE_MAX_LEVELS`` distinct values (a code such as 0/1/2) is rare-level when any
141
+ value is held by fewer than ``min_category_support`` rows: numeric pair metrics use the raw
142
+ values (nothing is pooled), so e.g. a Pearson correlation with one row coded 2 pins down
143
+ that row's other values. See the module docstring.
144
+ """
145
+ m = int(policy.min_category_support)
146
+ out: set[str] = set()
147
+ if m <= 1:
148
+ return out
149
+ for c in columns:
150
+ if c.name not in df.columns:
151
+ continue
152
+ if c.logical_type == LogicalType.DISCRETE:
153
+ counts = df[c.name].drop_nulls().value_counts(name="__n__").to_series(1).to_numpy()
154
+ if 1 < counts.size <= RARE_DISCRETE_MAX_LEVELS and int(counts.min()) < m:
155
+ out.add(c.name)
156
+ continue
157
+ if not is_category(c):
158
+ continue
159
+ vc = label_series(df[c.name]).drop_nulls().value_counts(name="__n__")
160
+ if vc.height == 0:
161
+ continue
162
+ names = vc[vc.columns[0]].to_numpy().astype(str)
163
+ counts = vc[vc.columns[1]].to_numpy().astype(np.int64)
164
+ if c.logical_type == LogicalType.BOOLEAN:
165
+ rare = int(np.min(counts)) < m if counts.size > 1 else False
166
+ else:
167
+ pooled = int(counts[(counts < m) | (names == OTHER)].sum())
168
+ rare = 0 < pooled < m
169
+ if rare:
170
+ out.add(c.name)
171
+ return out
172
+
173
+
174
+ def _select_pairs(df: pl.DataFrame, feats: list[ColumnSchema], policy: DisclosurePolicySpec,
175
+ seed: int, max_pairs: int) -> tuple[list[tuple[str, str]], dict[str, Any]]:
176
+ if len(feats) < 2 or max_pairs <= 0:
177
+ return [], {}
178
+ assoc = association_matrix(df, feats, policy, max_pairs=max_pairs, seed=seed)
179
+ order = {c.name: i for i, c in enumerate(feats)}
180
+ all_pairs = [tuple(p["columns"]) for p in assoc["pairs"]]
181
+ if len(all_pairs) <= max_pairs:
182
+ chosen = set(all_pairs)
183
+ else:
184
+ n_strong = max_pairs // 2
185
+ strong = [tuple(p["columns"]) for p in assoc["candidates"][:n_strong]]
186
+ chosen = set(strong)
187
+ rest = sorted((p for p in all_pairs if p not in chosen),
188
+ key=lambda p: (order[p[0]], order[p[1]]))
189
+ k = max_pairs - len(chosen)
190
+ rng = stream(seed, "pairs")
191
+ pick = rng.choice(len(rest), size=min(k, len(rest)), replace=False)
192
+ chosen.update(rest[i] for i in pick)
193
+ pairs = sorted(chosen, key=lambda p: (order[p[0]], order[p[1]]))
194
+ return [(a, b) for a, b in pairs], assoc["diagnostics"]
195
+
196
+
197
+ def _rare_nulls(s: pl.Series, policy: DisclosurePolicySpec) -> bool:
198
+ k = int(null_mask(s).sum())
199
+ return 0 < k < int(policy.min_category_support)
200
+
201
+
202
+ def _is_scalar(v: Any) -> bool:
203
+ return isinstance(v, (int, float)) and not isinstance(v, bool)
204
+
205
+
206
+ def build_targets(df: pl.DataFrame, columns: list[ColumnSchema],
207
+ policy: DisclosurePolicySpec | str | None, *, seed: int,
208
+ sealed_fraction: float = 0.3, max_pairs: int = 200,
209
+ metrics: list[str] | None = None,
210
+ sealed_families: Sequence[str] | None = None,
211
+ n_boot: int = N_BOOT) -> tuple[TargetSet, TargetSet]:
212
+ """Measure targets on ``df`` and partition them into (calibration, sealed)."""
213
+ pol = resolve_policy(policy)
214
+ seal_fams = set(SEALED_FAMILIES if sealed_families is None else sealed_families)
215
+ kinds = list(METRICS) if metrics is None else list(metrics)
216
+ classes = {k: METRICS.get(k) for k in kinds}
217
+ classes = {k: c for k, c in classes.items() if not _requires_data(c)}
218
+ inst = {k: c() for k, c in classes.items()}
219
+ uni = [k for k in inst if inst[k].arity == 1]
220
+ bi = [k for k in inst if inst[k].arity == 2]
221
+
222
+ feats = _feature_columns(df, columns)
223
+ by_name = {c.name: c for c in feats}
224
+ n = df.height
225
+ rare_cols = rare_level_columns(df, feats, pol)
226
+ pair_feats = [c for c in feats if c.name not in rare_cols]
227
+
228
+ # ---- target specs (metric, column names) ----------------------------------------------
229
+ specs: list[tuple[str, tuple[str, ...]]] = []
230
+ for c in feats:
231
+ for k in uni:
232
+ if k == "univariate.missing_rate" and _rare_nulls(df[c.name], pol):
233
+ continue
234
+ if inst[k].applies_to((c,)):
235
+ specs.append((k, (c.name,)))
236
+ pairs, _ = _select_pairs(df, pair_feats, pol, seed, max_pairs)
237
+ for a, b in pairs:
238
+ for k in bi:
239
+ if k == "missingness.co_missing":
240
+ continue
241
+ if inst[k].applies_to((by_name[a], by_name[b])):
242
+ specs.append((k, (a, b)))
243
+ if "missingness.co_missing" in inst:
244
+ with_nulls = [c.name for c in feats if null_mask(df[c.name]).any()]
245
+ for a, b in list(combinations(with_nulls, 2))[:max_pairs]:
246
+ specs.append(("missingness.co_missing", (a, b)))
247
+
248
+ # ---- shared bootstrap resamples ----------------------------------------------------------
249
+ names = [c.name for c in feats]
250
+ base = df.select(names)
251
+ if base.height > BOOT_MAX_ROWS:
252
+ idx = np.sort(stream(seed, "targets", "subsample").choice(base.height, BOOT_MAX_ROWS,
253
+ replace=False))
254
+ base_sub = base[idx]
255
+ else:
256
+ base_sub = base
257
+ m = min(n, BOOT_SAMPLE_SIZE)
258
+ boots: list[pl.DataFrame] = []
259
+ extra_idx: list[np.ndarray] = [] # further resamples for metrics with n_boot_min > n_boot
260
+ n_extra = max([int(getattr(inst[k], "n_boot_min", 0)) for k, _ in specs] + [0]) - n_boot
261
+ if m > 1 and n_boot > 0 and base_sub.height > 1: # a 0/1-row table has no resamples
262
+ brng = stream(seed, "targets", "bootstrap")
263
+ boots = [base_sub[brng.integers(0, base_sub.height, size=m)] for _ in range(n_boot)]
264
+ extra_idx = [brng.integers(0, base_sub.height, size=m) for _ in range(max(n_extra, 0))]
265
+ inflate = math.sqrt(1.0 + m / n) if n > 0 else 1.0
266
+ ci_scale = math.sqrt(m / n) if n > 0 else 1.0
267
+ # A reference column (ADR-0013) holds the size of its group on every row of the group: its
268
+ # rows are not independent draws, and a bootstrap of rows understates the sampling noise
269
+ # of its statistics by the design effect of the groups. For a value that is constant
270
+ # within a group (intraclass correlation 1) that is the row-weighted mean group size
271
+ # (Kish), which is the mean of the column itself.
272
+ design: dict[str, float] = {}
273
+ for c in feats:
274
+ if c.role == Role.REFERENCE:
275
+ sizes = df[c.name].drop_nulls().cast(pl.Float64)
276
+ mean = float(sizes.mean()) if sizes.len() else 1.0 # type: ignore[arg-type]
277
+ design[c.name] = math.sqrt(max(mean, 1.0))
278
+
279
+ # ---- measure ----------------------------------------------------------------------------
280
+ targets: list[Target] = []
281
+ for k, cols in specs:
282
+ metric = inst[k]
283
+ schemas = [by_name[c] for c in cols]
284
+ ref = metric.measure(base, schemas, pol)
285
+ ds, vals = [], []
286
+ extra = int(getattr(metric, "n_boot_min", 0)) - len(boots)
287
+ more = (base_sub.select(list(cols))[ix] for ix in extra_idx[:max(extra, 0)])
288
+ for bdf in [*boots, *more]:
289
+ v = metric.measure(bdf, schemas, pol)
290
+ ds.append(metric.distance(ref, v))
291
+ if _is_scalar(v):
292
+ vals.append(float(v))
293
+ grouped = max([design.get(c, 1.0) for c in cols] + [1.0])
294
+ nf = float(np.quantile(ds, 0.95)) * inflate * grouped if ds else 0.0
295
+ tol = max(float(metric.default_tolerance), nf)
296
+ ci = None
297
+ if _is_scalar(ref) and vals:
298
+ dev = np.quantile(np.asarray(vals) - np.mean(vals), [0.025, 0.975]) * ci_scale
299
+ dev = dev * grouped
300
+ ci = (coarsen(float(ref) + float(dev[0]), pol), coarsen(float(ref) + float(dev[1]),
301
+ pol))
302
+ targets.append(Target(
303
+ id=target_id(k, cols), metric=k, columns=list(cols), value=ref, ci=ci,
304
+ tolerance=coarsen(tol, pol), family=metric.family,
305
+ params={"n": int(n), "sample_size": int(m), "n_boot": len(boots),
306
+ "noise_floor": coarsen(nf, pol), "arity": metric.arity},
307
+ ))
308
+
309
+ # ---- partition ----------------------------------------------------------------------------
310
+ pair_groups = sorted({tuple(t.columns) for t in targets
311
+ if t.family not in seal_fams and t.family not in CALIBRATION_FAMILIES
312
+ and len(t.columns) == 2})
313
+ n_seal = int(round(sealed_fraction * len(pair_groups)))
314
+ perm = stream(seed, "seal").permutation(len(pair_groups))
315
+ sealed_pairs = {pair_groups[i] for i in perm[:n_seal]}
316
+ calib, sealed = [], []
317
+ for t in targets:
318
+ if t.family in seal_fams:
319
+ sealed.append(t)
320
+ elif t.family in CALIBRATION_FAMILIES or len(t.columns) != 2:
321
+ calib.append(t)
322
+ elif tuple(t.columns) in sealed_pairs:
323
+ sealed.append(t)
324
+ else:
325
+ calib.append(t)
326
+ return TargetSet(kind="calibration", targets=calib), TargetSet(kind="sealed", targets=sealed)
327
+
328
+
329
+ def evaluate_target(target: Target, df: pl.DataFrame, columns: dict[str, ColumnSchema],
330
+ policy: DisclosurePolicySpec | str | None) -> tuple[float, bool]:
331
+ """Measure ``df`` like the target and return ``(distance, passed)``.
332
+
333
+ A target column missing from ``df`` yields ``(inf, False)``.
334
+ """
335
+ pol = resolve_policy(policy)
336
+ metric = METRICS.get(target.metric)()
337
+ if _requires_data(type(metric)):
338
+ raise ValueError(f"{target.metric} requires row-level data; use compare_samples")
339
+ if any(c not in df.columns or c not in columns for c in target.columns):
340
+ return float("inf"), False
341
+ cand = metric.measure(df, [columns[c] for c in target.columns], pol)
342
+ d = float(metric.distance(target.value, cand))
343
+ tol = target.tolerance if target.tolerance is not None else metric.default_tolerance
344
+ return d, bool(d <= float(tol) + 1e-12)
345
+
346
+
347
+ def compare_values(target_a: Target, target_b: Target) -> float:
348
+ """Distance between two stored targets of the same metric (a = reference)."""
349
+ if target_a.metric != target_b.metric:
350
+ raise ValueError(f"cannot compare {target_a.metric} with {target_b.metric}")
351
+ metric = METRICS.get(target_a.metric)()
352
+ return float(metric.distance(target_a.value, target_b.value))
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,163 @@
1
+ """Constraint enforcement on generated frames: clamp repair and rejection masks.
2
+
3
+ See :mod:`ectype.compiler.plan` for the enforcement semantics. In short: a row
4
+ satisfies a constraint unless its expression evaluates to ``false`` -- a ``null`` result counts
5
+ as satisfied (SQL ``CHECK`` semantics).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import math
12
+ import re
13
+
14
+ import numpy as np
15
+ import polars as pl
16
+
17
+ from ectype.compiler.plan import Bound, CompiledConstraint
18
+
19
+ _DT_RE = re.compile(r"time_unit='(\w+)'(?:,\s*time_zone=(?:'([^']*)'|None))?")
20
+ _ENUM_RE = re.compile(r"^Enum\(categories=(\[.*\])\)$", re.S)
21
+
22
+
23
+ def enum_categories(s: str | None) -> list[str] | None:
24
+ """Categories of a stored ``Enum(categories=[...])`` dtype string (``None`` otherwise)."""
25
+ if not s:
26
+ return None
27
+ m = _ENUM_RE.match(s.strip())
28
+ if m is None:
29
+ return None
30
+ try:
31
+ cats = ast.literal_eval(m.group(1))
32
+ except (ValueError, SyntaxError):
33
+ return None
34
+ if not isinstance(cats, list) or not all(isinstance(c, str) for c in cats):
35
+ return None
36
+ return cats
37
+
38
+
39
+ def dtype_from_string(s: str | None) -> pl.DataType | None:
40
+ """Parse a stored polars dtype string (``ColumnSchema.physical_dtype``); ``None`` if
41
+ unknown."""
42
+ if not s:
43
+ return None
44
+ name = s.split("(")[0].strip()
45
+ if name == "Datetime":
46
+ m = _DT_RE.search(s)
47
+ unit = m.group(1) if m else "us"
48
+ tz = m.group(2) if m else None
49
+ return pl.Datetime(unit, tz) # type: ignore[arg-type]
50
+ if name == "Duration":
51
+ m = _DT_RE.search(s)
52
+ return pl.Duration(m.group(1) if m else "us") # type: ignore[arg-type]
53
+ if name in ("Utf8", "String"):
54
+ return pl.String()
55
+ if name == "Enum":
56
+ cats = enum_categories(s)
57
+ return pl.Enum(cats) if cats is not None else None
58
+ if name in ("List", "Array", "Struct", "Decimal", "Object"):
59
+ return None
60
+ obj = getattr(pl, name, None)
61
+ if isinstance(obj, type) and issubclass(obj, pl.DataType):
62
+ try:
63
+ return obj()
64
+ except TypeError:
65
+ return None
66
+ return None
67
+
68
+
69
+ def cast_to(s: pl.Series, dtype: pl.DataType | None) -> pl.Series:
70
+ """Cast to ``dtype``, rounding floats first when the target is an integer type."""
71
+ if dtype is None or s.dtype == dtype:
72
+ return s
73
+ if s.dtype == pl.String and dtype.is_numeric():
74
+ s = s.cast(pl.Float64, strict=False)
75
+ if dtype.is_integer() and s.dtype.is_float():
76
+ s = s.round(0)
77
+ if s.dtype == pl.String and dtype == pl.Date:
78
+ return s.str.to_date(strict=False)
79
+ if s.dtype == pl.String and isinstance(dtype, pl.Datetime):
80
+ return s.str.to_datetime(strict=False, time_unit=dtype.time_unit or "us",
81
+ time_zone=dtype.time_zone)
82
+ return s.cast(dtype, strict=False)
83
+
84
+
85
+ # ---------------------------------------------------------------------------------------------
86
+ # Repair
87
+ # ---------------------------------------------------------------------------------------------
88
+
89
+
90
+ def _clamp_value(b: Bound, dtype: pl.DataType) -> float | int:
91
+ v = b.value
92
+ if dtype.is_integer():
93
+ if b.op == ">=":
94
+ return math.ceil(v)
95
+ if b.op == ">":
96
+ return math.floor(v) + 1
97
+ if b.op == "<=":
98
+ return math.floor(v)
99
+ return math.ceil(v) - 1
100
+ # Strict bounds step to the adjacent representable value *in the column's precision*:
101
+ # a float64 nextafter rounds back onto the bound when stored as Float32.
102
+ ftype = np.float32 if dtype == pl.Float32 else np.float64
103
+ if b.op in (">", "<"):
104
+ direction = np.inf if b.op == ">" else -np.inf
105
+ x = ftype(v)
106
+ # the rounded bound itself may already lie on the wrong side of v
107
+ if (b.op == ">" and float(x) <= v) or (b.op == "<" and float(x) >= v):
108
+ x = np.nextafter(x, ftype(direction))
109
+ return float(x)
110
+ if b.op in (">=", "<=") and ftype is np.float32:
111
+ x = np.float32(v)
112
+ if (b.op == ">=" and float(x) < v) or (b.op == "<=" and float(x) > v):
113
+ x = np.nextafter(x, np.float32(np.inf if b.op == ">=" else -np.inf))
114
+ return float(x)
115
+ return v
116
+
117
+
118
+ def apply_repairs(df: pl.DataFrame, constraints: list[CompiledConstraint]
119
+ ) -> tuple[pl.DataFrame, dict[str, int]]:
120
+ """Clamp each bound of each repair constraint; returns the frame and rows changed per
121
+ constraint id. Nulls are left alone."""
122
+ counts: dict[str, int] = {}
123
+ for c in constraints:
124
+ changed = np.zeros(df.height, dtype=bool)
125
+ for b in c.bounds:
126
+ s = df.get_column(b.column)
127
+ v = _clamp_value(b, s.dtype)
128
+ lower = b.op in (">=", ">")
129
+ bad = (s < v) if lower else (s > v)
130
+ bad = bad.fill_null(False)
131
+ if not bad.any():
132
+ continue
133
+ changed |= bad.to_numpy()
134
+ fixed = (s.clip(lower_bound=v) if lower else s.clip(upper_bound=v))
135
+ df = df.with_columns(cast_to(fixed, s.dtype).alias(b.column))
136
+ counts[c.id] = int(changed.sum())
137
+ return df, counts
138
+
139
+
140
+ # ---------------------------------------------------------------------------------------------
141
+ # Checking
142
+ # ---------------------------------------------------------------------------------------------
143
+
144
+
145
+ def violation_masks(df: pl.DataFrame, constraints: list[CompiledConstraint]
146
+ ) -> dict[str, np.ndarray]:
147
+ """Per-constraint boolean arrays, ``True`` where the row *violates* the constraint (the
148
+ expression is ``false``; ``null`` counts as satisfied)."""
149
+ if not constraints or df.height == 0:
150
+ return {c.id: np.zeros(df.height, dtype=bool) for c in constraints}
151
+ out = df.select([(c.expr.cast(pl.Boolean) == pl.lit(False)).fill_null(False)
152
+ .alias(f"__c{i}") for i, c in enumerate(constraints)])
153
+ res = {}
154
+ for i, c in enumerate(constraints):
155
+ col = out.get_column(f"__c{i}")
156
+ arr = col.to_numpy().astype(bool) if col.len() == df.height else \
157
+ np.full(df.height, bool(col[0]))
158
+ res[c.id] = arr
159
+ return res
160
+
161
+
162
+ __all__ = ["apply_repairs", "cast_to", "dtype_from_string", "enum_categories",
163
+ "violation_masks"]