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,1087 @@
|
|
|
1
|
+
"""Structural profiler (M5): infer logical types, roles and structural facts per column.
|
|
2
|
+
|
|
3
|
+
``profile_structure`` looks at each source column once and returns a :class:`ColumnSchema` per
|
|
4
|
+
column, in source order. Everything stored is either structural (dtype, nullability, precision)
|
|
5
|
+
or passed through the disclosure policy (support bounds via ``clip_bounds``, coarsened distinct
|
|
6
|
+
counts).
|
|
7
|
+
|
|
8
|
+
Detection order for a column (first match wins)
|
|
9
|
+
-----------------------------------------------
|
|
10
|
+
1. **all null** -> role CONSTANT (a constant null column), note "all values are null".
|
|
11
|
+
2. **unsupported dtype** (List, Struct, Binary, Time, Duration, Object, ...) -> STRING/EXCLUDED.
|
|
12
|
+
3. **constant** -> exactly one non-null distinct value; role CONSTANT.
|
|
13
|
+
4. **boolean** -> ``pl.Boolean``, or exactly two distinct values forming one of
|
|
14
|
+
``{0,1}``, ``{true,false}``, ``{yes,no}``, ``{y,n}`` (case-insensitive). The physical dtype
|
|
15
|
+
is kept. String-coded booleans record their exact source spellings in ``bool_labels``.
|
|
16
|
+
5. **datetime** -> ``pl.Date`` / ``pl.Datetime``. String columns are probed against ISO
|
|
17
|
+
formats (``_ISO_FORMATS``) on the sample; if at least ``DATETIME_PARSE_MIN_FRACTION`` parse
|
|
18
|
+
with one format the full column is checked. Only if *every* non-null value parses with that
|
|
19
|
+
single format (unambiguous) does the column become DATETIME (``pattern`` holds the strptime
|
|
20
|
+
format, physical dtype stays ``String``). Otherwise a note is added and string detection
|
|
21
|
+
continues.
|
|
22
|
+
6. **numeric**:
|
|
23
|
+
* non-integer floats -> CONTINUOUS (``decimals`` detected);
|
|
24
|
+
* integer-valued, identifier evidence (see below) -> IDENTIFIER;
|
|
25
|
+
* integer-valued, <= ``CATEGORICAL_MAX_LEVELS`` levels -> DISCRETE (note suggests a
|
|
26
|
+
categorical override for nominal codes);
|
|
27
|
+
* integer-valued otherwise -> DISCRETE (``integer_valued=True``).
|
|
28
|
+
7. **strings / categoricals**:
|
|
29
|
+
* distinct <= max(``STRING_CATEGORICAL_MIN_LEVELS``, ``STRING_CATEGORICAL_MAX_FRACTION`` * rows)
|
|
30
|
+
and not identifier-like -> CATEGORICAL;
|
|
31
|
+
* zero-padded fixed-width digit codes (zip codes), not identifier-like -> CATEGORICAL
|
|
32
|
+
(above ``CODE_CATEGORICAL_MAX_LEVELS`` levels a note says rare levels are pooled);
|
|
33
|
+
* numeric strings (``"12.5"``, ``"40%"``, with NA tokens ``NUMERIC_NA_TOKENS``) -> profiled
|
|
34
|
+
as numbers; ``pattern`` is ``NUMERIC_PARSE`` or ``NUMERIC_PARSE_PERCENT`` (the parse rule,
|
|
35
|
+
see ``parse_numeric_strings``) and the physical dtype stays ``String``;
|
|
36
|
+
* identifier-like -> IDENTIFIER (``pattern`` filled);
|
|
37
|
+
* text-like (spaces in most values or long values) -> TEXT / EXCLUDED;
|
|
38
|
+
* otherwise -> STRING / EXCLUDED with a shape pattern.
|
|
39
|
+
|
|
40
|
+
Personal data (ADR-0010)
|
|
41
|
+
------------------------
|
|
42
|
+
After the steps above, text columns and integer codes are screened by
|
|
43
|
+
``profiling.personal.detect_personal`` (column-name tokens and value patterns; see that module
|
|
44
|
+
for the exact rules). Under every policy except ``research`` a column that looks personal never
|
|
45
|
+
keeps its real values by default:
|
|
46
|
+
|
|
47
|
+
* a categorical column gets the role ``pseudonym``: it is modeled as a categorical, and its
|
|
48
|
+
labels are replaced by stand-in tokens before anything is fitted (``profiling.pseudonym``);
|
|
49
|
+
* a column the steps above would exclude as text (its distinct values exceed the categorical
|
|
50
|
+
limit) or model as numbers also becomes a ``pseudonym`` categorical when at least
|
|
51
|
+
``PSEUDONYM_MIN_REPEAT_SHARE`` of its rows hold a value seen ``min_category_support`` times or
|
|
52
|
+
more, so the decision does not flip when the table grows; otherwise nothing repeats, there
|
|
53
|
+
are no levels to keep, and the column is excluded;
|
|
54
|
+
* an identifier stays an identifier (it is regenerated anyway).
|
|
55
|
+
|
|
56
|
+
Under ``research`` the column is left as detected. Every decision is recorded in ``notes``,
|
|
57
|
+
and an override of ``role`` decides either way (``"pseudonym"`` opts any text or integer-coded
|
|
58
|
+
column in, any other role opts a detected column out).
|
|
59
|
+
|
|
60
|
+
Reference keys (ADR-0013)
|
|
61
|
+
-------------------------
|
|
62
|
+
A column that the steps above leave as a whole number, a code or a category, and that the
|
|
63
|
+
personal-data screen did not catch, is a *reference key* when all of the following hold:
|
|
64
|
+
|
|
65
|
+
* its name says it is a key: a token ``id``, ``key``, ``ref``, ``reference``, ``fk``, ``uuid``
|
|
66
|
+
or ``guid``, or ``parent`` / ``master`` together with ``no``, ``number``, ``num``, ``nbr``,
|
|
67
|
+
``record`` or ``rec``; and no token that names a property or a quantity (``type``,
|
|
68
|
+
``status``, ``count``, ``amount``, ``value``, ...);
|
|
69
|
+
* it is not an identifier (its values repeat), it has at least ``IDENTIFIER_MIN_ROWS`` values
|
|
70
|
+
and more than ``REFERENCE_MIN_LEVELS`` distinct ones, and numbers are not negative;
|
|
71
|
+
* most of its rows hold a rare value: fewer than ``REFERENCE_MAX_REPEAT_SHARE`` of them hold
|
|
72
|
+
a value seen ``min_category_support`` times or more (at least ``REFERENCE_MIN_SUPPORT``
|
|
73
|
+
times, whatever the policy), so a categorical model would pool most of the column. A ZIP code, a product code or a store number has levels worth keeping
|
|
74
|
+
and is never caught; a parent record, an order number on its lines or a household number
|
|
75
|
+
has a repeat structure and little else.
|
|
76
|
+
|
|
77
|
+
Such a column gets the role ``reference`` under every policy except ``research`` (there it
|
|
78
|
+
is left as detected, with a note): it is modeled by the number of rows that share a key, and
|
|
79
|
+
generated keys are fresh values (``profiling.reference``). An override of ``role`` or
|
|
80
|
+
``logical_type`` decides either way (``"reference"`` opts any text or whole-number column in).
|
|
81
|
+
``profile_structure(..., references=False)`` switches the default off.
|
|
82
|
+
|
|
83
|
+
Identifiers
|
|
84
|
+
-----------
|
|
85
|
+
A column is identifier-like when it has at least ``IDENTIFIER_MIN_ROWS`` non-null values and a
|
|
86
|
+
unique ratio (distinct / non-null) of at least ``IDENTIFIER_MIN_UNIQUE_RATIO``, lowered to
|
|
87
|
+
``IDENTIFIER_HINT_UNIQUE_RATIO`` when the column name has an id-like token (``id``, ``uuid``,
|
|
88
|
+
``guid``, ``key``, ``pk``; camelCase aware). Strings must not contain whitespace in most values.
|
|
89
|
+
Integers additionally need *structural evidence*, because many-valued integer measurements
|
|
90
|
+
(e.g. income in whole dollars) are also nearly unique: a name hint, a dense range (span <=
|
|
91
|
+
``IDENTIFIER_DENSE_SPAN_FACTOR`` x distinct, also tested on the central 98% of the values),
|
|
92
|
+
fixed-width codes of at least ``IDENTIFIER_FIXED_WIDTH_DIGITS`` digits, or no repeated value at
|
|
93
|
+
all across ``IDENTIFIER_ALL_DISTINCT_ROWS`` rows or more. A strictly monotone sequence is recorded as supporting
|
|
94
|
+
evidence but is not enough on its own (a measurement exported sorted by value is monotone too).
|
|
95
|
+
Without evidence the column is DISCRETE with a
|
|
96
|
+
note and reduced confidence.
|
|
97
|
+
|
|
98
|
+
Disclosure decisions
|
|
99
|
+
--------------------
|
|
100
|
+
* ``min_value`` / ``max_value``: ``disclosure.clip_bounds`` over the full column (numeric) or its
|
|
101
|
+
epoch representation in ``datetime_unit`` (datetime).
|
|
102
|
+
* ``n_unique``: exact when it is at most ``CATEGORICAL_MAX_LEVELS`` (a structural fact that the
|
|
103
|
+
stored category list reveals anyway) or when the policy has ``min_category_support <= 1``
|
|
104
|
+
(research). Otherwise it is rounded to ``N_UNIQUE_SIGNIFICANT_DIGITS`` significant digits so
|
|
105
|
+
the exact distinct count of e.g. an identifier column is not stored.
|
|
106
|
+
* Float ``NaN`` is treated as null.
|
|
107
|
+
|
|
108
|
+
Performance
|
|
109
|
+
-----------
|
|
110
|
+
Cheap vectorised statistics (null count, distinct count, integrality, monotonicity, bounds) use
|
|
111
|
+
the full column. Expensive checks (string lengths/shapes, date probing, decimals) use a
|
|
112
|
+
deterministic systematic sample of at most ``SAMPLE_ROWS`` rows; decimals use at most
|
|
113
|
+
``DECIMALS_SAMPLE`` distinct values.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
from __future__ import annotations
|
|
117
|
+
|
|
118
|
+
import math
|
|
119
|
+
import re
|
|
120
|
+
from typing import Any, cast
|
|
121
|
+
|
|
122
|
+
import numpy as np
|
|
123
|
+
import polars as pl
|
|
124
|
+
from pydantic import ValidationError
|
|
125
|
+
|
|
126
|
+
from ectype.errors import ProfilingError
|
|
127
|
+
from ectype.fingerprint.disclosure import clip_bounds, resolve_policy
|
|
128
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
|
|
129
|
+
from ectype.io.values import category_labels
|
|
130
|
+
from ectype.profiling.personal import ATTRIBUTE_TOKENS, PersonalHint, detect_personal, name_tokens
|
|
131
|
+
from ectype.profiling.pseudonym import repeat_share, supports_pseudonym
|
|
132
|
+
from ectype.profiling.reference import supports_reference
|
|
133
|
+
from ectype.types import LogicalType, Role
|
|
134
|
+
|
|
135
|
+
__all__ = [
|
|
136
|
+
"profile_structure",
|
|
137
|
+
"shape_signature",
|
|
138
|
+
"CATEGORICAL_MAX_LEVELS",
|
|
139
|
+
"STRING_CATEGORICAL_MIN_LEVELS",
|
|
140
|
+
"STRING_CATEGORICAL_MAX_FRACTION",
|
|
141
|
+
"IDENTIFIER_MIN_ROWS",
|
|
142
|
+
"IDENTIFIER_MIN_UNIQUE_RATIO",
|
|
143
|
+
"IDENTIFIER_HINT_UNIQUE_RATIO",
|
|
144
|
+
"TEXT_MEAN_LENGTH",
|
|
145
|
+
"TEXT_SPACE_FRACTION",
|
|
146
|
+
"DATETIME_PARSE_MIN_FRACTION",
|
|
147
|
+
"SAMPLE_ROWS",
|
|
148
|
+
"PSEUDONYM_MIN_REPEAT_SHARE",
|
|
149
|
+
"REFERENCE_MAX_REPEAT_SHARE",
|
|
150
|
+
"REFERENCE_MIN_LEVELS",
|
|
151
|
+
"REFERENCE_NAME_TOKENS",
|
|
152
|
+
"NUMERIC_PARSE",
|
|
153
|
+
"NUMERIC_PARSE_PERCENT",
|
|
154
|
+
"NUMERIC_PATTERNS",
|
|
155
|
+
"NUMERIC_NA_TOKENS",
|
|
156
|
+
"parse_numeric_strings",
|
|
157
|
+
]
|
|
158
|
+
|
|
159
|
+
# ---------------------------------------------------------------------------------------------
|
|
160
|
+
# Thresholds
|
|
161
|
+
# ---------------------------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
#: integer-valued numerics with at most this many distinct values are integer-coded categoricals
|
|
164
|
+
CATEGORICAL_MAX_LEVELS = 20
|
|
165
|
+
#: string columns are categorical if distinct <= max(MIN_LEVELS, MAX_FRACTION * non-null rows)
|
|
166
|
+
STRING_CATEGORICAL_MIN_LEVELS = 50
|
|
167
|
+
STRING_CATEGORICAL_MAX_FRACTION = 0.05
|
|
168
|
+
#: identifier detection
|
|
169
|
+
IDENTIFIER_MIN_ROWS = 50
|
|
170
|
+
IDENTIFIER_MIN_UNIQUE_RATIO = 0.98
|
|
171
|
+
IDENTIFIER_HINT_UNIQUE_RATIO = 0.90
|
|
172
|
+
IDENTIFIER_NAME_TOKENS = frozenset({"id", "uuid", "guid", "key", "pk"})
|
|
173
|
+
IDENTIFIER_DENSE_SPAN_FACTOR = 2.0
|
|
174
|
+
IDENTIFIER_FIXED_WIDTH_DIGITS = 6
|
|
175
|
+
#: an integer column with no repeated value across this many rows is a key: independent draws
|
|
176
|
+
#: of a measurement would collide (n rows drawn from S values stay distinct with probability
|
|
177
|
+
#: about exp(-n^2 / 2S), so 10,000 distinct rows would need tens of millions of values)
|
|
178
|
+
IDENTIFIER_ALL_DISTINCT_ROWS = 10_000
|
|
179
|
+
#: the dense-range test is repeated on the central part of the values, so that a few stray
|
|
180
|
+
#: keys far from the rest cannot hide a dense block
|
|
181
|
+
IDENTIFIER_DENSE_TRIM = 0.01
|
|
182
|
+
#: free text: mean length above this, or whitespace in at least this fraction of values
|
|
183
|
+
TEXT_MEAN_LENGTH = 30.0
|
|
184
|
+
TEXT_SPACE_FRACTION = 0.5
|
|
185
|
+
#: ISO date/datetime probing of string columns
|
|
186
|
+
DATETIME_PARSE_MIN_FRACTION = 0.95
|
|
187
|
+
#: rounding-precision detection
|
|
188
|
+
DECIMALS_MAX = 10
|
|
189
|
+
DECIMALS_SAMPLE = 10_000
|
|
190
|
+
DECIMALS_ABS_TOL = 1e-6
|
|
191
|
+
DECIMALS_REL_TOL = 1e-12
|
|
192
|
+
#: sampling for expensive checks
|
|
193
|
+
SAMPLE_ROWS = 100_000
|
|
194
|
+
#: coarsening of stored distinct counts
|
|
195
|
+
N_UNIQUE_SIGNIFICANT_DIGITS = 2
|
|
196
|
+
#: shape signatures are truncated to this many characters
|
|
197
|
+
PATTERN_MAX_LENGTH = 64
|
|
198
|
+
|
|
199
|
+
#: a column that looks personal but exceeds the categorical limit is still modeled (as a
|
|
200
|
+
#: pseudonymised categorical) when at least this share of its non-null rows hold a value seen
|
|
201
|
+
#: ``min_category_support`` times or more; below it nothing repeats and the column is excluded
|
|
202
|
+
PSEUDONYM_MIN_REPEAT_SHARE = 0.1
|
|
203
|
+
|
|
204
|
+
#: name tokens that mark a key to another record (reference keys, ADR-0013) ...
|
|
205
|
+
REFERENCE_NAME_TOKENS = frozenset({"id", "key", "ref", "reference", "fk", "uuid", "guid"})
|
|
206
|
+
#: ... or one of these together with a word for a number
|
|
207
|
+
REFERENCE_OWNER_TOKENS = frozenset({"parent", "master"})
|
|
208
|
+
REFERENCE_NUMBER_TOKENS = frozenset({"no", "number", "num", "nbr", "record", "rec"})
|
|
209
|
+
#: a name with one of these describes a quantity, not a key
|
|
210
|
+
REFERENCE_MEASURE_TOKENS = frozenset({"value", "qty", "quantity", "size", "weight", "balance",
|
|
211
|
+
"sum", "avg", "mean", "min", "max", "days", "hours"})
|
|
212
|
+
#: (the attribute words of ``profiling.personal``, apart from the key words themselves)
|
|
213
|
+
_REFERENCE_NOT_A_KEY = ATTRIBUTE_TOKENS - REFERENCE_NAME_TOKENS - {"pk"}
|
|
214
|
+
#: a reference key has more distinct values than this
|
|
215
|
+
REFERENCE_MIN_LEVELS = 20
|
|
216
|
+
#: ... and fewer than this share of its non-null rows hold a value seen
|
|
217
|
+
#: ``min_category_support`` times or more (above it, the column has levels worth keeping);
|
|
218
|
+
#: the count is never taken below ``REFERENCE_MIN_SUPPORT``
|
|
219
|
+
REFERENCE_MAX_REPEAT_SHARE = 0.5
|
|
220
|
+
REFERENCE_MIN_SUPPORT = 10
|
|
221
|
+
|
|
222
|
+
#: zero-padded digit codes with at most this many levels are plain categoricals (more: pooled)
|
|
223
|
+
CODE_CATEGORICAL_MAX_LEVELS = 1000
|
|
224
|
+
#: name tokens marking nominal integer codes (an override hint suggests categorical)
|
|
225
|
+
CODE_NAME_TOKENS = frozenset({"zip", "zipcode", "postal", "postcode", "fips", "naics", "sic"})
|
|
226
|
+
#: numeric strings: ``pattern`` values telling io how to parse them (see parse_numeric_strings)
|
|
227
|
+
NUMERIC_PARSE = "numeric_parse"
|
|
228
|
+
NUMERIC_PARSE_PERCENT = "numeric_parse:%"
|
|
229
|
+
NUMERIC_PATTERNS = frozenset({NUMERIC_PARSE, NUMERIC_PARSE_PERCENT})
|
|
230
|
+
NUMERIC_NA_TOKENS = frozenset({"", "na", "n/a", "nan", "null", "none", "-"})
|
|
231
|
+
|
|
232
|
+
_TRUE_TOKENS = frozenset({"1", "true", "t", "yes", "y", "1.0"})
|
|
233
|
+
_FALSE_TOKENS = frozenset({"0", "false", "f", "no", "n", "0.0"})
|
|
234
|
+
|
|
235
|
+
_BOOLEAN_PAIRS = (
|
|
236
|
+
frozenset({"true", "false"}),
|
|
237
|
+
frozenset({"yes", "no"}),
|
|
238
|
+
frozenset({"y", "n"}),
|
|
239
|
+
frozenset({"t", "f"}),
|
|
240
|
+
frozenset({"0", "1"}),
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
# (strptime format, is_date). "%.f" matches an optional fractional-second part; "%#z" a UTC
|
|
244
|
+
# offset ("+02:00", "+0200" or "Z"). Offset strings parse to UTC datetimes (the column's
|
|
245
|
+
# ``timezone`` becomes "UTC") and are written back with a "+00:00" offset.
|
|
246
|
+
_ISO_FORMATS: tuple[tuple[str, bool], ...] = (
|
|
247
|
+
("%Y-%m-%d", True),
|
|
248
|
+
("%Y-%m-%dT%H:%M:%S%.f", False),
|
|
249
|
+
("%Y-%m-%d %H:%M:%S%.f", False),
|
|
250
|
+
("%Y-%m-%dT%H:%M", False),
|
|
251
|
+
("%Y-%m-%d %H:%M", False),
|
|
252
|
+
("%Y-%m-%dT%H:%M:%S%.f%#z", False),
|
|
253
|
+
("%Y-%m-%d %H:%M:%S%.f%#z", False),
|
|
254
|
+
("%Y-%m-%dT%H:%M%#z", False),
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
_STRUCTURED_NOTE = "structured string - pattern model not available until Phase 2"
|
|
258
|
+
|
|
259
|
+
_OVERRIDE_FORBIDDEN = frozenset({"name", "overridden"})
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# ---------------------------------------------------------------------------------------------
|
|
263
|
+
# Public API
|
|
264
|
+
# ---------------------------------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def profile_structure(df: pl.DataFrame, *, policy: str | DisclosurePolicySpec | None,
|
|
268
|
+
overrides: dict[str, dict] | None = None,
|
|
269
|
+
references: bool = True) -> list[ColumnSchema]:
|
|
270
|
+
"""Infer a :class:`ColumnSchema` for every column of ``df`` (in source column order).
|
|
271
|
+
|
|
272
|
+
``overrides`` maps column names to dicts of ``ColumnSchema`` fields, applied after
|
|
273
|
+
detection (``overridden=True``). Raises :class:`ProfilingError` for empty frames, duplicate
|
|
274
|
+
column names, unknown override columns/fields or invalid override values.
|
|
275
|
+
``references=False`` leaves reference keys (ADR-0013) to explicit overrides.
|
|
276
|
+
"""
|
|
277
|
+
if isinstance(df, pl.LazyFrame):
|
|
278
|
+
df = df.collect()
|
|
279
|
+
columns = list(getattr(df, "columns", []))
|
|
280
|
+
if len(set(columns)) != len(columns):
|
|
281
|
+
dupes = sorted({c for c in columns if columns.count(c) > 1})
|
|
282
|
+
raise ProfilingError(f"duplicate column names: {dupes}")
|
|
283
|
+
if not isinstance(df, pl.DataFrame):
|
|
284
|
+
raise ProfilingError(f"expected a polars DataFrame, got {type(df).__name__}")
|
|
285
|
+
if df.width == 0 or df.height == 0:
|
|
286
|
+
raise ProfilingError(f"cannot profile an empty frame (shape {df.shape})")
|
|
287
|
+
pol = resolve_policy(policy)
|
|
288
|
+
overrides = _check_overrides(overrides, columns)
|
|
289
|
+
|
|
290
|
+
n = df.height
|
|
291
|
+
if n > SAMPLE_ROWS:
|
|
292
|
+
idx = np.linspace(0, n - 1, SAMPLE_ROWS).round().astype(np.int64)
|
|
293
|
+
sample_df = df[idx]
|
|
294
|
+
else:
|
|
295
|
+
sample_df = df
|
|
296
|
+
|
|
297
|
+
out: list[ColumnSchema] = []
|
|
298
|
+
for name in columns:
|
|
299
|
+
spec = overrides.get(name, {})
|
|
300
|
+
# an override of the role or the type is a statement about the column: the
|
|
301
|
+
# reference-key default does not apply to it
|
|
302
|
+
col = _profile_column(df.get_column(name), sample_df.get_column(name), pol,
|
|
303
|
+
references=references and "role" not in spec
|
|
304
|
+
and "logical_type" not in spec)
|
|
305
|
+
if name in overrides:
|
|
306
|
+
col = _apply_override(col, overrides[name], df.get_column(name), pol,
|
|
307
|
+
sample_df.get_column(name))
|
|
308
|
+
out.append(col)
|
|
309
|
+
return out
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def shape_signature(value: str) -> str:
|
|
313
|
+
"""Letters -> ``A``, digits -> ``9``, everything else kept (e.g. ``"AB-12"`` -> ``"AA-99"``)."""
|
|
314
|
+
s = pl.Series([value]).str.replace_all(r"\p{L}", "A").str.replace_all(r"[0-9]", "9")
|
|
315
|
+
return str(s[0])[:PATTERN_MAX_LENGTH]
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---------------------------------------------------------------------------------------------
|
|
319
|
+
# Per-column detection
|
|
320
|
+
# ---------------------------------------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _margin(value: float, threshold: float, width: float) -> float:
|
|
324
|
+
"""Confidence in [0.5, 1]: 0.5 exactly at a threshold, 1 at ``width`` or more away."""
|
|
325
|
+
if width <= 0:
|
|
326
|
+
return 1.0
|
|
327
|
+
return 0.5 + 0.5 * min(1.0, abs(value - threshold) / width)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _name_hint(name: str) -> bool:
|
|
331
|
+
snake = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name)
|
|
332
|
+
snake = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1_\2", snake).lower()
|
|
333
|
+
tokens = [t for t in re.split(r"[^a-z0-9]+", snake) if t]
|
|
334
|
+
return any(t in IDENTIFIER_NAME_TOKENS for t in tokens)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _coarse_n_unique(k: int, policy: DisclosurePolicySpec) -> int:
|
|
338
|
+
if k <= CATEGORICAL_MAX_LEVELS or policy.min_category_support <= 1:
|
|
339
|
+
return int(k)
|
|
340
|
+
digits = N_UNIQUE_SIGNIFICANT_DIGITS - int(math.floor(math.log10(k))) - 1
|
|
341
|
+
return max(1, int(round(k, digits)))
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _bounds(values: np.ndarray, policy: DisclosurePolicySpec) -> tuple[float | None, float | None]:
|
|
345
|
+
lo, hi = clip_bounds(values, policy)
|
|
346
|
+
if not (math.isfinite(lo) and math.isfinite(hi)):
|
|
347
|
+
return None, None
|
|
348
|
+
return float(lo), float(hi)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _numeric_values(s: pl.Series) -> np.ndarray:
|
|
352
|
+
if s.dtype == pl.Boolean:
|
|
353
|
+
s = s.cast(pl.Int8)
|
|
354
|
+
return s.drop_nulls().cast(pl.Float64).to_numpy()
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _temporal_values(s: pl.Series) -> tuple[np.ndarray, str]:
|
|
358
|
+
s = s.drop_nulls()
|
|
359
|
+
if s.dtype == pl.Date:
|
|
360
|
+
return s.cast(pl.Int32).cast(pl.Float64).to_numpy(), "d"
|
|
361
|
+
s = s.dt.cast_time_unit("us")
|
|
362
|
+
return s.cast(pl.Int64).cast(pl.Float64).to_numpy(), "us"
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _detect_decimals(values: np.ndarray) -> int | None:
|
|
366
|
+
v = np.asarray(values, dtype=float)
|
|
367
|
+
v = v[np.isfinite(v)]
|
|
368
|
+
if v.size == 0:
|
|
369
|
+
return None
|
|
370
|
+
v = np.unique(v)
|
|
371
|
+
if v.size > DECIMALS_SAMPLE:
|
|
372
|
+
v = v[np.linspace(0, v.size - 1, DECIMALS_SAMPLE).round().astype(np.int64)]
|
|
373
|
+
for d in range(DECIMALS_MAX + 1):
|
|
374
|
+
scaled = v * (10.0 ** d)
|
|
375
|
+
resid = np.abs(scaled - np.round(scaled))
|
|
376
|
+
if np.all(resid <= DECIMALS_ABS_TOL + DECIMALS_REL_TOL * np.abs(scaled)):
|
|
377
|
+
return d
|
|
378
|
+
return None
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _is_integer_dtype(dt: pl.DataType) -> bool:
|
|
382
|
+
return dt.is_integer()
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _base(s: pl.Series, null_count: int) -> dict[str, Any]:
|
|
386
|
+
n = s.len()
|
|
387
|
+
return {
|
|
388
|
+
"name": s.name,
|
|
389
|
+
"physical_dtype": str(s.dtype),
|
|
390
|
+
"nullable": null_count > 0,
|
|
391
|
+
"null_fraction": float(null_count / n) if n else 0.0,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _profile_column(s: pl.Series, sample: pl.Series, policy: DisclosurePolicySpec, *,
|
|
396
|
+
references: bool = True) -> ColumnSchema:
|
|
397
|
+
dtype = s.dtype
|
|
398
|
+
if dtype.is_float():
|
|
399
|
+
s = s.fill_nan(None)
|
|
400
|
+
sample = sample.fill_nan(None)
|
|
401
|
+
null_count = s.null_count()
|
|
402
|
+
base = _base(s, null_count)
|
|
403
|
+
nn = s.len() - null_count
|
|
404
|
+
|
|
405
|
+
is_string = dtype in (pl.String, pl.Categorical) or isinstance(dtype, pl.Enum)
|
|
406
|
+
is_temporal = dtype in (pl.Date,) or isinstance(dtype, pl.Datetime)
|
|
407
|
+
is_numeric = dtype.is_numeric()
|
|
408
|
+
is_bool = dtype == pl.Boolean
|
|
409
|
+
|
|
410
|
+
if nn == 0:
|
|
411
|
+
return ColumnSchema(**base, logical_type=_fallback_type(dtype), role=Role.CONSTANT,
|
|
412
|
+
n_unique=0, notes=["all values are null"])
|
|
413
|
+
|
|
414
|
+
if not (is_string or is_temporal or is_numeric or is_bool):
|
|
415
|
+
return ColumnSchema(**base, logical_type=LogicalType.STRING, role=Role.EXCLUDED,
|
|
416
|
+
notes=[f"unsupported dtype {dtype}; column excluded"])
|
|
417
|
+
|
|
418
|
+
if is_string and dtype != pl.String:
|
|
419
|
+
s = s.cast(pl.String)
|
|
420
|
+
sample = sample.cast(pl.String)
|
|
421
|
+
|
|
422
|
+
k = int(s.drop_nulls().n_unique())
|
|
423
|
+
base["n_unique"] = _coarse_n_unique(k, policy)
|
|
424
|
+
|
|
425
|
+
if k == 1:
|
|
426
|
+
return _constant(s, base, dtype, policy)
|
|
427
|
+
if is_bool:
|
|
428
|
+
return ColumnSchema(**base, logical_type=LogicalType.BOOLEAN)
|
|
429
|
+
if is_temporal:
|
|
430
|
+
return _datetime(s, base, policy)
|
|
431
|
+
if is_numeric:
|
|
432
|
+
col = _numeric(s, sample, base, k, nn, policy)
|
|
433
|
+
else:
|
|
434
|
+
col = _string(s, sample, base, k, nn, policy)
|
|
435
|
+
col = _personal_default(col, s, sample, k, policy)
|
|
436
|
+
return _reference_default(col, s, k, nn, policy) if references else col
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
# ---------------------------------------------------------------------------------------------
|
|
440
|
+
# Reference keys (ADR-0013)
|
|
441
|
+
# ---------------------------------------------------------------------------------------------
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def _reference_name(name: str) -> str | None:
|
|
445
|
+
"""The token of a column name that marks a key to another record, or None."""
|
|
446
|
+
tokens = name_tokens(name)
|
|
447
|
+
words = {t for t in tokens if t.isalpha()}
|
|
448
|
+
if words & (_REFERENCE_NOT_A_KEY | REFERENCE_MEASURE_TOKENS):
|
|
449
|
+
return None # the name describes a property or a quantity
|
|
450
|
+
for t in tokens:
|
|
451
|
+
if t in REFERENCE_NAME_TOKENS:
|
|
452
|
+
return t
|
|
453
|
+
if words & REFERENCE_NUMBER_TOKENS:
|
|
454
|
+
return next((t for t in tokens if t in REFERENCE_OWNER_TOKENS), None)
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _as_reference(col: ColumnSchema, s: pl.Series, note: str) -> ColumnSchema:
|
|
459
|
+
"""``col`` as a reference key. ``profiling.reference.rewrite_references`` completes the
|
|
460
|
+
schema (the bounds of the group sizes) when the fingerprint is fitted."""
|
|
461
|
+
nulls = (s.fill_nan(None) if s.dtype.is_float() else s).null_count()
|
|
462
|
+
physical = col.physical_dtype
|
|
463
|
+
if physical.startswith(("Enum", "Categorical")):
|
|
464
|
+
physical = "String" # an Enum dtype lists the source keys
|
|
465
|
+
return ColumnSchema(name=col.name, physical_dtype=physical, nullable=nulls > 0,
|
|
466
|
+
null_fraction=float(nulls / s.len()) if s.len() else 0.0,
|
|
467
|
+
logical_type=LogicalType.DISCRETE, role=Role.REFERENCE,
|
|
468
|
+
integer_valued=True, decimals=0,
|
|
469
|
+
confidence=min(col.confidence, 0.9), overridden=col.overridden,
|
|
470
|
+
notes=[note])
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _reference_default(col: ColumnSchema, s: pl.Series, k: int, nn: int,
|
|
474
|
+
policy: DisclosurePolicySpec) -> ColumnSchema:
|
|
475
|
+
"""Apply the reference-key default to a profiled column (see the module docstring)."""
|
|
476
|
+
numeric = s.dtype.is_numeric()
|
|
477
|
+
if numeric:
|
|
478
|
+
if not (col.role == Role.FEATURE and col.logical_type == LogicalType.DISCRETE
|
|
479
|
+
and col.integer_valued):
|
|
480
|
+
return col
|
|
481
|
+
elif s.dtype == pl.String:
|
|
482
|
+
coded = col.role == Role.FEATURE and (
|
|
483
|
+
col.logical_type == LogicalType.CATEGORICAL
|
|
484
|
+
or (col.logical_type == LogicalType.DISCRETE and col.integer_valued))
|
|
485
|
+
if not (coded or (col.role == Role.EXCLUDED and col.logical_type == LogicalType.STRING)):
|
|
486
|
+
return col
|
|
487
|
+
else:
|
|
488
|
+
return col
|
|
489
|
+
if nn < IDENTIFIER_MIN_ROWS or k <= REFERENCE_MIN_LEVELS or k >= nn:
|
|
490
|
+
return col
|
|
491
|
+
token = _reference_name(col.name)
|
|
492
|
+
if token is None:
|
|
493
|
+
return col
|
|
494
|
+
if numeric and float(cast(float, s.min())) < 0:
|
|
495
|
+
return col
|
|
496
|
+
# (what a categorical would keep under the policy; never less than the standard minimum,
|
|
497
|
+
# or a policy that keeps every value would see levels everywhere)
|
|
498
|
+
support = max(int(policy.min_category_support), REFERENCE_MIN_SUPPORT)
|
|
499
|
+
share = repeat_share(s, policy.model_copy(update={"min_category_support": support}))
|
|
500
|
+
if share >= REFERENCE_MAX_REPEAT_SHARE:
|
|
501
|
+
return col
|
|
502
|
+
what = (f"looks like a reference key (column name token '{token}'; its values repeat, but "
|
|
503
|
+
f"only {share:.0%} of its rows hold a value seen at least {support} times)")
|
|
504
|
+
if policy.sensitive or policy.profile == "research":
|
|
505
|
+
return col.model_copy(update={"notes": [
|
|
506
|
+
*col.notes, f"{what}; left as detected under the {policy.profile} policy "
|
|
507
|
+
f"(override role to 'reference' to model its repeat structure and "
|
|
508
|
+
f"generate fresh keys)"]})
|
|
509
|
+
nonnull = (s.fill_nan(None) if s.dtype.is_float() else s).drop_nulls()
|
|
510
|
+
if numeric and not _reference_room(s.dtype, nonnull):
|
|
511
|
+
return col.model_copy(update={"notes": [
|
|
512
|
+
*col.notes, f"{what}; left as detected: its dtype {s.dtype} has no room for fresh "
|
|
513
|
+
f"keys above the source's (cast it to Int64 and it becomes a "
|
|
514
|
+
f"reference)"]})
|
|
515
|
+
return _as_reference(col, s, f"{what}; role 'reference' by default under the "
|
|
516
|
+
f"{policy.profile} policy (override role to 'feature' to "
|
|
517
|
+
f"model the values themselves)")
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _reference_room(dtype: pl.DataType, nonnull: pl.Series) -> bool:
|
|
521
|
+
from ectype.profiling.reference import has_room
|
|
522
|
+
|
|
523
|
+
return has_room(dtype, nonnull)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
# ---------------------------------------------------------------------------------------------
|
|
527
|
+
# Personal data (ADR-0010)
|
|
528
|
+
# ---------------------------------------------------------------------------------------------
|
|
529
|
+
|
|
530
|
+
_OPT_IN = "override role to 'pseudonym' to replace its values by stand-in tokens"
|
|
531
|
+
_OPT_OUT = "override role to 'feature' to keep the real values"
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _personal_hint(col: ColumnSchema, s: pl.Series, sample: pl.Series,
|
|
535
|
+
k: int) -> PersonalHint | None:
|
|
536
|
+
"""The personal-data hint for a profiled column, or None: only text columns and integer
|
|
537
|
+
codes are screened (booleans, dates and measurements never are)."""
|
|
538
|
+
if col.role in (Role.CONSTANT, Role.DERIVED):
|
|
539
|
+
return None
|
|
540
|
+
if col.logical_type in (LogicalType.BOOLEAN, LogicalType.DATETIME):
|
|
541
|
+
return None
|
|
542
|
+
numeric = s.dtype.is_numeric()
|
|
543
|
+
if numeric and not (col.logical_type == LogicalType.DISCRETE and col.integer_valued):
|
|
544
|
+
return None
|
|
545
|
+
if not (numeric or s.dtype == pl.String):
|
|
546
|
+
return None
|
|
547
|
+
return detect_personal(col.name, category_labels(sample), k, numeric=numeric)
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _as_pseudonym(col: ColumnSchema, s: pl.Series, note: str, *,
|
|
551
|
+
keep_notes: bool = True) -> ColumnSchema:
|
|
552
|
+
"""``col`` as a pseudonymised categorical: the numeric facts of a column first read as a
|
|
553
|
+
number no longer apply, and nulls are the raw nulls again. ``keep_notes=False`` drops the
|
|
554
|
+
notes of the decision this one replaces (for example "free text ... excluded")."""
|
|
555
|
+
nulls = (s.fill_nan(None) if s.dtype.is_float() else s).null_count()
|
|
556
|
+
# an Enum dtype lists the source labels: a pseudonymised column is generated as String
|
|
557
|
+
physical = "String" if col.physical_dtype.startswith("Enum") else col.physical_dtype
|
|
558
|
+
return ColumnSchema(name=col.name, physical_dtype=physical, nullable=nulls > 0,
|
|
559
|
+
null_fraction=float(nulls / s.len()) if s.len() else 0.0,
|
|
560
|
+
n_unique=col.n_unique, logical_type=LogicalType.CATEGORICAL,
|
|
561
|
+
role=Role.PSEUDONYM, confidence=min(col.confidence, 0.9),
|
|
562
|
+
overridden=col.overridden,
|
|
563
|
+
notes=[*(col.notes if keep_notes else []), note])
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
def _personal_default(col: ColumnSchema, s: pl.Series, sample: pl.Series, k: int,
|
|
567
|
+
policy: DisclosurePolicySpec) -> ColumnSchema:
|
|
568
|
+
"""Apply the personal-data default to a profiled column (see the module docstring)."""
|
|
569
|
+
hint = _personal_hint(col, s, sample, k)
|
|
570
|
+
if hint is None:
|
|
571
|
+
return col
|
|
572
|
+
what = f"looks like personal data ({hint.describe()})"
|
|
573
|
+
|
|
574
|
+
def noted(note: str, **update: Any) -> ColumnSchema:
|
|
575
|
+
return col.model_copy(update={**update, "notes": [*col.notes, note]})
|
|
576
|
+
|
|
577
|
+
if col.role == Role.IDENTIFIER:
|
|
578
|
+
return noted(f"{what}; identifiers are regenerated, never copied")
|
|
579
|
+
if policy.sensitive or policy.profile == "research":
|
|
580
|
+
if col.role == Role.EXCLUDED:
|
|
581
|
+
return noted(f"{what}; {_OPT_IN}")
|
|
582
|
+
return noted(f"{what}; real values are kept under the {policy.profile} policy "
|
|
583
|
+
f"({_OPT_IN})")
|
|
584
|
+
if col.role == Role.FEATURE and col.logical_type == LogicalType.CATEGORICAL:
|
|
585
|
+
return _as_pseudonym(col, s, f"{what}; role 'pseudonym' by default under the "
|
|
586
|
+
f"{policy.profile} policy ({_OPT_OUT})")
|
|
587
|
+
share = repeat_share(s, policy)
|
|
588
|
+
support = int(policy.min_category_support)
|
|
589
|
+
if share >= PSEUDONYM_MIN_REPEAT_SHARE:
|
|
590
|
+
otherwise = ("excluded as text" if col.role == Role.EXCLUDED
|
|
591
|
+
else f"modeled as a {col.logical_type.value} column")
|
|
592
|
+
return _as_pseudonym(
|
|
593
|
+
col, s, f"{what}; modeled as a pseudonymised categorical at any table size "
|
|
594
|
+
f"({share:.0%} of its rows hold a value seen at least {support} times; "
|
|
595
|
+
f"rarer values are pooled into '__other__'; a column that does not look "
|
|
596
|
+
f"personal would be {otherwise} here); {_OPT_OUT}", keep_notes=False)
|
|
597
|
+
return noted(f"{what}; its values hardly repeat ({share:.0%} of its rows hold a value seen "
|
|
598
|
+
f"at least {support} times), so there are no levels to model: excluded from "
|
|
599
|
+
f"generation (override role to 'pseudonym' or 'identifier' to generate "
|
|
600
|
+
f"stand-ins)", role=Role.EXCLUDED)
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def _fallback_type(dtype: pl.DataType) -> LogicalType:
|
|
604
|
+
if dtype == pl.Boolean:
|
|
605
|
+
return LogicalType.BOOLEAN
|
|
606
|
+
if dtype == pl.Date or isinstance(dtype, pl.Datetime):
|
|
607
|
+
return LogicalType.DATETIME
|
|
608
|
+
if dtype.is_integer():
|
|
609
|
+
return LogicalType.DISCRETE
|
|
610
|
+
if dtype.is_float():
|
|
611
|
+
return LogicalType.CONTINUOUS
|
|
612
|
+
if dtype in (pl.String, pl.Categorical) or isinstance(dtype, pl.Enum):
|
|
613
|
+
return LogicalType.CATEGORICAL
|
|
614
|
+
return LogicalType.STRING
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _constant(s: pl.Series, base: dict[str, Any], dtype: pl.DataType,
|
|
618
|
+
policy: DisclosurePolicySpec) -> ColumnSchema:
|
|
619
|
+
lt = _fallback_type(dtype)
|
|
620
|
+
extra: dict[str, Any] = {}
|
|
621
|
+
if dtype.is_numeric():
|
|
622
|
+
v = _numeric_values(s)
|
|
623
|
+
integral = bool(np.all(v == np.round(v)))
|
|
624
|
+
if dtype.is_float() and not integral:
|
|
625
|
+
lt = LogicalType.CONTINUOUS
|
|
626
|
+
else:
|
|
627
|
+
lt = LogicalType.DISCRETE
|
|
628
|
+
extra["integer_valued"] = True
|
|
629
|
+
extra["decimals"] = _detect_decimals(v[:1])
|
|
630
|
+
extra["min_value"], extra["max_value"] = _bounds(v, policy)
|
|
631
|
+
elif lt == LogicalType.DATETIME:
|
|
632
|
+
v, unit = _temporal_values(s)
|
|
633
|
+
extra.update(_datetime_meta(s.dtype, unit))
|
|
634
|
+
extra["min_value"], extra["max_value"] = _bounds(v, policy)
|
|
635
|
+
return ColumnSchema(**base, **extra, logical_type=lt, role=Role.CONSTANT,
|
|
636
|
+
notes=["single distinct non-null value"])
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _datetime_meta(dtype: pl.DataType, unit: str) -> dict[str, Any]:
|
|
640
|
+
tz = getattr(dtype, "time_zone", None) if isinstance(dtype, pl.Datetime) else None
|
|
641
|
+
return {"datetime_unit": unit, "is_date": unit == "d", "timezone": tz}
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _datetime(s: pl.Series, base: dict[str, Any], policy: DisclosurePolicySpec) -> ColumnSchema:
|
|
645
|
+
v, unit = _temporal_values(s)
|
|
646
|
+
lo, hi = _bounds(v, policy)
|
|
647
|
+
return ColumnSchema(**base, logical_type=LogicalType.DATETIME, min_value=lo, max_value=hi,
|
|
648
|
+
**_datetime_meta(s.dtype, unit))
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _boolean_pair(values: list[Any]) -> bool:
|
|
652
|
+
labels = frozenset(str(x).strip().lower() for x in values)
|
|
653
|
+
if len(labels) != 2:
|
|
654
|
+
return False
|
|
655
|
+
if labels in _BOOLEAN_PAIRS:
|
|
656
|
+
return True
|
|
657
|
+
# numeric 0/1 stored as floats ("0.0", "1.0")
|
|
658
|
+
try:
|
|
659
|
+
nums = frozenset(float(x) for x in values)
|
|
660
|
+
except (TypeError, ValueError):
|
|
661
|
+
return False
|
|
662
|
+
return nums == frozenset({0.0, 1.0})
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def _numeric(s: pl.Series, sample: pl.Series, base: dict[str, Any], k: int, nn: int,
|
|
666
|
+
policy: DisclosurePolicySpec) -> ColumnSchema:
|
|
667
|
+
nonnull = s.drop_nulls()
|
|
668
|
+
if k == 2 and _boolean_pair(nonnull.unique().to_list()):
|
|
669
|
+
return ColumnSchema(**base, logical_type=LogicalType.BOOLEAN,
|
|
670
|
+
notes=["0/1 coded boolean"])
|
|
671
|
+
|
|
672
|
+
v = _numeric_values(s)
|
|
673
|
+
finite = v[np.isfinite(v)]
|
|
674
|
+
integral = _is_integer_dtype(s.dtype) or bool(np.all(finite == np.round(finite)))
|
|
675
|
+
lo, hi = _bounds(v, policy)
|
|
676
|
+
|
|
677
|
+
if not integral:
|
|
678
|
+
decimals = _detect_decimals(_numeric_values(sample))
|
|
679
|
+
return ColumnSchema(**base, logical_type=LogicalType.CONTINUOUS, decimals=decimals,
|
|
680
|
+
min_value=lo, max_value=hi)
|
|
681
|
+
|
|
682
|
+
notes: list[str] = []
|
|
683
|
+
ratio = k / nn
|
|
684
|
+
hint = _name_hint(str(s.name))
|
|
685
|
+
threshold = IDENTIFIER_HINT_UNIQUE_RATIO if hint else IDENTIFIER_MIN_UNIQUE_RATIO
|
|
686
|
+
if nn >= IDENTIFIER_MIN_ROWS and ratio >= threshold:
|
|
687
|
+
evidence = _integer_id_evidence(nonnull, finite, k, hint)
|
|
688
|
+
# monotonicity alone is not evidence: a measurement exported sorted by value is
|
|
689
|
+
# monotone too. It only supports a name hint or a dense range.
|
|
690
|
+
if evidence and evidence != ["monotone sequence"]:
|
|
691
|
+
conf = _margin(ratio, threshold, 1.0 - threshold) if ratio < 1.0 else 1.0
|
|
692
|
+
return ColumnSchema(**base, logical_type=LogicalType.DISCRETE,
|
|
693
|
+
role=Role.IDENTIFIER, integer_valued=True, decimals=0,
|
|
694
|
+
min_value=lo, max_value=hi, confidence=conf,
|
|
695
|
+
notes=[f"identifier ({', '.join(evidence)})"])
|
|
696
|
+
notes.append("nearly unique integer without identifier evidence; "
|
|
697
|
+
"override role to 'identifier' if it is a key")
|
|
698
|
+
|
|
699
|
+
if k <= CATEGORICAL_MAX_LEVELS:
|
|
700
|
+
# Few-level integers stay numeric (DISCRETE): arithmetic in expressions keeps working,
|
|
701
|
+
# rare values merge into numeric neighbours instead of a string "__other__" bucket,
|
|
702
|
+
# and the randomized-PIT copula still captures their dependence. Nominal integer codes
|
|
703
|
+
# should be overridden to categorical by the user.
|
|
704
|
+
conf = _margin(k, CATEGORICAL_MAX_LEVELS + 0.5, 5)
|
|
705
|
+
return ColumnSchema(**base, logical_type=LogicalType.DISCRETE, integer_valued=True,
|
|
706
|
+
decimals=0, min_value=lo, max_value=hi, confidence=min(conf, 0.7),
|
|
707
|
+
notes=["few-level integer modeled as discrete; override "
|
|
708
|
+
"logical_type to 'categorical' if the codes are nominal",
|
|
709
|
+
*notes])
|
|
710
|
+
|
|
711
|
+
if _zip_like_integers(str(s.name), finite):
|
|
712
|
+
notes.append("integer values look like fixed-width nominal codes (e.g. zip codes); "
|
|
713
|
+
"override logical_type to 'categorical' if they are not quantities")
|
|
714
|
+
conf = _margin(k, CATEGORICAL_MAX_LEVELS + 0.5, 10)
|
|
715
|
+
if notes:
|
|
716
|
+
conf = min(conf, 0.6)
|
|
717
|
+
return ColumnSchema(**base, logical_type=LogicalType.DISCRETE, integer_valued=True,
|
|
718
|
+
decimals=0, min_value=lo, max_value=hi, confidence=conf, notes=notes)
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def _zip_like_integers(name: str, finite: np.ndarray) -> bool:
|
|
722
|
+
"""Code-like name (zip, postal, ...), or non-negative integers of at most 5 digits whose
|
|
723
|
+
zero-padded width is fixed at 5 (most values have 5 digits, the rest look like lost leading
|
|
724
|
+
zeros) and that are sparse over their range (not a count or measurement)."""
|
|
725
|
+
if finite.size == 0 or finite.min() < 0:
|
|
726
|
+
return False
|
|
727
|
+
if _code_name_hint(name):
|
|
728
|
+
return True
|
|
729
|
+
if finite.max() >= 100_000 or finite.max() < 10_000:
|
|
730
|
+
return False
|
|
731
|
+
k = np.unique(finite).size
|
|
732
|
+
span = float(finite.max() - finite.min()) + 1.0
|
|
733
|
+
return bool(np.mean(finite >= 10_000) >= 0.5 and span > 20 * k)
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _integer_id_evidence(nonnull: pl.Series, finite: np.ndarray, k: int, hint: bool) -> list[str]:
|
|
737
|
+
evidence: list[str] = []
|
|
738
|
+
if hint:
|
|
739
|
+
evidence.append("name hint")
|
|
740
|
+
if nonnull.len() > 1:
|
|
741
|
+
d = np.diff(finite)
|
|
742
|
+
if d.size and (np.all(d > 0) or np.all(d < 0)):
|
|
743
|
+
evidence.append("monotone sequence")
|
|
744
|
+
if finite.size:
|
|
745
|
+
span = float(finite.max() - finite.min()) + 1.0
|
|
746
|
+
lo, hi = np.quantile(finite, [IDENTIFIER_DENSE_TRIM, 1.0 - IDENTIFIER_DENSE_TRIM])
|
|
747
|
+
inner = float(hi - lo) + 1.0
|
|
748
|
+
if span <= IDENTIFIER_DENSE_SPAN_FACTOR * k:
|
|
749
|
+
evidence.append("dense range")
|
|
750
|
+
elif inner <= IDENTIFIER_DENSE_SPAN_FACTOR * k * (1.0 - 2.0 * IDENTIFIER_DENSE_TRIM):
|
|
751
|
+
evidence.append("dense range apart from outliers")
|
|
752
|
+
if k == nonnull.len() and k >= IDENTIFIER_ALL_DISTINCT_ROWS:
|
|
753
|
+
evidence.append(f"no repeated value in {k:,} rows")
|
|
754
|
+
absv = np.abs(finite)
|
|
755
|
+
if absv.min() >= 10 ** (IDENTIFIER_FIXED_WIDTH_DIGITS - 1):
|
|
756
|
+
widths = np.floor(np.log10(absv)).astype(np.int64)
|
|
757
|
+
if np.min(widths) == np.max(widths):
|
|
758
|
+
evidence.append("fixed-width code")
|
|
759
|
+
return evidence
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _most_common_shape(sample: pl.Series) -> tuple[str | None, float]:
|
|
763
|
+
vals = sample.drop_nulls()
|
|
764
|
+
if vals.len() == 0:
|
|
765
|
+
return None, 0.0
|
|
766
|
+
shapes = (vals.str.slice(0, PATTERN_MAX_LENGTH)
|
|
767
|
+
.str.replace_all(r"\p{L}", "A").str.replace_all(r"[0-9]", "9"))
|
|
768
|
+
vc = shapes.value_counts(name="__n").sort(["__n", shapes.name], descending=[True, False])
|
|
769
|
+
top = vc.row(0)
|
|
770
|
+
return str(top[0]), float(top[1] / vals.len())
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _probe_datetime(s: pl.Series, sample: pl.Series) -> tuple[str, bool, float, float] | None:
|
|
774
|
+
"""Best ISO format: (format, is_date, sample fraction parsed, full fraction parsed)."""
|
|
775
|
+
smp = sample.drop_nulls().str.strip_chars()
|
|
776
|
+
if smp.len() == 0:
|
|
777
|
+
return None
|
|
778
|
+
best: tuple[str, bool, float] | None = None
|
|
779
|
+
for fmt, is_date in _ISO_FORMATS:
|
|
780
|
+
target = pl.Date if is_date else pl.Datetime("us")
|
|
781
|
+
parsed = smp.str.strptime(target, fmt, strict=False)
|
|
782
|
+
frac = 1.0 - parsed.null_count() / smp.len()
|
|
783
|
+
if best is None or frac > best[2]:
|
|
784
|
+
best = (fmt, is_date, frac)
|
|
785
|
+
if best is None or best[2] < DATETIME_PARSE_MIN_FRACTION:
|
|
786
|
+
return None
|
|
787
|
+
fmt, is_date, frac = best
|
|
788
|
+
full = s.drop_nulls().str.strip_chars()
|
|
789
|
+
target = pl.Date if is_date else pl.Datetime("us")
|
|
790
|
+
parsed_full = full.str.strptime(target, fmt, strict=False)
|
|
791
|
+
full_frac = 1.0 - parsed_full.null_count() / full.len()
|
|
792
|
+
return fmt, is_date, frac, full_frac
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
def _bool_labels(values: list[Any]) -> tuple[str, str] | None:
|
|
796
|
+
"""``(false_label, true_label)`` in their exact source spelling, or None if ambiguous."""
|
|
797
|
+
false_l = [str(v) for v in values if str(v).strip().lower() in _FALSE_TOKENS]
|
|
798
|
+
true_l = [str(v) for v in values if str(v).strip().lower() in _TRUE_TOKENS]
|
|
799
|
+
if len(false_l) == 1 and len(true_l) == 1:
|
|
800
|
+
return false_l[0], true_l[0]
|
|
801
|
+
return None
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def parse_numeric_strings(s: pl.Series, pattern: str | None = NUMERIC_PARSE) -> pl.Series:
|
|
805
|
+
"""Parse a numeric-string column (see ``NUMERIC_PARSE``) to Float64.
|
|
806
|
+
|
|
807
|
+
Values are stripped of surrounding whitespace; NA tokens (``NUMERIC_NA_TOKENS``, case
|
|
808
|
+
insensitive) become null; with ``pattern == NUMERIC_PARSE_PERCENT`` a trailing ``"%"`` is
|
|
809
|
+
removed (the number is kept as written, e.g. ``"12.5%"`` -> 12.5). Anything else that does
|
|
810
|
+
not parse becomes null.
|
|
811
|
+
"""
|
|
812
|
+
t = s.cast(pl.String).str.strip_chars()
|
|
813
|
+
if pattern == NUMERIC_PARSE_PERCENT:
|
|
814
|
+
t = t.str.strip_suffix("%").str.strip_chars()
|
|
815
|
+
na = t.str.to_lowercase().is_in(list(NUMERIC_NA_TOKENS))
|
|
816
|
+
t = pl.select(pl.when(na).then(None).otherwise(t).alias(s.name)).to_series()
|
|
817
|
+
return t.cast(pl.Float64, strict=False).fill_nan(None)
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def _numeric_string(s: pl.Series, sample: pl.Series, base: dict[str, Any],
|
|
821
|
+
policy: DisclosurePolicySpec) -> ColumnSchema | None:
|
|
822
|
+
"""A string column whose non-NA values all parse as numbers (optionally all with a ``%``
|
|
823
|
+
suffix) is profiled as a number with ``pattern`` set to the parse rule."""
|
|
824
|
+
smp = sample.drop_nulls().str.strip_chars()
|
|
825
|
+
if smp.len() == 0:
|
|
826
|
+
return None
|
|
827
|
+
nonna = smp.filter(~smp.str.to_lowercase().is_in(list(NUMERIC_NA_TOKENS)))
|
|
828
|
+
if nonna.len() == 0:
|
|
829
|
+
return None
|
|
830
|
+
pct = bool(nonna.str.ends_with("%").all())
|
|
831
|
+
pattern = NUMERIC_PARSE_PERCENT if pct else NUMERIC_PARSE
|
|
832
|
+
if parse_numeric_strings(nonna, pattern).null_count() > 0:
|
|
833
|
+
return None
|
|
834
|
+
full = parse_numeric_strings(s, pattern)
|
|
835
|
+
raw_nonnull = s.drop_nulls()
|
|
836
|
+
n_bad = int(full.null_count() - s.null_count())
|
|
837
|
+
lowered = raw_nonnull.str.strip_chars().str.to_lowercase()
|
|
838
|
+
n_na = int(lowered.is_in(list(NUMERIC_NA_TOKENS)).sum())
|
|
839
|
+
if n_bad != n_na: # some value outside the sample does not parse
|
|
840
|
+
return None
|
|
841
|
+
nn = full.len() - full.null_count()
|
|
842
|
+
if nn == 0:
|
|
843
|
+
return None
|
|
844
|
+
k = int(full.drop_nulls().n_unique())
|
|
845
|
+
nb = {**base, "n_unique": _coarse_n_unique(k, policy),
|
|
846
|
+
"nullable": full.null_count() > 0,
|
|
847
|
+
"null_fraction": float(full.null_count() / full.len())}
|
|
848
|
+
col = _numeric(full, parse_numeric_strings(sample, pattern), nb, k, nn, policy)
|
|
849
|
+
note = (f"numeric strings parsed as numbers (rule {pattern!r}: whitespace stripped, "
|
|
850
|
+
f"NA tokens {sorted(NUMERIC_NA_TOKENS)} are missing"
|
|
851
|
+
+ (", '%' suffix removed" if pct else "") + ")")
|
|
852
|
+
return col.model_copy(update={"pattern": pattern, "notes": [note, *col.notes]})
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
def _fixed_width_code(smp: pl.Series, hint: bool) -> bool:
|
|
856
|
+
"""All-digit strings of one width, zero-padded (some value starts with '0') or with a
|
|
857
|
+
code-like name (zip, postal, ...): nominal codes, not numbers."""
|
|
858
|
+
if smp.len() == 0 or not bool(smp.str.contains(r"^[0-9]+$").all()):
|
|
859
|
+
return False
|
|
860
|
+
lengths = smp.str.len_chars()
|
|
861
|
+
if lengths.min() != lengths.max() or int(cast(int, lengths.min())) < 2:
|
|
862
|
+
return False
|
|
863
|
+
return hint or bool(smp.str.starts_with("0").any())
|
|
864
|
+
|
|
865
|
+
|
|
866
|
+
def _code_name_hint(name: str) -> bool:
|
|
867
|
+
snake = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", name).lower()
|
|
868
|
+
tokens = [t for t in re.split(r"[^a-z0-9]+", snake) if t]
|
|
869
|
+
return any(t in CODE_NAME_TOKENS for t in tokens)
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
def _string(s: pl.Series, sample: pl.Series, base: dict[str, Any], k: int, nn: int,
|
|
873
|
+
policy: DisclosurePolicySpec) -> ColumnSchema:
|
|
874
|
+
notes: list[str] = []
|
|
875
|
+
if k == 2 and _boolean_pair(s.drop_nulls().unique().to_list()):
|
|
876
|
+
labels = _bool_labels(s.drop_nulls().unique().to_list())
|
|
877
|
+
return ColumnSchema(**base, logical_type=LogicalType.BOOLEAN, bool_labels=labels,
|
|
878
|
+
notes=["string coded boolean"])
|
|
879
|
+
|
|
880
|
+
probe = _probe_datetime(s, sample)
|
|
881
|
+
if probe is not None:
|
|
882
|
+
fmt, is_date, _, full_frac = probe
|
|
883
|
+
if full_frac >= 1.0:
|
|
884
|
+
target = pl.Date if is_date else pl.Datetime("us")
|
|
885
|
+
parsed = s.str.strip_chars().str.strptime(target, fmt, strict=False)
|
|
886
|
+
v, unit = _temporal_values(parsed)
|
|
887
|
+
lo, hi = _bounds(v, policy)
|
|
888
|
+
return ColumnSchema(**base, logical_type=LogicalType.DATETIME, min_value=lo,
|
|
889
|
+
max_value=hi, pattern=fmt, confidence=0.9,
|
|
890
|
+
**_datetime_meta(parsed.dtype, unit),
|
|
891
|
+
notes=[f"ISO {'date' if is_date else 'datetime'} strings "
|
|
892
|
+
f"parsed with format {fmt!r}; cast to a temporal dtype "
|
|
893
|
+
"before generation"])
|
|
894
|
+
notes.append(f"{full_frac:.1%} of values parse as ISO dates/datetimes ({fmt!r}); "
|
|
895
|
+
"kept as string because parsing is not unambiguous")
|
|
896
|
+
|
|
897
|
+
smp = sample.drop_nulls()
|
|
898
|
+
hint = _name_hint(str(s.name))
|
|
899
|
+
ratio = k / nn
|
|
900
|
+
lengths = smp.str.len_chars()
|
|
901
|
+
mean_len = float(cast(float, lengths.mean() or 0.0))
|
|
902
|
+
space_frac = float(cast(float, smp.str.contains(r"\s").mean() or 0.0))
|
|
903
|
+
id_threshold = IDENTIFIER_HINT_UNIQUE_RATIO if hint else IDENTIFIER_MIN_UNIQUE_RATIO
|
|
904
|
+
id_like = (nn >= IDENTIFIER_MIN_ROWS and ratio >= id_threshold
|
|
905
|
+
and space_frac < TEXT_SPACE_FRACTION)
|
|
906
|
+
|
|
907
|
+
cat_limit = max(STRING_CATEGORICAL_MIN_LEVELS, STRING_CATEGORICAL_MAX_FRACTION * nn)
|
|
908
|
+
if k <= cat_limit and not id_like:
|
|
909
|
+
conf = _margin(k, cat_limit + 0.5, max(5.0, 0.2 * cat_limit))
|
|
910
|
+
return ColumnSchema(**base, logical_type=LogicalType.CATEGORICAL, confidence=conf,
|
|
911
|
+
notes=notes)
|
|
912
|
+
|
|
913
|
+
code = _fixed_width_code(smp, _code_name_hint(str(s.name)))
|
|
914
|
+
if code and not id_like:
|
|
915
|
+
# zero-padded fixed-width codes (zip codes, ...) are nominal: model them as categories
|
|
916
|
+
# (levels below the support minimum are pooled) instead of excluding the column
|
|
917
|
+
extra = ([] if k <= CODE_CATEGORICAL_MAX_LEVELS else
|
|
918
|
+
[f"high-cardinality code ({base['n_unique']} levels): levels below the "
|
|
919
|
+
"support minimum are pooled into '__other__'"])
|
|
920
|
+
return ColumnSchema(**base, logical_type=LogicalType.CATEGORICAL, confidence=0.8,
|
|
921
|
+
notes=[*notes, "fixed-width digit codes (leading zeros kept) "
|
|
922
|
+
"modeled as categorical", *extra])
|
|
923
|
+
if not code:
|
|
924
|
+
numeric_col = _numeric_string(s, sample, base, policy)
|
|
925
|
+
if numeric_col is not None:
|
|
926
|
+
return numeric_col.model_copy(update={"notes": [*notes, *numeric_col.notes]})
|
|
927
|
+
|
|
928
|
+
pattern, share = _most_common_shape(smp)
|
|
929
|
+
if id_like:
|
|
930
|
+
conf = _margin(ratio, id_threshold, 1.0 - id_threshold) if ratio < 1.0 else 1.0
|
|
931
|
+
why = "name hint, " if hint else ""
|
|
932
|
+
return ColumnSchema(**base, logical_type=LogicalType.STRING, role=Role.IDENTIFIER,
|
|
933
|
+
pattern=pattern, confidence=conf,
|
|
934
|
+
notes=[*notes, f"identifier ({why}unique ratio {ratio:.3f})"])
|
|
935
|
+
|
|
936
|
+
if mean_len > TEXT_MEAN_LENGTH or space_frac >= TEXT_SPACE_FRACTION:
|
|
937
|
+
conf = max(_margin(mean_len, TEXT_MEAN_LENGTH, 15), _margin(space_frac,
|
|
938
|
+
TEXT_SPACE_FRACTION, 0.3))
|
|
939
|
+
return ColumnSchema(**base, logical_type=LogicalType.TEXT, role=Role.EXCLUDED,
|
|
940
|
+
confidence=conf,
|
|
941
|
+
notes=[*notes, "free text (high cardinality, long or multi-word "
|
|
942
|
+
"values); excluded from generation"])
|
|
943
|
+
|
|
944
|
+
conf = _margin(k, cat_limit, max(5.0, 0.2 * cat_limit))
|
|
945
|
+
return ColumnSchema(**base, logical_type=LogicalType.STRING, role=Role.EXCLUDED,
|
|
946
|
+
pattern=pattern, confidence=conf,
|
|
947
|
+
notes=[*notes, _STRUCTURED_NOTE,
|
|
948
|
+
f"most common shape covers {share:.0%} of sampled values"])
|
|
949
|
+
|
|
950
|
+
|
|
951
|
+
# ---------------------------------------------------------------------------------------------
|
|
952
|
+
# Overrides
|
|
953
|
+
# ---------------------------------------------------------------------------------------------
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _check_overrides(overrides: dict[str, dict] | None, columns: list[str]) -> dict[str, dict]:
|
|
957
|
+
if overrides is None:
|
|
958
|
+
return {}
|
|
959
|
+
if not isinstance(overrides, dict):
|
|
960
|
+
raise ProfilingError("overrides must be a dict of column name -> dict of fields")
|
|
961
|
+
allowed = set(ColumnSchema.model_fields) - _OVERRIDE_FORBIDDEN
|
|
962
|
+
known = set(columns)
|
|
963
|
+
for name, spec in overrides.items():
|
|
964
|
+
if name not in known:
|
|
965
|
+
raise ProfilingError(f"override for unknown column {name!r}; "
|
|
966
|
+
f"columns are {columns}")
|
|
967
|
+
if not isinstance(spec, dict):
|
|
968
|
+
raise ProfilingError(f"override for {name!r} must be a dict, got "
|
|
969
|
+
f"{type(spec).__name__}")
|
|
970
|
+
bad = sorted(set(spec) - allowed)
|
|
971
|
+
if bad:
|
|
972
|
+
raise ProfilingError(f"override for {name!r} has unknown or forbidden fields {bad}; "
|
|
973
|
+
f"allowed: {sorted(allowed)}")
|
|
974
|
+
return overrides
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
def _apply_override(col: ColumnSchema, spec: dict, s: pl.Series,
|
|
978
|
+
policy: DisclosurePolicySpec, sample: pl.Series | None = None
|
|
979
|
+
) -> ColumnSchema:
|
|
980
|
+
data = col.model_dump()
|
|
981
|
+
data.update(spec)
|
|
982
|
+
data["overridden"] = True
|
|
983
|
+
try:
|
|
984
|
+
new = ColumnSchema.model_validate(data)
|
|
985
|
+
except ValidationError as exc:
|
|
986
|
+
raise ProfilingError(f"invalid override for column {col.name!r}: {exc}") from None
|
|
987
|
+
|
|
988
|
+
# Keep derived facts consistent when the logical type changes (explicit values win).
|
|
989
|
+
updates: dict[str, Any] = {}
|
|
990
|
+
lt = new.logical_type
|
|
991
|
+
if "logical_type" in spec and lt != col.logical_type:
|
|
992
|
+
if ("role" not in spec and new.role in (Role.IDENTIFIER, Role.EXCLUDED)
|
|
993
|
+
and lt not in (LogicalType.TEXT, LogicalType.STRING)):
|
|
994
|
+
updates["role"] = Role.FEATURE
|
|
995
|
+
numeric_src = s.dtype.is_numeric() or s.dtype == pl.Boolean
|
|
996
|
+
if lt in (LogicalType.CONTINUOUS, LogicalType.DISCRETE) and numeric_src:
|
|
997
|
+
v = _numeric_values(s.fill_nan(None) if s.dtype.is_float() else s)
|
|
998
|
+
if "min_value" not in spec and "max_value" not in spec:
|
|
999
|
+
updates["min_value"], updates["max_value"] = _bounds(v, policy)
|
|
1000
|
+
if lt == LogicalType.DISCRETE and "integer_valued" not in spec:
|
|
1001
|
+
updates["integer_valued"] = True
|
|
1002
|
+
if "decimals" not in spec and new.decimals is None:
|
|
1003
|
+
updates["decimals"] = 0 if lt == LogicalType.DISCRETE else _detect_decimals(v)
|
|
1004
|
+
if col.logical_type == LogicalType.DATETIME and "pattern" not in spec:
|
|
1005
|
+
updates["pattern"] = None # the strptime format no longer applies
|
|
1006
|
+
if updates:
|
|
1007
|
+
new = new.model_copy(update=updates)
|
|
1008
|
+
if new.role == Role.REFERENCE:
|
|
1009
|
+
return _override_reference(col, new, spec, s)
|
|
1010
|
+
return _override_pseudonym(col, new, spec, s, policy, s if sample is None else sample)
|
|
1011
|
+
|
|
1012
|
+
|
|
1013
|
+
def _override_reference(col: ColumnSchema, new: ColumnSchema, spec: dict,
|
|
1014
|
+
s: pl.Series) -> ColumnSchema:
|
|
1015
|
+
"""``role: "reference"`` opts a text or whole-number column in (ADR-0013)."""
|
|
1016
|
+
if "logical_type" in spec and new.logical_type != LogicalType.DISCRETE:
|
|
1017
|
+
raise ProfilingError(
|
|
1018
|
+
f"invalid override for column {col.name!r}: the role 'reference' is modeled by "
|
|
1019
|
+
f"group sizes; it cannot have logical_type '{new.logical_type.value}'")
|
|
1020
|
+
nn = (s.fill_nan(None) if s.dtype.is_float() else s).drop_nulls()
|
|
1021
|
+
integral = bool((nn == nn.round(0)).all()) if s.dtype.is_float() and nn.len() else True
|
|
1022
|
+
if not supports_reference(s.dtype, integral):
|
|
1023
|
+
raise ProfilingError(
|
|
1024
|
+
f"invalid override for column {col.name!r}: a {s.dtype} column cannot have the "
|
|
1025
|
+
f"role 'reference'; it needs text or integer keys")
|
|
1026
|
+
if col.role == Role.REFERENCE:
|
|
1027
|
+
return new
|
|
1028
|
+
out = _as_reference(new, s, "role 'reference' set by override")
|
|
1029
|
+
return out.model_copy(update={"overridden": True})
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def _override_pseudonym(col: ColumnSchema, new: ColumnSchema, spec: dict, s: pl.Series,
|
|
1033
|
+
policy: DisclosurePolicySpec, sample: pl.Series) -> ColumnSchema:
|
|
1034
|
+
"""Keep the ``pseudonym`` role consistent under an override (ADR-0010).
|
|
1035
|
+
|
|
1036
|
+
* ``role: "pseudonym"`` opts a text or integer-coded column in; the column becomes a
|
|
1037
|
+
categorical.
|
|
1038
|
+
* Any other explicit role opts a detected column out.
|
|
1039
|
+
* Without an explicit role, a detected column stays protected when the override makes or
|
|
1040
|
+
keeps it categorical; a ``logical_type`` override to anything else is taken as a
|
|
1041
|
+
statement about the column and drops the default.
|
|
1042
|
+
"""
|
|
1043
|
+
def noted(c: ColumnSchema, note: str, **update: Any) -> ColumnSchema:
|
|
1044
|
+
return c.model_copy(update={**update, "notes": [*c.notes, note]})
|
|
1045
|
+
|
|
1046
|
+
explicit_role = "role" in spec
|
|
1047
|
+
explicit_type = "logical_type" in spec
|
|
1048
|
+
lt = new.logical_type
|
|
1049
|
+
was = col.role == Role.PSEUDONYM
|
|
1050
|
+
if explicit_role and new.role != Role.PSEUDONYM:
|
|
1051
|
+
if was and new.role == Role.FEATURE:
|
|
1052
|
+
return noted(new, "real values kept: role 'feature' set by override")
|
|
1053
|
+
return new
|
|
1054
|
+
if not explicit_role and was and explicit_type and lt != LogicalType.CATEGORICAL:
|
|
1055
|
+
role = (Role.EXCLUDED if lt in (LogicalType.TEXT, LogicalType.STRING)
|
|
1056
|
+
else Role.FEATURE)
|
|
1057
|
+
return noted(new, f"personal-data default dropped: logical_type '{lt.value}' set by "
|
|
1058
|
+
f"override", role=role)
|
|
1059
|
+
text = s.cast(pl.String) if s.dtype == pl.Categorical or isinstance(s.dtype, pl.Enum) else s
|
|
1060
|
+
reason = "role 'pseudonym' set by override"
|
|
1061
|
+
if (not explicit_role and not was and explicit_type and lt == LogicalType.CATEGORICAL
|
|
1062
|
+
and col.role == Role.EXCLUDED and new.role == Role.FEATURE
|
|
1063
|
+
and not (policy.sensitive or policy.profile == "research")):
|
|
1064
|
+
# a detected column that was excluded for want of repeats, now made categorical
|
|
1065
|
+
k = int(text.drop_nulls().n_unique())
|
|
1066
|
+
probe = col.model_copy(update={"role": Role.FEATURE})
|
|
1067
|
+
if _personal_hint(probe, text, sample.cast(text.dtype, strict=False), k) is not None:
|
|
1068
|
+
new = new.model_copy(update={"role": Role.PSEUDONYM})
|
|
1069
|
+
reason = ("looks like personal data: role 'pseudonym' applies with the categorical "
|
|
1070
|
+
f"override ({_OPT_OUT})")
|
|
1071
|
+
if new.role != Role.PSEUDONYM:
|
|
1072
|
+
return new
|
|
1073
|
+
if explicit_type and lt != LogicalType.CATEGORICAL:
|
|
1074
|
+
raise ProfilingError(f"invalid override for column {col.name!r}: the role 'pseudonym' "
|
|
1075
|
+
f"is a categorical; it cannot have logical_type '{lt.value}'")
|
|
1076
|
+
nn = (s.fill_nan(None) if s.dtype.is_float() else s).drop_nulls()
|
|
1077
|
+
integral = bool((nn == nn.round(0)).all()) if s.dtype.is_float() and nn.len() else True
|
|
1078
|
+
if not supports_pseudonym(s.dtype, integral):
|
|
1079
|
+
raise ProfilingError(
|
|
1080
|
+
f"invalid override for column {col.name!r}: a {s.dtype} column cannot have the "
|
|
1081
|
+
f"role 'pseudonym'; it needs text or integer codes (cast the column to strings "
|
|
1082
|
+
f"to pseudonymise it anyway)")
|
|
1083
|
+
if was and new.logical_type == LogicalType.CATEGORICAL and not explicit_role:
|
|
1084
|
+
return new
|
|
1085
|
+
if was and explicit_role:
|
|
1086
|
+
return new
|
|
1087
|
+
return _as_pseudonym(new, text, reason)
|