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,280 @@
1
+ """Relational schema: tables, primary keys and parent -> child foreign-key relationships.
2
+
3
+ ``RelationalSchema`` is a pydantic model validated on construction:
4
+
5
+ * table names are safe identifiers (``[A-Za-z0-9_-]``, they become ``tables/<name>.dfp``
6
+ members of the ``.dfpr`` container);
7
+ * every relationship names known tables, the parent key is the parent's primary key, the child
8
+ is not its own parent and the foreign key is not the child's primary key;
9
+ * the parent -> child graph is acyclic (a forest of hierarchies is the common case; a table with
10
+ several parents is a valid schema but the M30 generator supports one parent per table).
11
+
12
+ :func:`infer_relationships` proposes relationships from data (name match + value inclusion).
13
+ Its output is evidence for a human, never binding.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from dataclasses import dataclass, field
20
+ from typing import Any, cast
21
+
22
+ import polars as pl
23
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
24
+
25
+ from ectype.errors import ProfilingError
26
+
27
+ _NAME_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_-]{0,127}$")
28
+ #: Helper-column prefixes reserved by the relational layer.
29
+ COUNT_PREFIX = "__n_"
30
+ PARENT_PREFIX = "__parent_"
31
+
32
+
33
+ def count_column(child: str) -> str:
34
+ """Name of the per-parent child-count helper column added to the parent table."""
35
+ return f"{COUNT_PREFIX}{child}"
36
+
37
+
38
+ def parent_column(col: str) -> str:
39
+ """Name of the parent-attribute helper column joined onto child rows."""
40
+ return f"{PARENT_PREFIX}{col}"
41
+
42
+
43
+ class _Model(BaseModel):
44
+ model_config = ConfigDict(extra="forbid", frozen=True)
45
+
46
+
47
+ class Relationship(_Model):
48
+ """``child.child_fk`` references ``parent.parent_key`` (one parent, many children)."""
49
+
50
+ parent: str
51
+ parent_key: str
52
+ child: str
53
+ child_fk: str
54
+
55
+ @property
56
+ def key(self) -> str:
57
+ return f"{self.parent}.{self.parent_key}->{self.child}.{self.child_fk}"
58
+
59
+
60
+ class CrossTableConstraint(_Model):
61
+ """A hard constraint over a child row joined with its parent row.
62
+
63
+ ``expression`` uses the normal expression grammar; child columns are referenced by name and
64
+ parent columns as ``parent.<col>`` (rewritten to the backquoted joined column
65
+ ```parent.<col>```), e.g. ``"order_day >= parent.signup_day"``. Enforced by rejection per
66
+ child row at generation time.
67
+ """
68
+
69
+ id: str
70
+ child: str
71
+ expression: str
72
+ description: str | None = None
73
+
74
+
75
+ class RelationalSchema(_Model):
76
+ """``tables`` maps table name -> primary-key column."""
77
+
78
+ tables: dict[str, str]
79
+ relationships: list[Relationship] = Field(default_factory=list)
80
+
81
+ @model_validator(mode="after")
82
+ def _check(self) -> RelationalSchema:
83
+ if not self.tables:
84
+ raise ValueError("a relational schema needs at least one table")
85
+ for name, pk in self.tables.items():
86
+ if not _NAME_RE.match(name):
87
+ raise ValueError(f"invalid table name {name!r}: use letters, digits, '_' "
88
+ f"and '-' only")
89
+ if not pk:
90
+ raise ValueError(f"table {name!r} has an empty primary key")
91
+ seen = set()
92
+ for r in self.relationships:
93
+ for t in (r.parent, r.child):
94
+ if t not in self.tables:
95
+ raise ValueError(f"relationship {r.key} references unknown table {t!r}")
96
+ if r.parent == r.child:
97
+ raise ValueError(f"self-referencing relationship {r.key} is not supported")
98
+ if r.parent_key != self.tables[r.parent]:
99
+ raise ValueError(f"relationship {r.key}: parent key must be the primary key "
100
+ f"{self.tables[r.parent]!r} of {r.parent!r}")
101
+ if r.child_fk == self.tables[r.child]:
102
+ raise ValueError(f"relationship {r.key}: the foreign key cannot be the child's "
103
+ f"primary key")
104
+ if (r.parent, r.child) in seen:
105
+ raise ValueError(f"duplicate relationship between {r.parent!r} and "
106
+ f"{r.child!r}")
107
+ seen.add((r.parent, r.child))
108
+ self.topological_order() # raises on cycles
109
+ return self
110
+
111
+ # -- graph helpers ---------------------------------------------------------------------
112
+ def parents_of(self, table: str) -> list[Relationship]:
113
+ return [r for r in self.relationships if r.child == table]
114
+
115
+ def children_of(self, table: str) -> list[Relationship]:
116
+ return [r for r in self.relationships if r.parent == table]
117
+
118
+ @property
119
+ def roots(self) -> list[str]:
120
+ children = {r.child for r in self.relationships}
121
+ return [t for t in self.tables if t not in children]
122
+
123
+ def topological_order(self) -> list[str]:
124
+ """Parents before children (stable: schema order among ready tables)."""
125
+ indeg = {t: 0 for t in self.tables}
126
+ for r in self.relationships:
127
+ indeg[r.child] += 1
128
+ order: list[str] = []
129
+ ready = [t for t in self.tables if indeg[t] == 0]
130
+ while ready:
131
+ t = ready.pop(0)
132
+ order.append(t)
133
+ for r in self.relationships:
134
+ if r.parent == t:
135
+ indeg[r.child] -= 1
136
+ if indeg[r.child] == 0:
137
+ ready.append(r.child)
138
+ if len(order) != len(self.tables):
139
+ cyc = sorted(t for t, d in indeg.items() if d > 0)
140
+ raise ValueError(f"relationships contain a cycle among tables {cyc}")
141
+ return order
142
+
143
+ def check_tables(self, tables: dict[str, pl.DataFrame]) -> None:
144
+ """Keys exist in the data, primary keys are unique and non-null."""
145
+ missing = sorted(set(self.tables) - set(tables))
146
+ if missing:
147
+ raise ProfilingError(f"tables missing from the input: {missing}")
148
+ for name, pk in self.tables.items():
149
+ df = tables[name]
150
+ if pk not in df.columns:
151
+ raise ProfilingError(f"primary key {pk!r} not found in table {name!r}")
152
+ s = df.get_column(pk)
153
+ if s.null_count():
154
+ raise ProfilingError(f"primary key {name}.{pk} has nulls")
155
+ if s.n_unique() != s.len():
156
+ raise ProfilingError(f"primary key {name}.{pk} is not unique")
157
+ for r in self.relationships:
158
+ if r.child_fk not in tables[r.child].columns:
159
+ raise ProfilingError(f"foreign key {r.child}.{r.child_fk} not found")
160
+
161
+
162
+ # ---------------------------------------------------------------------------------------------
163
+ # Inference
164
+ # ---------------------------------------------------------------------------------------------
165
+
166
+
167
+ @dataclass
168
+ class RelationshipSuggestion:
169
+ """A proposed relationship with its evidence (not binding)."""
170
+
171
+ relationship: Relationship
172
+ inclusion: float # share of non-null child values found among parent keys
173
+ name_match: str | None # which naming rule matched, if any
174
+ child_coverage: float # share of child rows with a non-null FK
175
+ parent_coverage: float # share of parent keys referenced at least once
176
+ score: float
177
+ evidence: list[str] = field(default_factory=list)
178
+
179
+ def to_dict(self) -> dict[str, Any]:
180
+ return {**self.relationship.model_dump(), "inclusion": self.inclusion,
181
+ "name_match": self.name_match, "child_coverage": self.child_coverage,
182
+ "parent_coverage": self.parent_coverage, "score": self.score,
183
+ "evidence": list(self.evidence)}
184
+
185
+
186
+ def _singular(name: str) -> str:
187
+ n = name.lower()
188
+ if n.endswith("ies") and len(n) > 3:
189
+ return n[:-3] + "y"
190
+ if n.endswith("ses") or n.endswith("xes"):
191
+ return n[:-2]
192
+ if n.endswith("s") and not n.endswith("ss"):
193
+ return n[:-1]
194
+ return n
195
+
196
+
197
+ def _name_rule(parent: str, pk: str, fk: str) -> str | None:
198
+ f, k, p = fk.lower(), pk.lower(), parent.lower()
199
+ s = _singular(parent)
200
+ if f == k and k != "id":
201
+ return "same_name"
202
+ if k == "id" and f in (f"{s}_id", f"{p}_id", f"{s}id"):
203
+ return "table_id"
204
+ if f in (f"{s}_{k}", f"{p}_{k}"):
205
+ return "table_prefixed_key"
206
+ if f.endswith(f"_{k}") and k != "id":
207
+ return "key_suffix"
208
+ return None
209
+
210
+
211
+ def _key_candidates(name: str, df: pl.DataFrame) -> list[str]:
212
+ out = []
213
+ for c in df.columns:
214
+ s = df.get_column(c)
215
+ if s.dtype.is_float() or s.len() == 0 or s.null_count():
216
+ continue
217
+ if not (s.dtype.is_integer() or s.dtype == pl.String):
218
+ continue
219
+ if s.n_unique() == s.len():
220
+ out.append(c)
221
+ hint = {"id", f"{_singular(name)}_id", f"{name.lower()}_id"}
222
+ out.sort(key=lambda c: (c.lower() not in hint, not c.lower().endswith("id"), c))
223
+ return out
224
+
225
+
226
+ def infer_relationships(tables: dict[str, pl.DataFrame], *, min_inclusion: float = 0.99,
227
+ require_name_match: bool = True,
228
+ primary_keys: dict[str, str] | None = None
229
+ ) -> list[RelationshipSuggestion]:
230
+ """Suggest foreign keys: a child column whose non-null values are (>= ``min_inclusion``)
231
+ contained in a parent's unique key column, preferably with a matching name.
232
+
233
+ ``primary_keys`` pins the key per table; otherwise every unique, non-null integer/string
234
+ column is a key candidate. Suggestions are sorted by score (best first)."""
235
+ pks = dict(primary_keys or {})
236
+ keys = {t: ([pks[t]] if t in pks else _key_candidates(t, df)) for t, df in tables.items()}
237
+ out: list[RelationshipSuggestion] = []
238
+ for parent, pdf in tables.items():
239
+ for pk in keys[parent]:
240
+ if pk not in pdf.columns:
241
+ continue
242
+ pvals = pdf.get_column(pk)
243
+ pset = pvals.unique()
244
+ for child, cdf in tables.items():
245
+ if child == parent:
246
+ continue
247
+ for fk in cdf.columns:
248
+ if fk in keys[child][:1]:
249
+ continue
250
+ s = cdf.get_column(fk)
251
+ if s.dtype != pvals.dtype and not (s.dtype.is_integer()
252
+ and pvals.dtype.is_integer()):
253
+ continue
254
+ rule = _name_rule(parent, pk, fk)
255
+ if require_name_match and rule is None:
256
+ continue
257
+ nn = s.drop_nulls()
258
+ if nn.len() == 0:
259
+ continue
260
+ inc = float(cast(float, nn.is_in(pset.cast(nn.dtype).implode()).mean()))
261
+ if inc < min_inclusion:
262
+ continue
263
+ pcov = float(cast(float, pset.is_in(nn.unique().cast(pset.dtype).implode()).mean()))
264
+ ccov = nn.len() / max(s.len(), 1)
265
+ score = inc + (0.5 if rule else 0.0) + 0.1 * pcov
266
+ ev = [f"{inc:.2%} of {child}.{fk} values found in {parent}.{pk}",
267
+ f"{pcov:.0%} of {parent} keys referenced",
268
+ f"{ccov:.0%} of {child} rows have a non-null {fk}"]
269
+ if rule:
270
+ ev.append(f"name rule: {rule}")
271
+ out.append(RelationshipSuggestion(
272
+ Relationship(parent=parent, parent_key=pk, child=child, child_fk=fk),
273
+ inc, rule, ccov, pcov, score, ev))
274
+ out.sort(key=lambda s: (-s.score, s.relationship.key))
275
+ return out
276
+
277
+
278
+ __all__ = ["COUNT_PREFIX", "PARENT_PREFIX", "CrossTableConstraint", "RelationalSchema",
279
+ "Relationship", "RelationshipSuggestion", "count_column", "infer_relationships",
280
+ "parent_column"]
@@ -0,0 +1,288 @@
1
+ """Validate synthetic related tables against a :class:`RelationalFingerprint`.
2
+
3
+ Sections:
4
+
5
+ * **Referential integrity** per relationship: share of non-null foreign keys that resolve to a
6
+ parent primary key (must be 100%), plus null foreign keys and duplicate primary keys.
7
+ * **Child-count distribution** per relationship: 1-Wasserstein distance between the synthetic
8
+ per-parent child counts and the stored (policy-coarsened) count quantiles, computed on the
9
+ stored quantile levels and reported relative to ``max(stored mean, 1)``.
10
+ * **Parent-child associations**: Spearman (numeric parent attribute) or correlation ratio
11
+ ``eta`` (categorical parent attribute) between parent attributes and child aggregates (count,
12
+ mean of a numeric child column per parent), compared to the stored values by absolute
13
+ difference.
14
+ * **Cross-table constraints**: violations on the child rows joined with their parents.
15
+ * **Per-table reports**: :func:`ectype.validate` for every table, after re-deriving
16
+ the helper columns (``__n_*`` from the synthetic children, ``__parent_*`` by joining the
17
+ synthetic parent) and dropping foreign keys, which the per-table models exclude.
18
+
19
+ ``passed`` requires every relational check to pass and every per-table report to pass;
20
+ ``relational_passed`` covers the relational sections only.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from dataclasses import dataclass, field
26
+ from typing import Any
27
+
28
+ import numpy as np
29
+ import polars as pl
30
+
31
+ from ectype.fingerprint.disclosure import resolve_policy
32
+ from ectype.io import read_table
33
+ from ectype.relational.fit import (
34
+ NUMERIC_TYPES,
35
+ RelationalFingerprint,
36
+ association,
37
+ child_counts,
38
+ child_means,
39
+ count_quantiles,
40
+ cross_violations,
41
+ join_parent,
42
+ )
43
+ from ectype.types import Role
44
+
45
+
46
+ @dataclass
47
+ class IntegrityResult:
48
+ relationship: str
49
+ n_child_rows: int
50
+ n_null_fk: int
51
+ n_orphans: int
52
+ duplicate_parent_keys: int
53
+ passed: bool
54
+
55
+ @property
56
+ def integrity(self) -> float:
57
+ nn = self.n_child_rows - self.n_null_fk
58
+ return 1.0 if nn == 0 else (nn - self.n_orphans) / nn
59
+
60
+ def to_dict(self) -> dict[str, Any]:
61
+ return {"relationship": self.relationship, "n_child_rows": self.n_child_rows,
62
+ "n_null_fk": self.n_null_fk, "n_orphans": self.n_orphans,
63
+ "duplicate_parent_keys": self.duplicate_parent_keys,
64
+ "integrity": self.integrity, "passed": self.passed}
65
+
66
+
67
+ @dataclass
68
+ class CountResult:
69
+ relationship: str
70
+ wasserstein: float
71
+ relative: float
72
+ tolerance: float
73
+ stored_mean: float
74
+ synthetic_mean: float
75
+ stored_zero_fraction: float
76
+ synthetic_zero_fraction: float
77
+ passed: bool
78
+
79
+ def to_dict(self) -> dict[str, Any]:
80
+ return dict(self.__dict__)
81
+
82
+
83
+ @dataclass
84
+ class AssociationResult:
85
+ relationship: str
86
+ parent_column: str
87
+ aggregate: str
88
+ metric: str
89
+ stored: float
90
+ synthetic: float
91
+ tolerance: float
92
+ passed: bool
93
+
94
+ @property
95
+ def error(self) -> float:
96
+ return abs(self.synthetic - self.stored) if np.isfinite(self.synthetic) else float("inf")
97
+
98
+ def to_dict(self) -> dict[str, Any]:
99
+ return {**self.__dict__, "error": self.error}
100
+
101
+
102
+ @dataclass
103
+ class CrossConstraintResult:
104
+ id: str
105
+ child: str
106
+ expression: str
107
+ violations: int
108
+ n_rows: int
109
+ passed: bool
110
+
111
+ def to_dict(self) -> dict[str, Any]:
112
+ return dict(self.__dict__)
113
+
114
+
115
+ @dataclass
116
+ class RelationalReport:
117
+ integrity: list[IntegrityResult] = field(default_factory=list)
118
+ counts: list[CountResult] = field(default_factory=list)
119
+ associations: list[AssociationResult] = field(default_factory=list)
120
+ cross_constraints: list[CrossConstraintResult] = field(default_factory=list)
121
+ tables: dict[str, Any] = field(default_factory=dict) # name -> ValidationReport
122
+ notes: list[str] = field(default_factory=list)
123
+
124
+ @property
125
+ def referential_integrity(self) -> float:
126
+ return min((r.integrity for r in self.integrity), default=1.0)
127
+
128
+ @property
129
+ def relational_passed(self) -> bool:
130
+ return (all(r.passed for r in self.integrity) and all(r.passed for r in self.counts)
131
+ and all(r.passed for r in self.associations)
132
+ and all(r.passed for r in self.cross_constraints))
133
+
134
+ @property
135
+ def tables_passed(self) -> bool:
136
+ return all(r.passed for r in self.tables.values())
137
+
138
+ @property
139
+ def passed(self) -> bool:
140
+ return self.relational_passed and self.tables_passed
141
+
142
+ def summary(self) -> str:
143
+ lines = [f"Relational validation {'PASSED' if self.passed else 'FAILED'} "
144
+ f"(relational {'ok' if self.relational_passed else 'FAILED'}, tables "
145
+ f"{'ok' if self.tables_passed else 'FAILED'})",
146
+ f"Referential integrity: {self.referential_integrity:.2%}"]
147
+ for r in self.integrity:
148
+ lines.append(f" [{'ok' if r.passed else 'FAIL'}] {r.relationship}: "
149
+ f"{r.integrity:.2%} ({r.n_orphans} orphans, {r.n_null_fk} null FKs)")
150
+ lines.append("Child-count distribution (W1 / max(mean, 1)):")
151
+ for c in self.counts:
152
+ lines.append(f" [{'ok' if c.passed else 'FAIL'}] {c.relationship}: "
153
+ f"{c.relative:.3f} (tol {c.tolerance}); mean {c.synthetic_mean:.3g} "
154
+ f"vs {c.stored_mean:.3g}")
155
+ n_ok = sum(a.passed for a in self.associations)
156
+ lines.append(f"Parent-child associations: {n_ok}/{len(self.associations)} within "
157
+ f"tolerance")
158
+ for a in sorted(self.associations, key=lambda a: (a.passed, -a.error))[:8]:
159
+ lines.append(f" [{'ok' if a.passed else 'FAIL'}] {a.relationship} "
160
+ f"{a.metric}({a.parent_column}, {a.aggregate}): "
161
+ f"{a.synthetic:.3f} vs {a.stored:.3f}")
162
+ for x in self.cross_constraints:
163
+ lines.append(f" [{'ok' if x.passed else 'FAIL'}] cross {x.id} ({x.child}): "
164
+ f"{x.violations} violations")
165
+ for name, rep in self.tables.items():
166
+ lines.append(f"Table {name}: {'PASSED' if rep.passed else 'FAILED'}")
167
+ lines.extend(f"Note: {n}" for n in self.notes)
168
+ return "\n".join(lines)
169
+
170
+ def to_dict(self, verbose: bool = False) -> dict[str, Any]:
171
+ return {
172
+ "passed": self.passed,
173
+ "relational_passed": self.relational_passed,
174
+ "tables_passed": self.tables_passed,
175
+ "referential_integrity": self.referential_integrity,
176
+ "integrity": [r.to_dict() for r in self.integrity],
177
+ "child_counts": [r.to_dict() for r in self.counts],
178
+ "associations": [r.to_dict() for r in self.associations],
179
+ "cross_constraints": [r.to_dict() for r in self.cross_constraints],
180
+ "tables": {n: r.to_dict(verbose=verbose) if hasattr(r, "to_dict") else r
181
+ for n, r in self.tables.items()},
182
+ "notes": list(self.notes),
183
+ }
184
+
185
+
186
+ def with_helpers(rfp: RelationalFingerprint, tables: dict[str, pl.DataFrame], name: str
187
+ ) -> pl.DataFrame:
188
+ """``tables[name]`` in the per-table fingerprint's layout: helper columns re-derived from
189
+ the related tables, foreign keys dropped, columns in manifest order."""
190
+ from ectype.validation.validator import expected_columns
191
+
192
+ schema = rfp.schema
193
+ df = tables[name]
194
+ pk = schema.tables[name]
195
+ for rel in schema.children_of(name):
196
+ fit = rfp.section.fit_for(rel.child)
197
+ assert fit is not None, f"no relationship fit for child table {rel.child!r}"
198
+ n = child_counts(df.get_column(pk), tables[rel.child].get_column(rel.child_fk))
199
+ df = df.with_columns(pl.Series(fit.count_column, n, dtype=pl.Int64))
200
+ for rel in schema.parents_of(name):
201
+ fit = rfp.section.fit_for(name)
202
+ if fit and fit.conditioning:
203
+ joined = join_parent(df.select(rel.child_fk),
204
+ tables[rel.parent].select([rel.parent_key] +
205
+ [c.parent_column
206
+ for c in fit.conditioning]), rel)
207
+ df = df.with_columns(joined.get_column(f"parent.{c.parent_column}")
208
+ .alias(c.helper_column) for c in fit.conditioning)
209
+ fp = rfp.fingerprints[name]
210
+ want = expected_columns(fp)
211
+ return df.select([c for c in want if c in df.columns])
212
+
213
+
214
+ def validate_relational(rfp: RelationalFingerprint, synthetic_tables: dict[str, Any], *,
215
+ seed: int = 0, association_tolerance: float = 0.1,
216
+ count_tolerance: float = 0.15, per_table: bool = True
217
+ ) -> RelationalReport:
218
+ """Validate ``synthetic_tables`` (name -> table) against ``rfp`` (see module doc)."""
219
+ from ectype.validation.validator import validate
220
+
221
+ schema = rfp.schema
222
+ tables = {n: read_table(synthetic_tables[n]) for n in schema.tables
223
+ if n in synthetic_tables}
224
+ report = RelationalReport()
225
+ missing = sorted(set(schema.tables) - set(tables))
226
+ if missing:
227
+ raise ValueError(f"synthetic tables missing: {missing}")
228
+ policy = resolve_policy(rfp.section.disclosure_policy)
229
+
230
+ for fit in rfp.section.relationships:
231
+ rel = fit.relationship
232
+ parent, child = tables[rel.parent], tables[rel.child]
233
+ pk = parent.get_column(rel.parent_key)
234
+ fk = child.get_column(rel.child_fk)
235
+ nn = fk.drop_nulls()
236
+ orphans = int((~nn.is_in(pk.cast(nn.dtype, strict=False).drop_nulls().implode())).sum())
237
+ dup = int(pk.len() - pk.n_unique())
238
+ report.integrity.append(IntegrityResult(rel.key, child.height, fk.null_count(),
239
+ orphans, dup, orphans == 0 and dup == 0))
240
+
241
+ n = child_counts(pk, fk)
242
+ levels = np.asarray(fit.count_levels)
243
+ q_syn = count_quantiles(n, levels)
244
+ q_ref = np.asarray(fit.count_quantiles)
245
+ w1 = float(np.mean(np.abs(q_syn - q_ref)))
246
+ rel_w1 = w1 / max(fit.count_mean, 1.0)
247
+ report.counts.append(CountResult(
248
+ rel.key, w1, rel_w1, count_tolerance, fit.count_mean,
249
+ float(n.mean()) if n.size else 0.0, fit.zero_fraction,
250
+ float((n == 0).mean()) if n.size else 0.0, rel_w1 <= count_tolerance))
251
+
252
+ pschema = {c.name: c for c in rfp.fingerprints[rel.parent].manifest.columns}
253
+ cschema = {c.name: c for c in rfp.fingerprints[rel.child].manifest.columns}
254
+ numeric_child = {c: s for c, s in cschema.items() if s.role == Role.FEATURE
255
+ and s.logical_type in NUMERIC_TYPES and c in child.columns}
256
+ means = child_means(pk, child, rel.child_fk, numeric_child)
257
+ for t in fit.associations:
258
+ if t.aggregate == "count":
259
+ y = n.astype(float)
260
+ else:
261
+ y = means.get(t.aggregate.split(":", 1)[1], np.full(pk.len(), np.nan))
262
+ if t.parent_column in parent.columns:
263
+ _, val = association(parent.get_column(t.parent_column),
264
+ pschema[t.parent_column], y, policy)
265
+ else:
266
+ val = float("nan")
267
+ ok = bool(np.isfinite(val) and abs(val - t.value) <= association_tolerance)
268
+ report.associations.append(AssociationResult(
269
+ rel.key, t.parent_column, t.aggregate, t.metric, t.value, float(val),
270
+ association_tolerance, ok))
271
+
272
+ for c in rfp.section.cross_constraints:
273
+ rel = schema.parents_of(c.child)[0]
274
+ joined = join_parent(tables[c.child], tables[rel.parent], rel)
275
+ v = int(cross_violations(joined, [c])[c.id].sum())
276
+ report.cross_constraints.append(CrossConstraintResult(
277
+ c.id, c.child, c.expression, v, joined.height, v == 0))
278
+
279
+ if per_table:
280
+ for name in schema.tables:
281
+ report.tables[name] = validate(rfp.fingerprints[name],
282
+ with_helpers(rfp, tables, name), seed=seed)
283
+ report.notes.extend(rfp.section.notes)
284
+ return report
285
+
286
+
287
+ __all__ = ["AssociationResult", "CountResult", "CrossConstraintResult", "IntegrityResult",
288
+ "RelationalReport", "validate_relational", "with_helpers"]