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/types.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Shared vocabulary used across profiling, models, fingerprint and generation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class LogicalType(StrEnum):
|
|
9
|
+
CONTINUOUS = "continuous" # real-valued numeric
|
|
10
|
+
DISCRETE = "discrete" # integer-valued numeric (counts, ordinal ints)
|
|
11
|
+
BOOLEAN = "boolean"
|
|
12
|
+
CATEGORICAL = "categorical" # nominal, low/moderate cardinality
|
|
13
|
+
DATETIME = "datetime" # timestamps / dates (cross-sectional: modeled as epoch)
|
|
14
|
+
STRING = "string" # structured strings (codes) - pattern model (Phase 2)
|
|
15
|
+
TEXT = "text" # free text - excluded with diagnostic
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Role(StrEnum):
|
|
19
|
+
FEATURE = "feature" # modeled statistically
|
|
20
|
+
IDENTIFIER = "identifier" # regenerated, never copied
|
|
21
|
+
PSEUDONYM = "pseudonym" # modeled as a categorical; labels replaced by stand-in tokens
|
|
22
|
+
REFERENCE = "reference" # a repeating key: modeled by its group sizes, regenerated
|
|
23
|
+
CONSTANT = "constant" # single value, emitted as-is (subject to policy)
|
|
24
|
+
DERIVED = "derived" # computed from an expression
|
|
25
|
+
EXCLUDED = "excluded" # not generated (e.g. free text); reported in diagnostics
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
#: roles whose columns are fitted by the statistical model (marginal, encoding, joint model,
|
|
29
|
+
#: targets). A ``PSEUDONYM`` column is modeled exactly like a categorical ``FEATURE``, on a frame
|
|
30
|
+
#: in which its labels have already been replaced by tokens (``profiling.pseudonym``, ADR-0010).
|
|
31
|
+
#: A ``REFERENCE`` column (ADR-0013) is modeled as a discrete number, on a frame in which each key
|
|
32
|
+
#: has been replaced by the number of rows that share it (``profiling.reference``).
|
|
33
|
+
MODELED_ROLES = frozenset({Role.FEATURE, Role.PSEUDONYM, Role.REFERENCE})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Severity(StrEnum):
|
|
37
|
+
HARD = "hard"
|
|
38
|
+
SOFT = "soft"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Enforcement(StrEnum):
|
|
42
|
+
SUPPORT = "support" # guaranteed by model support
|
|
43
|
+
DERIVATION = "derivation" # column computed from prerequisites
|
|
44
|
+
REJECTION = "rejection" # violating rows resampled
|
|
45
|
+
REPAIR = "repair" # minimal adjustment
|
|
46
|
+
NONE = "none" # measured only (soft)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Metric protocol.
|
|
2
|
+
|
|
3
|
+
A metric turns data into a JSON-safe *summary value* (``measure``) and compares two summary
|
|
4
|
+
values with a normalized, non-negative *distance* (``distance``; 0 = identical). Targets store
|
|
5
|
+
reference summary values; the validator measures synthetic data the same way and compares.
|
|
6
|
+
Fingerprint-vs-fingerprint comparison compares stored values directly, with no data.
|
|
7
|
+
|
|
8
|
+
Summary values are subject to the disclosure policy (e.g. quantile resolution, minimum cell
|
|
9
|
+
support) - metrics must coarsen what they store via ``policy``.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from abc import ABC, abstractmethod
|
|
15
|
+
from typing import Any, ClassVar, Literal
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import polars as pl
|
|
19
|
+
|
|
20
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
21
|
+
from ectype.registry import Registry
|
|
22
|
+
from ectype.types import LogicalType
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Metric(ABC):
|
|
26
|
+
kind: ClassVar[str] # registry key, e.g. "univariate.wasserstein"
|
|
27
|
+
family: ClassVar[str] # partition unit for sealing (usually == kind)
|
|
28
|
+
arity: ClassVar[Literal[1, 2, "all"]]
|
|
29
|
+
#: default tolerance on ``distance`` if no noise-floor estimate is available
|
|
30
|
+
default_tolerance: ClassVar[float] = 0.05
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
34
|
+
"""Whether this metric is meaningful for the given column types."""
|
|
35
|
+
return True
|
|
36
|
+
|
|
37
|
+
@abstractmethod
|
|
38
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
39
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
40
|
+
"""JSON-safe summary of ``df[columns]`` (policy-coarsened)."""
|
|
41
|
+
|
|
42
|
+
@abstractmethod
|
|
43
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
44
|
+
"""Normalized distance >= 0 between two summaries (0 = identical)."""
|
|
45
|
+
|
|
46
|
+
def noise_floor(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
47
|
+
policy: DisclosurePolicySpec, rng: np.random.Generator,
|
|
48
|
+
n_boot: int = 20, sample_size: int | None = None) -> float:
|
|
49
|
+
"""Typical distance between the full-data summary and a resample-of-size-n summary.
|
|
50
|
+
|
|
51
|
+
Used to set tolerances: a synthetic sample of size n cannot be expected to be closer
|
|
52
|
+
than sampling noise. Default: bootstrap with replacement.
|
|
53
|
+
"""
|
|
54
|
+
ref = self.measure(df, columns, policy)
|
|
55
|
+
n = df.height if sample_size is None else min(sample_size, df.height)
|
|
56
|
+
if n == 0:
|
|
57
|
+
return 0.0
|
|
58
|
+
ds = []
|
|
59
|
+
for _ in range(n_boot):
|
|
60
|
+
idx = rng.integers(0, df.height, size=n)
|
|
61
|
+
ds.append(self.distance(ref, self.measure(df[idx], columns, policy)))
|
|
62
|
+
return float(np.quantile(ds, 0.95))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
METRICS: Registry[Metric] = Registry("metric")
|
|
66
|
+
|
|
67
|
+
NUMERIC_TYPES = (LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.DATETIME)
|
|
68
|
+
CATEGORY_TYPES = (LogicalType.CATEGORICAL, LogicalType.BOOLEAN)
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""Bivariate metrics.
|
|
2
|
+
|
|
3
|
+
Applicability (``applies_to``):
|
|
4
|
+
|
|
5
|
+
* ``spearman``, ``pearson``, ``kendall``: both columns numeric-like (continuous, discrete,
|
|
6
|
+
datetime, boolean as 0/1).
|
|
7
|
+
* ``cramers_v``: both columns categorical/boolean, at least one categorical.
|
|
8
|
+
* ``correlation_ratio``: one categorical, one numeric (continuous, discrete, datetime).
|
|
9
|
+
* ``mutual_info``: any pair of numeric-like/categorical columns (numerics quantile-binned).
|
|
10
|
+
* ``contingency``: both columns categorical/boolean.
|
|
11
|
+
|
|
12
|
+
Summary formats: scalar metrics store a float (coarsened); ``contingency`` stores
|
|
13
|
+
``{"cells": [[label_a, label_b, prob], ...], "suppressed": prob}`` where cells whose count is
|
|
14
|
+
below ``rare_cell_min`` are folded into ``suppressed`` and labels below
|
|
15
|
+
``min_category_support`` are pooled into ``"__other__"``. Rows with a null in either column are
|
|
16
|
+
dropped. Correlation distances are absolute differences (default tolerance 0.05).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import Any, ClassVar, Literal
|
|
22
|
+
|
|
23
|
+
import numpy as np
|
|
24
|
+
import polars as pl
|
|
25
|
+
from scipy import stats
|
|
26
|
+
|
|
27
|
+
from ectype.fingerprint.disclosure import OTHER
|
|
28
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
29
|
+
from ectype.rng import stream
|
|
30
|
+
from ectype.types import LogicalType
|
|
31
|
+
from ectype.validation.metrics.base import METRICS, Metric
|
|
32
|
+
from ectype.validation.metrics.univariate import (
|
|
33
|
+
aligned_tvd,
|
|
34
|
+
category_codes_from_data,
|
|
35
|
+
is_category,
|
|
36
|
+
is_numeric,
|
|
37
|
+
is_numeric_like,
|
|
38
|
+
numeric_values,
|
|
39
|
+
safe_float,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
SUPPRESSED = "__suppressed__"
|
|
43
|
+
KENDALL_MAX_ROWS = 2000
|
|
44
|
+
MI_MAX_BINS = 10
|
|
45
|
+
N_BOOT_HEAVY = 60 # bootstrap resamples for the Pearson noise floor (targets.build_targets)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------------------------------------
|
|
49
|
+
# Pure statistics on arrays (shared with profiling/bivariate.py)
|
|
50
|
+
# ---------------------------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _complete(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
54
|
+
m = np.isfinite(x) & np.isfinite(y)
|
|
55
|
+
return x[m], y[m]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def pearson(x: np.ndarray, y: np.ndarray) -> float:
|
|
59
|
+
x, y = _complete(x, y)
|
|
60
|
+
if x.size < 3:
|
|
61
|
+
return 0.0
|
|
62
|
+
sx, sy = x.std(), y.std()
|
|
63
|
+
if sx <= 0 or sy <= 0:
|
|
64
|
+
return 0.0
|
|
65
|
+
r = float(np.mean((x - x.mean()) * (y - y.mean())) / (sx * sy))
|
|
66
|
+
return float(np.clip(r, -1.0, 1.0))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def spearman(x: np.ndarray, y: np.ndarray) -> float:
|
|
70
|
+
x, y = _complete(x, y)
|
|
71
|
+
if x.size < 3:
|
|
72
|
+
return 0.0
|
|
73
|
+
return pearson(stats.rankdata(x), stats.rankdata(y))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def kendall(x: np.ndarray, y: np.ndarray, max_rows: int = KENDALL_MAX_ROWS) -> float:
|
|
77
|
+
x, y = _complete(x, y)
|
|
78
|
+
if x.size < 3:
|
|
79
|
+
return 0.0
|
|
80
|
+
if x.size > max_rows:
|
|
81
|
+
idx = np.sort(stream(0, "kendall", int(x.size)).choice(x.size, max_rows, replace=False))
|
|
82
|
+
x, y = x[idx], y[idx]
|
|
83
|
+
if np.all(x == x[0]) or np.all(y == y[0]):
|
|
84
|
+
return 0.0
|
|
85
|
+
t = stats.kendalltau(x, y).statistic
|
|
86
|
+
return 0.0 if not np.isfinite(t) else float(t)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _table(a: np.ndarray, b: np.ndarray, ka: int, kb: int) -> np.ndarray:
|
|
90
|
+
"""Contingency counts from integer codes (no nulls)."""
|
|
91
|
+
return np.bincount(a * kb + b, minlength=ka * kb).reshape(ka, kb).astype(float)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def cramers_v(a: np.ndarray, b: np.ndarray, ka: int, kb: int,
|
|
95
|
+
bias_correct: bool = False) -> float:
|
|
96
|
+
"""Cramer's V from integer codes. ``bias_correct`` uses Bergsma's correction."""
|
|
97
|
+
n = a.size
|
|
98
|
+
if n < 2 or ka < 2 or kb < 2:
|
|
99
|
+
return 0.0
|
|
100
|
+
t = _table(a, b, ka, kb)
|
|
101
|
+
t = t[t.sum(1) > 0][:, t.sum(0) > 0]
|
|
102
|
+
r, c = t.shape
|
|
103
|
+
if r < 2 or c < 2:
|
|
104
|
+
return 0.0
|
|
105
|
+
e = t.sum(1, keepdims=True) * t.sum(0, keepdims=True) / n
|
|
106
|
+
chi2 = float(((t - e) ** 2 / e).sum())
|
|
107
|
+
phi2 = chi2 / n
|
|
108
|
+
if bias_correct and n > 1:
|
|
109
|
+
phi2 = max(0.0, phi2 - (r - 1) * (c - 1) / (n - 1))
|
|
110
|
+
r = r - (r - 1) ** 2 / (n - 1)
|
|
111
|
+
c = c - (c - 1) ** 2 / (n - 1)
|
|
112
|
+
denom = min(r - 1, c - 1)
|
|
113
|
+
return float(np.sqrt(min(1.0, phi2 / denom))) if denom > 0 else 0.0
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def correlation_ratio(codes: np.ndarray, y: np.ndarray, k: int,
|
|
117
|
+
bias_correct: bool = False) -> float:
|
|
118
|
+
"""eta = sqrt(SS_between / SS_total) for integer group codes and numeric y."""
|
|
119
|
+
n = y.size
|
|
120
|
+
if n < 2 or k < 2:
|
|
121
|
+
return 0.0
|
|
122
|
+
sst = float(((y - y.mean()) ** 2).sum())
|
|
123
|
+
if sst <= 0:
|
|
124
|
+
return 0.0
|
|
125
|
+
cnt = np.bincount(codes, minlength=k).astype(float)
|
|
126
|
+
sums = np.bincount(codes, weights=y, minlength=k)
|
|
127
|
+
nz = cnt > 0
|
|
128
|
+
ssb = float((sums[nz] ** 2 / cnt[nz]).sum() - y.sum() ** 2 / n)
|
|
129
|
+
eta2 = min(1.0, max(0.0, ssb / sst))
|
|
130
|
+
if bias_correct:
|
|
131
|
+
g = int(nz.sum())
|
|
132
|
+
if n > g:
|
|
133
|
+
eta2 = max(0.0, eta2 - (g - 1) / (n - g) * (1.0 - eta2))
|
|
134
|
+
return float(np.sqrt(eta2))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def quantile_bins(x: np.ndarray, max_bins: int = MI_MAX_BINS) -> tuple[np.ndarray, int]:
|
|
138
|
+
"""Integer bin codes from quantile edges (ties collapse bins)."""
|
|
139
|
+
if x.size == 0:
|
|
140
|
+
return x.astype(np.int64), 0
|
|
141
|
+
edges = np.unique(np.quantile(x, np.linspace(0, 1, max_bins + 1)[1:-1]))
|
|
142
|
+
codes = np.searchsorted(edges, x, side="right")
|
|
143
|
+
return codes.astype(np.int64), int(edges.size + 1)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def normalized_mi(a: np.ndarray, b: np.ndarray, ka: int, kb: int) -> float:
|
|
147
|
+
"""MI / sqrt(H(a) H(b)) from integer codes, in [0, 1]."""
|
|
148
|
+
n = a.size
|
|
149
|
+
if n < 2 or ka < 2 or kb < 2:
|
|
150
|
+
return 0.0
|
|
151
|
+
p = _table(a, b, ka, kb) / n
|
|
152
|
+
pa, pb = p.sum(1), p.sum(0)
|
|
153
|
+
nz = p > 0
|
|
154
|
+
mi = float((p[nz] * np.log(p[nz] / np.outer(pa, pb)[nz])).sum())
|
|
155
|
+
ha = float(-(pa[pa > 0] * np.log(pa[pa > 0])).sum())
|
|
156
|
+
hb = float(-(pb[pb > 0] * np.log(pb[pb > 0])).sum())
|
|
157
|
+
if ha <= 0 or hb <= 0:
|
|
158
|
+
return 0.0
|
|
159
|
+
return float(np.clip(mi / np.sqrt(ha * hb), 0.0, 1.0))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
# ---------------------------------------------------------------------------------------------
|
|
163
|
+
# Metric classes
|
|
164
|
+
# ---------------------------------------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _codes_int(c: np.ndarray) -> np.ndarray:
|
|
168
|
+
return c.astype(np.int64)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class _Pair(Metric):
|
|
172
|
+
arity: ClassVar[Literal[1, 2, "all"]] = 2
|
|
173
|
+
default_tolerance = 0.05
|
|
174
|
+
|
|
175
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
176
|
+
return abs(float(reference) - float(candidate))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class _NumericPair(_Pair):
|
|
180
|
+
@classmethod
|
|
181
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
182
|
+
return len(columns) == 2 and all(is_numeric_like(c) for c in columns)
|
|
183
|
+
|
|
184
|
+
@staticmethod
|
|
185
|
+
def _stat(x: np.ndarray, y: np.ndarray) -> float:
|
|
186
|
+
raise NotImplementedError
|
|
187
|
+
|
|
188
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
189
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
190
|
+
a, b = columns
|
|
191
|
+
x = numeric_values(df[a.name], a)
|
|
192
|
+
y = numeric_values(df[b.name], b)
|
|
193
|
+
return safe_float(self._stat(x, y), policy)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
@METRICS.register()
|
|
197
|
+
class Spearman(_NumericPair):
|
|
198
|
+
kind = "bivariate.spearman"
|
|
199
|
+
family = "bivariate.spearman"
|
|
200
|
+
_stat = staticmethod(spearman)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@METRICS.register()
|
|
204
|
+
class Pearson(_NumericPair):
|
|
205
|
+
"""Pearson's r. Dominated by a few extreme rows under heavy tails, so its tolerance noise
|
|
206
|
+
floor uses ``n_boot_min`` bootstrap resamples (see ``fingerprint.targets``)."""
|
|
207
|
+
|
|
208
|
+
kind = "bivariate.pearson"
|
|
209
|
+
family = "bivariate.pearson"
|
|
210
|
+
n_boot_min = N_BOOT_HEAVY
|
|
211
|
+
_stat = staticmethod(pearson)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
@METRICS.register()
|
|
215
|
+
class Kendall(_NumericPair):
|
|
216
|
+
"""Kendall's tau-b on a deterministic subsample of at most 2000 complete rows."""
|
|
217
|
+
|
|
218
|
+
kind = "bivariate.kendall"
|
|
219
|
+
family = "bivariate.kendall"
|
|
220
|
+
_stat = staticmethod(kendall)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _cat_pair_codes(df: pl.DataFrame, columns: list[ColumnSchema], policy: DisclosurePolicySpec
|
|
224
|
+
) -> tuple[list[str], np.ndarray, list[str], np.ndarray]:
|
|
225
|
+
a, b = columns
|
|
226
|
+
la, ca, _ = category_codes_from_data(df[a.name], policy)
|
|
227
|
+
lb, cb, _ = category_codes_from_data(df[b.name], policy)
|
|
228
|
+
m = np.isfinite(ca) & np.isfinite(cb)
|
|
229
|
+
return la, _codes_int(ca[m]), lb, _codes_int(cb[m])
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@METRICS.register()
|
|
233
|
+
class CramersV(_Pair):
|
|
234
|
+
kind = "bivariate.cramers_v"
|
|
235
|
+
family = "bivariate.cramers_v"
|
|
236
|
+
|
|
237
|
+
@classmethod
|
|
238
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
239
|
+
return (len(columns) == 2 and all(is_category(c) for c in columns)
|
|
240
|
+
and any(c.logical_type == LogicalType.CATEGORICAL for c in columns))
|
|
241
|
+
|
|
242
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
243
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
244
|
+
la, a, lb, b = _cat_pair_codes(df, columns, policy)
|
|
245
|
+
return safe_float(cramers_v(a, b, len(la), len(lb)), policy)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
@METRICS.register()
|
|
249
|
+
class CorrelationRatio(_Pair):
|
|
250
|
+
"""eta of the numeric column given the categorical column (either order)."""
|
|
251
|
+
|
|
252
|
+
kind = "bivariate.correlation_ratio"
|
|
253
|
+
family = "bivariate.correlation_ratio"
|
|
254
|
+
|
|
255
|
+
@classmethod
|
|
256
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
257
|
+
if len(columns) != 2:
|
|
258
|
+
return False
|
|
259
|
+
a, b = columns
|
|
260
|
+
return ((a.logical_type == LogicalType.CATEGORICAL and is_numeric(b))
|
|
261
|
+
or (b.logical_type == LogicalType.CATEGORICAL and is_numeric(a)))
|
|
262
|
+
|
|
263
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
264
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
265
|
+
a, b = columns
|
|
266
|
+
cat, num = (a, b) if a.logical_type == LogicalType.CATEGORICAL else (b, a)
|
|
267
|
+
labels, codes, _ = category_codes_from_data(df[cat.name], policy)
|
|
268
|
+
y = numeric_values(df[num.name], num)
|
|
269
|
+
m = np.isfinite(codes) & np.isfinite(y)
|
|
270
|
+
return safe_float(correlation_ratio(_codes_int(codes[m]), y[m], len(labels)), policy)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _mi_codes(df: pl.DataFrame, col: ColumnSchema, policy: DisclosurePolicySpec
|
|
274
|
+
) -> tuple[np.ndarray, str]:
|
|
275
|
+
"""Raw codes (float, NaN null) and how to bin: 'cat' (already codes) or 'num'."""
|
|
276
|
+
if col.logical_type == LogicalType.CATEGORICAL or (
|
|
277
|
+
col.logical_type == LogicalType.BOOLEAN):
|
|
278
|
+
_, codes, _ = category_codes_from_data(df[col.name], policy)
|
|
279
|
+
return codes, "cat"
|
|
280
|
+
return numeric_values(df[col.name], col), "num"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
@METRICS.register()
|
|
284
|
+
class MutualInfo(_Pair):
|
|
285
|
+
"""Normalized mutual information; numerics binned at (up to 10) quantile bins."""
|
|
286
|
+
|
|
287
|
+
kind = "bivariate.mutual_info"
|
|
288
|
+
family = "bivariate.mutual_info"
|
|
289
|
+
|
|
290
|
+
@classmethod
|
|
291
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
292
|
+
return len(columns) == 2 and all(is_numeric_like(c) or is_category(c) for c in columns)
|
|
293
|
+
|
|
294
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
295
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
296
|
+
xa, ta = _mi_codes(df, columns[0], policy)
|
|
297
|
+
xb, tb = _mi_codes(df, columns[1], policy)
|
|
298
|
+
m = np.isfinite(xa) & np.isfinite(xb)
|
|
299
|
+
xa, xb = xa[m], xb[m]
|
|
300
|
+
out = []
|
|
301
|
+
for x, t in ((xa, ta), (xb, tb)):
|
|
302
|
+
if t == "num":
|
|
303
|
+
out.append(quantile_bins(x))
|
|
304
|
+
else:
|
|
305
|
+
c = x.astype(np.int64)
|
|
306
|
+
out.append((c, int(np.max(c)) + 1 if c.size else 0))
|
|
307
|
+
(a, ka), (b, kb) = out
|
|
308
|
+
return safe_float(normalized_mi(a, b, ka, kb), policy)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
@METRICS.register()
|
|
312
|
+
class Contingency(_Pair):
|
|
313
|
+
"""Joint label frequencies with rare cells suppressed; distance = TVD."""
|
|
314
|
+
|
|
315
|
+
kind = "bivariate.contingency"
|
|
316
|
+
family = "bivariate.contingency"
|
|
317
|
+
default_tolerance = 0.05
|
|
318
|
+
|
|
319
|
+
@classmethod
|
|
320
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
321
|
+
return len(columns) == 2 and all(is_category(c) for c in columns)
|
|
322
|
+
|
|
323
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
324
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
325
|
+
la, a, lb, b = _cat_pair_codes(df, columns, policy)
|
|
326
|
+
n = a.size
|
|
327
|
+
if n == 0 or not la or not lb:
|
|
328
|
+
return {"cells": [], "suppressed": 0.0}
|
|
329
|
+
t = _table(a, b, len(la), len(lb)).astype(np.int64)
|
|
330
|
+
cells = []
|
|
331
|
+
kept = 0
|
|
332
|
+
for i, j in zip(*np.nonzero(t >= policy.rare_cell_min)):
|
|
333
|
+
cells.append([la[i], lb[j], safe_float(t[i, j] / n, policy)])
|
|
334
|
+
kept += int(t[i, j])
|
|
335
|
+
cells.sort(key=lambda c: (c[0], c[1]))
|
|
336
|
+
return {"cells": cells, "suppressed": safe_float((n - kept) / n, policy)}
|
|
337
|
+
|
|
338
|
+
@staticmethod
|
|
339
|
+
def _as_map(v: Any) -> dict[str, float]:
|
|
340
|
+
out = {f"{a}\x1f{b}": float(p) for a, b, p in v["cells"]}
|
|
341
|
+
if float(v.get("suppressed", 0.0)) > 0:
|
|
342
|
+
out[SUPPRESSED] = float(v["suppressed"])
|
|
343
|
+
return out
|
|
344
|
+
|
|
345
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
346
|
+
ref, cand = self._as_map(reference), self._as_map(candidate)
|
|
347
|
+
# candidate cells absent from the reference fall into the reference's suppressed
|
|
348
|
+
# bucket if it has one (they may be cells the reference suppressed)
|
|
349
|
+
return aligned_tvd(ref, cand, SUPPRESSED)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
__all__ = ["OTHER", "SUPPRESSED", "pearson", "spearman", "kendall", "cramers_v",
|
|
353
|
+
"correlation_ratio", "normalized_mi", "quantile_bins"]
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Missingness metrics.
|
|
2
|
+
|
|
3
|
+
``missingness.co_missing`` stores ``{"both": p11, "a": pa, "b": pb}``: the fraction of rows where
|
|
4
|
+
both columns are null and each marginal null rate. Any rate whose underlying row count is below
|
|
5
|
+
``rare_cell_min`` is stored as 0 (suppressed). Distance = max absolute difference of the three
|
|
6
|
+
rates (default tolerance 0.02).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, ClassVar, Literal
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import polars as pl
|
|
15
|
+
|
|
16
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
17
|
+
from ectype.validation.metrics.base import METRICS, Metric
|
|
18
|
+
from ectype.validation.metrics.univariate import safe_float
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def null_mask(s: pl.Series) -> np.ndarray:
|
|
22
|
+
m = s.is_null()
|
|
23
|
+
if s.dtype.is_float():
|
|
24
|
+
m = m | s.is_nan().fill_null(False)
|
|
25
|
+
return m.to_numpy().astype(bool)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@METRICS.register()
|
|
29
|
+
class CoMissing(Metric):
|
|
30
|
+
kind = "missingness.co_missing"
|
|
31
|
+
family = "missingness.co_missing"
|
|
32
|
+
arity: ClassVar[Literal[1, 2, "all"]] = 2
|
|
33
|
+
default_tolerance = 0.02
|
|
34
|
+
|
|
35
|
+
@classmethod
|
|
36
|
+
def applies_to(cls, columns: tuple[ColumnSchema, ...]) -> bool:
|
|
37
|
+
return len(columns) == 2
|
|
38
|
+
|
|
39
|
+
def measure(self, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
40
|
+
policy: DisclosurePolicySpec) -> Any:
|
|
41
|
+
n = df.height
|
|
42
|
+
if n == 0:
|
|
43
|
+
return {"both": 0.0, "a": 0.0, "b": 0.0}
|
|
44
|
+
ma = null_mask(df[columns[0].name])
|
|
45
|
+
mb = null_mask(df[columns[1].name])
|
|
46
|
+
|
|
47
|
+
def rate(count: int) -> float:
|
|
48
|
+
return 0.0 if count < policy.rare_cell_min else safe_float(count / n, policy)
|
|
49
|
+
|
|
50
|
+
return {"both": rate(int((ma & mb).sum())), "a": rate(int(ma.sum())),
|
|
51
|
+
"b": rate(int(mb.sum()))}
|
|
52
|
+
|
|
53
|
+
def distance(self, reference: Any, candidate: Any) -> float:
|
|
54
|
+
return max(abs(float(reference[k]) - float(candidate[k])) for k in ("both", "a", "b"))
|