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,622 @@
1
+ """What is worth saying about a fingerprint: alerts, the overview paragraph, the terminal
2
+ summary (ADR-0016).
3
+
4
+ Works on a :class:`~ectype.reporting.view.ReportView` only: standard library, no engine
5
+ knowledge. Every rule's threshold is in :data:`THRESHOLDS`.
6
+
7
+ An :class:`Alert` message is one sentence. When the alert concerns columns, the message holds
8
+ the placeholder ``{cols}`` exactly once, where the renderer puts the linked column names (the
9
+ renderer should substitute it with ``str.replace``, not ``str.format``, and only when
10
+ ``columns`` is not empty: engine warnings are carried verbatim and may hold braces).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from collections.abc import Iterable, Sequence
17
+ from dataclasses import dataclass, field
18
+
19
+ from ectype.reporting import fmt
20
+ from ectype.reporting.view import HANDLINGS, ColumnView, ReportView
21
+
22
+ PLACEHOLDER = "{cols}"
23
+
24
+ THRESHOLDS: dict[str, float] = {
25
+ # missing share at or above which a column is "nearly empty" (act)
26
+ "nearly_empty": 0.95,
27
+ # missing share at or above which a column is "mostly empty" (note), below nearly_empty
28
+ "mostly_empty": 0.5,
29
+ # association strength at or above which two columns are near duplicates
30
+ "near_duplicate": 0.98,
31
+ # near-duplicate pairs listed one by one before the rest are counted
32
+ "max_near_duplicates": 10,
33
+ # engine warnings listed one by one before the rest are counted
34
+ "max_engine_warnings": 8,
35
+ # share of the largest level at or above which one value dominates a column
36
+ "dominant_value": 0.95,
37
+ # share of a point mass at 0 at or above which a column is zero-heavy
38
+ "zero_heavy": 0.5,
39
+ # (p95 - p50) / (p50 - p05), or the mirror ratio, at or above which a column is skewed
40
+ "skew_ratio": 8.0,
41
+ # a point mass is a likely placeholder when it holds at least this share of the rows ...
42
+ "sentinel_share": 0.01,
43
+ # ... and lies at least this many times the width of the other values away from them
44
+ "sentinel_gap": 1.0,
45
+ # share of rows in the pooled bucket at or above which pooling is heavy
46
+ "pooled_heavy": 0.2,
47
+ # confidence of the inferred type and role below which it is low
48
+ "low_confidence": 0.7,
49
+ }
50
+
51
+ #: kinds in the order they are listed ("act" kinds first)
52
+ ACT_KINDS = ("sensitive", "left_out", "personal", "unread", "engine_warning", "nearly_empty")
53
+ NOTE_KINDS = ("near_duplicate", "mostly_empty", "constant", "key", "exceptions",
54
+ "dominant_value", "sentinel", "zero_heavy", "skew", "pooled_heavy", "coarse",
55
+ "low_confidence", "uncharted")
56
+
57
+ #: measures that treat two columns alike, so that a strength near 1 means "the same information"
58
+ SYMMETRIC = ("spearman", "cramers_v")
59
+ KINDS = ACT_KINDS + NOTE_KINDS
60
+
61
+
62
+ @dataclass
63
+ class Alert:
64
+ """One finding. ``severity`` is ``"act"`` (worth acting on) or ``"note"``."""
65
+
66
+ kind: str
67
+ severity: str
68
+ columns: list[str] = field(default_factory=list)
69
+ message: str = ""
70
+ advice: str = ""
71
+
72
+ @property
73
+ def text(self) -> str:
74
+ """The finished sentence: :attr:`message` with the column names in place."""
75
+ return render_message(self)
76
+
77
+
78
+ # -- helpers ----------------------------------------------------------------------------------
79
+
80
+
81
+ def _num(x: object) -> float | None:
82
+ if x is None or isinstance(x, bool):
83
+ return None
84
+ try:
85
+ v = float(x) # type: ignore[arg-type]
86
+ except (TypeError, ValueError, OverflowError):
87
+ return None
88
+ return v if v == v and v not in (float("inf"), float("-inf")) else None
89
+
90
+
91
+ def _is(n: int, one: str = "is", many: str = "are") -> str:
92
+ return one if n == 1 else many
93
+
94
+
95
+ def _safe(text: object) -> str:
96
+ """Untrusted vocabulary put into a message: no braces, so ``{cols}`` stays unique."""
97
+ return str(text).replace("{", "(").replace("}", ")")
98
+
99
+
100
+ def _as_sentence(text: str) -> str:
101
+ """An engine warning as a sentence: its words untouched, a capital first, a full stop last."""
102
+ t = text.strip()
103
+ if not t:
104
+ return t
105
+ t = t[0].upper() + t[1:]
106
+ return t if t[-1] in ".!?:" else t + "."
107
+
108
+
109
+ def _unique(names: Iterable[str]) -> list[str]:
110
+ seen: set[str] = set()
111
+ out = []
112
+ for n in names:
113
+ if n not in seen:
114
+ seen.add(n)
115
+ out.append(n)
116
+ return out
117
+
118
+
119
+ def _sorted_by_index(view: ReportView, names: Iterable[str]) -> list[str]:
120
+ pos = {c.name: i for i, c in enumerate(view.columns)}
121
+ idx = {c.name: c.index for c in view.columns}
122
+ unique = _unique(names)
123
+ return sorted(unique, key=lambda n: (idx.get(n, 10**9), pos.get(n, 10**9)))
124
+
125
+
126
+ def _group(view: ReportView, kind: str, severity: str, names: Iterable[str], one: str,
127
+ many: str, advice: str = "") -> list[Alert]:
128
+ cols = _sorted_by_index(view, names)
129
+ if not cols:
130
+ return []
131
+ return [Alert(kind, severity, cols, one if len(cols) == 1 else many, advice)]
132
+
133
+
134
+ def _quantile(c: ColumnView, p: float) -> float | None:
135
+ if c.histogram is None:
136
+ return None
137
+ for q in c.histogram.quantiles or []:
138
+ try:
139
+ qp, qv = _num(q[0]), _num(q[1])
140
+ except (IndexError, TypeError):
141
+ continue
142
+ if qp is not None and qv is not None and abs(qp - p) < 1e-6:
143
+ return qv
144
+ return None
145
+
146
+
147
+ def _sentinel(c: ColumnView) -> tuple[float, float] | None:
148
+ """``(value, share)`` of the point mass that lies far outside the column's other values
149
+ (the largest such), or ``None``. "Far" is at least ``sentinel_gap`` times the width of the
150
+ range the other values occupy: -9.99 beside values between 0 and 2, 9999 beside ages."""
151
+ h = c.histogram
152
+ if h is None or h.axis not in ("number", "date") or not h.atoms:
153
+ return None
154
+ edges = [_num(e) for e in h.edges or []]
155
+ shares = [_num(x) or 0.0 for x in h.shares or []]
156
+ held = [i for i, x in enumerate(shares) if x > 0 and i + 1 < len(edges)]
157
+ if not held:
158
+ return None
159
+ lo, hi = edges[held[0]], edges[held[-1] + 1]
160
+ if lo is None or hi is None or not hi > lo:
161
+ return None
162
+ best: tuple[float, float] | None = None
163
+ for a in h.atoms:
164
+ val, share = _num(a.value), _num(a.share)
165
+ if val is None or share is None or share < THRESHOLDS["sentinel_share"] or val == 0:
166
+ continue # an exact 0 is a value in its own right
167
+ gap = lo - val if val < lo else val - hi
168
+ if gap >= THRESHOLDS["sentinel_gap"] * (hi - lo) and (best is None or share > best[1]):
169
+ best = (val, share)
170
+ return best
171
+
172
+
173
+ def _skewed(c: ColumnView) -> bool:
174
+ h = c.histogram
175
+ if h is None or _sentinel(c) is not None: # the far value is the story, not a tail
176
+ return False
177
+ if h.scale == "log":
178
+ return True
179
+ p05, p50, p95 = _quantile(c, 0.05), _quantile(c, 0.5), _quantile(c, 0.95)
180
+ if p05 is None or p50 is None or p95 is None:
181
+ return False
182
+ r = THRESHOLDS["skew_ratio"]
183
+ return (p50 > p05 and (p95 - p50) >= r * (p50 - p05)) or (
184
+ p95 > p50 and (p50 - p05) >= r * (p95 - p50))
185
+
186
+
187
+ def _pooled_share(view: ReportView, c: ColumnView) -> float:
188
+ shares: list[float] = []
189
+ if c.levels is not None:
190
+ shares.append(_num(c.levels.pooled_share) or 0.0)
191
+ shares += [_num(b.share) or 0.0 for b in c.levels.bars or [] if b.kind == "pooled"]
192
+ shares += [_num(p.share) or 0.0 for p in view.privacy.pooled if p.column == c.name]
193
+ return max(shares, default=0.0)
194
+
195
+
196
+ # -- alerts -----------------------------------------------------------------------------------
197
+
198
+
199
+ def alerts(view: ReportView) -> list[Alert]:
200
+ """The alerts of a view: "act" first, then notes, kinds in the order of :data:`KINDS`,
201
+ each kind's alerts by column index. Columns that share a finding share one alert, except
202
+ where the message needs a number of its own (near duplicates, exceptions)."""
203
+ t = THRESHOLDS
204
+ cols = list(view.columns)
205
+ out: list[Alert] = []
206
+
207
+ if view.privacy.sensitive:
208
+ out.append(Alert("sensitive", "act", [],
209
+ "The policy marks this fingerprint as sensitive: it and this page hold "
210
+ "finer detail than usual.",
211
+ "Share the page only with people who may see the fingerprint."))
212
+
213
+ out += _group(view, "left_out", "act",
214
+ [c.name for c in cols if c.handling == "excluded"],
215
+ "{cols} was left out of the model: nothing of its values is in the "
216
+ "fingerprint, so this page cannot describe it.",
217
+ "{cols} were left out of the model: nothing of their values is in the "
218
+ "fingerprint, so this page cannot describe them.")
219
+
220
+ personal = [c.name for c in cols if c.handling == "pseudonym"]
221
+ personal += [p.column for p in view.privacy.personal if p.handling == "pseudonym"]
222
+ out += _group(view, "personal", "act", personal,
223
+ "{cols} looks personal: its values are replaced by stand-in tokens.",
224
+ "{cols} look personal: their values are replaced by stand-in tokens.",
225
+ "Check that this is intended; to keep the real values, override the role "
226
+ "to feature.")
227
+
228
+ unread = view.all_unread()
229
+ if unread:
230
+ n = len(unread)
231
+ out.append(Alert("unread", "act", [],
232
+ f"{fmt.plural(n, 'item')} in this fingerprint {_is(n)} not described "
233
+ "by this version of the report.",
234
+ "They are listed under What this page does not describe."))
235
+
236
+ warns = [str(w) for w in view.privacy.warnings]
237
+ cap = int(t["max_engine_warnings"])
238
+ quoted = "A warning the engine gave when it fitted the table, quoted as written."
239
+ out += [Alert("engine_warning", "act", [], _as_sentence(w), quoted) for w in warns[:cap]]
240
+ if len(warns) > cap:
241
+ more = len(warns) - cap
242
+ out.append(Alert("engine_warning", "act", [],
243
+ f"The engine gave {fmt.plural(more, 'more warning')}, listed in the "
244
+ "privacy section."))
245
+
246
+ def missing(c: ColumnView) -> float | None:
247
+ return _num(c.missing)
248
+
249
+ pct_ne = fmt.share(t["nearly_empty"])
250
+ out += _group(view, "nearly_empty", "act",
251
+ [c.name for c in cols if (missing(c) or 0.0) >= t["nearly_empty"]],
252
+ f"{{cols}} is empty in {pct_ne} or more of rows.",
253
+ f"{{cols}} are empty in {pct_ne} or more of rows.",
254
+ "Check whether these columns are worth keeping.")
255
+
256
+ # columns that carry the same information: one alert per group the adapter formed, and
257
+ # one per remaining pair (a view without groups, or a pair across two groups)
258
+ dup: list[tuple[list[str], float | None, str]] = []
259
+ grouped: set[str] = set()
260
+ for grp in view.relationships.groups or []:
261
+ names = _unique(grp.columns or [])
262
+ if len(names) >= 2 and not grp.explained_by:
263
+ dup.append((names, _num(grp.weakest), grp.measure))
264
+ grouped.update(names)
265
+ for p in view.relationships.pairs:
266
+ if ((_num(p.strength) or 0.0) >= t["near_duplicate"] and not p.explained_by
267
+ and p.measure in SYMMETRIC and p.a_group is None and p.b_group is None
268
+ and not (p.a in grouped and p.b in grouped)):
269
+ dup.append((_unique([p.a, p.b]), _num(p.strength), p.measure))
270
+ dcap = int(t["max_near_duplicates"])
271
+ for names, strength, raw in dup[:dcap]:
272
+ measure = _safe(fmt.measure_label(raw)) if raw else "strength"
273
+ if strength is not None:
274
+ strength = math.floor(strength * 100) / 100 # "at least": never rounded up
275
+ if len(names) == 2:
276
+ detail = f" ({measure} {strength:.2f})" if strength is not None else ""
277
+ else:
278
+ detail = (f" ({measure} of at least {strength:.2f} between any two)"
279
+ if strength is not None else "")
280
+ out.append(Alert("near_duplicate", "note", names,
281
+ f"{{cols}} move together almost exactly{detail}.",
282
+ "Check whether the table needs all of them, or whether one is "
283
+ "computed from another."))
284
+ if len(dup) > dcap:
285
+ more = len(dup) - dcap
286
+ out.append(Alert("near_duplicate", "note", [],
287
+ f"{fmt.plural(more, 'more group')} of columns "
288
+ f"{_is(more, 'moves', 'move')} together almost exactly."))
289
+
290
+ # -- notes --
291
+ pct_me = fmt.share(t["mostly_empty"])
292
+ out += _group(view, "mostly_empty", "note",
293
+ [c.name for c in cols
294
+ if t["mostly_empty"] <= (missing(c) or 0.0) < t["nearly_empty"]],
295
+ f"{{cols}} is empty in more than {pct_me} of rows.",
296
+ f"{{cols}} are empty in more than {pct_me} of rows.")
297
+ out += _group(view, "constant", "note", [c.name for c in cols if c.handling == "constant"],
298
+ "{cols} holds a single value.", "{cols} each hold a single value.")
299
+ out += _group(view, "key", "note",
300
+ [c.name for c in cols if c.handling in ("identifier", "reference")],
301
+ "{cols} is a key: its values are regenerated, never copied.",
302
+ "{cols} are keys: their values are regenerated, never copied.")
303
+
304
+ exc: list[tuple[str, float, str]] = []
305
+ s = view.structure
306
+ for comp in s.computed:
307
+ exc.append((comp.column, _num(comp.exceptions) or 0.0,
308
+ "{cols} does not follow the rule that computes it in"))
309
+ seen_sums: dict[str, int] = {}
310
+ for sr in s.sums:
311
+ seen_sums[sr.total or ""] = seen_sums.get(sr.total or "", 0) + 1
312
+ for o in s.orderings:
313
+ if not o.signed:
314
+ exc.append((o.target, _num(o.exceptions) or 0.0, "{cols} breaks its ordering in"))
315
+ for sr in s.sums:
316
+ name = sr.total or (sr.parts[0] if sr.parts else "")
317
+ which = ""
318
+ if seen_sums.get(sr.total or "", 0) > 1 and sr.parts: # say which of its sums
319
+ which = f" ({_safe(fmt.join(list(sr.parts), 2))})"
320
+ exc.append((name, _num(sr.exceptions) or 0.0,
321
+ f"{{cols}} does not equal the sum of its "
322
+ f"{fmt.plural(len(sr.parts or []), 'part')}{which} in"))
323
+ for g in s.entities:
324
+ for a in g.attributes:
325
+ key = f" for its {_safe(g.key)}" if g.key else ""
326
+ exc.append((a.column, _num(a.exceptions) or 0.0,
327
+ f"{{cols}} differs from the usual value{key} in"))
328
+ order = {n: i for i, n in enumerate(_sorted_by_index(view, [e[0] for e in exc]))}
329
+ for name, share, text in sorted((e for e in exc if e[1] > 0 and e[0]),
330
+ key=lambda e: order.get(e[0], 10**9)):
331
+ out.append(Alert("exceptions", "note", [name],
332
+ f"{text} {fmt.share(share)} of source rows; the fingerprint does "
333
+ "not keep these exceptions."))
334
+
335
+ def dominant(c: ColumnView) -> bool:
336
+ if c.levels is None:
337
+ return False
338
+ top = max((_num(b.share) or 0.0 for b in c.levels.bars or [] if b.kind == "level"),
339
+ default=0.0)
340
+ return top >= t["dominant_value"]
341
+
342
+ pct_dv = fmt.share(t["dominant_value"])
343
+ out += _group(view, "dominant_value", "note", [c.name for c in cols if dominant(c)],
344
+ f"One value holds {pct_dv} or more of the rows of {{cols}}.",
345
+ f"In each of {{cols}}, one value holds {pct_dv} or more of the rows.")
346
+
347
+ far = [(c, x) for c in cols for x in [_sentinel(c)] if x is not None]
348
+ advice = ("A value like this is often a placeholder for a missing value. If it is, treat "
349
+ "it as empty before analysing the column.")
350
+ if len(far) <= 3:
351
+ for c, (val, share) in far:
352
+ h = c.histogram
353
+ shown = fmt.axis_value(val, h.axis, h.unit) if h is not None else fmt.number(val)
354
+ out.append(Alert("sentinel", "note", [c.name],
355
+ f"{{cols}} is exactly {shown} in {fmt.share(share)} of rows, far "
356
+ "outside its other values.", advice))
357
+ else:
358
+ out += _group(view, "sentinel", "note", [c.name for c, _ in far], "",
359
+ "{cols} each hold one exact value far outside their other values; "
360
+ "each column's chart marks it.",
361
+ "Values like these are often placeholders for a missing value. If they "
362
+ "are, treat them as empty before analysing the columns.")
363
+
364
+ def zero_heavy(c: ColumnView) -> bool:
365
+ return c.histogram is not None and any(
366
+ _num(a.value) == 0 and (_num(a.share) or 0.0) >= t["zero_heavy"]
367
+ for a in c.histogram.atoms or [])
368
+
369
+ out += _group(view, "zero_heavy", "note", [c.name for c in cols if zero_heavy(c)],
370
+ "Half or more of the values of {cols} are exactly 0.",
371
+ "Half or more of the values of each of {cols} are exactly 0.")
372
+ out += _group(view, "skew", "note", [c.name for c in cols if _skewed(c)],
373
+ "{cols} has a long tail: a few values lie far from the rest.",
374
+ "{cols} have long tails: a few values lie far from the rest.",
375
+ "Read them by their median and quantiles rather than the mean.")
376
+ pct_ph = fmt.share(t["pooled_heavy"])
377
+ out += _group(view, "pooled_heavy", "note",
378
+ [c.name for c in cols if _pooled_share(view, c) >= t["pooled_heavy"]],
379
+ f"{pct_ph} or more of the rows of {{cols}} are in the pooled bucket of rare "
380
+ "values.",
381
+ f"{pct_ph} or more of the rows of each of {{cols}} are in the pooled bucket "
382
+ "of rare values.")
383
+ out += _group(view, "coarse", "note", view.privacy.coarse_columns,
384
+ "{cols} is stored as a mean and spread only.",
385
+ "{cols} are stored as a mean and spread only.")
386
+ out += _group(view, "low_confidence", "note",
387
+ [c.name for c in cols if not c.overridden and c.confidence is not None
388
+ and (_num(c.confidence) or 0.0) < t["low_confidence"]],
389
+ "The type or role of {cols} was inferred with low confidence.",
390
+ "The types or roles of {cols} were inferred with low confidence.",
391
+ "An override sets a type or role the engine guessed wrong.")
392
+ out += _group(view, "uncharted", "note",
393
+ [c.name for c in cols
394
+ if c.handling == "unknown" or c.handling not in HANDLINGS or c.chart_note],
395
+ "{cols} is not fully described by this version of the report.",
396
+ "{cols} are not fully described by this version of the report.",
397
+ "The column card says what is missing.")
398
+
399
+ rank = {k: i for i, k in enumerate(KINDS)}
400
+ sev = {"act": 0, "note": 1}
401
+ return sorted(out, key=lambda a: (sev.get(a.severity, 2), rank.get(a.kind, len(KINDS))))
402
+
403
+
404
+ def headline(alerts: Sequence[Alert], limit: int = 6) -> list[Alert]:
405
+ """The alerts for the top of the page: "act" first, then notes, at most ``limit``, and one
406
+ alert of every kind before a second of any kind, so one busy kind cannot fill the list."""
407
+ acts = [a for a in alerts if a.severity == "act"]
408
+ notes = [a for a in alerts if a.severity != "act"]
409
+ ordered = acts + notes
410
+ first: list[Alert] = [] # one alert of each kind before a second of any
411
+ seen: set[str] = set()
412
+ for a in ordered:
413
+ if a.kind not in seen:
414
+ seen.add(a.kind)
415
+ first.append(a)
416
+ rest = [a for a in ordered if not any(a is f for f in first)]
417
+ picked = (first + rest)[: max(0, int(limit))]
418
+ return [a for a in ordered if any(a is x for x in picked)]
419
+
420
+
421
+ def render_message(alert: Alert, limit: int = 3) -> str:
422
+ """The message as plain text, with the column names joined in place of ``{cols}``."""
423
+ if not alert.columns:
424
+ return alert.message
425
+ return alert.message.replace(PLACEHOLDER, fmt.join(alert.columns, limit), 1)
426
+
427
+
428
+ # -- overview ---------------------------------------------------------------------------------
429
+
430
+ _TYPE_WORDS = {
431
+ "discrete": ("whole number", "whole numbers"),
432
+ "continuous": ("decimal number", "decimal numbers"),
433
+ "categorical": ("category", "categories"),
434
+ "boolean": ("yes/no flag", "yes/no flags"),
435
+ "date": ("date", "dates"),
436
+ "datetime": ("timestamp", "timestamps"),
437
+ "string": ("structured text column", "structured text columns"),
438
+ "text": ("free text column", "free text columns"),
439
+ }
440
+
441
+
442
+ def _and(items: Sequence[str]) -> str:
443
+ if len(items) <= 1:
444
+ return "".join(items)
445
+ if len(items) == 2:
446
+ return f"{items[0]} and {items[1]}"
447
+ return ", ".join(items[:-1]) + f" and {items[-1]}"
448
+
449
+
450
+ def _count(n: int, one: str, many: str) -> str:
451
+ return f"{fmt.count(n)} {one if n == 1 else many}"
452
+
453
+
454
+ def overview(view: ReportView) -> list[str]:
455
+ """The "what was found" paragraph: two to five short sentences built from the view."""
456
+ cols = list(view.columns)
457
+ n_cols = view.overview.columns if view.overview.columns else len(cols)
458
+ rows = view.overview.rows
459
+ if not cols and not n_cols:
460
+ return ["This fingerprint describes no columns."]
461
+
462
+ # 1. size and types
463
+ counts: dict[str, int] = {}
464
+ for c in cols:
465
+ key = "date" if c.logical_type == "datetime" and c.is_date else (c.logical_type or "")
466
+ counts[key] = counts.get(key, 0) + 1
467
+ order = list(_TYPE_WORDS)
468
+ kinds = sorted(counts, key=lambda k: (-counts[k], order.index(k) if k in order else 99, k))
469
+ bits = []
470
+ for k in kinds:
471
+ n = counts[k]
472
+ if k in _TYPE_WORDS:
473
+ bits.append(_count(n, *_TYPE_WORDS[k]))
474
+ elif k:
475
+ bits.append(f"{_count(n, 'column', 'columns')} of type {k}")
476
+ else:
477
+ bits.append(f"{_count(n, 'column', 'columns')} of unrecorded type")
478
+ size = (f"A table of {_count(rows, 'row', 'rows')} and {_count(n_cols, 'column', 'columns')}"
479
+ if rows is not None else f"A table of {_count(n_cols, 'column', 'columns')}")
480
+ first = size + (": " + fmt.join(bits, limit=len(bits)) if bits else "") + "."
481
+ out = [first]
482
+
483
+ # 2. structure
484
+ s = view.structure
485
+ found = []
486
+ if s.sums:
487
+ found.append(_count(len(s.sums), "total that adds up from its parts",
488
+ "totals that add up from their parts"))
489
+ if s.entities:
490
+ found.append(_count(len(s.entities), "entity whose attributes follow its key",
491
+ "entities whose attributes follow their keys"))
492
+ if s.computed:
493
+ found.append(_count(len(s.computed), "column computed from another",
494
+ "columns computed from others"))
495
+ if s.orderings:
496
+ found.append(_count(len(s.orderings), "pair of columns kept in order",
497
+ "pairs of columns kept in order"))
498
+ if s.weekly:
499
+ found.append(_count(len(s.weekly), "date column with a weekly pattern",
500
+ "date columns with a weekly pattern"))
501
+ if s.confirmed:
502
+ found.append(_count(len(s.confirmed), "confirmed rule", "confirmed rules"))
503
+ if found:
504
+ out.append(f"The engine found {_and(found)}.")
505
+
506
+ # 3. privacy handling
507
+ stand_ins = len(_unique([c.name for c in cols if c.handling == "pseudonym"]
508
+ + [p.column for p in view.privacy.personal
509
+ if p.handling == "pseudonym"]))
510
+ left = [c for c in cols if c.handling == "excluded"]
511
+ keys = [c for c in cols if c.handling in ("identifier", "reference")]
512
+ priv = []
513
+ if stand_ins:
514
+ priv.append("shows " + _count(stand_ins, "personal-looking column",
515
+ "personal-looking columns") + " as stand-in tokens")
516
+ if keys:
517
+ priv.append("regenerates " + _count(len(keys), "key column", "key columns"))
518
+ if left:
519
+ texty = all(c.logical_type in ("text", "string") for c in left)
520
+ noun = ("text column", "text columns") if texty else ("column", "columns")
521
+ priv.append(f"leaves {_count(len(left), *noun)} out of the model")
522
+ if priv:
523
+ out.append(f"The fingerprint {_and(priv)}.")
524
+
525
+ # 4. empty cells
526
+ miss = [m for m in (_num(c.missing) for c in cols) if m is not None]
527
+ if miss:
528
+ mean = sum(miss) / len(miss)
529
+ half = sum(1 for m in miss if m > 0.5)
530
+ if mean > 0:
531
+ if mean < 0.001:
532
+ text = "Fewer than 0.1% of all cells are empty"
533
+ else:
534
+ text = f"About {fmt.share(mean)} of all cells are empty"
535
+ if half:
536
+ text += f"; {_count(half, 'column is', 'columns are')} more than half empty"
537
+ out.append(text + ".")
538
+
539
+ # 5. strongest relationship
540
+ pairs = [p for p in view.relationships.pairs if _num(p.strength) is not None]
541
+ groups = sorted((g for g in view.relationships.groups or [] if len(g.columns or []) >= 3),
542
+ key=lambda g: -len(g.columns))
543
+ if groups:
544
+ big = groups[0]
545
+ out.append(f"A group of {fmt.count(len(big.columns))} columns moves together almost "
546
+ f"exactly ({fmt.join(list(big.columns), 2)}).")
547
+ elif pairs:
548
+ p = max(pairs, key=lambda x: _num(x.strength) or 0.0)
549
+ measure = fmt.measure_label(p.measure) if p.measure else "strength"
550
+ out.append(f"The strongest relationship is between {p.a} and {p.b} "
551
+ f"({measure} {(_num(p.strength) or 0.0):.2f}).")
552
+ return [s_[0].upper() + s_[1:] if s_ and s_[0].islower() else s_ for s_ in out[:5]]
553
+
554
+
555
+ # -- terminal summary -------------------------------------------------------------------------
556
+
557
+
558
+ #: handlings whose label is a noun phrase: how they read after a count (one, several)
559
+ _COUNTED_HANDLINGS = {
560
+ "share": ("share of a total", "shares of a total"),
561
+ "total": ("sum of its parts", "sums of their parts"),
562
+ "identifier": ("regenerated key", "regenerated keys"),
563
+ "reference": ("repeating key", "repeating keys"),
564
+ "pseudonym": ("with stand-in tokens", "with stand-in tokens"),
565
+ }
566
+
567
+
568
+ def _counted_handling(handling: str, n: int) -> str:
569
+ """A handling's label as it reads after a count: "1 regenerated key", "2 regenerated keys"."""
570
+ one, several = _COUNTED_HANDLINGS.get(handling, (fmt.handling_label(handling),) * 2)
571
+ return one if n == 1 else several
572
+
573
+
574
+ def summary(view: ReportView, alerts: Sequence[Alert]) -> str:
575
+ """The short terminal summary: four to eight plain lines (no colour codes, no path)."""
576
+ o = view.overview
577
+ name = o.name or "Unnamed fingerprint"
578
+ n_cols = o.columns if o.columns else len(view.columns)
579
+ rows = fmt.count(o.rows) if o.rows is not None else "unknown"
580
+ lines = [f"{name}: {rows} rows x {fmt.count(n_cols)} columns"]
581
+ policy = o.policy or view.privacy.policy
582
+ lines.append(f"Policy {policy or fmt.NOT_RECORDED}, format {o.format_version or fmt.NOT_RECORDED}")
583
+
584
+ by: dict[str, int] = {}
585
+ for c in view.columns:
586
+ by[c.handling] = by.get(c.handling, 0) + 1
587
+ order = list(HANDLINGS)
588
+ parts = [f"{n} {_counted_handling(h, n)}"
589
+ for h, n in sorted(by.items(), key=lambda kv: (order.index(kv[0])
590
+ if kv[0] in order else 99, kv[0]))]
591
+ lines.append("Columns: " + (", ".join(parts) if parts else "none"))
592
+
593
+ s = view.structure
594
+ st = [x for x in (
595
+ _count(len(s.sums), "sum", "sums") if s.sums else "",
596
+ _count(len(s.entities), "entity group", "entity groups") if s.entities else "",
597
+ _count(len(s.computed), "computed column", "computed columns") if s.computed else "",
598
+ _count(len(s.orderings), "ordering", "orderings") if s.orderings else "",
599
+ _count(len(s.confirmed), "confirmed rule", "confirmed rules") if s.confirmed else "",
600
+ ) if x]
601
+ if st:
602
+ lines.append("Structure: " + ", ".join(st))
603
+
604
+ acts = [a for a in alerts if a.severity == "act"]
605
+ notes = [a for a in alerts if a.severity != "act"]
606
+ if acts or notes:
607
+ lines.append(f"Alerts: {fmt.count(len(acts))} worth acting on, "
608
+ f"{_count(len(notes), 'note', 'notes')}")
609
+ else:
610
+ lines.append("Alerts: none")
611
+ unread = view.all_unread()
612
+ tail = []
613
+ if unread:
614
+ tail.append(f"Not described: {_count(len(unread), 'item', 'items')} this version of "
615
+ "the report does not read")
616
+ room = max(0, min(3, 8 - len(lines) - len(tail))) # at most eight lines in all
617
+ lines += [f" - {render_message(a)}" for a in acts[:room]]
618
+ return "\n".join(lines + tail)
619
+
620
+
621
+ __all__ = ["ACT_KINDS", "KINDS", "NOTE_KINDS", "THRESHOLDS", "Alert", "alerts", "headline",
622
+ "overview", "render_message", "summary"]