ectype-data 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,1705 @@
|
|
|
1
|
+
"""The profile report page: one self-contained HTML document from a :class:`ReportView`.
|
|
2
|
+
|
|
3
|
+
ADR-0016. Imports only the standard library and ``ectype.reporting.{view, fmt, charts,
|
|
4
|
+
findings, style}``. Rules this module keeps:
|
|
5
|
+
|
|
6
|
+
* Every string of the view is untrusted and goes through :func:`_e` (``html.escape`` after
|
|
7
|
+
dropping characters HTML cannot carry). Ids and links are built from integers and fixed
|
|
8
|
+
words only (``col-12``, ``columns``).
|
|
9
|
+
* Every optional field may be ``None`` and every list may be empty; each section and each
|
|
10
|
+
column card is drawn inside its own guard, so a surprise in one cannot take the page down.
|
|
11
|
+
* Unknown vocabulary (a role, kind, measure or mode this module has no words for) is printed
|
|
12
|
+
as stored, inside a neutral sentence.
|
|
13
|
+
* Strings are built with lists and ``"".join``; no regular expression runs per column, so a
|
|
14
|
+
table of thousands of columns renders in well under a second in ``list`` detail.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import html
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Callable, Sequence
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
from functools import partial
|
|
25
|
+
|
|
26
|
+
from ectype.reporting import charts, findings, fmt
|
|
27
|
+
from ectype.reporting.findings import Alert
|
|
28
|
+
from ectype.reporting.style import CSS, SCRIPT
|
|
29
|
+
from ectype.reporting.view import (
|
|
30
|
+
HANDLINGS,
|
|
31
|
+
ColumnGroup,
|
|
32
|
+
ColumnView,
|
|
33
|
+
Computed,
|
|
34
|
+
Constraint,
|
|
35
|
+
Fact,
|
|
36
|
+
Histogram,
|
|
37
|
+
Levels,
|
|
38
|
+
Ordering,
|
|
39
|
+
Pair,
|
|
40
|
+
ReportView,
|
|
41
|
+
SumRule,
|
|
42
|
+
Unread,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
#: levels of detail for the columns section, most detailed first
|
|
46
|
+
DETAILS = ("full", "compact", "list")
|
|
47
|
+
|
|
48
|
+
#: section ids in page order, with their rail labels
|
|
49
|
+
SECTIONS = (
|
|
50
|
+
("overview", "Overview"),
|
|
51
|
+
("columns", "Columns"),
|
|
52
|
+
("relationships", "Relationships"),
|
|
53
|
+
("structure", "Structure"),
|
|
54
|
+
("privacy", "Privacy"),
|
|
55
|
+
("alerts", "Alerts"),
|
|
56
|
+
("reading", "How to read this page"),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
#: pairs listed before the rest are folded into a ``<details>``
|
|
60
|
+
CARD_ALERTS = 2 # alert lines on one column card
|
|
61
|
+
MANY_VALUES = 50 # a category of this many values is tagged in a pair
|
|
62
|
+
#: alert kinds a card does not repeat: the card says the same in its own words
|
|
63
|
+
CARD_SILENT = frozenset({"constant", "left_out", "key", "personal"})
|
|
64
|
+
GROUP_VISIBLE = 8 # columns of a group named before the rest is folded
|
|
65
|
+
PAIRS_VISIBLE = 12
|
|
66
|
+
#: formulas longer than this are folded into a ``<details>``
|
|
67
|
+
FORMULA_FOLD = 160
|
|
68
|
+
#: pooled columns listed in the privacy table
|
|
69
|
+
POOLED_ROWS = 30
|
|
70
|
+
|
|
71
|
+
LIMITS_SENTENCE = (
|
|
72
|
+
"These measures limit what the fingerprint stores about any one row. They are not a formal "
|
|
73
|
+
"privacy guarantee: a table with few rows or many columns can still describe an unusual "
|
|
74
|
+
"record closely."
|
|
75
|
+
)
|
|
76
|
+
FOOTER = "Made by Ectype from a fingerprint. No row of the source table was read to make this page."
|
|
77
|
+
|
|
78
|
+
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
79
|
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
|
80
|
+
|
|
81
|
+
# control characters and lone surrogates: dropped from every string before escaping
|
|
82
|
+
_CLEAN: dict[int, None] = {
|
|
83
|
+
**{c: None for c in range(0x20) if c not in (0x09, 0x0A, 0x0D)},
|
|
84
|
+
0x7F: None,
|
|
85
|
+
**{c: None for c in range(0xD800, 0xE000)},
|
|
86
|
+
0xFFFE: None,
|
|
87
|
+
0xFFFF: None,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
_OFF = frozenset(("identifier", "constant", "excluded", "unknown"))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _e(s: object) -> str:
|
|
94
|
+
"""Untrusted text, escaped for HTML content and attribute values."""
|
|
95
|
+
if s is None:
|
|
96
|
+
return ""
|
|
97
|
+
t = s if isinstance(s, str) else str(s)
|
|
98
|
+
return html.escape(t.translate(_CLEAN), quote=True)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
_TICKED = re.compile(r"`([^`<>]{1,120})`")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _notice(s: object) -> str:
|
|
105
|
+
"""A notice sentence, escaped, with backtick-quoted spans drawn as code (the same
|
|
106
|
+
sentences are printed in the terminal, where the backticks stay)."""
|
|
107
|
+
return _TICKED.sub(lambda m: "<code>" + m.group(1) + "</code>", _e(s))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _f(x: object) -> float | None:
|
|
111
|
+
"""``x`` as a finite float, or ``None``."""
|
|
112
|
+
if x is None or isinstance(x, bool):
|
|
113
|
+
return None
|
|
114
|
+
try:
|
|
115
|
+
v = float(x) # type: ignore[arg-type]
|
|
116
|
+
except (TypeError, ValueError, OverflowError):
|
|
117
|
+
return None
|
|
118
|
+
return v if math.isfinite(v) else None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _share01(x: object) -> float:
|
|
122
|
+
v = _f(x)
|
|
123
|
+
return 0.0 if v is None else min(max(v, 0.0), 1.0)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _pct_width(x: object) -> str:
|
|
127
|
+
return f"{100 * _share01(x):.1f}".rstrip("0").rstrip(".") + "%"
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _sentence(text: str) -> str:
|
|
131
|
+
return text[:1].upper() + text[1:] if text else text
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _full_sentence(text: str) -> str:
|
|
135
|
+
"""The engine's own note as a sentence: first letter capital, one full stop."""
|
|
136
|
+
s = " ".join(str(text).split())
|
|
137
|
+
if not s:
|
|
138
|
+
return ""
|
|
139
|
+
s = s[0].upper() + s[1:]
|
|
140
|
+
return s if s[-1] in ".!?" else s + "."
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _known(label: str, raw: str | None) -> bool:
|
|
144
|
+
"""Whether a ``fmt`` label function had words for ``raw`` (it returns unknowns as-is)."""
|
|
145
|
+
return bool(raw) and label != raw
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _ordinal(p: float) -> str:
|
|
149
|
+
"""A percentile number with its suffix: 1st, 2nd, 3rd, 0.5th, 99.5th."""
|
|
150
|
+
text = fmt.number(p)
|
|
151
|
+
if p.is_integer():
|
|
152
|
+
n = int(p)
|
|
153
|
+
if n % 100 not in (11, 12, 13) and n % 10 in (1, 2, 3):
|
|
154
|
+
return text + ("st", "nd", "rd")[n % 10 - 1]
|
|
155
|
+
return text + "th"
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _fitted(created: str) -> str:
|
|
159
|
+
try:
|
|
160
|
+
d = datetime.fromisoformat(created.strip().replace("Z", "+00:00"))
|
|
161
|
+
except (ValueError, AttributeError):
|
|
162
|
+
return created
|
|
163
|
+
return f"{d.day} {_MONTHS[d.month - 1]} {d.year}"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _fact_value(f: Fact) -> str:
|
|
167
|
+
"""A :class:`Fact`'s value as plain text (not escaped)."""
|
|
168
|
+
if f.text:
|
|
169
|
+
return f.text
|
|
170
|
+
v = _f(f.number)
|
|
171
|
+
if v is None:
|
|
172
|
+
return ""
|
|
173
|
+
unit = f.unit or ""
|
|
174
|
+
if unit == "share":
|
|
175
|
+
return fmt.share(v)
|
|
176
|
+
if unit.startswith("date:"):
|
|
177
|
+
return fmt.date(v, unit[5:])
|
|
178
|
+
if unit.startswith("duration:"):
|
|
179
|
+
return fmt.duration(v, unit[9:])
|
|
180
|
+
if unit in ("rows", "columns", "keys", "entries", "values"):
|
|
181
|
+
return f"{fmt.count(v)} {unit}"
|
|
182
|
+
return f"{fmt.number(v)} {unit}" if unit else fmt.number(v)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _quantile(h: Histogram, p: float) -> float | None:
|
|
186
|
+
for q in h.quantiles or []:
|
|
187
|
+
try:
|
|
188
|
+
qp, qv = _f(q[0]), _f(q[1])
|
|
189
|
+
except (IndexError, TypeError, KeyError):
|
|
190
|
+
continue
|
|
191
|
+
if qp is not None and qv is not None and abs(qp - p) < 1e-6:
|
|
192
|
+
return qv
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _axis_formatter(h: Histogram) -> Callable[[float | None], str]:
|
|
197
|
+
vals = [v for v in (_f(x) for x in [*(h.edges or []), h.low, h.high]) if v is not None]
|
|
198
|
+
for q in h.quantiles or []:
|
|
199
|
+
try:
|
|
200
|
+
v = _f(q[1])
|
|
201
|
+
except (IndexError, TypeError, KeyError):
|
|
202
|
+
v = None
|
|
203
|
+
if v is not None:
|
|
204
|
+
vals.append(v)
|
|
205
|
+
span = (max(vals) - min(vals)) if vals else None
|
|
206
|
+
axis, unit = h.axis or "number", h.unit or ""
|
|
207
|
+
return lambda v: fmt.axis_value(v, axis, unit, span=span)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# -- the page context ------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class _Page:
|
|
214
|
+
"""What every part of the page needs: the view, the alerts, column anchors, chart ids."""
|
|
215
|
+
|
|
216
|
+
def __init__(self, view: ReportView, alerts: list[Alert], detail: str) -> None:
|
|
217
|
+
self.view = view
|
|
218
|
+
self.alerts = alerts
|
|
219
|
+
self.detail = detail
|
|
220
|
+
cols = list(view.columns)
|
|
221
|
+
idx = [c.index for c in cols]
|
|
222
|
+
good = all(isinstance(i, int) and not isinstance(i, bool) and i >= 0 for i in idx)
|
|
223
|
+
if not good or len(set(idx)) != len(idx):
|
|
224
|
+
idx = list(range(len(cols)))
|
|
225
|
+
self.anchors: list[str] = [f"col-{int(i)}" for i in idx]
|
|
226
|
+
self.positions: list[int] = [int(i) for i in idx]
|
|
227
|
+
self.by_name: dict[str, int] = {}
|
|
228
|
+
for k, c in enumerate(cols):
|
|
229
|
+
if isinstance(c.name, str):
|
|
230
|
+
self.by_name.setdefault(c.name, k)
|
|
231
|
+
self.named: dict[str, list[Alert]] = {}
|
|
232
|
+
self.act: set[str] = set()
|
|
233
|
+
for a in alerts:
|
|
234
|
+
for n in a.columns or []:
|
|
235
|
+
if not isinstance(n, str):
|
|
236
|
+
continue
|
|
237
|
+
lst = self.named.setdefault(n, [])
|
|
238
|
+
if not lst or lst[-1] is not a:
|
|
239
|
+
lst.append(a)
|
|
240
|
+
if a.severity == "act":
|
|
241
|
+
self.act.add(n)
|
|
242
|
+
self._uid = 0
|
|
243
|
+
|
|
244
|
+
def uid(self, prefix: str = "ch") -> str:
|
|
245
|
+
self._uid += 1
|
|
246
|
+
return f"{prefix}{self._uid}"
|
|
247
|
+
|
|
248
|
+
def href(self, name: str) -> str | None:
|
|
249
|
+
k = self.by_name.get(name) if isinstance(name, str) else None
|
|
250
|
+
return None if k is None else "#" + self.anchors[k]
|
|
251
|
+
|
|
252
|
+
def link(self, name: object) -> str:
|
|
253
|
+
"""A column name, linked to its card (or list row) when the page has one."""
|
|
254
|
+
text = _e(name) if name not in (None, "") else "(unnamed column)"
|
|
255
|
+
h = self.href(name) if isinstance(name, str) else None
|
|
256
|
+
return f'<a href="{h}">{text}</a>' if h else text
|
|
257
|
+
|
|
258
|
+
def links(self, names: Sequence[str], limit: int = 3) -> str:
|
|
259
|
+
return fmt.join([self.link(n) for n in names or []], limit)
|
|
260
|
+
|
|
261
|
+
def column(self, name: object) -> ColumnView | None:
|
|
262
|
+
k = self.by_name.get(name) if isinstance(name, str) else None
|
|
263
|
+
return None if k is None else self.view.columns[k]
|
|
264
|
+
|
|
265
|
+
def message(self, a: Alert, limit: int = 3, linked: bool = True) -> str:
|
|
266
|
+
"""An alert's message as HTML, with the column names put in place of ``{cols}``."""
|
|
267
|
+
msg = _e(a.message)
|
|
268
|
+
if a.columns:
|
|
269
|
+
names = (self.links(a.columns, limit) if linked
|
|
270
|
+
else fmt.join([_e(n) for n in a.columns], limit))
|
|
271
|
+
msg = msg.replace(findings.PLACEHOLDER, names, 1)
|
|
272
|
+
return msg
|
|
273
|
+
|
|
274
|
+
def advice(self, a: Alert, limit: int = 3) -> str:
|
|
275
|
+
text = _e(a.advice or "")
|
|
276
|
+
if a.columns and findings.PLACEHOLDER in text:
|
|
277
|
+
text = text.replace(findings.PLACEHOLDER, self.links(a.columns, limit), 1)
|
|
278
|
+
return text
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _guard(build: Callable[[], str], what: str) -> str:
|
|
282
|
+
"""Run one part of the page; a failure becomes a sentence instead of a broken page."""
|
|
283
|
+
try:
|
|
284
|
+
return build()
|
|
285
|
+
except Exception as exc: # noqa: BLE001 - the page must render whatever the view holds
|
|
286
|
+
return (f'<p class="notice serious">This {what} could not be drawn: '
|
|
287
|
+
f"{_e(fmt.truncate(f'{type(exc).__name__}: {exc}', 300))}</p>")
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _level(a: Alert) -> str:
|
|
291
|
+
if a.severity == "act":
|
|
292
|
+
return '<span class="lvl serious">Act</span>'
|
|
293
|
+
return '<span class="lvl">Note</span>'
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _section(sid: str, title: str, body: str) -> str:
|
|
297
|
+
return (f'<section id="{sid}" aria-labelledby="{sid}-h"><h2 id="{sid}-h">{title}</h2>'
|
|
298
|
+
f"{body}</section>")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _table(caption: str, head: Sequence[str], rows: list[str], label: str,
|
|
302
|
+
cls: str = "", num_cols: Sequence[int] = (), hide_caption: bool = True) -> str:
|
|
303
|
+
"""A table inside a keyboard-scrollable wrapper. ``rows`` are complete ``<tr>`` strings;
|
|
304
|
+
``caption`` and ``head`` are fixed words (not escaped here)."""
|
|
305
|
+
num = ' class="num"'
|
|
306
|
+
ths = "".join(f'<th scope="col"{num if i in num_cols else ""}>{h}</th>'
|
|
307
|
+
for i, h in enumerate(head))
|
|
308
|
+
vh = ' class="vh"' if hide_caption else ""
|
|
309
|
+
cap = f"<caption{vh}>{caption}</caption>"
|
|
310
|
+
klass = f' class="{cls}"' if cls else ""
|
|
311
|
+
return (f'<div class="scroll" tabindex="0" role="region" aria-label="{label}">'
|
|
312
|
+
f"<table{klass}>{cap}<thead><tr>{ths}</tr></thead><tbody>{''.join(rows)}</tbody>"
|
|
313
|
+
f"</table></div>")
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _formula(text: str, cls: str = "") -> str:
|
|
317
|
+
"""A formula in ``<code>``; a long one folded into ``<details>``."""
|
|
318
|
+
t = text or ""
|
|
319
|
+
if len(t) > FORMULA_FOLD:
|
|
320
|
+
return (f'<details class="more{" " + cls if cls else ""}"><summary><code>'
|
|
321
|
+
f"{_e(fmt.truncate(t, 120))}</code></summary><code>{_e(t)}</code></details>")
|
|
322
|
+
return f"<code>{_e(t)}</code>"
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
# -- overview ---------------------------------------------------------------------------------
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _overview(p: _Page, heading: str, notices: Sequence[str]) -> str:
|
|
329
|
+
v = p.view
|
|
330
|
+
o = v.overview
|
|
331
|
+
out = [f'<section id="overview" aria-labelledby="overview-h"><h1 id="overview-h">'
|
|
332
|
+
f"{_e(heading)}</h1>"]
|
|
333
|
+
if o.description:
|
|
334
|
+
out.append(f'<p class="desc">{_e(o.description)}</p>')
|
|
335
|
+
try:
|
|
336
|
+
lede = " ".join(findings.overview(v))
|
|
337
|
+
except Exception: # noqa: BLE001
|
|
338
|
+
lede = ""
|
|
339
|
+
if lede:
|
|
340
|
+
out.append(f'<p class="lede">{_e(lede)}</p>')
|
|
341
|
+
out.append('<p class="small intro">This page is drawn from the fingerprint of the table: a '
|
|
342
|
+
"statistical summary fitted by Ectype (the engine) that holds no rows. "
|
|
343
|
+
'<a href="#reading">How to read this page</a> explains the words and the '
|
|
344
|
+
"marks.</p>")
|
|
345
|
+
for n in notices or ():
|
|
346
|
+
out.append(f'<p class="notice">{_notice(n)}</p>')
|
|
347
|
+
if o.lineage:
|
|
348
|
+
steps = fmt.join([str(x) for x in o.lineage], 4)
|
|
349
|
+
out.append(f'<p class="notice">This fingerprint was not fitted to a table as it '
|
|
350
|
+
f"stands: it was made from another fingerprint ({_e(steps)}). The page "
|
|
351
|
+
"describes the result.</p>")
|
|
352
|
+
if o.older_format:
|
|
353
|
+
x = o.format_version or "an older version"
|
|
354
|
+
y = o.reader_format or "a newer one"
|
|
355
|
+
out.append(f'<p class="notice">Written by format {_e(x)}, read by format {_e(y)}: '
|
|
356
|
+
"sections added since are empty.</p>")
|
|
357
|
+
if o.newer_format:
|
|
358
|
+
x = o.format_version or "not recorded"
|
|
359
|
+
y = o.reader_format or "not recorded"
|
|
360
|
+
out.append(f'<p class="notice serious">Written by a newer format ({_e(x)}) than this '
|
|
361
|
+
f"engine reads ({_e(y)}): fields it does not know were ignored and are "
|
|
362
|
+
'listed at the end, under <a href="#reading">How to read this page</a>.</p>')
|
|
363
|
+
|
|
364
|
+
facts: list[tuple[str, str, str]] = []
|
|
365
|
+
if o.rows is not None and _f(o.rows) is not None:
|
|
366
|
+
facts.append(("Rows", fmt.count(o.rows), ""))
|
|
367
|
+
n_cols = o.columns if o.columns is not None else (len(v.columns) or None)
|
|
368
|
+
if n_cols is not None and _f(n_cols) is not None:
|
|
369
|
+
facts.append(("Columns", fmt.count(n_cols), ""))
|
|
370
|
+
policy = o.policy or v.privacy.policy
|
|
371
|
+
if policy or v.privacy.sensitive:
|
|
372
|
+
text = policy or "not recorded"
|
|
373
|
+
if v.privacy.sensitive:
|
|
374
|
+
text += ", sensitive"
|
|
375
|
+
facts.append(("Policy", text, ""))
|
|
376
|
+
if o.format_version:
|
|
377
|
+
facts.append(("Format", o.format_version, ""))
|
|
378
|
+
if o.engine_version:
|
|
379
|
+
facts.append(("Engine", o.engine_version, ""))
|
|
380
|
+
if o.created:
|
|
381
|
+
facts.append(("Fitted", _fitted(o.created), ""))
|
|
382
|
+
if o.content_id:
|
|
383
|
+
facts.append(("Fingerprint", o.content_id, "mono"))
|
|
384
|
+
if facts:
|
|
385
|
+
out.append('<dl class="facts">')
|
|
386
|
+
for label, value, cls in facts:
|
|
387
|
+
c = f' class="{cls}"' if cls else ""
|
|
388
|
+
out.append(f"<div><dt>{label}</dt><dd{c}>{_e(value)}</dd></div>")
|
|
389
|
+
out.append("</dl>")
|
|
390
|
+
|
|
391
|
+
if v.columns:
|
|
392
|
+
out.append(_guard(lambda: _strip(p), "column strip"))
|
|
393
|
+
|
|
394
|
+
top = findings.headline(p.alerts)
|
|
395
|
+
only_acts = bool(top) and all(a.severity == "act" for a in top)
|
|
396
|
+
out.append(f'<h2 class="minor">{"Worth acting on" if only_acts else "Worth knowing first"}'
|
|
397
|
+
"</h2>")
|
|
398
|
+
if top:
|
|
399
|
+
out.append('<ul class="act">')
|
|
400
|
+
for a in top:
|
|
401
|
+
cls = ' class="serious"' if a.severity == "act" else ""
|
|
402
|
+
adv = p.advice(a)
|
|
403
|
+
adv_html = f' <span class="advice">{adv}</span>' if adv else ""
|
|
404
|
+
out.append(f"<li{cls}>{_level(a)} {p.message(a)}{adv_html}</li>")
|
|
405
|
+
out.append("</ul>")
|
|
406
|
+
if len(p.alerts) > len(top):
|
|
407
|
+
out.append(f'<p><a href="#alerts">All {fmt.count(len(p.alerts))} alerts</a></p>')
|
|
408
|
+
else:
|
|
409
|
+
out.append("<p>Nothing stands out.</p>")
|
|
410
|
+
out.append("</section>")
|
|
411
|
+
return "".join(out)
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _strip(p: _Page) -> str:
|
|
415
|
+
cells = []
|
|
416
|
+
for k, c in enumerate(p.view.columns):
|
|
417
|
+
m = _f(c.missing)
|
|
418
|
+
present = None if m is None else 1 - min(max(m, 0.0), 1.0)
|
|
419
|
+
off = c.handling in _OFF or c.handling not in HANDLINGS
|
|
420
|
+
cells.append(charts.StripCell(
|
|
421
|
+
name=c.name if isinstance(c.name, str) else str(c.name), present=present,
|
|
422
|
+
state="off" if off else "on", href="#" + p.anchors[k],
|
|
423
|
+
flagged=c.name in p.act))
|
|
424
|
+
svg = charts.strip(cells, uid="strip", title="Every column, in table order")
|
|
425
|
+
return ('<figure class="stripfig"><figcaption>Every column, in table order. The filled '
|
|
426
|
+
"height is the share of rows that hold a value; grey columns are not modeled; a dot "
|
|
427
|
+
"marks a column with an alert worth acting on. Select one to jump to it."
|
|
428
|
+
f"</figcaption>{svg}</figure>")
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
# -- columns ----------------------------------------------------------------------------------
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _type_text(c: ColumnView) -> str:
|
|
435
|
+
if not c.logical_type:
|
|
436
|
+
return "type not recorded"
|
|
437
|
+
return fmt.type_label(c.logical_type, c.is_date)
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _how_text(c: ColumnView) -> str:
|
|
441
|
+
if c.handling == "modeled":
|
|
442
|
+
if not c.model_kind:
|
|
443
|
+
return "modeled"
|
|
444
|
+
return fmt.model_label(c.model_kind, c.slab_kind)
|
|
445
|
+
if not c.handling:
|
|
446
|
+
return "not recorded"
|
|
447
|
+
return fmt.handling_label(c.handling)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _offset_words(c: ColumnView, name: str) -> str:
|
|
451
|
+
sign = c.gap_sign
|
|
452
|
+
if sign == 1:
|
|
453
|
+
return f"{name} plus a modeled gap"
|
|
454
|
+
if sign == -1:
|
|
455
|
+
return f"{name} minus a modeled gap"
|
|
456
|
+
return f"{name} and a modeled gap"
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _nochart_html(p: _Page, c: ColumnView) -> str:
|
|
460
|
+
"""The sentence a card shows in place of a chart (HTML)."""
|
|
461
|
+
h = c.handling
|
|
462
|
+
first = c.inputs[0] if c.inputs else None
|
|
463
|
+
if h == "constant":
|
|
464
|
+
if c.constant is None:
|
|
465
|
+
return "Always the same value; the value is not recorded."
|
|
466
|
+
return f"Always <b>{_e(c.constant)}</b>."
|
|
467
|
+
if h == "excluded":
|
|
468
|
+
return "Left out of the model: the fingerprint holds no values of this column."
|
|
469
|
+
if h == "identifier":
|
|
470
|
+
return "A unique key. Its values are regenerated; none is stored."
|
|
471
|
+
if h == "computed":
|
|
472
|
+
if c.formula:
|
|
473
|
+
return "Computed: " + _formula(c.formula)
|
|
474
|
+
if c.inputs:
|
|
475
|
+
return f"Computed from {p.links(c.inputs, 4)}."
|
|
476
|
+
return "Computed from other columns."
|
|
477
|
+
if h == "offset":
|
|
478
|
+
base = p.link(first) if first else "another column"
|
|
479
|
+
return f"Computed as {_offset_words(c, base)}."
|
|
480
|
+
if h == "share":
|
|
481
|
+
total = p.link(first) if first else "a total"
|
|
482
|
+
return f"A modeled share of {total}."
|
|
483
|
+
if h == "total":
|
|
484
|
+
if c.inputs:
|
|
485
|
+
return f"The sum of its parts: {p.links(c.inputs, 4)}."
|
|
486
|
+
if c.formula:
|
|
487
|
+
return "The sum of its parts: " + _formula(c.formula)
|
|
488
|
+
return "The sum of its parts."
|
|
489
|
+
if h == "reference":
|
|
490
|
+
return ("A repeating key: how many rows share a key is modeled, and key values are "
|
|
491
|
+
"issued fresh.")
|
|
492
|
+
if h == "pseudonym":
|
|
493
|
+
return "Values replaced by stand-in tokens; the fingerprint holds no chart of them."
|
|
494
|
+
if h == "modeled":
|
|
495
|
+
return "The fingerprint holds no distribution this page can draw for this column."
|
|
496
|
+
if h in HANDLINGS or not h:
|
|
497
|
+
return "This version of the report does not know how this column is produced."
|
|
498
|
+
return ("This version of the report does not know how this column is produced (the "
|
|
499
|
+
f"fingerprint calls it {_e(h)}).")
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _nochart_text(c: ColumnView) -> str:
|
|
503
|
+
"""The same sentence as plain text, for the list detail (not escaped)."""
|
|
504
|
+
h = c.handling
|
|
505
|
+
first = c.inputs[0] if c.inputs else ""
|
|
506
|
+
if h == "constant":
|
|
507
|
+
return f"Always {c.constant}." if c.constant is not None else "Always the same value."
|
|
508
|
+
if h == "excluded":
|
|
509
|
+
return "Left out of the model."
|
|
510
|
+
if h == "identifier":
|
|
511
|
+
return "A unique key, regenerated; none of its values is stored."
|
|
512
|
+
if h == "computed":
|
|
513
|
+
if c.formula:
|
|
514
|
+
return f"Computed: {c.formula}"
|
|
515
|
+
return f"Computed from {fmt.join(c.inputs, 4)}." if c.inputs else "Computed."
|
|
516
|
+
if h == "offset":
|
|
517
|
+
return f"Computed as {_offset_words(c, first or 'another column')}."
|
|
518
|
+
if h == "share":
|
|
519
|
+
return f"A modeled share of {first or 'a total'}."
|
|
520
|
+
if h == "total":
|
|
521
|
+
return f"The sum of {fmt.join(c.inputs, 4)}." if c.inputs else "The sum of its parts."
|
|
522
|
+
if h == "reference":
|
|
523
|
+
return "A repeating key; key values are issued fresh."
|
|
524
|
+
if h == "pseudonym":
|
|
525
|
+
return "Values replaced by stand-in tokens."
|
|
526
|
+
if h == "modeled":
|
|
527
|
+
return "No distribution to show."
|
|
528
|
+
if h in HANDLINGS or not h:
|
|
529
|
+
return "Not described by this version of the report."
|
|
530
|
+
return f"Not described by this version of the report ({h})."
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _chart_of(p: _Page, c: ColumnView) -> str:
|
|
534
|
+
what = c.chart_of
|
|
535
|
+
if not what:
|
|
536
|
+
return ""
|
|
537
|
+
first = c.inputs[0] if c.inputs else None
|
|
538
|
+
if what == "gap":
|
|
539
|
+
if first:
|
|
540
|
+
return f'<p class="small">The chart shows the gap after {p.link(first)}.</p>'
|
|
541
|
+
return '<p class="small">The chart shows the modeled gap, not the column itself.</p>'
|
|
542
|
+
if what == "share":
|
|
543
|
+
if first:
|
|
544
|
+
return f'<p class="small">The chart shows this column\'s share of {p.link(first)}.</p>'
|
|
545
|
+
return '<p class="small">The chart shows this column\'s share of its total.</p>'
|
|
546
|
+
if what == "group sizes":
|
|
547
|
+
return '<p class="small">The chart shows rows per key.</p>'
|
|
548
|
+
return f'<p class="small">The chart shows what the fingerprint calls {_e(what)}.</p>'
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _hist_items(h: Histogram) -> list[tuple[str, str]]:
|
|
552
|
+
f = _axis_formatter(h)
|
|
553
|
+
items: list[tuple[str, str]] = []
|
|
554
|
+
q25, q50, q75 = _quantile(h, 0.25), _quantile(h, 0.5), _quantile(h, 0.75)
|
|
555
|
+
if q50 is not None:
|
|
556
|
+
items.append(("Median", f(q50)))
|
|
557
|
+
if q25 is not None and q75 is not None:
|
|
558
|
+
items.append(("Middle half", f"{f(q25)} to {f(q75)}"))
|
|
559
|
+
q05, q95 = _quantile(h, 0.05), _quantile(h, 0.95)
|
|
560
|
+
if q05 is not None and q95 is not None:
|
|
561
|
+
items.append(("Middle 90%", f"{f(q05)} to {f(q95)}"))
|
|
562
|
+
atoms = [(v, s) for v, s in ((_f(a.value), _f(a.share)) for a in h.atoms or [])
|
|
563
|
+
if v is not None and s is not None and s > 0]
|
|
564
|
+
if atoms:
|
|
565
|
+
v, s = max(atoms, key=lambda t: t[1])
|
|
566
|
+
items.append((f"Exactly {f(v)}", fmt.share(s)))
|
|
567
|
+
steps = [s for s in (_f(x) for x in h.heap_steps or []) if s is not None and s > 0]
|
|
568
|
+
if steps:
|
|
569
|
+
if h.axis in ("date", "duration"):
|
|
570
|
+
words = [fmt.duration(s, h.unit or "") for s in steps[:3]]
|
|
571
|
+
elif h.axis == "share":
|
|
572
|
+
words = [fmt.share(s) for s in steps[:3]]
|
|
573
|
+
else:
|
|
574
|
+
words = [fmt.number(s) for s in steps[:3]]
|
|
575
|
+
items.append(("Heaps", "on multiples of " + fmt.join(words, 3)))
|
|
576
|
+
return items
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def _level_items(lv: Levels) -> list[tuple[str, str]]:
|
|
580
|
+
items: list[tuple[str, str]] = []
|
|
581
|
+
if lv.n_levels is not None and _f(lv.n_levels) is not None:
|
|
582
|
+
items.append(("Values", fmt.count(lv.n_levels)))
|
|
583
|
+
plain = [b for b in lv.bars or [] if b.kind == "level" and _f(b.share) is not None]
|
|
584
|
+
if plain:
|
|
585
|
+
top = max(plain, key=lambda b: _f(b.share) or 0.0)
|
|
586
|
+
items.append(("Most common", f"{fmt.truncate(top.label, 40)} ({fmt.share(top.share)})"))
|
|
587
|
+
pooled_share = _f(lv.pooled_share)
|
|
588
|
+
if pooled_share is None:
|
|
589
|
+
pooled_share = sum(_f(b.share) or 0.0 for b in lv.bars or [] if b.kind == "pooled") or None
|
|
590
|
+
if lv.n_pooled or pooled_share:
|
|
591
|
+
what = fmt.plural(lv.n_pooled, "rare value") if lv.n_pooled else "rare values"
|
|
592
|
+
if pooled_share:
|
|
593
|
+
what += f" ({fmt.share(pooled_share)} of rows)"
|
|
594
|
+
items.append(("Pooled", what))
|
|
595
|
+
return items
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _dl(items: list[tuple[str, str]]) -> str:
|
|
599
|
+
if not items:
|
|
600
|
+
return ""
|
|
601
|
+
return ('<dl class="stats">'
|
|
602
|
+
+ "".join(f"<div><dt>{_e(k)}</dt><dd>{_e(v)}</dd></div>" for k, v in items)
|
|
603
|
+
+ "</dl>")
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _card(p: _Page, k: int, c: ColumnView, compact: bool) -> str:
|
|
607
|
+
name = c.name if isinstance(c.name, str) else str(c.name)
|
|
608
|
+
anchor = p.anchors[k]
|
|
609
|
+
flag = "1" if name in p.named else "0"
|
|
610
|
+
out = [f'<article class="col{" compact" if compact else ""}" id="{anchor}" '
|
|
611
|
+
f'data-name="{_e(name.lower())}" data-flag="{flag}"><header><h3>'
|
|
612
|
+
f'{_e(name) or "(unnamed column)"}</h3><p class="kind"><span>{_e(_type_text(c))}</span>'
|
|
613
|
+
f"<span>{_e(_how_text(c))}</span></p></header>"]
|
|
614
|
+
m = _f(c.missing)
|
|
615
|
+
if m is not None:
|
|
616
|
+
if m > 0:
|
|
617
|
+
out.append(f'<p class="missline has"><span class="miss"><span style="width:'
|
|
618
|
+
f'{_pct_width(m)}"></span></span>{_e(fmt.share(m))} empty</p>')
|
|
619
|
+
else:
|
|
620
|
+
out.append('<p class="missline">No empty cells</p>')
|
|
621
|
+
|
|
622
|
+
title = name if len(name) <= 120 else fmt.truncate(name, 120)
|
|
623
|
+
if c.histogram is not None and len(c.histogram.atoms or []) == 1 \
|
|
624
|
+
and not (c.histogram.shares or []):
|
|
625
|
+
only = _axis_formatter(c.histogram)(c.histogram.atoms[0].value)
|
|
626
|
+
what = {"gap": "gap", "share": "share", "group sizes": "group size"}.get(
|
|
627
|
+
c.chart_of, "value")
|
|
628
|
+
out.append(f'<p class="nochart">Every stored {what} is <b>{_e(only)}</b>.</p>')
|
|
629
|
+
out.append(_chart_of(p, c))
|
|
630
|
+
elif c.histogram is not None and charts.has_data(c.histogram):
|
|
631
|
+
h = c.histogram
|
|
632
|
+
out.append(charts.histogram(h, uid=p.uid(), title=f"{title}: distribution",
|
|
633
|
+
compact=compact))
|
|
634
|
+
out.append(_chart_of(p, c))
|
|
635
|
+
items = _hist_items(h)
|
|
636
|
+
if compact:
|
|
637
|
+
keep = []
|
|
638
|
+
for k_, v in items:
|
|
639
|
+
if k_ == "Median":
|
|
640
|
+
keep.append(f"median {v}")
|
|
641
|
+
elif k_ == "Middle half":
|
|
642
|
+
keep.append(f"middle half {v}")
|
|
643
|
+
elif k_.startswith("Exactly "):
|
|
644
|
+
keep.append(f"{v} exactly {k_[8:]}")
|
|
645
|
+
line = _sentence("; ".join(keep))
|
|
646
|
+
if not line:
|
|
647
|
+
line = fmt.truncate(charts.describe_histogram(h), 100)
|
|
648
|
+
out.append(f'<p class="stats1">{_e(line)}</p>')
|
|
649
|
+
else:
|
|
650
|
+
out.append(_dl(items))
|
|
651
|
+
elif c.levels is not None and charts.has_data(c.levels):
|
|
652
|
+
lv = c.levels
|
|
653
|
+
out.append(charts.levels(lv, uid=p.uid(), title=f"{title}: values",
|
|
654
|
+
max_bars=4 if compact else 8, compact=compact))
|
|
655
|
+
out.append(_chart_of(p, c))
|
|
656
|
+
items = _level_items(lv)
|
|
657
|
+
if compact:
|
|
658
|
+
bits = []
|
|
659
|
+
for k_, v in items:
|
|
660
|
+
if k_ == "Values":
|
|
661
|
+
bits.append(f"{v} values")
|
|
662
|
+
elif k_ == "Most common":
|
|
663
|
+
bits.append(f"most common {v}")
|
|
664
|
+
line = "; ".join(bits) or fmt.truncate(charts.describe_levels(lv), 100)
|
|
665
|
+
out.append(f'<p class="stats1">{_e(_sentence(line))}</p>')
|
|
666
|
+
else:
|
|
667
|
+
out.append(_dl(items))
|
|
668
|
+
if lv.stand_ins:
|
|
669
|
+
out.append('<p class="small">Labels are stand-in tokens.</p>')
|
|
670
|
+
else:
|
|
671
|
+
out.append(f'<p class="nochart">{_nochart_html(p, c)}</p>')
|
|
672
|
+
|
|
673
|
+
if c.chart_note:
|
|
674
|
+
out.append(f'<p class="small">{_e(c.chart_note)}</p>')
|
|
675
|
+
if not compact:
|
|
676
|
+
if c.conditional_on:
|
|
677
|
+
out.append(f'<p class="small">Tied directly to {p.link(c.conditional_on)} in the '
|
|
678
|
+
"model.</p>")
|
|
679
|
+
if c.pattern:
|
|
680
|
+
out.append(f'<p class="small">Shape: <code>{_e(c.pattern)}</code></p>')
|
|
681
|
+
conf = _f(c.confidence)
|
|
682
|
+
if conf is not None and conf < 0.7 and not c.overridden:
|
|
683
|
+
out.append(f'<p class="small">Inferred with confidence {_e(fmt.share(conf))}.</p>')
|
|
684
|
+
if c.overridden:
|
|
685
|
+
out.append('<p class="small">Type set by the user.</p>')
|
|
686
|
+
# an alert the card already states in its own words is not repeated on it, and a compact
|
|
687
|
+
# card keeps only what is worth acting on
|
|
688
|
+
named = [a for a in p.named.get(name, []) if a.kind not in CARD_SILENT
|
|
689
|
+
and (not compact or a.severity == "act")]
|
|
690
|
+
for a in named[:CARD_ALERTS]:
|
|
691
|
+
cls = "flagline serious" if a.severity == "act" else "flagline"
|
|
692
|
+
out.append(f'<p class="{cls}">{_level(a)} {p.message(a, 2, linked=False)}</p>')
|
|
693
|
+
if len(named) > CARD_ALERTS:
|
|
694
|
+
rest = len(named) - CARD_ALERTS
|
|
695
|
+
more = fmt.plural(rest, "more alert")
|
|
696
|
+
verb = "names" if rest == 1 else "name"
|
|
697
|
+
out.append(f'<p class="small"><a href="#alerts">{more}</a> {verb} this column.</p>')
|
|
698
|
+
for u in c.unread or []:
|
|
699
|
+
out.append(f'<p class="small">Not described here: {_e(u.what or "an entry")} '
|
|
700
|
+
f"(<code>{_e(u.where)}</code>).</p>")
|
|
701
|
+
notes = [n for n in c.notes or [] if n]
|
|
702
|
+
if notes:
|
|
703
|
+
out.append(f'<details class="notes"><summary>{fmt.plural(len(notes), "engine note")}'
|
|
704
|
+
"</summary><ul>" + "".join(f"<li>{_e(n)}</li>" for n in notes)
|
|
705
|
+
+ "</ul></details>")
|
|
706
|
+
out.append("</article>")
|
|
707
|
+
return "".join(out)
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
_CHART_OF_PREFIX = {"gap": "Gap after {}: ", "share": "Share of {}: ", "group sizes": "Rows per key: "}
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
def _list_row(p: _Page, k: int, c: ColumnView) -> str:
|
|
714
|
+
name = c.name if isinstance(c.name, str) else str(c.name)
|
|
715
|
+
flag = "1" if name in p.named else "0"
|
|
716
|
+
if c.histogram is not None and charts.has_data(c.histogram):
|
|
717
|
+
summary = _CHART_OF_PREFIX.get(c.chart_of, "").replace(
|
|
718
|
+
"{}", c.inputs[0] if c.inputs else "its input") + charts.describe_histogram(c.histogram)
|
|
719
|
+
elif c.levels is not None and charts.has_data(c.levels):
|
|
720
|
+
summary = charts.describe_levels(c.levels)
|
|
721
|
+
else:
|
|
722
|
+
summary = _nochart_text(c)
|
|
723
|
+
m = _f(c.missing)
|
|
724
|
+
return (f'<tr id="{p.anchors[k]}" data-name="{_e(name.lower())}" data-flag="{flag}">'
|
|
725
|
+
f'<td class="num">{p.positions[k] + 1}</td><th scope="row">'
|
|
726
|
+
f'{_e(name) or "(unnamed column)"}</th><td>{_e(_type_text(c))}</td>'
|
|
727
|
+
f"<td>{_e(_how_text(c))}</td>"
|
|
728
|
+
f'<td class="num">{_e(fmt.share(m)) if m is not None else ""}</td>'
|
|
729
|
+
f'<td class="num">{_e(fmt.count(c.distinct)) if c.distinct is not None else ""}</td>'
|
|
730
|
+
f"<td>{_e(fmt.truncate(summary, 140))}</td></tr>")
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
def _columns(p: _Page) -> str:
|
|
734
|
+
v = p.view
|
|
735
|
+
out = []
|
|
736
|
+
clip = [x for x in (_f(t) for t in v.privacy.tail_clip or []) if x is not None]
|
|
737
|
+
clipped = len(clip) >= 2 and (clip[0] > 0 or clip[1] < 1)
|
|
738
|
+
if p.detail == "list":
|
|
739
|
+
intro = ("One row per column. Charts are left out at this level of detail; the summary "
|
|
740
|
+
"gives the key figures, rebuilt from the model fitted to each column, not from "
|
|
741
|
+
"its rows.")
|
|
742
|
+
else:
|
|
743
|
+
intro = ("Each chart is rebuilt from the model fitted to the column, not from its "
|
|
744
|
+
"rows.")
|
|
745
|
+
if clipped:
|
|
746
|
+
intro += (f" Axes of numbers end where the policy clips the tails, at the "
|
|
747
|
+
f"{_ordinal(100 * clip[0])} and {_ordinal(100 * clip[1])} percentiles.")
|
|
748
|
+
if not v.columns:
|
|
749
|
+
return _section("columns", "Columns", "<p>This fingerprint describes no columns.</p>")
|
|
750
|
+
out.append(f'<p class="intro">{_e(intro)}</p>')
|
|
751
|
+
out.append('<form class="filter" hidden aria-label="Filter columns"><label>Filter columns by '
|
|
752
|
+
'name<input type="search" name="q" autocomplete="off" spellcheck="false"></label>'
|
|
753
|
+
'<label><input type="checkbox" name="flag">Only columns with alerts</label>'
|
|
754
|
+
'<p class="count" aria-live="polite"></p></form>')
|
|
755
|
+
if p.detail == "list":
|
|
756
|
+
rows = []
|
|
757
|
+
for k, c in enumerate(v.columns):
|
|
758
|
+
try:
|
|
759
|
+
rows.append(_list_row(p, k, c))
|
|
760
|
+
except Exception: # noqa: BLE001
|
|
761
|
+
rows.append(f'<tr id="{p.anchors[k]}" data-name="" data-flag="0"><td class="num">'
|
|
762
|
+
f'{k + 1}</td><th scope="row">{_e(c.name)}</th><td colspan="5">'
|
|
763
|
+
"This column could not be drawn.</td></tr>")
|
|
764
|
+
out.append(_table("All columns", ("#", "Column", "Type", "How it is produced", "Empty",
|
|
765
|
+
"Distinct", "Summary"),
|
|
766
|
+
rows, "Columns, one row each", cls="cols wide", num_cols=(0, 4, 5)))
|
|
767
|
+
else:
|
|
768
|
+
compact = p.detail == "compact"
|
|
769
|
+
out.append('<div class="grid">')
|
|
770
|
+
for k, c in enumerate(v.columns):
|
|
771
|
+
card = _guard(partial(_card, p, k, c, compact), "column")
|
|
772
|
+
if not card.startswith("<article"):
|
|
773
|
+
card = (f'<article class="col" id="{p.anchors[k]}" data-name="" data-flag="0">'
|
|
774
|
+
f"<h3>{_e(c.name)}</h3>{card}</article>")
|
|
775
|
+
out.append(card)
|
|
776
|
+
out.append("</div>")
|
|
777
|
+
return _section("columns", "Columns", "".join(out))
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
# -- relationships ----------------------------------------------------------------------------
|
|
781
|
+
|
|
782
|
+
_TAGS = {
|
|
783
|
+
"sum": "parts of one total",
|
|
784
|
+
"offset": "one is the other plus a gap",
|
|
785
|
+
"computed": "one is computed from the other",
|
|
786
|
+
"entity": "same entity",
|
|
787
|
+
"ordering": "kept in order",
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
_MEASURE_SENTENCES = {
|
|
791
|
+
"spearman": ("Rank correlation measures how far two columns rise or fall together, "
|
|
792
|
+
"whatever the shape of the relation."),
|
|
793
|
+
"cramers_v": ("Cramér's V measures how far the values of two categories go together: 0 "
|
|
794
|
+
"when knowing one says nothing about the other, 1 when it fixes it."),
|
|
795
|
+
"correlation_ratio": ("The correlation ratio measures how much of the spread of a number "
|
|
796
|
+
"is explained by the values of a category. A category of very many "
|
|
797
|
+
"values scores high on it by its number of groups alone, so such "
|
|
798
|
+
"pairs are tagged."),
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
#: a strength below this is stated as "close to unrelated" rather than as a weak direction
|
|
803
|
+
UNRELATED = 0.1
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
def _band(s: float, top: str) -> str:
|
|
807
|
+
if s >= 0.9:
|
|
808
|
+
return top
|
|
809
|
+
if s >= 0.7:
|
|
810
|
+
return "strongly"
|
|
811
|
+
if s >= 0.4:
|
|
812
|
+
return "moderately"
|
|
813
|
+
return "weakly"
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def _is_category(c: ColumnView | None) -> bool | None:
|
|
817
|
+
if c is None:
|
|
818
|
+
return None
|
|
819
|
+
if c.logical_type in ("categorical", "boolean"):
|
|
820
|
+
return True
|
|
821
|
+
if c.levels is not None and not c.levels.ordered:
|
|
822
|
+
return True
|
|
823
|
+
if c.histogram is not None or c.logical_type in ("continuous", "discrete", "datetime"):
|
|
824
|
+
return False
|
|
825
|
+
return None
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _side(p: _Page, name: str, group: int | None) -> str:
|
|
829
|
+
"""One side of a pair: the column, and a word about the group it stands for."""
|
|
830
|
+
text = p.link(name)
|
|
831
|
+
groups = p.view.relationships.groups or []
|
|
832
|
+
if isinstance(group, int) and 0 <= group < len(groups):
|
|
833
|
+
others = len(groups[group].columns or []) - 1
|
|
834
|
+
if others > 0:
|
|
835
|
+
twin = [c for c in groups[group].columns if c != name]
|
|
836
|
+
like = p.link(twin[0]) if others == 1 else fmt.plural(others, "other column")
|
|
837
|
+
text += f' <span class="with">(like {like})</span>'
|
|
838
|
+
return text
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def _group_li(p: _Page, g: ColumnGroup) -> str:
|
|
842
|
+
cols = [c for c in g.columns or [] if isinstance(c, str)]
|
|
843
|
+
weakest = _f(g.weakest)
|
|
844
|
+
label = fmt.measure_label(g.measure) if g.measure else "strength"
|
|
845
|
+
floor = (f": every pair among them has a {_e(label)} of at least "
|
|
846
|
+
f"{math.floor(weakest * 100) / 100:.2f}" if weakest is not None else "")
|
|
847
|
+
tag = (f' <span class="tag">{_e(_TAGS.get(g.explained_by, g.explained_by))}</span>'
|
|
848
|
+
if g.explained_by else "")
|
|
849
|
+
if len(cols) == 2 and weakest is not None:
|
|
850
|
+
floor = f" ({_e(label)} {math.floor(weakest * 100) / 100:.2f})"
|
|
851
|
+
if len(cols) <= GROUP_VISIBLE:
|
|
852
|
+
names = p.links(cols, GROUP_VISIBLE)
|
|
853
|
+
return f"<li>{names} move together almost exactly{floor}.{tag}</li>"
|
|
854
|
+
names = p.links(cols, GROUP_VISIBLE - 2)
|
|
855
|
+
rest = ", ".join(p.link(c) for c in cols)
|
|
856
|
+
return (f"<li>{names} ({fmt.count(len(cols))} columns) move together almost exactly"
|
|
857
|
+
f"{floor}.{tag}<details class=\"more\"><summary>All {fmt.count(len(cols))} "
|
|
858
|
+
f"columns</summary><p>{rest}</p></details></li>")
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
def _statement(p: _Page, pr: Pair, s: float) -> str:
|
|
862
|
+
a, b = _side(p, pr.a, pr.a_group), _side(p, pr.b, pr.b_group)
|
|
863
|
+
m = pr.measure
|
|
864
|
+
if s < UNRELATED and m in ("spearman", "cramers_v", "correlation_ratio"):
|
|
865
|
+
return f"{a} and {b} are close to unrelated"
|
|
866
|
+
if m == "spearman":
|
|
867
|
+
band = _band(s, "almost in step")
|
|
868
|
+
if pr.sign == 1:
|
|
869
|
+
return f"{a} and {b} rise together, {band}"
|
|
870
|
+
if pr.sign == -1:
|
|
871
|
+
return f"{b} falls as {a} rises, {band}"
|
|
872
|
+
return f"{a} and {b} move together, {band} (direction not recorded)"
|
|
873
|
+
if m == "cramers_v":
|
|
874
|
+
if s >= 0.9:
|
|
875
|
+
return f"{a} and {b} almost determine each other"
|
|
876
|
+
return f"{a} and {b} go together, {_band(s, '')}"
|
|
877
|
+
if m == "correlation_ratio":
|
|
878
|
+
band = _band(s, "very strongly")
|
|
879
|
+
ca, cb = _is_category(p.column(pr.a)), _is_category(p.column(pr.b))
|
|
880
|
+
if ca is True and cb is False:
|
|
881
|
+
return f"{b} differs between the values of {a}, {band}"
|
|
882
|
+
if cb is True and ca is False:
|
|
883
|
+
return f"{a} differs between the values of {b}, {band}"
|
|
884
|
+
return f"{a} and {b} are associated, {band}"
|
|
885
|
+
label = fmt.measure_label(m) if m else "measure not recorded"
|
|
886
|
+
return f"{a} and {b} are associated ({_e(label)})"
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
def _pair_li(p: _Page, pr: Pair) -> str:
|
|
890
|
+
s = _share01(pr.strength)
|
|
891
|
+
tag = ""
|
|
892
|
+
if pr.explained_by:
|
|
893
|
+
tag = f' <span class="tag">{_e(_TAGS.get(pr.explained_by, pr.explained_by))}</span>'
|
|
894
|
+
elif pr.measure == "correlation_ratio":
|
|
895
|
+
# a category with very many values explains much of any number by its count of groups
|
|
896
|
+
for name in (pr.a, pr.b):
|
|
897
|
+
c = p.column(name)
|
|
898
|
+
n = _f(c.levels.n_levels) if c is not None and c.levels is not None else None
|
|
899
|
+
if c is not None and _is_category(c) and n is not None and n >= MANY_VALUES:
|
|
900
|
+
tag = f' <span class="tag plain">a category of {fmt.count(n)} values</span>'
|
|
901
|
+
break
|
|
902
|
+
return (f'<li><span class="meter"><span style="width:{_pct_width(s)}"></span></span>'
|
|
903
|
+
f'<span class="num">{s:.2f}</span><span class="say">{_statement(p, pr, s)}'
|
|
904
|
+
f"{tag}</span></li>")
|
|
905
|
+
|
|
906
|
+
|
|
907
|
+
def _relationships(p: _Page) -> str:
|
|
908
|
+
r = p.view.relationships
|
|
909
|
+
pairs = list(r.pairs or [])
|
|
910
|
+
out = []
|
|
911
|
+
intro = []
|
|
912
|
+
n_pairs = r.n_pairs if _f(r.n_pairs) is not None else None
|
|
913
|
+
n_cols = r.n_columns if _f(r.n_columns) is not None else None
|
|
914
|
+
if pairs or n_pairs:
|
|
915
|
+
measured = (f"The engine measured {fmt.plural(n_pairs or 0, 'pair')} of columns"
|
|
916
|
+
if n_pairs is not None else "The engine measured pairs of columns")
|
|
917
|
+
if n_cols is not None:
|
|
918
|
+
measured += f" over {fmt.plural(n_cols, 'column')}"
|
|
919
|
+
if pairs:
|
|
920
|
+
if n_pairs is not None and len(pairs) >= n_pairs:
|
|
921
|
+
measured += "; all are stated below, strongest first."
|
|
922
|
+
elif r.groups:
|
|
923
|
+
measured += ("; the strongest are stated below. Columns that move together "
|
|
924
|
+
"almost exactly are stated once, as a group.")
|
|
925
|
+
else:
|
|
926
|
+
measured += f"; the {fmt.count(len(pairs))} strongest are stated below."
|
|
927
|
+
else:
|
|
928
|
+
measured += "."
|
|
929
|
+
intro.append(measured)
|
|
930
|
+
intro.append("Strength runs from 0 (unrelated) to 1 (one column fixes the other).")
|
|
931
|
+
jk = r.joint_kind
|
|
932
|
+
if jk:
|
|
933
|
+
label = fmt.joint_label(jk)
|
|
934
|
+
over = (f" over {fmt.plural(r.joint_columns or 0, 'column')}"
|
|
935
|
+
if _f(r.joint_columns) is not None else "")
|
|
936
|
+
if jk == "independent":
|
|
937
|
+
intro.append("The model generates each column on its own: it does not tie columns "
|
|
938
|
+
"together.")
|
|
939
|
+
elif _known(label, jk):
|
|
940
|
+
intro.append(f"The fingerprint's model of how columns move together is a {label}.")
|
|
941
|
+
else:
|
|
942
|
+
intro.append(f"How columns move together is held by a model the fingerprint "
|
|
943
|
+
f"calls {jk}{over}.")
|
|
944
|
+
if r.joint_reason:
|
|
945
|
+
intro.append(f"Why this model: {_full_sentence(r.joint_reason)}")
|
|
946
|
+
if r.joint_limit:
|
|
947
|
+
intro.append(_full_sentence(r.joint_limit))
|
|
948
|
+
if intro:
|
|
949
|
+
out.append(f'<p class="intro">{_e(" ".join(intro))}</p>')
|
|
950
|
+
groups = [g for g in r.groups or [] if len(g.columns or []) >= 2]
|
|
951
|
+
has_matrix = r.matrix is not None and len(r.matrix.columns or []) >= 3
|
|
952
|
+
if not pairs and not has_matrix and not groups:
|
|
953
|
+
out.append("<p>This fingerprint holds no measured associations between columns.</p>")
|
|
954
|
+
if groups:
|
|
955
|
+
out.append('<h3 id="same-h">Columns that move as one</h3><ul class="rules">')
|
|
956
|
+
out += [_group_li(p, g) for g in groups]
|
|
957
|
+
out.append("</ul>")
|
|
958
|
+
if pairs:
|
|
959
|
+
out.append("<h3>Strongest relationships between the rest</h3>")
|
|
960
|
+
if pairs:
|
|
961
|
+
out.append('<ol class="pairs">')
|
|
962
|
+
out += [_pair_li(p, pr) for pr in pairs[:PAIRS_VISIBLE]]
|
|
963
|
+
out.append("</ol>")
|
|
964
|
+
rest = pairs[PAIRS_VISIBLE:]
|
|
965
|
+
if rest:
|
|
966
|
+
out.append(f'<details class="more"><summary>{fmt.plural(len(rest), "more pair")}'
|
|
967
|
+
f'</summary><ol class="pairs" start="{PAIRS_VISIBLE + 1}">')
|
|
968
|
+
out += [_pair_li(p, pr) for pr in rest]
|
|
969
|
+
out.append("</ol></details>")
|
|
970
|
+
seen = []
|
|
971
|
+
for pr in pairs:
|
|
972
|
+
if pr.measure in _MEASURE_SENTENCES and pr.measure not in seen:
|
|
973
|
+
seen.append(pr.measure)
|
|
974
|
+
if seen:
|
|
975
|
+
out.append('<p class="explain">' + " ".join(_MEASURE_SENTENCES[m] for m in seen)
|
|
976
|
+
+ "</p>")
|
|
977
|
+
if has_matrix and r.matrix is not None:
|
|
978
|
+
mx = r.matrix
|
|
979
|
+
n = min(len(mx.columns), charts.MATRIX_MAX)
|
|
980
|
+
hrefs = {c: h for c in mx.columns if isinstance(c, str) and (h := p.href(c))}
|
|
981
|
+
svg = charts.matrix(mx, uid="matrix", title="Association strengths", hrefs=hrefs)
|
|
982
|
+
# draw the matrix at its own size (text at 12px), never wider than 600px
|
|
983
|
+
try:
|
|
984
|
+
width = float(svg.split('viewBox="', 1)[1].split('"', 1)[0].split()[2])
|
|
985
|
+
except (IndexError, ValueError):
|
|
986
|
+
width = 600.0
|
|
987
|
+
width = min(max(width, 120.0), 600.0)
|
|
988
|
+
box = f"width:{width:.0f}px;min-width:{min(width, 480.0):.0f}px;max-width:100%"
|
|
989
|
+
out.append(f'<figure class="matrixfig"><figcaption>The {fmt.count(n)} columns that '
|
|
990
|
+
"appear in the strongest pairs, each pair once. A darker cell is a stronger "
|
|
991
|
+
"association.</figcaption>"
|
|
992
|
+
f'<div class="scroll" tabindex="0" role="region" aria-label="Matrix of '
|
|
993
|
+
f'association strengths"><div style="{box}">{svg}</div></div></figure>')
|
|
994
|
+
if r.left_out:
|
|
995
|
+
out.append("<p>Not measured against other columns, because too few rows hold their "
|
|
996
|
+
f"rarer values: {p.links(r.left_out, 6)}.</p>")
|
|
997
|
+
return _section("relationships", "Relationships", "".join(out))
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
# -- structure --------------------------------------------------------------------------------
|
|
1001
|
+
|
|
1002
|
+
#: how fresh key values are issued, by the engine's name for it
|
|
1003
|
+
_SURROGATES = {
|
|
1004
|
+
"surrogate_sequence": "Key values are issued fresh, as new whole numbers.",
|
|
1005
|
+
"surrogate_token": "Key values are issued fresh, as made-up tokens.",
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
_SOURCES = {
|
|
1009
|
+
"detected": "found by the engine",
|
|
1010
|
+
"suggested": "from a suggested rule",
|
|
1011
|
+
"confirmed": "confirmed by the user",
|
|
1012
|
+
"user": "declared by the user",
|
|
1013
|
+
"declared": "declared by the user",
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
_FAMILIES = {
|
|
1017
|
+
"calendar": "a calendar part of a date",
|
|
1018
|
+
"periodic": "a repeating function of a whole number",
|
|
1019
|
+
"identity": "a copy of another column",
|
|
1020
|
+
"declared": "declared by the user",
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
_SUM_MODES = {
|
|
1024
|
+
"split": "the parts are modeled as shares of the total",
|
|
1025
|
+
"scale": "in generated rows the parts are scaled so that they add up",
|
|
1026
|
+
"sum": "the total is computed from the parts",
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
_DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
#: families of suggested rules, in words (singular, plural)
|
|
1033
|
+
_RULE_FAMILIES = {
|
|
1034
|
+
"ordering": ("ordering", "orderings"),
|
|
1035
|
+
"bound": ("bound", "bounds"),
|
|
1036
|
+
"nullability": ("rule about empty cells", "rules about empty cells"),
|
|
1037
|
+
"identity": ("identity", "identities"),
|
|
1038
|
+
"fd": ("column fixed by another", "columns fixed by another"),
|
|
1039
|
+
"sum": ("sum", "sums"),
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _family_word(family: str) -> str:
|
|
1044
|
+
words = _RULE_FAMILIES.get(family)
|
|
1045
|
+
return words[0] if words else family
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def _rule_text(c: Constraint) -> str:
|
|
1049
|
+
"""The rule as text. Some families store a bare ``true`` as their expression and say what
|
|
1050
|
+
they mean in the description (``a -> b``: a fixes b); the description is shown then."""
|
|
1051
|
+
expr = (c.expression or "").strip()
|
|
1052
|
+
if expr.lower() in ("", "true", "false") and c.description:
|
|
1053
|
+
return c.description
|
|
1054
|
+
return expr or c.description
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
def _family_count(f: Fact) -> str:
|
|
1058
|
+
n = _f(f.number)
|
|
1059
|
+
words = _RULE_FAMILIES.get(f.label)
|
|
1060
|
+
if n is None:
|
|
1061
|
+
return words[1] if words else f"of family {f.label}"
|
|
1062
|
+
if words:
|
|
1063
|
+
return fmt.plural(int(n), *words)
|
|
1064
|
+
return f"{fmt.count(n)} of family {f.label}"
|
|
1065
|
+
|
|
1066
|
+
|
|
1067
|
+
def _source(s: str) -> str:
|
|
1068
|
+
if not s:
|
|
1069
|
+
return ""
|
|
1070
|
+
return _SOURCES.get(s, f"source: {s}")
|
|
1071
|
+
|
|
1072
|
+
|
|
1073
|
+
def _ordering(p: _Page, o: Ordering) -> str:
|
|
1074
|
+
target = p.column(o.target)
|
|
1075
|
+
dated = target is not None and target.logical_type == "datetime"
|
|
1076
|
+
t = p.link(o.target)
|
|
1077
|
+
clauses = []
|
|
1078
|
+
if o.lower:
|
|
1079
|
+
lows = p.links(o.lower, 4)
|
|
1080
|
+
if o.strict:
|
|
1081
|
+
clauses.append(f"always {'after' if dated else 'above'} {lows}")
|
|
1082
|
+
else:
|
|
1083
|
+
clauses.append(f"never {'before' if dated else 'below'} {lows}")
|
|
1084
|
+
if o.upper:
|
|
1085
|
+
ups = p.links(o.upper, 4)
|
|
1086
|
+
if o.strict:
|
|
1087
|
+
clauses.append(f"always {'before' if dated else 'below'} {ups}")
|
|
1088
|
+
else:
|
|
1089
|
+
clauses.append(f"never {'after' if dated else 'above'} {ups}")
|
|
1090
|
+
head = (f"{t} is " + " and ".join(clauses) + "."
|
|
1091
|
+
if clauses else f"{t} keeps an order with other columns.")
|
|
1092
|
+
how = []
|
|
1093
|
+
chart = ""
|
|
1094
|
+
if o.how == "gap":
|
|
1095
|
+
base = o.base or (o.lower[0] if o.lower else (o.upper[0] if o.upper else ""))
|
|
1096
|
+
if base:
|
|
1097
|
+
if base in (o.upper or []) and base not in (o.lower or []):
|
|
1098
|
+
how.append(f"modeled as {p.link(base)} minus a gap")
|
|
1099
|
+
elif base in (o.lower or []):
|
|
1100
|
+
how.append(f"modeled as {p.link(base)} plus a gap")
|
|
1101
|
+
else:
|
|
1102
|
+
how.append(f"modeled as {p.link(base)} plus (or minus) a gap")
|
|
1103
|
+
else:
|
|
1104
|
+
how.append("modeled as another column plus a gap")
|
|
1105
|
+
if o.gap is not None and charts.has_data(o.gap):
|
|
1106
|
+
f = _axis_formatter(o.gap)
|
|
1107
|
+
bits = []
|
|
1108
|
+
med, q1, q3 = (_quantile(o.gap, x) for x in (0.5, 0.25, 0.75))
|
|
1109
|
+
if med is not None:
|
|
1110
|
+
bits.append(f"median {f(med)}")
|
|
1111
|
+
if q1 is not None and q3 is not None:
|
|
1112
|
+
bits.append(f"middle half {f(q1)} to {f(q3)}")
|
|
1113
|
+
top = max(o.gap.atoms or [], key=lambda a: _share01(a.share), default=None)
|
|
1114
|
+
if top is not None and _share01(top.share) >= 0.01:
|
|
1115
|
+
bits.append(f"{fmt.share(top.share)} exactly {f(top.value)}")
|
|
1116
|
+
line = "; ".join(bits) or charts.describe_histogram(o.gap)
|
|
1117
|
+
chart = (f'<div class="mini">'
|
|
1118
|
+
f'{charts.histogram(o.gap, uid=p.uid(), title="The gap", compact=True)}'
|
|
1119
|
+
f'</div><span class="how">The gap: {_e(line)}</span>')
|
|
1120
|
+
elif o.how == "redraw":
|
|
1121
|
+
how.append("a generated row that breaks the order is drawn again")
|
|
1122
|
+
elif o.how:
|
|
1123
|
+
how.append(f"method as stored: {_e(o.how)}")
|
|
1124
|
+
if o.signed:
|
|
1125
|
+
how.append("the share of source rows that break the order is reproduced")
|
|
1126
|
+
exc = _f(o.exceptions)
|
|
1127
|
+
if exc is not None and exc > 0:
|
|
1128
|
+
how.append(f"{_e(fmt.share(exc))} of source rows break it")
|
|
1129
|
+
if o.source:
|
|
1130
|
+
how.append(_e(_source(o.source)))
|
|
1131
|
+
tail = f'<span class="how">{_sentence("; ".join(how))}.</span>' if how else ""
|
|
1132
|
+
return f"<li>{head}{tail}{chart}</li>"
|
|
1133
|
+
|
|
1134
|
+
|
|
1135
|
+
def _assignment(p: _Page, column: str, rhs: str) -> str:
|
|
1136
|
+
"""``column = rhs`` in ``<code>``, the column linked; a long one folded."""
|
|
1137
|
+
if len(column) + len(rhs) + 3 > FORMULA_FOLD:
|
|
1138
|
+
return _formula(f"{column} = {rhs}")
|
|
1139
|
+
return f"<code>{p.link(column)} = {_e(rhs)}</code>"
|
|
1140
|
+
|
|
1141
|
+
|
|
1142
|
+
def _computed_li(p: _Page, comp: Computed) -> str:
|
|
1143
|
+
head = (_assignment(p, comp.column, comp.formula) if comp.formula
|
|
1144
|
+
else f"{p.link(comp.column)}: formula not recorded")
|
|
1145
|
+
words = []
|
|
1146
|
+
fam = comp.family
|
|
1147
|
+
if fam == "step":
|
|
1148
|
+
segs = _f(comp.segments)
|
|
1149
|
+
src = p.link(comp.inputs[0]) if comp.inputs else "a number"
|
|
1150
|
+
n = f"{fmt.plural(comp.segments or 0, 'band')}" if segs is not None else "bands"
|
|
1151
|
+
words.append(f"one value for each of {n} of {src}: the formula gives the first "
|
|
1152
|
+
"band's value, then each cut point and the value above it")
|
|
1153
|
+
elif fam in _FAMILIES:
|
|
1154
|
+
words.append(_FAMILIES[fam])
|
|
1155
|
+
elif fam:
|
|
1156
|
+
words.append(f"of the kind the fingerprint calls {_e(fam)}")
|
|
1157
|
+
exc = _f(comp.exceptions)
|
|
1158
|
+
if exc is not None and exc > 0:
|
|
1159
|
+
words.append(f"{_e(fmt.share(exc))} of source rows do not follow it; the fingerprint does not "
|
|
1160
|
+
"keep these exceptions")
|
|
1161
|
+
if comp.source:
|
|
1162
|
+
words.append(_e(_source(comp.source)))
|
|
1163
|
+
tail = f'<span class="how">{_sentence("; ".join(words))}.</span>' if words else ""
|
|
1164
|
+
return f"<li>{head}{tail}</li>"
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
#: parts written out in a sum's equation before the rest are counted
|
|
1168
|
+
SUM_PARTS = 8
|
|
1169
|
+
|
|
1170
|
+
|
|
1171
|
+
def _parts_html(p: _Page, sr: SumRule) -> str:
|
|
1172
|
+
"""The parts as linked names joined by plus and minus signs, at most :data:`SUM_PARTS`.
|
|
1173
|
+
Names are links, not code: a part called ``18 - 24`` must not read as arithmetic."""
|
|
1174
|
+
signs = list(sr.signs or [])
|
|
1175
|
+
bits = []
|
|
1176
|
+
for i, name in enumerate(list(sr.parts or [])[:SUM_PARTS]):
|
|
1177
|
+
neg = i < len(signs) and signs[i] == -1
|
|
1178
|
+
if i == 0:
|
|
1179
|
+
bits.append(("minus " if neg else "") + p.link(name))
|
|
1180
|
+
else:
|
|
1181
|
+
bits.append((" − " if neg else " + ") + p.link(name))
|
|
1182
|
+
return "".join(bits)
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _sum_li(p: _Page, sr: SumRule) -> str:
|
|
1186
|
+
rhs = _parts_html(p, sr)
|
|
1187
|
+
n_parts = len(sr.parts or [])
|
|
1188
|
+
more = (f" + {fmt.plural(n_parts - SUM_PARTS, 'more part')}" if n_parts > SUM_PARTS
|
|
1189
|
+
else "")
|
|
1190
|
+
const = _f(sr.constant)
|
|
1191
|
+
if sr.total:
|
|
1192
|
+
head = f'<span class="eq">{p.link(sr.total)} = {rhs}{more}</span>'
|
|
1193
|
+
elif const is not None:
|
|
1194
|
+
head = f'<span class="eq">{rhs}{more} = {_e(fmt.number(const))}</span>'
|
|
1195
|
+
else:
|
|
1196
|
+
head = f'<span class="eq">{rhs}{more}</span>'
|
|
1197
|
+
words = []
|
|
1198
|
+
if sr.mode:
|
|
1199
|
+
words.append(_e(_SUM_MODES.get(sr.mode, f"mode as stored: {sr.mode}")))
|
|
1200
|
+
if sr.rounding == "independent":
|
|
1201
|
+
tol = _f(sr.tolerance)
|
|
1202
|
+
words.append("each part is rounded on its own, so the sum holds within "
|
|
1203
|
+
+ (_e(fmt.number(tol)) if tol is not None else "a rounding step"))
|
|
1204
|
+
elif sr.rounding and sr.rounding != "exact":
|
|
1205
|
+
words.append(f"rounding as stored: {_e(sr.rounding)}")
|
|
1206
|
+
exc = _f(sr.exceptions)
|
|
1207
|
+
if exc is not None and exc > 0:
|
|
1208
|
+
words.append(f"{_e(fmt.share(exc))} of source rows do not add up; the fingerprint does not keep "
|
|
1209
|
+
"these exceptions")
|
|
1210
|
+
if sr.source:
|
|
1211
|
+
words.append(_e(_source(sr.source)))
|
|
1212
|
+
tail = f'<span class="how">{_sentence("; ".join(words))}.</span>' if words else ""
|
|
1213
|
+
chart = ""
|
|
1214
|
+
shares = [_share01(s) for s in sr.mean_shares or []][:n_parts]
|
|
1215
|
+
if shares and sum(shares) > 0:
|
|
1216
|
+
title = f"Mean shares of {sr.total or 'the total'}"
|
|
1217
|
+
chart = f'<div class="mini">{charts.parts(sr.parts, shares, uid=p.uid(), title=title)}</div>'
|
|
1218
|
+
top = sorted(zip(sr.parts, shares, strict=False), key=lambda t: -t[1])[:3]
|
|
1219
|
+
text = fmt.join([f"{_e(n)} {_e(fmt.share(s))}" for n, s in top], 3)
|
|
1220
|
+
chart += f'<span class="how">Largest parts on average: {text}.</span>'
|
|
1221
|
+
return f"<li>{head}{tail}{chart}</li>"
|
|
1222
|
+
|
|
1223
|
+
|
|
1224
|
+
def _structure(p: _Page) -> str:
|
|
1225
|
+
s = p.view.structure
|
|
1226
|
+
out = ['<p class="intro">Rules that hold in the table: the engine found them, or the '
|
|
1227
|
+
"user declared them. Rows generated from this fingerprint obey them.</p>"]
|
|
1228
|
+
any_part = False
|
|
1229
|
+
|
|
1230
|
+
if s.orderings:
|
|
1231
|
+
any_part = True
|
|
1232
|
+
out.append("<h3>Values that stay in order</h3><ul class=\"rules\">")
|
|
1233
|
+
out += [_ordering(p, o) for o in s.orderings]
|
|
1234
|
+
out.append("</ul>")
|
|
1235
|
+
if s.computed:
|
|
1236
|
+
any_part = True
|
|
1237
|
+
out.append("<h3>Computed columns</h3><ul class=\"rules\">")
|
|
1238
|
+
out += [_computed_li(p, comp) for comp in s.computed]
|
|
1239
|
+
out.append("</ul>")
|
|
1240
|
+
if s.sums:
|
|
1241
|
+
any_part = True
|
|
1242
|
+
out.append("<h3>Totals and their parts</h3><ul class=\"rules\">")
|
|
1243
|
+
out += [_sum_li(p, sr) for sr in s.sums]
|
|
1244
|
+
out.append("</ul>")
|
|
1245
|
+
if s.entities:
|
|
1246
|
+
any_part = True
|
|
1247
|
+
out.append("<h3>Entities</h3>")
|
|
1248
|
+
for g in s.entities:
|
|
1249
|
+
attrs = [a for a in g.attributes or [] if not a.anchor]
|
|
1250
|
+
anchors = [a for a in g.attributes or [] if a.anchor]
|
|
1251
|
+
n = (f" ({fmt.plural(g.n_keys or 0, 'key')})" if _f(g.n_keys) is not None else "")
|
|
1252
|
+
text = f"{p.link(g.key)} names an entity{n}."
|
|
1253
|
+
if attrs:
|
|
1254
|
+
text += f" Each key has one {p.links([a.column for a in attrs], 6)}."
|
|
1255
|
+
if anchors:
|
|
1256
|
+
text += f" It follows {p.links([a.column for a in anchors], 3)}."
|
|
1257
|
+
if g.key_stand_ins:
|
|
1258
|
+
text += " Keys are stand-in tokens."
|
|
1259
|
+
if g.source:
|
|
1260
|
+
text += f" {_e(_sentence(_source(g.source)))}."
|
|
1261
|
+
out.append(f"<p>{text}</p>")
|
|
1262
|
+
if g.attributes:
|
|
1263
|
+
rows = []
|
|
1264
|
+
for a in g.attributes:
|
|
1265
|
+
exc = _f(a.exceptions)
|
|
1266
|
+
rows.append(
|
|
1267
|
+
f'<tr><th scope="row">{p.link(a.column)}'
|
|
1268
|
+
f"{' (followed)' if a.anchor else ''}</th>"
|
|
1269
|
+
f'<td class="num">{_e(fmt.count(a.entries)) if a.entries is not None else ""}</td>'
|
|
1270
|
+
f'<td class="num">{_e(fmt.share(exc)) if exc is not None else ""}</td></tr>')
|
|
1271
|
+
out.append(_table(f"Attributes of {_e(g.key)}",
|
|
1272
|
+
("Attribute", "Keys with a value", "Rows that disagree"),
|
|
1273
|
+
rows, f"Attributes of {_e(g.key)}", num_cols=(1, 2)))
|
|
1274
|
+
if s.references:
|
|
1275
|
+
any_part = True
|
|
1276
|
+
out.append("<h3>Keys that repeat</h3><ul class=\"rules\">")
|
|
1277
|
+
for ref in s.references:
|
|
1278
|
+
bits = []
|
|
1279
|
+
mg, mx, sg = _f(ref.mean_group), _f(ref.max_group), _f(ref.singletons)
|
|
1280
|
+
if mg is not None:
|
|
1281
|
+
bits.append(f"about {_e(fmt.number(mg, 2))} rows per key")
|
|
1282
|
+
if mx is not None:
|
|
1283
|
+
bits.append(f"at most {_e(fmt.number(mx))}")
|
|
1284
|
+
text = ", ".join(bits)
|
|
1285
|
+
if sg is not None:
|
|
1286
|
+
text += ("; " if text else "") + f"{_e(fmt.share(sg))} of keys occur once"
|
|
1287
|
+
issued = "Key values are issued fresh."
|
|
1288
|
+
extra = ""
|
|
1289
|
+
for f in ref.facts or []:
|
|
1290
|
+
if f.label == "surrogate kind" and f.text in _SURROGATES:
|
|
1291
|
+
issued = _SURROGATES[f.text]
|
|
1292
|
+
else:
|
|
1293
|
+
extra += f" {_e(_sentence(str(f.label)))}: {_e(_fact_value(f))}."
|
|
1294
|
+
body = f"{text}." if text else ""
|
|
1295
|
+
out.append(f"<li>{p.link(ref.column)}: {body} {issued}{extra}</li>")
|
|
1296
|
+
out.append("</ul>")
|
|
1297
|
+
if s.weekly:
|
|
1298
|
+
any_part = True
|
|
1299
|
+
out.append("<h3>Weekly patterns</h3><ul class=\"rules\">")
|
|
1300
|
+
for w in s.weekly:
|
|
1301
|
+
vals = [_f(x) for x in w.weekday_shares or []]
|
|
1302
|
+
cycle = (f" (a cycle of {fmt.plural(w.period, 'day')})"
|
|
1303
|
+
if w.period and w.period != 7 else "")
|
|
1304
|
+
if len(vals) == 7 and all(x is not None for x in vals) and sum(
|
|
1305
|
+
x or 0.0 for x in vals) > 0:
|
|
1306
|
+
nums = [x or 0.0 for x in vals]
|
|
1307
|
+
busiest = max(range(7), key=lambda i: nums[i])
|
|
1308
|
+
weekend = (nums[5] + nums[6]) / (sum(nums) or 1.0)
|
|
1309
|
+
svg = charts.weekdays(nums, uid=p.uid(), title=f"{fmt.truncate(w.column, 80)}: rows per weekday")
|
|
1310
|
+
out.append(f"<li>{p.link(w.column)}{cycle}: most rows fall on "
|
|
1311
|
+
f"{_DAYS[busiest]} ({_e(fmt.share(nums[busiest] / (sum(nums) or 1.0)))}); "
|
|
1312
|
+
f"{_e(fmt.share(weekend))} fall on a weekend."
|
|
1313
|
+
f'<div class="mini">{svg}</div></li>')
|
|
1314
|
+
elif w.tied_to:
|
|
1315
|
+
out.append(f"<li>{p.link(w.column)}{cycle} moves together with "
|
|
1316
|
+
f"{p.links(w.tied_to, 4)} over the week.</li>")
|
|
1317
|
+
else:
|
|
1318
|
+
out.append(f"<li>{p.link(w.column)}{cycle} follows a weekly pattern; its "
|
|
1319
|
+
"shares are not recorded.</li>")
|
|
1320
|
+
out.append("</ul>")
|
|
1321
|
+
if s.confirmed or s.suggested or s.n_suggested:
|
|
1322
|
+
any_part = True
|
|
1323
|
+
out.append("<h3>Rules</h3>")
|
|
1324
|
+
if s.confirmed:
|
|
1325
|
+
rows = [f'<tr><th scope="row">{_formula(_rule_text(c) or c.id)}</th>'
|
|
1326
|
+
f"<td>{_e(c.enforcement or 'not recorded')}</td></tr>" for c in s.confirmed]
|
|
1327
|
+
out.append(_table("Confirmed rules", ("Rule", "How it is enforced"), rows,
|
|
1328
|
+
"Confirmed rules"))
|
|
1329
|
+
n_sugg = max(int(_f(s.n_suggested) or 0), len(s.suggested))
|
|
1330
|
+
if n_sugg:
|
|
1331
|
+
fams = [_e(_family_count(f)) for f in s.suggested_families or []]
|
|
1332
|
+
by = f" ({fmt.join(fams, 6)})" if fams else ""
|
|
1333
|
+
out.append(f"<p>The engine also suggests {fmt.plural(n_sugg, 'rule')}{by}. "
|
|
1334
|
+
"Suggestions are not enforced until confirmed, with "
|
|
1335
|
+
"<code>ectype constraints FILE --confirm ID</code>.</p>")
|
|
1336
|
+
if s.suggested:
|
|
1337
|
+
rows = []
|
|
1338
|
+
for c in s.suggested:
|
|
1339
|
+
rows.append(
|
|
1340
|
+
f'<tr><td>{_e(c.id)}</td><th scope="row">'
|
|
1341
|
+
f"{_formula(_rule_text(c))}</th><td>{_e(_family_word(c.family))}</td>"
|
|
1342
|
+
f"<td>{_e(c.confidence)}</td>"
|
|
1343
|
+
f'<td class="num">{_e(fmt.count(c.support)) if c.support is not None else ""}</td>'
|
|
1344
|
+
f'<td class="num">{_e(fmt.count(c.violations)) if c.violations is not None else ""}</td></tr>')
|
|
1345
|
+
shown = ""
|
|
1346
|
+
if n_sugg > len(s.suggested):
|
|
1347
|
+
shown = (f"<p class=\"small\">Showing {fmt.count(len(s.suggested))} of "
|
|
1348
|
+
f"{fmt.count(n_sugg)}.</p>")
|
|
1349
|
+
out.append('<details class="more"><summary>The suggested rules</summary>'
|
|
1350
|
+
+ _table("Suggested rules", ("Id", "Rule", "Family", "Confidence",
|
|
1351
|
+
"Rows checked", "Rows that break it"),
|
|
1352
|
+
rows, "Suggested rules", cls="wide", num_cols=(4, 5))
|
|
1353
|
+
+ shown + "</details>")
|
|
1354
|
+
if s.not_applied or s.n_not_applied:
|
|
1355
|
+
any_part = True
|
|
1356
|
+
n_na = max(int(_f(s.n_not_applied) or 0), len(s.not_applied))
|
|
1357
|
+
out.append("<h3>Considered and turned down</h3>")
|
|
1358
|
+
items = "".join(f"<li>{_e(_sentence(x.kind) or 'Structure')}, <b>{_e(x.subject)}</b>"
|
|
1359
|
+
f"{': ' + _e(x.reason) if x.reason else ''}</li>"
|
|
1360
|
+
for x in s.not_applied)
|
|
1361
|
+
more = ""
|
|
1362
|
+
if n_na > len(s.not_applied):
|
|
1363
|
+
more = f"<p class=\"small\">Showing {fmt.count(len(s.not_applied))} of {fmt.count(n_na)}.</p>"
|
|
1364
|
+
out.append(f'<details class="more"><summary>{fmt.plural(n_na, "structure")} the engine '
|
|
1365
|
+
f'considered and did not use</summary><ul class="rules">{items}</ul>{more}'
|
|
1366
|
+
"</details>")
|
|
1367
|
+
if not any_part:
|
|
1368
|
+
out.append("<p>The engine found no rules that tie columns together in this table.</p>")
|
|
1369
|
+
return _section("structure", "Structure", "".join(out))
|
|
1370
|
+
|
|
1371
|
+
|
|
1372
|
+
# -- privacy ----------------------------------------------------------------------------------
|
|
1373
|
+
|
|
1374
|
+
_STYLES = {"indexed": "numbered tokens", "shape": "random values of the same shape"}
|
|
1375
|
+
_DONE = {
|
|
1376
|
+
"identifier": "regenerated; no value stored",
|
|
1377
|
+
"reference": "fresh keys; the pattern of repeats is kept",
|
|
1378
|
+
"excluded": "left out",
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
def _privacy(p: _Page) -> str:
|
|
1383
|
+
v = p.view
|
|
1384
|
+
pv = v.privacy
|
|
1385
|
+
out = []
|
|
1386
|
+
policy = pv.policy or v.overview.policy
|
|
1387
|
+
clauses = []
|
|
1388
|
+
mcs = _f(pv.min_category_support)
|
|
1389
|
+
if mcs is not None:
|
|
1390
|
+
clauses.append(f"a value seen in fewer than {_e(fmt.count(mcs))} rows is pooled with "
|
|
1391
|
+
"other rare values")
|
|
1392
|
+
qr = _f(pv.quantile_resolution)
|
|
1393
|
+
clip = [x for x in (_f(t) for t in pv.tail_clip or []) if x is not None]
|
|
1394
|
+
if len(clip) >= 2:
|
|
1395
|
+
lo, hi = _ordinal(100 * clip[0]), _ordinal(100 * clip[1])
|
|
1396
|
+
stored = (f"each number is stored as at most {_e(fmt.count(qr))} quantiles"
|
|
1397
|
+
if qr is not None else "each number is stored")
|
|
1398
|
+
clauses.append(f"{stored} between its {_e(lo)} and {_e(hi)} percentiles, so its "
|
|
1399
|
+
"extremes are not in the fingerprint or on this page")
|
|
1400
|
+
elif qr is not None:
|
|
1401
|
+
clauses.append(f"each number is stored as at most {_e(fmt.count(qr))} quantiles")
|
|
1402
|
+
sd = _f(pv.significant_digits)
|
|
1403
|
+
if sd is not None:
|
|
1404
|
+
clauses.append(f"stored numbers are rounded to {_e(fmt.plural(sd, 'significant digit'))}")
|
|
1405
|
+
sss = _f(pv.smallest_stored_support)
|
|
1406
|
+
if sss is not None:
|
|
1407
|
+
clauses.append(f"no group of fewer than {_e(fmt.count(sss))} rows is described on its own")
|
|
1408
|
+
items = "".join(f"<li>{_sentence(c)}.</li>" for c in clauses)
|
|
1409
|
+
if policy:
|
|
1410
|
+
lead = f"This fingerprint was fitted under the <b>{_e(policy)}</b> policy"
|
|
1411
|
+
out.append(f"<p>{lead}{'. Under it:' if clauses else '.'}</p>")
|
|
1412
|
+
if clauses:
|
|
1413
|
+
out.append(f'<ul class="rules">{items}</ul>')
|
|
1414
|
+
elif clauses:
|
|
1415
|
+
out.append(f'<p>What the fingerprint stores is limited as follows.</p>'
|
|
1416
|
+
f'<ul class="rules">{items}</ul>')
|
|
1417
|
+
else:
|
|
1418
|
+
out.append("<p>The fingerprint does not record the policy it was fitted under.</p>")
|
|
1419
|
+
if pv.sensitive:
|
|
1420
|
+
out.append('<p class="notice serious">This policy keeps finer detail than usual, and the '
|
|
1421
|
+
"fingerprint is marked sensitive. Share this page only with people who may see "
|
|
1422
|
+
"the fingerprint.</p>")
|
|
1423
|
+
|
|
1424
|
+
if pv.personal:
|
|
1425
|
+
rows = []
|
|
1426
|
+
for pc in pv.personal:
|
|
1427
|
+
if pc.handling == "pseudonym":
|
|
1428
|
+
done = "values replaced by stand-in tokens"
|
|
1429
|
+
if pc.style:
|
|
1430
|
+
done += f" ({_STYLES.get(pc.style, 'style as stored: ' + pc.style)})"
|
|
1431
|
+
else:
|
|
1432
|
+
done = _DONE.get(pc.handling, pc.handling or "not recorded")
|
|
1433
|
+
rows.append(f'<tr><th scope="row">{p.link(pc.column)}</th><td>{_e(done)}</td>'
|
|
1434
|
+
f"<td class=\"why\">{_e(fmt.truncate(pc.reason or '', 200))}</td></tr>")
|
|
1435
|
+
out.append("<h3>Columns handled specially</h3>")
|
|
1436
|
+
out.append(_table("Columns handled specially", ("Column", "What was done", "Why"),
|
|
1437
|
+
rows, "Columns handled specially", cls="special"))
|
|
1438
|
+
if pv.pooled:
|
|
1439
|
+
pooled = sorted(pv.pooled, key=lambda x: (_f(x.share) is None, -(_f(x.share) or 0.0)))
|
|
1440
|
+
rows = [f'<tr><th scope="row">{p.link(x.column)}</th>'
|
|
1441
|
+
f'<td class="num">{_e(fmt.count(x.n_pooled)) if x.n_pooled is not None else ""}</td>'
|
|
1442
|
+
f'<td class="num">{_e(fmt.share(x.share)) if _f(x.share) is not None else ""}</td></tr>'
|
|
1443
|
+
for x in pooled[:POOLED_ROWS]]
|
|
1444
|
+
out.append("<h3>Rare values pooled</h3>")
|
|
1445
|
+
out.append(_table("Rare values pooled", ("Column", "Rare values pooled",
|
|
1446
|
+
"Rows in the pooled bucket"),
|
|
1447
|
+
rows, "Rare values pooled", num_cols=(1, 2)))
|
|
1448
|
+
if len(pooled) > POOLED_ROWS:
|
|
1449
|
+
out.append(f"<p class=\"small\">And {fmt.plural(len(pooled) - POOLED_ROWS, 'more column')}.</p>")
|
|
1450
|
+
if pv.coarse_columns:
|
|
1451
|
+
out.append(f"<p>Stored as a mean and spread only, with no finer shape: "
|
|
1452
|
+
f"{p.links(pv.coarse_columns, 8)}.</p>")
|
|
1453
|
+
if pv.other_facts:
|
|
1454
|
+
out.append('<ul class="small">' + "".join(
|
|
1455
|
+
f"<li>{_e(f.label)}: {_e(_fact_value(f))}</li>" for f in pv.other_facts) + "</ul>")
|
|
1456
|
+
if pv.warnings:
|
|
1457
|
+
out.append("<h3>Warnings from the engine</h3><ul>"
|
|
1458
|
+
+ "".join(f"<li>{_e(w)}</li>" for w in pv.warnings) + "</ul>")
|
|
1459
|
+
|
|
1460
|
+
holds = ["No row of the source table is in the fingerprint or on this page."]
|
|
1461
|
+
if mcs is not None or pv.pooled:
|
|
1462
|
+
holds.append("Values seen in only a few rows are pooled, so none of them is shown.")
|
|
1463
|
+
if any(c.handling == "pseudonym" for c in v.columns) or any(
|
|
1464
|
+
x.handling == "pseudonym" for x in pv.personal):
|
|
1465
|
+
holds.append("Columns that look personal show stand-in tokens, not their values.")
|
|
1466
|
+
if any(c.handling in ("identifier", "reference") for c in v.columns) or any(
|
|
1467
|
+
x.handling in ("identifier", "reference") for x in pv.personal):
|
|
1468
|
+
holds.append("Keys are regenerated; no key value is stored.")
|
|
1469
|
+
out.append("<h3>What this does and does not mean</h3><ul>"
|
|
1470
|
+
+ "".join(f"<li>{h}</li>" for h in holds) + f"</ul><p>{LIMITS_SENTENCE}</p>")
|
|
1471
|
+
return _section("privacy", "Privacy", "".join(out))
|
|
1472
|
+
|
|
1473
|
+
|
|
1474
|
+
# -- alerts -----------------------------------------------------------------------------------
|
|
1475
|
+
|
|
1476
|
+
|
|
1477
|
+
def _alerts(p: _Page) -> str:
|
|
1478
|
+
if not p.alerts:
|
|
1479
|
+
return _section("alerts", "Alerts", "<p>Nothing flagged.</p>")
|
|
1480
|
+
acts = sum(1 for a in p.alerts if a.severity == "act")
|
|
1481
|
+
intro = (f'<p class="intro">{fmt.plural(acts, "alert")} worth acting on and '
|
|
1482
|
+
f'{fmt.plural(len(p.alerts) - acts, "note")}.</p>')
|
|
1483
|
+
rows = []
|
|
1484
|
+
for a in p.alerts:
|
|
1485
|
+
adv = p.advice(a, 8)
|
|
1486
|
+
adv_html = f'<span class="advice">{adv}</span>' if adv else ""
|
|
1487
|
+
rows.append(f"<tr><td>{_level(a)}</td><th scope=\"row\">{p.message(a, 8)}{adv_html}"
|
|
1488
|
+
"</th></tr>")
|
|
1489
|
+
return _section("alerts", "Alerts", intro + _table(
|
|
1490
|
+
"All alerts", ("Level", "What, and what to do about it"), rows, "All alerts",
|
|
1491
|
+
cls="alerts"))
|
|
1492
|
+
|
|
1493
|
+
|
|
1494
|
+
# -- how to read this page --------------------------------------------------------------------
|
|
1495
|
+
|
|
1496
|
+
#: what the page is, for a reader who has not met Ectype (plain sentences, inline HTML)
|
|
1497
|
+
_ABOUT = (
|
|
1498
|
+
"This page describes a table from its <b>fingerprint</b>: a file that Ectype fits to the "
|
|
1499
|
+
"table once. A fingerprint holds a model of each column, a model of how columns move "
|
|
1500
|
+
"together and the rules found in the table. It holds no rows, and this page was drawn "
|
|
1501
|
+
"from it without the table.",
|
|
1502
|
+
"<b>The engine</b> is the Ectype software that fitted the fingerprint. <b>The policy</b> is "
|
|
1503
|
+
"the set of limits on what a fingerprint may store, such as how many rows must share a "
|
|
1504
|
+
"value before the value is kept; see <a href=\"#privacy\">Privacy</a>. A column is "
|
|
1505
|
+
"<b>modeled</b> when the fingerprint holds a distribution fitted to it, and its chart is "
|
|
1506
|
+
"drawn from that distribution.",
|
|
1507
|
+
)
|
|
1508
|
+
|
|
1509
|
+
#: the words at the top right of a column card: how the column is stored or produced
|
|
1510
|
+
_CARD_WORDS = (
|
|
1511
|
+
("Stored quantiles, stored values, stored frequencies",
|
|
1512
|
+
"The column's distribution is kept as it was measured: evenly spaced percentiles of a "
|
|
1513
|
+
"number or date, or the share of rows of each value."),
|
|
1514
|
+
("Point masses and a curve",
|
|
1515
|
+
"A number where a few exact values hold many rows: those values are kept one by one, "
|
|
1516
|
+
"and a smooth distribution covers the rest."),
|
|
1517
|
+
("A named family (normal, gamma, Poisson …)",
|
|
1518
|
+
"The column is kept as that distribution's few parameters."),
|
|
1519
|
+
("Computed", "Not modeled on its own: worked out from other columns by the formula shown."),
|
|
1520
|
+
("Modeled as a gap",
|
|
1521
|
+
"Not modeled on its own: the distance to another column is modeled, so the two stay in "
|
|
1522
|
+
"order. The chart draws that distance."),
|
|
1523
|
+
("Share of a total, sum of its parts",
|
|
1524
|
+
"Columns bound by a sum: the total or its parts are worked out so that they add up."),
|
|
1525
|
+
("Regenerated key",
|
|
1526
|
+
"A unique identifier. Its values are not kept; generated rows get new ones of the same "
|
|
1527
|
+
"shape."),
|
|
1528
|
+
("Repeating key",
|
|
1529
|
+
"An identifier shared by several rows. How many rows share a key is modeled; the key "
|
|
1530
|
+
"values are not kept."),
|
|
1531
|
+
("Constant", "Every row holds the same value."),
|
|
1532
|
+
("Left out", "The fingerprint holds nothing of this column's values."),
|
|
1533
|
+
)
|
|
1534
|
+
|
|
1535
|
+
_DEFS = (
|
|
1536
|
+
("Empty cells", "The share of rows with no value in the column, drawn as a short rose bar."),
|
|
1537
|
+
("A histogram bar", "The share of rows whose value falls in that stretch of the axis."),
|
|
1538
|
+
("A point mass", "One exact value held by many rows (often 0), drawn as a rose line with a "
|
|
1539
|
+
"dot, apart from the bars."),
|
|
1540
|
+
("The triangle", "Marks the median: half of the values lie below it."),
|
|
1541
|
+
("Clipped axis ends", "Where the policy stops storing the tails, the axis ends; the true "
|
|
1542
|
+
"smallest and largest values are not stored."),
|
|
1543
|
+
("Log scale", "Each step along the axis multiplies the value; used for long-tailed numbers."),
|
|
1544
|
+
("Pooled rare values", "Values seen in too few rows to be stored one by one, added up into "
|
|
1545
|
+
"one bar."),
|
|
1546
|
+
("N more values", "The stored values that are not drawn one by one, added up."),
|
|
1547
|
+
("Heaps", "Values pile up on round numbers, such as multiples of 5 or 100, more than a "
|
|
1548
|
+
"smooth distribution would give."),
|
|
1549
|
+
("Tied directly to another column", "The model draws this column's value given the other "
|
|
1550
|
+
"column's value, a closer tie than the general model "
|
|
1551
|
+
"of how columns move together."),
|
|
1552
|
+
("Stand-in tokens", "Labels that replace the values of a column that looks personal; they "
|
|
1553
|
+
"keep the frequencies, not the values."),
|
|
1554
|
+
("Strength", "How closely two columns are tied, from 0 (unrelated) to 1. Rank correlation is "
|
|
1555
|
+
"used for two numbers or dates, Cramér's V for two categories, the correlation "
|
|
1556
|
+
"ratio for a number and a category."),
|
|
1557
|
+
)
|
|
1558
|
+
|
|
1559
|
+
_CANNOT = (
|
|
1560
|
+
"The rows themselves.",
|
|
1561
|
+
"The exact minimum and maximum of a number.",
|
|
1562
|
+
"Values seen in fewer rows than the policy allows.",
|
|
1563
|
+
"Any value of a column that was left out of the model.",
|
|
1564
|
+
"How three or more columns depend on each other jointly: the model holds it, the page "
|
|
1565
|
+
"states pairs.",
|
|
1566
|
+
"The distribution of a column computed from others: the page gives its rule instead.",
|
|
1567
|
+
"The measurements the fingerprint keeps sealed for checking generated data.",
|
|
1568
|
+
"Whether any single record is correct.",
|
|
1569
|
+
)
|
|
1570
|
+
|
|
1571
|
+
|
|
1572
|
+
def _unread_li(u: Unread) -> str:
|
|
1573
|
+
what = u.what or "an entry"
|
|
1574
|
+
if what == "unknown section":
|
|
1575
|
+
what = "a section this version of the report does not describe"
|
|
1576
|
+
text = f"<code>{_e(u.where or 'unknown place')}</code>: {_e(what)}"
|
|
1577
|
+
n = _f(u.entries)
|
|
1578
|
+
if n is not None:
|
|
1579
|
+
text += f": {_e(fmt.plural(n, 'entry', 'entries'))}"
|
|
1580
|
+
if u.reason:
|
|
1581
|
+
text += f". Reading it failed: {_e(fmt.truncate(u.reason, 300))}"
|
|
1582
|
+
return f"<li>{text}</li>"
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
def _reading(p: _Page) -> str:
|
|
1586
|
+
v = p.view
|
|
1587
|
+
o = v.overview
|
|
1588
|
+
out = ["<h3>What this page is</h3>"]
|
|
1589
|
+
out += [f"<p>{x}</p>" for x in _ABOUT]
|
|
1590
|
+
out.append("<h3>Reading the charts</h3><dl class=\"defs\">")
|
|
1591
|
+
out += [f"<dt>{k}</dt><dd>{d}</dd>" for k, d in _DEFS]
|
|
1592
|
+
out.append("</dl><h3>How a column is kept</h3><p class=\"small\">The words at the top "
|
|
1593
|
+
"right of a column's card.</p><dl class=\"defs\">")
|
|
1594
|
+
out += [f"<dt>{k}</dt><dd>{d}</dd>" for k, d in _CARD_WORDS]
|
|
1595
|
+
out.append("</dl><h3>What this page cannot show</h3><ul>")
|
|
1596
|
+
out += [f"<li>{x}</li>" for x in _CANNOT]
|
|
1597
|
+
out.append("</ul><h3>What this page does not describe</h3>")
|
|
1598
|
+
unread = v.all_unread()
|
|
1599
|
+
if unread:
|
|
1600
|
+
out.append("<ul>" + "".join(_unread_li(u) for u in unread) + "</ul>")
|
|
1601
|
+
for name in v.extra_sections or []:
|
|
1602
|
+
out.append(f"<p>This fingerprint also has a {_e(name)} section, which this page does not "
|
|
1603
|
+
"cover.</p>")
|
|
1604
|
+
if not unread and not v.extra_sections:
|
|
1605
|
+
out.append("<p>Everything in this fingerprint that the report reads is described "
|
|
1606
|
+
"above.</p>")
|
|
1607
|
+
|
|
1608
|
+
facts: list[tuple[str, str]] = []
|
|
1609
|
+
if o.content_id:
|
|
1610
|
+
facts.append(("Fingerprint id", o.content_id))
|
|
1611
|
+
if o.created:
|
|
1612
|
+
fitted = _fitted(o.created)
|
|
1613
|
+
facts.append(("Created", fitted if fitted == o.created else f"{fitted} ({o.created})"))
|
|
1614
|
+
if o.fit_seed is not None and _f(o.fit_seed) is not None:
|
|
1615
|
+
facts.append(("Fit seed", str(o.fit_seed)))
|
|
1616
|
+
tc, ts = _f(o.targets_calibration), _f(o.targets_sealed)
|
|
1617
|
+
if tc is not None or ts is not None:
|
|
1618
|
+
bits = []
|
|
1619
|
+
if tc is not None:
|
|
1620
|
+
bits.append(f"{fmt.count(tc)} calibration")
|
|
1621
|
+
if ts is not None:
|
|
1622
|
+
bits.append(f"{fmt.count(ts)} sealed")
|
|
1623
|
+
facts.append(("Targets", ", ".join(bits)))
|
|
1624
|
+
if o.lineage:
|
|
1625
|
+
facts.append(("Lineage", ", then ".join(str(x) for x in o.lineage)))
|
|
1626
|
+
if o.reader_engine or o.reader_format:
|
|
1627
|
+
rb = f"engine {o.reader_engine or 'not recorded'}"
|
|
1628
|
+
if o.reader_format:
|
|
1629
|
+
rb += f" (format {o.reader_format})"
|
|
1630
|
+
facts.append(("Read by", rb))
|
|
1631
|
+
facts.append(("View version", str(v.view_version)))
|
|
1632
|
+
out.append("<h3>About this fingerprint</h3><dl class=\"about\">")
|
|
1633
|
+
out += [f"<dt>{k}</dt><dd>{_e(val)}</dd>" for k, val in facts]
|
|
1634
|
+
out.append("</dl>")
|
|
1635
|
+
return _section("reading", "How to read this page", "".join(out))
|
|
1636
|
+
|
|
1637
|
+
|
|
1638
|
+
# -- the document -----------------------------------------------------------------------------
|
|
1639
|
+
|
|
1640
|
+
|
|
1641
|
+
def render(view: ReportView, *, detail: str = "full", alerts: Sequence[Alert] | None = None,
|
|
1642
|
+
title: str | None = None, notices: Sequence[str] = ()) -> str:
|
|
1643
|
+
"""The whole page as one HTML document.
|
|
1644
|
+
|
|
1645
|
+
``detail`` is one of :data:`DETAILS`: ``"full"`` column cards with charts, ``"compact"``
|
|
1646
|
+
smaller cards, ``"list"`` one table row per column. ``alerts=None`` computes them with
|
|
1647
|
+
:func:`findings.alerts`. ``notices`` are sentences shown at the top. Raises
|
|
1648
|
+
:class:`ValueError` for an unknown ``detail``; never raises on a well-typed view.
|
|
1649
|
+
"""
|
|
1650
|
+
if detail not in DETAILS:
|
|
1651
|
+
raise ValueError(f"detail must be one of {', '.join(DETAILS)}, not {detail!r}")
|
|
1652
|
+
if alerts is None:
|
|
1653
|
+
try:
|
|
1654
|
+
alerts = findings.alerts(view)
|
|
1655
|
+
except Exception: # noqa: BLE001
|
|
1656
|
+
alerts = []
|
|
1657
|
+
p = _Page(view, list(alerts), detail)
|
|
1658
|
+
name = view.overview.name if isinstance(view.overview.name, str) else ""
|
|
1659
|
+
heading = title or name or "Untitled table"
|
|
1660
|
+
page_title = title or f"{name or 'Untitled table'}: profile report"
|
|
1661
|
+
n_cols = len(view.columns)
|
|
1662
|
+
|
|
1663
|
+
rail = ['<nav class="rail" aria-label="Sections"><p class="brand">Ectype <span>profile '
|
|
1664
|
+
"report</span></p><ol>"]
|
|
1665
|
+
for sid, label in SECTIONS:
|
|
1666
|
+
count = ""
|
|
1667
|
+
if sid == "columns":
|
|
1668
|
+
count = f" <span>{fmt.count(n_cols)}</span>"
|
|
1669
|
+
elif sid == "alerts":
|
|
1670
|
+
count = f" <span>{fmt.count(len(p.alerts))}</span>"
|
|
1671
|
+
rail.append(f'<li><a href="#{sid}">{label}{count}</a></li>')
|
|
1672
|
+
rail.append("</ol></nav>")
|
|
1673
|
+
|
|
1674
|
+
sections = [
|
|
1675
|
+
_guard(lambda: _overview(p, heading, notices), "overview"),
|
|
1676
|
+
_guard(lambda: _columns(p), "section"),
|
|
1677
|
+
_guard(lambda: _relationships(p), "section"),
|
|
1678
|
+
_guard(lambda: _structure(p), "section"),
|
|
1679
|
+
_guard(lambda: _privacy(p), "section"),
|
|
1680
|
+
_guard(lambda: _alerts(p), "section"),
|
|
1681
|
+
_guard(lambda: _reading(p), "section"),
|
|
1682
|
+
]
|
|
1683
|
+
# a section that failed still carries its id and heading
|
|
1684
|
+
for i, (sid, label) in enumerate(SECTIONS):
|
|
1685
|
+
if not sections[i].startswith("<section"):
|
|
1686
|
+
head = (f'<h1 id="{sid}-h">{_e(heading)}</h1>' if sid == "overview"
|
|
1687
|
+
else f'<h2 id="{sid}-h">{label}</h2>')
|
|
1688
|
+
sections[i] = (f'<section id="{sid}" aria-labelledby="{sid}-h">{head}'
|
|
1689
|
+
f"{sections[i]}</section>")
|
|
1690
|
+
|
|
1691
|
+
return "".join([
|
|
1692
|
+
'<!doctype html><html lang="en"><head><meta charset="utf-8">'
|
|
1693
|
+
'<meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
1694
|
+
'<meta name="color-scheme" content="light dark">'
|
|
1695
|
+
'<meta name="generator" content="Ectype profile report">'
|
|
1696
|
+
f"<title>{_e(page_title)}</title><style>{CSS}</style></head><body>"
|
|
1697
|
+
'<a class="skip" href="#main">Skip to the report</a><div class="shell">',
|
|
1698
|
+
"".join(rail),
|
|
1699
|
+
'<main id="main">',
|
|
1700
|
+
"".join(sections),
|
|
1701
|
+
f"<footer><p>{FOOTER}</p></footer></main></div><script>{SCRIPT}</script></body></html>",
|
|
1702
|
+
])
|
|
1703
|
+
|
|
1704
|
+
|
|
1705
|
+
__all__ = ["DETAILS", "SECTIONS", "render"]
|