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,661 @@
|
|
|
1
|
+
"""Constraint inference (M16): candidate constraints as *confirmable suggestions*.
|
|
2
|
+
|
|
3
|
+
``suggest_constraints`` screens a set of candidate relationships and returns
|
|
4
|
+
:class:`~ectype.fingerprint.schema.SuggestedConstraint` entries. Nothing returned here
|
|
5
|
+
is binding: a suggestion becomes a hard constraint only through ``Fingerprint.confirm_constraint``
|
|
6
|
+
or a manifest edit (design doc section 3.6).
|
|
7
|
+
|
|
8
|
+
Candidate families (``family``)
|
|
9
|
+
-------------------------------
|
|
10
|
+
* ``ordering`` ``a <= b`` / ``a < b`` for numeric-numeric or same-kind temporal pairs.
|
|
11
|
+
* ``bound`` ``col >= 0``, ``col > 0``, ``col >= 1``, ``col <= 1``, ``col <= 100``: round
|
|
12
|
+
"natural" bounds only. Observed extremes are never emitted.
|
|
13
|
+
* ``identity`` ``c == a + b`` and ``c == a * b`` over numeric triples (subtraction is covered:
|
|
14
|
+
``c == a - b`` is the same relation as ``a == b + c``), with a tolerance derived from the
|
|
15
|
+
detected decimals. Triples are limited to compatible scales and screened on a row sample
|
|
16
|
+
before the full check.
|
|
17
|
+
* ``nullability`` ``is_not_null(a) implies is_not_null(b)``, and for low-cardinality
|
|
18
|
+
categoricals ``x == 'v' implies is_not_null(y)`` and ``is_not_null(y) implies x == 'v'``.
|
|
19
|
+
* ``fd`` functional dependency between categoricals (``city -> region``). The mapping
|
|
20
|
+
itself is never stored (only its size); it is not expressible in the v0.1 grammar, so the
|
|
21
|
+
expression is the no-op ``true`` and ``evidence["expressible"]`` is ``False``.
|
|
22
|
+
* ``unique`` a uniqueness candidate, evidence only (expression ``true``).
|
|
23
|
+
|
|
24
|
+
Multiplicity-aware confidence
|
|
25
|
+
-----------------------------
|
|
26
|
+
For each candidate the number of violations ``v`` on ``n`` supporting rows is compared with a
|
|
27
|
+
simple null model giving a per-row violation probability ``p0``:
|
|
28
|
+
|
|
29
|
+
* ordering / identity: a permutation estimate (the partner column is shuffled a few times);
|
|
30
|
+
* bound: the values in a band just inside the bound, extrapolated past it with an exponential
|
|
31
|
+
tail model (``_tail_continuation``): if the support continued past the bound, about that
|
|
32
|
+
fraction of rows would fall on the other side;
|
|
33
|
+
* nullability: independence of the two null / value indicators;
|
|
34
|
+
* fd: a permutation estimate of the non-modal rate within determinant groups;
|
|
35
|
+
* unique: a birthday bound over a coarse estimate of the value range.
|
|
36
|
+
|
|
37
|
+
``p_chance = P(Binomial(n, p0) <= v)`` is the probability that the relationship would hold this
|
|
38
|
+
well by chance. A Bonferroni correction over ``candidates_screened`` (all candidates of all
|
|
39
|
+
families) gives ``p_adj = min(1, m * p_chance)`` and ``confidence = 1 - p_adj``. Labels:
|
|
40
|
+
``high`` for confidence >= 0.99, ``medium`` >= 0.9, else ``low``. Relationships with a small
|
|
41
|
+
violation rate (<= 0.1 %) are kept as *soft* suggestions: their violations are recorded and
|
|
42
|
+
their label is capped at ``medium``.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
from __future__ import annotations
|
|
46
|
+
|
|
47
|
+
import hashlib
|
|
48
|
+
import math
|
|
49
|
+
from collections.abc import Callable
|
|
50
|
+
from dataclasses import dataclass, field
|
|
51
|
+
from functools import partial
|
|
52
|
+
from itertools import combinations, permutations
|
|
53
|
+
from typing import Any, cast
|
|
54
|
+
|
|
55
|
+
import numpy as np
|
|
56
|
+
import polars as pl
|
|
57
|
+
from scipy import stats
|
|
58
|
+
|
|
59
|
+
from ectype.fingerprint.disclosure import coarsen, resolve_policy
|
|
60
|
+
from ectype.fingerprint.expressions import (
|
|
61
|
+
Binary,
|
|
62
|
+
Call,
|
|
63
|
+
Column,
|
|
64
|
+
Literal,
|
|
65
|
+
Node,
|
|
66
|
+
check,
|
|
67
|
+
unparse,
|
|
68
|
+
)
|
|
69
|
+
from ectype.fingerprint.schema import (
|
|
70
|
+
ColumnSchema,
|
|
71
|
+
DisclosurePolicySpec,
|
|
72
|
+
SuggestedConstraint,
|
|
73
|
+
)
|
|
74
|
+
from ectype.io.values import category_labels, column_to_values
|
|
75
|
+
from ectype.rng import stream
|
|
76
|
+
from ectype.types import LogicalType, Role
|
|
77
|
+
|
|
78
|
+
__all__ = ["suggest_constraints", "MAX_SUGGESTIONS", "SOFT_VIOLATION_RATE"]
|
|
79
|
+
|
|
80
|
+
MAX_SUGGESTIONS = 50
|
|
81
|
+
SOFT_VIOLATION_RATE = 0.001 # at most 0.1 % violations for a "soft" suggestion
|
|
82
|
+
MIN_CONFIDENCE = 0.5 # suggestions below this are dropped
|
|
83
|
+
HIGH_CONFIDENCE = 0.99
|
|
84
|
+
MEDIUM_CONFIDENCE = 0.9
|
|
85
|
+
SOFT_CONFIDENCE_CAP = 0.98 # soft suggestions never reach the "high" label
|
|
86
|
+
N_SHUFFLES = 3
|
|
87
|
+
MIN_SUPPORT = 20
|
|
88
|
+
IDENTITY_SCREEN_ROWS = 256
|
|
89
|
+
MAX_LOW_CARDINALITY = 20
|
|
90
|
+
MAX_FD_LEVELS = 1000
|
|
91
|
+
BOUND_BAND_FRACTION = 0.1 # band width as a fraction of the 10-90 % spread
|
|
92
|
+
BOUND_TAIL_MIN_K = 10 # the bound tail model uses the max(10, sqrt(n)) nearest values
|
|
93
|
+
UNIQUE_MIN_ROWS = 50
|
|
94
|
+
|
|
95
|
+
_RELATIONAL_ROLES = (Role.FEATURE, Role.DERIVED)
|
|
96
|
+
_FAMILY_ORDER = {"identity": 0, "ordering": 1, "nullability": 2, "bound": 3, "fd": 4, "unique": 5}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------------------------
|
|
100
|
+
# Internal records
|
|
101
|
+
# ---------------------------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass
|
|
105
|
+
class _Raw:
|
|
106
|
+
family: str
|
|
107
|
+
expression: str
|
|
108
|
+
support: int
|
|
109
|
+
violations: int
|
|
110
|
+
log_p: float # natural log of the chance probability (unadjusted)
|
|
111
|
+
description: str
|
|
112
|
+
evidence: dict[str, Any] = field(default_factory=dict)
|
|
113
|
+
expressible: bool = True
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@dataclass
|
|
117
|
+
class _Num:
|
|
118
|
+
values: np.ndarray # float64, NaN for null (temporal: common unit)
|
|
119
|
+
kind: str # "num" | "date" | "datetime"
|
|
120
|
+
tz: str | None
|
|
121
|
+
col: ColumnSchema
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass
|
|
125
|
+
class _Ctx:
|
|
126
|
+
df: pl.DataFrame
|
|
127
|
+
n: int
|
|
128
|
+
policy: DisclosurePolicySpec
|
|
129
|
+
seed: int
|
|
130
|
+
by_name: dict[str, ColumnSchema]
|
|
131
|
+
nums: dict[str, _Num]
|
|
132
|
+
cats: dict[str, tuple[np.ndarray, list[str]]] # name -> (codes with -1 for null, labels)
|
|
133
|
+
nulls: dict[str, np.ndarray]
|
|
134
|
+
soft_max: int
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
# ---------------------------------------------------------------------------------------------
|
|
138
|
+
# Helpers
|
|
139
|
+
# ---------------------------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _col(name: str) -> Column:
|
|
143
|
+
return Column(name)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _text(node: Node) -> str:
|
|
147
|
+
return unparse(node)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _allowed_violations(n: int) -> int:
|
|
151
|
+
return int(math.floor(SOFT_VIOLATION_RATE * n))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _log_chance(v: int, n: int, p0: float) -> float:
|
|
155
|
+
"""ln P(Binomial(n, p0) <= v)."""
|
|
156
|
+
p0 = float(min(max(p0, 1e-300), 1.0))
|
|
157
|
+
if p0 >= 1.0:
|
|
158
|
+
return 0.0 if v >= n else -math.inf
|
|
159
|
+
return float(min(0.0, stats.binom.logcdf(v, n, p0)))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _rate(hits: float, trials: float) -> float:
|
|
163
|
+
"""Violation-rate estimate with a half pseudo-count (never exactly 0 or 1)."""
|
|
164
|
+
return (hits + 0.5) / (trials + 1.0)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _c(x: float, policy: DisclosurePolicySpec) -> float:
|
|
168
|
+
return coarsen(float(x), policy) if math.isfinite(x) else float(x)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _is_numeric_dtype(dt: pl.DataType) -> bool:
|
|
172
|
+
return dt.is_numeric() and dt != pl.Boolean
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _prepare(df: pl.DataFrame, columns: list[ColumnSchema], policy: DisclosurePolicySpec,
|
|
176
|
+
seed: int) -> _Ctx:
|
|
177
|
+
n = df.height
|
|
178
|
+
by_name = {c.name: c for c in columns if c.name in df.columns}
|
|
179
|
+
nums: dict[str, _Num] = {}
|
|
180
|
+
cats: dict[str, tuple[np.ndarray, list[str]]] = {}
|
|
181
|
+
nulls: dict[str, np.ndarray] = {}
|
|
182
|
+
for name, col in by_name.items():
|
|
183
|
+
s = df.get_column(name)
|
|
184
|
+
if col.role == Role.EXCLUDED:
|
|
185
|
+
continue
|
|
186
|
+
nulls[name] = s.is_null().to_numpy()
|
|
187
|
+
if col.role not in _RELATIONAL_ROLES:
|
|
188
|
+
continue
|
|
189
|
+
lt = col.logical_type
|
|
190
|
+
dt = s.dtype
|
|
191
|
+
if lt in (LogicalType.CONTINUOUS, LogicalType.DISCRETE) and _is_numeric_dtype(dt):
|
|
192
|
+
v = column_to_values(s, col)
|
|
193
|
+
nums[name] = _Num(v, "num", None, col)
|
|
194
|
+
elif lt == LogicalType.DATETIME and (dt == pl.Date or isinstance(dt, pl.Datetime)):
|
|
195
|
+
v = column_to_values(s, col)
|
|
196
|
+
kind = "date" if dt == pl.Date else "datetime"
|
|
197
|
+
tz = getattr(dt, "time_zone", None)
|
|
198
|
+
nums[name] = _Num(v, kind, tz, col)
|
|
199
|
+
elif lt == LogicalType.CATEGORICAL:
|
|
200
|
+
labels = category_labels(s)
|
|
201
|
+
uniq = labels.drop_nulls().unique().sort().to_list()
|
|
202
|
+
if 2 <= len(uniq) <= MAX_FD_LEVELS:
|
|
203
|
+
lookup = {u: i for i, u in enumerate(uniq)}
|
|
204
|
+
codes = np.array([-1 if x is None else lookup[x] for x in labels.to_list()],
|
|
205
|
+
dtype=np.int64)
|
|
206
|
+
cats[name] = (codes, [str(u) for u in uniq])
|
|
207
|
+
return _Ctx(df=df, n=n, policy=policy, seed=seed, by_name=by_name, nums=nums, cats=cats,
|
|
208
|
+
nulls=nulls, soft_max=_allowed_violations(n))
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
# ---------------------------------------------------------------------------------------------
|
|
212
|
+
# Families
|
|
213
|
+
# ---------------------------------------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _ordering(ctx: _Ctx, a: str, b: str) -> list[_Raw]:
|
|
217
|
+
"""``a <= b`` / ``a < b`` and the reverse direction (4 candidates)."""
|
|
218
|
+
x, y = ctx.nums[a].values, ctx.nums[b].values
|
|
219
|
+
ok = np.isfinite(x) & np.isfinite(y)
|
|
220
|
+
n = int(ok.sum())
|
|
221
|
+
if n < MIN_SUPPORT:
|
|
222
|
+
return []
|
|
223
|
+
x, y = x[ok], y[ok]
|
|
224
|
+
rng = stream(ctx.seed, "constraints", "ordering", a, b)
|
|
225
|
+
perms = [y[rng.permutation(n)] for _ in range(N_SHUFFLES)]
|
|
226
|
+
trials = n * N_SHUFFLES
|
|
227
|
+
out: list[_Raw] = []
|
|
228
|
+
for lo, hi, lo_name, hi_name in ((x, y, a, b), (y, x, b, a)):
|
|
229
|
+
gt = int(np.sum(lo > hi))
|
|
230
|
+
ge = int(np.sum(lo >= hi))
|
|
231
|
+
if gt > ctx.soft_max:
|
|
232
|
+
continue
|
|
233
|
+
if lo is x:
|
|
234
|
+
p_gt = _rate(sum(int(np.sum(x > p)) for p in perms), trials)
|
|
235
|
+
p_ge = _rate(sum(int(np.sum(x >= p)) for p in perms), trials)
|
|
236
|
+
else:
|
|
237
|
+
p_gt = _rate(sum(int(np.sum(p > x)) for p in perms), trials)
|
|
238
|
+
p_ge = _rate(sum(int(np.sum(p >= x)) for p in perms), trials)
|
|
239
|
+
if ge <= ctx.soft_max:
|
|
240
|
+
op, v, p0 = "<", ge, p_ge
|
|
241
|
+
else:
|
|
242
|
+
op, v, p0 = "<=", gt, p_gt
|
|
243
|
+
expr = _text(Binary(op, _col(lo_name), _col(hi_name)))
|
|
244
|
+
out.append(_Raw(
|
|
245
|
+
family="ordering", expression=expr, support=n, violations=v,
|
|
246
|
+
log_p=_log_chance(v, n, p0),
|
|
247
|
+
description=f"{lo_name} {op} {hi_name}",
|
|
248
|
+
evidence={"method": "permutation", "shuffles": N_SHUFFLES,
|
|
249
|
+
"null_violation_rate": _c(p0, ctx.policy)},
|
|
250
|
+
))
|
|
251
|
+
return out
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
_LOWER = ((1.0, ">="), (0.0, ">"), (0.0, ">=")) # strongest first
|
|
255
|
+
_UPPER = ((1.0, "<="), (100.0, "<="))
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _bound(ctx: _Ctx, name: str) -> list[_Raw]:
|
|
259
|
+
"""Round natural bounds; at most one lower and one upper bound per column."""
|
|
260
|
+
v = ctx.nums[name].values
|
|
261
|
+
v = v[np.isfinite(v)]
|
|
262
|
+
n = int(v.size)
|
|
263
|
+
if n < MIN_SUPPORT:
|
|
264
|
+
return []
|
|
265
|
+
q10, q90 = np.quantile(v, [0.1, 0.9])
|
|
266
|
+
h = BOUND_BAND_FRACTION * float(q90 - q10)
|
|
267
|
+
if not h > 0:
|
|
268
|
+
return []
|
|
269
|
+
out: list[_Raw] = []
|
|
270
|
+
for cands, side in ((_LOWER, "lower"), (_UPPER, "upper")):
|
|
271
|
+
best: _Raw | None = None
|
|
272
|
+
for rank, (b, op) in enumerate(cands):
|
|
273
|
+
if op == ">=":
|
|
274
|
+
viol = int(np.sum(v < b))
|
|
275
|
+
inside = v[(v >= b) & (v <= b + h)] - b
|
|
276
|
+
elif op == ">":
|
|
277
|
+
viol = int(np.sum(v <= b))
|
|
278
|
+
inside = v[(v > b) & (v <= b + h)] - b
|
|
279
|
+
else:
|
|
280
|
+
viol = int(np.sum(v > b))
|
|
281
|
+
inside = b - v[(v <= b) & (v >= b - h)]
|
|
282
|
+
band = int(inside.size)
|
|
283
|
+
if viol > ctx.soft_max or band == 0:
|
|
284
|
+
continue
|
|
285
|
+
near = np.sort(inside)[:max(BOUND_TAIL_MIN_K, math.ceil(math.sqrt(n)))]
|
|
286
|
+
p0 = _rate(near.size * _tail_continuation(near), n)
|
|
287
|
+
lit = Literal(int(b), "int")
|
|
288
|
+
expr = _text(Binary(op, _col(name), lit))
|
|
289
|
+
raw = _Raw(
|
|
290
|
+
family="bound", expression=expr, support=n, violations=viol,
|
|
291
|
+
log_p=_log_chance(viol, n, p0),
|
|
292
|
+
description=f"{side} bound {name} {op} {int(b)}",
|
|
293
|
+
evidence={"method": "boundary_density", "side": side,
|
|
294
|
+
"null_violation_rate": _c(p0, ctx.policy), "strength_rank": rank},
|
|
295
|
+
)
|
|
296
|
+
if best is None or raw.log_p < best.log_p - 1e-9:
|
|
297
|
+
best = raw
|
|
298
|
+
if best is not None:
|
|
299
|
+
out.append(best)
|
|
300
|
+
return out
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _tail_continuation(dist: np.ndarray) -> float:
|
|
304
|
+
"""Share of the band mass expected beyond the bound if the support continued past it.
|
|
305
|
+
|
|
306
|
+
``dist`` are the distances from the bound (>= 0) of the ``k`` values nearest to it
|
|
307
|
+
(``k = max(BOUND_TAIL_MIN_K, sqrt(n))``, within the band). The tail is modelled as
|
|
308
|
+
exponential towards the bound: conditional on lying below the band edge ``d_max`` the
|
|
309
|
+
distance ``d_max - d`` is exponential with MLE scale ``beta = mean(d_max - d)``, so the mass
|
|
310
|
+
beyond the bound is ``k * exp(-d_max / beta)``. A tail that thins out before the bound
|
|
311
|
+
(e.g. a lognormal near 1) gives little mass beyond it, so a bound the data merely has not
|
|
312
|
+
reached yet is not reported with high confidence; mass piled up at the bound gives ~1.
|
|
313
|
+
"""
|
|
314
|
+
d = np.asarray(dist, dtype=float)
|
|
315
|
+
if d.size == 0:
|
|
316
|
+
return 0.0
|
|
317
|
+
d_max = float(d.max())
|
|
318
|
+
if d_max <= 0.0:
|
|
319
|
+
return 1.0 # everything sits on the bound
|
|
320
|
+
beta = float(np.mean(d_max - d))
|
|
321
|
+
if beta <= 0.0:
|
|
322
|
+
return 0.0
|
|
323
|
+
return float(math.exp(-d_max / beta))
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _scale(v: np.ndarray) -> float:
|
|
327
|
+
a = np.abs(v[np.isfinite(v)])
|
|
328
|
+
if a.size == 0:
|
|
329
|
+
return 0.0
|
|
330
|
+
return float(np.median(a)) or float(np.mean(a))
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _identity_tolerance(c: ColumnSchema, a: ColumnSchema, b: ColumnSchema
|
|
334
|
+
) -> tuple[str, float, float]:
|
|
335
|
+
"""Return (mode, abs_tol, rel_tol). mode: "exact" | "abs" | "rel"."""
|
|
336
|
+
if all(col.integer_valued or col.decimals == 0 for col in (a, b, c)):
|
|
337
|
+
return "exact", 0.0, 0.0
|
|
338
|
+
if c.decimals is not None and c.decimals <= 6:
|
|
339
|
+
return "abs", float(10.0 ** -c.decimals), 0.0
|
|
340
|
+
return "rel", 1e-9, 1e-6
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _identity_node(op: str, c: str, a: str, b: str, mode: str, atol: float, rtol: float) -> Node:
|
|
344
|
+
rhs = Binary(op, _col(a), _col(b))
|
|
345
|
+
if mode == "exact":
|
|
346
|
+
return Binary("==", _col(c), rhs)
|
|
347
|
+
diff = Call("abs", (Binary("-", _col(c), rhs),))
|
|
348
|
+
if mode == "abs":
|
|
349
|
+
return Binary("<=", diff, Literal(atol, "float"))
|
|
350
|
+
tol = Binary("+", Binary("*", Literal(rtol, "float"), Call("abs", (_col(c),))),
|
|
351
|
+
Literal(atol, "float"))
|
|
352
|
+
return Binary("<=", diff, tol)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _identity(ctx: _Ctx, op: str, c: str, a: str, b: str, screen_idx: np.ndarray) -> list[_Raw]:
|
|
356
|
+
nc, na, nb = ctx.nums[c], ctx.nums[a], ctx.nums[b]
|
|
357
|
+
sc, sa, sb = _scale(nc.values), _scale(na.values), _scale(nb.values)
|
|
358
|
+
if min(sc, sa, sb) <= 0:
|
|
359
|
+
return []
|
|
360
|
+
if op == "+":
|
|
361
|
+
if abs(math.log10(sc) - math.log10(max(sa, sb))) > 1.0:
|
|
362
|
+
return []
|
|
363
|
+
elif abs(math.log10(sc) - (math.log10(sa) + math.log10(sb))) > 1.5:
|
|
364
|
+
return []
|
|
365
|
+
mode, atol, rtol = _identity_tolerance(nc.col, na.col, nb.col)
|
|
366
|
+
|
|
367
|
+
def resid(cv: np.ndarray, av: np.ndarray, bv: np.ndarray) -> np.ndarray:
|
|
368
|
+
f = av + bv if op == "+" else av * bv
|
|
369
|
+
return np.abs(cv - f) - (atol + rtol * np.abs(cv)) * (1 + 1e-9)
|
|
370
|
+
|
|
371
|
+
# fast screen on a row sample
|
|
372
|
+
cs, as_, bs = nc.values[screen_idx], na.values[screen_idx], nb.values[screen_idx]
|
|
373
|
+
ok = np.isfinite(cs) & np.isfinite(as_) & np.isfinite(bs)
|
|
374
|
+
if ok.sum() < min(MIN_SUPPORT, len(screen_idx)) or \
|
|
375
|
+
int(np.sum(resid(cs[ok], as_[ok], bs[ok]) > 0)) > 1:
|
|
376
|
+
return []
|
|
377
|
+
ok = np.isfinite(nc.values) & np.isfinite(na.values) & np.isfinite(nb.values)
|
|
378
|
+
n = int(ok.sum())
|
|
379
|
+
if n < MIN_SUPPORT:
|
|
380
|
+
return []
|
|
381
|
+
cv, av, bv = nc.values[ok], na.values[ok], nb.values[ok]
|
|
382
|
+
v = int(np.sum(resid(cv, av, bv) > 0))
|
|
383
|
+
if v > ctx.soft_max:
|
|
384
|
+
return []
|
|
385
|
+
rng = stream(ctx.seed, "constraints", "identity", op, c, a, b)
|
|
386
|
+
hits = sum(int(np.sum(resid(cv[rng.permutation(n)], av, bv) > 0)) for _ in range(N_SHUFFLES))
|
|
387
|
+
p0 = _rate(hits, n * N_SHUFFLES)
|
|
388
|
+
node = _identity_node(op, c, a, b, mode, atol, rtol)
|
|
389
|
+
return [_Raw(
|
|
390
|
+
family="identity", expression=_text(node), support=n, violations=v,
|
|
391
|
+
log_p=_log_chance(v, n, p0),
|
|
392
|
+
description=f"{c} == {a} {op} {b}",
|
|
393
|
+
evidence={"method": "permutation", "shuffles": N_SHUFFLES,
|
|
394
|
+
"null_violation_rate": _c(p0, ctx.policy), "tolerance_mode": mode,
|
|
395
|
+
"abs_tolerance": atol, "rel_tolerance": rtol},
|
|
396
|
+
)]
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def _null_implies(ctx: _Ctx, a: str, b: str) -> list[_Raw]:
|
|
400
|
+
"""``is_not_null(a) implies is_not_null(b)``."""
|
|
401
|
+
na, nb = ctx.nulls[a], ctx.nulls[b]
|
|
402
|
+
n = ctx.n
|
|
403
|
+
v = int(np.sum(~na & nb))
|
|
404
|
+
if v > ctx.soft_max:
|
|
405
|
+
return []
|
|
406
|
+
p0 = float(np.mean(~na)) * float(np.mean(nb))
|
|
407
|
+
expr = _text(Binary("implies", Call("is_not_null", (_col(a),)),
|
|
408
|
+
Call("is_not_null", (_col(b),))))
|
|
409
|
+
return [_Raw(
|
|
410
|
+
family="nullability", expression=expr, support=n, violations=v,
|
|
411
|
+
log_p=_log_chance(v, n, p0),
|
|
412
|
+
description=f"{b} is present whenever {a} is present",
|
|
413
|
+
evidence={"method": "independence", "null_violation_rate": _c(p0, ctx.policy)},
|
|
414
|
+
)]
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _value_literal(ctx: _Ctx, x: str, label: str) -> Literal | None:
|
|
418
|
+
dt = ctx.df.schema[x]
|
|
419
|
+
if dt == pl.String or isinstance(dt, pl.Categorical | pl.Enum):
|
|
420
|
+
return Literal(label, "str")
|
|
421
|
+
if dt.is_integer():
|
|
422
|
+
try:
|
|
423
|
+
return Literal(int(label), "int")
|
|
424
|
+
except ValueError:
|
|
425
|
+
return None
|
|
426
|
+
return None
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _value_implies(ctx: _Ctx, x: str, code: int, y: str) -> list[_Raw]:
|
|
430
|
+
"""``x == 'v' implies is_not_null(y)`` and ``is_not_null(y) implies x == 'v'``."""
|
|
431
|
+
codes, labels = ctx.cats[x]
|
|
432
|
+
lit = _value_literal(ctx, x, labels[code])
|
|
433
|
+
if lit is None:
|
|
434
|
+
return []
|
|
435
|
+
n = ctx.n
|
|
436
|
+
is_v = codes == code
|
|
437
|
+
ynull = ctx.nulls[y]
|
|
438
|
+
eq = Binary("==", _col(x), lit)
|
|
439
|
+
notnull_y = Call("is_not_null", (_col(y),))
|
|
440
|
+
out: list[_Raw] = []
|
|
441
|
+
# x == v implies y not null
|
|
442
|
+
v1 = int(np.sum(is_v & ynull))
|
|
443
|
+
if v1 <= ctx.soft_max:
|
|
444
|
+
p0 = float(np.mean(is_v)) * float(np.mean(ynull))
|
|
445
|
+
out.append(_Raw(
|
|
446
|
+
family="nullability", expression=_text(Binary("implies", eq, notnull_y)),
|
|
447
|
+
support=n, violations=v1, log_p=_log_chance(v1, n, p0),
|
|
448
|
+
description=f"{y} is present whenever {x} == {labels[code]!r}",
|
|
449
|
+
evidence={"method": "independence", "null_violation_rate": _c(p0, ctx.policy)},
|
|
450
|
+
))
|
|
451
|
+
# y not null implies x == v
|
|
452
|
+
v2 = int(np.sum(~ynull & ~is_v))
|
|
453
|
+
if v2 <= ctx.soft_max:
|
|
454
|
+
p0 = float(np.mean(~ynull)) * float(np.mean(~is_v))
|
|
455
|
+
out.append(_Raw(
|
|
456
|
+
family="nullability", expression=_text(Binary("implies", notnull_y, eq)),
|
|
457
|
+
support=n, violations=v2, log_p=_log_chance(v2, n, p0),
|
|
458
|
+
description=f"{y} is present only when {x} == {labels[code]!r}",
|
|
459
|
+
evidence={"method": "independence", "null_violation_rate": _c(p0, ctx.policy)},
|
|
460
|
+
))
|
|
461
|
+
return out
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _fd_violations(xc: np.ndarray, yc: np.ndarray, ky: int, kx: int) -> int:
|
|
465
|
+
joint = np.bincount(xc * ky + yc, minlength=kx * ky).reshape(kx, ky)
|
|
466
|
+
return int(joint.sum() - joint.max(axis=1).sum())
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _fd(ctx: _Ctx, x: str, y: str) -> list[_Raw]:
|
|
470
|
+
xc, xl = ctx.cats[x]
|
|
471
|
+
yc, yl = ctx.cats[y]
|
|
472
|
+
ok = (xc >= 0) & (yc >= 0)
|
|
473
|
+
n = int(ok.sum())
|
|
474
|
+
kx, ky = len(xl), len(yl)
|
|
475
|
+
if n < MIN_SUPPORT or kx < ky or kx > n // 2:
|
|
476
|
+
return []
|
|
477
|
+
xc, yc = xc[ok], yc[ok]
|
|
478
|
+
v = _fd_violations(xc, yc, ky, kx)
|
|
479
|
+
if v > ctx.soft_max:
|
|
480
|
+
return []
|
|
481
|
+
present = int(np.unique(xc).size)
|
|
482
|
+
eff = n - present # the first row of each group cannot violate
|
|
483
|
+
if eff <= 0:
|
|
484
|
+
return []
|
|
485
|
+
rng = stream(ctx.seed, "constraints", "fd", x, y)
|
|
486
|
+
hits = sum(_fd_violations(xc, yc[rng.permutation(n)], ky, kx) for _ in range(N_SHUFFLES))
|
|
487
|
+
p0 = _rate(hits, eff * N_SHUFFLES)
|
|
488
|
+
desc = f"{x} -> {y}"
|
|
489
|
+
return [_Raw(
|
|
490
|
+
family="fd", expression="true", support=n, violations=v,
|
|
491
|
+
log_p=_log_chance(v, eff, p0), description=desc, expressible=False,
|
|
492
|
+
evidence={"method": "permutation", "shuffles": N_SHUFFLES,
|
|
493
|
+
"null_violation_rate": _c(p0, ctx.policy), "determinant": x,
|
|
494
|
+
"dependent": y, "mapping_size": present,
|
|
495
|
+
"enforcement": "functional dependencies are not expressible in the v0.1 "
|
|
496
|
+
"expression grammar; measured only"},
|
|
497
|
+
)]
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
def _unique(ctx: _Ctx, name: str) -> list[_Raw]:
|
|
501
|
+
col = ctx.by_name[name]
|
|
502
|
+
s = ctx.df.get_column(name).drop_nulls()
|
|
503
|
+
n = s.len()
|
|
504
|
+
if n < UNIQUE_MIN_ROWS or s.n_unique() != n:
|
|
505
|
+
return []
|
|
506
|
+
lt = col.logical_type
|
|
507
|
+
if lt in (LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.CATEGORICAL) and \
|
|
508
|
+
_is_numeric_dtype(s.dtype):
|
|
509
|
+
if not (col.integer_valued or s.dtype.is_integer()):
|
|
510
|
+
return [] # real-valued uniqueness is trivial
|
|
511
|
+
q01, q99 = np.quantile(s.cast(pl.Float64).to_numpy(), [0.01, 0.99])
|
|
512
|
+
span = float(q99 - q01) / 0.98 + 1.0
|
|
513
|
+
elif s.dtype == pl.String:
|
|
514
|
+
sample = s.head(1000)
|
|
515
|
+
alphabet = len(set("".join(sample.to_list()))) or 1
|
|
516
|
+
length = float(cast(float, sample.str.len_chars().median() or 1.0))
|
|
517
|
+
span = float(min(alphabet ** length, 1e18))
|
|
518
|
+
else:
|
|
519
|
+
return []
|
|
520
|
+
log_p = -n * (n - 1) / (2.0 * max(span, 1.0)) # birthday bound on "no collisions"
|
|
521
|
+
return [_Raw(
|
|
522
|
+
family="unique", expression="true", support=n, violations=0, log_p=log_p,
|
|
523
|
+
description=f"{name} is unique", expressible=False,
|
|
524
|
+
evidence={"method": "birthday",
|
|
525
|
+
"enforcement": "uniqueness is not expressible in the v0.1 expression "
|
|
526
|
+
"grammar; evidence only"},
|
|
527
|
+
)]
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
# ---------------------------------------------------------------------------------------------
|
|
531
|
+
# Public API
|
|
532
|
+
# ---------------------------------------------------------------------------------------------
|
|
533
|
+
|
|
534
|
+
|
|
535
|
+
def _id_for(raw: _Raw) -> str:
|
|
536
|
+
key = raw.expression if raw.expressible else f"{raw.family}|{raw.description}"
|
|
537
|
+
return "c_" + hashlib.sha256(key.encode("utf-8")).hexdigest()[:12]
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _label(conf: float) -> str:
|
|
541
|
+
if conf >= HIGH_CONFIDENCE:
|
|
542
|
+
return "high"
|
|
543
|
+
if conf >= MEDIUM_CONFIDENCE:
|
|
544
|
+
return "medium"
|
|
545
|
+
return "low"
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _tasks(ctx: _Ctx, seed: int) -> list[tuple[int, Callable[[], list[_Raw]]]]:
|
|
549
|
+
"""Candidate tasks in priority order as (number of candidates, thunk)."""
|
|
550
|
+
tasks: list[tuple[int, Callable[[], list[_Raw]]]] = []
|
|
551
|
+
num_names = [k for k, v in ctx.nums.items() if v.kind == "num"]
|
|
552
|
+
names = list(ctx.nums)
|
|
553
|
+
# bounds
|
|
554
|
+
for name in num_names:
|
|
555
|
+
tasks.append((len(_LOWER) + len(_UPPER), partial(_bound, ctx, name)))
|
|
556
|
+
# ordering
|
|
557
|
+
for a, b in combinations(names, 2):
|
|
558
|
+
na, nb = ctx.nums[a], ctx.nums[b]
|
|
559
|
+
if na.kind == nb.kind and na.tz == nb.tz:
|
|
560
|
+
tasks.append((4, partial(_ordering, ctx, a, b)))
|
|
561
|
+
# nullability
|
|
562
|
+
with_nulls = [k for k, m in ctx.nulls.items() if m.any()]
|
|
563
|
+
for a, b in permutations(with_nulls, 2):
|
|
564
|
+
tasks.append((1, partial(_null_implies, ctx, a, b)))
|
|
565
|
+
min_support = max(ctx.policy.min_category_support, ctx.policy.rare_cell_min)
|
|
566
|
+
for x, (codes, labels) in ctx.cats.items():
|
|
567
|
+
if len(labels) > MAX_LOW_CARDINALITY:
|
|
568
|
+
continue
|
|
569
|
+
counts = np.bincount(codes[codes >= 0], minlength=len(labels))
|
|
570
|
+
for code in range(len(labels)):
|
|
571
|
+
if counts[code] < min_support:
|
|
572
|
+
continue
|
|
573
|
+
for y in with_nulls:
|
|
574
|
+
if y != x:
|
|
575
|
+
tasks.append((2, partial(_value_implies, ctx, x, code, y)))
|
|
576
|
+
# functional dependencies
|
|
577
|
+
for x, y in permutations(ctx.cats, 2):
|
|
578
|
+
tasks.append((1, partial(_fd, ctx, x, y)))
|
|
579
|
+
# uniqueness
|
|
580
|
+
for name in ctx.nulls:
|
|
581
|
+
tasks.append((1, partial(_unique, ctx, name)))
|
|
582
|
+
# identities (last: the most numerous family)
|
|
583
|
+
if num_names and ctx.n > 0:
|
|
584
|
+
rng = stream(seed, "constraints", "identity_screen")
|
|
585
|
+
k = min(ctx.n, IDENTITY_SCREEN_ROWS)
|
|
586
|
+
screen_idx = np.sort(rng.choice(ctx.n, size=k, replace=False))
|
|
587
|
+
for trio in combinations(num_names, 3):
|
|
588
|
+
for c in trio:
|
|
589
|
+
a, b = (t for t in trio if t != c)
|
|
590
|
+
for op in ("+", "*"):
|
|
591
|
+
tasks.append((1, partial(_identity, ctx, op, c, a, b, screen_idx)))
|
|
592
|
+
return tasks
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def suggest_constraints(df: pl.DataFrame, columns: list[ColumnSchema],
|
|
596
|
+
policy: DisclosurePolicySpec | str | None = None, *,
|
|
597
|
+
max_candidates: int = 5000, seed: int = 0,
|
|
598
|
+
min_confidence: float = MIN_CONFIDENCE) -> list[SuggestedConstraint]:
|
|
599
|
+
"""Screen candidate constraints and return confirmable suggestions.
|
|
600
|
+
|
|
601
|
+
Returns at most :data:`MAX_SUGGESTIONS` suggestions sorted by confidence (descending), each
|
|
602
|
+
with support, violations, the number of candidates screened (the Bonferroni multiplicity)
|
|
603
|
+
and a confidence in [0, 1]. Every expression type-checks against ``columns``. Suggestions
|
|
604
|
+
are never binding; see ``Fingerprint.confirm_constraint``.
|
|
605
|
+
"""
|
|
606
|
+
if isinstance(df, pl.LazyFrame):
|
|
607
|
+
df = df.collect()
|
|
608
|
+
pol = resolve_policy(policy)
|
|
609
|
+
if df.height == 0 or not columns:
|
|
610
|
+
return []
|
|
611
|
+
ctx = _prepare(df, columns, pol, seed)
|
|
612
|
+
|
|
613
|
+
screened = 0
|
|
614
|
+
raws: list[_Raw] = []
|
|
615
|
+
for cost, thunk in _tasks(ctx, seed):
|
|
616
|
+
if screened + cost > max_candidates:
|
|
617
|
+
break
|
|
618
|
+
screened += cost
|
|
619
|
+
raws.extend(thunk())
|
|
620
|
+
m = max(screened, 1)
|
|
621
|
+
schema_map = {c.name: c for c in columns}
|
|
622
|
+
|
|
623
|
+
out: list[tuple[float, int, str, SuggestedConstraint]] = []
|
|
624
|
+
for r in raws:
|
|
625
|
+
log_adj = min(0.0, math.log(m) + r.log_p)
|
|
626
|
+
conf = float(-math.expm1(log_adj)) if log_adj > -745 else 1.0
|
|
627
|
+
soft = r.violations > 0
|
|
628
|
+
if soft:
|
|
629
|
+
conf = min(conf, SOFT_CONFIDENCE_CAP)
|
|
630
|
+
conf = min(max(conf, 0.0), 1.0)
|
|
631
|
+
if conf < min_confidence:
|
|
632
|
+
continue
|
|
633
|
+
check(r.expression, schema_map) # every expression must type-check
|
|
634
|
+
evidence = {
|
|
635
|
+
"description": r.description,
|
|
636
|
+
"expressible": r.expressible,
|
|
637
|
+
"soft": soft,
|
|
638
|
+
"violation_rate": _c(r.violations / r.support, pol) if r.support else 0.0,
|
|
639
|
+
"log10_p_chance": _c(r.log_p / math.log(10), pol),
|
|
640
|
+
"log10_p_adjusted": _c(log_adj / math.log(10), pol),
|
|
641
|
+
"correction": "bonferroni",
|
|
642
|
+
**r.evidence,
|
|
643
|
+
}
|
|
644
|
+
sc = SuggestedConstraint(
|
|
645
|
+
id=_id_for(r), expression=r.expression, family=r.family, support=r.support,
|
|
646
|
+
violations=r.violations, candidates_screened=m, confidence=conf,
|
|
647
|
+
confidence_label=_label(conf), # type: ignore[arg-type]
|
|
648
|
+
evidence=evidence,
|
|
649
|
+
)
|
|
650
|
+
out.append((-conf, _FAMILY_ORDER.get(r.family, 9), sc.id, sc))
|
|
651
|
+
out.sort(key=lambda t: (t[0], t[1], t[2]))
|
|
652
|
+
seen: set[str] = set()
|
|
653
|
+
result: list[SuggestedConstraint] = []
|
|
654
|
+
for *_, sc in out:
|
|
655
|
+
if sc.id in seen:
|
|
656
|
+
continue
|
|
657
|
+
seen.add(sc.id)
|
|
658
|
+
result.append(sc)
|
|
659
|
+
if len(result) >= MAX_SUGGESTIONS:
|
|
660
|
+
break
|
|
661
|
+
return result
|