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,435 @@
1
+ """One rule for a relationship that holds on all but a few rows (ADR-0015).
2
+
3
+ Real tables are dirty. A date typed a year off puts ``issued`` before ``applied`` in three rows
4
+ of ten thousand; a weekday column contradicts its date where someone corrected one and not the
5
+ other; five amounts add up to the valuation except where a clerk keyed a digit twice; a
6
+ company has a second phone line. Four features of the profiler decide whether such a
7
+ relationship *holds* and is then modeled as one: orderings (``profiling.structure``), computed
8
+ columns (``profiling.functional``), sums (``profiling.sums``) and entity groups
9
+ (``profiling.entity``). They all ask this module, so that "holds despite dirty rows" means one
10
+ thing.
11
+
12
+ The rule (:func:`judge`)
13
+ ------------------------
14
+ Let ``e`` of the ``n`` rows the relationship is about break it.
15
+
16
+ ``exact``
17
+ ``e = 0``.
18
+ ``stray``
19
+ ``e <= floor(STRAY * n)``: at most 0.5 % of the rows, **wherever they are**. A handful of
20
+ rows is dirt, and nothing can be learned from where five rows sit.
21
+ ``isolated``
22
+ ``e <= floor(DIRTY * n)``, at most 2 %, **and the exceptions look like dirt**: isolated
23
+ incidents, not a second rule that some part of the table follows. What "isolated" means
24
+ is the feature's to say, because it depends on what the relationship is about:
25
+
26
+ * a relationship between the columns of a *row* (an ordering, a function, a sum): the
27
+ exception rows are scattered (:func:`scattered`). They are *not* scattered when at
28
+ least ``SYSTEMATIC_SHARE`` of them lie in places where the relationship is broken as
29
+ a rule: a category of some column, or a stretch of the values of some column, in
30
+ which at least ``DENSE_RATE`` of the rows break it. All late dates in one office, a
31
+ total that excludes one part above a threshold, a placeholder value that is not a
32
+ measurement: those are rules of their own, and enforcing the relationship there would
33
+ rewrite them;
34
+ * a relationship about an *entity* (a key and its attributes): the exceptions are
35
+ confined to a few entities, and at least ``CONSISTENT_KEYS`` of the kept keys are
36
+ consistent on their own (``profiling.entity``). An attribute that leaks a little in
37
+ most keys is a statistical relationship, not a property of the entity.
38
+
39
+ This tier needs ``floor(STRAY * n) >= 1`` (200 rows): a table that small does not show
40
+ whether an exception is dirt, and it is held to "no exception" as before.
41
+ anything else
42
+ The relationship is not adopted (``systematic`` or ``too_many``); the reason and the rate
43
+ are in the diagnostics of the feature, as a near miss when the rate is at most
44
+ ``NEAR_MISS``.
45
+
46
+ The rule says how many exceptions are tolerated and where. It does not replace the evidence
47
+ each feature asks for that the relationship is not a coincidence: a sum must fail once its
48
+ total is shuffled, an ordering must be unlikely between unrelated columns, an attribute must
49
+ break under a shuffled key, a function needs enough distinct base values. Those guards are
50
+ unchanged and apply at every tier.
51
+
52
+ Why these numbers
53
+ -----------------
54
+ ``STRAY = 0.005``
55
+ The lower tail-clip level of the standard policy: half a percent of a column is what the
56
+ policy already treats as tail that no stored statistic describes. The largest rate of
57
+ out-of-order rows among the date pairs ADR-0009 was built on was 0.2 %.
58
+ ``DIRTY = 0.02``
59
+ A judgement, set on cases: the phone number of a company (0.61 % of the rows of a real
60
+ permits table), the NAICS description of a code (0.73 % of a public loans table), a
61
+ five-part valuation sum (0.68 %). It is four times the stray rate and still means that 49
62
+ rows in 50 follow the rule. Beyond it a relationship is for the user to confirm.
63
+ ``DENSE_RATE = 0.25``, ``MIN_DENSE_ROWS = 5``, ``SYSTEMATIC_SHARE = 0.5``
64
+ Judgements. One row in four is 12 times the dirtiest table the rule accepts: where a
65
+ relationship fails that often it is not the rule. Five rows is the smallest number of
66
+ rows any policy lets a stored statistic stand for. And when most of the exceptions sit
67
+ in such places, the place explains them better than chance does. Scattered dirt at 2 %
68
+ puts about one exception in a thousand into a dense stretch by chance, so the test does
69
+ not refuse dirt (``tests/unit/test_tolerance.py`` measures it).
70
+ ``CONSISTENT_KEYS = 0.9``
71
+ A judgement from ADR-0013: nine kept keys in ten are functions on their own.
72
+
73
+ What generation does with the exceptions
74
+ ----------------------------------------
75
+ One principle: **an exception is reproduced only where the model of the relationship has a
76
+ place for it that costs the other rows nothing; otherwise it is dropped and counted.**
77
+
78
+ * An *unconfirmed ordering* is modeled as a difference whose gap keeps its sign
79
+ (``signed``): an out-of-order row is a negative gap, a value the gap's marginal holds
80
+ like any other. About the source's share of out-of-order rows is generated.
81
+ * An *equality* (a computed column, a sum, an entity attribute) has no such place: an
82
+ exception is some other value, and to generate it the model would need a second model of
83
+ "which wrong value", which invents errors where the source has none. The generated rows
84
+ all satisfy the relationship.
85
+ * A relationship the *user confirms* (a hard constraint, a declared entity group) always
86
+ holds on every generated row.
87
+
88
+ Either way the share of source rows that break the relationship is written to the notes of
89
+ the column it computes (:func:`note`) and to the diagnostics of the feature
90
+ (:meth:`Verdict.record`), coarsened by the policy.
91
+ """
92
+
93
+ from __future__ import annotations
94
+
95
+ import math
96
+ from collections.abc import Callable, Mapping, Sequence
97
+ from dataclasses import dataclass, field
98
+ from typing import Any
99
+
100
+ import numpy as np
101
+ import polars as pl
102
+
103
+ from ectype.fingerprint.disclosure import coarsen
104
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec
105
+ from ectype.types import LogicalType, Role
106
+
107
+ __all__ = [
108
+ "CONSISTENT_KEYS",
109
+ "DENSE_RATE",
110
+ "DIRTY",
111
+ "MAX_CONTEXT_COLUMNS",
112
+ "MAX_CONTEXT_LEVELS",
113
+ "MIN_DENSE_ROWS",
114
+ "NEAR_MISS",
115
+ "STRAY",
116
+ "SYSTEMATIC_SHARE",
117
+ "TIERS",
118
+ "Context",
119
+ "Isolation",
120
+ "Verdict",
121
+ "dirty_limit",
122
+ "judge",
123
+ "note",
124
+ "scattered",
125
+ "stray_limit",
126
+ "thresholds",
127
+ ]
128
+
129
+ #: largest share of rows that may break a relationship wherever they are (stray rows)
130
+ STRAY = 0.005
131
+ #: ... and the largest share when the exceptions are isolated (dirt, not a second rule)
132
+ DIRTY = 0.02
133
+ #: a category or a stretch of values is *dense* when at least this share of its rows break
134
+ #: the relationship ...
135
+ DENSE_RATE = 0.25
136
+ #: ... and at least this many do
137
+ MIN_DENSE_ROWS = 5
138
+ #: the exceptions of a row-level relationship are systematic when at least this share of
139
+ #: them lie in dense categories or stretches of one column
140
+ SYSTEMATIC_SHARE = 0.5
141
+ #: an entity relationship is dirty, not statistical, when at least this share of the kept
142
+ #: keys are consistent on their own
143
+ CONSISTENT_KEYS = 0.9
144
+ #: a refused relationship is reported as a near miss up to this share of exceptions
145
+ NEAR_MISS = 0.05
146
+ #: a categorical column is looked at for dense categories when it has at most this many
147
+ #: levels in the table, and at most this many columns beside the relationship's own are
148
+ #: looked at (in table order)
149
+ MAX_CONTEXT_LEVELS = 1000
150
+ MAX_CONTEXT_COLUMNS = 64
151
+ #: the verdicts of :func:`judge`; the first three adopt the relationship. (A feature may
152
+ #: build a :class:`Verdict` with the tier ``"declared"`` for a relationship the user stated:
153
+ #: it is used as stated, and only its exceptions are counted.)
154
+ TIERS = ("exact", "stray", "isolated", "systematic", "too_many")
155
+
156
+
157
+ def stray_limit(rows: int) -> int:
158
+ """Most rows that may break a relationship about ``rows`` rows wherever they are."""
159
+ return int(math.floor(STRAY * max(int(rows), 0)))
160
+
161
+
162
+ def dirty_limit(rows: int) -> int:
163
+ """Most rows that may break it when they are isolated: ``floor(DIRTY * rows)``, and no
164
+ more than :func:`stray_limit` while that is zero (fewer than 200 rows)."""
165
+ stray = stray_limit(rows)
166
+ return int(math.floor(DIRTY * max(int(rows), 0))) if stray >= 1 else stray
167
+
168
+
169
+ def thresholds() -> dict[str, float]:
170
+ """The numbers of the rule, for a feature's diagnostics."""
171
+ return {"max_exception_rate": STRAY, "max_dirty_rate": DIRTY,
172
+ "dense_rate": DENSE_RATE, "systematic_share": SYSTEMATIC_SHARE}
173
+
174
+
175
+ @dataclass(frozen=True)
176
+ class Isolation:
177
+ """What a feature found about where its exceptions are."""
178
+
179
+ isolated: bool
180
+ #: why not, or what was looked at, in words (goes into a refusal's reason)
181
+ detail: str = ""
182
+ #: JSON-safe numbers behind it (already coarsened by the caller where they are rates)
183
+ evidence: Mapping[str, Any] = field(default_factory=dict)
184
+
185
+
186
+ @dataclass(frozen=True)
187
+ class Verdict:
188
+ """Whether a relationship holds despite its exceptions (:func:`judge`)."""
189
+
190
+ tier: str
191
+ exceptions: int
192
+ rows: int
193
+ isolation: Isolation | None = None
194
+
195
+ @property
196
+ def holds(self) -> bool:
197
+ return self.tier in ("exact", "stray", "isolated")
198
+
199
+ @property
200
+ def rate(self) -> float:
201
+ return self.exceptions / max(self.rows, 1)
202
+
203
+ @property
204
+ def near_miss(self) -> bool:
205
+ """Refused, and close enough to be worth reporting."""
206
+ return not self.holds and self.exceptions <= NEAR_MISS * self.rows
207
+
208
+ def reason(self, breaks: str = "break it") -> str:
209
+ """Why the relationship was refused (empty when it holds). ``breaks`` says what an
210
+ exception row does, e.g. ``"do not follow the function"``."""
211
+ if self.holds:
212
+ return ""
213
+ head = f"{self.exceptions} of {self.rows} rows {breaks}"
214
+ if self.tier == "systematic":
215
+ detail = self.isolation.detail if self.isolation is not None else ""
216
+ return (f"{head} (more than {STRAY:.1%}), and they are not isolated"
217
+ f"{': ' + detail if detail else ''}")
218
+ if self.rows and stray_limit(self.rows) < 1:
219
+ return f"{head} (none is tolerated in fewer than {math.ceil(1 / STRAY)} rows)"
220
+ return f"{head} (more than {DIRTY:.0%})"
221
+
222
+ def record(self, policy: DisclosurePolicySpec) -> dict[str, Any]:
223
+ """The verdict for a feature's diagnostics: the coarsened exception rate, the tier
224
+ and what the isolation test found."""
225
+ out: dict[str, Any] = {
226
+ "exception_rate": coarsen(self.rate, policy) if self.exceptions else 0.0,
227
+ "tolerance": self.tier}
228
+ if self.isolation is not None and self.isolation.evidence:
229
+ out["isolation"] = dict(self.isolation.evidence)
230
+ return out
231
+
232
+
233
+ def judge(exceptions: int, rows: int,
234
+ isolated: Callable[[], Isolation] | None = None) -> Verdict:
235
+ """The rule of this module: do ``exceptions`` of ``rows`` rows leave the relationship
236
+ standing? ``isolated`` is the feature's test of where the exceptions are; it is called
237
+ only when the count is above the stray limit and within the dirty one. Without it the
238
+ stray limit is the only tolerance."""
239
+ exceptions, rows = int(exceptions), int(rows)
240
+ if exceptions <= 0:
241
+ return Verdict("exact", 0, rows)
242
+ if exceptions <= stray_limit(rows):
243
+ return Verdict("stray", exceptions, rows)
244
+ if exceptions > dirty_limit(rows) or isolated is None:
245
+ return Verdict("too_many", exceptions, rows)
246
+ found = isolated()
247
+ return Verdict("isolated" if found.isolated else "systematic", exceptions, rows, found)
248
+
249
+
250
+ def note(verdict: Verdict, policy: DisclosurePolicySpec, *, breaks: str,
251
+ reproduced: bool = False) -> str:
252
+ """The clause a column's note gets about the exceptions of the relationship that
253
+ computes it (empty without exceptions): the coarsened share of source rows, which
254
+ tolerance let it stand, and what generation does with them."""
255
+ if verdict.exceptions <= 0:
256
+ return ""
257
+ rate = float(coarsen(verdict.rate, policy))
258
+ kind = {"isolated": " (isolated dirty rows)", "stray": " (stray rows)"}.get(verdict.tier, "")
259
+ fate = ("about that share is reproduced" if reproduced else "they are not reproduced")
260
+ return f"{rate:.2%} of {verdict.rows} source rows {breaks}{kind}; {fate}"
261
+
262
+
263
+ # ---------------------------------------------------------------------------------------------
264
+ # Row-level relationships: are the exceptions scattered?
265
+ # ---------------------------------------------------------------------------------------------
266
+
267
+
268
+ def _dense_levels(codes: np.ndarray, exc: np.ndarray) -> int:
269
+ """Exceptions that lie in dense levels of ``codes`` (non-negative integers per row)."""
270
+ n_levels = int(codes.max()) + 1 if codes.size else 0
271
+ if not n_levels:
272
+ return 0
273
+ rows = np.bincount(codes, minlength=n_levels)
274
+ hits = np.bincount(codes[exc], minlength=n_levels)
275
+ dense = (hits >= MIN_DENSE_ROWS) & (hits >= DENSE_RATE * rows)
276
+ return int(hits[dense].sum())
277
+
278
+
279
+ def _dense_stretches(x: np.ndarray, exc: np.ndarray) -> int:
280
+ """Exceptions that lie in dense stretches of the values ``x`` (finite, one per row): runs
281
+ of ``MIN_DENSE_ROWS`` exceptions that are consecutive in the order of ``x`` and, with
282
+ every row that has a value between their smallest and largest (ties included), still make
283
+ up ``DENSE_RATE`` of those rows."""
284
+ ev = np.sort(x[exc])
285
+ m = MIN_DENSE_ROWS
286
+ if ev.size < m:
287
+ return 0
288
+ xs = np.sort(x)
289
+ first, last = ev[:ev.size - m + 1], ev[m - 1:]
290
+ span = np.searchsorted(xs, last, side="right") - np.searchsorted(xs, first, side="left")
291
+ inside = np.searchsorted(ev, last, side="right") - np.searchsorted(ev, first, side="left")
292
+ starts = np.flatnonzero(inside >= DENSE_RATE * span)
293
+ if not starts.size:
294
+ return 0
295
+ # the exceptions covered by a dense run: positions start .. start + m - 1 (and the ties
296
+ # of its ends, which the run's span already counts)
297
+ lo = np.searchsorted(ev, first[starts], side="left")
298
+ hi = np.searchsorted(ev, last[starts], side="right")
299
+ cover = np.zeros(ev.size + 1, dtype=np.int64)
300
+ np.add.at(cover, lo, 1)
301
+ np.add.at(cover, hi, -1)
302
+ return int((np.cumsum(cover[:-1]) > 0).sum())
303
+
304
+
305
+ def scattered(exceptions: np.ndarray, *, scope: np.ndarray | None = None,
306
+ ranges: Mapping[str, np.ndarray] | None = None,
307
+ levels: Mapping[str, np.ndarray] | None = None,
308
+ flags: tuple[Sequence[str], np.ndarray] | None = None,
309
+ policy: DisclosurePolicySpec | None = None) -> Isolation:
310
+ """Whether the exception rows of a row-level relationship are scattered (see the module
311
+ docstring).
312
+
313
+ ``exceptions`` marks the rows that break it, among the rows of ``scope`` (default: all).
314
+ ``ranges`` are columns whose order means something (numbers, dates as numbers; NaN for
315
+ an empty cell); ``levels`` are columns of categories as integer codes (negative for an
316
+ empty cell). The empty cells of either kind are one more category. ``flags`` is a list of
317
+ descriptions and a boolean matrix with one column for each: conditions a row meets or
318
+ not (the rows in which some column is filled), each looked at as a category of its own.
319
+ The position of a row in the table is always looked at as a range. Returns the column in
320
+ which the largest share of the exceptions lies in dense categories or stretches, and
321
+ that share.
322
+ """
323
+ exc = np.asarray(exceptions, dtype=bool)
324
+ inside = np.ones(exc.size, dtype=bool) if scope is None else np.asarray(scope, dtype=bool)
325
+ exc = exc & inside
326
+ total = int(exc.sum())
327
+ worst, where = 0, ""
328
+ if total >= MIN_DENSE_ROWS:
329
+ rows = np.flatnonzero(inside)
330
+ e = exc[rows]
331
+ found = _dense_stretches(rows.astype(np.float64), e)
332
+ if found > worst:
333
+ worst, where = found, "the order of the rows"
334
+ for name, values in (ranges or {}).items():
335
+ x = np.asarray(values, dtype=np.float64)[rows]
336
+ ok = np.isfinite(x)
337
+ found = _dense_stretches(x[ok], e[ok]) if ok.any() else 0
338
+ if not ok.all():
339
+ found += _dense_levels(np.zeros(int((~ok).sum()), dtype=np.int64), e[~ok])
340
+ if found > worst:
341
+ worst, where = found, f"the values of {name!r}"
342
+ for name, codes in (levels or {}).items():
343
+ c = np.asarray(codes, dtype=np.int64)[rows]
344
+ found = _dense_levels(np.where(c < 0, 0, c + 1), e)
345
+ if found > worst:
346
+ worst, where = found, f"the categories of {name!r}"
347
+ if flags is not None and len(flags[0]):
348
+ met = np.asarray(flags[1], dtype=bool)[rows]
349
+ size = met.sum(axis=0)
350
+ hits = met[e].sum(axis=0)
351
+ dense = np.where((hits >= MIN_DENSE_ROWS) & (hits >= DENSE_RATE * size), hits, 0)
352
+ k = int(np.argmax(dense))
353
+ if int(dense[k]) > worst:
354
+ worst, where = int(dense[k]), str(flags[0][k])
355
+ share = worst / max(total, 1)
356
+ isolated = share < SYSTEMATIC_SHARE
357
+ shown = float(coarsen(share, policy)) if policy is not None else round(share, 3)
358
+ evidence: dict[str, Any] = {"dense_share": shown if worst else 0.0}
359
+ if worst:
360
+ evidence["column"] = where
361
+ detail = "" if isolated else (
362
+ f"{share:.0%} of them lie where at least {DENSE_RATE:.0%} of the rows break it, in "
363
+ f"{where}")
364
+ return Isolation(isolated, detail, evidence)
365
+
366
+
367
+ class Context:
368
+ """The columns of a table in which the exceptions of a row-level relationship are looked
369
+ for a pattern: numbers and dates as ranges, categories and flags as levels. Reads the
370
+ frame the profiler fits (after pseudonymisation) when a test asks for a column."""
371
+
372
+ def __init__(self, df: pl.DataFrame, columns: Sequence[ColumnSchema],
373
+ policy: DisclosurePolicySpec | None = None) -> None:
374
+ self.df = df
375
+ self.policy = policy
376
+ self.schemas = {c.name: c for c in columns
377
+ if c.name in df.columns and c.role == Role.FEATURE
378
+ and not c.name.startswith("__")}
379
+ #: whether a categorical column has few enough levels (nothing else is cached: the
380
+ #: test runs for the few relationships between the two limits, and a wide table's
381
+ #: columns as arrays would cost more memory than the test is worth)
382
+ self._few: dict[str, bool] = {}
383
+
384
+ def range(self, name: str) -> np.ndarray | None:
385
+ """The values of a numeric or datetime feature column as floats (NaN: empty)."""
386
+ from ectype.io.values import column_to_values
387
+
388
+ col = self.schemas.get(name)
389
+ if col is None or col.logical_type not in (
390
+ LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.DATETIME):
391
+ return None
392
+ try:
393
+ return np.asarray(column_to_values(self.df.get_column(name), col),
394
+ dtype=np.float64)
395
+ except Exception: # noqa: BLE001 - a column that does not convert is no context
396
+ return None
397
+
398
+ def level(self, name: str) -> np.ndarray | None:
399
+ """The values of a categorical or boolean feature column as codes (-1: empty), when
400
+ it has at most ``MAX_CONTEXT_LEVELS`` of them."""
401
+ col = self.schemas.get(name)
402
+ if col is None or col.logical_type not in (LogicalType.CATEGORICAL,
403
+ LogicalType.BOOLEAN):
404
+ return None
405
+ if name not in self._few:
406
+ self._few[name] = self.df.get_column(name).n_unique() <= MAX_CONTEXT_LEVELS + 1
407
+ if not self._few[name]:
408
+ return None
409
+ s = self.df.get_column(name).cast(pl.String, strict=False)
410
+ codes = s.cast(pl.Categorical).to_physical().cast(pl.Int64).fill_null(-1)
411
+ return codes.to_numpy().astype(np.int64)
412
+
413
+ def scattered(self, exceptions: np.ndarray, own: Sequence[str] = (), *,
414
+ scope: np.ndarray | None = None,
415
+ ranges: Mapping[str, np.ndarray] | None = None,
416
+ levels: Mapping[str, np.ndarray] | None = None,
417
+ flags: tuple[Sequence[str], np.ndarray] | None = None) -> Isolation:
418
+ """:func:`scattered` over the relationship's ``own`` columns, the arrays the feature
419
+ passes itself (``ranges``, ``levels``, ``flags``: its own view of its columns) and
420
+ up to ``MAX_CONTEXT_COLUMNS`` other feature columns of the table."""
421
+ rng: dict[str, np.ndarray] = dict(ranges or {})
422
+ lev: dict[str, np.ndarray] = dict(levels or {})
423
+ others = [n for n in self.schemas if n not in own][:MAX_CONTEXT_COLUMNS]
424
+ for name in (*own, *others):
425
+ if name in rng or name in lev:
426
+ continue
427
+ r = self.range(name)
428
+ if r is not None:
429
+ rng[name] = r
430
+ continue
431
+ lv = self.level(name)
432
+ if lv is not None:
433
+ lev[name] = lv
434
+ return scattered(exceptions, scope=scope, ranges=rng, levels=lev, flags=flags,
435
+ policy=self.policy)