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/authoring/spec.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
1
|
+
"""Schema-driven authoring (M27): compile a declarative spec into a fingerprint.
|
|
2
|
+
|
|
3
|
+
A spec is a plain dict (YAML-like, but no YAML dependency: parse YAML yourself if you want it)::
|
|
4
|
+
|
|
5
|
+
{
|
|
6
|
+
"name": "customers",
|
|
7
|
+
"columns": [
|
|
8
|
+
{"name": "income", "type": "numeric", "dist": "lognormal", "mu": 10.5, "sigma": 0.6,
|
|
9
|
+
"decimals": 2, "missing": 0.05},
|
|
10
|
+
{"name": "age", "type": "numeric", "dist": "normal", "mean": 41, "sd": 12},
|
|
11
|
+
{"name": "orders", "type": "numeric", "dist": "poisson", "lam": 3},
|
|
12
|
+
{"name": "segment", "type": "categorical", "probs": {"a": 0.5, "b": 0.3, "c": 0.2}},
|
|
13
|
+
{"name": "vip", "type": "boolean", "p": 0.1},
|
|
14
|
+
{"name": "joined", "type": "datetime", "start": "2020-01-01", "end": "2024-12-31"},
|
|
15
|
+
{"name": "customer_id", "type": "identifier", "kind": "int_sequence"}
|
|
16
|
+
],
|
|
17
|
+
"correlations": [{"columns": ["income", "age"], "rho": 0.4}], # or ["a", "b", rho]
|
|
18
|
+
"constraints": ["age >= 18"], # or {"id", "expression"}
|
|
19
|
+
"derived": {"income_k": "income / 1000"}, # or [{"column", ...}]
|
|
20
|
+
"missing": {"age": 0.02},
|
|
21
|
+
"build": {"policy": "standard", "n_reference": 10000, "seed": 0}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
``columns`` may also be a mapping ``{name: entry}``. Numeric distribution parameters can be given
|
|
25
|
+
inline (as above) or under ``"params"``.
|
|
26
|
+
|
|
27
|
+
Semantics
|
|
28
|
+
---------
|
|
29
|
+
* **Marginals** are constructed directly from the registered model classes: ``normal`` (mu,
|
|
30
|
+
sigma; aliases mean, sd/std), ``lognormal`` (mu, sigma, shift=0), ``gamma`` (a/shape, scale,
|
|
31
|
+
loc=0), ``beta`` (a, b, lo=0, hi=1), ``uniform`` (lo/low, hi/high), ``poisson`` (lam/mean) and
|
|
32
|
+
``negbinom`` (r, mu/mean, shift=0). The last two make integer (discrete) columns.
|
|
33
|
+
``datetime`` columns are uniform between ``start`` and ``end`` (dates give a ``Date`` column,
|
|
34
|
+
timestamps a ``Datetime('us')`` column).
|
|
35
|
+
* **Correlations** are rank correlations by default (``method="spearman"``): the latent Gaussian
|
|
36
|
+
copula correlation is ``2 sin(pi rho / 6)``, exact for continuous margins and approximate for
|
|
37
|
+
discrete and categorical ones (for a categorical column, "higher" means a later label in the
|
|
38
|
+
``probs`` order). ``method="latent"`` sets the copula correlation directly. The full latent
|
|
39
|
+
matrix must be positive definite; a contradictory spec fails with an
|
|
40
|
+
:class:`AuthoringError` that names the conflicting pairs.
|
|
41
|
+
* **Encodings and missingness** come from :class:`~ectype.models.encoding.MixedEncoder`
|
|
42
|
+
fitted on a reference sample drawn independently from the marginals (no category reordering
|
|
43
|
+
and no conditional tree, since the reference sample carries no dependence); null rates are
|
|
44
|
+
set exactly to the stated rates.
|
|
45
|
+
* **Targets** (calibration and sealed) are measured on ``n_reference`` rows generated from the
|
|
46
|
+
authored model, so they are the user's stated intentions as realised by the engine
|
|
47
|
+
(``manifest.diagnostics["targets_source"]``).
|
|
48
|
+
* ``provenance.config`` is ``{"mode": "schema_driven", "spec": <the normalised spec>, ...}``.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import datetime as dt
|
|
54
|
+
import hashlib
|
|
55
|
+
import inspect
|
|
56
|
+
import math
|
|
57
|
+
from collections.abc import Mapping
|
|
58
|
+
from typing import Any
|
|
59
|
+
|
|
60
|
+
import numpy as np
|
|
61
|
+
import polars as pl
|
|
62
|
+
|
|
63
|
+
from ectype.errors import ScenarioError
|
|
64
|
+
from ectype.fingerprint.container import canonical_json
|
|
65
|
+
from ectype.fingerprint.core import ArrayStore, Fingerprint
|
|
66
|
+
from ectype.fingerprint.disclosure import resolve_policy
|
|
67
|
+
from ectype.fingerprint.schema import (
|
|
68
|
+
ColumnSchema,
|
|
69
|
+
ConstraintSpec,
|
|
70
|
+
DatasetInfo,
|
|
71
|
+
DerivedSpec,
|
|
72
|
+
Manifest,
|
|
73
|
+
ModelSpec,
|
|
74
|
+
Provenance,
|
|
75
|
+
TargetsSection,
|
|
76
|
+
)
|
|
77
|
+
from ectype.models import marginals as _marginals # noqa: F401 (registers kinds)
|
|
78
|
+
from ectype.models.base import MARGINALS, MarginalModel
|
|
79
|
+
from ectype.models.copulas import GaussianCopula
|
|
80
|
+
from ectype.rng import stream
|
|
81
|
+
from ectype.scenarios.feasibility import explain_not_pd, min_eigenvalue
|
|
82
|
+
from ectype.types import Enforcement, LogicalType, Role, Severity
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class AuthoringError(ScenarioError):
|
|
86
|
+
"""An authored spec is invalid or self-contradictory."""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
#: dist -> (registered kind, parameter names, defaults, aliases, discrete)
|
|
90
|
+
DISTRIBUTIONS: dict[str, tuple[str, tuple[str, ...], dict[str, float], dict[str, str], bool]] = {
|
|
91
|
+
"normal": ("normal", ("mu", "sigma"), {}, {"mean": "mu", "sd": "sigma", "std": "sigma"},
|
|
92
|
+
False),
|
|
93
|
+
"lognormal": ("lognormal", ("shift", "mu", "sigma"), {"shift": 0.0}, {}, False),
|
|
94
|
+
"gamma": ("gamma", ("loc", "a", "scale"), {"loc": 0.0}, {"shape": "a"}, False),
|
|
95
|
+
"beta": ("beta", ("lo", "hi", "a", "b"), {"lo": 0.0, "hi": 1.0}, {}, False),
|
|
96
|
+
"uniform": ("uniform", ("lo", "hi"), {}, {"low": "lo", "high": "hi"}, False),
|
|
97
|
+
"poisson": ("poisson", ("lam",), {}, {"mean": "lam", "lambda": "lam"}, True),
|
|
98
|
+
"negbinom": ("negbinom", ("shift", "r", "mu"), {"shift": 0.0}, {"mean": "mu"}, True),
|
|
99
|
+
}
|
|
100
|
+
_POSITIVE = {"sigma", "scale", "a", "b", "lam", "r"}
|
|
101
|
+
_COLUMN_KEYS = {"name", "type", "dist", "params", "decimals", "missing", "dtype", "probs", "p",
|
|
102
|
+
"start", "end", "kind", "start_value"}
|
|
103
|
+
CORR_METHODS = ("spearman", "latent")
|
|
104
|
+
DEFAULT_N_REFERENCE = 10_000
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# ---------------------------------------------------------------------------------------------
|
|
108
|
+
# normalisation
|
|
109
|
+
# ---------------------------------------------------------------------------------------------
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _num(x: Any, what: str) -> float:
|
|
113
|
+
if isinstance(x, bool):
|
|
114
|
+
raise AuthoringError(f"{what}: expected a number, got {x!r}")
|
|
115
|
+
try:
|
|
116
|
+
v = float(x)
|
|
117
|
+
except (TypeError, ValueError):
|
|
118
|
+
raise AuthoringError(f"{what}: expected a number, got {x!r}") from None
|
|
119
|
+
if not math.isfinite(v):
|
|
120
|
+
raise AuthoringError(f"{what}: must be finite, got {v}")
|
|
121
|
+
return v
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _rate(x: Any, what: str) -> float:
|
|
125
|
+
r = _num(x, what)
|
|
126
|
+
if not 0.0 <= r < 1.0:
|
|
127
|
+
raise AuthoringError(f"{what}: missing rate must be in [0, 1), got {r}")
|
|
128
|
+
return r
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _numeric_params(name: str, dist: str, raw: Mapping[str, Any]) -> dict[str, float]:
|
|
132
|
+
if dist not in DISTRIBUTIONS:
|
|
133
|
+
raise AuthoringError(f"column {name!r}: unknown distribution {dist!r}; choose one of "
|
|
134
|
+
f"{sorted(DISTRIBUTIONS)}")
|
|
135
|
+
_, names, defaults, aliases, discrete = DISTRIBUTIONS[dist]
|
|
136
|
+
params: dict[str, float] = {}
|
|
137
|
+
for k, v in raw.items():
|
|
138
|
+
key = aliases.get(k, k)
|
|
139
|
+
if key not in names:
|
|
140
|
+
raise AuthoringError(f"column {name!r}: {dist} has no parameter {k!r}; parameters "
|
|
141
|
+
f"are {list(names)} (aliases {aliases or 'none'})")
|
|
142
|
+
if key in params:
|
|
143
|
+
raise AuthoringError(f"column {name!r}: parameter {key!r} given twice")
|
|
144
|
+
params[key] = _num(v, f"column {name!r} parameter {k!r}")
|
|
145
|
+
for k, v in defaults.items():
|
|
146
|
+
params.setdefault(k, v)
|
|
147
|
+
missing = [k for k in names if k not in params]
|
|
148
|
+
if missing:
|
|
149
|
+
raise AuthoringError(f"column {name!r}: {dist} needs parameters {missing}")
|
|
150
|
+
for k in names:
|
|
151
|
+
if k in _POSITIVE and params[k] <= 0:
|
|
152
|
+
raise AuthoringError(f"column {name!r}: {dist} parameter {k!r} must be > 0, got "
|
|
153
|
+
f"{params[k]}")
|
|
154
|
+
if "hi" in params and params["hi"] <= params["lo"]:
|
|
155
|
+
raise AuthoringError(f"column {name!r}: {dist} needs hi > lo, got lo={params['lo']}, "
|
|
156
|
+
f"hi={params['hi']}")
|
|
157
|
+
if dist == "negbinom":
|
|
158
|
+
if params["mu"] < 0:
|
|
159
|
+
raise AuthoringError(f"column {name!r}: negbinom mean must be >= 0")
|
|
160
|
+
if params["shift"] != round(params["shift"]):
|
|
161
|
+
raise AuthoringError(f"column {name!r}: negbinom shift must be an integer")
|
|
162
|
+
if discrete and dist == "poisson" and params["lam"] > 1e6:
|
|
163
|
+
raise AuthoringError(f"column {name!r}: poisson lam too large")
|
|
164
|
+
return {k: params[k] for k in names}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _parse_time(x: Any, what: str) -> tuple[float, bool]:
|
|
168
|
+
"""(epoch value, is_date): days for dates, microseconds for datetimes."""
|
|
169
|
+
if isinstance(x, str):
|
|
170
|
+
try:
|
|
171
|
+
x = dt.date.fromisoformat(x) if len(x) == 10 else dt.datetime.fromisoformat(x)
|
|
172
|
+
except ValueError:
|
|
173
|
+
raise AuthoringError(f"{what}: cannot parse {x!r} as an ISO date/datetime") from None
|
|
174
|
+
if isinstance(x, dt.datetime):
|
|
175
|
+
if x.tzinfo is not None:
|
|
176
|
+
x = x.astimezone(dt.UTC).replace(tzinfo=None)
|
|
177
|
+
delta = x - dt.datetime(1970, 1, 1)
|
|
178
|
+
return delta.days * 86_400_000_000 + delta.seconds * 1_000_000 + delta.microseconds, False
|
|
179
|
+
if isinstance(x, dt.date):
|
|
180
|
+
return float((x - dt.date(1970, 1, 1)).days), True
|
|
181
|
+
raise AuthoringError(f"{what}: expected a date, datetime or ISO string, got {x!r}")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _column_entry(name: str, entry: Mapping[str, Any]) -> dict[str, Any]:
|
|
185
|
+
kind = str(entry.get("type", "numeric"))
|
|
186
|
+
out: dict[str, Any] = {"name": name, "type": kind}
|
|
187
|
+
if kind == "numeric":
|
|
188
|
+
dist = str(entry.get("dist", "normal"))
|
|
189
|
+
raw = dict(entry.get("params") or {})
|
|
190
|
+
raw.update({k: v for k, v in entry.items() if k not in _COLUMN_KEYS})
|
|
191
|
+
out["dist"] = dist
|
|
192
|
+
out["params"] = _numeric_params(name, dist, raw)
|
|
193
|
+
if entry.get("decimals") is not None:
|
|
194
|
+
d = int(entry["decimals"])
|
|
195
|
+
if d < 0:
|
|
196
|
+
raise AuthoringError(f"column {name!r}: decimals must be >= 0")
|
|
197
|
+
out["decimals"] = d
|
|
198
|
+
if entry.get("dtype") is not None:
|
|
199
|
+
out["dtype"] = str(entry["dtype"])
|
|
200
|
+
elif kind == "categorical":
|
|
201
|
+
probs = entry.get("probs")
|
|
202
|
+
if not isinstance(probs, Mapping) or not probs:
|
|
203
|
+
raise AuthoringError(f"column {name!r}: categorical needs probs={{label: p}}")
|
|
204
|
+
p = {str(k): _num(v, f"column {name!r} probability of {k!r}") for k, v in probs.items()}
|
|
205
|
+
if any(v < 0 for v in p.values()):
|
|
206
|
+
raise AuthoringError(f"column {name!r}: probabilities must be >= 0")
|
|
207
|
+
total = sum(p.values())
|
|
208
|
+
if total <= 0 or abs(total - 1.0) > 0.01:
|
|
209
|
+
raise AuthoringError(f"column {name!r}: probabilities sum to {total:.6g}, not 1")
|
|
210
|
+
out["probs"] = {k: v / total for k, v in p.items()}
|
|
211
|
+
elif kind == "boolean":
|
|
212
|
+
pv = _num(entry.get("p"), f"column {name!r} p")
|
|
213
|
+
if not 0.0 <= pv <= 1.0:
|
|
214
|
+
raise AuthoringError(f"column {name!r}: p must be in [0, 1], got {pv}")
|
|
215
|
+
out["p"] = pv
|
|
216
|
+
elif kind == "datetime":
|
|
217
|
+
for k in ("start", "end"):
|
|
218
|
+
if entry.get(k) is None:
|
|
219
|
+
raise AuthoringError(f"column {name!r}: datetime needs {k!r}")
|
|
220
|
+
lo, d0 = _parse_time(entry["start"], f"column {name!r} start")
|
|
221
|
+
hi, d1 = _parse_time(entry["end"], f"column {name!r} end")
|
|
222
|
+
if d0 != d1:
|
|
223
|
+
raise AuthoringError(f"column {name!r}: start and end must both be dates or both "
|
|
224
|
+
f"datetimes")
|
|
225
|
+
if hi <= lo:
|
|
226
|
+
raise AuthoringError(f"column {name!r}: end must be after start")
|
|
227
|
+
out["start"] = str(entry["start"])
|
|
228
|
+
out["end"] = str(entry["end"])
|
|
229
|
+
elif kind == "identifier":
|
|
230
|
+
k = str(entry.get("kind", "int_sequence"))
|
|
231
|
+
if k not in ("int_sequence", "uuid4"):
|
|
232
|
+
raise AuthoringError(f"column {name!r}: identifier kind must be int_sequence or "
|
|
233
|
+
f"uuid4")
|
|
234
|
+
out["kind"] = k
|
|
235
|
+
if k == "int_sequence":
|
|
236
|
+
out["start_value"] = int(entry.get("start_value", 1))
|
|
237
|
+
else:
|
|
238
|
+
raise AuthoringError(f"column {name!r}: unknown type {kind!r}; use numeric, "
|
|
239
|
+
f"categorical, boolean, datetime or identifier")
|
|
240
|
+
if entry.get("missing") is not None:
|
|
241
|
+
if kind == "identifier":
|
|
242
|
+
raise AuthoringError(f"column {name!r}: identifiers cannot have missing values")
|
|
243
|
+
out["missing"] = _rate(entry["missing"], f"column {name!r}")
|
|
244
|
+
return out
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def normalize_spec(spec: Mapping[str, Any]) -> dict[str, Any]:
|
|
248
|
+
"""Validate a spec dict and return its canonical (JSON-safe) form."""
|
|
249
|
+
if not isinstance(spec, Mapping):
|
|
250
|
+
raise AuthoringError("spec must be a dict")
|
|
251
|
+
unknown = set(spec) - {"name", "columns", "correlations", "constraints", "derived",
|
|
252
|
+
"missing", "build", "description"}
|
|
253
|
+
if unknown:
|
|
254
|
+
raise AuthoringError(f"unknown spec keys {sorted(unknown)}")
|
|
255
|
+
raw_cols = spec.get("columns")
|
|
256
|
+
if not raw_cols:
|
|
257
|
+
raise AuthoringError("spec has no columns")
|
|
258
|
+
items: list[tuple[str, Mapping[str, Any]]] = []
|
|
259
|
+
if isinstance(raw_cols, Mapping):
|
|
260
|
+
items = [(str(k), v) for k, v in raw_cols.items()]
|
|
261
|
+
else:
|
|
262
|
+
for e in raw_cols:
|
|
263
|
+
if not isinstance(e, Mapping) or "name" not in e:
|
|
264
|
+
raise AuthoringError(f"column entry {e!r} needs a 'name'")
|
|
265
|
+
items.append((str(e["name"]), e))
|
|
266
|
+
columns: list[dict[str, Any]] = []
|
|
267
|
+
names: list[str] = []
|
|
268
|
+
for name, entry in items:
|
|
269
|
+
if name in names:
|
|
270
|
+
raise AuthoringError(f"column {name!r} is declared twice")
|
|
271
|
+
if name.startswith("__"):
|
|
272
|
+
raise AuthoringError(f"column {name!r}: names starting with '__' are reserved")
|
|
273
|
+
columns.append(_column_entry(name, entry))
|
|
274
|
+
names.append(name)
|
|
275
|
+
by_name = {c["name"]: c for c in columns}
|
|
276
|
+
for col, r in dict(spec.get("missing") or {}).items():
|
|
277
|
+
if col not in by_name:
|
|
278
|
+
raise AuthoringError(f"missing: unknown column {col!r}")
|
|
279
|
+
if by_name[col]["type"] == "identifier":
|
|
280
|
+
raise AuthoringError(f"missing: identifier {col!r} cannot have missing values")
|
|
281
|
+
by_name[col]["missing"] = _rate(r, f"missing[{col!r}]")
|
|
282
|
+
|
|
283
|
+
derived: list[dict[str, Any]] = []
|
|
284
|
+
raw_der = spec.get("derived") or []
|
|
285
|
+
if isinstance(raw_der, Mapping):
|
|
286
|
+
raw_der = [{"column": k, "expression": v} for k, v in raw_der.items()]
|
|
287
|
+
for d in raw_der:
|
|
288
|
+
col, expr = str(d["column"]), str(d["expression"])
|
|
289
|
+
if col in by_name or col in [x["column"] for x in derived]:
|
|
290
|
+
raise AuthoringError(f"derived column {col!r} clashes with another column")
|
|
291
|
+
derived.append({"column": col, "expression": expr,
|
|
292
|
+
"dtype": str(d.get("dtype", "Float64")),
|
|
293
|
+
"logical_type": str(d.get("logical_type", "continuous"))})
|
|
294
|
+
|
|
295
|
+
features = {c["name"] for c in columns if c["type"] != "identifier"}
|
|
296
|
+
corrs: list[dict[str, Any]] = []
|
|
297
|
+
seen: dict[frozenset[str], float] = {}
|
|
298
|
+
for c in spec.get("correlations") or []:
|
|
299
|
+
if isinstance(c, Mapping):
|
|
300
|
+
a, b = (str(x) for x in c["columns"])
|
|
301
|
+
rho, method = c["rho"], str(c.get("method", "spearman"))
|
|
302
|
+
else:
|
|
303
|
+
a, b, rho = c[0], c[1], c[2]
|
|
304
|
+
method = str(c[3]) if len(c) > 3 else "spearman"
|
|
305
|
+
a, b = str(a), str(b)
|
|
306
|
+
for x in (a, b):
|
|
307
|
+
if x not in features:
|
|
308
|
+
raise AuthoringError(f"correlation ({a}, {b}): {x!r} is not a modeled column")
|
|
309
|
+
if a == b:
|
|
310
|
+
raise AuthoringError(f"correlation ({a}, {b}): a column cannot be correlated with "
|
|
311
|
+
f"itself")
|
|
312
|
+
if method not in CORR_METHODS:
|
|
313
|
+
raise AuthoringError(f"correlation ({a}, {b}): method must be one of {CORR_METHODS}")
|
|
314
|
+
r = _num(rho, f"correlation ({a}, {b})")
|
|
315
|
+
if not -1.0 < r < 1.0:
|
|
316
|
+
raise AuthoringError(f"correlation ({a}, {b}) = {r}: must lie strictly inside "
|
|
317
|
+
f"(-1, 1)")
|
|
318
|
+
key = frozenset((a, b))
|
|
319
|
+
if key in seen and seen[key] != r:
|
|
320
|
+
raise AuthoringError(f"correlation ({a}, {b}) is given twice with different values "
|
|
321
|
+
f"({seen[key]} and {r})")
|
|
322
|
+
seen[key] = r
|
|
323
|
+
corrs.append({"columns": [a, b], "rho": r, "method": method})
|
|
324
|
+
|
|
325
|
+
constraints: list[dict[str, Any]] = []
|
|
326
|
+
for i, c in enumerate(spec.get("constraints") or []):
|
|
327
|
+
if isinstance(c, str):
|
|
328
|
+
constraints.append({"id": f"user_{i + 1}", "expression": c})
|
|
329
|
+
else:
|
|
330
|
+
d = dict(c)
|
|
331
|
+
d.setdefault("id", f"user_{i + 1}")
|
|
332
|
+
constraints.append({k: (str(v) if k in ("id", "expression") else v)
|
|
333
|
+
for k, v in d.items()})
|
|
334
|
+
out: dict[str, Any] = {"name": str(spec.get("name", "authored")), "columns": columns,
|
|
335
|
+
"correlations": corrs, "constraints": constraints,
|
|
336
|
+
"derived": derived}
|
|
337
|
+
if spec.get("description"):
|
|
338
|
+
out["description"] = str(spec["description"])
|
|
339
|
+
return out
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
# ---------------------------------------------------------------------------------------------
|
|
343
|
+
# compilation
|
|
344
|
+
# ---------------------------------------------------------------------------------------------
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _schema_and_marginal(c: dict[str, Any]) -> tuple[ColumnSchema, MarginalModel | None,
|
|
348
|
+
ModelSpec | None]:
|
|
349
|
+
from ectype.models.marginals import CategoricalMarginal
|
|
350
|
+
|
|
351
|
+
name, kind = c["name"], c["type"]
|
|
352
|
+
rate = float(c.get("missing", 0.0))
|
|
353
|
+
common = {"name": name, "nullable": rate > 0, "null_fraction": rate, "overridden": True,
|
|
354
|
+
"notes": ["schema-driven (authored)"]}
|
|
355
|
+
if kind == "numeric":
|
|
356
|
+
reg_kind, _, _, _, discrete = DISTRIBUTIONS[c["dist"]]
|
|
357
|
+
model = MARGINALS.get(reg_kind)(**c["params"]) # type: ignore[call-arg]
|
|
358
|
+
lt = LogicalType.DISCRETE if discrete else LogicalType.CONTINUOUS
|
|
359
|
+
dtype = c.get("dtype") or ("Int64" if discrete else "Float64")
|
|
360
|
+
lo = float(np.asarray(model.ppf(np.array([1e-9])))[0])
|
|
361
|
+
hi = float(np.asarray(model.ppf(np.array([1 - 1e-9])))[0])
|
|
362
|
+
cs = ColumnSchema(logical_type=lt, physical_dtype=dtype, integer_valued=discrete,
|
|
363
|
+
decimals=c.get("decimals"), min_value=lo, max_value=hi, **common)
|
|
364
|
+
return cs, model, None
|
|
365
|
+
if kind == "categorical":
|
|
366
|
+
labels = np.asarray(list(c["probs"]), dtype=str)
|
|
367
|
+
model = CategoricalMarginal(labels, np.asarray(list(c["probs"].values())))
|
|
368
|
+
cs = ColumnSchema(logical_type=LogicalType.CATEGORICAL, physical_dtype="String",
|
|
369
|
+
n_unique=len(labels), **common)
|
|
370
|
+
return cs, model, None
|
|
371
|
+
if kind == "boolean":
|
|
372
|
+
p = float(c["p"])
|
|
373
|
+
model = CategoricalMarginal(np.array(["False", "True"]), np.array([1.0 - p, p]))
|
|
374
|
+
cs = ColumnSchema(logical_type=LogicalType.BOOLEAN, physical_dtype="Boolean",
|
|
375
|
+
n_unique=2, **common)
|
|
376
|
+
return cs, model, None
|
|
377
|
+
if kind == "datetime":
|
|
378
|
+
from ectype.models.marginals import UniformMarginal
|
|
379
|
+
|
|
380
|
+
lo, is_date = _parse_time(c["start"], name)
|
|
381
|
+
hi, _ = _parse_time(c["end"], name)
|
|
382
|
+
model = UniformMarginal(lo=lo, hi=hi)
|
|
383
|
+
cs = ColumnSchema(logical_type=LogicalType.DATETIME,
|
|
384
|
+
physical_dtype="Date" if is_date else
|
|
385
|
+
"Datetime(time_unit='us', time_zone=None)",
|
|
386
|
+
datetime_unit="d" if is_date else "us", is_date=is_date,
|
|
387
|
+
min_value=lo, max_value=hi, **common)
|
|
388
|
+
return cs, model, None
|
|
389
|
+
# identifier
|
|
390
|
+
if c["kind"] == "int_sequence":
|
|
391
|
+
spec = ModelSpec(kind="int_sequence", params={"start": int(c.get("start_value", 1))})
|
|
392
|
+
cs = ColumnSchema(name=name, logical_type=LogicalType.DISCRETE, role=Role.IDENTIFIER,
|
|
393
|
+
physical_dtype="Int64", integer_valued=True, overridden=True)
|
|
394
|
+
else:
|
|
395
|
+
spec = ModelSpec(kind="uuid4", params={})
|
|
396
|
+
cs = ColumnSchema(name=name, logical_type=LogicalType.STRING, role=Role.IDENTIFIER,
|
|
397
|
+
physical_dtype="String", overridden=True)
|
|
398
|
+
return cs, None, spec
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _reference_sample(features: list[ColumnSchema], marginals: dict[str, MarginalModel],
|
|
402
|
+
n: int, seed: int) -> pl.DataFrame:
|
|
403
|
+
from ectype.io.values import values_to_column
|
|
404
|
+
|
|
405
|
+
series = []
|
|
406
|
+
for cs in features:
|
|
407
|
+
m = marginals[cs.name]
|
|
408
|
+
v = np.asarray(m.ppf(stream(seed, "authoring", "reference", cs.name).random(n)),
|
|
409
|
+
dtype=np.float64)
|
|
410
|
+
k = int(round(cs.null_fraction * n))
|
|
411
|
+
if k:
|
|
412
|
+
idx = stream(seed, "authoring", "nulls", cs.name).permutation(n)[:k]
|
|
413
|
+
v[idx] = np.nan
|
|
414
|
+
labels = getattr(m, "labels", None)
|
|
415
|
+
series.append(values_to_column(v, cs, labels))
|
|
416
|
+
return pl.DataFrame(series)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _fit_encoder(ref: pl.DataFrame, features: list[ColumnSchema],
|
|
420
|
+
marginals: dict[str, MarginalModel], policy: Any, seed: int) -> Any:
|
|
421
|
+
from ectype.models.encoding import MixedEncoder
|
|
422
|
+
|
|
423
|
+
accepted = inspect.signature(MixedEncoder.fit).parameters
|
|
424
|
+
kwargs = {k: False for k in ("order_categories", "conditional") if k in accepted}
|
|
425
|
+
return MixedEncoder.fit(ref, features, marginals, policy, stream(seed, "authoring",
|
|
426
|
+
"encoder"), **kwargs)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _latent_matrix(latent: list[str], corrs: list[dict[str, Any]]) -> np.ndarray:
|
|
430
|
+
from ectype.scenarios.feasibility import spearman_to_latent
|
|
431
|
+
|
|
432
|
+
pos = {c: i for i, c in enumerate(latent)}
|
|
433
|
+
r = np.eye(len(latent))
|
|
434
|
+
for c in corrs:
|
|
435
|
+
a, b = c["columns"]
|
|
436
|
+
v = spearman_to_latent(c["rho"]) if c["method"] == "spearman" else float(c["rho"])
|
|
437
|
+
r[pos[a], pos[b]] = r[pos[b], pos[a]] = v
|
|
438
|
+
return r
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def compile_spec(spec: Mapping[str, Any], *, policy: Any = "standard",
|
|
442
|
+
n_reference: int = DEFAULT_N_REFERENCE, seed: int = 0,
|
|
443
|
+
sealed_fraction: float = 0.3) -> Fingerprint:
|
|
444
|
+
"""Compile a (normalised or raw) spec into a :class:`Fingerprint`."""
|
|
445
|
+
from ectype.fingerprint import expressions
|
|
446
|
+
from ectype.models.encoding import split_specs
|
|
447
|
+
from ectype.scenarios.mutate import retarget, sample_seed, untargeted
|
|
448
|
+
|
|
449
|
+
norm = normalize_spec(spec)
|
|
450
|
+
n_reference = int(n_reference)
|
|
451
|
+
if n_reference < 200:
|
|
452
|
+
raise AuthoringError(f"n_reference must be >= 200, got {n_reference}")
|
|
453
|
+
pol = resolve_policy(policy)
|
|
454
|
+
store = ArrayStore()
|
|
455
|
+
schemas: list[ColumnSchema] = []
|
|
456
|
+
marginals: dict[str, MarginalModel] = {}
|
|
457
|
+
identifiers: dict[str, ModelSpec] = {}
|
|
458
|
+
for c in norm["columns"]:
|
|
459
|
+
cs, model, ident = _schema_and_marginal(c)
|
|
460
|
+
schemas.append(cs)
|
|
461
|
+
if model is not None:
|
|
462
|
+
marginals[cs.name] = model
|
|
463
|
+
if ident is not None:
|
|
464
|
+
identifiers[cs.name] = ident
|
|
465
|
+
for d in norm["derived"]:
|
|
466
|
+
try:
|
|
467
|
+
lt = LogicalType(d["logical_type"])
|
|
468
|
+
except ValueError:
|
|
469
|
+
raise AuthoringError(f"derived column {d['column']!r}: unknown logical type "
|
|
470
|
+
f"{d['logical_type']!r}") from None
|
|
471
|
+
schemas.append(ColumnSchema(name=d["column"], logical_type=lt, role=Role.DERIVED,
|
|
472
|
+
physical_dtype=d["dtype"], overridden=True,
|
|
473
|
+
notes=["schema-driven (authored), derived"]))
|
|
474
|
+
by_name = {c.name: c for c in schemas}
|
|
475
|
+
for d in norm["derived"]:
|
|
476
|
+
try:
|
|
477
|
+
expressions.check(d["expression"], by_name)
|
|
478
|
+
except Exception as exc: # noqa: BLE001
|
|
479
|
+
raise AuthoringError(f"derived column {d['column']!r}: {exc}") from exc
|
|
480
|
+
constraints = []
|
|
481
|
+
for c in norm["constraints"]:
|
|
482
|
+
try:
|
|
483
|
+
expressions.check(c["expression"], by_name)
|
|
484
|
+
except Exception as exc: # noqa: BLE001
|
|
485
|
+
raise AuthoringError(f"constraint {c['id']!r}: {exc}") from exc
|
|
486
|
+
constraints.append(ConstraintSpec.model_validate({
|
|
487
|
+
"severity": Severity.HARD, "enforcement": Enforcement.REJECTION, **c}))
|
|
488
|
+
|
|
489
|
+
features = [s for s in schemas if s.name in marginals]
|
|
490
|
+
ref = _reference_sample(features, marginals, n_reference, seed)
|
|
491
|
+
encoder = _fit_encoder(ref, features, marginals, pol, seed)
|
|
492
|
+
enc_specs, miss_specs = split_specs(encoder.to_specs(store))
|
|
493
|
+
rates = {c["name"]: float(c.get("missing", 0.0)) for c in norm["columns"]}
|
|
494
|
+
for col, s in list(miss_specs.items()):
|
|
495
|
+
miss_specs[col] = s.model_copy(update={"params": {**s.params, "rate": rates[col]}})
|
|
496
|
+
|
|
497
|
+
latent = list(encoder.latent_columns)
|
|
498
|
+
r = _latent_matrix(latent, norm["correlations"])
|
|
499
|
+
if min_eigenvalue(r) < 1e-8:
|
|
500
|
+
stated = {(c["columns"][0], c["columns"][1]): c["rho"] for c in norm["correlations"]}
|
|
501
|
+
raise AuthoringError("contradictory correlation spec: " + explain_not_pd(r, latent,
|
|
502
|
+
stated))
|
|
503
|
+
joint = GaussianCopula(latent, r).to_spec(store, "joint")
|
|
504
|
+
|
|
505
|
+
cfg = {"mode": "schema_driven", "spec": norm, "policy": pol.model_dump(mode="json"),
|
|
506
|
+
"n_reference": n_reference, "seed": int(seed), "sealed_fraction": sealed_fraction}
|
|
507
|
+
manifest = Manifest(
|
|
508
|
+
dataset=DatasetInfo(name=norm["name"], source_records=n_reference,
|
|
509
|
+
source_columns=len(schemas),
|
|
510
|
+
description=norm.get("description") or
|
|
511
|
+
"schema-driven (authored) fingerprint: no source data; "
|
|
512
|
+
"source_records is the reference sample size"),
|
|
513
|
+
columns=schemas,
|
|
514
|
+
disclosure_policy=pol,
|
|
515
|
+
targets=TargetsSection(seal_hash="0" * 64, sealed_fraction=sealed_fraction,
|
|
516
|
+
partition_seed=int(seed)),
|
|
517
|
+
provenance=Provenance(config=cfg,
|
|
518
|
+
config_hash=hashlib.sha256(canonical_json(cfg)).hexdigest(),
|
|
519
|
+
fit_seed=int(seed)),
|
|
520
|
+
)
|
|
521
|
+
msec = manifest.model
|
|
522
|
+
msec.marginals = {name: m.to_spec(store, f"marginal.{name}.")
|
|
523
|
+
for name, m in marginals.items()}
|
|
524
|
+
msec.encodings = enc_specs
|
|
525
|
+
msec.missingness = miss_specs
|
|
526
|
+
msec.joint = joint
|
|
527
|
+
msec.identifiers = identifiers
|
|
528
|
+
msec.derived = [DerivedSpec(column=d["column"], expression=d["expression"])
|
|
529
|
+
for d in norm["derived"]]
|
|
530
|
+
msec.column_order = [s.name for s in schemas]
|
|
531
|
+
manifest.constraints.confirmed = constraints
|
|
532
|
+
draft = untargeted(manifest, store, {"authoring": {"mode": "schema_driven"}})
|
|
533
|
+
try:
|
|
534
|
+
out, _ = retarget(draft, n=n_reference, seed=sample_seed(seed, "authoring"),
|
|
535
|
+
op="schema_driven")
|
|
536
|
+
except AuthoringError:
|
|
537
|
+
raise
|
|
538
|
+
except Exception as exc: # noqa: BLE001
|
|
539
|
+
raise AuthoringError(f"the authored fingerprint cannot generate data: {exc}") from exc
|
|
540
|
+
return out
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def build_from_spec(spec: Mapping[str, Any], **build: Any) -> Fingerprint:
|
|
544
|
+
"""Build a fingerprint from a spec dict. Build options (``policy``, ``n_reference``,
|
|
545
|
+
``seed``, ``sealed_fraction``) come from ``spec["build"]``, overridden by keywords."""
|
|
546
|
+
opts = dict(spec.get("build") or {}) if isinstance(spec, Mapping) else {}
|
|
547
|
+
opts.update(build)
|
|
548
|
+
bad = set(opts) - {"policy", "n_reference", "seed", "sealed_fraction"}
|
|
549
|
+
if bad:
|
|
550
|
+
raise AuthoringError(f"unknown build options {sorted(bad)}")
|
|
551
|
+
return compile_spec({k: v for k, v in spec.items() if k != "build"}, **opts)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
__all__ = ["CORR_METHODS", "DISTRIBUTIONS", "AuthoringError", "build_from_spec",
|
|
555
|
+
"compile_spec", "normalize_spec"]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Post-processing distortion calibration (design §6.2, M25).
|
|
2
|
+
|
|
3
|
+
Importing this package registers the ``"calibrated"`` marginal kind in ``MARGINALS``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from ectype.calibration.adjustments import (
|
|
7
|
+
KIND_CALIBRATED,
|
|
8
|
+
Adjustment,
|
|
9
|
+
CalibratedMarginal,
|
|
10
|
+
)
|
|
11
|
+
from ectype.calibration.calibrator import (
|
|
12
|
+
CalibrationResult,
|
|
13
|
+
IterationRecord,
|
|
14
|
+
TargetEval,
|
|
15
|
+
calibrate,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"KIND_CALIBRATED",
|
|
20
|
+
"Adjustment",
|
|
21
|
+
"CalibratedMarginal",
|
|
22
|
+
"CalibrationResult",
|
|
23
|
+
"IterationRecord",
|
|
24
|
+
"TargetEval",
|
|
25
|
+
"calibrate",
|
|
26
|
+
]
|