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/profiler.py
ADDED
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
"""Fit pipeline: DataFrame -> Fingerprint.
|
|
2
|
+
|
|
3
|
+
structural profile -> pseudonymisation (ADR-0010) -> reference keys become group sizes
|
|
4
|
+
(ADR-0013) -> columns that are a function of another (computed, not modeled; ADR-0011)
|
|
5
|
+
-> totals and their parts (ADR-0014) -> suggested constraints -> structural transforms
|
|
6
|
+
and orderings (working frame, with the shares of the parts of a split in their place) ->
|
|
7
|
+
entity groups (tables of key -> attributes, applied after decoding; ADR-0013) ->
|
|
8
|
+
marginals -> mixed-type encoding -> joint
|
|
9
|
+
model -> calendars (the weekly pattern of date columns, fitted on rows drawn from the
|
|
10
|
+
model; ADR-0012) -> targets (calibration + sealed, on the *source* columns) ->
|
|
11
|
+
diagnostics -> manifest -> Fingerprint.build (commits seal hash)
|
|
12
|
+
|
|
13
|
+
Structural transforms (``profiling.structure``, ADR-0005) model relationships such as
|
|
14
|
+
``end = start + duration`` and ``total = qty * price`` directly: the marginals, encoder and joint
|
|
15
|
+
model are fitted on a working frame in which a hidden ``__delta__<target>`` column replaces each
|
|
16
|
+
``difference`` target and ``identity`` targets are not modeled at all. Targets and validation
|
|
17
|
+
still measure the original columns. An ordering whose gap depends on its base is not modeled as
|
|
18
|
+
a difference (ADR-0009): its target keeps its marginal and the ordering is enforced at
|
|
19
|
+
generation by a truncated redraw (``manifest.model.orderings``).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import hashlib
|
|
25
|
+
import importlib.metadata as md
|
|
26
|
+
from collections.abc import Iterable, Mapping
|
|
27
|
+
from typing import Any
|
|
28
|
+
|
|
29
|
+
import numpy as np
|
|
30
|
+
import polars as pl
|
|
31
|
+
|
|
32
|
+
from ectype._version import __version__
|
|
33
|
+
from ectype.errors import ProfilingError
|
|
34
|
+
from ectype.fingerprint.container import canonical_json
|
|
35
|
+
from ectype.fingerprint.core import ArrayStore, Fingerprint
|
|
36
|
+
from ectype.fingerprint.disclosure import resolve_policy
|
|
37
|
+
from ectype.fingerprint.schema import (
|
|
38
|
+
CalendarSpec,
|
|
39
|
+
ColumnSchema,
|
|
40
|
+
ConstraintSpec,
|
|
41
|
+
DatasetInfo,
|
|
42
|
+
DerivedSpec,
|
|
43
|
+
DisclosureDiagnostics,
|
|
44
|
+
DisclosurePolicySpec,
|
|
45
|
+
Manifest,
|
|
46
|
+
ModelSpec,
|
|
47
|
+
Provenance,
|
|
48
|
+
SuggestedConstraint,
|
|
49
|
+
TargetSet,
|
|
50
|
+
TargetsSection,
|
|
51
|
+
)
|
|
52
|
+
from ectype.io import read_table
|
|
53
|
+
from ectype.io.values import column_to_values
|
|
54
|
+
from ectype.models.base import DEFAULT_JOINT
|
|
55
|
+
from ectype.rng import stream
|
|
56
|
+
from ectype.types import MODELED_ROLES, Enforcement, LogicalType, Role, Severity
|
|
57
|
+
|
|
58
|
+
#: smallest table a fingerprint can be fitted to (statistics need at least two rows)
|
|
59
|
+
MIN_ROWS = 2
|
|
60
|
+
|
|
61
|
+
#: ``Profiler(effort=...)``: how much fitting time to spend, for users who think in time
|
|
62
|
+
#: rather than in model names (ADR-0015). Each level names the joint model that is fitted when
|
|
63
|
+
#: ``joint=`` names none, and the options its fit gets; an explicit ``joint=`` always wins,
|
|
64
|
+
#: and ``joint_options`` override the level's options.
|
|
65
|
+
#:
|
|
66
|
+
#: * ``"fast"``: the Gaussian copula, one correlation matrix. The shortest fit and the
|
|
67
|
+
#: smallest fingerprint, and clearly the least faithful of the three.
|
|
68
|
+
#: * ``"balanced"`` (default): the chain copula within its work budget
|
|
69
|
+
#: (``models.chain.DEFAULT_WORK_BUDGET``): in full on most tables, with its tree search
|
|
70
|
+
#: limited on very wide or tall ones.
|
|
71
|
+
#: * ``"best"``: the chain copula in full, however long a wide table takes.
|
|
72
|
+
EFFORTS: dict[str, tuple[str, dict[str, Any]]] = {
|
|
73
|
+
"fast": ("gaussian_copula", {}),
|
|
74
|
+
"balanced": (DEFAULT_JOINT, {}),
|
|
75
|
+
"best": (DEFAULT_JOINT, {"work_budget": None}),
|
|
76
|
+
}
|
|
77
|
+
DEFAULT_EFFORT = "balanced"
|
|
78
|
+
|
|
79
|
+
MODELED_TYPES = {LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.BOOLEAN,
|
|
80
|
+
LogicalType.CATEGORICAL, LogicalType.DATETIME}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _dependency_versions() -> dict[str, str]:
|
|
84
|
+
out = {}
|
|
85
|
+
for pkg in ("polars", "numpy", "scipy", "pyarrow", "pydantic"):
|
|
86
|
+
try:
|
|
87
|
+
out[pkg] = md.version(pkg)
|
|
88
|
+
except md.PackageNotFoundError:
|
|
89
|
+
pass
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _as_constraints(constraints: Iterable[str | Mapping[str, Any] | ConstraintSpec] | None
|
|
94
|
+
) -> list[ConstraintSpec]:
|
|
95
|
+
out: list[ConstraintSpec] = []
|
|
96
|
+
for i, c in enumerate(constraints or []):
|
|
97
|
+
if isinstance(c, ConstraintSpec):
|
|
98
|
+
out.append(c)
|
|
99
|
+
elif isinstance(c, str):
|
|
100
|
+
out.append(ConstraintSpec(id=f"user_{i + 1}", expression=c,
|
|
101
|
+
severity=Severity.HARD, enforcement=Enforcement.REJECTION))
|
|
102
|
+
else:
|
|
103
|
+
d = dict(c)
|
|
104
|
+
d.setdefault("id", f"user_{i + 1}")
|
|
105
|
+
out.append(ConstraintSpec.model_validate(d))
|
|
106
|
+
return out
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _json_safe(obj: Any) -> Any:
|
|
110
|
+
"""Diagnostics must be strict JSON: non-finite floats become strings, numpy -> python."""
|
|
111
|
+
if isinstance(obj, dict):
|
|
112
|
+
return {str(k): _json_safe(v) for k, v in obj.items()}
|
|
113
|
+
if isinstance(obj, (list, tuple)):
|
|
114
|
+
return [_json_safe(v) for v in obj]
|
|
115
|
+
if isinstance(obj, np.generic):
|
|
116
|
+
obj = obj.item()
|
|
117
|
+
if isinstance(obj, np.ndarray):
|
|
118
|
+
return _json_safe(obj.tolist())
|
|
119
|
+
if isinstance(obj, float) and not np.isfinite(obj):
|
|
120
|
+
return str(obj)
|
|
121
|
+
return obj
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _coerce_mixed_object_columns(data: Any) -> Any:
|
|
125
|
+
"""pandas ``object`` columns holding values of different Python types (``[1, "two", 3.0]``)
|
|
126
|
+
cannot be converted to Arrow; cast those columns to strings (missing values stay missing).
|
|
127
|
+
Anything else is returned unchanged."""
|
|
128
|
+
if type(data).__module__.split(".")[0] != "pandas" or not hasattr(data, "dtypes"):
|
|
129
|
+
return data
|
|
130
|
+
import pandas as pd
|
|
131
|
+
|
|
132
|
+
mixed = []
|
|
133
|
+
for name, dt in data.dtypes.items():
|
|
134
|
+
if str(dt) != "object":
|
|
135
|
+
continue
|
|
136
|
+
kinds = {type(v) for v in data[name] if v is not None and not _is_scalar_na(v)}
|
|
137
|
+
if len(kinds) > 1:
|
|
138
|
+
mixed.append(name)
|
|
139
|
+
if not mixed:
|
|
140
|
+
return data
|
|
141
|
+
out = data.copy()
|
|
142
|
+
for name in mixed:
|
|
143
|
+
out[name] = pd.Series([None if v is None or _is_scalar_na(v) else str(v)
|
|
144
|
+
for v in data[name]], index=data.index, dtype="string")
|
|
145
|
+
return out
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _is_scalar_na(v: Any) -> bool:
|
|
149
|
+
import pandas as pd
|
|
150
|
+
|
|
151
|
+
r = pd.isna(v)
|
|
152
|
+
return isinstance(r, (bool, np.bool_)) and bool(r)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _identifier_spec(df: pl.DataFrame, col: ColumnSchema) -> ModelSpec:
|
|
156
|
+
s = df[col.name].drop_nulls()
|
|
157
|
+
if s.dtype.is_integer() or (s.dtype.is_float() and col.integer_valued):
|
|
158
|
+
return ModelSpec(kind="int_sequence", params={"start": 1})
|
|
159
|
+
sample = s.cast(pl.String).head(1000).to_list()
|
|
160
|
+
lengths = [len(x) for x in sample] or [12]
|
|
161
|
+
if sample and all(len(x) == 36 and x.count("-") == 4 for x in sample[:50]):
|
|
162
|
+
return ModelSpec(kind="uuid4", params={})
|
|
163
|
+
return ModelSpec(kind="string_token", params={
|
|
164
|
+
"length": int(np.median(lengths)),
|
|
165
|
+
"pattern": col.pattern,
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _joint_diagnostics(requested: str, kind: str, model: Any, options: Mapping[str, Any],
|
|
170
|
+
selection: Mapping[str, Any] | None, *, effort: str = DEFAULT_EFFORT,
|
|
171
|
+
named: bool = True) -> dict[str, Any]:
|
|
172
|
+
"""``diagnostics["joint"]``: which joint model was fitted, why that one, and what was
|
|
173
|
+
limited to keep the fit short (the chain copula's work budget, ``models.chain``)."""
|
|
174
|
+
if not named:
|
|
175
|
+
reason = f'effort="{effort}"' + (", the default" if effort == DEFAULT_EFFORT else "")
|
|
176
|
+
elif requested == "auto":
|
|
177
|
+
base = str((selection or {}).get("baseline", DEFAULT_JOINT))
|
|
178
|
+
reason = (f'joint="auto": no candidate clearly beat {base} (the default) on the '
|
|
179
|
+
f"calibration targets and the energy distance" if kind == base else
|
|
180
|
+
f'joint="auto": {kind} was no worse than {base} (the default) on the '
|
|
181
|
+
f"calibration targets and the energy distance, and clearly better on one")
|
|
182
|
+
else:
|
|
183
|
+
reason = "named by joint="
|
|
184
|
+
out: dict[str, Any] = {"requested": requested if named else None, "effort": effort,
|
|
185
|
+
"kind": kind, "reason": reason}
|
|
186
|
+
if options:
|
|
187
|
+
out["options"] = dict(options)
|
|
188
|
+
info = getattr(model, "info", None)
|
|
189
|
+
if kind == "chain_copula" and isinstance(info, Mapping):
|
|
190
|
+
k, rows, source, n_limited = (
|
|
191
|
+
int(info.get(name, 0) or 0)
|
|
192
|
+
for name in ("max_predictors", "fit_rows", "source_rows", "limited_columns"))
|
|
193
|
+
budget = float(info.get("work_budget", 0.0) or 0.0)
|
|
194
|
+
d = len(getattr(model, "columns", []))
|
|
195
|
+
limits: dict[str, Any] = {
|
|
196
|
+
"work_budget": budget, "tree_work": float(info.get("tree_work", 0.0) or 0.0),
|
|
197
|
+
"screen_work": float(info.get("screen_work", 0.0) or 0.0),
|
|
198
|
+
"unlimited_work": float(info.get("unlimited_work", 0.0) or 0.0),
|
|
199
|
+
"max_predictors": k, "limited_columns": n_limited, "fit_rows": rows,
|
|
200
|
+
"source_rows": source, "latent_columns": d}
|
|
201
|
+
said = []
|
|
202
|
+
if k and k < d - 1 and budget:
|
|
203
|
+
# (the budget is applied as the fit goes, so the later columns of the chain are
|
|
204
|
+
# the ones limited, and not all to the same number)
|
|
205
|
+
said.append(f"the trees of {n_limited} of the model's {d} columns chose among "
|
|
206
|
+
f"their best-screened earlier columns (at least {k} each)")
|
|
207
|
+
elif k and k < d - 1:
|
|
208
|
+
said.append(f"each column's trees chose among the {k} best-screened of its up to "
|
|
209
|
+
f"{d - 1} earlier columns")
|
|
210
|
+
if rows and rows < source:
|
|
211
|
+
said.append(f"{rows} of {source} rows were used")
|
|
212
|
+
limits["limited"] = bool(said)
|
|
213
|
+
if said:
|
|
214
|
+
limits["note"] = (
|
|
215
|
+
("to keep the fit within its work budget, " if budget else "as asked, ")
|
|
216
|
+
+ " and ".join(said)
|
|
217
|
+
+ (' (effort="best" fits in full)' if budget else ""))
|
|
218
|
+
out["limits"] = limits
|
|
219
|
+
return out
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class Profiler:
|
|
223
|
+
"""Learn a fingerprint from a source table.
|
|
224
|
+
|
|
225
|
+
Parameters
|
|
226
|
+
----------
|
|
227
|
+
policy: disclosure policy name or spec (mandatory concept; defaults to "standard").
|
|
228
|
+
sealed_fraction: share of pair-level targets withheld from calibration.
|
|
229
|
+
seed: fit seed (randomized PIT, holdout splits, target partition).
|
|
230
|
+
overrides: per-column structural overrides, e.g. ``{"zip": {"logical_type": "categorical"}}``.
|
|
231
|
+
constraints: user-declared hard constraints (expressions or ConstraintSpec/dicts).
|
|
232
|
+
derived: ``{"revenue": "quantity * unit_price"}`` - columns computed, not modeled.
|
|
233
|
+
joint: the model of how columns move together; ``None`` (default) leaves the choice to
|
|
234
|
+
``effort``, which fits ``"chain_copula"`` unless told otherwise.
|
|
235
|
+
``"chain_copula"`` (ADR-0008 and ADR-0015): sequential conditional trees, the closest
|
|
236
|
+
to the source of the built-in models. ``"gaussian_copula"``: one correlation matrix;
|
|
237
|
+
the fastest and smallest, and the only one whose pairwise dependence the calibrator
|
|
238
|
+
and correlation scenarios adjust. ``"forest_copula"``,
|
|
239
|
+
``"gaussian_mixture_copula"``, ``"vine_copula"``, ``"independent"`` (baseline: no
|
|
240
|
+
dependence). ``"auto"``: every candidate is fitted, a sample of ``min(n, 5000)`` rows
|
|
241
|
+
is decoded from each and scored against the calibration targets (never the sealed
|
|
242
|
+
ones) and by its energy distance to the source; the default model is kept unless
|
|
243
|
+
another is no worse on both and clearly better on one
|
|
244
|
+
(``profiling.multivariate.select_joint_by_targets``; scores in
|
|
245
|
+
``diagnostics["marginal_selection"]["__joint_selection__"]``). Auto fits five models
|
|
246
|
+
and takes several times as long as the default.
|
|
247
|
+
Which model was fitted and why, and any limit applied to keep the fit short, is in
|
|
248
|
+
``diagnostics["joint"]``. The chain copula keeps the fit of a wide or tall table
|
|
249
|
+
within a work budget (``models.chain.DEFAULT_WORK_BUDGET``): it counts the work its
|
|
250
|
+
tree search does, and once the columns still to come would exceed the budget their
|
|
251
|
+
trees choose among the best-screened earlier columns only; if even that could not
|
|
252
|
+
fit, fewer rows are used. ``effort="best"`` (or
|
|
253
|
+
``joint_options={"work_budget": None}``) lifts it.
|
|
254
|
+
effort: ``"fast"``, ``"balanced"`` (default) or ``"best"``: how much fitting time to
|
|
255
|
+
spend, when you would rather not choose a model (``EFFORTS``). ``"fast"`` fits the
|
|
256
|
+
Gaussian copula; ``"balanced"`` the chain copula within its work budget; ``"best"``
|
|
257
|
+
the chain copula in full. An explicit ``joint=`` wins over the level's model; the
|
|
258
|
+
work budget follows the level whenever a chain copula is fitted.
|
|
259
|
+
joint_options: keyword options for the joint model's fit, e.g.
|
|
260
|
+
``{"work_budget": None}``, ``{"max_predictors": 32}`` or ``{"n_trees": 3}`` for the
|
|
261
|
+
chain copula. They override what ``effort`` sets. With ``joint="auto"`` they go to
|
|
262
|
+
the candidate of the default kind.
|
|
263
|
+
name: dataset name recorded in the manifest.
|
|
264
|
+
temporal: ``"auto"`` (detect series/panel/events) or a dict with ``time_col``,
|
|
265
|
+
``entity_col`` and ``value_cols``. Adds a temporal section used by
|
|
266
|
+
``ectype.temporal.pipeline.generate_temporal``.
|
|
267
|
+
structure: structural relationship modeling (``profiling.structure``). ``"auto"``
|
|
268
|
+
(default): confirmed hard orderings (``a <= b``) become ``difference`` transforms and
|
|
269
|
+
confirmed identities (``c == a * b``) ``identity`` transforms, and so do suggested
|
|
270
|
+
orderings and identities that are near-certain (no violations, high confidence, and
|
|
271
|
+
``|Spearman| >= 0.3`` for an ordering). A difference is only used when the gap does
|
|
272
|
+
not depend on its base so much that the target would be distorted
|
|
273
|
+
(``profiling.structure.gap_dependence``); an ordering that holds but fails that test
|
|
274
|
+
keeps both columns modeled and is enforced by a truncated redraw of one of them. In
|
|
275
|
+
auto mode an ordering that a few rows break (at most 0.5% of them, or up to 2% when
|
|
276
|
+
the out-of-order rows are isolated; ``profiling.tolerance``, ADR-0015) is modeled as
|
|
277
|
+
a *signed* difference, which reproduces about that share of out-of-order rows;
|
|
278
|
+
confirm the ordering to rule them out. The same rule decides whether a computed
|
|
279
|
+
column, a sum or an entity group holds despite a few dirty rows; those are generated
|
|
280
|
+
without the exceptions, and the share found is in the column's notes.
|
|
281
|
+
``"confirmed"``: confirmed constraints only.
|
|
282
|
+
``"off"``: none (every column modeled separately, constraints enforced by rejection
|
|
283
|
+
only). Auto mode acts on the profiler's suggestions, so with
|
|
284
|
+
``suggest_constraints=False`` it behaves like ``"confirmed"``. What was applied and
|
|
285
|
+
why is recorded in ``manifest.diagnostics["structure"]``.
|
|
286
|
+
In ``"auto"`` mode a column that is a pure function of one other column (a weekday
|
|
287
|
+
name, a calendar or fiscal year, a band; ``profiling.functional``, ADR-0011) is not
|
|
288
|
+
modeled either: the function is written to ``manifest.model.derived`` and the column is
|
|
289
|
+
computed from the generated value of its base (``manifest.diagnostics["functions"]``).
|
|
290
|
+
In the other modes only the columns you declare with ``derived=`` are computed. (This
|
|
291
|
+
detection does not use the suggestions: it also runs with ``suggest_constraints=False``.)
|
|
292
|
+
In ``"auto"`` mode a date column (or a column of day numbers) whose rows are clearly
|
|
293
|
+
not spread evenly over the week also gets a *calendar* (``profiling.calendar``,
|
|
294
|
+
ADR-0012): after decoding, generated rows are moved by whole days so that the column
|
|
295
|
+
has the source's share of rows per weekday, and same-day ties and the order between
|
|
296
|
+
related dates stay as generated (``manifest.model.calendars``,
|
|
297
|
+
``manifest.diagnostics["calendars"]``). The other modes leave generated dates smooth
|
|
298
|
+
over the week.
|
|
299
|
+
In ``"auto"`` mode *entity groups* are detected too (``profiling.entity``, ADR-0013):
|
|
300
|
+
when every value of a categorical key column has one value of another column (the
|
|
301
|
+
bank's city and registration number on every loan of that bank), that column is an
|
|
302
|
+
attribute of the key. Every column is modeled as before, and a generated row then
|
|
303
|
+
takes its attributes from its key, so an entity carries the same attributes on every
|
|
304
|
+
row (``manifest.model.entities``, ``manifest.diagnostics["entities"]``). ``"off"``
|
|
305
|
+
leaves the columns as the model generates them.
|
|
306
|
+
In ``"auto"`` mode totals and their parts are found as well (``profiling.sums``,
|
|
307
|
+
ADR-0014): a total and the columns that add up to it, several partitions of one total,
|
|
308
|
+
nested totals, a subtotal of lines that can be negative, columns that add up to 100 or
|
|
309
|
+
to 1. One side of each adopted sum is computed after decoding, so the sum holds on
|
|
310
|
+
every generated row: the parts from the total and a modeled composition (their own
|
|
311
|
+
decoded values scaled to it or, with ``joint="chain_copula"`` and parts that are small
|
|
312
|
+
counts, their shares of it), in whole units, or the total from its parts
|
|
313
|
+
(``manifest.model.sums``, ``manifest.diagnostics["sums"]``). A sum you
|
|
314
|
+
declare as a hard constraint (``"total == a + b + c"``, ``"a + b == 100"``) is
|
|
315
|
+
computed in ``"confirmed"`` mode too; ``"off"`` computes none.
|
|
316
|
+
entities: entity groups you declare, ``{"bank_name": ["bank_city", "bank_state"]}``: a key
|
|
317
|
+
column and its attribute columns. Declared groups are used as stated with
|
|
318
|
+
``structure="auto"`` and ``"confirmed"`` (which detects none itself); they need one of
|
|
319
|
+
the two.
|
|
320
|
+
"""
|
|
321
|
+
|
|
322
|
+
def __init__(self, policy: str | DisclosurePolicySpec | None = "standard", *,
|
|
323
|
+
sealed_fraction: float = 0.3, seed: int = 0,
|
|
324
|
+
overrides: dict[str, dict[str, Any]] | None = None,
|
|
325
|
+
constraints: Iterable[str | Mapping[str, Any] | ConstraintSpec] | None = None,
|
|
326
|
+
derived: Mapping[str, str] | None = None,
|
|
327
|
+
joint: str | None = None, name: str = "dataset",
|
|
328
|
+
max_pairs: int = 200, suggest_constraints: bool = True,
|
|
329
|
+
temporal: str | Mapping[str, Any] | None = None,
|
|
330
|
+
structure: str = "auto",
|
|
331
|
+
entities: Mapping[str, Iterable[str]] | None = None,
|
|
332
|
+
joint_options: Mapping[str, Any] | None = None,
|
|
333
|
+
effort: str = DEFAULT_EFFORT) -> None:
|
|
334
|
+
from ectype.profiling.structure import MODES
|
|
335
|
+
|
|
336
|
+
if structure not in MODES:
|
|
337
|
+
raise ValueError(f"structure must be one of {list(MODES)}, got {structure!r}")
|
|
338
|
+
if entities and structure == "off":
|
|
339
|
+
raise ValueError("entities= declares entity groups, which structure='off' "
|
|
340
|
+
"disables; use structure='confirmed' or 'auto'")
|
|
341
|
+
self.entities = {str(k): [str(a) for a in v] for k, v in (entities or {}).items()}
|
|
342
|
+
self.policy = resolve_policy(policy)
|
|
343
|
+
self.sealed_fraction = sealed_fraction
|
|
344
|
+
self.seed = int(seed)
|
|
345
|
+
self.overrides = dict(overrides or {})
|
|
346
|
+
self.constraints = _as_constraints(constraints)
|
|
347
|
+
self.derived = dict(derived or {})
|
|
348
|
+
if effort not in EFFORTS:
|
|
349
|
+
raise ValueError(f"effort must be one of {list(EFFORTS)}, got {effort!r}")
|
|
350
|
+
self.effort = effort
|
|
351
|
+
#: the joint model that is fitted: the one named, else the effort level's
|
|
352
|
+
self.joint = str(joint) if joint is not None else EFFORTS[effort][0]
|
|
353
|
+
self.joint_named = joint is not None
|
|
354
|
+
self.joint_options = dict(joint_options or {})
|
|
355
|
+
self.name = name
|
|
356
|
+
self.max_pairs = max_pairs
|
|
357
|
+
self.suggest_constraints = suggest_constraints
|
|
358
|
+
self.temporal = temporal
|
|
359
|
+
self.structure = structure
|
|
360
|
+
|
|
361
|
+
def config(self) -> dict[str, Any]:
|
|
362
|
+
return {
|
|
363
|
+
"policy": self.policy.model_dump(mode="json"),
|
|
364
|
+
"sealed_fraction": self.sealed_fraction,
|
|
365
|
+
"seed": self.seed,
|
|
366
|
+
"overrides": self.overrides,
|
|
367
|
+
"constraints": [c.model_dump(mode="json") for c in self.constraints],
|
|
368
|
+
"derived": self.derived,
|
|
369
|
+
"joint": self.joint,
|
|
370
|
+
"effort": self.effort,
|
|
371
|
+
"joint_options": self.joint_options,
|
|
372
|
+
"max_pairs": self.max_pairs,
|
|
373
|
+
"suggest_constraints": self.suggest_constraints,
|
|
374
|
+
"temporal": self.temporal if not isinstance(self.temporal, Mapping)
|
|
375
|
+
else dict(self.temporal),
|
|
376
|
+
"structure": self.structure,
|
|
377
|
+
"entities": self.entities,
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
# ---------------------------------------------------------------------------------------
|
|
381
|
+
def fit(self, data: Any) -> Fingerprint:
|
|
382
|
+
from ectype.fingerprint import expressions
|
|
383
|
+
from ectype.fingerprint.targets import build_targets
|
|
384
|
+
from ectype.models import ( # noqa: F401 (registers)
|
|
385
|
+
chain,
|
|
386
|
+
copulas,
|
|
387
|
+
forest,
|
|
388
|
+
mixtures,
|
|
389
|
+
vines,
|
|
390
|
+
)
|
|
391
|
+
from ectype.models import marginals as _register_marginals # noqa: F401
|
|
392
|
+
from ectype.models.base import JOINTS
|
|
393
|
+
from ectype.models.encoding import MixedEncoder, split_specs
|
|
394
|
+
from ectype.profiling.bivariate import association_matrix
|
|
395
|
+
from ectype.profiling.structural import (
|
|
396
|
+
NUMERIC_PATTERNS,
|
|
397
|
+
parse_numeric_strings,
|
|
398
|
+
profile_structure,
|
|
399
|
+
)
|
|
400
|
+
from ectype.profiling.univariate import fit_categorical, fit_marginal
|
|
401
|
+
|
|
402
|
+
df = read_table(_coerce_mixed_object_columns(data))
|
|
403
|
+
if df.height == 0 or df.width == 0:
|
|
404
|
+
raise ProfilingError("cannot fit a fingerprint to an empty table")
|
|
405
|
+
if df.height < MIN_ROWS:
|
|
406
|
+
raise ProfilingError(f"cannot fit a fingerprint to a table with {df.height} row(s); "
|
|
407
|
+
f"at least {MIN_ROWS} rows are needed")
|
|
408
|
+
# Float NaN is a missing value everywhere (schema, marginals, encoder, targets).
|
|
409
|
+
floats = [c for c, dt in df.schema.items() if dt.is_float()]
|
|
410
|
+
if floats:
|
|
411
|
+
df = df.with_columns(pl.col(floats).fill_nan(None))
|
|
412
|
+
policy = self.policy
|
|
413
|
+
|
|
414
|
+
overrides = dict(self.overrides)
|
|
415
|
+
for col in self.derived:
|
|
416
|
+
if col in df.columns:
|
|
417
|
+
overrides.setdefault(col, {})["role"] = Role.DERIVED.value
|
|
418
|
+
# (the temporal pipeline has entity keys of its own: no reference keys by default)
|
|
419
|
+
columns = profile_structure(df, policy=policy, overrides=overrides or None,
|
|
420
|
+
references=not self.temporal)
|
|
421
|
+
# Pseudonym columns (ADR-0010): their labels become stand-in tokens here, before
|
|
422
|
+
# anything is fitted, so no later stage sees (or can store) a source label.
|
|
423
|
+
from ectype.profiling.pseudonym import pseudonymise
|
|
424
|
+
df, columns, pseudonyms = pseudonymise(df, columns, policy, self.seed)
|
|
425
|
+
# Reference keys (ADR-0013): each key becomes the number of rows that share it, here,
|
|
426
|
+
# so the model, the targets and the diagnostics never see (or store) a key value.
|
|
427
|
+
from ectype.profiling.reference import rewrite_references
|
|
428
|
+
df, columns, references = rewrite_references(df, columns, policy, self.seed)
|
|
429
|
+
by_name = {c.name: c for c in columns}
|
|
430
|
+
# Numeric strings ("12.5", "N/A", "40%") are modeled as numbers: parse them once here
|
|
431
|
+
# so every later stage (marginals, encoder, targets, constraints) sees the numbers.
|
|
432
|
+
parsed = [parse_numeric_strings(df[c.name], c.pattern) for c in columns
|
|
433
|
+
if c.pattern in NUMERIC_PATTERNS and df[c.name].dtype == pl.String]
|
|
434
|
+
if parsed:
|
|
435
|
+
df = df.with_columns(parsed)
|
|
436
|
+
|
|
437
|
+
# Validate expressions against the schema before any heavy work.
|
|
438
|
+
for expr in self.derived.values():
|
|
439
|
+
expressions.check(expr, by_name)
|
|
440
|
+
for cons in self.constraints:
|
|
441
|
+
expressions.check(cons.expression, by_name)
|
|
442
|
+
|
|
443
|
+
# Columns that are a pure function of another column (a weekday, a year, a band) are
|
|
444
|
+
# computed from the generated value of that column, not modeled (ADR-0011). They stay
|
|
445
|
+
# features of the table (their targets are measured) with the function in their notes.
|
|
446
|
+
functions: dict[str, str] = {}
|
|
447
|
+
functions_diag: dict[str, Any] | None = None
|
|
448
|
+
if self.structure == "auto":
|
|
449
|
+
from ectype.profiling.functional import detect_functions
|
|
450
|
+
found, functions_diag = detect_functions(df, columns, policy,
|
|
451
|
+
exclude=[*self.derived, *references])
|
|
452
|
+
functions = {f.column: f.expression for f in found}
|
|
453
|
+
notes = {f.column: f.note(policy) for f in found}
|
|
454
|
+
columns = [c.model_copy(update={"notes": [*c.notes, notes[c.name]]})
|
|
455
|
+
if c.name in notes else c for c in columns]
|
|
456
|
+
by_name = {c.name: c for c in columns}
|
|
457
|
+
|
|
458
|
+
features = [c for c in columns
|
|
459
|
+
if c.role in MODELED_ROLES and c.logical_type in MODELED_TYPES
|
|
460
|
+
and c.name not in functions]
|
|
461
|
+
# Totals and their parts (ADR-0014): the columns a sum computes are not modeled; the
|
|
462
|
+
# parts of a split are replaced by their hidden shares in the working frame below.
|
|
463
|
+
from ectype.profiling.sums import (
|
|
464
|
+
computed_columns,
|
|
465
|
+
plan_sums,
|
|
466
|
+
scaled_columns,
|
|
467
|
+
share_schemas,
|
|
468
|
+
sums_working,
|
|
469
|
+
)
|
|
470
|
+
# (auto starts from the default joint model, so its working frame is that model's)
|
|
471
|
+
sums, sums_diag = plan_sums(df, columns, policy, self.constraints, mode=self.structure,
|
|
472
|
+
exclude=[*self.derived, *functions], seed=self.seed,
|
|
473
|
+
joint=DEFAULT_JOINT if self.joint == "auto" else self.joint)
|
|
474
|
+
summed = {*computed_columns(sums), *scaled_columns(sums)}
|
|
475
|
+
# (the share of source rows that break an adopted sum goes into the columns' notes)
|
|
476
|
+
sum_notes = sums_diag.pop("notes", {})
|
|
477
|
+
if sum_notes:
|
|
478
|
+
columns = [c.model_copy(update={"notes": [*c.notes, sum_notes[c.name]]})
|
|
479
|
+
if c.name in sum_notes else c for c in columns]
|
|
480
|
+
by_name = {c.name: c for c in columns}
|
|
481
|
+
# Date columns whose rows are not spread evenly over the week (ADR-0012). Detected
|
|
482
|
+
# here, on the source; their kernels are fitted below, on rows drawn from the model.
|
|
483
|
+
weekly: dict[str, np.ndarray] = {}
|
|
484
|
+
calendars_diag: dict[str, Any] | None = None
|
|
485
|
+
if self.structure == "auto":
|
|
486
|
+
from ectype.profiling.calendar import detect_calendars
|
|
487
|
+
weekly, calendars_diag = detect_calendars(
|
|
488
|
+
df, [c for c in features if c.name not in summed], policy)
|
|
489
|
+
calendars: list[CalendarSpec] = []
|
|
490
|
+
|
|
491
|
+
# Suggestions first: auto-mode structure acts on them (the screening itself is the
|
|
492
|
+
# same as before, on the same frame).
|
|
493
|
+
suggestions: list[SuggestedConstraint] = []
|
|
494
|
+
if self.suggest_constraints:
|
|
495
|
+
from ectype.profiling.constraints import suggest_constraints
|
|
496
|
+
suggestions = suggest_constraints(df, columns, policy, seed=self.seed)
|
|
497
|
+
# Structural transforms and the working frame the models are fitted on: each
|
|
498
|
+
# difference target is replaced by its hidden latent, identity targets are derived.
|
|
499
|
+
from ectype.profiling.structure import (
|
|
500
|
+
StructuredEncoder,
|
|
501
|
+
latent_schema,
|
|
502
|
+
plan_structure,
|
|
503
|
+
working_frame,
|
|
504
|
+
)
|
|
505
|
+
# (a computed column takes no part in a transform or an ordering)
|
|
506
|
+
plannable = [c.model_copy(update={"role": Role.DERIVED})
|
|
507
|
+
if c.name in functions or c.name in summed else c for c in columns]
|
|
508
|
+
structure = plan_structure(
|
|
509
|
+
df, plannable, policy, self.constraints,
|
|
510
|
+
suggestions if self.suggest_constraints else None, mode=self.structure,
|
|
511
|
+
seed=self.seed)
|
|
512
|
+
transforms, orderings = structure.transforms, structure.orderings
|
|
513
|
+
structure_diag = structure.diagnostics
|
|
514
|
+
if structure.notes: # orderings modeled with their out-of-order rows
|
|
515
|
+
columns = [c.model_copy(update={"notes": [*c.notes, structure.notes[c.name]]})
|
|
516
|
+
if c.name in structure.notes else c for c in columns]
|
|
517
|
+
by_name = {c.name: c for c in columns}
|
|
518
|
+
# Entity groups (ADR-0013): a column that is an attribute of a key column is read
|
|
519
|
+
# from the key after decoding. Columns with a structure of their own stay out.
|
|
520
|
+
from ectype.profiling.entity import plan_entities
|
|
521
|
+
from ectype.profiling.sums import sum_columns
|
|
522
|
+
busy = {*functions, *references, *weekly, *self.derived, *sum_columns(sums),
|
|
523
|
+
*(c for t in transforms for c in (t.target, *t.inputs)),
|
|
524
|
+
*(c for o in orderings for c in (o.target, *o.lower, *o.upper))}
|
|
525
|
+
entity_plan = plan_entities(df, columns, policy, mode=self.structure,
|
|
526
|
+
declared=self.entities, exclude=sorted(busy),
|
|
527
|
+
seed=self.seed)
|
|
528
|
+
if entity_plan:
|
|
529
|
+
columns = entity_plan.annotate(columns)
|
|
530
|
+
by_name = {c.name: c for c in columns}
|
|
531
|
+
working = sums_working(working_frame(df, features, transforms, policy, seed=self.seed),
|
|
532
|
+
df, sums, by_name, seed=self.seed)
|
|
533
|
+
work, modeled = working.frame, working.columns
|
|
534
|
+
hidden = {**{latent_schema(t).name: latent_schema(t)
|
|
535
|
+
for t in transforms if t.kind == "difference"}, **share_schemas(sums)}
|
|
536
|
+
for rec in structure_diag["applied"]:
|
|
537
|
+
if working.clamped.get(rec.get("target", "")):
|
|
538
|
+
rec["clamped_rows"] = working.clamped[rec["target"]]
|
|
539
|
+
|
|
540
|
+
store = ArrayStore()
|
|
541
|
+
manifest_model_marginals: dict[str, ModelSpec] = {}
|
|
542
|
+
marginals = {}
|
|
543
|
+
fit_diags: dict[str, Any] = {}
|
|
544
|
+
pooled: dict[str, int] = {}
|
|
545
|
+
for c in modeled:
|
|
546
|
+
rng = stream(self.seed, "marginal", c.name)
|
|
547
|
+
if c.logical_type in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
|
|
548
|
+
model = fit_categorical(work[c.name], c, policy)
|
|
549
|
+
diag: dict[str, Any] = {"kind": model.kind}
|
|
550
|
+
n_pooled = int(getattr(model, "n_pooled", 0) or 0)
|
|
551
|
+
if n_pooled:
|
|
552
|
+
pooled[c.name] = n_pooled
|
|
553
|
+
else:
|
|
554
|
+
x = column_to_values(work[c.name], c)
|
|
555
|
+
x = x[~np.isnan(x)]
|
|
556
|
+
if x.size == 0:
|
|
557
|
+
raise ProfilingError(f"column {c.name!r} has no non-null values to model")
|
|
558
|
+
model, diag = fit_marginal(x, c, policy, rng)
|
|
559
|
+
marginals[c.name] = model
|
|
560
|
+
manifest_model_marginals[c.name] = model.to_spec(store, f"marginal.{c.name}")
|
|
561
|
+
fit_diags[c.name] = diag
|
|
562
|
+
|
|
563
|
+
manifest_encodings: dict[str, ModelSpec] = {}
|
|
564
|
+
manifest_missing: dict[str, ModelSpec] = {}
|
|
565
|
+
joint_spec = None
|
|
566
|
+
joint_diag_out: dict[str, Any] | None = None
|
|
567
|
+
calibration: TargetSet | None = None
|
|
568
|
+
sealed: TargetSet | None = None
|
|
569
|
+
if modeled:
|
|
570
|
+
feat_df = working.encoded.select([c.name for c in modeled])
|
|
571
|
+
encoder = MixedEncoder.fit(feat_df, modeled, marginals, policy,
|
|
572
|
+
stream(self.seed, "encoder"))
|
|
573
|
+
z = encoder.encode(feat_df, stream(self.seed, "encode"))
|
|
574
|
+
gauss_kwargs: dict[str, Any] = {"attenuation": encoder.latent_attenuation}
|
|
575
|
+
if encoder.latent_hermite is not None:
|
|
576
|
+
gauss_kwargs["hermite"] = encoder.latent_hermite
|
|
577
|
+
# the chain copula models tied values as atoms of the encoder's intervals, and
|
|
578
|
+
# rows that copy another column through the marginals' quantile functions
|
|
579
|
+
chain_kwargs: dict[str, Any] = {"atoms": encoder.latent_atoms,
|
|
580
|
+
"values": encoder.latent_values}
|
|
581
|
+
# the effort level's options for a chain copula (its work budget), then the
|
|
582
|
+
# caller's own for the model that is fitted
|
|
583
|
+
level_joint, level_options = EFFORTS[self.effort]
|
|
584
|
+
if level_joint == "chain_copula":
|
|
585
|
+
chain_kwargs.update(level_options)
|
|
586
|
+
options_for = DEFAULT_JOINT if self.joint == "auto" else self.joint
|
|
587
|
+
if options_for == "chain_copula":
|
|
588
|
+
chain_kwargs.update(self.joint_options)
|
|
589
|
+
elif options_for in ("gaussian_copula", "forest_copula"):
|
|
590
|
+
gauss_kwargs = {**gauss_kwargs, **self.joint_options}
|
|
591
|
+
if self.joint == "auto":
|
|
592
|
+
# Choose by generated-data fidelity to the calibration targets (never the
|
|
593
|
+
# sealed ones); see profiling.multivariate.select_joint_by_targets. Samples
|
|
594
|
+
# are scored in the source columns: transform targets are recomputed.
|
|
595
|
+
from ectype.profiling.multivariate import select_joint_by_targets
|
|
596
|
+
calibration, sealed = build_targets(
|
|
597
|
+
df, columns, policy, seed=self.seed,
|
|
598
|
+
sealed_fraction=self.sealed_fraction, max_pairs=self.max_pairs)
|
|
599
|
+
decode: Any = encoder.decode
|
|
600
|
+
reference = feat_df
|
|
601
|
+
view: Any = encoder
|
|
602
|
+
if transforms or orderings or sums:
|
|
603
|
+
view = StructuredEncoder(encoder, transforms, {**by_name, **hidden},
|
|
604
|
+
orderings, sums=sums)
|
|
605
|
+
decode = view.decode
|
|
606
|
+
reference = df.select([c.name for c in features])
|
|
607
|
+
if entity_plan:
|
|
608
|
+
decode = entity_plan.view(view).decode
|
|
609
|
+
if functions:
|
|
610
|
+
# the calibration targets on computed columns need those columns
|
|
611
|
+
computed = [expressions.to_polars(e, by_name).alias(col)
|
|
612
|
+
for col, e in functions.items()]
|
|
613
|
+
|
|
614
|
+
def decode(z: Any, rng: Any = None, _inner: Any = decode) -> pl.DataFrame:
|
|
615
|
+
out: pl.DataFrame = _inner(z, rng)
|
|
616
|
+
for expr in computed:
|
|
617
|
+
out = out.with_columns(expr)
|
|
618
|
+
return out
|
|
619
|
+
joint_kind, joint, joint_diag = select_joint_by_targets(
|
|
620
|
+
z, list(encoder.latent_columns), decode,
|
|
621
|
+
list(calibration.targets), by_name, seed=self.seed, policy=policy,
|
|
622
|
+
reference=reference, fit_rng=lambda _kind: stream(self.seed, "joint"),
|
|
623
|
+
fit_kwargs={"gaussian_copula": gauss_kwargs,
|
|
624
|
+
"chain_copula": chain_kwargs})
|
|
625
|
+
fit_diags["__joint_selection__"] = {"chosen": joint_kind, **dict(joint_diag)}
|
|
626
|
+
else:
|
|
627
|
+
joint_cls = JOINTS.get(self.joint)
|
|
628
|
+
joint_kwargs = (gauss_kwargs if self.joint in ("gaussian_copula", "forest_copula")
|
|
629
|
+
else chain_kwargs if self.joint == "chain_copula"
|
|
630
|
+
else dict(self.joint_options))
|
|
631
|
+
joint = joint_cls.fit(z, list(encoder.latent_columns), policy=policy,
|
|
632
|
+
rng=stream(self.seed, "joint"), **joint_kwargs)
|
|
633
|
+
joint_kind = self.joint
|
|
634
|
+
joint_diag_out = _joint_diagnostics(self.joint, joint_kind, joint,
|
|
635
|
+
self.joint_options,
|
|
636
|
+
fit_diags.get("__joint_selection__"),
|
|
637
|
+
effort=self.effort, named=self.joint_named)
|
|
638
|
+
if weekly and calendars_diag is not None:
|
|
639
|
+
from ectype.profiling.calendar import SIM_ROWS, fit_calendars, plan_calendars
|
|
640
|
+
cal_plan = plan_calendars(list(weekly), transforms, orderings,
|
|
641
|
+
[c.name for c in features])
|
|
642
|
+
sampler: Any = encoder
|
|
643
|
+
if transforms or orderings or sums:
|
|
644
|
+
sampler = StructuredEncoder(encoder, transforms, {**by_name, **hidden},
|
|
645
|
+
orderings, sums=sums)
|
|
646
|
+
zs = np.asarray(joint.sample(SIM_ROWS, stream(self.seed, "calendar", "joint")),
|
|
647
|
+
dtype=np.float64)
|
|
648
|
+
if list(joint.columns) != list(encoder.latent_columns):
|
|
649
|
+
at = {c: j for j, c in enumerate(joint.columns)}
|
|
650
|
+
zs = zs[:, [at[c] for c in encoder.latent_columns]]
|
|
651
|
+
zs = zs[np.isfinite(zs).all(axis=1)]
|
|
652
|
+
calendars, fitted = fit_calendars(
|
|
653
|
+
sampler.decode(zs), cal_plan, weekly, by_name, policy,
|
|
654
|
+
stream(self.seed, "calendar", "fit"))
|
|
655
|
+
planned = {c.column for c in calendars}
|
|
656
|
+
for rec in calendars_diag["applied"]:
|
|
657
|
+
rec.update(fitted.get(rec["column"], {}))
|
|
658
|
+
if rec["column"] not in planned:
|
|
659
|
+
calendars_diag["not_selected"].append({
|
|
660
|
+
**rec, "reason": "part of an identity transform: the value is a "
|
|
661
|
+
"formula of other columns and does not move"})
|
|
662
|
+
calendars_diag["applied"] = [r for r in calendars_diag["applied"]
|
|
663
|
+
if r["column"] in planned]
|
|
664
|
+
calendars_diag["following"] = [
|
|
665
|
+
{"column": c.column, **fitted.get(c.column, {})}
|
|
666
|
+
for c in calendars if c.column not in weekly]
|
|
667
|
+
joint_spec = joint.to_spec(store, "joint")
|
|
668
|
+
manifest_encodings, manifest_missing = split_specs(encoder.to_specs(store))
|
|
669
|
+
|
|
670
|
+
identifiers = {c.name: _identifier_spec(df, c) for c in columns
|
|
671
|
+
if c.role == Role.IDENTIFIER}
|
|
672
|
+
constants: dict[str, Any] = {}
|
|
673
|
+
for c in columns:
|
|
674
|
+
if c.role == Role.CONSTANT:
|
|
675
|
+
v = df[c.name].drop_nulls()
|
|
676
|
+
val = v[0] if v.len() else None
|
|
677
|
+
if val is not None and hasattr(val, "isoformat"):
|
|
678
|
+
val = val.isoformat()
|
|
679
|
+
constants[c.name] = val
|
|
680
|
+
|
|
681
|
+
if calibration is None or sealed is None:
|
|
682
|
+
calibration, sealed = build_targets(
|
|
683
|
+
df, columns, policy, seed=self.seed, sealed_fraction=self.sealed_fraction,
|
|
684
|
+
max_pairs=self.max_pairs)
|
|
685
|
+
|
|
686
|
+
# Diagnostics follow the same disclosure rule as targets: no pairwise statistics for
|
|
687
|
+
# columns with rare levels (they could single out a few rows).
|
|
688
|
+
from ectype.fingerprint.targets import rare_level_columns
|
|
689
|
+
|
|
690
|
+
rare = rare_level_columns(df, features, policy)
|
|
691
|
+
assoc_features = [c for c in features if c.name not in rare]
|
|
692
|
+
assoc = association_matrix(df, assoc_features, policy, max_pairs=self.max_pairs) \
|
|
693
|
+
if len(assoc_features) > 1 else {}
|
|
694
|
+
if rare:
|
|
695
|
+
assoc = {**assoc, "excluded_rare_level_columns": sorted(rare)}
|
|
696
|
+
|
|
697
|
+
summarised = sorted(n for n, sp in manifest_model_marginals.items()
|
|
698
|
+
if sp.kind == "summary")
|
|
699
|
+
summary_warning = ([f"too few rows for a policy-safe quantile grid: marginal(s) of "
|
|
700
|
+
f"{', '.join(summarised)} stored as a coarse location/scale summary "
|
|
701
|
+
f"(mean and standard deviation; shape and tails are not preserved)"]
|
|
702
|
+
if summarised else [])
|
|
703
|
+
diag_disclosure = DisclosureDiagnostics(
|
|
704
|
+
smallest_stored_support=policy.min_category_support,
|
|
705
|
+
max_quantiles_per_row=float(policy.quantile_resolution) / max(1, df.height),
|
|
706
|
+
pooled_categories=pooled,
|
|
707
|
+
warnings=(["research profile: fingerprint is sensitive"] if policy.sensitive
|
|
708
|
+
else []) + ([f"small table ({df.height} rows): stored quantiles are "
|
|
709
|
+
f"coarse by policy"] if df.height < 2000 else [])
|
|
710
|
+
+ summary_warning,
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
cfg = self.config()
|
|
714
|
+
manifest = Manifest(
|
|
715
|
+
dataset=DatasetInfo(name=self.name, source_records=df.height,
|
|
716
|
+
source_columns=df.width),
|
|
717
|
+
columns=columns,
|
|
718
|
+
disclosure_policy=policy,
|
|
719
|
+
disclosure_diagnostics=diag_disclosure,
|
|
720
|
+
targets=TargetsSection(seal_hash="0" * 64, sealed_fraction=self.sealed_fraction,
|
|
721
|
+
partition_seed=self.seed),
|
|
722
|
+
provenance=Provenance(engine_version=__version__,
|
|
723
|
+
dependencies=_dependency_versions(), config=cfg,
|
|
724
|
+
config_hash=hashlib.sha256(canonical_json(cfg)).hexdigest(),
|
|
725
|
+
fit_seed=self.seed),
|
|
726
|
+
)
|
|
727
|
+
manifest.model.marginals = manifest_model_marginals
|
|
728
|
+
manifest.model.encodings = manifest_encodings
|
|
729
|
+
manifest.model.missingness = manifest_missing
|
|
730
|
+
manifest.model.joint = joint_spec
|
|
731
|
+
manifest.model.identifiers = identifiers
|
|
732
|
+
manifest.model.constants = constants
|
|
733
|
+
manifest.model.derived = [DerivedSpec(column=k, expression=v)
|
|
734
|
+
for k, v in {**functions, **self.derived}.items()]
|
|
735
|
+
manifest.model.transforms = list(transforms)
|
|
736
|
+
manifest.model.orderings = list(orderings)
|
|
737
|
+
manifest.model.calendars = list(calendars)
|
|
738
|
+
manifest.model.entities = entity_plan.specs(store)
|
|
739
|
+
manifest.model.references = dict(references)
|
|
740
|
+
manifest.model.sums = list(sums)
|
|
741
|
+
manifest.model.column_order = [c.name for c in columns if c.role != Role.EXCLUDED]
|
|
742
|
+
manifest.constraints.confirmed = list(self.constraints)
|
|
743
|
+
if self.suggest_constraints:
|
|
744
|
+
confirmed_exprs = {c.expression for c in self.constraints}
|
|
745
|
+
manifest.constraints.suggested = [
|
|
746
|
+
s for s in suggestions if s.expression not in confirmed_exprs]
|
|
747
|
+
manifest.diagnostics["structure"] = _json_safe(structure_diag)
|
|
748
|
+
if calendars_diag is not None and (calendars_diag["applied"]
|
|
749
|
+
or calendars_diag["not_selected"]):
|
|
750
|
+
manifest.diagnostics["calendars"] = _json_safe(calendars_diag)
|
|
751
|
+
if functions_diag is not None and (functions_diag["applied"]
|
|
752
|
+
or functions_diag["not_selected"]):
|
|
753
|
+
manifest.diagnostics["functions"] = _json_safe(functions_diag)
|
|
754
|
+
if entity_plan.diagnostics["applied"] or entity_plan.diagnostics["not_selected"]:
|
|
755
|
+
manifest.diagnostics["entities"] = _json_safe(entity_plan.diagnostics)
|
|
756
|
+
if any(sums_diag[k] for k in ("applied", "not_enforced", "not_selected", "skipped")):
|
|
757
|
+
manifest.diagnostics["sums"] = _json_safe(sums_diag)
|
|
758
|
+
|
|
759
|
+
if self.temporal:
|
|
760
|
+
from ectype.fingerprint.schema import ReservedSection
|
|
761
|
+
from ectype.temporal.pipeline import fit_temporal_section
|
|
762
|
+
opts = dict(self.temporal) if isinstance(self.temporal, Mapping) else {}
|
|
763
|
+
section = fit_temporal_section(df, columns, policy, self.seed, store, **opts)
|
|
764
|
+
if section is not None:
|
|
765
|
+
manifest.temporal = ReservedSection(**section)
|
|
766
|
+
|
|
767
|
+
excluded = {c.name: c.notes for c in columns if c.role == Role.EXCLUDED}
|
|
768
|
+
diagnostics = {
|
|
769
|
+
"marginal_selection": fit_diags,
|
|
770
|
+
"associations": assoc,
|
|
771
|
+
"excluded_columns": excluded,
|
|
772
|
+
}
|
|
773
|
+
if pseudonyms:
|
|
774
|
+
diagnostics["pseudonymised_columns"] = pseudonyms
|
|
775
|
+
if joint_diag_out is not None:
|
|
776
|
+
diagnostics["joint"] = joint_diag_out
|
|
777
|
+
return Fingerprint.build(manifest, store, calibration, sealed,
|
|
778
|
+
diagnostics=_json_safe(diagnostics))
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def fit(data: Any, **kwargs: Any) -> Fingerprint:
|
|
782
|
+
"""Shortcut for ``Profiler(**kwargs).fit(data)``."""
|
|
783
|
+
return Profiler(**kwargs).fit(data)
|