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,651 @@
|
|
|
1
|
+
"""Columns that are a pure function of one other column (ADR-0011).
|
|
2
|
+
|
|
3
|
+
A weekday name, a calendar year, a fiscal year or a valuation band is not a random variable
|
|
4
|
+
next to the column it is computed from: it is that column, read differently. Modeled as a
|
|
5
|
+
feature it is drawn from a joint model that at best knows a rank correlation with its base, and
|
|
6
|
+
when the base itself is computed after decoding (``issue = applied + gap``, ADR-0005) no model
|
|
7
|
+
ever sees the value the function applies to. The synthetic weekday then contradicts the
|
|
8
|
+
synthetic date in six rows out of seven.
|
|
9
|
+
|
|
10
|
+
:func:`detect_functions` finds such columns and writes each as an expression of the closed
|
|
11
|
+
grammar of :mod:`ectype.fingerprint.expressions`. The profiler records it in
|
|
12
|
+
``manifest.model.derived``, so the generator computes the column from the generated base, after
|
|
13
|
+
the transforms and orderings. The column is not modeled (no marginal, no slot in the joint
|
|
14
|
+
model) but stays a feature of the table: its targets are measured, sealed and validated like
|
|
15
|
+
those of any other column.
|
|
16
|
+
|
|
17
|
+
Families
|
|
18
|
+
--------
|
|
19
|
+
``calendar``
|
|
20
|
+
A part of a date or datetime column: ``year``, ``quarter``, ``month``, ``day``,
|
|
21
|
+
``weekday``, ``week`` (ISO) or ``fiscal_year(d, m)`` for a start month ``m`` learned from
|
|
22
|
+
the data. A numeric column equal to the part is written as the part (a fiscal year also
|
|
23
|
+
as ``fiscal_year(d, m) - 1``, when it is named by the year it starts in). Any other column
|
|
24
|
+
that is a function of a part with at most :data:`MAX_KEYS` values is a
|
|
25
|
+
``lookup(part, key, value, ...)`` whose table is learned: weekday names, month
|
|
26
|
+
abbreviations, a numbering that starts on Sunday, a weekend flag. Of several parts that
|
|
27
|
+
explain a column the one with the fewest keys is used.
|
|
28
|
+
``periodic``
|
|
29
|
+
A function of ``base % p`` for an integer-valued base and a small period ``p``: a weekday
|
|
30
|
+
from a day number (``p = 7``), a parity, the last digit. The periods of :data:`PERIODS` are
|
|
31
|
+
tried in increasing order and the first that fits is used: if ``p`` fits, so does every
|
|
32
|
+
multiple of it, and the smallest is the period itself (the larger ones only repeat its
|
|
33
|
+
table). Every residue must be seen, at :data:`MIN_CYCLES` distinct base values or more.
|
|
34
|
+
``step``
|
|
35
|
+
A column that is constant on intervals of a numeric base: a band, or a year computed from a
|
|
36
|
+
day number. The cut points are learned (:func:`_round_cut`).
|
|
37
|
+
|
|
38
|
+
Acceptance
|
|
39
|
+
----------
|
|
40
|
+
* **It holds**, by the rule every relationship is held to (:mod:`ectype.profiling.tolerance`,
|
|
41
|
+
ADR-0015). At most :data:`MAX_EXCEPTIONS` of the rows may disagree with the function
|
|
42
|
+
wherever they are (``floor(0.005 n)``: none below 200 rows): a recorded weekday or year
|
|
43
|
+
that contradicts its date in a handful of rows is a typing error. Up to
|
|
44
|
+
``tolerance.DIRTY`` of them may when the rows are isolated: not gathered in a stretch of
|
|
45
|
+
the base (the days before a year ends, the values around a cut point), in one value of the
|
|
46
|
+
column itself (its empty cells, a second spelling) or in a category of another column,
|
|
47
|
+
which would be information the function does not have. A null where the function gives a
|
|
48
|
+
value, or a value where it gives null, is a disagreement. The count is taken by evaluating
|
|
49
|
+
the final expression on the source rows, so it is the generator's own arithmetic that is
|
|
50
|
+
tested.
|
|
51
|
+
* **It is not a coincidence.** The base takes at least :data:`MIN_DISTINCT_BASE` distinct
|
|
52
|
+
values, and at least :data:`MIN_BASE_PER_VALUE` times as many as the function has segments
|
|
53
|
+
or keys; the function takes at least two values. A dependence between two low-cardinality
|
|
54
|
+
columns is therefore never a function here, however exact: the conditional tables of the
|
|
55
|
+
joint model hold those.
|
|
56
|
+
* **It is not merely statistical.** A column that follows its base only on average (a year of
|
|
57
|
+
a *later* date, a band of a noisy copy) breaks the function in far more rows than the
|
|
58
|
+
tolerance allows.
|
|
59
|
+
|
|
60
|
+
Exceptions are not reproduced: the generated column follows the function on every row. The
|
|
61
|
+
share of source rows that do not is recorded in the column's notes and in the diagnostics.
|
|
62
|
+
|
|
63
|
+
Disclosure
|
|
64
|
+
----------
|
|
65
|
+
What is stored is the expression text: the names of the two columns, the function, and its
|
|
66
|
+
table. A ``pseudonym`` column (ADR-0010) may be computed like any categorical: detection runs
|
|
67
|
+
on the frame ``pseudonymise`` returned, so its table holds stand-in tokens and never a source
|
|
68
|
+
label. Every entry of a table stands for at least ``min_category_support`` source rows:
|
|
69
|
+
|
|
70
|
+
* a ``lookup`` key is kept only when that many rows hold its value, like a category label;
|
|
71
|
+
rarer keys are left out (their rows count as exceptions, and the function gives null there);
|
|
72
|
+
* a ``step`` segment holds that many rows that agree with it; a thinner run of values is
|
|
73
|
+
merged into its neighbours (its rows count as exceptions). A cut point is therefore a value
|
|
74
|
+
with that many rows on either side, as a stored quantile is, and it is not a value of the
|
|
75
|
+
data: it is the roundest number in the gap between the two segments (the value with the
|
|
76
|
+
fewest significant digits above the largest base value of the lower segment and not above
|
|
77
|
+
the smallest of the upper one), which is also where a band's nominal limit is.
|
|
78
|
+
|
|
79
|
+
Nothing else about the rows is kept. Rates in the diagnostics are coarsened.
|
|
80
|
+
|
|
81
|
+
Planning
|
|
82
|
+
--------
|
|
83
|
+
One base per column. Of several candidates the base with the most distinct values is used (the
|
|
84
|
+
date itself before a column computed from it), then the family in the order above. A column
|
|
85
|
+
may be computed from a computed column, never from itself through a chain: columns are settled
|
|
86
|
+
from the fewest distinct values up, and a candidate whose base depends on the column is
|
|
87
|
+
dropped, so two columns that determine each other get one direction.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
from __future__ import annotations
|
|
91
|
+
|
|
92
|
+
import math
|
|
93
|
+
from collections.abc import Sequence
|
|
94
|
+
from dataclasses import dataclass, field
|
|
95
|
+
from typing import Any
|
|
96
|
+
|
|
97
|
+
import numpy as np
|
|
98
|
+
import polars as pl
|
|
99
|
+
|
|
100
|
+
from ectype.fingerprint.disclosure import coarsen, resolve_policy
|
|
101
|
+
from ectype.fingerprint.expressions import (
|
|
102
|
+
MAX_LENGTH,
|
|
103
|
+
Binary,
|
|
104
|
+
Call,
|
|
105
|
+
Column,
|
|
106
|
+
Literal,
|
|
107
|
+
Node,
|
|
108
|
+
Unary,
|
|
109
|
+
check,
|
|
110
|
+
to_polars,
|
|
111
|
+
unparse,
|
|
112
|
+
)
|
|
113
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
114
|
+
from ectype.profiling import tolerance
|
|
115
|
+
from ectype.types import MODELED_ROLES, LogicalType, Role
|
|
116
|
+
|
|
117
|
+
__all__ = [
|
|
118
|
+
"FAMILIES",
|
|
119
|
+
"MAX_EXCEPTIONS",
|
|
120
|
+
"MAX_KEYS",
|
|
121
|
+
"MAX_SEGMENTS",
|
|
122
|
+
"MIN_BASE_PER_VALUE",
|
|
123
|
+
"MIN_CYCLES",
|
|
124
|
+
"MIN_DISTINCT_BASE",
|
|
125
|
+
"PERIODS",
|
|
126
|
+
"FunctionSpec",
|
|
127
|
+
"detect_functions",
|
|
128
|
+
]
|
|
129
|
+
|
|
130
|
+
FAMILIES = ("calendar", "periodic", "step")
|
|
131
|
+
#: largest share of rows that may disagree with a function wherever they are (the shared
|
|
132
|
+
#: rule of ``profiling.tolerance``, which also allows ``tolerance.DIRTY`` of isolated rows)
|
|
133
|
+
MAX_EXCEPTIONS = tolerance.STRAY
|
|
134
|
+
#: fewest distinct base values a function must be seen on
|
|
135
|
+
MIN_DISTINCT_BASE = 30
|
|
136
|
+
#: ... and fewest per segment or key of the function, on average
|
|
137
|
+
MIN_BASE_PER_VALUE = 3
|
|
138
|
+
#: periods tried for ``base % p``, in this order: 2 to 12 (parity, weekdays, months, small
|
|
139
|
+
#: cycles), then hours, minutes and the last two digits
|
|
140
|
+
PERIODS = (*range(2, 13), 24, 60, 100)
|
|
141
|
+
#: fewest distinct base values at which every residue of a period must be seen
|
|
142
|
+
MIN_CYCLES = 3
|
|
143
|
+
#: most keys of a ``lookup`` and most segments of a ``step``
|
|
144
|
+
MAX_KEYS = 64
|
|
145
|
+
MAX_SEGMENTS = 150
|
|
146
|
+
#: a candidate is recorded as not selected when it fails with at most this share of exceptions
|
|
147
|
+
_NEAR_MISS = tolerance.NEAR_MISS
|
|
148
|
+
#: most (column, base) pairs examined
|
|
149
|
+
_MAX_PAIRS = 4000
|
|
150
|
+
|
|
151
|
+
_PARTS = ("year", "quarter", "month", "day", "weekday", "week")
|
|
152
|
+
_NUMERIC = (LogicalType.CONTINUOUS, LogicalType.DISCRETE)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
@dataclass
|
|
156
|
+
class FunctionSpec:
|
|
157
|
+
"""One detected function: ``column = expression(base)``."""
|
|
158
|
+
|
|
159
|
+
column: str
|
|
160
|
+
base: str
|
|
161
|
+
family: str
|
|
162
|
+
expression: str
|
|
163
|
+
exceptions: int # source rows that do not follow the function
|
|
164
|
+
rows: int
|
|
165
|
+
detail: dict[str, Any] = field(default_factory=dict)
|
|
166
|
+
#: how the exceptions were judged (``profiling.tolerance``)
|
|
167
|
+
verdict: tolerance.Verdict | None = None
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def exception_rate(self) -> float:
|
|
171
|
+
return self.exceptions / max(self.rows, 1)
|
|
172
|
+
|
|
173
|
+
def judged(self) -> tolerance.Verdict:
|
|
174
|
+
return self.verdict if self.verdict is not None else tolerance.judge(
|
|
175
|
+
self.exceptions, self.rows)
|
|
176
|
+
|
|
177
|
+
def note(self, policy: DisclosurePolicySpec | str | None = None) -> str:
|
|
178
|
+
"""The text added to the column's notes."""
|
|
179
|
+
text = self.expression if len(self.expression) <= 80 else self.expression[:77] + "..."
|
|
180
|
+
out = f"computed from {self.base!r} ({self.family}): {text}"
|
|
181
|
+
if self.exceptions:
|
|
182
|
+
out += "; " + tolerance.note(self.judged(), resolve_policy(policy),
|
|
183
|
+
breaks="do not follow the function")
|
|
184
|
+
return out
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ---------------------------------------------------------------------------------------------
|
|
188
|
+
# Values and literals
|
|
189
|
+
# ---------------------------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
@dataclass
|
|
193
|
+
class _Target:
|
|
194
|
+
"""A candidate column: its values as codes (``-1`` for null) and the literal of each."""
|
|
195
|
+
|
|
196
|
+
col: ColumnSchema
|
|
197
|
+
codes: np.ndarray # int64 per row
|
|
198
|
+
values: list[Any] # python value per code
|
|
199
|
+
kind: str # "num" | "str" | "bool"
|
|
200
|
+
numbers: np.ndarray | None # float per row (NaN for null) when kind == "num"
|
|
201
|
+
|
|
202
|
+
@property
|
|
203
|
+
def n_values(self) -> int:
|
|
204
|
+
return len(self.values)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _literal(value: Any) -> Node:
|
|
208
|
+
if isinstance(value, bool):
|
|
209
|
+
return Literal(value, "bool")
|
|
210
|
+
if isinstance(value, str):
|
|
211
|
+
return Literal(value, "str")
|
|
212
|
+
v = float(value)
|
|
213
|
+
if v == int(v) and abs(v) < 2**53:
|
|
214
|
+
lit: Node = Literal(abs(int(v)), "int")
|
|
215
|
+
else:
|
|
216
|
+
lit = Literal(abs(v), "float")
|
|
217
|
+
return Unary("-", lit) if v < 0 else lit
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _target(df: pl.DataFrame, col: ColumnSchema, max_values: int) -> _Target | None:
|
|
221
|
+
"""``col`` as a candidate, or ``None`` when it cannot be the value of a function here: a
|
|
222
|
+
datetime, more than ``max_values`` distinct values, fewer than two, or a column whose
|
|
223
|
+
stored form differs from its modeled one (numbers kept as strings)."""
|
|
224
|
+
s = df.get_column(col.name)
|
|
225
|
+
dt = s.dtype
|
|
226
|
+
if dt.is_numeric():
|
|
227
|
+
if not col.physical_dtype.startswith(("Int", "UInt", "Float")):
|
|
228
|
+
return None
|
|
229
|
+
kind = "num"
|
|
230
|
+
s = s.cast(pl.Float64).fill_nan(None)
|
|
231
|
+
elif dt == pl.Boolean:
|
|
232
|
+
kind = "bool"
|
|
233
|
+
elif dt == pl.String or isinstance(dt, pl.Categorical | pl.Enum):
|
|
234
|
+
kind = "str"
|
|
235
|
+
s = s.cast(pl.String)
|
|
236
|
+
else:
|
|
237
|
+
return None
|
|
238
|
+
uniq = s.drop_nulls().unique().sort()
|
|
239
|
+
if not 2 <= uniq.len() <= max_values:
|
|
240
|
+
return None
|
|
241
|
+
values = uniq.to_list()
|
|
242
|
+
null = s.is_null().to_numpy()
|
|
243
|
+
if kind == "str":
|
|
244
|
+
codes = uniq.search_sorted(s.fill_null(values[0])).to_numpy()
|
|
245
|
+
else:
|
|
246
|
+
as_float = s.cast(pl.Float64)
|
|
247
|
+
codes = np.searchsorted(uniq.cast(pl.Float64).to_numpy(),
|
|
248
|
+
as_float.fill_null(float(values[0])).to_numpy())
|
|
249
|
+
codes = np.where(null, -1, np.asarray(codes, dtype=np.int64))
|
|
250
|
+
numbers = (s.to_numpy().astype(np.float64) if kind == "num" else None)
|
|
251
|
+
return _Target(col, codes, values, kind, numbers)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _majority(keys: np.ndarray, codes: np.ndarray, n_keys: int, n_codes: int
|
|
255
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
256
|
+
"""For key ``0..n_keys-1`` (a small table): the most frequent code among its rows and how
|
|
257
|
+
many rows hold it (rows with a negative key or code are ignored)."""
|
|
258
|
+
ok = (keys >= 0) & (codes >= 0)
|
|
259
|
+
table = np.bincount(keys[ok] * n_codes + codes[ok],
|
|
260
|
+
minlength=n_keys * n_codes).reshape(n_keys, n_codes)
|
|
261
|
+
return table.argmax(axis=1), table.max(axis=1)
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _majority_along(x: np.ndarray, codes: np.ndarray
|
|
265
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
266
|
+
"""For each distinct value of ``x`` (in increasing order): the value, the most frequent
|
|
267
|
+
code among its rows, and how many rows hold it. Needs no table, so ``x`` may take any
|
|
268
|
+
number of values."""
|
|
269
|
+
order = np.lexsort((codes, x))
|
|
270
|
+
xs, cs = x[order], codes[order]
|
|
271
|
+
first = np.flatnonzero(np.r_[True, (xs[1:] != xs[:-1]) | (cs[1:] != cs[:-1])])
|
|
272
|
+
held = np.diff(np.r_[first, xs.size]) # rows per (value, code)
|
|
273
|
+
px, pc = xs[first], cs[first]
|
|
274
|
+
group = np.cumsum(np.r_[True, px[1:] != px[:-1]]) - 1
|
|
275
|
+
by = np.lexsort((held, group)) # within a value: the largest count last
|
|
276
|
+
last = np.r_[group[by][1:] != group[by][:-1], True]
|
|
277
|
+
top = by[last]
|
|
278
|
+
return px[top], pc[top], held[top]
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# ---------------------------------------------------------------------------------------------
|
|
282
|
+
# The detector
|
|
283
|
+
# ---------------------------------------------------------------------------------------------
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class _Detector:
|
|
287
|
+
def __init__(self, df: pl.DataFrame, columns: Sequence[ColumnSchema],
|
|
288
|
+
policy: DisclosurePolicySpec, exclude: set[str]) -> None:
|
|
289
|
+
self.df = df
|
|
290
|
+
self.n = df.height
|
|
291
|
+
self.policy = policy
|
|
292
|
+
self.support = max(int(policy.min_category_support), 1)
|
|
293
|
+
#: most exceptions any tier of the rule allows: candidates above it are dropped
|
|
294
|
+
#: early; the rest are judged in :meth:`accept`
|
|
295
|
+
self.allowed = tolerance.dirty_limit(self.n)
|
|
296
|
+
self.context = tolerance.Context(df, columns, policy)
|
|
297
|
+
self.schemas = {c.name: c for c in columns if c.name in df.columns}
|
|
298
|
+
#: modeled columns: features, and pseudonym columns (ADR-0010), whose values in
|
|
299
|
+
#: ``df`` are stand-in tokens by now, so a table learned for one holds tokens only
|
|
300
|
+
self.usable = [c for c in self.schemas.values()
|
|
301
|
+
if c.role in MODELED_ROLES and c.name not in exclude
|
|
302
|
+
and not c.name.startswith("__")]
|
|
303
|
+
self._numbers: dict[str, np.ndarray] = {}
|
|
304
|
+
self._parts: dict[str, dict[str, np.ndarray]] = {}
|
|
305
|
+
self._distinct: dict[str, int] = {}
|
|
306
|
+
#: (column, base, family) -> fewest exceptions of a candidate that was refused, and
|
|
307
|
+
#: the reason
|
|
308
|
+
self.near: dict[tuple[str, str, str], tuple[int, str]] = {}
|
|
309
|
+
|
|
310
|
+
# -- bases --------------------------------------------------------------------------------
|
|
311
|
+
def distinct(self, name: str) -> int:
|
|
312
|
+
if name not in self._distinct:
|
|
313
|
+
self._distinct[name] = int(self.df.get_column(name).drop_nulls().n_unique())
|
|
314
|
+
return self._distinct[name]
|
|
315
|
+
|
|
316
|
+
def is_date(self, col: ColumnSchema) -> bool:
|
|
317
|
+
dt = self.df.schema[col.name]
|
|
318
|
+
return col.role == Role.FEATURE and col.logical_type == LogicalType.DATETIME and (
|
|
319
|
+
dt == pl.Date or isinstance(dt, pl.Datetime))
|
|
320
|
+
|
|
321
|
+
def is_number(self, col: ColumnSchema) -> bool:
|
|
322
|
+
return col.role == Role.FEATURE and col.logical_type in _NUMERIC \
|
|
323
|
+
and self.df.schema[col.name].is_numeric() \
|
|
324
|
+
and col.physical_dtype.startswith(("Int", "UInt", "Float"))
|
|
325
|
+
|
|
326
|
+
def numbers(self, name: str) -> np.ndarray:
|
|
327
|
+
if name not in self._numbers:
|
|
328
|
+
self._numbers[name] = self.df.get_column(name).cast(pl.Float64).fill_null(
|
|
329
|
+
np.nan).to_numpy().astype(np.float64)
|
|
330
|
+
return self._numbers[name]
|
|
331
|
+
|
|
332
|
+
def parts(self, name: str) -> dict[str, np.ndarray]:
|
|
333
|
+
"""The calendar parts of a date column, as the expression grammar computes them
|
|
334
|
+
(``-1`` for null)."""
|
|
335
|
+
if name not in self._parts:
|
|
336
|
+
exprs = [to_polars(Call(p, (Column(name),)), self.schemas).alias(p) for p in _PARTS]
|
|
337
|
+
frame = self.df.select(exprs)
|
|
338
|
+
self._parts[name] = {p: frame.get_column(p).fill_null(-1).to_numpy().astype(np.int64)
|
|
339
|
+
for p in _PARTS}
|
|
340
|
+
return self._parts[name]
|
|
341
|
+
|
|
342
|
+
# -- checking a finished expression -------------------------------------------------------
|
|
343
|
+
def exceptions(self, node: Node, target: _Target) -> np.ndarray | None:
|
|
344
|
+
"""The rows of the source on which ``node`` does not give the target's value
|
|
345
|
+
(``None`` when the expression does not compile to the target's kind)."""
|
|
346
|
+
try:
|
|
347
|
+
text = unparse(node)
|
|
348
|
+
if len(text) > MAX_LENGTH:
|
|
349
|
+
return None
|
|
350
|
+
check(text, self.schemas)
|
|
351
|
+
got = self.df.select(to_polars(node, self.schemas).alias("r")).to_series()
|
|
352
|
+
except Exception: # noqa: BLE001 - a candidate that does not compile is no candidate
|
|
353
|
+
return None
|
|
354
|
+
want = self.df.get_column(target.col.name)
|
|
355
|
+
try:
|
|
356
|
+
if target.kind == "num":
|
|
357
|
+
a, b = got.cast(pl.Float64).fill_nan(None), want.cast(pl.Float64).fill_nan(None)
|
|
358
|
+
elif target.kind == "bool":
|
|
359
|
+
a, b = got.cast(pl.Boolean), want
|
|
360
|
+
else:
|
|
361
|
+
a, b = got.cast(pl.String), want.cast(pl.String)
|
|
362
|
+
except pl.exceptions.PolarsError:
|
|
363
|
+
return None
|
|
364
|
+
return np.asarray(a.ne_missing(b).to_numpy(), dtype=bool)
|
|
365
|
+
|
|
366
|
+
def accept(self, node: Node, target: _Target, base: str, family: str,
|
|
367
|
+
detail: dict[str, Any]) -> FunctionSpec | None:
|
|
368
|
+
wrong = self.exceptions(node, target)
|
|
369
|
+
if wrong is None:
|
|
370
|
+
return None
|
|
371
|
+
exc = int(wrong.sum())
|
|
372
|
+
# the shared rule: stray rows anywhere, or isolated ones (not gathered in a stretch
|
|
373
|
+
# of the base, a value of the column itself or a category of another column)
|
|
374
|
+
verdict = tolerance.judge(exc, self.n, lambda: self.context.scattered(
|
|
375
|
+
wrong, [base, target.col.name], levels={target.col.name: target.codes}))
|
|
376
|
+
if not verdict.holds:
|
|
377
|
+
self.refuse(target, base, family, exc, verdict)
|
|
378
|
+
return None
|
|
379
|
+
return FunctionSpec(target.col.name, base, family, unparse(node), exc, self.n, detail,
|
|
380
|
+
verdict)
|
|
381
|
+
|
|
382
|
+
def refuse(self, target: _Target, base: str, family: str, exc: int,
|
|
383
|
+
verdict: tolerance.Verdict | None = None) -> None:
|
|
384
|
+
"""Remember a candidate that breaks its function in more rows than the rule allows,
|
|
385
|
+
when it is close enough to be worth reporting."""
|
|
386
|
+
if verdict is None:
|
|
387
|
+
if exc <= self.allowed:
|
|
388
|
+
return # not refused for its exceptions
|
|
389
|
+
verdict = tolerance.judge(exc, self.n)
|
|
390
|
+
if verdict.near_miss:
|
|
391
|
+
key = (target.col.name, base, family)
|
|
392
|
+
if key not in self.near or exc < self.near[key][0]:
|
|
393
|
+
self.near[key] = (exc, verdict.reason("do not follow the function"))
|
|
394
|
+
|
|
395
|
+
def near_misses(self, chosen: set[str]) -> list[dict[str, Any]]:
|
|
396
|
+
return [{"column": column, "base": base, "family": family,
|
|
397
|
+
"exception_rate": coarsen(exc / max(self.n, 1), self.policy),
|
|
398
|
+
"reason": reason}
|
|
399
|
+
for (column, base, family), (exc, reason) in sorted(self.near.items())
|
|
400
|
+
if column not in chosen]
|
|
401
|
+
|
|
402
|
+
def evident(self, base: str, n_values: int) -> bool:
|
|
403
|
+
"""Whether the base takes enough distinct values for a function with ``n_values``
|
|
404
|
+
segments or keys not to be a coincidence."""
|
|
405
|
+
return self.distinct(base) >= max(MIN_DISTINCT_BASE, MIN_BASE_PER_VALUE * n_values)
|
|
406
|
+
|
|
407
|
+
# -- lookups ------------------------------------------------------------------------------
|
|
408
|
+
def table(self, keys: np.ndarray, target: _Target
|
|
409
|
+
) -> tuple[list[tuple[int, Any]], int] | None:
|
|
410
|
+
"""The function ``key -> target`` for small integer keys (negative: null), and the
|
|
411
|
+
rows it gets wrong. For each key the value most of its rows hold is kept, when
|
|
412
|
+
``min_category_support`` rows hold it (a rarer key is left out: the function gives null
|
|
413
|
+
there). ``None`` when the keys are too many or fewer than two values are left."""
|
|
414
|
+
valid = keys >= 0
|
|
415
|
+
if not valid.any():
|
|
416
|
+
return None
|
|
417
|
+
present, index = np.unique(keys[valid], return_inverse=True)
|
|
418
|
+
if present.size > MAX_KEYS:
|
|
419
|
+
return None
|
|
420
|
+
full = np.full(keys.size, -1, dtype=np.int64)
|
|
421
|
+
full[valid] = index
|
|
422
|
+
best, count = _majority(full, target.codes, present.size, target.n_values)
|
|
423
|
+
kept = count >= self.support
|
|
424
|
+
if np.unique(best[kept]).size < 2:
|
|
425
|
+
return None
|
|
426
|
+
code_of = np.where(kept, best, -1)
|
|
427
|
+
wrong = int(np.sum(np.where(valid, code_of[np.maximum(full, 0)], -1) != target.codes))
|
|
428
|
+
pairs = [(int(present[i]), target.values[int(best[i])])
|
|
429
|
+
for i in range(present.size) if kept[i]]
|
|
430
|
+
return pairs, wrong
|
|
431
|
+
|
|
432
|
+
@staticmethod
|
|
433
|
+
def lookup(arg: Node, pairs: Sequence[tuple[int, Any]]) -> Node:
|
|
434
|
+
args: list[Node] = [arg]
|
|
435
|
+
for key, value in pairs:
|
|
436
|
+
args += [_literal(key), _literal(value)]
|
|
437
|
+
return Call("lookup", tuple(args))
|
|
438
|
+
|
|
439
|
+
# -- families -----------------------------------------------------------------------------
|
|
440
|
+
def calendar(self, target: _Target, base: ColumnSchema) -> FunctionSpec | None:
|
|
441
|
+
name = base.name
|
|
442
|
+
if self.distinct(name) < MIN_DISTINCT_BASE:
|
|
443
|
+
return None
|
|
444
|
+
parts = self.parts(name)
|
|
445
|
+
col = Column(name)
|
|
446
|
+
year, month = parts["year"], parts["month"]
|
|
447
|
+
present = year >= 0
|
|
448
|
+
|
|
449
|
+
def fiscal(start: int) -> np.ndarray:
|
|
450
|
+
return np.where(present, year + (month >= start), -1)
|
|
451
|
+
|
|
452
|
+
# a numeric column equal to a part
|
|
453
|
+
if target.numbers is not None:
|
|
454
|
+
y = np.where(np.isfinite(target.numbers), target.numbers, -1.0)
|
|
455
|
+
direct: list[tuple[int, int, Node, dict[str, Any]]] = []
|
|
456
|
+
for rank, part in enumerate(_PARTS):
|
|
457
|
+
miss = int(np.sum(y != parts[part]))
|
|
458
|
+
direct.append((miss, rank, Call(part, (col,)), {"part": part}))
|
|
459
|
+
for start in range(2, 13):
|
|
460
|
+
fy = fiscal(start)
|
|
461
|
+
call = Call("fiscal_year", (col, Literal(start, "int")))
|
|
462
|
+
named: tuple[tuple[int, Node], ...] = (
|
|
463
|
+
(0, call), (1, Binary("-", call, Literal(1, "int"))))
|
|
464
|
+
for offset, node in named:
|
|
465
|
+
miss = int(np.sum(y != np.where(present, fy - offset, -1)))
|
|
466
|
+
direct.append((miss, 100 + 2 * start + offset, node,
|
|
467
|
+
{"part": "fiscal_year", "start_month": start,
|
|
468
|
+
"named_by": "end" if offset == 0 else "start"}))
|
|
469
|
+
miss, _, node, detail = min(direct, key=lambda t: (t[0], t[1]))
|
|
470
|
+
if miss <= self.allowed and self.evident(name, 2):
|
|
471
|
+
spec = self.accept(node, target, name, "calendar", detail)
|
|
472
|
+
if spec is not None:
|
|
473
|
+
return spec
|
|
474
|
+
self.refuse(target, name, "calendar", miss)
|
|
475
|
+
# any column that is a function of a part with few values
|
|
476
|
+
best: tuple[int, int, Node, dict[str, Any]] | None = None
|
|
477
|
+
keyed: list[tuple[int, Node, np.ndarray, dict[str, Any]]] = [
|
|
478
|
+
(rank, Call(part, (col,)), parts[part], {"part": part})
|
|
479
|
+
for rank, part in enumerate(_PARTS)]
|
|
480
|
+
keyed += [(100 + start, Call("fiscal_year", (col, Literal(start, "int"))), fiscal(start),
|
|
481
|
+
{"part": "fiscal_year", "start_month": start}) for start in range(2, 13)]
|
|
482
|
+
for rank, arg, keys, detail in keyed:
|
|
483
|
+
found = self.table(keys, target)
|
|
484
|
+
if found is None:
|
|
485
|
+
continue
|
|
486
|
+
pairs, wrong = found
|
|
487
|
+
if best is not None and (len(pairs), rank) >= best[:2]:
|
|
488
|
+
continue
|
|
489
|
+
if wrong <= self.allowed and self.evident(name, len(pairs)):
|
|
490
|
+
best = (len(pairs), rank, self.lookup(arg, pairs),
|
|
491
|
+
{**detail, "keys": len(pairs)})
|
|
492
|
+
else:
|
|
493
|
+
self.refuse(target, name, "calendar", wrong)
|
|
494
|
+
if best is not None:
|
|
495
|
+
return self.accept(best[2], target, name, "calendar", best[3])
|
|
496
|
+
return None
|
|
497
|
+
|
|
498
|
+
def periodic(self, target: _Target, base: ColumnSchema) -> FunctionSpec | None:
|
|
499
|
+
name = base.name
|
|
500
|
+
x = self.numbers(name)
|
|
501
|
+
ok = np.isfinite(x)
|
|
502
|
+
if not ok.any() or np.any(x[ok] != np.rint(x[ok])) or np.max(np.abs(x[ok])) >= 2**53:
|
|
503
|
+
return None
|
|
504
|
+
whole = np.where(ok, x, 0).astype(np.int64)
|
|
505
|
+
seen = np.unique(whole[ok])
|
|
506
|
+
for p in PERIODS:
|
|
507
|
+
if seen.size < max(MIN_DISTINCT_BASE, MIN_CYCLES * p, MIN_BASE_PER_VALUE * p):
|
|
508
|
+
break
|
|
509
|
+
if int(np.min(np.bincount(seen % p, minlength=p))) < MIN_CYCLES:
|
|
510
|
+
continue # a residue seen at too few base values
|
|
511
|
+
found = self.table(np.where(ok, whole % p, -1), target)
|
|
512
|
+
if found is None or len(found[0]) != p:
|
|
513
|
+
continue # no function, or a residue too thinly held
|
|
514
|
+
if found[1] > self.allowed:
|
|
515
|
+
self.refuse(target, name, "periodic", found[1])
|
|
516
|
+
continue
|
|
517
|
+
pairs = found[0]
|
|
518
|
+
arg = Binary("%", Column(name), Literal(p, "int"))
|
|
519
|
+
if all(not isinstance(v, bool | str) and float(v) == k for k, v in pairs):
|
|
520
|
+
node: Node = arg # the column is the residue itself
|
|
521
|
+
else:
|
|
522
|
+
node = self.lookup(arg, pairs)
|
|
523
|
+
spec = self.accept(node, target, name, "periodic", {"period": p})
|
|
524
|
+
if spec is not None:
|
|
525
|
+
return spec
|
|
526
|
+
return None
|
|
527
|
+
|
|
528
|
+
def step(self, target: _Target, base: ColumnSchema) -> FunctionSpec | None:
|
|
529
|
+
name = base.name
|
|
530
|
+
x = self.numbers(name)
|
|
531
|
+
ok = np.isfinite(x) & (target.codes >= 0)
|
|
532
|
+
if int(ok.sum()) < 2 * self.support:
|
|
533
|
+
return None
|
|
534
|
+
if not self.evident(name, 2):
|
|
535
|
+
return None
|
|
536
|
+
# one value per distinct base value: the one most of its rows hold
|
|
537
|
+
points, best, count = _majority_along(x[ok], target.codes[ok])
|
|
538
|
+
# runs of equal values along the base; a run too thin to be stored is left out
|
|
539
|
+
starts = np.flatnonzero(np.r_[True, best[1:] != best[:-1]])
|
|
540
|
+
if starts.size > MAX_SEGMENTS + 2 * self.allowed + 2:
|
|
541
|
+
return None # the value changes too often: not a step
|
|
542
|
+
ends = np.r_[starts[1:], points.size]
|
|
543
|
+
rows = np.add.reduceat(count, starts)
|
|
544
|
+
runs = [(int(best[s]), float(points[s]), float(points[e - 1]))
|
|
545
|
+
for s, e, r in zip(starts, ends, rows) if r >= self.support]
|
|
546
|
+
segments: list[tuple[int, float, float]] = []
|
|
547
|
+
for code, lo, hi in runs:
|
|
548
|
+
if segments and segments[-1][0] == code:
|
|
549
|
+
segments[-1] = (code, segments[-1][1], hi)
|
|
550
|
+
else:
|
|
551
|
+
segments.append((code, lo, hi))
|
|
552
|
+
if not 2 <= len(segments) <= MAX_SEGMENTS or not self.evident(name, len(segments)):
|
|
553
|
+
return None
|
|
554
|
+
args: list[Node] = [Column(name), _literal(target.values[segments[0][0]])]
|
|
555
|
+
for (_, _, below), (code, above, _) in zip(segments, segments[1:]):
|
|
556
|
+
args += [_literal(_round_cut(below, above)), _literal(target.values[code])]
|
|
557
|
+
return self.accept(Call("step", tuple(args)), target, name, "step",
|
|
558
|
+
{"segments": len(segments)})
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _round_cut(below: float, above: float) -> float:
|
|
562
|
+
"""The roundest number ``c`` with ``below < c <= above``: the multiple of the largest
|
|
563
|
+
power of ten that falls in the gap (the smallest such multiple). For a gap that holds no
|
|
564
|
+
rounder number than its upper end, that end."""
|
|
565
|
+
if not below < above:
|
|
566
|
+
return above
|
|
567
|
+
top = int(math.ceil(math.log10(max(abs(below), abs(above), 1.0)))) + 1
|
|
568
|
+
for e in range(top, -13, -1):
|
|
569
|
+
p = 10.0 ** e
|
|
570
|
+
c = (math.floor(below / p) + 1) * p
|
|
571
|
+
c = round(c, max(-e, 0))
|
|
572
|
+
if below < c <= above:
|
|
573
|
+
return float(c)
|
|
574
|
+
return above
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def detect_functions(df: pl.DataFrame, columns: Sequence[ColumnSchema],
|
|
578
|
+
policy: DisclosurePolicySpec | str | None = None, *,
|
|
579
|
+
exclude: Sequence[str] = ()) -> tuple[list[FunctionSpec], dict[str, Any]]:
|
|
580
|
+
"""The feature columns of ``df`` that are a function of one other feature column (see the
|
|
581
|
+
module docstring), as :class:`FunctionSpec` in an order in which every base comes before
|
|
582
|
+
the columns computed from it, and a JSON-safe record of what was found and of the near
|
|
583
|
+
misses. Columns named in ``exclude`` are neither computed nor used as a base."""
|
|
584
|
+
pol = resolve_policy(policy)
|
|
585
|
+
det = _Detector(df, columns, pol, set(exclude))
|
|
586
|
+
diag: dict[str, Any] = {
|
|
587
|
+
"applied": [], "not_selected": [],
|
|
588
|
+
"thresholds": {**tolerance.thresholds(),
|
|
589
|
+
"min_distinct_base": MIN_DISTINCT_BASE,
|
|
590
|
+
"min_base_per_value": MIN_BASE_PER_VALUE,
|
|
591
|
+
"min_support": det.support}}
|
|
592
|
+
if det.n < 2 or len(det.usable) < 2:
|
|
593
|
+
return [], diag
|
|
594
|
+
dates = [c for c in det.usable if det.is_date(c)]
|
|
595
|
+
numbers = [c for c in det.usable if det.is_number(c)
|
|
596
|
+
and det.distinct(c.name) >= MIN_DISTINCT_BASE]
|
|
597
|
+
targets = [t for t in (_target(df, c, max(MAX_SEGMENTS, MAX_KEYS)) for c in det.usable
|
|
598
|
+
if c.logical_type != LogicalType.DATETIME) if t is not None]
|
|
599
|
+
candidates: dict[str, list[FunctionSpec]] = {}
|
|
600
|
+
pairs = 0
|
|
601
|
+
for t in targets:
|
|
602
|
+
found: list[FunctionSpec] = []
|
|
603
|
+
for base in (*dates, *numbers):
|
|
604
|
+
if base.name == t.col.name or pairs >= _MAX_PAIRS:
|
|
605
|
+
continue
|
|
606
|
+
pairs += 1
|
|
607
|
+
if det.is_date(base):
|
|
608
|
+
spec = det.calendar(t, base)
|
|
609
|
+
else:
|
|
610
|
+
spec = det.periodic(t, base) or det.step(t, base)
|
|
611
|
+
if spec is not None:
|
|
612
|
+
found.append(spec)
|
|
613
|
+
if found:
|
|
614
|
+
found.sort(key=lambda s: (-det.distinct(s.base), FAMILIES.index(s.family),
|
|
615
|
+
s.exceptions))
|
|
616
|
+
candidates[t.col.name] = found
|
|
617
|
+
|
|
618
|
+
# one base per column, no cycles: settle the columns with the fewest distinct values first
|
|
619
|
+
chosen: dict[str, FunctionSpec] = {}
|
|
620
|
+
|
|
621
|
+
def depends(name: str, on: str) -> bool:
|
|
622
|
+
while name in chosen:
|
|
623
|
+
name = chosen[name].base
|
|
624
|
+
if name == on:
|
|
625
|
+
return True
|
|
626
|
+
return False
|
|
627
|
+
|
|
628
|
+
order = {c.name: i for i, c in enumerate(det.usable)}
|
|
629
|
+
for name in sorted(candidates, key=lambda c: (det.distinct(c), order[c])):
|
|
630
|
+
for spec in candidates[name]:
|
|
631
|
+
if spec.base != name and not depends(spec.base, name):
|
|
632
|
+
chosen[name] = spec
|
|
633
|
+
break
|
|
634
|
+
out: list[FunctionSpec] = []
|
|
635
|
+
placed: set[str] = set()
|
|
636
|
+
|
|
637
|
+
def place(name: str) -> None:
|
|
638
|
+
if name in placed or name not in chosen:
|
|
639
|
+
return
|
|
640
|
+
placed.add(name)
|
|
641
|
+
place(chosen[name].base)
|
|
642
|
+
out.append(chosen[name])
|
|
643
|
+
|
|
644
|
+
for name in chosen:
|
|
645
|
+
place(name)
|
|
646
|
+
for spec in out:
|
|
647
|
+
diag["applied"].append({
|
|
648
|
+
"column": spec.column, "base": spec.base, "family": spec.family,
|
|
649
|
+
"expression": spec.expression, **spec.judged().record(pol), **spec.detail})
|
|
650
|
+
diag["not_selected"] = det.near_misses(set(chosen))
|
|
651
|
+
return out, diag
|