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
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""Univariate marginal fitting and model selection (M7).
|
|
2
|
+
|
|
3
|
+
``fit_marginal`` fits each candidate family on a training split, scores it on a held-out split
|
|
4
|
+
(mean log-likelihood minus a BIC-like complexity penalty), and rejects parametric candidates that
|
|
5
|
+
fail a Kolmogorov-Smirnov check, a tail-quantile check or one of the two granularity checks
|
|
6
|
+
(ADR-0007): the number of distinct values a sample of the model would show against the holdout's,
|
|
7
|
+
and the mass the model puts on the holdout's point masses. The best surviving parametric family
|
|
8
|
+
wins. When none survives a non-parametric model is used, the simplest one that passes the
|
|
9
|
+
granularity checks and covers the holdout's range (``_nonparametric_choice``): the finite
|
|
10
|
+
support (``discrete_empirical``) for a discrete column that fits one, otherwise the
|
|
11
|
+
spike-and-slab model (``mixed``) when the column has point masses or a granularity of its own,
|
|
12
|
+
otherwise the policy-limited quantile model (``empirical``).
|
|
13
|
+
The winner is then refitted on all data. On a column with too few rows for a policy-safe quantile
|
|
14
|
+
grid the fallback stores a coarse location/scale summary instead
|
|
15
|
+
(``models.marginals.SummaryMarginal``).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import math
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import polars as pl
|
|
25
|
+
from scipy import stats
|
|
26
|
+
|
|
27
|
+
from ectype.fingerprint.disclosure import pool_categories, quantile_levels, resolve_policy
|
|
28
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
29
|
+
from ectype.io.values import category_labels
|
|
30
|
+
from ectype.models.base import MARGINALS, MarginalModel
|
|
31
|
+
from ectype.models.marginals import (
|
|
32
|
+
ATOM_MIN_COUNT,
|
|
33
|
+
LATTICE_MAX_DECIMALS,
|
|
34
|
+
PARAMETRIC_KINDS,
|
|
35
|
+
CategoricalMarginal,
|
|
36
|
+
is_bounded,
|
|
37
|
+
point_masses,
|
|
38
|
+
)
|
|
39
|
+
from ectype.types import LogicalType
|
|
40
|
+
|
|
41
|
+
__all__ = ["fit_marginal", "fit_categorical", "default_candidates",
|
|
42
|
+
"treat_discrete_as_continuous", "discrete_merge_loss"]
|
|
43
|
+
|
|
44
|
+
#: Below this many held-out rows the KS p-value rule applies; above it the KS statistic rule.
|
|
45
|
+
KS_LARGE_N = 5000
|
|
46
|
+
KS_PVALUE_MIN = 0.01
|
|
47
|
+
KS_STAT_MAX = 0.03
|
|
48
|
+
#: Tail check at q01/q99: the error |model q - holdout q|, relative to the holdout q99 - q01
|
|
49
|
+
#: range, may not exceed TAIL_Z * (sampling s.e. of the holdout quantile), clipped to
|
|
50
|
+
#: [TAIL_REL_ERROR_MIN, TAIL_REL_ERROR_MAX] (the cap keeps heavy tails from excusing big errors).
|
|
51
|
+
TAIL_LEVELS = (0.01, 0.99)
|
|
52
|
+
TAIL_REL_ERROR_MIN = 0.05
|
|
53
|
+
TAIL_REL_ERROR_MAX = 0.2
|
|
54
|
+
TAIL_Z = 4.0
|
|
55
|
+
#: Below this many rows (or held-out rows) selection is skipped and the fallback is used.
|
|
56
|
+
MIN_ROWS_FOR_SELECTION = 50
|
|
57
|
+
MIN_HOLDOUT = 20
|
|
58
|
+
|
|
59
|
+
#: A discrete column with at most this many distinct values always keeps a discrete model.
|
|
60
|
+
DISCRETE_MAX_LEVELS = 50
|
|
61
|
+
#: With more, it is many-valued when a finite support would lose more than this share of its
|
|
62
|
+
#: rows (``discrete_merge_loss``); it then gets continuous families and the mixed model.
|
|
63
|
+
MERGE_LOSS_MAX = 0.05
|
|
64
|
+
#: Distinct-value check: the distinct values expected in a model sample of the holdout's size may
|
|
65
|
+
#: differ from the holdout's count by DISTINCT_REL_TOL of that count, DISTINCT_ABS_TOL of the
|
|
66
|
+
#: rows, or DISTINCT_Z standard errors of the count, whichever is largest.
|
|
67
|
+
DISTINCT_REL_TOL = 0.25
|
|
68
|
+
DISTINCT_ABS_TOL = 0.02
|
|
69
|
+
DISTINCT_Z = 3.0
|
|
70
|
+
#: ... measured on at most this many holdout rows, with this many model quantiles per row
|
|
71
|
+
DISTINCT_MAX_ROWS = 25_000
|
|
72
|
+
DISTINCT_OVERSAMPLE = 4
|
|
73
|
+
#: Point-mass check: on the holdout's point masses (``marginals.point_masses``; the
|
|
74
|
+
#: ATOM_CHECK_TOP most frequent) the model's mass may differ from the holdout share by
|
|
75
|
+
#: ATOM_ABS_TOL or ATOM_Z standard errors of the share, whichever is larger.
|
|
76
|
+
ATOM_CHECK_TOP = 20
|
|
77
|
+
ATOM_ABS_TOL = 0.01
|
|
78
|
+
ATOM_Z = 4.0
|
|
79
|
+
#: Range check: the largest share of the holdout rows that may lie beyond the values the model
|
|
80
|
+
#: can generate (a finite support ends at its largest stored value; a quantile model has tails).
|
|
81
|
+
RANGE_MAX_OUTSIDE = 0.005
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def discrete_merge_loss(x: np.ndarray, min_support: int = 10,
|
|
85
|
+
max_values: int | None = None) -> float:
|
|
86
|
+
"""Share of the rows a finite-support model (``discrete_empirical``) cannot keep at their
|
|
87
|
+
own value: the rows of values seen fewer than ``min_support`` times, plus those of
|
|
88
|
+
well-supported values beyond the ``max_values`` most frequent (the model's cap). These rows
|
|
89
|
+
are merged into a neighbouring value."""
|
|
90
|
+
counts = np.unique(x, return_counts=True)[1]
|
|
91
|
+
kept = np.sort(counts[counts >= min_support])[::-1]
|
|
92
|
+
if max_values is not None:
|
|
93
|
+
kept = kept[:max(int(max_values), 0)]
|
|
94
|
+
return 1.0 - float(kept.sum()) / max(float(counts.sum()), 1.0)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def treat_discrete_as_continuous(x: np.ndarray, min_support: int = 10,
|
|
98
|
+
max_values: int | None = None) -> bool:
|
|
99
|
+
"""Whether a discrete column is many-valued: modeled with continuous families or the mixed
|
|
100
|
+
spike-and-slab model (both rounded on output) instead of a finite support.
|
|
101
|
+
|
|
102
|
+
A finite support can only store values seen at least ``min_support`` times (and at most
|
|
103
|
+
``max_values`` of them); every other row is merged into a neighbouring value. When that
|
|
104
|
+
moves more than ``MERGE_LOSS_MAX`` of the rows (amounts, weights, counts with a long tail)
|
|
105
|
+
the merge collapses the column onto a few values, so it is not used. A heavy point mass
|
|
106
|
+
does not change this: a zero-inflated or heaped amount is many-valued too, and gets the
|
|
107
|
+
mixed model, which keeps the point masses as atoms. Columns whose rows almost all sit on
|
|
108
|
+
well-supported values (codes, ages, zero-inflated gains with a few recurring amounts) keep
|
|
109
|
+
a discrete model, as does any column with at most ``DISCRETE_MAX_LEVELS`` distinct values.
|
|
110
|
+
"""
|
|
111
|
+
if np.unique(x).size <= DISCRETE_MAX_LEVELS:
|
|
112
|
+
return False
|
|
113
|
+
return bool(discrete_merge_loss(x, min_support, max_values) > MERGE_LOSS_MAX)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _has_point_mass(x: np.ndarray, min_support: int) -> bool:
|
|
117
|
+
"""Whether any value is held by enough rows to be an atom of the mixed model."""
|
|
118
|
+
counts = np.unique(x, return_counts=True)[1]
|
|
119
|
+
return bool(np.max(counts) >= max(int(min_support), ATOM_MIN_COUNT))
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _has_decimal_lattice(column: ColumnSchema) -> bool:
|
|
123
|
+
"""Whether the column is recorded to few enough decimals for the mixed model to treat its
|
|
124
|
+
values as a lattice. It can then have a granularity of its own, or rounding levels, without
|
|
125
|
+
any point mass: values recorded to six significant digits have fewer decimals the larger
|
|
126
|
+
they are."""
|
|
127
|
+
if column.integer_valued:
|
|
128
|
+
return True
|
|
129
|
+
return column.decimals is not None and 0 <= int(column.decimals) <= LATTICE_MAX_DECIMALS
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def default_candidates(x: np.ndarray, column: ColumnSchema, min_support: int = 10,
|
|
133
|
+
max_values: int | None = None) -> list[str]:
|
|
134
|
+
lt = column.logical_type
|
|
135
|
+
if lt == LogicalType.DATETIME:
|
|
136
|
+
return ["empirical"]
|
|
137
|
+
if lt in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
|
|
138
|
+
return ["categorical"]
|
|
139
|
+
if lt == LogicalType.DISCRETE and not treat_discrete_as_continuous(x, min_support,
|
|
140
|
+
max_values):
|
|
141
|
+
cands = ["poisson", "negbinom", "discrete_empirical"]
|
|
142
|
+
if np.unique(x).size > DISCRETE_MAX_LEVELS:
|
|
143
|
+
cands.append("mixed") # the alternative when the finite support does not fit
|
|
144
|
+
return cands
|
|
145
|
+
cands = ["normal", "lognormal", "gamma"]
|
|
146
|
+
if is_bounded(x, column):
|
|
147
|
+
cands.append("beta")
|
|
148
|
+
if lt != LogicalType.DISCRETE:
|
|
149
|
+
cands.append("uniform")
|
|
150
|
+
cands.append("empirical")
|
|
151
|
+
if (lt == LogicalType.DISCRETE or _has_point_mass(x, min_support)
|
|
152
|
+
or _has_decimal_lattice(column)):
|
|
153
|
+
cands.append("mixed")
|
|
154
|
+
return cands
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _fallback_kind(column: ColumnSchema) -> str:
|
|
158
|
+
lt = column.logical_type
|
|
159
|
+
if lt == LogicalType.DISCRETE:
|
|
160
|
+
return "discrete_empirical"
|
|
161
|
+
if lt in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
|
|
162
|
+
return "categorical"
|
|
163
|
+
return "empirical"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _output_step(column: ColumnSchema | None) -> float | None:
|
|
167
|
+
"""Resolution the column's codec rounds generated values to (``io.values``): 1 for
|
|
168
|
+
integer-valued and datetime columns, ``10^-decimals`` when a rounding precision was
|
|
169
|
+
detected, else ``None``."""
|
|
170
|
+
if column is None:
|
|
171
|
+
return None
|
|
172
|
+
if column.integer_valued or column.logical_type == LogicalType.DATETIME:
|
|
173
|
+
return 1.0
|
|
174
|
+
if column.decimals is not None and 0 <= int(column.decimals) <= 12:
|
|
175
|
+
return 10.0 ** -int(column.decimals)
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _resolution(model: MarginalModel) -> float:
|
|
180
|
+
"""Spacing of a discrete model's values (1 unless the model has its own granularity)."""
|
|
181
|
+
return float(getattr(model, "granularity", 0.0) or 1.0)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _has_jumps(model: MarginalModel) -> bool:
|
|
185
|
+
return bool(model.discrete or getattr(model, "has_atoms", False))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _tail_check(model: MarginalModel, holdout: np.ndarray) -> tuple[float, float]:
|
|
189
|
+
"""(relative tail error, allowed relative error)."""
|
|
190
|
+
levels = np.asarray(TAIL_LEVELS)
|
|
191
|
+
hq = np.quantile(holdout, levels)
|
|
192
|
+
mq = model.ppf(levels)
|
|
193
|
+
scale = float(hq[1] - hq[0])
|
|
194
|
+
if not scale > 0:
|
|
195
|
+
scale = max(float(np.std(holdout)), 1e-12)
|
|
196
|
+
rel = np.abs(mq - hq) / scale
|
|
197
|
+
# asymptotic s.e. of a sample quantile: sqrt(p(1-p)/n) / f(q), with f from the model
|
|
198
|
+
lp = model.logpdf(mq)
|
|
199
|
+
dens = np.exp(lp) if lp is not None else np.full(levels.size, np.nan)
|
|
200
|
+
if model.discrete:
|
|
201
|
+
dens = dens / _resolution(model) # a mass per step is a density
|
|
202
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
203
|
+
se = np.sqrt(levels * (1 - levels) / holdout.size) / dens / scale
|
|
204
|
+
se = np.where(np.isfinite(se), se, 0.0)
|
|
205
|
+
allowed = np.clip(TAIL_Z * se, TAIL_REL_ERROR_MIN, TAIL_REL_ERROR_MAX)
|
|
206
|
+
if model.discrete:
|
|
207
|
+
allowed = np.maximum(allowed, _resolution(model) / scale) # one unit of resolution
|
|
208
|
+
worst = int(np.argmax(rel / allowed))
|
|
209
|
+
return float(rel[worst]), float(allowed[worst])
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _ks(model: MarginalModel, holdout: np.ndarray) -> tuple[float, float]:
|
|
213
|
+
"""KS statistic and p-value. For models whose CDF jumps (discrete models, point masses) the
|
|
214
|
+
statistic is evaluated on the support (sup |ECDF - F| at the distinct values, both right
|
|
215
|
+
limits and left limits); the asymptotic p-value is then conservative."""
|
|
216
|
+
if not _has_jumps(model):
|
|
217
|
+
r = stats.kstest(holdout, model.cdf)
|
|
218
|
+
return float(r.statistic), float(r.pvalue)
|
|
219
|
+
v = np.sort(holdout)
|
|
220
|
+
u = np.unique(v)
|
|
221
|
+
n = v.size
|
|
222
|
+
ecdf_r = np.searchsorted(v, u, side="right") / n
|
|
223
|
+
ecdf_l = np.searchsorted(v, u, side="left") / n
|
|
224
|
+
d = max(float(np.max(np.abs(ecdf_r - model.cdf(u)))),
|
|
225
|
+
float(np.max(np.abs(ecdf_l - model.cdf_left(u)))))
|
|
226
|
+
return d, float(stats.kstwo.sf(d, n))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _distinct_check(model: MarginalModel, holdout: np.ndarray,
|
|
230
|
+
step: float | None) -> tuple[float, int, float]:
|
|
231
|
+
"""(distinct values expected in a model sample of the holdout's size, distinct values in
|
|
232
|
+
the holdout, allowed difference).
|
|
233
|
+
|
|
234
|
+
The expectation needs no random draw: the model's quantiles at ``DISTINCT_OVERSAMPLE``
|
|
235
|
+
evenly spaced levels per holdout row, rounded like the column's codec rounds (``step``),
|
|
236
|
+
give each value ``v`` a probability ``p_v`` (its share of the levels), and a sample of
|
|
237
|
+
``n`` rows shows ``sum_v 1 - (1 - p_v)^n`` distinct values. A value met at a single level
|
|
238
|
+
counts as continuous mass (every draw from it is new).
|
|
239
|
+
"""
|
|
240
|
+
h = holdout
|
|
241
|
+
if h.size > DISTINCT_MAX_ROWS:
|
|
242
|
+
h = h[np.linspace(0, h.size - 1, DISTINCT_MAX_ROWS).round().astype(np.int64)]
|
|
243
|
+
n = int(h.size)
|
|
244
|
+
observed = int(np.unique(h).size)
|
|
245
|
+
allowed = max(DISTINCT_ABS_TOL * n, DISTINCT_REL_TOL * observed,
|
|
246
|
+
DISTINCT_Z * math.sqrt(observed))
|
|
247
|
+
if observed == n and not _has_jumps(model):
|
|
248
|
+
return float(n), observed, allowed # no ties on either side
|
|
249
|
+
m = DISTINCT_OVERSAMPLE * n
|
|
250
|
+
q = np.asarray(model.ppf((np.arange(m) + 0.5) / m), dtype=np.float64)
|
|
251
|
+
if step:
|
|
252
|
+
q = np.rint(q / step)
|
|
253
|
+
counts = np.unique(q, return_counts=True)[1]
|
|
254
|
+
single = counts == 1
|
|
255
|
+
expected = n * float(single.sum()) / m + float(np.sum(1.0 - (1.0 - counts[~single] / m) ** n))
|
|
256
|
+
return expected, observed, allowed
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _atom_check(model: MarginalModel, holdout: np.ndarray, step: float | None,
|
|
260
|
+
min_support: int) -> tuple[float, float]:
|
|
261
|
+
"""(error, allowed error) of the model's mass on the holdout's point masses, for the value
|
|
262
|
+
where error / allowed is largest. The point masses are those of ``marginals.point_masses``
|
|
263
|
+
(a zero, a heaped round number: a count clearly above its neighbours' on the lattice the
|
|
264
|
+
column's codec rounds to, ``step``; an ordinary value of a smooth count distribution is
|
|
265
|
+
not one), at most the ``ATOM_CHECK_TOP`` most frequent. The model's mass is that of the
|
|
266
|
+
cell the codec rounds to the value, or the jump of its CDF."""
|
|
267
|
+
vals, counts = np.unique(holdout, return_counts=True)
|
|
268
|
+
if vals.size == holdout.size:
|
|
269
|
+
return 0.0, ATOM_ABS_TOL
|
|
270
|
+
idx = None
|
|
271
|
+
if step and float(np.max(np.abs(vals))) / step < 1e15:
|
|
272
|
+
idx = np.rint(vals / step).astype(np.int64)
|
|
273
|
+
sel = np.flatnonzero(point_masses(idx, counts, min_support)[0])
|
|
274
|
+
if sel.size == 0:
|
|
275
|
+
return 0.0, ATOM_ABS_TOL
|
|
276
|
+
sel = sel[np.argsort(-counts[sel], kind="stable")[:ATOM_CHECK_TOP]]
|
|
277
|
+
v, share = vals[sel], counts[sel] / holdout.size
|
|
278
|
+
half = 0.5 * step if step else 0.0
|
|
279
|
+
mass = np.asarray(model.cdf(v + half), dtype=np.float64) \
|
|
280
|
+
- np.asarray(model.cdf_left(v - half), dtype=np.float64)
|
|
281
|
+
allowed = np.maximum(ATOM_ABS_TOL, ATOM_Z * np.sqrt(share * (1 - share) / holdout.size))
|
|
282
|
+
err = np.abs(mass - share)
|
|
283
|
+
worst = int(np.argmax(err / allowed))
|
|
284
|
+
return float(err[worst]), float(allowed[worst])
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _evaluate(model: MarginalModel, kind: str, train_n: int, holdout: np.ndarray,
|
|
288
|
+
column: ColumnSchema | None = None, min_support: int = 10) -> dict[str, Any]:
|
|
289
|
+
n_h = holdout.size
|
|
290
|
+
k = model.n_parameters
|
|
291
|
+
lp = model.logpdf(holdout)
|
|
292
|
+
mean_ll = float(np.mean(lp)) if lp is not None and np.all(np.isfinite(lp)) else -math.inf
|
|
293
|
+
penalty = 0.5 * k * math.log(max(train_n, 2)) / max(train_n, 1)
|
|
294
|
+
ks_stat, ks_p = _ks(model, holdout)
|
|
295
|
+
tail, tail_max = _tail_check(model, holdout)
|
|
296
|
+
parametric = kind in PARAMETRIC_KINDS
|
|
297
|
+
reasons: list[str] = []
|
|
298
|
+
if parametric:
|
|
299
|
+
if not math.isfinite(mean_ll):
|
|
300
|
+
reasons.append("zero likelihood on held-out values (support mismatch)")
|
|
301
|
+
if n_h <= KS_LARGE_N and ks_p < KS_PVALUE_MIN:
|
|
302
|
+
reasons.append(f"KS p-value {ks_p:.3g} < {KS_PVALUE_MIN}")
|
|
303
|
+
if n_h > KS_LARGE_N and ks_stat > KS_STAT_MAX:
|
|
304
|
+
reasons.append(f"KS statistic {ks_stat:.3g} > {KS_STAT_MAX}")
|
|
305
|
+
if tail > tail_max:
|
|
306
|
+
reasons.append(f"tail error {tail:.3g} > {tail_max:.3g}")
|
|
307
|
+
out: dict[str, Any] = {
|
|
308
|
+
"mean_loglik": mean_ll,
|
|
309
|
+
"penalty": penalty,
|
|
310
|
+
"score": mean_ll - penalty,
|
|
311
|
+
"n_parameters": k,
|
|
312
|
+
"ks_statistic": ks_stat,
|
|
313
|
+
"ks_pvalue": ks_p,
|
|
314
|
+
"tail_error": tail,
|
|
315
|
+
"tail_allowed": tail_max,
|
|
316
|
+
}
|
|
317
|
+
if not reasons:
|
|
318
|
+
# the granularity checks (a family already rejected above is not put through them)
|
|
319
|
+
step = _output_step(column)
|
|
320
|
+
d_exp, d_obs, d_allowed = _distinct_check(model, holdout, step)
|
|
321
|
+
atom_err, atom_allowed = _atom_check(model, holdout, step, min_support)
|
|
322
|
+
if parametric and abs(d_exp - d_obs) > d_allowed:
|
|
323
|
+
reasons.append(f"distinct values: {d_exp:.4g} expected in a sample, {d_obs} on "
|
|
324
|
+
f"the holdout (allowed difference {d_allowed:.4g})")
|
|
325
|
+
if parametric and atom_err > atom_allowed:
|
|
326
|
+
reasons.append(f"point-mass error {atom_err:.3g} > {atom_allowed:.3g}")
|
|
327
|
+
outside = _outside_range(model, holdout)
|
|
328
|
+
out.update(distinct_expected=d_exp, distinct_holdout=d_obs, distinct_allowed=d_allowed,
|
|
329
|
+
atom_error=atom_err, atom_allowed=atom_allowed, outside_range=outside,
|
|
330
|
+
# how far the model is from passing these checks (<= 1: it passes them all)
|
|
331
|
+
violation=max(abs(d_exp - d_obs) / d_allowed, atom_err / atom_allowed,
|
|
332
|
+
outside / RANGE_MAX_OUTSIDE))
|
|
333
|
+
out.update(parametric=parametric, passed=not reasons, reject_reasons=reasons)
|
|
334
|
+
return out
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _outside_range(model: MarginalModel, holdout: np.ndarray) -> float:
|
|
338
|
+
"""Share of the holdout rows beyond the values the model can generate (its extreme
|
|
339
|
+
quantiles). Zero for a model with tails; a finite support that stops short of a long tail
|
|
340
|
+
leaves the rows of that tail outside."""
|
|
341
|
+
lo, hi = np.asarray(model.ppf(np.array([0.0, 1.0])), dtype=np.float64)
|
|
342
|
+
return float(np.mean((holdout < lo) | (holdout > hi)))
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _mixed_adds_structure(model: MarginalModel, column: ColumnSchema | None) -> bool:
|
|
346
|
+
"""Whether a fitted ``mixed`` model says more than the quantile model rounded by the
|
|
347
|
+
column's codec would: it stores atoms, rounds to a coarser step than the codec, or mixes
|
|
348
|
+
rounding levels."""
|
|
349
|
+
if model.kind != "mixed":
|
|
350
|
+
return True
|
|
351
|
+
if np.size(getattr(model, "atoms", ())) > 0:
|
|
352
|
+
return True
|
|
353
|
+
step = _output_step(column)
|
|
354
|
+
g = float(getattr(model, "granularity", 0.0))
|
|
355
|
+
if g > 0 and (step is None or g > step * (1.0 + 1e-9)):
|
|
356
|
+
return True
|
|
357
|
+
return bool(np.size(getattr(model, "level_steps", ())) > 1)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _nonparametric_choice(cands: list[str], results: dict[str, dict[str, Any]], fallback: str,
|
|
361
|
+
finite_first: bool) -> tuple[str, str]:
|
|
362
|
+
"""The non-parametric model used when no parametric family passes, and why.
|
|
363
|
+
|
|
364
|
+
The candidates are taken in order of simplicity (a finite support first for a discrete
|
|
365
|
+
column that is not many-valued, else the mixed model, then the plain quantile model) and
|
|
366
|
+
the first that passes three checks on the holdout is used (``violation <= 1`` in
|
|
367
|
+
``_evaluate``): the distinct-value check, the point-mass check, and the range check, which
|
|
368
|
+
a finite support fails when the column has a long tail (it cannot reach beyond its largest
|
|
369
|
+
stored value; the mixed model's slab can). When no candidate passes, the one closest to
|
|
370
|
+
passing is used.
|
|
371
|
+
"""
|
|
372
|
+
order = (["discrete_empirical", "mixed", "empirical"] if finite_first
|
|
373
|
+
else ["mixed", "empirical", "discrete_empirical"])
|
|
374
|
+
usable = [k for k in order if k in cands and k in results
|
|
375
|
+
and math.isfinite(results[k].get("violation", math.inf))]
|
|
376
|
+
names = {"mixed": "mixed spike-and-slab", "discrete_empirical": "empirical",
|
|
377
|
+
"empirical": "empirical"}
|
|
378
|
+
base = "no parametric family passed the fit checks"
|
|
379
|
+
for k in usable:
|
|
380
|
+
if results[k]["violation"] <= 1.0:
|
|
381
|
+
return k, f"{base}; {names[k]} fallback"
|
|
382
|
+
if usable:
|
|
383
|
+
k = min(usable, key=lambda c: results[c]["violation"])
|
|
384
|
+
return k, (f"{base}; {names[k]} fallback (closest to the granularity and range checks "
|
|
385
|
+
f"on the holdout, none passes them)")
|
|
386
|
+
nonparam = [k for k in cands if k not in PARAMETRIC_KINDS]
|
|
387
|
+
kind = fallback if fallback in nonparam else (nonparam[0] if nonparam else fallback)
|
|
388
|
+
return kind, f"{base}; empirical fallback"
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def fit_marginal(x: np.ndarray, column: ColumnSchema, policy: DisclosurePolicySpec | str | None,
|
|
392
|
+
rng: np.random.Generator, *, candidates: list[str] | None = None,
|
|
393
|
+
holdout_fraction: float = 0.2) -> tuple[MarginalModel, dict]:
|
|
394
|
+
"""Select and fit a marginal for the non-null values ``x`` of ``column``.
|
|
395
|
+
|
|
396
|
+
Returns ``(model, diagnostics)``; diagnostics hold per-candidate scores and checks plus the
|
|
397
|
+
reason the winner was chosen.
|
|
398
|
+
"""
|
|
399
|
+
pol = resolve_policy(policy)
|
|
400
|
+
a = np.asarray(x, dtype=np.float64).ravel()
|
|
401
|
+
a = a[np.isfinite(a)]
|
|
402
|
+
if a.size == 0:
|
|
403
|
+
raise ValueError(f"column {column.name!r}: no non-null values to fit")
|
|
404
|
+
k_min = pol.min_category_support
|
|
405
|
+
max_values = len(quantile_levels(a.size, pol))
|
|
406
|
+
discrete = column.logical_type == LogicalType.DISCRETE
|
|
407
|
+
many_valued = discrete and treat_discrete_as_continuous(a, k_min, max_values)
|
|
408
|
+
cands = (list(candidates) if candidates is not None
|
|
409
|
+
else default_candidates(a, column, k_min, max_values))
|
|
410
|
+
fallback = _fallback_kind(column)
|
|
411
|
+
if many_valued:
|
|
412
|
+
fallback = "empirical" # many-level integers: continuous model, rounded on output
|
|
413
|
+
if fallback not in cands and column.logical_type not in (LogicalType.CATEGORICAL,
|
|
414
|
+
LogicalType.BOOLEAN):
|
|
415
|
+
cands.append(fallback)
|
|
416
|
+
diag: dict[str, Any] = {"column": column.name, "n": int(a.size), "candidates": {},
|
|
417
|
+
"fallback": fallback}
|
|
418
|
+
|
|
419
|
+
n_hold = int(round(a.size * holdout_fraction))
|
|
420
|
+
n_unique = np.unique(a).size
|
|
421
|
+
if (a.size < MIN_ROWS_FOR_SELECTION or n_hold < MIN_HOLDOUT or n_unique < 2
|
|
422
|
+
or len(cands) == 1):
|
|
423
|
+
kind = cands[0] if len(cands) == 1 else fallback
|
|
424
|
+
only = MARGINALS.get(kind).fit(a, column=column, policy=pol, rng=rng)
|
|
425
|
+
diag.update(chosen=kind, n_train=int(a.size), n_holdout=0,
|
|
426
|
+
reason=("only candidate" if len(cands) == 1 else
|
|
427
|
+
"too few rows or distinct values for selection; fallback used"))
|
|
428
|
+
return only, _note_summary(only, kind, diag)
|
|
429
|
+
|
|
430
|
+
perm = rng.permutation(a.size)
|
|
431
|
+
hold, train = a[perm[:n_hold]], a[perm[n_hold:]]
|
|
432
|
+
diag.update(n_train=int(train.size), n_holdout=int(hold.size))
|
|
433
|
+
|
|
434
|
+
results: dict[str, dict[str, Any]] = {}
|
|
435
|
+
for kind in cands:
|
|
436
|
+
try:
|
|
437
|
+
m = MARGINALS.get(kind).fit(train, column=column, policy=pol, rng=rng)
|
|
438
|
+
if not _mixed_adds_structure(m, column):
|
|
439
|
+
results[kind] = {"passed": False, "parametric": False, "score": -math.inf,
|
|
440
|
+
"reject_reasons": ["no point masses or granularity beyond "
|
|
441
|
+
"the column's rounding: same as empirical"]}
|
|
442
|
+
continue
|
|
443
|
+
with np.errstate(all="ignore"):
|
|
444
|
+
results[kind] = _evaluate(m, kind, train.size, hold, column, k_min)
|
|
445
|
+
except (ValueError, ArithmeticError, FloatingPointError) as exc:
|
|
446
|
+
results[kind] = {"passed": False, "parametric": kind in PARAMETRIC_KINDS,
|
|
447
|
+
"score": -math.inf, "reject_reasons": [f"fit failed: {exc}"]}
|
|
448
|
+
diag["candidates"] = results
|
|
449
|
+
|
|
450
|
+
passing = sorted((k for k, r in results.items()
|
|
451
|
+
if r["parametric"] and r["passed"] and math.isfinite(r["score"])),
|
|
452
|
+
key=lambda k: -results[k]["score"])
|
|
453
|
+
# A count family must also fit the held-out values at least as well as the observed shares
|
|
454
|
+
# do, with the parameter penalty counted. The KS test has little power on a handful of
|
|
455
|
+
# integer levels, so a family can pass it and still miss the shares a validator measures
|
|
456
|
+
# (two rates mixed in one column, an excess of zeros). Applies when the finite support is
|
|
457
|
+
# itself usable; a long-tailed count keeps its family.
|
|
458
|
+
if discrete and not many_valued:
|
|
459
|
+
shares = results.get("discrete_empirical", {})
|
|
460
|
+
shares_score = shares.get("score", -math.inf)
|
|
461
|
+
if math.isfinite(shares_score) and shares.get("violation", math.inf) <= 1.0:
|
|
462
|
+
for cand in list(passing):
|
|
463
|
+
if results[cand]["score"] < shares_score:
|
|
464
|
+
results[cand]["passed"] = False
|
|
465
|
+
results[cand]["reject_reasons"].append(
|
|
466
|
+
f"held-out fit {results[cand]['score']:.4g} below the observed "
|
|
467
|
+
f"shares' {shares_score:.4g} (parameter penalty included)")
|
|
468
|
+
passing.remove(cand)
|
|
469
|
+
model: MarginalModel | None = None
|
|
470
|
+
kind, reason = fallback, ""
|
|
471
|
+
for rank, cand in enumerate(passing):
|
|
472
|
+
# refit on all data, then re-check the tails in-sample: a heavy-tailed split can let a
|
|
473
|
+
# family pass on the holdout yet miss the full-data q01/q99
|
|
474
|
+
m = MARGINALS.get(cand).fit(a, column=column, policy=pol, rng=rng)
|
|
475
|
+
with np.errstate(all="ignore"):
|
|
476
|
+
tail, allowed = _tail_check(m, a)
|
|
477
|
+
results[cand]["refit_tail_error"] = tail
|
|
478
|
+
if tail > allowed:
|
|
479
|
+
results[cand]["passed"] = False
|
|
480
|
+
results[cand]["reject_reasons"].append(
|
|
481
|
+
f"refit tail error {tail:.3g} > {allowed:.3g} on all data")
|
|
482
|
+
continue
|
|
483
|
+
model, kind = m, cand
|
|
484
|
+
nxt = passing[rank + 1] if rank + 1 < len(passing) else None
|
|
485
|
+
reason = (f"best penalized held-out log-likelihood among parametric candidates passing "
|
|
486
|
+
f"KS and tail checks ({results[cand]['score']:.4g}"
|
|
487
|
+
+ (f"; next {nxt} {results[nxt]['score']:.4g})" if nxt else ")"))
|
|
488
|
+
break
|
|
489
|
+
if model is None:
|
|
490
|
+
kind, reason = _nonparametric_choice(cands, results, fallback,
|
|
491
|
+
discrete and not many_valued)
|
|
492
|
+
model = MARGINALS.get(kind).fit(a, column=column, policy=pol, rng=rng)
|
|
493
|
+
diag.update(chosen=kind, reason=reason)
|
|
494
|
+
if model.kind == "mixed":
|
|
495
|
+
diag.update(atoms=int(np.size(getattr(model, "atoms", ()))),
|
|
496
|
+
granularity=float(getattr(model, "granularity", 0.0)))
|
|
497
|
+
return model, _note_summary(model, kind, diag)
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _note_summary(model: MarginalModel, kind: str, diag: dict[str, Any]) -> dict[str, Any]:
|
|
501
|
+
"""Record when a grid fallback (``empirical`` / ``discrete_empirical``) stored a coarse
|
|
502
|
+
location/scale summary instead because the column has too few rows for a policy-safe
|
|
503
|
+
quantile grid (``disclosure.needs_coarse_summary``)."""
|
|
504
|
+
if model.kind != kind:
|
|
505
|
+
diag["chosen"] = model.kind
|
|
506
|
+
diag["reason"] = (f"{diag.get('reason', '')}; too few rows for a policy-safe {kind} grid, "
|
|
507
|
+
f"stored a coarse location/scale summary")
|
|
508
|
+
return diag
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def fit_categorical(labels: pl.Series, column: ColumnSchema,
|
|
512
|
+
policy: DisclosurePolicySpec | str | None) -> MarginalModel:
|
|
513
|
+
"""Categorical/boolean marginal over codes, matching ``io.values.category_codes``.
|
|
514
|
+
|
|
515
|
+
Booleans use the fixed categories ``["False", "True"]`` (code 0 = False) and are never pooled
|
|
516
|
+
(the labels are the type's domain, not data); a level rarer than ``min_category_support`` is
|
|
517
|
+
stored with that support instead (see ``_boolean_marginal``). Other columns pool labels with support below
|
|
518
|
+
``min_category_support`` into ``"__other__"`` (last); kept labels are ordered by descending
|
|
519
|
+
count, then label. Labels come from ``io.values.category_labels`` (the canonical rule), so
|
|
520
|
+
stored categories match ``io.values.category_codes``.
|
|
521
|
+
"""
|
|
522
|
+
pol = resolve_policy(policy)
|
|
523
|
+
s = labels.drop_nulls()
|
|
524
|
+
if s.dtype.is_float():
|
|
525
|
+
s = s.drop_nans()
|
|
526
|
+
if s.len() == 0:
|
|
527
|
+
raise ValueError(f"column {column.name!r}: no non-null values to fit")
|
|
528
|
+
if s.dtype == pl.Boolean:
|
|
529
|
+
n_true = int(s.sum())
|
|
530
|
+
return _boolean_marginal(np.array(["False", "True"]),
|
|
531
|
+
np.array([s.len() - n_true, n_true]), pol)
|
|
532
|
+
vc = category_labels(s).value_counts(sort=False, name="__n__")
|
|
533
|
+
lab = np.asarray(vc[:, 0].to_list(), dtype=str)
|
|
534
|
+
cnt = np.asarray(vc[:, 1].to_list(), dtype=np.int64)
|
|
535
|
+
if column.logical_type == LogicalType.BOOLEAN:
|
|
536
|
+
order = np.argsort(lab, kind="stable") # e.g. "0" < "1", "false" < "true"
|
|
537
|
+
return _boolean_marginal(lab[order], cnt[order], pol)
|
|
538
|
+
kept, counts, n_pooled = pool_categories(lab, cnt, pol)
|
|
539
|
+
model = CategoricalMarginal.from_counts(kept, counts, pol)
|
|
540
|
+
model.n_pooled = int(n_pooled)
|
|
541
|
+
return model
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def _boolean_marginal(labels: np.ndarray, counts: np.ndarray,
|
|
545
|
+
pol: DisclosurePolicySpec) -> CategoricalMarginal:
|
|
546
|
+
"""Boolean levels are never pooled (they are the type's domain), but a level seen fewer than
|
|
547
|
+
``min_category_support`` times is stored as if it had exactly that support (the rule
|
|
548
|
+
``pool_categories`` applies to the pooled bucket), so a rare flag's exact count - and with it
|
|
549
|
+
the identity of the few flagged rows - is not stored. ``n_pooled`` counts the raised levels."""
|
|
550
|
+
c = np.asarray(counts, dtype=np.int64).copy()
|
|
551
|
+
rare = (c > 0) & (c < pol.min_category_support)
|
|
552
|
+
c[rare] = pol.min_category_support
|
|
553
|
+
model = CategoricalMarginal.from_counts(labels, c, pol)
|
|
554
|
+
model.n_pooled = int(rare.sum())
|
|
555
|
+
return model
|
ectype/py.typed
ADDED
|
File without changes
|
ectype/registry.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Minimal plug-in registries.
|
|
2
|
+
|
|
3
|
+
Each extensible component kind (marginal models, joint models, metrics, enforcers, ...) has a
|
|
4
|
+
``Registry``. Implementations register themselves at import time with ``@REGISTRY.register``.
|
|
5
|
+
Registries map a stable string ``kind`` (stored in fingerprints) to a class, so loading a
|
|
6
|
+
fingerprint never imports arbitrary code: it can only instantiate already-registered kinds.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Callable, Iterator
|
|
12
|
+
from typing import Generic, TypeVar
|
|
13
|
+
|
|
14
|
+
T = TypeVar("T")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Registry(Generic[T]):
|
|
18
|
+
def __init__(self, name: str) -> None:
|
|
19
|
+
self.name = name
|
|
20
|
+
self._items: dict[str, type[T]] = {}
|
|
21
|
+
|
|
22
|
+
def register(self, kind: str | None = None) -> Callable[[type[T]], type[T]]:
|
|
23
|
+
def deco(cls: type[T]) -> type[T]:
|
|
24
|
+
key = kind or getattr(cls, "kind", None)
|
|
25
|
+
if not key:
|
|
26
|
+
raise ValueError(f"{cls!r} has no 'kind' to register under in {self.name}")
|
|
27
|
+
if key in self._items and self._items[key] is not cls:
|
|
28
|
+
raise ValueError(f"duplicate {self.name} kind {key!r}")
|
|
29
|
+
self._items[key] = cls
|
|
30
|
+
return cls
|
|
31
|
+
|
|
32
|
+
return deco
|
|
33
|
+
|
|
34
|
+
def get(self, kind: str) -> type[T]:
|
|
35
|
+
try:
|
|
36
|
+
return self._items[kind]
|
|
37
|
+
except KeyError:
|
|
38
|
+
known = ", ".join(sorted(self._items)) or "<none>"
|
|
39
|
+
raise KeyError(f"unknown {self.name} kind {kind!r}; registered: {known}") from None
|
|
40
|
+
|
|
41
|
+
def __contains__(self, kind: object) -> bool:
|
|
42
|
+
return kind in self._items
|
|
43
|
+
|
|
44
|
+
def __iter__(self) -> Iterator[str]:
|
|
45
|
+
return iter(sorted(self._items))
|
|
46
|
+
|
|
47
|
+
def items(self) -> list[tuple[str, type[T]]]:
|
|
48
|
+
return sorted(self._items.items())
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Multi-table / relational synthesis (M30).
|
|
2
|
+
|
|
3
|
+
Typical use::
|
|
4
|
+
|
|
5
|
+
from ectype.relational import (RelationalSchema, Relationship,
|
|
6
|
+
RelationalProfiler, RelationalGenerator, validate_relational)
|
|
7
|
+
|
|
8
|
+
schema = RelationalSchema(
|
|
9
|
+
tables={"customers": "customer_id", "orders": "order_id"},
|
|
10
|
+
relationships=[Relationship(parent="customers", parent_key="customer_id",
|
|
11
|
+
child="orders", child_fk="customer_id")])
|
|
12
|
+
rfp = RelationalProfiler(schema, policy="standard", seed=0).fit(
|
|
13
|
+
{"customers": customers, "orders": orders})
|
|
14
|
+
rfp.save("shop.dfpr")
|
|
15
|
+
tables = RelationalGenerator(rfp).generate(n_root=1000, seed=42)
|
|
16
|
+
print(validate_relational(rfp, tables).summary())
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import os
|
|
22
|
+
|
|
23
|
+
from ectype.relational.container import read_relational, write_relational
|
|
24
|
+
from ectype.relational.fit import (
|
|
25
|
+
RelationalFingerprint,
|
|
26
|
+
RelationalProfiler,
|
|
27
|
+
RelationalSection,
|
|
28
|
+
)
|
|
29
|
+
from ectype.relational.generate import RelationalGenerator, generate_relational
|
|
30
|
+
from ectype.relational.schema import (
|
|
31
|
+
CrossTableConstraint,
|
|
32
|
+
RelationalSchema,
|
|
33
|
+
Relationship,
|
|
34
|
+
RelationshipSuggestion,
|
|
35
|
+
infer_relationships,
|
|
36
|
+
)
|
|
37
|
+
from ectype.relational.validate import RelationalReport, validate_relational
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load_relational(path: str | os.PathLike[str]) -> RelationalFingerprint:
|
|
41
|
+
"""Load and fully validate a ``.dfpr`` relational fingerprint."""
|
|
42
|
+
return read_relational(path)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
__all__ = [
|
|
46
|
+
"CrossTableConstraint",
|
|
47
|
+
"RelationalFingerprint",
|
|
48
|
+
"RelationalGenerator",
|
|
49
|
+
"RelationalProfiler",
|
|
50
|
+
"RelationalReport",
|
|
51
|
+
"RelationalSchema",
|
|
52
|
+
"RelationalSection",
|
|
53
|
+
"Relationship",
|
|
54
|
+
"RelationshipSuggestion",
|
|
55
|
+
"generate_relational",
|
|
56
|
+
"infer_relationships",
|
|
57
|
+
"load_relational",
|
|
58
|
+
"read_relational",
|
|
59
|
+
"validate_relational",
|
|
60
|
+
"write_relational",
|
|
61
|
+
]
|