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.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,1143 @@
1
+ """Entity groups (ADR-0013): the attributes of a repeated entity are read from its key.
2
+
3
+ A table that repeats an entity on many rows (the lending bank on every loan, the contractor on
4
+ every permit, the hospital on every stay) carries, next to the column that names the entity,
5
+ columns that describe it: its city, its registration number, its phone. Each value of the *key*
6
+ has one value of each *attribute*. Modeled as separate categoricals these columns are tied by
7
+ pairwise conditional tables and rare-level pooling at best, and a synthetic row then names one
8
+ bank with the city of a second and the registration number of a third.
9
+
10
+ :func:`plan_entities` finds such groups (or takes the ones the user declared) and the profiler
11
+ records them in ``manifest.model.entities``. A group is **a step after decoding**
12
+ (:class:`EntityEncoder`), on the generated values; marginals, encodings and the joint model
13
+ are fitted and sampled exactly as without it:
14
+
15
+ * the **key** is what it was: a categorical in the joint model, with its frequencies, its
16
+ pooled rare levels and its dependence on the other columns;
17
+ * an **attribute** of a generated row is replaced by the entry of the group's table,
18
+ ``attribute = table[key]``, so every row of an entity carries that entity's values;
19
+ * a row whose key has **no entry** (a pooled rare key, an empty key, a key whose rows
20
+ disagree) keeps the attribute the model generated for it, as before, as long as that
21
+ value is one the source rows without an entry hold: a pooled entity has the attributes of
22
+ the pooled rows, drawn by the joint model with the other columns. A value that only
23
+ entities with an entry have (the name of a large bank next to a pooled bank's key) is
24
+ replaced by a draw from the attribute's distribution among the rows without an entry
25
+ (its *rest*), which is mostly the pooled level ``__other__``;
26
+ * a group may have one **anchor**: the attribute with the most values among those with at
27
+ most :data:`ANCHOR_MAX_LEVELS`. A column of that few levels is what the encoder's
28
+ conditional tables model best, and other columns depend on it directly (the borrower's
29
+ state on the bank's state), so the anchor is *not* overwritten. Instead the key follows
30
+ it: a row whose key belongs to another anchor value gets a key drawn among the entities of
31
+ its own (:meth:`EntityTable.reconcile`), by their frequencies. The other attributes are
32
+ then read from that key. Rows on a pooled key stay there, so the pooled share is the
33
+ model's. Where the anchor says nothing it is filled in like an attribute: an empty anchor
34
+ beside a key that has one takes the key's, and a row without a key has the anchor that
35
+ rows without a key have (usually none).
36
+
37
+ Acceptance (detected groups)
38
+ ----------------------------
39
+ ``key -> attribute`` is accepted when all of the following hold, on the rows that have a key.
40
+ The first two are the rule every relationship is held to (:mod:`ectype.profiling.tolerance`,
41
+ ADR-0015), with this module's meaning of "isolated":
42
+
43
+ * **It holds.** At most :data:`MAX_EXCEPTIONS` of the rows hold another value than most rows
44
+ of their key do (``floor(0.005 n)``): a handful of stray rows is dirt wherever it falls.
45
+ * **Or it holds for nearly every entity.** A real directory is dirtier than that, and not at
46
+ random: a company has a second phone line, two firms share a name. Up to
47
+ :data:`MAX_DIRTY` of the rows may disagree when the disagreement is isolated, which for an
48
+ entity means confined to a few keys: at least :data:`MIN_CONSISTENT_KEYS` of the kept key
49
+ values must be consistent on their own (at most one row of the key, or
50
+ :data:`MAX_EXCEPTIONS` of its rows, hold another value). A relationship that is only
51
+ statistical (a ZIP code and its county, an office and the state of its clients) leaks a
52
+ little in most keys and fails this; an entity table with a few ambiguous entries passes.
53
+ * **It says something.** If the attribute were unrelated to the key (its values shuffled over
54
+ the rows), at least :data:`MIN_EVIDENCE_ROWS` rows would break the function, and the source
55
+ breaks it in at most :data:`MAX_EVIDENCE_RATIO` of that number. A nearly constant column is
56
+ a function of anything; it is not an attribute.
57
+ * **There is an entity table to speak of.** At least :data:`MIN_KEYS` key values are kept
58
+ (seen on ``min_category_support`` rows or more), and they hold at least
59
+ :data:`MIN_COVERAGE` of the rows with a key. Fewer levels are within reach of the
60
+ conditional tables of the encoder; a table that serves a minority of the rows is not worth
61
+ a second mechanism.
62
+ * **Key and attribute are filled together.** The kept key values must also hold at least
63
+ :data:`MIN_COVERAGE` of the rows on which the key *or the attribute* is filled. A column
64
+ that is empty on most rows where the attribute has a value cannot own it, however exactly
65
+ it determines it on the few rows where both are present (an applicant who is sometimes the
66
+ contractor does not determine the contractor).
67
+
68
+ Keys are categorical columns; attributes are categorical, boolean or whole-number columns
69
+ (a registration number or a ZIP stored as an integer is a label here, not a quantity).
70
+
71
+ Planning
72
+ --------
73
+ Every attribute gets **one** key: of the keys that determine it, the one whose table gets
74
+ the most rows right (rows on a kept key value that hold the value most rows of that key hold;
75
+ then the key with the fewest distinct values, then the first in the table). Edges are settled
76
+ in that order and an edge that would close a cycle is dropped.
77
+
78
+ Of two columns that determine each other (a name and a registration number, a company and
79
+ its phone) one direction is dropped first: the key is the column that is the better key of
80
+ the *other* columns both determine (the sum of the rows its tables get right). Two banks
81
+ under one name have two streets, cities and numbers, so the street is the key and the name
82
+ its attribute; a company with a second phone line has one address, so the company is the key
83
+ and the second line is dirt. Without other columns to judge by, the key is the direction that
84
+ gets more rows right (the column with fewer empty cells), then the column with fewer
85
+ distinct values, then the first in the table. A key may itself be an attribute of another key: ``zip -> city -> state`` is
86
+ a chain of two groups, and a row whose ZIP is too rare to keep still gets the state of its
87
+ city. The anchor of a group is taken from everything its key determines, directly or through
88
+ such a chain, and only a key that is not itself looked up has one.
89
+
90
+ Disclosure
91
+ ----------
92
+ A table entry ``(key, value)`` is stored only when at least ``min_category_support`` rows hold
93
+ exactly that pair, and the entries of one key are stored only as far as that many rows hold
94
+ all of them together: every stored tuple is backed by that many rows, the rule for a category
95
+ label. Keys below the support minimum have no entry (the key itself is pooled into
96
+ ``__other__`` by its marginal, as before). Detection runs after pseudonymisation (ADR-0010),
97
+ so for a ``pseudonym`` key or attribute the table holds stand-in tokens: one entity has one
98
+ name token, one phone token and one address token on every row, and no source label is
99
+ stored. The rest of an attribute is the share of each of its levels among the rows without an
100
+ entry: a level is listed when at least ``min_category_support`` of those rows hold it (rarer
101
+ ones are left out), and the shares are coarsened. An anchor stores its value per key, like
102
+ an attribute, and nothing else.
103
+
104
+ Exceptions are not reproduced: a generated row whose key has an entry carries that entry.
105
+ """
106
+
107
+ from __future__ import annotations
108
+
109
+ from collections.abc import Mapping, Sequence
110
+ from dataclasses import dataclass, field
111
+ from typing import Any
112
+
113
+ import numpy as np
114
+ import polars as pl
115
+
116
+ from ectype.errors import FingerprintError, ProfilingError
117
+ from ectype.fingerprint.core import ArrayStore
118
+ from ectype.fingerprint.disclosure import OTHER, coarsen, resolve_policy
119
+ from ectype.fingerprint.schema import (
120
+ ColumnSchema,
121
+ DisclosurePolicySpec,
122
+ EntityAnchor,
123
+ EntityAttribute,
124
+ EntitySpec,
125
+ )
126
+ from ectype.io.values import category_labels
127
+ from ectype.profiling import tolerance
128
+ from ectype.rng import stream
129
+ from ectype.types import LogicalType, Role
130
+
131
+ __all__ = [
132
+ "ANCHOR_MAX_LEVELS",
133
+ "MAX_DIRTY",
134
+ "MAX_EVIDENCE_RATIO",
135
+ "MAX_EXCEPTIONS",
136
+ "METHODS",
137
+ "MIN_CONSISTENT_KEYS",
138
+ "MIN_COVERAGE",
139
+ "MIN_EVIDENCE_ROWS",
140
+ "MIN_KEYS",
141
+ "EntityEncoder",
142
+ "EntityPlan",
143
+ "EntityTable",
144
+ "array_refs",
145
+ "check_entities",
146
+ "load_tables",
147
+ "plan_entities",
148
+ ]
149
+
150
+ METHODS = ("lookup",)
151
+ #: largest share of the rows with a key that may disagree with their key's value, wherever
152
+ #: the disagreeing rows are (the shared rule of ``profiling.tolerance``)
153
+ MAX_EXCEPTIONS = tolerance.STRAY
154
+ #: ... and the largest share when they are isolated, which here means confined to a few
155
+ #: keys: at least ``MIN_CONSISTENT_KEYS`` of the kept key values are consistent on their own
156
+ #: (at most one row, or ``MAX_EXCEPTIONS`` of the key's rows, hold another value)
157
+ MAX_DIRTY = tolerance.DIRTY
158
+ MIN_CONSISTENT_KEYS = tolerance.CONSISTENT_KEYS
159
+ #: fewest kept key values (seen on ``min_category_support`` rows or more) of a detected group
160
+ MIN_KEYS = 30
161
+ #: ... and the smallest share of the rows with a key that those values must hold; for an
162
+ #: edge, also of the rows on which the key or the attribute is filled
163
+ MIN_COVERAGE = 0.5
164
+ #: rows that would break the function if the attribute were unrelated to the key: at least ...
165
+ MIN_EVIDENCE_ROWS = 100
166
+ #: ... and the source may break it in at most this share of them
167
+ MAX_EVIDENCE_RATIO = 0.1
168
+ #: most distinct values of an attribute that can be the anchor of its group
169
+ ANCHOR_MAX_LEVELS = 64
170
+ #: most (key, attribute) pairs examined
171
+ _MAX_PAIRS = 4000
172
+ #: pairs are screened on a sample of this many rows first ...
173
+ _SCREEN_ROWS = 100_000
174
+ #: ... and dropped when the sample breaks the function this many times more often than allowed
175
+ _SCREEN_FACTOR = 4.0
176
+ #: a pair refused with at most this share of exceptions is reported as a near miss
177
+ _NEAR_MISS = tolerance.NEAR_MISS
178
+
179
+ _STATE_NONE, _STATE_VALUE, _STATE_NULL = 0, 1, 2
180
+ _KEY_TYPES = (LogicalType.CATEGORICAL,)
181
+ _ROLES = (Role.FEATURE, Role.PSEUDONYM)
182
+ #: stands for an empty anchor cell while rows are grouped by anchor value
183
+ _EMPTY = "\x00"
184
+
185
+
186
+ def _labels(s: pl.Series) -> pl.Series:
187
+ if s.dtype.is_float():
188
+ s = s.fill_nan(None)
189
+ return category_labels(s).cast(pl.String)
190
+
191
+
192
+ def _like(labels: pl.Series, model: pl.Series) -> pl.Series:
193
+ """Labels as values of the kind ``model`` (a decoded column) holds."""
194
+ dtype = model.dtype
195
+ if dtype == pl.String:
196
+ return labels
197
+ if dtype == pl.Boolean:
198
+ return pl.select(pl.when(labels == "True").then(True).when(labels == "False")
199
+ .then(False).otherwise(None).alias(labels.name)).to_series()
200
+ if dtype.is_numeric():
201
+ num = labels.cast(pl.Float64, strict=False)
202
+ return (num.round(0) if dtype.is_integer() else num).cast(dtype, strict=False)
203
+ return labels.cast(dtype, strict=False)
204
+
205
+
206
+ # ---------------------------------------------------------------------------------------------
207
+ # Tables
208
+ # ---------------------------------------------------------------------------------------------
209
+
210
+
211
+ @dataclass
212
+ class _Attribute:
213
+ column: str
214
+ values: np.ndarray # str per key ("" where there is no value)
215
+ state: np.ndarray # int8 per key: 0 no entry, 1 value, 2 empty
216
+ missing_state: int = _STATE_NONE
217
+ missing_value: str | None = None
218
+ rest_levels: np.ndarray | None = None # str: values a row without an entry may hold
219
+ rest_probs: np.ndarray | None = None # float, aligned
220
+ rest_null: float = 0.0 # ... and the share of empty cells among them
221
+
222
+
223
+ @dataclass
224
+ class _Anchor:
225
+ column: str
226
+ values: np.ndarray # as for an attribute
227
+ state: np.ndarray
228
+ missing_state: int = _STATE_NONE
229
+ missing_value: str | None = None
230
+
231
+
232
+ @dataclass
233
+ class EntityTable:
234
+ """One entity group with its table in memory (the compiled form of an ``EntitySpec``)."""
235
+
236
+ key: str
237
+ keys: np.ndarray # str, distinct
238
+ attributes: list[_Attribute]
239
+ anchor: _Anchor | None = None
240
+ source: str | None = None
241
+
242
+ def index(self, key_labels: pl.Series) -> np.ndarray:
243
+ """Row of the table for each key label (``-1``: not in the table, ``-2``: empty)."""
244
+ n = key_labels.len()
245
+ if self.keys.size == 0:
246
+ idx = np.full(n, -1, dtype=np.int64)
247
+ else:
248
+ idx = key_labels.replace_strict(
249
+ pl.Series(self.keys, dtype=pl.String),
250
+ pl.Series(np.arange(self.keys.size, dtype=np.int64)),
251
+ default=-1, return_dtype=pl.Int64).fill_null(-1).to_numpy()
252
+ return np.where(key_labels.is_null().to_numpy(), -2, idx)
253
+
254
+ def lookup(self, attr: _Attribute | _Anchor, idx: np.ndarray
255
+ ) -> tuple[np.ndarray, np.ndarray]:
256
+ """``(state, value)`` per row for the table rows ``idx`` (see :meth:`index`)."""
257
+ inside = idx >= 0
258
+ safe = np.where(inside, idx, 0)
259
+ if self.keys.size:
260
+ state = np.where(inside, attr.state[safe], _STATE_NONE).astype(np.int8)
261
+ value = np.where(inside, attr.values[safe], "")
262
+ else:
263
+ state = np.zeros(idx.size, dtype=np.int8)
264
+ value = np.full(idx.size, "", dtype=str)
265
+ empty = idx == -2
266
+ if empty.any():
267
+ state = np.where(empty, attr.missing_state, state).astype(np.int8)
268
+ value = np.where(empty, attr.missing_value or "", value)
269
+ return state, value
270
+
271
+ def disagreeing(self, df: pl.DataFrame) -> np.ndarray:
272
+ """Rows whose key (or whose lack of a key) has an entry for another anchor value than
273
+ the row holds."""
274
+ anchor = self.anchor
275
+ if anchor is None or anchor.column not in df.columns or self.key not in df.columns:
276
+ return np.zeros(df.height, dtype=bool)
277
+ state, value = self.lookup(anchor, self.index(_labels(df.get_column(self.key))))
278
+ have = _labels(df.get_column(anchor.column))
279
+ empty = have.is_null().to_numpy()
280
+ same = have.fill_null("").to_numpy().astype(str) == value
281
+ agrees = np.where(state == _STATE_VALUE, ~empty & same,
282
+ np.where(state == _STATE_NULL, empty, True))
283
+ return np.asarray(~agrees, dtype=bool)
284
+
285
+ def reconcile(self, df: pl.DataFrame, weights: Mapping[str, float],
286
+ u: np.ndarray) -> pl.DataFrame:
287
+ """Make the key agree with the anchor.
288
+
289
+ A row whose key has an entry for another anchor value than the row's gets a new key:
290
+ one of the keys of its anchor value, by their frequencies (``weights``: label ->
291
+ probability, the key's marginal). When no key has that anchor value the row goes to
292
+ the pooled ``__other__`` key, or is left alone when the key has no pooled level. ``u``
293
+ holds one uniform number per row. Rows whose key is pooled or without an entry for
294
+ the anchor are consistent with any anchor value and are never touched.
295
+
296
+ The anchor itself changes only where it says nothing about the entity: a row whose
297
+ anchor is empty while its key has a value for it (and no key has an empty anchor)
298
+ takes that value, and a row whose key is empty takes the entry of rows without a key.
299
+ """
300
+ anchor = self.anchor
301
+ off = self.disagreeing(df)
302
+ if anchor is None or not off.any():
303
+ return df
304
+ key = _labels(df.get_column(self.key))
305
+ idx = self.index(key)
306
+ state, value = self.lookup(anchor, idx)
307
+ seen = df.get_column(anchor.column)
308
+ labels = _labels(seen)
309
+ # rows the anchor is filled in on: no key, or no anchor where every key has one
310
+ fill = off & ((idx == -2) | (labels.is_null().to_numpy() & (state == _STATE_VALUE)
311
+ & ~np.any(anchor.state == _STATE_NULL)))
312
+ if fill.any():
313
+ entry = _like(pl.Series(anchor.column, value, dtype=pl.String), seen)
314
+ if entry.dtype != seen.dtype:
315
+ seen, entry = seen.cast(pl.String), entry.cast(pl.String)
316
+ df = df.with_columns(pl.select(
317
+ pl.when(pl.Series(fill & (state == _STATE_VALUE))).then(entry)
318
+ .when(pl.Series(fill)).then(None).otherwise(seen)
319
+ .alias(anchor.column)).to_series())
320
+ bad = np.flatnonzero(off & ~fill)
321
+ if bad.size == 0:
322
+ return df
323
+ have = labels.fill_null(_EMPTY).to_numpy().astype(str)
324
+ pooled = OTHER if OTHER in weights else None
325
+ w = np.asarray([float(weights.get(k, 0.0)) for k in self.keys.tolist()])
326
+ new = key.to_numpy().astype(object)
327
+ wanted = have[bad]
328
+ for a in np.unique(wanted):
329
+ rows = bad[wanted == a]
330
+ if a == _EMPTY:
331
+ cand = np.flatnonzero(anchor.state == _STATE_NULL)
332
+ else:
333
+ cand = np.flatnonzero((anchor.state == _STATE_VALUE) & (anchor.values == a))
334
+ mass = w[cand]
335
+ total = float(mass.sum())
336
+ if total <= 0.0:
337
+ if pooled is not None:
338
+ new[rows] = pooled
339
+ continue
340
+ pick = np.searchsorted(np.cumsum(mass) / total, u[rows], side="right")
341
+ new[rows] = self.keys[cand][np.minimum(pick, cand.size - 1)]
342
+ labels = pl.Series(self.key, new.tolist(), dtype=pl.String)
343
+ return df.with_columns(_like(labels, df.get_column(self.key)).alias(self.key))
344
+
345
+ def rest_columns(self) -> list[str]:
346
+ """The attributes that have a rest: one uniform number per row is needed for each."""
347
+ return [a.column for a in self.attributes if a.rest_levels is not None]
348
+
349
+ def _rest(self, attr: _Attribute, have: pl.Series, open_rows: np.ndarray,
350
+ u: np.ndarray) -> pl.Series:
351
+ """``have`` with the values of ``open_rows`` (rows without an entry) that no source
352
+ row without an entry holds replaced by draws from the attribute's rest."""
353
+ levels, probs = attr.rest_levels, attr.rest_probs
354
+ if levels is None or probs is None or not open_rows.any():
355
+ return have
356
+ labels = _labels(have)
357
+ known = labels.is_in(pl.Series(levels, dtype=pl.String).implode()).fill_null(False)
358
+ fine = known.to_numpy() | (labels.is_null().to_numpy() & (attr.rest_null > 0.0))
359
+ redo = np.flatnonzero(open_rows & ~fine)
360
+ mass = np.r_[np.asarray(probs, dtype=np.float64), attr.rest_null]
361
+ if redo.size == 0 or mass.sum() <= 0.0:
362
+ return have
363
+ pick = np.searchsorted(np.cumsum(mass) / mass.sum(), u[redo], side="right")
364
+ pick = np.minimum(pick, mass.size - 1)
365
+ new = labels.to_numpy().astype(object)
366
+ new[redo] = np.r_[np.asarray(levels).astype(object), [None]][pick]
367
+ drawn = _like(pl.Series(have.name, new.tolist(), dtype=pl.String), have)
368
+ if drawn.dtype != have.dtype:
369
+ have = have.cast(pl.String)
370
+ mask = np.zeros(have.len(), dtype=bool)
371
+ mask[redo] = True
372
+ return pl.select(pl.when(pl.Series(mask)).then(drawn).otherwise(have)
373
+ .alias(have.name)).to_series()
374
+
375
+ def apply(self, df: pl.DataFrame, uniforms: Mapping[str, np.ndarray] | None = None
376
+ ) -> pl.DataFrame:
377
+ """Replace the attributes of ``df`` by the entries of its keys. A row whose key has no
378
+ entry keeps what it holds; with ``uniforms`` (one array of uniform numbers per column
379
+ of :meth:`rest_columns`), a value such a row cannot have is drawn again from the
380
+ attribute's rest. Columns ``df`` lacks are skipped."""
381
+ if self.key not in df.columns:
382
+ return df
383
+ idx = self.index(_labels(df.get_column(self.key)))
384
+ done: list[pl.Series] = []
385
+ for attr in self.attributes:
386
+ if attr.column not in df.columns:
387
+ continue
388
+ state, value = self.lookup(attr, idx)
389
+ have = df.get_column(attr.column)
390
+ if uniforms is not None and attr.column in uniforms:
391
+ have = self._rest(attr, have, state == _STATE_NONE, uniforms[attr.column])
392
+ entry = _like(pl.Series(attr.column, value, dtype=pl.String), have)
393
+ if entry.dtype != have.dtype: # e.g. an Enum without the label
394
+ have, entry = have.cast(pl.String), entry.cast(pl.String)
395
+ done.append(pl.select(
396
+ pl.when(pl.Series(state == _STATE_VALUE)).then(entry)
397
+ .when(pl.Series(state == _STATE_NULL)).then(None)
398
+ .otherwise(have).alias(attr.column)).to_series())
399
+ return df.with_columns(done) if done else df
400
+
401
+ def to_spec(self, store: ArrayStore) -> EntitySpec:
402
+ base = f"entity.{self.key}"
403
+
404
+ def put(what: str, column: str, arr: np.ndarray, dtype: Any) -> str:
405
+ return store.put(f"{base}.{what}.{column}", np.asarray(arr, dtype=dtype))
406
+
407
+ attrs = [EntityAttribute(
408
+ column=a.column, values=put("values", a.column, a.values, str),
409
+ state=put("state", a.column, a.state, np.int8),
410
+ missing_state=int(a.missing_state), missing_value=a.missing_value,
411
+ rest_levels=None if a.rest_levels is None
412
+ else put("rest_levels", a.column, a.rest_levels, str),
413
+ rest_probs=None if a.rest_probs is None
414
+ else put("rest_probs", a.column, a.rest_probs, np.float64),
415
+ rest_null=float(a.rest_null))
416
+ for a in self.attributes]
417
+ anchor = None
418
+ if self.anchor is not None:
419
+ a = self.anchor
420
+ anchor = EntityAnchor(
421
+ column=a.column, values=put("values", a.column, a.values, str),
422
+ state=put("state", a.column, a.state, np.int8),
423
+ missing_state=int(a.missing_state), missing_value=a.missing_value)
424
+ return EntitySpec(key=self.key, attributes=attrs, anchor=anchor, source=self.source,
425
+ keys=store.put(f"{base}.keys", np.asarray(self.keys, dtype=str)))
426
+
427
+ @classmethod
428
+ def from_spec(cls, spec: EntitySpec, store: ArrayStore) -> EntityTable:
429
+ keys = np.asarray(store.get(spec.keys)).astype(str)
430
+
431
+ def table(column: str, values_ref: str, state_ref: str
432
+ ) -> tuple[np.ndarray, np.ndarray]:
433
+ values = np.asarray(store.get(values_ref)).astype(str)
434
+ state = np.asarray(store.get(state_ref)).astype(np.int8)
435
+ if values.shape != keys.shape or state.shape != keys.shape:
436
+ raise FingerprintError(f"entity group of {spec.key!r}: the table of "
437
+ f"{column!r} does not match its keys")
438
+ return values, state
439
+
440
+ attrs = []
441
+ for a in spec.attributes:
442
+ attr = _Attribute(a.column, *table(a.column, a.values, a.state),
443
+ int(a.missing_state), a.missing_value)
444
+ if a.rest_levels is not None and a.rest_probs is not None:
445
+ levels = np.asarray(store.get(a.rest_levels)).astype(str)
446
+ probs = np.asarray(store.get(a.rest_probs), dtype=np.float64)
447
+ if levels.shape != probs.shape or np.any(probs < 0) \
448
+ or not np.all(np.isfinite(probs)):
449
+ raise FingerprintError(f"entity group of {spec.key!r}: malformed rest "
450
+ f"of {a.column!r}")
451
+ attr.rest_levels, attr.rest_probs = levels, probs
452
+ attr.rest_null = float(a.rest_null)
453
+ attrs.append(attr)
454
+ anchor = None
455
+ if spec.anchor is not None:
456
+ anchor = _Anchor(spec.anchor.column,
457
+ *table(spec.anchor.column, spec.anchor.values, spec.anchor.state),
458
+ int(spec.anchor.missing_state), spec.anchor.missing_value)
459
+ return cls(spec.key, keys, attrs, anchor, spec.source)
460
+
461
+
462
+ def load_tables(specs: Sequence[EntitySpec], store: ArrayStore) -> list[EntityTable]:
463
+ return [EntityTable.from_spec(s, store) for s in specs]
464
+
465
+
466
+ def array_refs(specs: Sequence[EntitySpec]) -> list[str]:
467
+ """Every array the entity groups reference."""
468
+ refs: list[str] = []
469
+ for g in specs:
470
+ refs.append(g.keys)
471
+ for a in g.attributes:
472
+ refs += [a.values, a.state]
473
+ refs += [r for r in (a.rest_levels, a.rest_probs) if r is not None]
474
+ if g.anchor is not None:
475
+ refs += [g.anchor.values, g.anchor.state]
476
+ return refs
477
+
478
+
479
+ def check_entities(specs: Sequence[EntitySpec], schemas: Mapping[str, ColumnSchema],
480
+ generated: Sequence[str]) -> list[str]:
481
+ """Problems that make ``specs`` unusable (empty when they are fine). ``generated`` are
482
+ the columns decoding produces (modeled features and transform targets)."""
483
+ problems: list[str] = []
484
+ have = set(generated)
485
+ seen: set[str] = set()
486
+ for spec in specs:
487
+ what = f"entity group of {spec.key!r}"
488
+ if spec.method not in METHODS:
489
+ problems.append(f"{what}: unknown method {spec.method!r}")
490
+ if spec.key not in schemas:
491
+ problems.append(f"{what}: unknown key column")
492
+ elif spec.key not in have:
493
+ problems.append(f"{what}: the key is not a column decoding generates")
494
+ if not spec.attributes and spec.anchor is None:
495
+ problems.append(f"{what}: no attributes")
496
+ if spec.anchor is not None and spec.key in seen:
497
+ problems.append(f"{what}: a key that is looked up cannot follow an anchor")
498
+ for column in [a.column for a in spec.attributes] + (
499
+ [spec.anchor.column] if spec.anchor is not None else []):
500
+ if column not in schemas:
501
+ problems.append(f"{what}: unknown column {column!r}")
502
+ elif column not in have:
503
+ problems.append(f"{what}: {column!r} is not a column decoding generates")
504
+ if column == spec.key:
505
+ problems.append(f"{what}: {column!r} is its own key")
506
+ for a in spec.attributes:
507
+ if a.column in seen:
508
+ problems.append(f"{what}: attribute {a.column!r} is looked up more than once")
509
+ seen.add(a.column)
510
+ if spec.anchor is not None and spec.anchor.column in seen:
511
+ problems.append(f"{what}: the anchor {spec.anchor.column!r} is looked up from "
512
+ f"another key")
513
+ return problems
514
+
515
+
516
+ # ---------------------------------------------------------------------------------------------
517
+ # Encoder facade
518
+ # ---------------------------------------------------------------------------------------------
519
+
520
+
521
+ class EntityEncoder:
522
+ """An encoder whose decoded rows go through the entity groups.
523
+
524
+ ``base`` is the encoder beneath (a :class:`~ectype.models.encoding.MixedEncoder`, or a
525
+ :class:`~ectype.profiling.structure.StructuredEncoder` over one); ``inner`` is the
526
+ innermost ``MixedEncoder``, as for a ``StructuredEncoder``. Columns, latent columns and
527
+ ``encode`` are the base's: the groups change values, not columns.
528
+
529
+ ``decode`` runs the groups in their order on the decoded rows: the key is first made to
530
+ agree with the group's anchor (:meth:`EntityTable.reconcile`), then the attributes are
531
+ read from the key (:meth:`EntityTable.apply`). From the ``rng`` given to ``decode`` one
532
+ uniform number per row is drawn for the anchor of a group and then for each of its
533
+ attributes that has a rest, in the order of the groups and of their attributes, whether or
534
+ not a row needs it; nothing else here is random. ``complete`` only reads the attributes:
535
+ it is idempotent on rows that went through ``decode``.
536
+ """
537
+
538
+ def __init__(self, base: Any, tables: Sequence[EntityTable]) -> None:
539
+ self.base = base
540
+ self.inner = getattr(base, "inner", base)
541
+ self.tables = list(tables)
542
+ self.columns = list(base.columns)
543
+
544
+ @property
545
+ def latent_columns(self) -> list[str]:
546
+ return list(self.base.latent_columns)
547
+
548
+ @property
549
+ def conditional_parents(self) -> dict[str, str]:
550
+ return dict(self.base.conditional_parents)
551
+
552
+ @property
553
+ def missing_rates(self) -> dict[str, float]:
554
+ return dict(self.base.missing_rates)
555
+
556
+ @property
557
+ def missing_columns(self) -> list[str]:
558
+ return list(self.base.missing_columns)
559
+
560
+ def encode(self, df: pl.DataFrame, rng: np.random.Generator) -> np.ndarray:
561
+ return np.asarray(self.base.encode(df, rng))
562
+
563
+ def weights(self, key: str) -> dict[str, float]:
564
+ """Label -> probability of a key column, from its marginal."""
565
+ marginal = self.inner.marginals.get(key)
566
+ labels = getattr(marginal, "labels", None)
567
+ probs = getattr(marginal, "probs", None)
568
+ if labels is None or probs is None:
569
+ return {}
570
+ return {str(lab): float(p) for lab, p in zip(np.asarray(labels).tolist(),
571
+ np.asarray(probs).tolist())}
572
+
573
+ def apply(self, df: pl.DataFrame, rng: np.random.Generator | None = None, *,
574
+ reconcile: bool = True) -> pl.DataFrame:
575
+ if reconcile and rng is None:
576
+ rng = stream(0, "entity")
577
+ for t in self.tables:
578
+ if t.key not in df.columns:
579
+ continue
580
+ uniforms = None
581
+ if reconcile and rng is not None:
582
+ if t.anchor is not None:
583
+ df = t.reconcile(df, self.weights(t.key), rng.random(df.height))
584
+ uniforms = {c: rng.random(df.height) for c in t.rest_columns()}
585
+ df = t.apply(df, uniforms)
586
+ return df
587
+
588
+ def complete(self, df: pl.DataFrame) -> pl.DataFrame:
589
+ out = self.base.complete(df) if hasattr(self.base, "complete") else df
590
+ return self.apply(out, reconcile=False)
591
+
592
+ def decode(self, z: np.ndarray, rng: np.random.Generator | None = None) -> pl.DataFrame:
593
+ return self.apply(self.base.decode(z, rng), rng)
594
+
595
+
596
+ # ---------------------------------------------------------------------------------------------
597
+ # Detection
598
+ # ---------------------------------------------------------------------------------------------
599
+
600
+
601
+ @dataclass
602
+ class _Coded:
603
+ col: ColumnSchema
604
+ labels: list[str] # distinct values, sorted
605
+ codes: np.ndarray # int32 per row, -1 for an empty cell
606
+ order: int # position in the table
607
+
608
+ @property
609
+ def n_values(self) -> int:
610
+ return len(self.labels)
611
+
612
+
613
+ def _code(df: pl.DataFrame, col: ColumnSchema, order: int) -> _Coded:
614
+ lab = _labels(df.get_column(col.name))
615
+ uniq = lab.drop_nulls().unique().sort()
616
+ if uniq.len() == 0:
617
+ return _Coded(col, [], np.full(lab.len(), -1, dtype=np.int32), order)
618
+ codes = np.asarray(uniq.search_sorted(lab.fill_null(uniq[0])).to_numpy(), dtype=np.int32)
619
+ codes = np.where(lab.is_null().to_numpy(), np.int32(-1), codes)
620
+ return _Coded(col, [str(x) for x in uniq.to_list()], codes, order)
621
+
622
+
623
+ def _modal(key: np.ndarray, val: np.ndarray, n_keys: int, n_vals: int
624
+ ) -> tuple[np.ndarray, np.ndarray]:
625
+ """For key ``0..n_keys-1``: the value code most of its rows hold (``val`` in
626
+ ``0..n_vals-1``; ties go to the smallest code) and how many rows hold it. ``key`` and
627
+ ``val`` list the rows that have a key."""
628
+ best = np.full(n_keys, -1, dtype=np.int64)
629
+ count = np.zeros(n_keys, dtype=np.int64)
630
+ if key.size == 0:
631
+ return best, count
632
+ pair, cnt = np.unique(key.astype(np.int64) * np.int64(n_vals) + val,
633
+ return_counts=True)
634
+ k, v = pair // n_vals, pair % n_vals
635
+ order = np.lexsort((v, -cnt, k))
636
+ first = np.r_[True, k[order][1:] != k[order][:-1]]
637
+ top = order[first]
638
+ best[k[top]] = v[top]
639
+ count[k[top]] = cnt[top]
640
+ return best, count
641
+
642
+
643
+ def _exceptions(key: np.ndarray, val: np.ndarray, n_keys: int, n_vals: int) -> int:
644
+ return int(key.size - _modal(key, val, n_keys, n_vals)[1].sum())
645
+
646
+
647
+ @dataclass
648
+ class _Edge:
649
+ key: str
650
+ attribute: str
651
+ rows: int # rows with a key
652
+ exceptions: int
653
+ shuffled: int # exceptions with the attribute shuffled over those rows
654
+ kept_keys: int
655
+ coverage: int # rows whose key value is kept
656
+ declared: bool = False
657
+ served: int = 0 # rows on a kept key that hold the value its table would give
658
+ consistent: float = 1.0 # share of the kept keys that are consistent on their own
659
+ #: how the exceptions were judged (``profiling.tolerance``); None for a declared edge
660
+ verdict: tolerance.Verdict | None = None
661
+
662
+ def record(self, policy: DisclosurePolicySpec) -> dict[str, Any]:
663
+ rate = self.exceptions / max(self.rows, 1)
664
+ return {"attribute": self.attribute,
665
+ "exception_rate": coarsen(rate, policy) if self.exceptions else 0.0,
666
+ **({"tolerance": self.verdict.tier} if self.verdict is not None else {}),
667
+ "consistent_keys": coarsen(self.consistent, policy),
668
+ "shuffled_exception_rate": coarsen(self.shuffled / max(self.rows, 1), policy),
669
+ "declared": self.declared}
670
+
671
+
672
+ @dataclass
673
+ class EntityPlan:
674
+ """What :func:`plan_entities` decided: the groups with their tables, in the order they
675
+ run, a note for every column that takes part and a JSON-safe record."""
676
+
677
+ tables: list[EntityTable] = field(default_factory=list)
678
+ diagnostics: dict[str, Any] = field(default_factory=dict)
679
+ notes: dict[str, str] = field(default_factory=dict)
680
+
681
+ def __bool__(self) -> bool:
682
+ return bool(self.tables)
683
+
684
+ @property
685
+ def attributes(self) -> list[str]:
686
+ """The columns that are looked up (anchors are not)."""
687
+ return [a.column for t in self.tables for a in t.attributes]
688
+
689
+ @property
690
+ def anchors(self) -> dict[str, str]:
691
+ """Key -> anchor column of the groups that have one."""
692
+ return {t.key: t.anchor.column for t in self.tables if t.anchor is not None}
693
+
694
+ def view(self, base: Any) -> Any:
695
+ """``base`` (an encoder) with the groups applied to what it decodes; ``base`` itself
696
+ without groups."""
697
+ return EntityEncoder(base, self.tables) if self.tables else base
698
+
699
+ def specs(self, store: ArrayStore) -> list[EntitySpec]:
700
+ return [t.to_spec(store) for t in self.tables]
701
+
702
+ def annotate(self, columns: Sequence[ColumnSchema]) -> list[ColumnSchema]:
703
+ return [c.model_copy(update={"notes": [*c.notes, self.notes[c.name]]})
704
+ if c.name in self.notes else c for c in columns]
705
+
706
+
707
+ class _Detector:
708
+ def __init__(self, df: pl.DataFrame, columns: Sequence[ColumnSchema],
709
+ policy: DisclosurePolicySpec, exclude: set[str], seed: int) -> None:
710
+ self.df = df
711
+ self.n = df.height
712
+ self.policy = policy
713
+ self.seed = seed
714
+ self.support = max(int(policy.min_category_support), 1)
715
+ self.order = {c.name: i for i, c in enumerate(columns)}
716
+ self.schemas = {c.name: c for c in columns if c.name in df.columns}
717
+ self.excluded = set(exclude)
718
+ self.usable = {c.name: c for c in self.schemas.values()
719
+ if c.role in _ROLES and c.name not in exclude
720
+ and not c.name.startswith("__")}
721
+ self._coded: dict[str, _Coded] = {}
722
+ self._counts: dict[str, np.ndarray] = {}
723
+ #: (key, attribute) -> exception rate of a pair that was refused narrowly
724
+ self.near: dict[tuple[str, str], float] = {}
725
+ if self.n > _SCREEN_ROWS:
726
+ self.sample: np.ndarray | None = np.linspace(
727
+ 0, self.n - 1, _SCREEN_ROWS).round().astype(np.int64)
728
+ else:
729
+ self.sample = None
730
+
731
+ # -- columns ------------------------------------------------------------------------------
732
+ def coded(self, name: str) -> _Coded:
733
+ if name not in self._coded:
734
+ self._coded[name] = _code(self.df, self.schemas[name], self.order[name])
735
+ return self._coded[name]
736
+
737
+ def counts(self, name: str) -> np.ndarray:
738
+ """Rows per value of a column."""
739
+ if name not in self._counts:
740
+ c = self.coded(name)
741
+ self._counts[name] = np.bincount(c.codes[c.codes >= 0], minlength=c.n_values)
742
+ return self._counts[name]
743
+
744
+ def _unusable(self, name: str) -> str:
745
+ if name in self.excluded:
746
+ return ("it takes part in another structure (a sum, a transform or ordering, a "
747
+ "calendar, a computed or derived column, or a reference key)")
748
+ return "not a modeled column"
749
+
750
+ def can_be_key(self, name: str) -> str | None:
751
+ col = self.usable.get(name)
752
+ if col is None:
753
+ return self._unusable(name)
754
+ if col.logical_type not in _KEY_TYPES:
755
+ return f"a key must be a categorical column (it is {col.logical_type.value})"
756
+ return None
757
+
758
+ def can_be_attribute(self, name: str) -> str | None:
759
+ col = self.usable.get(name)
760
+ if col is None:
761
+ return self._unusable(name)
762
+ lt = col.logical_type
763
+ if lt in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
764
+ return None
765
+ if (lt == LogicalType.DISCRETE and col.integer_valued
766
+ and col.physical_dtype.startswith(("Int", "UInt", "Float"))):
767
+ return None
768
+ return f"an attribute must be a categorical, boolean or whole-number column (it is " \
769
+ f"{lt.value})"
770
+
771
+ def kept(self, name: str) -> tuple[int, int, int]:
772
+ """Kept values of a column (seen on the support minimum or more), the rows they
773
+ hold, and the rows that have a value."""
774
+ cnt = self.counts(name)
775
+ keep = cnt >= self.support
776
+ return int(keep.sum()), int(cnt[keep].sum()), int(cnt.sum())
777
+
778
+ def is_table(self, name: str) -> str | None:
779
+ """Why the values of ``name`` make no entity table worth having (None: they do)."""
780
+ kept_keys, coverage, rows = self.kept(name)
781
+ if kept_keys < MIN_KEYS:
782
+ return f"fewer than {MIN_KEYS} key values are seen on {self.support} rows or more"
783
+ if coverage < MIN_COVERAGE * rows:
784
+ return (f"the key values seen on {self.support} rows or more hold less than "
785
+ f"{MIN_COVERAGE:.0%} of the rows")
786
+ return None
787
+
788
+ # -- one pair -----------------------------------------------------------------------------
789
+ def edge(self, key: str, attribute: str, *, declared: bool = False) -> _Edge | str:
790
+ """The edge ``key -> attribute`` when it is accepted, else the reason it is not."""
791
+ k, a = self.coded(key), self.coded(attribute)
792
+ has = k.codes >= 0
793
+ kept_keys, coverage, rows = self.kept(key)
794
+ if declared:
795
+ if rows == 0:
796
+ return "the key column is empty"
797
+ else:
798
+ why = self.is_table(key)
799
+ if why is not None:
800
+ return why
801
+ if a.n_values < 2:
802
+ return "the attribute takes a single value"
803
+ filled = int((has | (a.codes >= 0)).sum())
804
+ if coverage < MIN_COVERAGE * filled:
805
+ return (f"the key values seen on {self.support} rows or more hold less than "
806
+ f"{MIN_COVERAGE:.0%} of the rows on which the key or the attribute is "
807
+ f"filled")
808
+ n_vals = a.n_values + 1
809
+ if not declared and self.sample is not None:
810
+ ks, vs = k.codes[self.sample], a.codes[self.sample] + 1
811
+ sub = ks >= 0
812
+ exc = _exceptions(ks[sub], vs[sub], k.n_values, n_vals)
813
+ if exc > _SCREEN_FACTOR * MAX_DIRTY * max(int(sub.sum()), 1) + 5:
814
+ return "screened out on a sample"
815
+ kk, vv = k.codes[has], a.codes[has] + 1
816
+ _, held = _modal(kk, vv, k.n_values, n_vals)
817
+ per_key = self.counts(key)
818
+ keep = per_key >= self.support
819
+ exc = int(rows - held.sum())
820
+ # rows the table would get right: on a kept key whose usual value has the support
821
+ served = int(held[keep & (held >= self.support)].sum())
822
+ stray = np.maximum(1, np.floor(MAX_EXCEPTIONS * per_key[keep]))
823
+ consistent = float(np.mean((per_key[keep] - held[keep]) <= stray)) if keep.any() else 1.0
824
+ if declared:
825
+ return _Edge(key, attribute, rows, exc, 0, kept_keys, coverage, True, served,
826
+ consistent)
827
+ # the shared rule: stray rows anywhere, or isolated ones, which for an entity means
828
+ # confined to a few keys
829
+ verdict = tolerance.judge(exc, rows, lambda: tolerance.Isolation(
830
+ consistent >= MIN_CONSISTENT_KEYS,
831
+ f"they are not confined to a few keys: {consistent:.0%} of the kept keys are "
832
+ f"consistent (fewer than {MIN_CONSISTENT_KEYS:.0%})",
833
+ {"consistent_keys": float(coarsen(consistent, self.policy))}))
834
+ if not verdict.holds:
835
+ if verdict.near_miss:
836
+ self.near[key, attribute] = exc / max(rows, 1)
837
+ return verdict.reason("hold another value than most rows of their key")
838
+ rng = stream(self.seed, "entity", "shuffle", key, attribute)
839
+ shuffled = _exceptions(kk, rng.permutation(vv), k.n_values, n_vals)
840
+ if shuffled < MIN_EVIDENCE_ROWS or exc > MAX_EVIDENCE_RATIO * shuffled:
841
+ return (f"the attribute is nearly constant: unrelated to the key it would break "
842
+ f"the function in {shuffled} rows only")
843
+ return _Edge(key, attribute, rows, exc, shuffled, kept_keys, coverage, False, served,
844
+ consistent, verdict)
845
+
846
+ # -- tables -------------------------------------------------------------------------------
847
+ def rest(self, attr: _Attribute, a: _Coded, open_rows: np.ndarray) -> None:
848
+ """Give ``attr`` its rest: the share of each level of the column among the rows the
849
+ table does not serve. Levels are the column's own (a value seen on fewer rows than the
850
+ support minimum is the pooled ``__other__``, as in its marginal); a level held by
851
+ fewer than that many unserved rows is left out. Only for columns modeled as
852
+ categories: a number has no pooled level to fall back on."""
853
+ if a.col.logical_type not in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
854
+ return
855
+ n_open = int(open_rows.sum())
856
+ if n_open < self.support:
857
+ return
858
+ codes = a.codes[open_rows]
859
+ n_null = int((codes < 0).sum())
860
+ cnt = np.bincount(codes[codes >= 0], minlength=a.n_values)
861
+ pooled = self.counts(a.col.name) < self.support
862
+ if a.col.logical_type == LogicalType.BOOLEAN:
863
+ pooled = np.zeros(a.n_values, dtype=bool) # a flag's levels are never pooled
864
+ levels = [a.labels[i] for i in np.flatnonzero(~pooled & (cnt >= self.support))]
865
+ mass = [float(cnt[i]) for i in np.flatnonzero(~pooled & (cnt >= self.support))]
866
+ other = float(cnt[pooled].sum())
867
+ for i in np.flatnonzero(~pooled):
868
+ if a.labels[i] == OTHER:
869
+ other += float(cnt[i])
870
+ if other >= self.support and OTHER not in levels:
871
+ levels.append(OTHER)
872
+ mass.append(other)
873
+ null = float(n_null) if n_null >= self.support else 0.0
874
+ total = float(sum(mass)) + null
875
+ if total <= 0.0:
876
+ return
877
+ attr.rest_levels = np.asarray(levels, dtype=str) if levels else np.zeros(0, dtype="<U1")
878
+ attr.rest_probs = np.asarray([coarsen(m / total, self.policy) for m in mass],
879
+ dtype=np.float64)
880
+ attr.rest_null = float(coarsen(null / total, self.policy))
881
+
882
+ def table(self, key: str, edges: Sequence[_Edge], anchor: _Edge | None
883
+ ) -> tuple[EntityTable, dict[str, Any]]:
884
+ """The table of one group: ``edges`` are looked up, ``anchor`` is followed."""
885
+ k = self.coded(key)
886
+ has = k.codes >= 0
887
+ kk = k.codes[has]
888
+ keep = self.counts(key) >= self.support
889
+ every = [*edges, *([anchor] if anchor is not None else [])]
890
+ # the modal value of each attribute, where enough rows of the key hold it
891
+ modal: dict[str, np.ndarray] = {}
892
+ covered: dict[str, np.ndarray] = {}
893
+ held: dict[str, np.ndarray] = {}
894
+ for e in every:
895
+ a = self.coded(e.attribute)
896
+ best, count = _modal(kk, a.codes[has] + 1, k.n_values, a.n_values + 1)
897
+ modal[e.attribute], held[e.attribute] = best, count
898
+ covered[e.attribute] = keep & (count >= self.support)
899
+ # the entries of one key are stored only as far as enough rows hold all of them
900
+ big = np.iinfo(np.int64).max
901
+ for _ in range(len(every)):
902
+ agree = np.ones(kk.size, dtype=bool)
903
+ for e in every:
904
+ a = self.coded(e.attribute)
905
+ agree &= ~covered[e.attribute][kk] | (a.codes[has] + 1 == modal[e.attribute][kk])
906
+ together = np.bincount(kk[agree], minlength=k.n_values)
907
+ thin = (together < self.support) & np.any([covered[e.attribute] for e in every],
908
+ axis=0)
909
+ if not thin.any():
910
+ break
911
+ # drop, for each thin key, the entry held by the fewest rows
912
+ weakest = np.stack([np.where(covered[e.attribute], held[e.attribute], big)
913
+ for e in every]).argmin(axis=0)
914
+ for j, e in enumerate(every):
915
+ covered[e.attribute] = covered[e.attribute] & ~(thin & (weakest == j))
916
+ listed = np.flatnonzero(np.any([covered[e.attribute] for e in every], axis=0)) \
917
+ if every else np.zeros(0, dtype=np.int64)
918
+ keys = np.asarray([k.labels[i] for i in listed], dtype=str)
919
+ if keys.size == 0:
920
+ keys = np.zeros(0, dtype="<U1")
921
+ empty_rows = ~has
922
+ n_empty = int(empty_rows.sum())
923
+ info: dict[str, Any] = {"key": key, "keys": int(listed.size), "attributes": []}
924
+
925
+ def column(e: _Edge) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]:
926
+ """Values and state per listed key, the rows served, the rows changed."""
927
+ a = self.coded(e.attribute)
928
+ cov, best = covered[e.attribute][listed], modal[e.attribute][listed]
929
+ state = np.where(~cov, _STATE_NONE, np.where(best == 0, _STATE_NULL,
930
+ _STATE_VALUE)).astype(np.int8)
931
+ values = np.asarray([a.labels[b - 1] if s == _STATE_VALUE else ""
932
+ for b, s in zip(best.tolist(), state.tolist())], dtype=str)
933
+ if values.size == 0:
934
+ values = np.zeros(0, dtype="<U1")
935
+ served = np.zeros(self.n, dtype=bool)
936
+ served[has] = covered[e.attribute][kk]
937
+ wrong = int(np.sum(served[has] & (a.codes[has] + 1 != modal[e.attribute][kk])))
938
+ return values, state, served, wrong
939
+
940
+ def without_key(a: _Coded) -> tuple[int, str | None]:
941
+ """The entry of the rows without a key: one value, when nearly all of them
942
+ (the stray-row tolerance) agree on it and enough of them hold it."""
943
+ if n_empty < self.support:
944
+ return _STATE_NONE, None
945
+ vals, cnt = np.unique(a.codes[empty_rows] + 1, return_counts=True)
946
+ top = int(np.argmax(cnt))
947
+ if cnt[top] < self.support or \
948
+ n_empty - cnt[top] > tolerance.stray_limit(n_empty):
949
+ return _STATE_NONE, None
950
+ if vals[top] == 0:
951
+ return _STATE_NULL, None
952
+ return _STATE_VALUE, a.labels[int(vals[top]) - 1]
953
+
954
+ attrs: list[_Attribute] = []
955
+ for e in edges:
956
+ a = self.coded(e.attribute)
957
+ values, state, served, wrong = column(e)
958
+ attr = _Attribute(e.attribute, values, state)
959
+ attr.missing_state, attr.missing_value = without_key(a)
960
+ if attr.missing_state != _STATE_NONE:
961
+ served |= empty_rows
962
+ self.rest(attr, a, ~served)
963
+ attrs.append(attr)
964
+ info["attributes"].append({
965
+ **e.record(self.policy), "entries": int((state != _STATE_NONE).sum()),
966
+ "rows_served": coarsen(float(served.mean()), self.policy),
967
+ "rest_levels": 0 if attr.rest_levels is None else int(attr.rest_levels.size),
968
+ "rows_changed": coarsen(wrong / max(self.n, 1), self.policy) if wrong else 0.0})
969
+ anchored = None
970
+ if anchor is not None:
971
+ values, state, _, _ = column(anchor)
972
+ anchored = _Anchor(anchor.attribute, values, state,
973
+ *without_key(self.coded(anchor.attribute)))
974
+ info["anchor"] = {**anchor.record(self.policy),
975
+ "entries": int((state != _STATE_NONE).sum())}
976
+ return EntityTable(key, keys, attrs, anchored), info
977
+
978
+
979
+ def plan_entities(df: pl.DataFrame, columns: Sequence[ColumnSchema],
980
+ policy: DisclosurePolicySpec | str | None = None, *, mode: str = "auto",
981
+ declared: Mapping[str, Sequence[str]] | None = None,
982
+ exclude: Sequence[str] = (), seed: int = 0) -> EntityPlan:
983
+ """The entity groups of ``df`` (see the module docstring).
984
+
985
+ ``mode`` is the profiler's ``structure`` setting: ``"auto"`` detects groups and adds the
986
+ declared ones, ``"confirmed"`` uses the declared ones only, ``"off"`` none. ``declared``
987
+ maps a key column to its attribute columns; a declared group is taken as stated (the
988
+ acceptance tests are not applied; the disclosure rules are). Columns in ``exclude`` take
989
+ no part. Run this on the frame ``pseudonymise`` returned.
990
+ """
991
+ pol = resolve_policy(policy)
992
+ declared = {k: list(v) for k, v in (declared or {}).items()}
993
+ diag: dict[str, Any] = {
994
+ "mode": mode, "applied": [], "not_selected": [],
995
+ "thresholds": {"max_exception_rate": MAX_EXCEPTIONS, "max_dirty_rate": MAX_DIRTY,
996
+ "min_consistent_keys": MIN_CONSISTENT_KEYS, "min_keys": MIN_KEYS,
997
+ "min_coverage": MIN_COVERAGE,
998
+ "min_evidence_rows": MIN_EVIDENCE_ROWS,
999
+ "max_evidence_ratio": MAX_EVIDENCE_RATIO,
1000
+ "anchor_max_levels": ANCHOR_MAX_LEVELS,
1001
+ "min_support": max(int(pol.min_category_support), 1)}}
1002
+ if mode == "off" or df.height < 2:
1003
+ return EntityPlan(diagnostics=diag)
1004
+ det = _Detector(df, columns, pol, set(exclude), seed)
1005
+
1006
+ edges: list[_Edge] = []
1007
+ taken: set[str] = set()
1008
+ for key, attrs in declared.items():
1009
+ why = det.can_be_key(key) if key in det.schemas else "unknown column"
1010
+ if why is not None:
1011
+ raise ProfilingError(f"entities: {key!r} cannot be the key of a group: {why}")
1012
+ if not attrs:
1013
+ raise ProfilingError(f"entities: the group of {key!r} has no attributes")
1014
+ for a in attrs:
1015
+ why = "unknown column" if a not in det.schemas else \
1016
+ "it is the key" if a == key else det.can_be_attribute(a)
1017
+ if why is not None:
1018
+ raise ProfilingError(f"entities: {a!r} cannot be an attribute of {key!r}: "
1019
+ f"{why}")
1020
+ if a in taken:
1021
+ raise ProfilingError(f"entities: {a!r} is declared as an attribute of more "
1022
+ f"than one key")
1023
+ taken.add(a)
1024
+ found = det.edge(key, a, declared=True)
1025
+ if isinstance(found, str):
1026
+ raise ProfilingError(f"entities: {a!r} cannot be an attribute of {key!r}: "
1027
+ f"{found}")
1028
+ edges.append(found)
1029
+
1030
+ if mode == "auto":
1031
+ keys = [n for n in det.usable if det.can_be_key(n) is None and det.is_table(n) is None]
1032
+ targets = [n for n in det.usable if det.can_be_attribute(n) is None and n not in taken]
1033
+ pairs = 0
1034
+ for key in keys:
1035
+ for a in targets:
1036
+ if a == key or pairs >= _MAX_PAIRS:
1037
+ continue
1038
+ pairs += 1
1039
+ found = det.edge(key, a)
1040
+ if isinstance(found, _Edge):
1041
+ edges.append(found)
1042
+ elif (key, a) in det.near: # a near miss worth reporting
1043
+ diag["not_selected"].append({
1044
+ "key": key, "attribute": a, "reason": found,
1045
+ "exception_rate": coarsen(det.near[key, a], pol)})
1046
+
1047
+ # Two columns that determine each other: which of them names the entity? The one that
1048
+ # is the better key of the *other* columns both determine. Two banks under one name have
1049
+ # two streets, cities and numbers (the name is ambiguous: the street is the key); a
1050
+ # company with two phone lines has one address (the company is the key, the second line
1051
+ # is dirt). Without other columns to judge by, the direction that gets more rows right.
1052
+ accepted = {(e.key, e.attribute): e for e in edges}
1053
+ lost: set[tuple[str, str]] = set()
1054
+ for (a, b), ab in accepted.items():
1055
+ ba = accepted.get((b, a))
1056
+ if ba is None or ab.declared or ba.declared or det.order[a] > det.order[b]:
1057
+ continue
1058
+ shared = [x for (key, x) in accepted if key == a and (b, x) in accepted]
1059
+ score_a = (sum(accepted[a, x].served for x in shared), ab.served,
1060
+ -det.coded(a).n_values)
1061
+ score_b = (sum(accepted[b, x].served for x in shared), ba.served,
1062
+ -det.coded(b).n_values)
1063
+ lost.add((b, a) if score_a >= score_b else (a, b))
1064
+ edges = [e for e in edges if (e.key, e.attribute) not in lost]
1065
+ # one key per attribute: the key whose table gets the most rows right; no cycles
1066
+ edges.sort(key=lambda e: (not e.declared, -e.served, det.coded(e.key).n_values,
1067
+ det.order[e.key], det.order[e.attribute]))
1068
+ parent: dict[str, _Edge] = {}
1069
+
1070
+ def root(name: str) -> str:
1071
+ while name in parent:
1072
+ name = parent[name].key
1073
+ return name
1074
+
1075
+ def depends(name: str, on: str) -> bool:
1076
+ while name in parent:
1077
+ name = parent[name].key
1078
+ if name == on:
1079
+ return True
1080
+ return False
1081
+
1082
+ for e in edges:
1083
+ if e.attribute in parent:
1084
+ continue
1085
+ if e.key == e.attribute or depends(e.key, e.attribute):
1086
+ if e.declared:
1087
+ raise ProfilingError(f"entities: the declared groups form a cycle through "
1088
+ f"{e.key!r} and {e.attribute!r}")
1089
+ continue
1090
+ parent[e.attribute] = e
1091
+
1092
+ # the anchor of a root key: of the columns it determines (directly, or through a chain),
1093
+ # the one with the most values among those with few. It stays modeled; the key follows it.
1094
+ anchors: dict[str, _Edge] = {}
1095
+ for r in sorted({root(a) for a in parent}, key=lambda name: det.order[name]):
1096
+ cands = [accepted[r, a] for a in parent
1097
+ if root(a) == r and (r, a) in accepted
1098
+ and det.coded(a).n_values <= ANCHOR_MAX_LEVELS]
1099
+ if cands:
1100
+ anchors[r] = max(cands, key=lambda e: (det.coded(e.attribute).n_values,
1101
+ -det.order[e.attribute]))
1102
+ followed = {e.attribute for e in anchors.values()}
1103
+ by_key: dict[str, list[_Edge]] = {}
1104
+ for e in parent.values():
1105
+ if e.attribute not in followed:
1106
+ by_key.setdefault(e.key, []).append(e)
1107
+ # a group runs after the group that produces its key (an anchor is produced by the model)
1108
+ ordered: list[str] = []
1109
+
1110
+ def place(key: str) -> None:
1111
+ if key in ordered:
1112
+ return
1113
+ if key in parent and key not in followed:
1114
+ place(parent[key].key)
1115
+ ordered.append(key)
1116
+
1117
+ for key in sorted({*by_key, *anchors}, key=lambda name: det.order[name]):
1118
+ place(key)
1119
+ plan = EntityPlan(diagnostics=diag)
1120
+ for key in ordered:
1121
+ if key not in by_key and key not in anchors:
1122
+ continue
1123
+ group = sorted(by_key.get(key, []), key=lambda e: det.order[e.attribute])
1124
+ table, info = det.table(key, group, anchors.get(key))
1125
+ members = [*group, *([anchors[key]] if key in anchors else [])]
1126
+ table.source = "declared" if all(e.declared for e in members) else "detected"
1127
+ plan.tables.append(table)
1128
+ diag["applied"].append({**info, "source": table.source})
1129
+ for e in members:
1130
+ if e.attribute in followed:
1131
+ note = (f"anchor of the {table.source} entity group of {key!r}: modeled as "
1132
+ f"before; a generated key that belongs to another value of this "
1133
+ f"column is drawn again among the keys of the row's own")
1134
+ else:
1135
+ note = (f"attribute of {key!r} ({table.source} entity group): a generated "
1136
+ f"row whose key has an entry takes this column from the key")
1137
+ if e.exceptions:
1138
+ note += "; " + tolerance.note(
1139
+ e.verdict if e.verdict is not None else tolerance.Verdict(
1140
+ "declared", e.exceptions, e.rows),
1141
+ pol, breaks="hold another value than their key's")
1142
+ plan.notes[e.attribute] = note
1143
+ return plan