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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
ectype/relational/fit.py
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
"""Fit a relational fingerprint: one single-table fingerprint per table plus a relational section.
|
|
2
|
+
|
|
3
|
+
Design (M30)
|
|
4
|
+
------------
|
|
5
|
+
For every relationship ``parent -> child`` (``child.fk`` references ``parent.pk``):
|
|
6
|
+
|
|
7
|
+
1. **Child counts conditioned on the parent.** The number of children of each parent row is
|
|
8
|
+
added to the parent frame as the helper column ``__n_<child>`` (a discrete feature) before
|
|
9
|
+
the parent is fitted, so the parent's joint model (copula) carries the dependence between
|
|
10
|
+
parent attributes and how many children a parent has. Generation reads the counts back from
|
|
11
|
+
the generated parent rows.
|
|
12
|
+
2. **Child attributes conditioned on parent features.** The ``k`` parent columns most associated
|
|
13
|
+
with the child's columns (bias-corrected plug-in mutual information on rank-binned values,
|
|
14
|
+
``k = 3`` by default) are joined onto the child rows as ``__parent_<col>`` helper columns and
|
|
15
|
+
the child is fitted *with* them. At generation time the helper latents are fixed to the
|
|
16
|
+
encoded values of the generated parent and the remaining child latents are drawn from the
|
|
17
|
+
Gaussian conditional (see :mod:`ectype.relational.generate`).
|
|
18
|
+
|
|
19
|
+
Keys: each table's primary key is an identifier (regenerated fresh), each foreign key is
|
|
20
|
+
excluded from the per-table model (it is assigned from the synthetic parents, so referential
|
|
21
|
+
integrity is 100% by construction).
|
|
22
|
+
|
|
23
|
+
Fit order is topological (parents first) so the child's ``__parent_*`` helper columns can reuse
|
|
24
|
+
the parent's logical types; child counts are taken from the source data, i.e. parents are always
|
|
25
|
+
fitted *after* their children have been counted.
|
|
26
|
+
|
|
27
|
+
Stored relational targets (policy-safe: quantiles at the policy's quantile levels and coarsened
|
|
28
|
+
to its significant digits, statistics only for groups with at least ``min_category_support``
|
|
29
|
+
parents) are the child-count quantiles and parent-child associations (Spearman for numeric parent
|
|
30
|
+
attributes, correlation ratio ``eta`` for categorical ones) between parent attributes and child
|
|
31
|
+
aggregates (child count; mean of each numeric child column per parent).
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
from __future__ import annotations
|
|
35
|
+
|
|
36
|
+
import re
|
|
37
|
+
from collections.abc import Iterable, Mapping
|
|
38
|
+
from dataclasses import dataclass, field
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
from typing import Any
|
|
41
|
+
|
|
42
|
+
import numpy as np
|
|
43
|
+
import polars as pl
|
|
44
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
45
|
+
|
|
46
|
+
from ectype.errors import ProfilingError
|
|
47
|
+
from ectype.fingerprint.core import Fingerprint
|
|
48
|
+
from ectype.fingerprint.disclosure import (
|
|
49
|
+
coarsen,
|
|
50
|
+
coarsen_array,
|
|
51
|
+
quantile_levels,
|
|
52
|
+
resolve_policy,
|
|
53
|
+
)
|
|
54
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ReservedSection
|
|
55
|
+
from ectype.io import read_table
|
|
56
|
+
from ectype.io.values import column_to_values
|
|
57
|
+
from ectype.relational.schema import (
|
|
58
|
+
CrossTableConstraint,
|
|
59
|
+
RelationalSchema,
|
|
60
|
+
Relationship,
|
|
61
|
+
count_column,
|
|
62
|
+
parent_column,
|
|
63
|
+
)
|
|
64
|
+
from ectype.rng import stream
|
|
65
|
+
from ectype.types import LogicalType, Role
|
|
66
|
+
|
|
67
|
+
RELATIONAL_FORMAT_VERSION = "1.0"
|
|
68
|
+
NUMERIC_TYPES = (LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.DATETIME)
|
|
69
|
+
CATEGORY_TYPES = (LogicalType.CATEGORICAL, LogicalType.BOOLEAN)
|
|
70
|
+
MODELED = NUMERIC_TYPES + CATEGORY_TYPES
|
|
71
|
+
_PARENT_REF = re.compile(r"(?<![`\w.])parent\.([A-Za-z_]\w*)")
|
|
72
|
+
_MI_BINS = 10
|
|
73
|
+
#: Minimum correlation ratio for count stratification by a categorical parent column.
|
|
74
|
+
STRATA_MIN_ETA = 0.1
|
|
75
|
+
OTHER = "__other__"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def strata_labels(s: pl.Series) -> np.ndarray:
|
|
79
|
+
return s.cast(pl.String).fill_null("<null>").to_numpy().astype(str)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class _Model(BaseModel):
|
|
83
|
+
model_config = ConfigDict(extra="forbid")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ConditioningColumn(_Model):
|
|
87
|
+
parent_column: str
|
|
88
|
+
helper_column: str
|
|
89
|
+
mutual_information: float
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class AssociationTarget(_Model):
|
|
93
|
+
"""``metric(parent_column, aggregate)`` over parents; aggregate is ``"count"`` or
|
|
94
|
+
``"mean:<child column>"``."""
|
|
95
|
+
|
|
96
|
+
parent_column: str
|
|
97
|
+
aggregate: str
|
|
98
|
+
metric: str # "spearman" | "eta"
|
|
99
|
+
value: float
|
|
100
|
+
n_parents: int
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class CountStrata(_Model):
|
|
104
|
+
"""Per-category child-count quantiles for the categorical parent column most associated
|
|
105
|
+
with the count (``eta``). Categories with fewer than ``min_category_support`` parents are
|
|
106
|
+
pooled into ``"__other__"`` (also used for unseen labels)."""
|
|
107
|
+
|
|
108
|
+
column: str
|
|
109
|
+
eta: float
|
|
110
|
+
labels: list[str]
|
|
111
|
+
levels: list[list[float]]
|
|
112
|
+
quantiles: list[list[float]]
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class RelationshipFit(_Model):
|
|
116
|
+
relationship: Relationship
|
|
117
|
+
count_column: str
|
|
118
|
+
conditioning: list[ConditioningColumn] = Field(default_factory=list)
|
|
119
|
+
count_strata: CountStrata | None = None
|
|
120
|
+
n_parents: int
|
|
121
|
+
n_children: int
|
|
122
|
+
count_levels: list[float]
|
|
123
|
+
count_quantiles: list[float]
|
|
124
|
+
count_mean: float
|
|
125
|
+
zero_fraction: float
|
|
126
|
+
associations: list[AssociationTarget] = Field(default_factory=list)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class TableInfo(_Model):
|
|
130
|
+
columns: list[str] # source column order (output order)
|
|
131
|
+
primary_key: str
|
|
132
|
+
foreign_keys: dict[str, str] = Field(default_factory=dict) # fk column -> parent table
|
|
133
|
+
count_columns: list[str] = Field(default_factory=list)
|
|
134
|
+
parent_columns: list[str] = Field(default_factory=list)
|
|
135
|
+
source_records: int
|
|
136
|
+
content_hash: str
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class RelationalSection(_Model):
|
|
140
|
+
format: str = "dfpr"
|
|
141
|
+
version: str = RELATIONAL_FORMAT_VERSION
|
|
142
|
+
schema_: RelationalSchema = Field(alias="schema")
|
|
143
|
+
tables: dict[str, TableInfo]
|
|
144
|
+
relationships: list[RelationshipFit]
|
|
145
|
+
cross_constraints: list[CrossTableConstraint] = Field(default_factory=list)
|
|
146
|
+
disclosure_policy: DisclosurePolicySpec
|
|
147
|
+
seed: int
|
|
148
|
+
notes: list[str] = Field(default_factory=list)
|
|
149
|
+
|
|
150
|
+
model_config = ConfigDict(extra="forbid", populate_by_name=True)
|
|
151
|
+
|
|
152
|
+
def fit_for(self, child: str) -> RelationshipFit | None:
|
|
153
|
+
for f in self.relationships:
|
|
154
|
+
if f.relationship.child == child:
|
|
155
|
+
return f
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
@dataclass
|
|
160
|
+
class RelationalFingerprint:
|
|
161
|
+
"""Per-table fingerprints plus the relational section (``relational.json``)."""
|
|
162
|
+
|
|
163
|
+
section: RelationalSection
|
|
164
|
+
fingerprints: dict[str, Fingerprint] = field(default_factory=dict)
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def schema(self) -> RelationalSchema:
|
|
168
|
+
return self.section.schema_
|
|
169
|
+
|
|
170
|
+
def save(self, path: str | Path) -> Path:
|
|
171
|
+
from ectype.relational.container import write_relational
|
|
172
|
+
|
|
173
|
+
return write_relational(self, path)
|
|
174
|
+
|
|
175
|
+
@classmethod
|
|
176
|
+
def load(cls, path: str | Path) -> RelationalFingerprint:
|
|
177
|
+
from ectype.relational.container import read_relational
|
|
178
|
+
|
|
179
|
+
return read_relational(path)
|
|
180
|
+
|
|
181
|
+
def __repr__(self) -> str:
|
|
182
|
+
rels = ", ".join(f.relationship.key for f in self.section.relationships)
|
|
183
|
+
return (f"RelationalFingerprint(tables={list(self.fingerprints)}, "
|
|
184
|
+
f"relationships=[{rels}], policy={self.section.disclosure_policy.profile!r})")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---------------------------------------------------------------------------------------------
|
|
188
|
+
# Shared statistics (used by fit and validate)
|
|
189
|
+
# ---------------------------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def rewrite_parent_refs(expression: str) -> str:
|
|
193
|
+
"""``parent.x`` -> ```parent.x``` so the grammar sees one column of the joined frame."""
|
|
194
|
+
return _PARENT_REF.sub(lambda m: f"`parent.{m.group(1)}`", expression)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def child_counts(parent_keys: pl.Series, child_fk: pl.Series) -> np.ndarray:
|
|
198
|
+
"""Number of children per parent row (in parent row order)."""
|
|
199
|
+
vc = child_fk.drop_nulls().value_counts(name="__n__")
|
|
200
|
+
vc.columns = ["__key", "__n"]
|
|
201
|
+
keys = pl.DataFrame({"__key": parent_keys.cast(vc.schema["__key"], strict=False)})
|
|
202
|
+
joined = keys.join(vc, on="__key", how="left", maintain_order="left")
|
|
203
|
+
return joined.get_column("__n").fill_null(0).to_numpy().astype(np.int64)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def child_means(parent_keys: pl.Series, child: pl.DataFrame, fk: str,
|
|
207
|
+
columns: dict[str, ColumnSchema]) -> dict[str, np.ndarray]:
|
|
208
|
+
"""Mean of each numeric child column per parent (NaN for parents without children)."""
|
|
209
|
+
out: dict[str, np.ndarray] = {}
|
|
210
|
+
if not columns or child.height == 0:
|
|
211
|
+
return {c: np.full(parent_keys.len(), np.nan) for c in columns}
|
|
212
|
+
vals = {c: column_to_values(child.get_column(c), s) for c, s in columns.items()}
|
|
213
|
+
frame = pl.DataFrame({"__key": child.get_column(fk), **{f"__v{i}": v for i, v in
|
|
214
|
+
enumerate(vals.values())}})
|
|
215
|
+
frame = frame.with_columns(pl.col(f"__v{i}").fill_nan(None) for i in range(len(vals)))
|
|
216
|
+
agg = frame.group_by("__key").agg(pl.col(f"__v{i}").mean() for i in range(len(vals)))
|
|
217
|
+
keys = pl.DataFrame({"__key": parent_keys.cast(agg.schema["__key"], strict=False)})
|
|
218
|
+
joined = keys.join(agg, on="__key", how="left", maintain_order="left")
|
|
219
|
+
for i, c in enumerate(vals):
|
|
220
|
+
out[c] = joined.get_column(f"__v{i}").cast(pl.Float64).fill_null(np.nan).to_numpy()
|
|
221
|
+
return out
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def _rank(x: np.ndarray) -> np.ndarray:
|
|
225
|
+
from scipy.stats import rankdata
|
|
226
|
+
|
|
227
|
+
return rankdata(x)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def spearman(x: np.ndarray, y: np.ndarray) -> float:
|
|
231
|
+
ok = np.isfinite(x) & np.isfinite(y)
|
|
232
|
+
if ok.sum() < 3:
|
|
233
|
+
return float("nan")
|
|
234
|
+
rx, ry = _rank(x[ok]), _rank(y[ok])
|
|
235
|
+
if rx.std() == 0 or ry.std() == 0:
|
|
236
|
+
return 0.0
|
|
237
|
+
return float(np.corrcoef(rx, ry)[0, 1])
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def correlation_ratio(labels: np.ndarray, y: np.ndarray, min_support: int) -> float:
|
|
241
|
+
"""``eta`` of ``y`` by group; groups smaller than ``min_support`` are pooled together."""
|
|
242
|
+
ok = np.isfinite(y)
|
|
243
|
+
lab, y = np.asarray(labels, dtype=str)[ok], y[ok]
|
|
244
|
+
if y.size < 3 or y.std() == 0:
|
|
245
|
+
return 0.0
|
|
246
|
+
uniq, inv, cnt = np.unique(lab, return_inverse=True, return_counts=True)
|
|
247
|
+
small = cnt[inv] < max(1, min_support)
|
|
248
|
+
inv = np.where(small, -1, inv)
|
|
249
|
+
groups = np.unique(inv)
|
|
250
|
+
mu = y.mean()
|
|
251
|
+
between = sum(((inv == g).sum()) * (y[inv == g].mean() - mu) ** 2 for g in groups)
|
|
252
|
+
total = float(((y - mu) ** 2).sum())
|
|
253
|
+
return float(np.sqrt(max(between, 0.0) / total)) if total > 0 else 0.0
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def association(parent: pl.Series, schema: ColumnSchema, y: np.ndarray,
|
|
257
|
+
policy: DisclosurePolicySpec) -> tuple[str, float]:
|
|
258
|
+
if schema.logical_type in CATEGORY_TYPES:
|
|
259
|
+
labels = parent.cast(pl.String).fill_null("<null>").to_numpy()
|
|
260
|
+
return "eta", correlation_ratio(labels, y, policy.min_category_support)
|
|
261
|
+
return "spearman", spearman(column_to_values(parent, schema), y)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def count_quantiles(counts: np.ndarray, levels: np.ndarray) -> np.ndarray:
|
|
265
|
+
if counts.size == 0:
|
|
266
|
+
return np.zeros_like(levels)
|
|
267
|
+
return np.quantile(counts.astype(float), levels)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _codes(s: pl.Series, schema: ColumnSchema) -> np.ndarray:
|
|
271
|
+
if schema.logical_type in NUMERIC_TYPES:
|
|
272
|
+
v = column_to_values(s, schema)
|
|
273
|
+
out = np.full(v.shape[0], -1, dtype=np.int64)
|
|
274
|
+
ok = np.isfinite(v)
|
|
275
|
+
if ok.any():
|
|
276
|
+
r = _rank(v[ok]) / ok.sum()
|
|
277
|
+
out[ok] = np.minimum((r * _MI_BINS).astype(np.int64), _MI_BINS - 1)
|
|
278
|
+
return out
|
|
279
|
+
_, inv = np.unique(s.cast(pl.String).fill_null("<null>").to_numpy().astype(str),
|
|
280
|
+
return_inverse=True)
|
|
281
|
+
return inv.astype(np.int64)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def mutual_information(x: np.ndarray, y: np.ndarray) -> float:
|
|
285
|
+
"""Plug-in MI (nats) with the Miller-Madow bias correction."""
|
|
286
|
+
n = x.size
|
|
287
|
+
if n == 0:
|
|
288
|
+
return 0.0
|
|
289
|
+
_, xi = np.unique(x, return_inverse=True)
|
|
290
|
+
_, yi = np.unique(y, return_inverse=True)
|
|
291
|
+
kx, ky = int(np.max(xi)) + 1, int(np.max(yi)) + 1
|
|
292
|
+
joint = np.zeros((kx, ky))
|
|
293
|
+
np.add.at(joint, (xi, yi), 1.0)
|
|
294
|
+
p = joint / n
|
|
295
|
+
px, py = p.sum(axis=1, keepdims=True), p.sum(axis=0, keepdims=True)
|
|
296
|
+
nz = p > 0
|
|
297
|
+
mi = float(np.sum(p[nz] * np.log(p[nz] / (px @ py)[nz])))
|
|
298
|
+
return mi - (kx - 1) * (ky - 1) / (2.0 * n)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
# ---------------------------------------------------------------------------------------------
|
|
302
|
+
# Profiler
|
|
303
|
+
# ---------------------------------------------------------------------------------------------
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _merge_overrides(*parts: Mapping[str, Mapping[str, Any]] | None) -> dict[str, dict[str, Any]]:
|
|
307
|
+
out: dict[str, dict[str, Any]] = {}
|
|
308
|
+
for p in parts:
|
|
309
|
+
for k, v in (p or {}).items():
|
|
310
|
+
out.setdefault(k, {}).update(dict(v))
|
|
311
|
+
return out
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
class RelationalProfiler:
|
|
315
|
+
"""Fit a :class:`RelationalFingerprint` from a dict of tables.
|
|
316
|
+
|
|
317
|
+
Parameters
|
|
318
|
+
----------
|
|
319
|
+
schema: the :class:`RelationalSchema` (or a dict accepted by it).
|
|
320
|
+
policy: disclosure policy for every table and for the relational targets.
|
|
321
|
+
seed: fit seed; per-table seeds are derived streams.
|
|
322
|
+
per_table_kwargs: extra :class:`~ectype.profiler.Profiler` arguments per table
|
|
323
|
+
(``overrides`` are merged with the relational key overrides). A table without a
|
|
324
|
+
parent gets the profiler's default joint model; a child table gets
|
|
325
|
+
``joint="gaussian_copula"`` unless named otherwise here, because its rows are drawn
|
|
326
|
+
from the Gaussian conditional given the parent's values.
|
|
327
|
+
k_parent_features: number of parent columns joined onto child rows (default 3).
|
|
328
|
+
cross_constraints: :class:`CrossTableConstraint` objects or dicts
|
|
329
|
+
(``{"child": ..., "expression": "order_day >= parent.signup_day"}``).
|
|
330
|
+
stratify_counts: store per-category child-count quantiles for the categorical parent
|
|
331
|
+
column most associated with the count (``eta >= 0.1``); generation then quantile-maps
|
|
332
|
+
the copula's counts within each category (see ``generate``). A Gaussian copula alone
|
|
333
|
+
attenuates category -> count relations.
|
|
334
|
+
"""
|
|
335
|
+
|
|
336
|
+
def __init__(self, schema: RelationalSchema | Mapping[str, Any],
|
|
337
|
+
policy: str | DisclosurePolicySpec | None = "standard", *, seed: int = 0,
|
|
338
|
+
per_table_kwargs: Mapping[str, Mapping[str, Any]] | None = None,
|
|
339
|
+
k_parent_features: int = 3,
|
|
340
|
+
cross_constraints: Iterable[CrossTableConstraint | Mapping[str, Any]]
|
|
341
|
+
| None = None, stratify_counts: bool = True) -> None:
|
|
342
|
+
self.schema = schema if isinstance(schema, RelationalSchema) \
|
|
343
|
+
else RelationalSchema.model_validate(dict(schema))
|
|
344
|
+
self.policy = resolve_policy(policy)
|
|
345
|
+
self.seed = int(seed)
|
|
346
|
+
self.per_table_kwargs = {k: dict(v) for k, v in (per_table_kwargs or {}).items()}
|
|
347
|
+
unknown = sorted(set(self.per_table_kwargs) - set(self.schema.tables))
|
|
348
|
+
if unknown:
|
|
349
|
+
raise ProfilingError(f"per_table_kwargs for unknown tables {unknown}")
|
|
350
|
+
if k_parent_features < 0:
|
|
351
|
+
raise ValueError("k_parent_features must be >= 0")
|
|
352
|
+
self.k = int(k_parent_features)
|
|
353
|
+
self.stratify_counts = bool(stratify_counts)
|
|
354
|
+
self.cross_constraints: list[CrossTableConstraint] = []
|
|
355
|
+
for i, c in enumerate(cross_constraints or []):
|
|
356
|
+
if isinstance(c, CrossTableConstraint):
|
|
357
|
+
self.cross_constraints.append(c)
|
|
358
|
+
else:
|
|
359
|
+
d = dict(c)
|
|
360
|
+
d.setdefault("id", f"cross_{i + 1}")
|
|
361
|
+
self.cross_constraints.append(CrossTableConstraint.model_validate(d))
|
|
362
|
+
for t in self.schema.tables:
|
|
363
|
+
if len(self.schema.parents_of(t)) > 1:
|
|
364
|
+
raise ProfilingError(f"table {t!r} has several parents; the relational "
|
|
365
|
+
f"generator supports one parent per table")
|
|
366
|
+
for c in self.cross_constraints:
|
|
367
|
+
if not self.schema.parents_of(c.child):
|
|
368
|
+
raise ProfilingError(f"cross-table constraint {c.id!r}: table {c.child!r} has "
|
|
369
|
+
f"no parent")
|
|
370
|
+
|
|
371
|
+
# -----------------------------------------------------------------------------------------
|
|
372
|
+
def _table_seed(self, name: str) -> int:
|
|
373
|
+
return int(stream(self.seed, "relational", "fit", name).integers(0, 2**31 - 1))
|
|
374
|
+
|
|
375
|
+
def _rank_parent_columns(self, rel: Relationship, parent_df: pl.DataFrame,
|
|
376
|
+
parent_fp: Fingerprint, child_df: pl.DataFrame,
|
|
377
|
+
child_cols: list[ColumnSchema]) -> list[ConditioningColumn]:
|
|
378
|
+
if self.k == 0 or not child_cols or child_df.height == 0:
|
|
379
|
+
return []
|
|
380
|
+
pschema = {c.name: c for c in parent_fp.manifest.columns}
|
|
381
|
+
cand = [pschema[c] for c in parent_df.columns
|
|
382
|
+
if c in pschema and pschema[c].role == Role.FEATURE
|
|
383
|
+
and pschema[c].logical_type in MODELED and not c.startswith("__")]
|
|
384
|
+
if not cand:
|
|
385
|
+
return []
|
|
386
|
+
joined = child_df.select(rel.child_fk).join(
|
|
387
|
+
parent_df.select([rel.parent_key] + [c.name for c in cand]),
|
|
388
|
+
left_on=rel.child_fk, right_on=rel.parent_key, how="left", maintain_order="left")
|
|
389
|
+
ycodes = {c.name: _codes(child_df.get_column(c.name), c) for c in child_cols}
|
|
390
|
+
scored = []
|
|
391
|
+
for pc in cand:
|
|
392
|
+
x = _codes(joined.get_column(pc.name), pc)
|
|
393
|
+
mi = max(mutual_information(x, y) for y in ycodes.values())
|
|
394
|
+
scored.append((mi, pc.name))
|
|
395
|
+
scored.sort(key=lambda t: (-t[0], t[1]))
|
|
396
|
+
return [ConditioningColumn(parent_column=n, helper_column=parent_column(n),
|
|
397
|
+
mutual_information=coarsen(float(mi), self.policy))
|
|
398
|
+
for mi, n in scored[: self.k] if mi > 0]
|
|
399
|
+
|
|
400
|
+
def _fit_table(self, name: str, df: pl.DataFrame, overrides: dict[str, dict[str, Any]],
|
|
401
|
+
*, child: bool = False) -> Fingerprint:
|
|
402
|
+
from ectype.profiler import Profiler
|
|
403
|
+
|
|
404
|
+
kw = dict(self.per_table_kwargs.get(name, {}))
|
|
405
|
+
kw["overrides"] = _merge_overrides(overrides, kw.get("overrides"))
|
|
406
|
+
kw.setdefault("name", name)
|
|
407
|
+
if child:
|
|
408
|
+
# A child's rows are drawn conditionally on the generated parent's values, in
|
|
409
|
+
# closed form from a Gaussian copula (relational.generate). Another joint model
|
|
410
|
+
# would only be used through its moment-matched Gaussian approximation, so a
|
|
411
|
+
# child keeps the Gaussian copula unless per_table_kwargs names another.
|
|
412
|
+
kw.setdefault("joint", "gaussian_copula")
|
|
413
|
+
return Profiler(self.policy, seed=self._table_seed(name), **kw).fit(df)
|
|
414
|
+
|
|
415
|
+
def fit(self, tables: Mapping[str, Any]) -> RelationalFingerprint:
|
|
416
|
+
schema = self.schema
|
|
417
|
+
frames = {name: read_table(tables[name]) for name in schema.tables if name in tables}
|
|
418
|
+
schema.check_tables(frames)
|
|
419
|
+
policy = self.policy
|
|
420
|
+
for name, df in frames.items():
|
|
421
|
+
bad = [c for c in df.columns if c.startswith(("__n_", "__parent_"))]
|
|
422
|
+
if bad:
|
|
423
|
+
raise ProfilingError(f"table {name!r} uses reserved helper column names {bad}")
|
|
424
|
+
|
|
425
|
+
# 1. child counts from the source data, added to every parent before it is fitted
|
|
426
|
+
augmented = {n: df for n, df in frames.items()}
|
|
427
|
+
counts: dict[str, np.ndarray] = {}
|
|
428
|
+
for rel in schema.relationships:
|
|
429
|
+
pk = frames[rel.parent].get_column(rel.parent_key)
|
|
430
|
+
n = child_counts(pk, frames[rel.child].get_column(rel.child_fk))
|
|
431
|
+
counts[rel.child] = n
|
|
432
|
+
augmented[rel.parent] = augmented[rel.parent].with_columns(
|
|
433
|
+
pl.Series(count_column(rel.child), n, dtype=pl.Int64))
|
|
434
|
+
|
|
435
|
+
fps: dict[str, Fingerprint] = {}
|
|
436
|
+
infos: dict[str, TableInfo] = {}
|
|
437
|
+
fits: list[RelationshipFit] = []
|
|
438
|
+
notes: list[str] = []
|
|
439
|
+
for name in schema.topological_order():
|
|
440
|
+
src = frames[name]
|
|
441
|
+
df = augmented[name]
|
|
442
|
+
pk_name = schema.tables[name]
|
|
443
|
+
overrides: dict[str, dict[str, Any]] = {pk_name: {"role": Role.IDENTIFIER.value}}
|
|
444
|
+
fks: dict[str, str] = {}
|
|
445
|
+
for rel in schema.parents_of(name):
|
|
446
|
+
overrides[rel.child_fk] = {"role": Role.EXCLUDED.value}
|
|
447
|
+
fks[rel.child_fk] = rel.parent
|
|
448
|
+
count_cols = [count_column(r.child) for r in schema.children_of(name)]
|
|
449
|
+
for cc in count_cols:
|
|
450
|
+
overrides[cc] = {"logical_type": LogicalType.DISCRETE.value,
|
|
451
|
+
"role": Role.FEATURE.value}
|
|
452
|
+
helper_parent: list[str] = []
|
|
453
|
+
rel_fit: RelationshipFit | None = None
|
|
454
|
+
parents = schema.parents_of(name)
|
|
455
|
+
if parents:
|
|
456
|
+
rel = parents[0]
|
|
457
|
+
pfp = fps[rel.parent]
|
|
458
|
+
pdf = augmented[rel.parent]
|
|
459
|
+
own = self._fit_table_probe(name, src, overrides)
|
|
460
|
+
child_feats = [c for c in own if c.role == Role.FEATURE
|
|
461
|
+
and c.logical_type in MODELED]
|
|
462
|
+
cond = self._rank_parent_columns(rel, frames[rel.parent], pfp, src, child_feats)
|
|
463
|
+
if cond:
|
|
464
|
+
joined = src.select(rel.child_fk).join(
|
|
465
|
+
pdf.select([rel.parent_key] + [c.parent_column for c in cond]),
|
|
466
|
+
left_on=rel.child_fk, right_on=rel.parent_key, how="left",
|
|
467
|
+
maintain_order="left")
|
|
468
|
+
pschema = {c.name: c for c in pfp.manifest.columns}
|
|
469
|
+
df = df.with_columns(joined.get_column(c.parent_column)
|
|
470
|
+
.alias(c.helper_column) for c in cond)
|
|
471
|
+
for c in cond:
|
|
472
|
+
overrides[c.helper_column] = {
|
|
473
|
+
"logical_type": pschema[c.parent_column].logical_type.value,
|
|
474
|
+
"role": Role.FEATURE.value}
|
|
475
|
+
helper_parent = [c.helper_column for c in cond]
|
|
476
|
+
rel_fit = self._relationship_fit(rel, frames, counts[name], cond, pfp, own)
|
|
477
|
+
fits.append(rel_fit)
|
|
478
|
+
fp = self._fit_table(name, df, overrides, child=bool(parents))
|
|
479
|
+
fp.manifest.relational = ReservedSection(
|
|
480
|
+
enabled=True, table=name, primary_key=pk_name, foreign_keys=fks,
|
|
481
|
+
count_columns=count_cols, parent_columns=helper_parent)
|
|
482
|
+
fps[name] = fp
|
|
483
|
+
infos[name] = TableInfo(columns=list(src.columns), primary_key=pk_name,
|
|
484
|
+
foreign_keys=fks,
|
|
485
|
+
count_columns=count_cols, parent_columns=helper_parent,
|
|
486
|
+
source_records=src.height, content_hash=fp.content_hash())
|
|
487
|
+
|
|
488
|
+
for xc in self.cross_constraints:
|
|
489
|
+
notes.extend(self._check_cross(xc, frames, fps))
|
|
490
|
+
section = RelationalSection(
|
|
491
|
+
schema=schema, tables={n: infos[n] for n in schema.tables}, relationships=fits,
|
|
492
|
+
cross_constraints=list(self.cross_constraints), disclosure_policy=policy,
|
|
493
|
+
seed=self.seed, notes=notes)
|
|
494
|
+
return RelationalFingerprint(section=section,
|
|
495
|
+
fingerprints={n: fps[n] for n in schema.tables})
|
|
496
|
+
|
|
497
|
+
def _fit_table_probe(self, name: str, df: pl.DataFrame,
|
|
498
|
+
overrides: dict[str, dict[str, Any]]) -> list[ColumnSchema]:
|
|
499
|
+
"""Structural profile of the source child table (to know its modelled columns)."""
|
|
500
|
+
from ectype.profiling.structural import profile_structure
|
|
501
|
+
|
|
502
|
+
kw = self.per_table_kwargs.get(name, {})
|
|
503
|
+
ov = {k: v for k, v in _merge_overrides(overrides, kw.get("overrides")).items()
|
|
504
|
+
if k in df.columns}
|
|
505
|
+
return profile_structure(df, policy=self.policy, overrides=ov or None)
|
|
506
|
+
|
|
507
|
+
def _relationship_fit(self, rel: Relationship, frames: dict[str, pl.DataFrame],
|
|
508
|
+
n: np.ndarray, cond: list[ConditioningColumn], pfp: Fingerprint,
|
|
509
|
+
child_cols: list[ColumnSchema]) -> RelationshipFit:
|
|
510
|
+
policy = self.policy
|
|
511
|
+
parent_df = frames[rel.parent]
|
|
512
|
+
levels = quantile_levels(n.size, policy)
|
|
513
|
+
if levels.size > 21:
|
|
514
|
+
levels = np.linspace(levels[0], levels[-1], 21)
|
|
515
|
+
q = coarsen_array(count_quantiles(n, levels), policy)
|
|
516
|
+
pschema = {c.name: c for c in pfp.manifest.columns}
|
|
517
|
+
numeric_child = {c.name: c for c in child_cols if c.role == Role.FEATURE
|
|
518
|
+
and c.logical_type in NUMERIC_TYPES}
|
|
519
|
+
means = child_means(parent_df.get_column(rel.parent_key), frames[rel.child],
|
|
520
|
+
rel.child_fk, numeric_child)
|
|
521
|
+
assoc: list[AssociationTarget] = []
|
|
522
|
+
if n.size >= 2 * policy.min_category_support:
|
|
523
|
+
feats = [c for c in parent_df.columns if c in pschema
|
|
524
|
+
and pschema[c].role == Role.FEATURE and pschema[c].logical_type in MODELED]
|
|
525
|
+
cond_names = {c.parent_column for c in cond}
|
|
526
|
+
for pc in feats:
|
|
527
|
+
aggs: dict[str, np.ndarray] = {"count": n.astype(float)}
|
|
528
|
+
if pc in cond_names:
|
|
529
|
+
aggs.update({f"mean:{k}": v for k, v in means.items()})
|
|
530
|
+
for agg, y in aggs.items():
|
|
531
|
+
ok = np.isfinite(y)
|
|
532
|
+
if ok.sum() < 2 * policy.min_category_support:
|
|
533
|
+
continue
|
|
534
|
+
metric, val = association(parent_df.get_column(pc), pschema[pc], y, policy)
|
|
535
|
+
if not np.isfinite(val):
|
|
536
|
+
continue
|
|
537
|
+
assoc.append(AssociationTarget(parent_column=pc, aggregate=agg,
|
|
538
|
+
metric=metric, value=coarsen(val, policy),
|
|
539
|
+
n_parents=int(ok.sum())))
|
|
540
|
+
strata = self._count_strata(parent_df, pschema, n) if self.stratify_counts else None
|
|
541
|
+
return RelationshipFit(
|
|
542
|
+
relationship=rel, count_column=count_column(rel.child), conditioning=cond,
|
|
543
|
+
count_strata=strata,
|
|
544
|
+
n_parents=int(n.size), n_children=int(n.sum()),
|
|
545
|
+
count_levels=[float(x) for x in levels], count_quantiles=[float(x) for x in q],
|
|
546
|
+
count_mean=coarsen(float(n.mean()) if n.size else 0.0, policy),
|
|
547
|
+
zero_fraction=coarsen(float((n == 0).mean()) if n.size else 0.0, policy),
|
|
548
|
+
associations=assoc)
|
|
549
|
+
|
|
550
|
+
def _count_strata(self, parent_df: pl.DataFrame, pschema: dict[str, ColumnSchema],
|
|
551
|
+
n: np.ndarray) -> CountStrata | None:
|
|
552
|
+
policy = self.policy
|
|
553
|
+
support = max(1, policy.min_category_support)
|
|
554
|
+
best: tuple[float, str] | None = None
|
|
555
|
+
y = n.astype(float)
|
|
556
|
+
for c in parent_df.columns:
|
|
557
|
+
sc = pschema.get(c)
|
|
558
|
+
if sc is None or sc.role != Role.FEATURE or sc.logical_type not in CATEGORY_TYPES:
|
|
559
|
+
continue
|
|
560
|
+
lab = parent_df.get_column(c).cast(pl.String).fill_null("<null>").to_numpy()
|
|
561
|
+
eta = correlation_ratio(lab, y, support)
|
|
562
|
+
if eta >= STRATA_MIN_ETA and (best is None or eta > best[0]):
|
|
563
|
+
best = (eta, c)
|
|
564
|
+
if best is None:
|
|
565
|
+
return None
|
|
566
|
+
eta, col = best
|
|
567
|
+
lab = strata_labels(parent_df.get_column(col))
|
|
568
|
+
uniq, cnt = np.unique(lab, return_counts=True)
|
|
569
|
+
keep = [str(u) for u, k in zip(uniq, cnt, strict=True) if k >= support and u != OTHER]
|
|
570
|
+
grouped = np.where(np.isin(lab, keep), lab, OTHER)
|
|
571
|
+
labels, levels, quants = [], [], []
|
|
572
|
+
for g in [*keep, OTHER]:
|
|
573
|
+
v = n[grouped == g]
|
|
574
|
+
if v.size < support:
|
|
575
|
+
v = n # the pool is too small: fall back to the marginal counts
|
|
576
|
+
lv = quantile_levels(v.size, policy)
|
|
577
|
+
labels.append(g)
|
|
578
|
+
levels.append([float(x) for x in lv])
|
|
579
|
+
quants.append([float(x) for x in coarsen_array(np.quantile(v.astype(float), lv),
|
|
580
|
+
policy)])
|
|
581
|
+
if len(keep) < 2:
|
|
582
|
+
return None
|
|
583
|
+
return CountStrata(column=col, eta=coarsen(eta, policy), labels=labels, levels=levels,
|
|
584
|
+
quantiles=quants)
|
|
585
|
+
|
|
586
|
+
def _check_cross(self, c: CrossTableConstraint, frames: dict[str, pl.DataFrame],
|
|
587
|
+
fps: dict[str, Fingerprint]) -> list[str]:
|
|
588
|
+
from ectype.fingerprint import expressions
|
|
589
|
+
|
|
590
|
+
rel = self.schema.parents_of(c.child)[0]
|
|
591
|
+
cols = {s.name: s for s in fps[c.child].manifest.columns}
|
|
592
|
+
for s in fps[rel.parent].manifest.columns:
|
|
593
|
+
cols[f"parent.{s.name}"] = s.model_copy(update={"name": f"parent.{s.name}"})
|
|
594
|
+
expressions.check(rewrite_parent_refs(c.expression), cols)
|
|
595
|
+
joined = join_parent(frames[c.child], frames[rel.parent], rel)
|
|
596
|
+
mask = cross_violations(joined, [c])[c.id]
|
|
597
|
+
if mask.any():
|
|
598
|
+
return [f"cross-table constraint {c.id!r} is violated by {mask.mean():.2%} of the "
|
|
599
|
+
f"source {c.child} rows"]
|
|
600
|
+
return []
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def join_parent(child: pl.DataFrame, parent: pl.DataFrame, rel: Relationship) -> pl.DataFrame:
|
|
604
|
+
"""Child rows with every parent column attached as ``parent.<col>``."""
|
|
605
|
+
p = parent.rename({c: f"parent.{c}" for c in parent.columns})
|
|
606
|
+
key = f"parent.{rel.parent_key}"
|
|
607
|
+
fk = child.get_column(rel.child_fk)
|
|
608
|
+
if p.schema[key] != fk.dtype:
|
|
609
|
+
p = p.with_columns(pl.col(key).cast(fk.dtype, strict=False))
|
|
610
|
+
return child.join(p, left_on=rel.child_fk, right_on=key, how="left",
|
|
611
|
+
maintain_order="left").with_columns(fk.alias(key))
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def cross_violations(joined: pl.DataFrame, constraints: list[CrossTableConstraint]
|
|
615
|
+
) -> dict[str, np.ndarray]:
|
|
616
|
+
"""``True`` where a joined row violates the constraint (``null`` counts as satisfied)."""
|
|
617
|
+
from ectype.fingerprint import expressions
|
|
618
|
+
|
|
619
|
+
out = {}
|
|
620
|
+
for c in constraints:
|
|
621
|
+
if joined.height == 0:
|
|
622
|
+
out[c.id] = np.zeros(0, dtype=bool)
|
|
623
|
+
continue
|
|
624
|
+
res = expressions.evaluate(rewrite_parent_refs(c.expression), joined)
|
|
625
|
+
out[c.id] = (res.cast(pl.Boolean) == False).fill_null(False).to_numpy().astype(bool) # noqa: E712
|
|
626
|
+
return out
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
__all__ = ["AssociationTarget", "ConditioningColumn", "CountStrata", "RELATIONAL_FORMAT_VERSION",
|
|
630
|
+
"RelationalFingerprint", "RelationalProfiler", "RelationalSection",
|
|
631
|
+
"RelationshipFit", "TableInfo", "association", "child_counts", "child_means",
|
|
632
|
+
"count_quantiles", "cross_violations", "join_parent", "mutual_information",
|
|
633
|
+
"rewrite_parent_refs"]
|