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,707 @@
1
+ """Validate a synthetic table against a fingerprint (M12).
2
+
3
+ Three independent sections (design doc sections 4.2, 6.1):
4
+
5
+ 1. **calibration** - ``fp.calibration`` targets. Optimizer evidence only; failures are reported
6
+ but never fail the report.
7
+ 2. **sealed** - ``fp.open_seal()`` targets. The primary evidence of fidelity. Each target
8
+ still passes or fails against its own tolerance (a ~95% sampling bound), but with dozens or
9
+ hundreds of sealed targets a perfect generator would fail a few of them by chance, so the
10
+ verdict is multiplicity-controlled (``sealed_decision``): a failed target gets an
11
+ approximate p-value from its exceedance, and the sealed section fails when
12
+ Benjamini-Hochberg at level ``q`` (``sensitivity``: strict 0.20, standard 0.05, lenient
13
+ 0.01, or a number) rejects any of them. The p-value uses the same machinery as drift
14
+ comparison (``fingerprint.comparison``): the stored noise floor is rescaled to the two
15
+ row counts involved (``noise95 = u * sqrt(1/n_source + 1/n_synthetic)``), then
16
+ ``p = 2 (1 - Phi(1.96 (d - step) / (KAPPA * noise95)))`` (``step`` discounts one unit of
17
+ a lumpy statistic, see ``comparison.resolution_step``); a target within its tolerance has
18
+ ``p = 1``, and an error (missing column, failed metric, infinite distance) has ``p = 0`` so
19
+ it always fails the verdict.
20
+ Pseudonymised columns (role ``pseudonym``, ADR-0010)
21
+ Their targets were measured on tokens, and synthetic rows carry the same tokens, so the
22
+ calibration and sealed sections compare them like any categorical. A frame of *real* rows
23
+ (the holdout, or a real sample passed as ``synthetic``) carries source labels, and no
24
+ real-to-token map exists. Whenever one side of a comparison lacks the tokens
25
+ (``carries_tokens``), only what can be compared without matching labels is compared:
26
+ ``univariate.frequencies`` as sorted level-frequency profiles
27
+ (``metrics.univariate.rank_profiles``), and missingness and association strengths (Cramer's
28
+ V, correlation ratio, mutual information) as usual, since they never use labels.
29
+ ``bivariate.contingency`` targets are skipped, and the columns are left out of the
30
+ multivariate holdout metrics. Each section says so in its notes.
31
+
32
+ Reference keys (role ``reference``, ADR-0013)
33
+ Their targets were measured on group sizes: each key replaced by the number of rows that
34
+ share it. Every frame given here (synthetic or real) is read the same way before a
35
+ target is measured (``profiling.reference.size_view``), so no comparison needs a key to
36
+ match. Group sizes are counts: a frame much smaller than the source (a holdout sample)
37
+ has smaller groups, and the holdout section then says so rather than compare them.
38
+ The structural checks see the keys themselves (their dtype).
39
+
40
+ 3. **holdout** - only when a ``holdout`` frame of real rows is given (trusted environment).
41
+ Every stored target is re-measured on the holdout with the same metric definition and the
42
+ synthetic data is compared against that value; the tolerance is rescaled for the holdout's
43
+ own sampling noise (see ``_holdout_tolerance``). The data-requiring multivariate metrics
44
+ (``requires_data = True``: energy, c2st) are run between holdout and synthetic on the feature
45
+ columns. Informational: it does not affect ``report.passed``.
46
+
47
+ Plus structural checks (column names / order against the compiled plan's output columns,
48
+ dtypes against the manifest, identifier columns unique and non-null, row count) and
49
+ hard-constraint checks (every confirmed constraint via ``expressions.evaluate`` of the same
50
+ predicate the generator enforces, so ``a == b`` with a tolerance is ``abs(a - b) <= tol``; a
51
+ null result counts as satisfied; any violation of a hard constraint fails). Structural,
52
+ identifier and hard-constraint failures are absolute: no multiplicity control applies.
53
+
54
+ Sums (``model.sums``, ADR-0014)
55
+ When the fingerprint computes totals or parts, the structural check ``sums`` counts, for
56
+ every recorded sum, the rows in which its columns are present and not all zero and how
57
+ many of them satisfy it (``profiling.sums.sum_hold``, with the sum's own tolerance). The
58
+ generator computes these columns, so the check fails when a sum holds on fewer than all
59
+ of those rows. With a holdout, the same count on the real rows is reported next to it
60
+ (the source is allowed a few rows that break a sum; the output has none).
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import math
66
+ from typing import Any
67
+
68
+ import polars as pl
69
+
70
+ from ectype._version import __version__
71
+ from ectype.fingerprint.core import Fingerprint
72
+ from ectype.fingerprint.disclosure import OTHER, resolve_policy
73
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, Target
74
+ from ectype.io import read_table
75
+ from ectype.io.values import category_labels
76
+ from ectype.rng import stream
77
+ from ectype.types import Role, Severity
78
+ from ectype.validation.metrics import ( # noqa: F401 (registration side effects)
79
+ bivariate,
80
+ missingness,
81
+ multivariate,
82
+ univariate,
83
+ )
84
+ from ectype.validation.metrics.base import METRICS, Metric
85
+ from ectype.validation.metrics.univariate import is_category, is_numeric_like, rank_profiles
86
+ from ectype.validation.report import (
87
+ CALIBRATION_EVIDENCE,
88
+ HOLDOUT_EVIDENCE,
89
+ SEALED_EVIDENCE,
90
+ Check,
91
+ ConstraintResult,
92
+ Section,
93
+ TargetResult,
94
+ ValidationReport,
95
+ )
96
+
97
+ _EPS = 1e-12
98
+ #: metrics whose summaries are keyed by category labels
99
+ _FREQUENCIES = "univariate.frequencies"
100
+ _LABEL_KEYED_PAIRS = frozenset({"bivariate.contingency"})
101
+ #: a frame carries a pseudonym column's tokens when at least this share of its values are
102
+ #: labels stored in the fingerprint
103
+ TOKEN_SHARE_MIN = 0.5
104
+
105
+
106
+ def _requires_data(metric: Metric | type[Metric]) -> bool:
107
+ return bool(getattr(metric, "requires_data", False))
108
+
109
+
110
+ def _metric(kind: str) -> Metric:
111
+ return METRICS.get(kind)()
112
+
113
+
114
+ def _tolerance(target: Target, metric: Metric) -> float:
115
+ return float(target.tolerance if target.tolerance is not None else metric.default_tolerance)
116
+
117
+
118
+ def pseudonym_labels(fp: Fingerprint) -> dict[str, set[str]]:
119
+ """The stored labels (tokens) of every pseudonymised column of ``fp``: those of its
120
+ marginal, or, for a column computed from another one (ADR-0011), the string values of the
121
+ table in its expression."""
122
+ out: dict[str, set[str]] = {}
123
+ derived = {d.column: d.expression for d in fp.manifest.model.derived}
124
+ for c in fp.manifest.columns:
125
+ if c.role != Role.PSEUDONYM:
126
+ continue
127
+ spec = fp.manifest.model.marginals.get(c.name)
128
+ ref = spec.arrays.get("labels") if spec is not None else None
129
+ labels = fp.arrays.get(ref).tolist() if ref is not None and ref in fp.arrays else []
130
+ if spec is None and c.name in derived:
131
+ labels = _string_literals(derived[c.name])
132
+ out[c.name] = {str(x) for x in labels}
133
+ return out
134
+
135
+
136
+ def _string_literals(expression: str) -> list[str]:
137
+ """Every string literal of an expression (the values of a ``lookup`` or ``step`` table)."""
138
+ from ectype.fingerprint import expressions as ex
139
+
140
+ found: list[str] = []
141
+ stack: list[ex.Node] = [ex.parse(expression)]
142
+ while stack:
143
+ node = stack.pop()
144
+ if isinstance(node, ex.Literal) and node.kind == "str":
145
+ found.append(str(node.value))
146
+ elif isinstance(node, ex.Call):
147
+ stack.extend(node.args)
148
+ elif isinstance(node, ex.Binary):
149
+ stack.extend((node.left, node.right))
150
+ elif isinstance(node, ex.Unary):
151
+ stack.append(node.operand)
152
+ elif isinstance(node, ex.InList):
153
+ stack.extend((node.operand, *node.items))
154
+ return found
155
+
156
+
157
+ def carries_tokens(df: pl.DataFrame, column: str, labels: set[str]) -> bool:
158
+ """Whether ``df[column]`` holds a pseudonymised column's tokens (synthetic rows do) rather
159
+ than source labels (real rows do): at least ``TOKEN_SHARE_MIN`` of its values are labels
160
+ stored in the fingerprint. Blank values and the pooled ``__other__`` bucket are the same on
161
+ both sides and do not count; a column with no other value counts as carrying the tokens."""
162
+ if column not in df.columns:
163
+ return True
164
+ values = category_labels(df.get_column(column)).drop_nulls()
165
+ values = values.filter((values.str.strip_chars() != "") & (values != OTHER))
166
+ if values.len() == 0:
167
+ return True
168
+ share = values.is_in(sorted(labels)).mean()
169
+ return float(share or 0.0) >= TOKEN_SHARE_MIN # type: ignore[arg-type]
170
+
171
+
172
+ def _label_free_note(cols: list[str], frame: str, n_skipped: int) -> str:
173
+ return (f"Pseudonymised column(s) {', '.join(cols)}: {frame} carry source labels where the "
174
+ f"fingerprint and synthetic rows carry tokens, and no real-to-token map exists. "
175
+ f"Their label frequencies are compared as sorted level-frequency profiles; "
176
+ f"missingness and association strengths do not use labels and are compared as "
177
+ f"usual; {n_skipped} label-level target(s) (bivariate.contingency) were skipped.")
178
+
179
+
180
+ def _comparable(targets: list[Target], label_free: set[str]) -> tuple[list[Target], int]:
181
+ """Targets that can be compared when the columns in ``label_free`` cannot be matched by
182
+ label, and the number of targets skipped."""
183
+ if not label_free:
184
+ return list(targets), 0
185
+ kept = [t for t in targets
186
+ if not (t.metric in _LABEL_KEYED_PAIRS and label_free & set(t.columns))]
187
+ return kept, len(targets) - len(kept)
188
+
189
+
190
+ def evaluate_one(target: Target, df: pl.DataFrame, columns: dict[str, ColumnSchema],
191
+ policy: DisclosurePolicySpec, *, tolerance: float | None = None,
192
+ label_free: set[str] | frozenset[str] = frozenset()) -> TargetResult:
193
+ """Measure ``df`` like ``target`` (same semantics as ``targets.evaluate_target``) and keep
194
+ the candidate summary for verbose reports. For a ``univariate.frequencies`` target on a
195
+ column in ``label_free`` the two summaries are compared as sorted level-frequency profiles
196
+ (the result's ``reference`` and ``candidate`` hold those profiles)."""
197
+ family = target.family or target.metric
198
+ try:
199
+ metric = _metric(target.metric)
200
+ except Exception as exc: # unknown metric kind
201
+ return TargetResult(target.id, target.metric, family, list(target.columns), math.inf,
202
+ float(target.tolerance or 0.0), False, target.value, None,
203
+ f"unknown metric: {exc}")
204
+ tol = _tolerance(target, metric) if tolerance is None else float(tolerance)
205
+ missing = [c for c in target.columns if c not in df.columns or c not in columns]
206
+ if missing:
207
+ return TargetResult(target.id, target.metric, family, list(target.columns), math.inf,
208
+ tol, False, target.value, None,
209
+ f"missing column(s): {', '.join(missing)}")
210
+ if _requires_data(metric):
211
+ return TargetResult(target.id, target.metric, family, list(target.columns), math.inf,
212
+ tol, False, target.value, None, "metric requires row-level data")
213
+ try:
214
+ cand = metric.measure(df, [columns[c] for c in target.columns], policy)
215
+ reference = target.value
216
+ if target.metric == _FREQUENCIES and label_free & set(target.columns):
217
+ reference, cand = rank_profiles(reference, cand)
218
+ d = float(metric.distance(reference, cand))
219
+ except Exception as exc: # a metric failure is a failed target, not a crash
220
+ return TargetResult(target.id, target.metric, family, list(target.columns), math.inf,
221
+ tol, False, target.value, None, f"{type(exc).__name__}: {exc}")
222
+ if math.isnan(d):
223
+ return TargetResult(target.id, target.metric, family, list(target.columns), math.inf,
224
+ tol, False, reference, cand, "distance is NaN")
225
+ return TargetResult(target.id, target.metric, family, list(target.columns), d, tol,
226
+ bool(d <= tol + _EPS), reference, cand)
227
+
228
+
229
+ # ---------------------------------------------------------------------------------------------
230
+ # Structural checks
231
+ # ---------------------------------------------------------------------------------------------
232
+
233
+
234
+ def expected_columns(fp: Fingerprint) -> list[str]:
235
+ """Output column order promised by the fingerprint: the compiled plan's
236
+ ``output_columns`` (so derived columns that are new to the source are expected too).
237
+ Falls back to the manifest's column order when the fingerprint cannot be compiled."""
238
+ from ectype.compiler.plan import compile_plan
239
+
240
+ try:
241
+ return list(compile_plan(fp).output_columns)
242
+ except Exception: # noqa: BLE001 (an uncompilable fingerprint still gets checked)
243
+ pass
244
+ order = list(fp.manifest.model.column_order)
245
+ if order:
246
+ return order
247
+ return [c.name for c in fp.manifest.columns if c.role != Role.EXCLUDED]
248
+
249
+
250
+ def _enum_downgrades(fp: Fingerprint) -> dict[str, list[str]]:
251
+ from ectype.compiler.plan import enum_downgrades
252
+
253
+ try:
254
+ return enum_downgrades(fp)
255
+ except Exception: # noqa: BLE001
256
+ return {}
257
+
258
+
259
+ def _identifier_check(fp: Fingerprint, df: pl.DataFrame) -> Check:
260
+ """Identifier columns are regenerated and must be unique.
261
+
262
+ They must also be non-null, unless the source column had empty cells: then the share of
263
+ empty cells has to match the source's (within 2 points or four standard errors).
264
+ """
265
+ problems: dict[str, dict[str, int]] = {}
266
+ schemas = {c.name: c for c in fp.manifest.columns}
267
+ for col in fp.manifest.model.identifiers:
268
+ if col not in df.columns:
269
+ continue
270
+ s = df.get_column(col)
271
+ nulls = int(s.null_count())
272
+ dups = int(s.drop_nulls().len() - s.drop_nulls().n_unique())
273
+ expected = float(getattr(schemas.get(col), "null_fraction", 0.0) or 0.0)
274
+ null_problem = bool(nulls)
275
+ if expected > 0.0 and s.len():
276
+ tolerance = max(0.02, 4.0 * (expected * (1.0 - expected) / s.len()) ** 0.5)
277
+ null_problem = abs(nulls / s.len() - expected) > tolerance
278
+ if null_problem or dups:
279
+ problems[col] = {"nulls": nulls, "duplicates": dups}
280
+ if problems:
281
+ return Check("identifiers", False,
282
+ "; ".join(f"{k}: {v['nulls']} null(s), {v['duplicates']} duplicate(s)"
283
+ for k, v in problems.items()), problems)
284
+ return Check("identifiers", True,
285
+ "identifier columns are unique, with empty cells only where the source had them")
286
+
287
+
288
+ def structural_checks(fp: Fingerprint, df: pl.DataFrame,
289
+ expected_rows: int | None = None) -> list[Check]:
290
+ m = fp.manifest
291
+ expected = expected_columns(fp)
292
+ by_name = {c.name: c for c in m.columns}
293
+ excluded = {c.name for c in m.columns if c.role == Role.EXCLUDED}
294
+ actual = list(df.columns)
295
+ checks: list[Check] = []
296
+
297
+ missing = [c for c in expected if c not in actual]
298
+ extra = [c for c in actual if c not in expected]
299
+ unexpected_excluded = [c for c in extra if c in excluded]
300
+ if missing or extra:
301
+ msg = []
302
+ if missing:
303
+ msg.append(f"missing {missing}")
304
+ if extra:
305
+ msg.append(f"unexpected {extra}")
306
+ if unexpected_excluded:
307
+ msg.append(f"(excluded in the manifest: {unexpected_excluded})")
308
+ checks.append(Check("column_names", False, "; ".join(msg),
309
+ {"missing": missing, "unexpected": extra,
310
+ "excluded_present": unexpected_excluded}))
311
+ else:
312
+ checks.append(Check("column_names", True,
313
+ f"all {len(expected)} expected columns present"))
314
+
315
+ common_actual = [c for c in actual if c in expected]
316
+ common_expected = [c for c in expected if c in actual]
317
+ if common_actual == common_expected:
318
+ checks.append(Check("column_order", True, "column order matches the manifest"))
319
+ else:
320
+ checks.append(Check("column_order", False, "column order differs from the manifest",
321
+ {"expected": common_expected, "actual": common_actual}))
322
+
323
+ mismatches = {}
324
+ downgrades = _enum_downgrades(fp)
325
+ downgraded = []
326
+ for name in common_expected:
327
+ col = by_name.get(name)
328
+ if col is None:
329
+ continue
330
+ got = str(df.schema[name])
331
+ if got == "String" and name in downgrades and col.physical_dtype.startswith("Enum"):
332
+ downgraded.append(name) # documented Enum -> String downgrade (plan notes)
333
+ continue
334
+ if got != col.physical_dtype and not (df[name].null_count() == df.height
335
+ and got == "Null"):
336
+ mismatches[name] = {"expected": col.physical_dtype, "actual": got}
337
+ if mismatches:
338
+ checks.append(Check("dtypes", False,
339
+ "; ".join(f"{k}: expected {v['expected']}, got {v['actual']}"
340
+ for k, v in mismatches.items()), mismatches))
341
+ else:
342
+ dmsg = "dtypes match the manifest"
343
+ if downgraded:
344
+ dmsg += (f" (documented Enum -> String downgrade for {downgraded}: the model emits "
345
+ f"labels outside the Enum categories)")
346
+ checks.append(Check("dtypes", True, dmsg,
347
+ {"enum_downgrades": downgraded} if downgraded else {}))
348
+ checks.append(_identifier_check(fp, df))
349
+
350
+ if df.height == 0:
351
+ checks.append(Check("row_count", False, "synthetic table is empty",
352
+ {"n_rows": 0, "expected": expected_rows}))
353
+ elif expected_rows is not None and df.height != int(expected_rows):
354
+ checks.append(Check("row_count", False,
355
+ f"{df.height} rows, expected {int(expected_rows)}",
356
+ {"n_rows": df.height, "expected": int(expected_rows)}))
357
+ else:
358
+ checks.append(Check("row_count", True, f"{df.height} rows "
359
+ f"(source had {m.dataset.source_records})",
360
+ {"n_rows": df.height, "expected": expected_rows,
361
+ "source_records": m.dataset.source_records}))
362
+ return checks
363
+
364
+
365
+ def sum_checks(fp: Fingerprint, df: pl.DataFrame,
366
+ holdout: pl.DataFrame | None = None) -> list[Check]:
367
+ """The ``sums`` check: how often each recorded sum (``model.sums``) holds on ``df``, and
368
+ on ``holdout`` when given. Empty when the fingerprint records no sum. The check passes
369
+ when every sum holds on every row of ``df`` that has its columns (a sum whose columns are
370
+ missing from ``df`` fails it)."""
371
+ from ectype.profiling.sums import sum_hold, sum_text
372
+
373
+ sums = list(fp.manifest.model.sums)
374
+ if not sums:
375
+ return []
376
+ schemas = {c.name: c for c in fp.manifest.columns}
377
+ rows: list[dict[str, Any]] = []
378
+ broken: list[str] = []
379
+ for spec in sums:
380
+ n, ok = sum_hold(df, spec, schemas)
381
+ names = ([spec.total] if spec.total is not None else []) + list(spec.parts)
382
+ absent = [c for c in names if c not in df.columns]
383
+ rec: dict[str, Any] = {"sum": sum_text(spec), "mode": spec.mode, "rows": n,
384
+ "holding": ok, "rate": (ok / n) if n else None}
385
+ if absent:
386
+ rec["missing_columns"] = absent
387
+ if holdout is not None:
388
+ hn, hok = sum_hold(holdout, spec, schemas)
389
+ rec.update(holdout_rows=hn, holdout_holding=hok,
390
+ holdout_rate=(hok / hn) if hn else None)
391
+ if absent or ok < n:
392
+ broken.append(rec["sum"])
393
+ rows.append(rec)
394
+ total = sum(r["rows"] for r in rows)
395
+ holding = sum(r["holding"] for r in rows)
396
+ details: dict[str, Any] = {"sums": rows, "n_sums": len(rows), "n_broken": len(broken),
397
+ "rate": (holding / total) if total else None}
398
+ if holdout is not None:
399
+ hn = sum(r["holdout_rows"] for r in rows)
400
+ details["holdout_rate"] = (sum(r["holdout_holding"] for r in rows) / hn) if hn else None
401
+ if broken:
402
+ worst = min((r for r in rows if r["sum"] in broken),
403
+ key=lambda r: r["rate"] if r["rate"] is not None else -1.0)
404
+ rate = "no row" if worst["rate"] is None else f"{worst['rate']:.2%} of {worst['rows']} rows"
405
+ return [Check("sums", False,
406
+ f"{len(broken)} of {len(rows)} sum(s) do not hold on every row; the worst "
407
+ f"({worst['sum'][:80]}) holds on {rate}", details)]
408
+ msg = f"{len(rows)} sum(s) hold on every row that has their columns"
409
+ if details.get("holdout_rate") is not None:
410
+ msg += f" (holdout: {details['holdout_rate']:.2%} of the row-sum pairs)"
411
+ return [Check("sums", True, msg, details)]
412
+
413
+
414
+ def constraint_checks(fp: Fingerprint, df: pl.DataFrame) -> list[ConstraintResult]:
415
+ from ectype.compiler.plan import enforced_node
416
+ from ectype.fingerprint import expressions
417
+
418
+ out = []
419
+ for c in fp.manifest.constraints.confirmed:
420
+ sev = c.severity.value if isinstance(c.severity, Severity) else str(c.severity)
421
+ try:
422
+ # the same predicate the generator enforces (tolerance on ``==`` included)
423
+ res = expressions.evaluate(enforced_node(c), df)
424
+ if res.dtype != pl.Boolean:
425
+ res = res.cast(pl.Boolean)
426
+ violations = int((~res.fill_null(True)).sum())
427
+ error = None
428
+ except Exception as exc: # unknown column, type error, ...
429
+ violations, error = df.height, f"{type(exc).__name__}: {exc}"
430
+ if sev == Severity.HARD.value:
431
+ passed = violations == 0 and error is None
432
+ else:
433
+ rate = violations / df.height if df.height else 0.0
434
+ passed = error is None and rate <= float(c.tolerance) + _EPS
435
+ out.append(ConstraintResult(c.id, c.expression, sev, df.height, violations, passed,
436
+ error))
437
+ return out
438
+
439
+
440
+ # ---------------------------------------------------------------------------------------------
441
+ # Holdout
442
+ # ---------------------------------------------------------------------------------------------
443
+
444
+
445
+ def _holdout_tolerance(target: Target, metric: Metric, n_holdout: int) -> float:
446
+ """Rescale a stored tolerance from reference size ``n`` to holdout size ``h``.
447
+
448
+ Stored tolerances inflate the bootstrap noise floor by ``sqrt(1 + m/n)`` (sample of size m
449
+ vs reference of size n). Against a holdout of size h the reference is itself noisier, so the
450
+ factor becomes ``sqrt(1 + m/h)``. Never below the stored tolerance.
451
+ """
452
+ tol = _tolerance(target, metric)
453
+ n = target.params.get("n") if target.params else None
454
+ m = target.params.get("sample_size") if target.params else None
455
+ if not n or not m or n_holdout <= 0:
456
+ return tol
457
+ factor = math.sqrt((1.0 + float(m) / n_holdout) / (1.0 + float(m) / float(n)))
458
+ return tol * max(1.0, factor)
459
+
460
+
461
+ def _holdout_section(fp: Fingerprint, syn: pl.DataFrame, holdout: pl.DataFrame,
462
+ targets: list[Target], columns: dict[str, ColumnSchema],
463
+ policy: DisclosurePolicySpec, seed: int,
464
+ include_multivariate: bool,
465
+ tokens: dict[str, set[str]] | None = None) -> Section:
466
+ sec = Section("holdout", "Row-level holdout", HOLDOUT_EVIDENCE)
467
+ sec.notes.append(f"Reference values re-measured on {holdout.height} holdout rows; "
468
+ "tolerances rescaled for holdout sampling noise. Informational: does not "
469
+ "change the pass/fail verdict.")
470
+ # pseudonymised columns whose labels cannot be matched between holdout and synthetic rows
471
+ label_free = {c for c, labels in (tokens or {}).items()
472
+ if not (carries_tokens(holdout, c, labels) and carries_tokens(syn, c, labels))}
473
+ targets, n_skipped = _comparable(targets, label_free)
474
+ if label_free:
475
+ sec.notes.append(_label_free_note(sorted(label_free), "the holdout rows", n_skipped))
476
+ for t in targets:
477
+ try:
478
+ metric = _metric(t.metric)
479
+ except Exception:
480
+ continue
481
+ if _requires_data(metric):
482
+ continue
483
+ if any(c not in holdout.columns or c not in columns for c in t.columns):
484
+ sec.results.append(TargetResult(t.id, t.metric, t.family or t.metric,
485
+ list(t.columns), math.inf, _tolerance(t, metric),
486
+ False, None, None, "column missing from holdout"))
487
+ continue
488
+ try:
489
+ ref = metric.measure(holdout, [columns[c] for c in t.columns], policy)
490
+ except Exception as exc:
491
+ sec.results.append(TargetResult(t.id, t.metric, t.family or t.metric,
492
+ list(t.columns), math.inf, _tolerance(t, metric),
493
+ False, None, None,
494
+ f"holdout measure failed: {exc}"))
495
+ continue
496
+ ht = t.model_copy(update={"value": ref})
497
+ sec.results.append(evaluate_one(ht, syn, columns, policy,
498
+ tolerance=_holdout_tolerance(t, metric, holdout.height),
499
+ label_free=label_free))
500
+
501
+ if include_multivariate:
502
+ feats = [c for c in fp.manifest.columns
503
+ if c.role == Role.FEATURE and (is_numeric_like(c) or is_category(c))
504
+ and c.name in holdout.columns and c.name in syn.columns]
505
+ names = [c.name for c in feats]
506
+ if tokens:
507
+ sec.notes.append(f"Pseudonymised column(s) {', '.join(sorted(tokens))} are left out "
508
+ "of the multivariate metrics (they compare rows label by label).")
509
+ for kind in sorted(METRICS):
510
+ cls = METRICS.get(kind)
511
+ if not _requires_data(cls) or not feats:
512
+ continue
513
+ metric = cls()
514
+ tid = f"{kind}:*"
515
+ if not metric.applies_to(tuple(feats)):
516
+ continue
517
+ try:
518
+ rng = stream(seed, "validate", "holdout", kind)
519
+ d = float(metric.compare_samples(holdout.select(names), syn.select(names), # type: ignore[attr-defined]
520
+ feats, rng, policy))
521
+ nf = float(metric.noise_floor(holdout.select(names), feats, policy,
522
+ stream(seed, "validate", "noise", kind),
523
+ n_boot=3))
524
+ tol = max(float(metric.default_tolerance), nf)
525
+ sec.results.append(TargetResult(tid, kind, metric.family, names, d, tol,
526
+ bool(d <= tol + _EPS),
527
+ {"noise_floor": nf}, {"distance": d}))
528
+ except Exception as exc:
529
+ sec.results.append(TargetResult(tid, kind, metric.family, names, math.inf,
530
+ float(metric.default_tolerance), False,
531
+ None, None, f"{type(exc).__name__}: {exc}"))
532
+ return sec
533
+
534
+
535
+ # ---------------------------------------------------------------------------------------------
536
+ # Sealed verdict (multiplicity control)
537
+ # ---------------------------------------------------------------------------------------------
538
+
539
+
540
+ def sealed_decision(targets: list[Target], results: list[TargetResult], *,
541
+ source_rows: int | None, synthetic_rows: int,
542
+ sensitivity: str | float = "standard",
543
+ extra_steps: dict[str, float] | None = None) -> dict[str, Any]:
544
+ """Benjamini-Hochberg verdict over the sealed targets (see the module docstring).
545
+
546
+ ``extra_steps`` holds, per target id, a distance discounted before testing (the level an
547
+ association statistic takes on unrelated columns at the two row counts; see
548
+ ``fingerprint.comparison.null_level_step``)."""
549
+ from ectype.fingerprint.comparison import (
550
+ bh_cutoff,
551
+ noise_threshold,
552
+ p_value,
553
+ resolution_step,
554
+ resolve_sensitivity,
555
+ sensitivity_label,
556
+ )
557
+
558
+ q = resolve_sensitivity(sensitivity)
559
+ n_src = float(source_rows) if source_rows else None
560
+ n_syn = float(synthetic_rows) if synthetic_rows > 0 else None
561
+ p_values: dict[str, float] = {}
562
+ for t, r in zip(targets, results):
563
+ if r.error is not None or not math.isfinite(r.distance):
564
+ p = 0.0
565
+ elif r.passed:
566
+ p = 1.0
567
+ else:
568
+ try:
569
+ floor = float(_metric(t.metric).default_tolerance)
570
+ except Exception:
571
+ floor = 0.0
572
+ step = (resolution_step(t.metric, r.reference, r.candidate)
573
+ + (extra_steps or {}).get(r.id, 0.0))
574
+ p = p_value(max(0.0, r.distance - step), noise_threshold(t, t, n_src, n_syn), floor)
575
+ p_values[r.id] = p
576
+ _, cut = bh_cutoff(list(p_values.values()), q)
577
+ failed = [r.id for r in results if p_values[r.id] <= cut and not r.passed]
578
+ return {"rule": "benjamini-hochberg", "sensitivity": sensitivity_label(sensitivity),
579
+ "q": q, "n_tests": len(results), "n_rejected": len(failed),
580
+ "p_cut": cut if results else None, "failed": failed, "p_values": p_values}
581
+
582
+
583
+ # ---------------------------------------------------------------------------------------------
584
+ # Entry point
585
+ # ---------------------------------------------------------------------------------------------
586
+
587
+
588
+ def validate(fp: Fingerprint, synthetic: Any, *, holdout: Any = None, seed: int = 0,
589
+ include_multivariate: bool = True,
590
+ expected_rows: int | None = None,
591
+ sensitivity: str | float = "standard") -> ValidationReport:
592
+ """Validate ``synthetic`` against ``fp``; see the module docstring for the semantics.
593
+
594
+ ``synthetic`` and ``holdout`` accept anything ``io.read_table`` accepts. ``expected_rows``
595
+ optionally asserts the synthetic row count. ``sensitivity`` sets the false-discovery rate
596
+ of the sealed verdict: ``"strict"`` (q=0.20, fails most readily), ``"standard"`` (q=0.05)
597
+ or ``"lenient"`` (q=0.01), or a number ``0 < q < 1``.
598
+ """
599
+ from ectype.fingerprint.comparison import resolve_sensitivity
600
+
601
+ resolve_sensitivity(sensitivity) # reject a bad setting before any work
602
+ from ectype.profiling.reference import size_view
603
+
604
+ syn = read_table(synthetic)
605
+ hold = read_table(holdout) if holdout is not None else None
606
+ policy = resolve_policy(fp.manifest.disclosure_policy)
607
+ columns = {c.name: c for c in fp.manifest.columns}
608
+ # Reference keys are measured as group sizes, in every frame (module docstring). The
609
+ # structural and constraint checks below see the rows as given.
610
+ references = sorted(c.name for c in fp.manifest.columns if c.role == Role.REFERENCE)
611
+ given = syn
612
+ syn = size_view(syn, references)
613
+ if hold is not None:
614
+ hold = size_view(hold, references)
615
+
616
+ # Pseudonymised columns: synthetic rows carry the fingerprint's tokens. A frame of real
617
+ # rows does not, and is then compared without matching labels (module docstring).
618
+ tokens = pseudonym_labels(fp)
619
+ label_free = {c for c, labels in tokens.items() if not carries_tokens(syn, c, labels)}
620
+
621
+ sealed_set = fp.open_seal()
622
+ calib_targets, calib_skipped = _comparable(list(fp.calibration.targets), label_free)
623
+ sealed_targets, sealed_skipped = _comparable(list(sealed_set.targets), label_free)
624
+ calib = Section("calibration", "Calibration targets", CALIBRATION_EVIDENCE,
625
+ [evaluate_one(t, syn, columns, policy, label_free=label_free)
626
+ for t in calib_targets])
627
+ calib.notes.append("Optimizer evidence only: these targets were visible to calibration "
628
+ "and are not evidence of fidelity. Failures do not fail the report.")
629
+ sealed = Section("sealed", "Sealed targets", SEALED_EVIDENCE,
630
+ [evaluate_one(t, syn, columns, policy, label_free=label_free)
631
+ for t in sealed_targets])
632
+ if references:
633
+ for sec in (calib, sealed):
634
+ sec.notes.append(f"Reference key column(s) {', '.join(references)}: compared by "
635
+ "group size (the number of rows that share a key), never by key "
636
+ "value.")
637
+ if tokens:
638
+ which = ", ".join(sorted(tokens))
639
+ for sec, skipped in ((calib, calib_skipped), (sealed, sealed_skipped)):
640
+ if label_free:
641
+ sec.notes.append(_label_free_note(sorted(label_free), "the validated rows",
642
+ skipped))
643
+ else:
644
+ sec.notes.append(f"Pseudonymised column(s) {which}: targets and synthetic "
645
+ "rows carry the fingerprint's stand-in tokens, not source "
646
+ "labels.")
647
+ from ectype.fingerprint.comparison import NULL_LEVEL_METRICS, null_level_step
648
+
649
+ n_source = fp.manifest.dataset.source_records
650
+ steps = {r.id: null_level_step(fp, t, r.reference, r.candidate, n_source, syn.height)
651
+ for t, r in zip(sealed_targets, sealed.results)
652
+ if t.metric in NULL_LEVEL_METRICS and r.error is None}
653
+ decision = sealed_decision(sealed_targets, sealed.results, source_rows=n_source,
654
+ synthetic_rows=syn.height, sensitivity=sensitivity,
655
+ extra_steps=steps)
656
+ sealed.notes.append(
657
+ "Withheld from calibration (seal hash verified). Each target is checked against its own "
658
+ "~95% tolerance; the verdict fails when a failure is beyond sampling noise after "
659
+ f"Benjamini-Hochberg control over all {sealed.n} sealed targets "
660
+ f"(sensitivity {decision['sensitivity']}, q={decision['q']:g}).")
661
+
662
+ hold_sec = None
663
+ if hold is not None:
664
+ hold_targets = list(fp.calibration.targets) + list(sealed_set.targets)
665
+ # group sizes are counts: they compare only between frames of about the same size
666
+ sized = bool(references) and not 0.5 <= hold.height / max(syn.height, 1) <= 2.0
667
+ if sized:
668
+ hold_targets = [t for t in hold_targets
669
+ if t.metric == "univariate.missing_rate"
670
+ or not set(t.columns) & set(references)]
671
+ hold_sec = _holdout_section(fp, syn, hold, hold_targets,
672
+ columns, policy, seed, include_multivariate, tokens)
673
+ if sized:
674
+ hold_sec.notes.append(
675
+ f"Reference key column(s) {', '.join(references)}: the holdout has "
676
+ f"{hold.height} rows and the validated table {syn.height}; group sizes "
677
+ f"depend on the size of a table, so only their empty-cell share is compared.")
678
+
679
+ m = fp.manifest
680
+ header = {
681
+ "fingerprint_hash": fp.content_hash(),
682
+ "seal_hash": m.targets.seal_hash,
683
+ "dataset": m.dataset.name,
684
+ "policy": m.disclosure_policy.profile,
685
+ "engine_version": __version__,
686
+ "fingerprint_engine_version": getattr(m.provenance, "engine_version", None),
687
+ "fingerprint_version": m.fingerprint_version,
688
+ "n_rows": syn.height,
689
+ "n_columns": syn.width,
690
+ "holdout_rows": None if hold is None else hold.height,
691
+ "seed": seed,
692
+ "pseudonymised_columns": sorted(tokens),
693
+ "reference_columns": references,
694
+ }
695
+ return ValidationReport(
696
+ header=header,
697
+ structural=structural_checks(fp, given, expected_rows) + sum_checks(fp, given, hold),
698
+ constraints=constraint_checks(fp, given),
699
+ calibration=calib,
700
+ sealed=sealed,
701
+ holdout=hold_sec,
702
+ sealed_decision=decision,
703
+ )
704
+
705
+
706
+ __all__ = ["ValidationReport", "carries_tokens", "evaluate_one", "expected_columns",
707
+ "pseudonym_labels", "sealed_decision", "sum_checks", "validate"]