ectype-data 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,746 @@
|
|
|
1
|
+
"""Fingerprint-vs-fingerprint drift comparison (M13). No data is needed.
|
|
2
|
+
|
|
3
|
+
``compare(a, b)`` reports
|
|
4
|
+
|
|
5
|
+
* **schema drift** - added / removed columns, logical-type and role changes, and category-set
|
|
6
|
+
changes (labels read from the categorical marginal arrays; columns without a readable
|
|
7
|
+
categorical spec are skipped with a note);
|
|
8
|
+
* **policy compatibility** - a warning when the disclosure policies differ (stored summaries are
|
|
9
|
+
coarsened differently, so small distances may be policy artefacts);
|
|
10
|
+
* **target drift** - targets matched by id across calibration *and* sealed sets of both
|
|
11
|
+
fingerprints (drift detection is not optimisation, so both seals are opened), with
|
|
12
|
+
``distance = compare_values(ta, tb)`` (``a`` = reference), tested together under a
|
|
13
|
+
false-discovery-rate control (below);
|
|
14
|
+
* **localisation** - drift ranked by column (sum of normalised exceedance
|
|
15
|
+
``distance / tolerance - 1`` over drifted single-column targets) and by column pair (same sum
|
|
16
|
+
over drifted pair targets). Each column also reports ``pair_share`` (half of the exceedance of
|
|
17
|
+
drifted pairs it belongs to) for context; it does not enter the column ranking, so a column
|
|
18
|
+
that merely partners a drifted column is not blamed for it.
|
|
19
|
+
|
|
20
|
+
Pseudonymised columns (role ``pseudonym`` in either fingerprint, ADR-0010)
|
|
21
|
+
Their stored labels are stand-in tokens, assigned independently in every fingerprint, so
|
|
22
|
+
equal tokens mean nothing and label sets cannot be compared. For such a column the category
|
|
23
|
+
sets are not compared; its ``univariate.frequencies`` target is compared as a sorted
|
|
24
|
+
level-frequency profile (``validation.metrics.univariate.rank_profiles``: how concentrated
|
|
25
|
+
the column is and how much of it is pooled, not which level is which); and
|
|
26
|
+
``bivariate.contingency`` targets involving it are left out. Scalar targets (missing rate,
|
|
27
|
+
Cramer's V, correlation ratio, mutual information) do not use labels and are compared as
|
|
28
|
+
usual. The schema notes say what was done.
|
|
29
|
+
|
|
30
|
+
Per-target noise threshold
|
|
31
|
+
A target's stored tolerance reflects the noise of *one* sample, but two fingerprints carry
|
|
32
|
+
the noise of two. Each stored target has ``params.noise_floor`` ``nf``: the 95% quantile of
|
|
33
|
+
the distance between the summary of a size-``m`` resample and the summary of all ``n``
|
|
34
|
+
rows, inflated to cover both, so ``nf ~= u * sqrt(1/m + 1/n)`` with ``u`` a per-target
|
|
35
|
+
noise constant of the population (``m = params.sample_size``, ``n = params.n``). Each
|
|
36
|
+
fingerprint gives an estimate ``u = nf / sqrt(1/m + 1/n)``; their mean is rescaled to the
|
|
37
|
+
two row counts being compared (``N_a``, ``N_b`` = ``manifest.dataset.source_records``)::
|
|
38
|
+
|
|
39
|
+
noise95 = mean(u_a, u_b) * sqrt(1/N_a + 1/N_b)
|
|
40
|
+
|
|
41
|
+
Row counts are capped where a metric subsamples (Kendall's tau uses at most
|
|
42
|
+
``KENDALL_MAX_ROWS`` rows). A target without a stored noise floor (for example a
|
|
43
|
+
hand-built one) uses its stored ``tolerance`` as the 95% quantile of an ``n_t``-vs-``n_t``
|
|
44
|
+
comparison, rescaled the same way: ``noise95 = tol * sqrt((1/N_a + 1/N_b) / (2/n_t))``
|
|
45
|
+
with ``n_t = params.n`` or the fingerprint's row count. ``metric.default_tolerance`` stays a
|
|
46
|
+
minimum effect size: a distance at or below it is never drift.
|
|
47
|
+
|
|
48
|
+
Decision rule (multiplicity control)
|
|
49
|
+
The distance is modelled as half-normal noise whose 95% quantile is
|
|
50
|
+
``KAPPA * noise95``. ``KAPPA`` calibrates the approximation: the noise floor is a
|
|
51
|
+
95% quantile estimated from 10 resamples, and some distances (maxima over several
|
|
52
|
+
components) have heavier tails than a half-normal. It was set from repeated comparisons of
|
|
53
|
+
independent samples of one population and from validating fresh real samples against
|
|
54
|
+
fingerprints (where only one noise estimate is available; see
|
|
55
|
+
``tests/statistical/test_drift_calibration.py`` and ``test_validation_calibration.py``)::
|
|
56
|
+
|
|
57
|
+
z = 1.96 * (distance - step) / (KAPPA * noise95), p = 2 * (1 - Phi(z))
|
|
58
|
+
|
|
59
|
+
and ``p = 1`` when ``distance - step <= metric.default_tolerance``. ``step`` discounts one
|
|
60
|
+
unit of a lumpy statistic (``resolution_step``: the 1%/99% quantiles of an integer column
|
|
61
|
+
move in whole units) and, for the correlation ratio and Cramér's V, the difference those
|
|
62
|
+
statistics show between the two row counts on one population (``null_level_step``: on
|
|
63
|
+
unrelated columns they sit at about ``sqrt(levels / rows)``, not at zero). It is 0 for
|
|
64
|
+
every other metric.
|
|
65
|
+
|
|
66
|
+
Benjamini-Hochberg at level ``q`` is applied to the p-values of all compared targets
|
|
67
|
+
(``q`` from ``sensitivity``: ``"strict"`` 0.20, ``"standard"`` 0.05, ``"lenient"`` 0.01,
|
|
68
|
+
or a number in (0, 1)). With ``k`` rejections out of ``M`` tests a target is drifted iff
|
|
69
|
+
``p <= q * max(k, 1) / M``; equivalently ``distance > tolerance`` with the decision
|
|
70
|
+
distance ``tolerance = step + max(metric.default_tolerance, KAPPA * noise95 * z_cut / 1.96)``
|
|
71
|
+
and
|
|
72
|
+
``z_cut = Phi^-1(1 - q * max(k, 1) / (2 M))``. That decision distance is what each
|
|
73
|
+
``TargetResult.tolerance`` holds. When no target has drifted, BH controls the chance of
|
|
74
|
+
flagging any target at about ``q``, so two fingerprints of independent samples of the same
|
|
75
|
+
population pass ``--fail-on-drift`` in about ``1 - q`` of comparisons.
|
|
76
|
+
|
|
77
|
+
Fail closed: a matched target whose distance cannot be computed is recorded in ``errors`` and
|
|
78
|
+
makes the comparison **inconclusive**: ``passed`` is False (although ``drifted`` only reflects
|
|
79
|
+
measured drift) and the summary says so.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
from __future__ import annotations
|
|
83
|
+
|
|
84
|
+
import math
|
|
85
|
+
from dataclasses import dataclass, field
|
|
86
|
+
from statistics import NormalDist
|
|
87
|
+
from typing import Any
|
|
88
|
+
|
|
89
|
+
from ectype._version import __version__
|
|
90
|
+
from ectype.fingerprint.core import Fingerprint
|
|
91
|
+
from ectype.fingerprint.schema import Target
|
|
92
|
+
from ectype.types import LogicalType, Role
|
|
93
|
+
from ectype.validation.report import (
|
|
94
|
+
ReportShell,
|
|
95
|
+
TargetResult,
|
|
96
|
+
_fmt,
|
|
97
|
+
esc,
|
|
98
|
+
html_table,
|
|
99
|
+
json_safe,
|
|
100
|
+
meta_list,
|
|
101
|
+
pill,
|
|
102
|
+
stats_row,
|
|
103
|
+
target_rows,
|
|
104
|
+
worst_first,
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
#: Benjamini-Hochberg level for each named sensitivity (higher q flags drift more readily).
|
|
108
|
+
SENSITIVITY: dict[str, float] = {"strict": 0.20, "standard": 0.05, "lenient": 0.01}
|
|
109
|
+
#: Calibration of the half-normal approximation (see the module docstring).
|
|
110
|
+
KAPPA = 1.5
|
|
111
|
+
Z95 = NormalDist().inv_cdf(0.975)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _subsample_caps() -> dict[str, int]:
|
|
115
|
+
from ectype.validation.metrics.bivariate import KENDALL_MAX_ROWS
|
|
116
|
+
|
|
117
|
+
return {"bivariate.kendall": int(KENDALL_MAX_ROWS)}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def resolve_sensitivity(sensitivity: str | float) -> float:
|
|
121
|
+
"""The BH level ``q`` for a sensitivity name or number (0 < q < 1)."""
|
|
122
|
+
if isinstance(sensitivity, str):
|
|
123
|
+
key = sensitivity.strip().lower()
|
|
124
|
+
if key in SENSITIVITY:
|
|
125
|
+
return SENSITIVITY[key]
|
|
126
|
+
try:
|
|
127
|
+
q = float(key)
|
|
128
|
+
except ValueError:
|
|
129
|
+
raise ValueError(f"unknown sensitivity {sensitivity!r}; use one of "
|
|
130
|
+
f"{', '.join(SENSITIVITY)} or a number in (0, 1)") from None
|
|
131
|
+
else:
|
|
132
|
+
q = float(sensitivity)
|
|
133
|
+
if not 0.0 < q < 1.0:
|
|
134
|
+
raise ValueError(f"sensitivity must be in (0, 1), got {q}")
|
|
135
|
+
return q
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def sensitivity_label(sensitivity: str | float) -> str:
|
|
139
|
+
"""The sensitivity name (``"standard"``, ...) or ``"q=<value>"`` for a number."""
|
|
140
|
+
q = resolve_sensitivity(sensitivity)
|
|
141
|
+
if isinstance(sensitivity, str) and sensitivity.strip().lower() in SENSITIVITY:
|
|
142
|
+
return sensitivity.strip().lower()
|
|
143
|
+
return f"q={q:g}"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _categories(fp: Fingerprint, column: str) -> list[str] | None:
|
|
147
|
+
"""Stored category labels of ``column`` (from its categorical marginal), or None."""
|
|
148
|
+
spec = fp.manifest.model.marginals.get(column)
|
|
149
|
+
if spec is None or "labels" not in spec.arrays:
|
|
150
|
+
return None
|
|
151
|
+
ref = spec.arrays["labels"]
|
|
152
|
+
if ref not in fp.arrays:
|
|
153
|
+
return None
|
|
154
|
+
try:
|
|
155
|
+
return [str(x) for x in fp.arrays.get(ref).tolist()]
|
|
156
|
+
except Exception:
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def fingerprint_categories(fp: Fingerprint, column: str) -> list[str] | None:
|
|
161
|
+
"""Category labels stored for ``column`` in ``fp`` (None when not categorical)."""
|
|
162
|
+
return _categories(fp, column)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def all_targets(fp: Fingerprint) -> dict[str, Target]:
|
|
166
|
+
"""Every target (calibration and sealed) of ``fp`` keyed by id. Opens the seal: use only
|
|
167
|
+
for comparison and drift work, never for calibration."""
|
|
168
|
+
return {tid: t for tid, (t, _section) in _all_targets(fp).items()}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _all_targets(fp: Fingerprint) -> dict[str, tuple[Target, str]]:
|
|
172
|
+
out: dict[str, tuple[Target, str]] = {}
|
|
173
|
+
for t in fp.calibration.targets:
|
|
174
|
+
out[t.id] = (t, "calibration")
|
|
175
|
+
for t in fp.open_seal().targets:
|
|
176
|
+
out[t.id] = (t, "sealed")
|
|
177
|
+
return out
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _default_tolerance(metric: str) -> float:
|
|
181
|
+
try:
|
|
182
|
+
from ectype.validation.metrics.base import METRICS
|
|
183
|
+
|
|
184
|
+
return float(METRICS.get(metric).default_tolerance)
|
|
185
|
+
except Exception:
|
|
186
|
+
return 0.05
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _positive(v: Any) -> float | None:
|
|
190
|
+
try:
|
|
191
|
+
x = float(v)
|
|
192
|
+
except (TypeError, ValueError):
|
|
193
|
+
return None
|
|
194
|
+
return x if math.isfinite(x) and x > 0 else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _unit_noise(t: Target, rows: float | None, cap: float) -> float | None:
|
|
198
|
+
"""Per-target noise constant ``u`` (95% distance quantile at ``sqrt(1/n1 + 1/n2) = 1``)."""
|
|
199
|
+
p = t.params or {}
|
|
200
|
+
nf = p.get("noise_floor")
|
|
201
|
+
m, n = _positive(p.get("sample_size")), _positive(p.get("n"))
|
|
202
|
+
if nf is not None and m and n:
|
|
203
|
+
try:
|
|
204
|
+
nfv = float(nf)
|
|
205
|
+
except (TypeError, ValueError):
|
|
206
|
+
nfv = math.nan
|
|
207
|
+
if math.isfinite(nfv) and nfv >= 0:
|
|
208
|
+
return nfv / math.sqrt(1.0 / min(m, cap) + 1.0 / min(n, cap))
|
|
209
|
+
tol = _positive(t.tolerance)
|
|
210
|
+
nt = n or rows
|
|
211
|
+
if tol is not None and nt:
|
|
212
|
+
return tol / math.sqrt(2.0 / min(nt, cap))
|
|
213
|
+
return None
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def noise_threshold(ta: Target, tb: Target, rows_a: float | None,
|
|
217
|
+
rows_b: float | None) -> float:
|
|
218
|
+
"""``noise95``: 95% distance quantile of a two-sample comparison (see module docstring).
|
|
219
|
+
|
|
220
|
+
Falls back to the larger stored tolerance (at least the metric's default tolerance) when
|
|
221
|
+
neither target carries a usable noise floor or tolerance, or a row count is unknown.
|
|
222
|
+
"""
|
|
223
|
+
cap = float(_subsample_caps().get(ta.metric, math.inf))
|
|
224
|
+
us = [u for u in (_unit_noise(ta, rows_a, cap), _unit_noise(tb, rows_b, cap))
|
|
225
|
+
if u is not None]
|
|
226
|
+
if us and rows_a and rows_b:
|
|
227
|
+
return sum(us) / len(us) * math.sqrt(1.0 / min(rows_a, cap) + 1.0 / min(rows_b, cap))
|
|
228
|
+
tols = [x for x in (_positive(ta.tolerance), _positive(tb.tolerance)) if x is not None]
|
|
229
|
+
return max([_default_tolerance(ta.metric), *tols])
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def resolution_step(metric: str, reference: Any, candidate: Any) -> float:
|
|
233
|
+
"""Distance of one step of a lumpy statistic, discounted before testing.
|
|
234
|
+
|
|
235
|
+
``univariate.tail`` stores the 1% / 99% quantiles; on an integer-valued column they move
|
|
236
|
+
in whole units, so a one-unit jump (``1 / scale``) happens between samples of one
|
|
237
|
+
population far more often than a half-normal model allows, and the 10-resample noise
|
|
238
|
+
floor is often exactly 0. When all four stored quantiles are integers, one unit is
|
|
239
|
+
discounted. Every other metric: 0.
|
|
240
|
+
"""
|
|
241
|
+
if metric != "univariate.tail":
|
|
242
|
+
return 0.0
|
|
243
|
+
try:
|
|
244
|
+
vals = [float(v[k]) for v in (reference, candidate) for k in ("q_lo", "q_hi")]
|
|
245
|
+
scale = float(reference.get("scale") or 0.0) or 1.0
|
|
246
|
+
except (TypeError, ValueError, KeyError, AttributeError):
|
|
247
|
+
return 0.0
|
|
248
|
+
if all(math.isfinite(v) and v.is_integer() for v in vals) and scale > 0:
|
|
249
|
+
return 1.0 / scale
|
|
250
|
+
return 0.0
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
#: Association statistics that cannot fall below zero. On two unrelated columns they do not sit
|
|
254
|
+
#: at zero but at a level set by the row count, about ``sqrt(levels / rows)``: 0.05 for eight
|
|
255
|
+
#: groups in 3,000 rows, 0.003 in a million. Two samples of one population with very different
|
|
256
|
+
#: row counts therefore differ by about that much, and the two-sample noise model (which
|
|
257
|
+
#: scales a spread measured at equal sizes) does not see it.
|
|
258
|
+
NULL_LEVEL_METRICS = ("bivariate.correlation_ratio", "bivariate.cramers_v")
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def null_level_step(fp: Fingerprint, target: Target, reference: Any, candidate: Any,
|
|
262
|
+
rows_ref: float | None, rows_cand: float | None) -> float:
|
|
263
|
+
"""Distance expected between two sizes of one population, discounted before testing.
|
|
264
|
+
|
|
265
|
+
For the statistics in ``NULL_LEVEL_METRICS``: the expected value at ``rows`` rows is
|
|
266
|
+
``sqrt(assoc^2 + levels / rows)``, with ``levels`` the groups minus one (the larger of the
|
|
267
|
+
two for Cramér's V) and ``rows`` the rows where both columns are present. ``assoc`` is
|
|
268
|
+
estimated from the side with more rows. The step is the difference of the two expected
|
|
269
|
+
values: close to the whole distance for unrelated columns measured on few rows against
|
|
270
|
+
many, and close to zero when the association is real or the row counts are alike. Every
|
|
271
|
+
other metric, and a pair whose levels the fingerprint does not hold: 0.
|
|
272
|
+
"""
|
|
273
|
+
if target.metric not in NULL_LEVEL_METRICS or not rows_ref or not rows_cand:
|
|
274
|
+
return 0.0
|
|
275
|
+
try:
|
|
276
|
+
a, b = float(reference), float(candidate)
|
|
277
|
+
except (TypeError, ValueError):
|
|
278
|
+
return 0.0
|
|
279
|
+
if not (math.isfinite(a) and math.isfinite(b)) or len(target.columns) != 2:
|
|
280
|
+
return 0.0
|
|
281
|
+
cols = {c.name: c for c in fp.manifest.columns}
|
|
282
|
+
if any(c not in cols for c in target.columns):
|
|
283
|
+
return 0.0
|
|
284
|
+
counts = [len(labels) if (labels := _categories(fp, c)) else 0 for c in target.columns]
|
|
285
|
+
if target.metric == "bivariate.cramers_v":
|
|
286
|
+
if min(counts) < 2:
|
|
287
|
+
return 0.0
|
|
288
|
+
levels = float(max(counts) - 1)
|
|
289
|
+
else:
|
|
290
|
+
grouped = [n for n, c in zip(counts, target.columns)
|
|
291
|
+
if cols[c].logical_type == LogicalType.CATEGORICAL]
|
|
292
|
+
if len(grouped) != 1 or grouped[0] < 2:
|
|
293
|
+
return 0.0
|
|
294
|
+
levels = float(grouped[0] - 1)
|
|
295
|
+
present = 1.0
|
|
296
|
+
for c in target.columns:
|
|
297
|
+
present *= 1.0 - min(max(float(cols[c].null_fraction or 0.0), 0.0), 1.0)
|
|
298
|
+
if present <= 0.0:
|
|
299
|
+
return 0.0
|
|
300
|
+
lvl_ref = min(1.0, levels / (rows_ref * present))
|
|
301
|
+
lvl_cand = min(1.0, levels / (rows_cand * present))
|
|
302
|
+
larger, lvl_larger = (a, lvl_ref) if rows_ref >= rows_cand else (b, lvl_cand)
|
|
303
|
+
assoc2 = max(0.0, larger * larger - lvl_larger)
|
|
304
|
+
return abs(math.sqrt(assoc2 + lvl_ref) - math.sqrt(assoc2 + lvl_cand))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def p_value(distance: float, noise95: float, floor: float) -> float:
|
|
308
|
+
"""Approximate p-value of ``distance`` under no drift; 1 at or below the minimum effect."""
|
|
309
|
+
if distance <= floor + 1e-12:
|
|
310
|
+
return 1.0
|
|
311
|
+
if not math.isfinite(distance) or noise95 <= 0:
|
|
312
|
+
return 0.0
|
|
313
|
+
z = Z95 * distance / (KAPPA * noise95)
|
|
314
|
+
return math.erfc(z / math.sqrt(2.0))
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def bh_cutoff(p_values: list[float], q: float) -> tuple[int, float]:
|
|
318
|
+
"""Benjamini-Hochberg: ``(k, cut)`` with ``k`` rejections and ``p <= cut`` rejected."""
|
|
319
|
+
m = len(p_values)
|
|
320
|
+
if m == 0:
|
|
321
|
+
return 0, q
|
|
322
|
+
k = 0
|
|
323
|
+
for i, p in enumerate(sorted(p_values), start=1):
|
|
324
|
+
if p <= q * i / m:
|
|
325
|
+
k = i
|
|
326
|
+
return k, q * max(k, 1) / m
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def decide_targets(pairs: list[tuple[Target, Target]], rows_a: float | None,
|
|
330
|
+
rows_b: float | None, sensitivity: str | float = "standard", *,
|
|
331
|
+
tolerance_scale: float = 1.0,
|
|
332
|
+
extra_steps: dict[str, float] | None = None,
|
|
333
|
+
) -> tuple[list[TargetResult], list[dict[str, str]], dict[str, dict[str, float]]]:
|
|
334
|
+
"""The drift decision for matched ``(reference, candidate)`` target pairs.
|
|
335
|
+
|
|
336
|
+
This is the rule ``compare`` uses: per-target two-sample noise thresholds, approximate
|
|
337
|
+
p-values and a Benjamini-Hochberg cut at the ``sensitivity`` level. Each result's
|
|
338
|
+
``passed`` is False for a target rejected by the cut. ``tolerance_scale`` widens (> 1) or
|
|
339
|
+
narrows (< 1) the noise model. ``extra_steps`` holds, per target id, a distance discounted
|
|
340
|
+
before testing in addition to ``resolution_step`` (see ``null_level_step``). Targets whose
|
|
341
|
+
distance cannot be computed are returned in
|
|
342
|
+
``errors``; callers must treat errors as inconclusive, never as "no drift". The third
|
|
343
|
+
value holds per-target ``p_values`` and ``noise_thresholds`` keyed by target id.
|
|
344
|
+
"""
|
|
345
|
+
from ectype.fingerprint.targets import compare_values
|
|
346
|
+
|
|
347
|
+
q = resolve_sensitivity(sensitivity)
|
|
348
|
+
scale = float(tolerance_scale)
|
|
349
|
+
measured: list[tuple[Target, Target, float, float, float, float]] = []
|
|
350
|
+
errors: list[dict[str, str]] = []
|
|
351
|
+
for ta, tb in pairs:
|
|
352
|
+
try:
|
|
353
|
+
d = float(compare_values(ta, tb))
|
|
354
|
+
if math.isnan(d):
|
|
355
|
+
raise ValueError("distance is NaN")
|
|
356
|
+
except Exception as exc: # noqa: BLE001 - reported per target
|
|
357
|
+
errors.append({"id": ta.id, "error": f"{type(exc).__name__}: {exc}"})
|
|
358
|
+
continue
|
|
359
|
+
noise = noise_threshold(ta, tb, rows_a, rows_b) * scale
|
|
360
|
+
step = resolution_step(ta.metric, ta.value, tb.value) + (extra_steps or {}).get(ta.id, 0.0)
|
|
361
|
+
measured.append((ta, tb, d, noise, step,
|
|
362
|
+
p_value(max(0.0, d - step), noise, _default_tolerance(ta.metric))))
|
|
363
|
+
_, p_cut = bh_cutoff([m[5] for m in measured], q)
|
|
364
|
+
z_cut = NormalDist().inv_cdf(1.0 - p_cut / 2.0)
|
|
365
|
+
results: list[TargetResult] = []
|
|
366
|
+
for ta, tb, d, noise, step, p in measured:
|
|
367
|
+
decision_tol = step + max(_default_tolerance(ta.metric), KAPPA * noise * z_cut / Z95)
|
|
368
|
+
results.append(TargetResult(ta.id, ta.metric, ta.family or ta.metric, list(ta.columns),
|
|
369
|
+
d, decision_tol, bool(p > p_cut), ta.value, tb.value))
|
|
370
|
+
info = {"p_values": {m[0].id: m[5] for m in measured},
|
|
371
|
+
"noise_thresholds": {m[0].id: m[3] for m in measured}}
|
|
372
|
+
return results, errors, info
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _exceedance(r: TargetResult) -> float:
|
|
376
|
+
if r.passed:
|
|
377
|
+
return 0.0
|
|
378
|
+
ratio = r.ratio
|
|
379
|
+
if not math.isfinite(ratio):
|
|
380
|
+
return 10.0 # cap for errors / infinite distances so rankings stay meaningful
|
|
381
|
+
return max(1e-9, ratio - 1.0)
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
@dataclass
|
|
385
|
+
class DriftReport(ReportShell):
|
|
386
|
+
header: dict[str, Any]
|
|
387
|
+
schema: dict[str, Any]
|
|
388
|
+
policy_warnings: list[str]
|
|
389
|
+
targets: list[TargetResult]
|
|
390
|
+
sections: dict[str, str] # target id -> section in a/b
|
|
391
|
+
unmatched: dict[str, list[str]]
|
|
392
|
+
errors: list[dict[str, str]] = field(default_factory=list)
|
|
393
|
+
title: str = "Drift report"
|
|
394
|
+
#: per-target p-value and two-sample 95% noise threshold (before the BH cut)
|
|
395
|
+
p_values: dict[str, float] = field(default_factory=dict)
|
|
396
|
+
noise_thresholds: dict[str, float] = field(default_factory=dict) # noise95
|
|
397
|
+
sensitivity: str = "standard"
|
|
398
|
+
q: float = SENSITIVITY["standard"]
|
|
399
|
+
|
|
400
|
+
# -- derived views ---------------------------------------------------------------------
|
|
401
|
+
@property
|
|
402
|
+
def drifted_targets(self) -> list[TargetResult]:
|
|
403
|
+
return [r for r in worst_first(self.targets) if not r.passed]
|
|
404
|
+
|
|
405
|
+
@property
|
|
406
|
+
def schema_changed(self) -> bool:
|
|
407
|
+
s = self.schema
|
|
408
|
+
return bool(s["added"] or s["removed"] or s["type_changes"] or s["role_changes"]
|
|
409
|
+
or s["category_changes"])
|
|
410
|
+
|
|
411
|
+
@property
|
|
412
|
+
def drifted(self) -> bool:
|
|
413
|
+
"""Schema changed, or some target is drifted under the BH decision at level ``q``."""
|
|
414
|
+
return self.schema_changed or bool(self.drifted_targets)
|
|
415
|
+
|
|
416
|
+
@property
|
|
417
|
+
def inconclusive(self) -> bool:
|
|
418
|
+
"""True when some matched targets could not be compared (see ``errors``)."""
|
|
419
|
+
return bool(self.errors)
|
|
420
|
+
|
|
421
|
+
@property
|
|
422
|
+
def passed(self) -> bool:
|
|
423
|
+
"""True only when no drift was found *and* every matched target could be compared
|
|
424
|
+
(mirrors the validation report surface; errors fail closed)."""
|
|
425
|
+
return not self.drifted and not self.inconclusive
|
|
426
|
+
|
|
427
|
+
@property
|
|
428
|
+
def decision(self) -> dict[str, Any]:
|
|
429
|
+
n, nd = len(self.targets), len(self.drifted_targets)
|
|
430
|
+
return {"rule": "benjamini-hochberg", "sensitivity": self.sensitivity, "q": self.q,
|
|
431
|
+
"n_tests": n, "n_rejected": nd,
|
|
432
|
+
"p_cut": self.q * max(nd, 1) / n if n else None}
|
|
433
|
+
|
|
434
|
+
def column_ranking(self) -> list[dict[str, Any]]:
|
|
435
|
+
cols: dict[str, dict[str, Any]] = {}
|
|
436
|
+
|
|
437
|
+
def entry(c: str) -> dict[str, Any]:
|
|
438
|
+
return cols.setdefault(c, {"column": c, "score": 0.0, "n_drifted": 0,
|
|
439
|
+
"pair_share": 0.0, "targets": [], "schema": []})
|
|
440
|
+
|
|
441
|
+
for r in self.targets:
|
|
442
|
+
if r.passed:
|
|
443
|
+
continue
|
|
444
|
+
ex = _exceedance(r)
|
|
445
|
+
if len(r.columns) == 1:
|
|
446
|
+
e = entry(r.columns[0])
|
|
447
|
+
e["score"] += ex
|
|
448
|
+
e["n_drifted"] += 1
|
|
449
|
+
e["targets"].append(r.id)
|
|
450
|
+
else:
|
|
451
|
+
for c in r.columns:
|
|
452
|
+
entry(c)["pair_share"] += ex / len(r.columns)
|
|
453
|
+
s = self.schema
|
|
454
|
+
for c in s["added"]:
|
|
455
|
+
entry(c)["schema"].append("added")
|
|
456
|
+
for c in s["removed"]:
|
|
457
|
+
entry(c)["schema"].append("removed")
|
|
458
|
+
for c in s["type_changes"]:
|
|
459
|
+
entry(c)["schema"].append("type")
|
|
460
|
+
for c in s["role_changes"]:
|
|
461
|
+
entry(c)["schema"].append("role")
|
|
462
|
+
for c in s["category_changes"]:
|
|
463
|
+
entry(c)["schema"].append("categories")
|
|
464
|
+
out = [e for e in cols.values() if e["score"] > 0 or e["schema"]]
|
|
465
|
+
return sorted(out, key=lambda e: (-(e["score"] + 10.0 * bool(e["schema"])),
|
|
466
|
+
-e["pair_share"], e["column"]))
|
|
467
|
+
|
|
468
|
+
def pair_ranking(self) -> list[dict[str, Any]]:
|
|
469
|
+
pairs: dict[tuple[str, ...], dict[str, Any]] = {}
|
|
470
|
+
for r in self.targets:
|
|
471
|
+
if len(r.columns) < 2 or r.passed:
|
|
472
|
+
continue
|
|
473
|
+
key = tuple(r.columns)
|
|
474
|
+
e = pairs.setdefault(key, {"columns": list(key), "score": 0.0, "n_drifted": 0,
|
|
475
|
+
"targets": []})
|
|
476
|
+
e["score"] += _exceedance(r)
|
|
477
|
+
e["n_drifted"] += 1
|
|
478
|
+
e["targets"].append(r.id)
|
|
479
|
+
return sorted(pairs.values(), key=lambda e: (-e["score"], e["columns"]))
|
|
480
|
+
|
|
481
|
+
@property
|
|
482
|
+
def drifted_columns(self) -> list[str]:
|
|
483
|
+
return [e["column"] for e in self.column_ranking()]
|
|
484
|
+
|
|
485
|
+
@property
|
|
486
|
+
def drifted_pairs(self) -> list[tuple[str, ...]]:
|
|
487
|
+
return [tuple(e["columns"]) for e in self.pair_ranking()]
|
|
488
|
+
|
|
489
|
+
# -- serialisation -------------------------------------------------------------------
|
|
490
|
+
def to_dict(self, verbose: bool = False) -> dict[str, Any]:
|
|
491
|
+
n = len(self.targets)
|
|
492
|
+
nd = len(self.drifted_targets)
|
|
493
|
+
return json_safe({
|
|
494
|
+
"report": "drift",
|
|
495
|
+
"drifted": self.drifted,
|
|
496
|
+
"passed": self.passed,
|
|
497
|
+
"inconclusive": self.inconclusive,
|
|
498
|
+
"decision": self.decision,
|
|
499
|
+
"header": self.header,
|
|
500
|
+
"schema": self.schema,
|
|
501
|
+
"policy_warnings": list(self.policy_warnings),
|
|
502
|
+
"targets": {"n_matched": n, "n_drifted": nd,
|
|
503
|
+
"drift_rate": nd / n if n else None,
|
|
504
|
+
"unmatched": self.unmatched, "errors": self.errors,
|
|
505
|
+
"results": [dict(r.to_dict(verbose), section=self.sections.get(r.id),
|
|
506
|
+
p_value=self.p_values.get(r.id),
|
|
507
|
+
noise_threshold=self.noise_thresholds.get(r.id))
|
|
508
|
+
for r in worst_first(self.targets)]},
|
|
509
|
+
"localisation": {"columns": self.column_ranking(), "pairs": self.pair_ranking()},
|
|
510
|
+
})
|
|
511
|
+
|
|
512
|
+
def summary(self) -> str:
|
|
513
|
+
h = self.header
|
|
514
|
+
n, nd = len(self.targets), len(self.drifted_targets)
|
|
515
|
+
verdict = ("DETECTED" if self.drifted else
|
|
516
|
+
"INCONCLUSIVE" if self.inconclusive else "none")
|
|
517
|
+
lines = [f"Drift {verdict}"
|
|
518
|
+
f" {str(h.get('a_hash', ''))[:12]} -> {str(h.get('b_hash', ''))[:12]}"
|
|
519
|
+
f" targets drifted {nd}/{n}"
|
|
520
|
+
f" (sensitivity {self.sensitivity}, FDR q={self.q:g})"
|
|
521
|
+
+ (f" errors {len(self.errors)}" if self.errors else "")]
|
|
522
|
+
if self.errors:
|
|
523
|
+
lines.append(f" ! {len(self.errors)} matched target(s) could not be compared; "
|
|
524
|
+
"the comparison is inconclusive:")
|
|
525
|
+
for e in self.errors[:5]:
|
|
526
|
+
lines.append(f" {e['id']}: {e['error']}")
|
|
527
|
+
if len(self.errors) > 5:
|
|
528
|
+
lines.append(f" ... and {len(self.errors) - 5} more")
|
|
529
|
+
s = self.schema
|
|
530
|
+
for key, label in (("added", "added"), ("removed", "removed")):
|
|
531
|
+
if s[key]:
|
|
532
|
+
lines.append(f" columns {label}: {', '.join(s[key])}")
|
|
533
|
+
for c, v in s["type_changes"].items():
|
|
534
|
+
lines.append(f" type change {c}: {v['a']} -> {v['b']}")
|
|
535
|
+
for c, v in s["role_changes"].items():
|
|
536
|
+
lines.append(f" role change {c}: {v['a']} -> {v['b']}")
|
|
537
|
+
for c, v in s["category_changes"].items():
|
|
538
|
+
lines.append(f" categories {c}: +{v['added']} -{v['removed']}")
|
|
539
|
+
if s.get("pseudonymised"):
|
|
540
|
+
lines.append(" pseudonymised columns (tokens differ between fingerprints; compared "
|
|
541
|
+
"by level-frequency profile): " + ", ".join(s["pseudonymised"]))
|
|
542
|
+
for w in self.policy_warnings:
|
|
543
|
+
lines.append(f" ! {w}")
|
|
544
|
+
for e in self.column_ranking()[:5]:
|
|
545
|
+
lines.append(f" column {e['column']:<20} score={e['score']:.3g} "
|
|
546
|
+
f"drifted={e['n_drifted']} {'/'.join(e['schema'])}")
|
|
547
|
+
for e in self.pair_ranking()[:5]:
|
|
548
|
+
lines.append(f" pair {' x '.join(e['columns']):<30} score={e['score']:.3g} "
|
|
549
|
+
f"drifted={e['n_drifted']}")
|
|
550
|
+
return "\n".join(lines)
|
|
551
|
+
|
|
552
|
+
def _html_body(self) -> tuple[str, str]:
|
|
553
|
+
h = self.header
|
|
554
|
+
parts = ['<section class="card">' + meta_list({
|
|
555
|
+
"reference (a)": f"{h.get('a_dataset')} - {h.get('a_hash')}",
|
|
556
|
+
"candidate (b)": f"{h.get('b_dataset')} - {h.get('b_hash')}",
|
|
557
|
+
"policy (a / b)": f"{h.get('a_policy')} / {h.get('b_policy')}",
|
|
558
|
+
"engine version": h.get("engine_version"),
|
|
559
|
+
"rows (a / b)": f"{h.get('a_rows')} / {h.get('b_rows')}",
|
|
560
|
+
"sensitivity": f"{self.sensitivity} (Benjamini-Hochberg q={self.q:g})",
|
|
561
|
+
}) + "</section>"]
|
|
562
|
+
n, nd = len(self.targets), len(self.drifted_targets)
|
|
563
|
+
if self.drifted:
|
|
564
|
+
parts.append(f'<div class="verdict bad">DRIFT DETECTED: {nd} of {n} matched targets '
|
|
565
|
+
"drifted beyond sampling noise"
|
|
566
|
+
+ (" and the schema changed" if self.schema_changed else "")
|
|
567
|
+
+ ".</div>")
|
|
568
|
+
elif self.inconclusive:
|
|
569
|
+
parts.append(f'<div class="verdict bad">INCONCLUSIVE: {len(self.errors)} matched '
|
|
570
|
+
"target(s) could not be compared.</div>")
|
|
571
|
+
else:
|
|
572
|
+
parts.append('<div class="verdict ok">No drift: schema unchanged and every matched '
|
|
573
|
+
"target within sampling noise.</div>")
|
|
574
|
+
if self.errors:
|
|
575
|
+
parts.append('<section class="card"><h2>Comparison errors</h2>'
|
|
576
|
+
+ html_table(["target", "error"],
|
|
577
|
+
[[esc(e["id"]), esc(e["error"])] for e in self.errors])
|
|
578
|
+
+ "</section>")
|
|
579
|
+
for w in self.policy_warnings:
|
|
580
|
+
parts.append(f'<div class="note">{esc(w)}</div>')
|
|
581
|
+
|
|
582
|
+
s = self.schema
|
|
583
|
+
srows = ([[pill(False, text_bad="added"), esc(c), ""] for c in s["added"]]
|
|
584
|
+
+ [[pill(False, text_bad="removed"), esc(c), ""] for c in s["removed"]]
|
|
585
|
+
+ [[pill(False, text_bad="type"), esc(c), esc(f"{v['a']} -> {v['b']}")]
|
|
586
|
+
for c, v in s["type_changes"].items()]
|
|
587
|
+
+ [[pill(False, text_bad="role"), esc(c), esc(f"{v['a']} -> {v['b']}")]
|
|
588
|
+
for c, v in s["role_changes"].items()]
|
|
589
|
+
+ [[pill(False, text_bad="categories"), esc(c),
|
|
590
|
+
esc(f"added {v['added']}; removed {v['removed']}")]
|
|
591
|
+
for c, v in s["category_changes"].items()])
|
|
592
|
+
notes = "".join(f'<div class="note">{esc(x)}</div>' for x in s.get("notes", []))
|
|
593
|
+
parts.append('<section class="card"><h2>Schema drift</h2>' + notes
|
|
594
|
+
+ html_table(["", "column", "change"], srows,
|
|
595
|
+
empty="No schema changes.") + "</section>")
|
|
596
|
+
|
|
597
|
+
crow = [[esc(e["column"]), _fmt(e["score"], 3), str(e["n_drifted"]),
|
|
598
|
+
_fmt(e["pair_share"], 3), esc("/".join(e["schema"]))]
|
|
599
|
+
for e in self.column_ranking()]
|
|
600
|
+
prow = [[esc(" x ".join(e["columns"])), _fmt(e["score"], 3), str(e["n_drifted"])]
|
|
601
|
+
for e in self.pair_ranking()]
|
|
602
|
+
parts.append('<section class="card"><h2>Where the drift is</h2>'
|
|
603
|
+
'<p class="sub">Score = sum of normalised exceedance (distance / tolerance '
|
|
604
|
+
"- 1) over drifted targets.</p>"
|
|
605
|
+
+ html_table(["column", "score", "drifted targets", "pair share",
|
|
606
|
+
"schema"], crow, numeric={1, 2, 3},
|
|
607
|
+
empty="No column-level drift.")
|
|
608
|
+
+ '<h2 style="margin-top:14px">Pairs</h2>'
|
|
609
|
+
+ html_table(["pair", "score", "drifted targets"], prow,
|
|
610
|
+
numeric={1, 2}, empty="No pair-level drift.")
|
|
611
|
+
+ "</section>")
|
|
612
|
+
|
|
613
|
+
rate = (nd / n) if n else None
|
|
614
|
+
unmatched = (f"{len(self.unmatched['only_a'])} only in a, "
|
|
615
|
+
f"{len(self.unmatched['only_b'])} only in b")
|
|
616
|
+
parts.append('<section class="card"><h2>Matched targets</h2>'
|
|
617
|
+
'<p class="sub">Calibration and sealed targets of both fingerprints, '
|
|
618
|
+
"matched by id. Tolerance is the decision distance: the two-sample noise "
|
|
619
|
+
"threshold widened for the number of targets tested (Benjamini-Hochberg "
|
|
620
|
+
f"at q={self.q:g}).</p>"
|
|
621
|
+
+ stats_row({"drifted": f"{nd}/{n}",
|
|
622
|
+
"drift rate": "n/a" if rate is None else f"{100 * rate:.1f}%",
|
|
623
|
+
"unmatched": unmatched})
|
|
624
|
+
+ html_table(["", "metric", "columns", "distance", "tolerance",
|
|
625
|
+
"distance / tol", "note"],
|
|
626
|
+
[[pill(r.passed, "stable", "drift"), *row[1:]]
|
|
627
|
+
for r, row in zip(worst_first(self.targets),
|
|
628
|
+
target_rows(worst_first(self.targets)))],
|
|
629
|
+
numeric={3, 4, 5}, empty="No matched targets.")
|
|
630
|
+
+ "</section>")
|
|
631
|
+
return ("Fingerprint-to-fingerprint comparison; no data involved.", "".join(parts))
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def compare(a: Fingerprint, b: Fingerprint, *, seed: int = 0,
|
|
635
|
+
sensitivity: str | float = "standard") -> DriftReport:
|
|
636
|
+
"""Compare two fingerprints (``a`` = reference, ``b`` = candidate). See module docstring.
|
|
637
|
+
|
|
638
|
+
``sensitivity`` sets the false-discovery rate of the target-drift decision:
|
|
639
|
+
``"strict"`` (q=0.20, flags drift most readily), ``"standard"`` (q=0.05) or ``"lenient"``
|
|
640
|
+
(q=0.01), or a number ``0 < q < 1``. ``seed`` is accepted for API symmetry; the
|
|
641
|
+
comparison is deterministic and data-free.
|
|
642
|
+
"""
|
|
643
|
+
q = resolve_sensitivity(sensitivity)
|
|
644
|
+
sens_name = sensitivity_label(sensitivity)
|
|
645
|
+
ma, mb = a.manifest, b.manifest
|
|
646
|
+
ca = {c.name: c for c in ma.columns}
|
|
647
|
+
cb = {c.name: c for c in mb.columns}
|
|
648
|
+
|
|
649
|
+
# ---- schema ---------------------------------------------------------------------------
|
|
650
|
+
added = [c for c in cb if c not in ca]
|
|
651
|
+
removed = [c for c in ca if c not in cb]
|
|
652
|
+
type_changes: dict[str, dict[str, str]] = {}
|
|
653
|
+
role_changes: dict[str, dict[str, str]] = {}
|
|
654
|
+
category_changes: dict[str, dict[str, list[str]]] = {}
|
|
655
|
+
notes: list[str] = []
|
|
656
|
+
# columns whose labels are stand-in tokens in either fingerprint (never comparable)
|
|
657
|
+
pseudonyms = {name for name in ca if name in cb
|
|
658
|
+
and Role.PSEUDONYM in (ca[name].role, cb[name].role)}
|
|
659
|
+
for name in (c for c in ca if c in cb):
|
|
660
|
+
x, y = ca[name], cb[name]
|
|
661
|
+
if x.logical_type != y.logical_type:
|
|
662
|
+
type_changes[name] = {"a": str(x.logical_type), "b": str(y.logical_type)}
|
|
663
|
+
if x.role != y.role:
|
|
664
|
+
role_changes[name] = {"a": str(x.role), "b": str(y.role)}
|
|
665
|
+
if name in pseudonyms:
|
|
666
|
+
notes.append(f"{name}: pseudonymised (stand-in tokens are assigned independently "
|
|
667
|
+
"in every fingerprint): category sets not compared; label "
|
|
668
|
+
"frequencies compared as a sorted level-frequency profile")
|
|
669
|
+
continue
|
|
670
|
+
sa, sb = _categories(a, name), _categories(b, name)
|
|
671
|
+
if sa is None and sb is None:
|
|
672
|
+
continue
|
|
673
|
+
if sa is None or sb is None:
|
|
674
|
+
notes.append(f"{name}: category set available in only one fingerprint")
|
|
675
|
+
continue
|
|
676
|
+
plus = sorted(set(sb) - set(sa))
|
|
677
|
+
minus = sorted(set(sa) - set(sb))
|
|
678
|
+
if plus or minus:
|
|
679
|
+
category_changes[name] = {"added": plus, "removed": minus}
|
|
680
|
+
|
|
681
|
+
# ---- policy -----------------------------------------------------------------------------
|
|
682
|
+
pa = ma.disclosure_policy.model_dump(mode="json")
|
|
683
|
+
pb = mb.disclosure_policy.model_dump(mode="json")
|
|
684
|
+
policy_warnings = []
|
|
685
|
+
diff = sorted(k for k in set(pa) | set(pb) if pa.get(k) != pb.get(k))
|
|
686
|
+
if diff:
|
|
687
|
+
policy_warnings.append(
|
|
688
|
+
f"disclosure policies differ ({pa.get('profile')} vs {pb.get('profile')}; fields: "
|
|
689
|
+
f"{', '.join(diff)}): stored summaries are coarsened differently, so small "
|
|
690
|
+
"distances may reflect policy rather than data")
|
|
691
|
+
|
|
692
|
+
# ---- targets ----------------------------------------------------------------------------
|
|
693
|
+
rows_a = _positive(ma.dataset.source_records)
|
|
694
|
+
rows_b = _positive(mb.dataset.source_records)
|
|
695
|
+
ta_all, tb_all = _all_targets(a), _all_targets(b)
|
|
696
|
+
sections: dict[str, str] = {}
|
|
697
|
+
pairs: list[tuple[Target, Target]] = []
|
|
698
|
+
label_level: list[str] = []
|
|
699
|
+
for tid in sorted(set(ta_all) & set(tb_all)):
|
|
700
|
+
(ta, sa_), (tb, sb_) = ta_all[tid], tb_all[tid]
|
|
701
|
+
if pseudonyms & set(ta.columns) and ta.metric == tb.metric:
|
|
702
|
+
if ta.metric == "bivariate.contingency":
|
|
703
|
+
label_level.append(tid) # cells are keyed by labels: not comparable
|
|
704
|
+
continue
|
|
705
|
+
if ta.metric == "univariate.frequencies":
|
|
706
|
+
from ectype.validation.metrics.univariate import rank_profiles
|
|
707
|
+
|
|
708
|
+
try:
|
|
709
|
+
va, vb = rank_profiles(ta.value, tb.value)
|
|
710
|
+
ta = ta.model_copy(update={"value": va})
|
|
711
|
+
tb = tb.model_copy(update={"value": vb})
|
|
712
|
+
except Exception: # noqa: BLE001 - malformed values fail in decide_targets
|
|
713
|
+
pass
|
|
714
|
+
sections[tid] = sa_ if sa_ == sb_ else f"{sa_}/{sb_}"
|
|
715
|
+
pairs.append((ta, tb))
|
|
716
|
+
if label_level:
|
|
717
|
+
notes.append(f"{len(label_level)} label-level target(s) on pseudonymised columns not "
|
|
718
|
+
f"compared (bivariate.contingency): {', '.join(label_level[:5])}"
|
|
719
|
+
+ (" ..." if len(label_level) > 5 else ""))
|
|
720
|
+
steps = {ta.id: null_level_step(a, ta, ta.value, tb.value, rows_a, rows_b)
|
|
721
|
+
for ta, tb in pairs if ta.metric in NULL_LEVEL_METRICS}
|
|
722
|
+
results, errors, info = decide_targets(pairs, rows_a, rows_b, q, extra_steps=steps)
|
|
723
|
+
unmatched = {"only_a": sorted(set(ta_all) - set(tb_all)),
|
|
724
|
+
"only_b": sorted(set(tb_all) - set(ta_all))}
|
|
725
|
+
|
|
726
|
+
header = {
|
|
727
|
+
"a_hash": a.content_hash(), "b_hash": b.content_hash(),
|
|
728
|
+
"a_dataset": ma.dataset.name, "b_dataset": mb.dataset.name,
|
|
729
|
+
"a_rows": ma.dataset.source_records, "b_rows": mb.dataset.source_records,
|
|
730
|
+
"a_policy": ma.disclosure_policy.profile, "b_policy": mb.disclosure_policy.profile,
|
|
731
|
+
"engine_version": __version__, "seed": seed,
|
|
732
|
+
}
|
|
733
|
+
schema = {"added": added, "removed": removed, "type_changes": type_changes,
|
|
734
|
+
"role_changes": role_changes, "category_changes": category_changes,
|
|
735
|
+
"notes": notes, "pseudonymised": sorted(pseudonyms)}
|
|
736
|
+
return DriftReport(header=header, schema=schema, policy_warnings=policy_warnings,
|
|
737
|
+
targets=results, sections=sections, unmatched=unmatched, errors=errors,
|
|
738
|
+
p_values=info["p_values"],
|
|
739
|
+
noise_thresholds=info["noise_thresholds"],
|
|
740
|
+
sensitivity=sens_name, q=q)
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
__all__ = ["SENSITIVITY", "DriftReport", "all_targets", "bh_cutoff", "compare",
|
|
744
|
+
"decide_targets", "fingerprint_categories",
|
|
745
|
+
"noise_threshold", "p_value",
|
|
746
|
+
"resolution_step", "resolve_sensitivity", "sensitivity_label"]
|