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,964 @@
1
+ """Inline SVG charts drawn from the report's view model (ADR-0016).
2
+
3
+ Standard library only. Each chart function returns one ``<svg class="chart ...">`` string with
4
+ ``role="img"``, a ``<title>`` and a ``<desc>`` (the text alternative) referenced by
5
+ ``aria-labelledby``. The SVG carries classes only, never colours or inline styles: the page's
6
+ stylesheet draws it. The one data-encoding attribute is ``fill-opacity`` on matrix cells.
7
+
8
+ Rules every function keeps:
9
+
10
+ * Every string is escaped and stripped of characters XML cannot hold; labels are truncated.
11
+ * Every number is checked: no NaN or infinity reaches the output, and coordinates carry at
12
+ most two decimals.
13
+ * **Degenerate input never raises and always gives an SVG.** When there is nothing to draw (no
14
+ bins, all shares zero, ``None``), the chart is a small SVG with its title and a ``<desc>``
15
+ that says so, and no marks. The renderer should call :func:`has_data` first and write a
16
+ sentence instead of an empty chart.
17
+ * Column charts use a viewBox 300 units wide, so their 12px text is never drawn smaller than
18
+ 12px in a card 300px wide.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import html
24
+ import math
25
+ import re
26
+ from collections.abc import Callable, Mapping, Sequence
27
+ from dataclasses import dataclass
28
+
29
+ from ectype.reporting import fmt
30
+ from ectype.reporting.view import Atom, Histogram, Level, Levels, Matrix
31
+
32
+ #: viewBox width of the column charts
33
+ WIDTH = 300
34
+ #: average advance of a 12px character, used to keep labels apart
35
+ CHAR_W = 6.6
36
+ #: the column strip's fixed viewBox
37
+ STRIP_W, STRIP_H = 1000, 54
38
+
39
+ _CONTROL = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff￾￿]")
40
+ _WHITESPACE = re.compile(r"[\t\r\n]+")
41
+ _ID_UNSAFE = re.compile(r"[^A-Za-z0-9_-]")
42
+
43
+ NO_DATA = "No distribution to draw."
44
+
45
+
46
+ @dataclass
47
+ class StripCell:
48
+ """One column of the column strip. ``present`` is the share of rows that hold a value
49
+ (``None`` when not recorded); ``state`` is ``"on"`` (modeled) or ``"off"`` (not modeled);
50
+ ``href`` is the link to the column's card (``"#col-12"``); ``flagged`` puts a dot under it.
51
+ """
52
+
53
+ name: str
54
+ present: float | None
55
+ state: str = "on"
56
+ href: str = ""
57
+ flagged: bool = False
58
+
59
+
60
+ # -- small helpers ----------------------------------------------------------------------------
61
+
62
+
63
+ def _text(s: object, limit: int | None = None) -> str:
64
+ """Untrusted text, made safe for XML content and attributes."""
65
+ t = "" if s is None else str(s)
66
+ t = _WHITESPACE.sub(" ", t)
67
+ t = _CONTROL.sub("", t)
68
+ if limit is not None:
69
+ t = fmt.truncate(t, limit)
70
+ return html.escape(t, quote=True)
71
+
72
+
73
+ _WIDE_CHARS = frozenset("MWmw@%")
74
+ _NARROW_CHARS = frozenset("iljtfrI.,:;'|!()[]{} -/")
75
+
76
+
77
+ def _fit(s: object, px: float) -> str:
78
+ """``s`` cut, with an ellipsis, to about ``px`` pixels of 12px text. Widths are estimated
79
+ by class of character (capitals and digits are wider than lower case), on the wide side, so
80
+ a label never runs into the bar beside it. Not escaped: pass the result to :func:`_text`."""
81
+ t = _CONTROL.sub("", _WHITESPACE.sub(" ", "" if s is None else str(s)))
82
+ used = 0.0
83
+ for i, ch in enumerate(t):
84
+ if ch in _WIDE_CHARS:
85
+ w = 10.8
86
+ elif ch in _NARROW_CHARS:
87
+ w = 4.2
88
+ elif ord(ch) >= 0x1100:
89
+ w = 12.5 # full-width scripts
90
+ elif ch.isupper():
91
+ w = 8.0
92
+ elif ch.isdigit():
93
+ w = 6.9
94
+ else:
95
+ w = 6.4
96
+ used += w
97
+ if used > px:
98
+ # room for the ellipsis: drop characters until it fits
99
+ cut = t[:i]
100
+ while cut and used + 9.0 - w > px:
101
+ used -= 6.9
102
+ cut = cut[:-1]
103
+ return cut.rstrip() + "…"
104
+ return t
105
+
106
+
107
+ def _pct(v: float | None) -> str:
108
+ """A share for markup ("<0.1%" must be escaped)."""
109
+ return html.escape(fmt.share(v))
110
+
111
+
112
+ def _n(v: float) -> str:
113
+ """A coordinate: finite, at most two decimals, no ``-0``."""
114
+ try:
115
+ x = float(v)
116
+ except (TypeError, ValueError):
117
+ x = 0.0
118
+ if not math.isfinite(x):
119
+ x = 0.0
120
+ s = f"{x:.2f}".rstrip("0").rstrip(".")
121
+ return "0" if s in ("-0", "", "-") else s
122
+
123
+
124
+ def _f(v: object) -> float | None:
125
+ if v is None:
126
+ return None
127
+ try:
128
+ x = float(v) # type: ignore[arg-type]
129
+ except (TypeError, ValueError, OverflowError):
130
+ return None
131
+ return x if math.isfinite(x) else None
132
+
133
+
134
+ def _share(v: object) -> float:
135
+ """A share in [0, 1]; anything else is 0."""
136
+ x = _f(v)
137
+ return 0.0 if x is None else min(max(x, 0.0), 1.0)
138
+
139
+
140
+ def _uid(uid: str) -> str:
141
+ return _ID_UNSAFE.sub("-", str(uid)) or "chart"
142
+
143
+
144
+ def _open(uid: str, cls: str, w: float, h: float, title: str, desc: str,
145
+ extra: str = "") -> str:
146
+ u = _uid(uid)
147
+ return (f'<svg class="chart {cls}" viewBox="0 0 {_n(w)} {_n(h)}"{extra} role="img" '
148
+ f'aria-labelledby="{u}-t {u}-d"><title id="{u}-t">{_text(title, 300)}</title>'
149
+ f'<desc id="{u}-d">{_text(desc, 1200)}</desc>')
150
+
151
+
152
+ def _empty(uid: str, cls: str, title: str, desc: str = NO_DATA) -> str:
153
+ return _open(uid, cls, WIDTH, 24, title, desc) + "</svg>"
154
+
155
+
156
+ def _fits(text: str, width: float) -> bool:
157
+ return len(text) * CHAR_W <= width
158
+
159
+
160
+ # -- histograms -------------------------------------------------------------------------------
161
+
162
+
163
+ @dataclass
164
+ class _Hist:
165
+ """A histogram checked and cleaned: finite edges, non-negative shares, valid atoms."""
166
+
167
+ edges: list[float]
168
+ shares: list[float]
169
+ log: bool
170
+ atoms: list[Atom]
171
+ median: float | None
172
+
173
+
174
+ def _clean_hist(h: Histogram, compact: bool) -> _Hist:
175
+ edges = [_f(e) for e in (h.edges or [])]
176
+ shares = [_share(s) for s in (h.shares or [])]
177
+ n = min(len(edges) - 1, len(shares)) if edges else 0
178
+ good: list[float] = []
179
+ out_shares: list[float] = []
180
+ if n > 0 and all(e is not None for e in edges[: n + 1]):
181
+ good = [float(e) for e in edges[: n + 1] if e is not None]
182
+ if any(b < a for a, b in zip(good, good[1:], strict=False)):
183
+ good = []
184
+ else:
185
+ out_shares = shares[:n]
186
+ log = h.scale == "log" and bool(good) and good[0] > 0
187
+ if compact and len(out_shares) > 1:
188
+ merged_edges = good[0::2]
189
+ if len(out_shares) % 2:
190
+ merged_edges.append(good[-1])
191
+ out_shares = [sum(out_shares[i:i + 2]) for i in range(0, len(out_shares), 2)]
192
+ good = merged_edges
193
+ if not good:
194
+ out_shares = []
195
+ atoms = []
196
+ for a in h.atoms or []:
197
+ v, s = _f(getattr(a, "value", None)), _share(getattr(a, "share", 0.0))
198
+ if v is not None and s > 0:
199
+ atoms.append(Atom(value=v, share=s))
200
+ return _Hist(good, out_shares, log, atoms, _quantile(h, 0.5))
201
+
202
+
203
+ def _quantile(h: Histogram, p: float) -> float | None:
204
+ for q in h.quantiles or []:
205
+ try:
206
+ qp, qv = _f(q[0]), _f(q[1])
207
+ except (IndexError, TypeError, KeyError):
208
+ continue
209
+ if qp is not None and qv is not None and abs(qp - p) < 1e-6:
210
+ return qv
211
+ return None
212
+
213
+
214
+ def has_data(chart: Histogram | Levels | None) -> bool:
215
+ """Whether :func:`histogram` or :func:`levels` would draw any mark for ``chart``."""
216
+ if chart is None:
217
+ return False
218
+ if isinstance(chart, Histogram):
219
+ c = _clean_hist(chart, False)
220
+ return any(s > 0 for s in c.shares) or bool(c.atoms)
221
+ if isinstance(chart, Levels):
222
+ return any(_share(b.share) > 0 for b in chart.bars or [])
223
+ return False
224
+
225
+
226
+ def _span(h: Histogram) -> float | None:
227
+ vals = [v for v in (_f(e) for e in h.edges or []) if v is not None]
228
+ vals += [v for v in (_f(q[1]) for q in h.quantiles or [] if len(q) > 1) if v is not None]
229
+ return max(vals) - min(vals) if vals else None
230
+
231
+
232
+ def _formatter(h: Histogram) -> Callable[[float | None], str]:
233
+ span = _span(h)
234
+ axis, unit = h.axis or "number", h.unit or ""
235
+ return lambda v: fmt.axis_value(v, axis, unit, span=span)
236
+
237
+
238
+ def describe_histogram(h: Histogram | None) -> str:
239
+ """One or two plain sentences describing the distribution: the median, the middle half,
240
+ the tails, the point masses. Used as the chart's ``<desc>``."""
241
+ if h is None:
242
+ return NO_DATA
243
+ c = _clean_hist(h, False)
244
+ f = _formatter(h)
245
+ q = {p: _quantile(h, p) for p in (0.05, 0.25, 0.5, 0.75, 0.95)}
246
+ parts: list[str] = []
247
+ if q[0.5] is not None:
248
+ parts.append(f"Median {f(q[0.5])}")
249
+ if q[0.25] is not None and q[0.75] is not None:
250
+ parts.append(f"middle half from {f(q[0.25])} to {f(q[0.75])}")
251
+ if q[0.05] is not None and q[0.95] is not None:
252
+ parts.append(f"5% below {f(q[0.05])} and 5% above {f(q[0.95])}")
253
+ sentences = []
254
+ if parts:
255
+ sentences.append("; ".join(parts) + ".")
256
+ elif c.edges and any(s > 0 for s in c.shares):
257
+ sentences.append(f"Values from {f(c.edges[0])} to {f(c.edges[-1])}.")
258
+ if c.atoms:
259
+ top = sorted(c.atoms, key=lambda a: -a.share)[:3]
260
+ bits = [f"{fmt.share(a.share)} {'of values are ' if i == 0 else ''}exactly {f(a.value)}"
261
+ for i, a in enumerate(top)]
262
+ sentences.append(fmt.join(bits, 3) + ".")
263
+ extra = []
264
+ if c.log:
265
+ extra.append("drawn on a log scale")
266
+ if h.clipped:
267
+ extra.append("the axis ends at the policy's clip points")
268
+ if extra and sentences:
269
+ sentences.append(extra[0][0].upper() + "; ".join(extra)[1:] + ".")
270
+ return " ".join(sentences) if sentences else NO_DATA
271
+
272
+
273
+ def histogram(h: Histogram | None, *, uid: str, title: str, compact: bool = False,
274
+ second: Histogram | None = None) -> str:
275
+ """Bars for the binned part, rose lollipops (``atom``) for point masses, a triangle under
276
+ the axis at the median and the two axis ends labelled.
277
+
278
+ With ``second`` the two distributions share one x range: the first as bars, the second as
279
+ a stepped outline (``second``) with its point masses as ``atom second``. ``compact`` merges
280
+ pairs of bins, lowers the chart and drops the labels inside it. Without data: a small SVG
281
+ with title and description and no marks (see :func:`has_data`).
282
+ """
283
+ if h is None and second is not None:
284
+ h, second = second, None
285
+ if h is None or not (has_data(h) or (second is not None and has_data(second))):
286
+ return _empty(uid, "hist", title)
287
+ a = _clean_hist(h, compact)
288
+ b = _clean_hist(second, compact) if second is not None else None
289
+ log = a.log and (b is None or b.log or not b.edges)
290
+
291
+ def tr(v: float) -> float | None:
292
+ if log:
293
+ return math.log10(v) if v > 0 else None
294
+ return v
295
+
296
+ # x domain (transformed): edges and atoms of both
297
+ dom: list[float] = []
298
+ zero_slot = False
299
+ for c in (a, b):
300
+ if c is None:
301
+ continue
302
+ for v in [*(c.edges[:1] + c.edges[-1:]), *(x.value for x in c.atoms)]:
303
+ t = tr(v)
304
+ if t is None:
305
+ zero_slot = True
306
+ elif math.isfinite(t):
307
+ dom.append(t)
308
+ if not dom:
309
+ dom = [0.0, 1.0]
310
+ lo, hi = min(dom), max(dom)
311
+ if hi - lo <= 0 or not math.isfinite(hi - lo):
312
+ pad = 1.0 if log else max(abs(lo) * 0.1, 1.0)
313
+ lo, hi = lo - pad, hi + pad
314
+
315
+ pad_x = 6.0
316
+ slot = 18.0 if zero_slot else 0.0
317
+ x0, x1 = pad_x + slot, WIDTH - pad_x
318
+ if compact:
319
+ top_y, ph = 6.0, 40.0
320
+ else:
321
+ top_y, ph = (18.0 if a.atoms or (b and b.atoms) else 6.0), 64.0
322
+ base = top_y + ph
323
+ tick_y = base + (20.0 if compact else 22.0)
324
+ height = tick_y + 4.0
325
+
326
+ def X(v: float) -> float:
327
+ t = tr(v)
328
+ if t is None:
329
+ return pad_x + slot / 2
330
+ return x0 + (x1 - x0) * (t - lo) / (hi - lo)
331
+
332
+ def heights(c: _Hist) -> list[float]:
333
+ """Share per bin, rescaled to the first histogram's bin width so that bins of
334
+ different widths compare (equal to the shares when there is one histogram)."""
335
+ if not c.shares:
336
+ return []
337
+ ref_edges = a.edges if a.edges else c.edges
338
+ ref = ((tr(ref_edges[-1]) or 0.0) - (tr(ref_edges[0]) or 0.0)) / max(len(ref_edges) - 1, 1)
339
+ out = []
340
+ for i, s in enumerate(c.shares):
341
+ ta, tb = tr(c.edges[i]), tr(c.edges[i + 1])
342
+ w = (tb - ta) if ta is not None and tb is not None else 0.0
343
+ out.append(s * ref / w if w > 0 and ref > 0 else s)
344
+ return out
345
+
346
+ ha = heights(a)
347
+ hb = heights(b) if b is not None else []
348
+ peak = max([*ha, *hb, *(x.share for x in a.atoms), *((x.share for x in b.atoms) if b else [])],
349
+ default=0.0)
350
+ if peak <= 0:
351
+ peak = 1.0
352
+
353
+ f = _formatter(h)
354
+ desc = describe_histogram(h)
355
+ if second is not None:
356
+ desc = f"First: {desc} Second: {describe_histogram(second)}"
357
+ out = [_open(uid, "hist" + (" compact" if compact else ""), WIDTH, height, title, desc)]
358
+ out.append(f'<line class="axis" x1="{_n(pad_x)}" x2="{_n(x1)}" '
359
+ f'y1="{_n(base + 0.5)}" y2="{_n(base + 0.5)}"/>')
360
+
361
+ # bars of the first
362
+ for i, s in enumerate(a.shares):
363
+ if s <= 0:
364
+ continue
365
+ xa, xb = X(a.edges[i]), X(a.edges[i + 1])
366
+ gap = 1.5 if xb - xa > 3 else 0.0
367
+ w = max(xb - xa - gap, 0.6)
368
+ bh = max(ph * ha[i] / peak, 1.0) # every non-empty bin stays visible
369
+ rx = min(1.5, w / 2)
370
+ out.append(f'<rect class="bar" x="{_n(xa + gap / 2)}" y="{_n(base - bh)}" '
371
+ f'width="{_n(w)}" height="{_n(bh)}" rx="{_n(rx)}"><title>'
372
+ f'{_text(f(a.edges[i]))} to {_text(f(a.edges[i + 1]))}: {_pct(s)}'
373
+ f'</title></rect>')
374
+
375
+ # stepped outline of the second
376
+ if b is not None and b.shares:
377
+ d = [f"M{_n(X(b.edges[0]))} {_n(base)}"]
378
+ for i, s in enumerate(b.shares):
379
+ y = base - (ph * hb[i] / peak if s > 0 else 0.0)
380
+ d.append(f"V{_n(y)}H{_n(X(b.edges[i + 1]))}")
381
+ d.append(f"V{_n(base)}")
382
+ out.append(f'<path class="second" d="{"".join(d)}"><title>second: '
383
+ f'{_text(f(b.edges[0]))} to {_text(f(b.edges[-1]))}</title></path>')
384
+
385
+ # point masses
386
+ r = 3.0 if compact else 3.5
387
+ for c, cls in ((a, "atom"), (b, "atom second")):
388
+ if c is None:
389
+ continue
390
+ for at in c.atoms:
391
+ ax = X(at.value)
392
+ ah = max(ph * at.share / peak, 3.0)
393
+ out.append(f'<g class="{cls}"><title>exactly {_text(f(at.value))}: '
394
+ f'{_pct(at.share)}</title><line x1="{_n(ax)}" x2="{_n(ax)}" '
395
+ f'y1="{_n(base)}" y2="{_n(base - ah)}"/><circle cx="{_n(ax)}" '
396
+ f'cy="{_n(base - ah)}" r="{_n(r)}"/></g>')
397
+ if a.atoms and not compact:
398
+ big = max(a.atoms, key=lambda x: x.share)
399
+ ax = X(big.value)
400
+ label = f"exactly {f(big.value)}: {fmt.share(big.share)}"
401
+ anchor = "start" if ax < WIDTH / 2 else "end"
402
+ lx = ax - 4 if anchor == "start" else ax + 4
403
+ out.append(f'<text class="lab atom-lab" x="{_n(lx)}" y="12" text-anchor="{anchor}">'
404
+ f'{_text(label, 40)}</text>')
405
+
406
+ # medians
407
+ for c, cls in ((a, "median"), (b, "median second")):
408
+ if c is None or c.median is None:
409
+ continue
410
+ mx = min(max(X(c.median), pad_x), x1)
411
+ out.append(f'<path class="{cls}" d="M{_n(mx)} {_n(base + 2)}l-3.5 6h7z"><title>median '
412
+ f'{_text(f(c.median))}</title></path>')
413
+
414
+ # axis ends, scale note, median value
415
+ lo_v = (10 ** lo) if log else lo
416
+ hi_v = (10 ** hi) if log else hi
417
+ left, right = f(lo_v), f(hi_v)
418
+ if zero_slot:
419
+ out.append(f'<text class="tick" x="{_n(pad_x + slot / 2 - 2)}" y="{_n(tick_y)}" '
420
+ f'text-anchor="middle">{_text(f(0.0))}</text>')
421
+ out.append(f'<text class="tick" x="{_n(x0)}" y="{_n(tick_y)}">{_text(left, 24)}</text>')
422
+ out.append(f'<text class="tick" x="{_n(x1)}" y="{_n(tick_y)}" text-anchor="end">'
423
+ f'{_text(right, 24)}</text>')
424
+ used_l = x0 + len(left) * CHAR_W
425
+ used_r = x1 - len(right) * CHAR_W
426
+ if log:
427
+ note = "log scale"
428
+ cx = (used_l + used_r) / 2
429
+ if not compact and _fits(note, used_r - used_l - 12):
430
+ out.append(f'<text class="tick" x="{_n(cx)}" y="{_n(tick_y)}" '
431
+ f'text-anchor="middle">{note}</text>')
432
+ elif not compact and a.median is not None and b is None:
433
+ med = f"median {f(a.median)}"
434
+ wm = len(med) * CHAR_W
435
+ mx = min(max(X(a.median), used_l + 8 + wm / 2), used_r - 8 - wm / 2)
436
+ if used_r - used_l - 16 >= wm and abs(mx - X(a.median)) < 40:
437
+ out.append(f'<text class="tick med" x="{_n(mx)}" y="{_n(tick_y)}" '
438
+ f'text-anchor="middle">{_text(med, 30)}</text>')
439
+ out.append("</svg>")
440
+ return "".join(out)
441
+
442
+
443
+ # -- levels -----------------------------------------------------------------------------------
444
+
445
+
446
+ def _fold(l: Levels, max_bars: int, compact: bool) -> list[Level]: # noqa: E741
447
+ """The bars to draw: at most ``max_bars`` levels (4 bars in all when compact), the surplus
448
+ added to the rest bar, the pooled bar last."""
449
+ plain: list[Level] = []
450
+ rest: Level | None = None
451
+ pooled: Level | None = None
452
+ for bar in l.bars or []:
453
+ s = _share(bar.share)
454
+ if bar.kind == "rest":
455
+ if rest is None:
456
+ rest = Level(label=bar.label, share=s, kind="rest", count=bar.count)
457
+ else:
458
+ rest.share += s
459
+ rest.count = (rest.count + bar.count
460
+ if rest.count is not None and bar.count is not None else None)
461
+ elif bar.kind == "pooled":
462
+ if pooled is None:
463
+ pooled = Level(label=bar.label, share=s, kind="pooled", count=bar.count)
464
+ else:
465
+ pooled.share += s
466
+ else:
467
+ plain.append(Level(label=bar.label, share=s, kind="level", count=bar.count))
468
+ limit = max(1, int(max_bars))
469
+ if compact:
470
+ room = 4 - (1 if pooled else 0)
471
+ needs_rest = rest is not None or len(plain) > room
472
+ limit = max(1, min(limit, room - (1 if needs_rest else 0)))
473
+ if len(plain) > limit:
474
+ order = sorted(range(len(plain)), key=lambda i: -plain[i].share)
475
+ keep = set(order[:limit])
476
+ surplus = [plain[i] for i in range(len(plain)) if i not in keep]
477
+ kept = [plain[i] for i in range(len(plain)) if i in keep]
478
+ if not l.ordered:
479
+ kept.sort(key=lambda x: -x.share)
480
+ add = sum(x.share for x in surplus)
481
+ if rest is None:
482
+ rest = Level(label="", share=add, kind="rest", count=len(surplus))
483
+ else:
484
+ rest.share += add
485
+ rest.count = rest.count + len(surplus) if rest.count is not None else None
486
+ plain = kept
487
+ elif not l.ordered:
488
+ plain.sort(key=lambda x: -x.share)
489
+ bars = list(plain)
490
+ if rest is not None:
491
+ if rest.count is None and l.n_levels is not None:
492
+ n = int(l.n_levels) - len(plain)
493
+ rest.count = n if n > 0 else None
494
+ rest.label = (fmt.plural(rest.count, "more value") if rest.count
495
+ else (rest.label or "other values"))
496
+ bars.append(rest)
497
+ if pooled is not None:
498
+ pooled.label = "pooled rare values"
499
+ bars.append(pooled)
500
+ return bars
501
+
502
+
503
+ def describe_levels(l: Levels | None) -> str: # noqa: E741
504
+ """One sentence listing the largest values and their shares, then the rest and the pooled
505
+ rare values: ``"CCNH 94%, CCNH/RHNS 5.1%, RHNS 0.5%; 1 rare value pooled (0.4%)."``"""
506
+ if l is None or not has_data(l):
507
+ return NO_DATA
508
+ bars = _fold(l, 8, False)
509
+ plain = [b for b in bars if b.kind == "level"]
510
+ shown, hidden = plain[:5], plain[5:]
511
+ bits = [f"{fmt.truncate(b.label, 40)} {fmt.share(b.share)}" for b in shown]
512
+ rest = next((b for b in bars if b.kind == "rest"), None)
513
+ if rest is not None or hidden:
514
+ more = len(hidden) + ((rest.count or 0) if rest is not None else 0)
515
+ other = sum(b.share for b in hidden) + (rest.share if rest is not None else 0.0)
516
+ what = fmt.plural(more, "other value") if more else "other values"
517
+ bits.append(f"{what} {fmt.share(other)}")
518
+ text = ", ".join(bits)
519
+ pooled = next((b for b in bars if b.kind == "pooled"), None)
520
+ if pooled is not None:
521
+ n = l.n_pooled
522
+ what = f"{fmt.plural(n, 'rare value')} pooled" if n else "rare values pooled"
523
+ text = f"{text}; {what}" if text else what[0].upper() + what[1:]
524
+ text += f" ({fmt.share(pooled.share)})"
525
+ note = " The labels are stand-in tokens." if l.stand_ins else ""
526
+ return text + "." + note
527
+
528
+
529
+ def levels(l: Levels | None, *, uid: str, title: str, max_bars: int = 8, # noqa: E741
530
+ compact: bool = False) -> str:
531
+ """Horizontal bars, largest first (or in value order when ``ordered``): the label on the
532
+ left, the share right of the bar. Levels beyond ``max_bars`` are added to the ``rest`` bar;
533
+ the ``pooled`` bar is always last. ``compact`` draws at most four bars. Without data: a
534
+ small SVG with title and description and no marks (see :func:`has_data`)."""
535
+ if l is None or not has_data(l):
536
+ return _empty(uid, "levels", title)
537
+ bars = _fold(l, max_bars, compact)
538
+ row = 18.0 if compact else 20.0
539
+ label_w = 118.0
540
+ bx = label_w + 6
541
+ bw = WIDTH - bx - 44
542
+ height = len(bars) * row + 4
543
+ peak = max((b.share for b in bars), default=0.0) or 1.0
544
+ out = [_open(uid, "levels" + (" compact" if compact else ""), WIDTH, height, title,
545
+ describe_levels(l))]
546
+ for i, b in enumerate(bars):
547
+ y = 2 + i * row
548
+ kind = "" if b.kind == "level" else f" {b.kind}"
549
+ tip = f"{b.label}: {fmt.share(b.share)}"
550
+ if b.kind == "pooled" and l.n_pooled:
551
+ tip = f"pooled rare values ({fmt.plural(l.n_pooled, 'source value')}): " \
552
+ f"{fmt.share(b.share)}"
553
+ out.append(f"<g><title>{_text(tip, 300)}</title>")
554
+ out.append(f'<text class="lab{kind}" x="0" y="{_n(y + 12)}">'
555
+ f'{_text(_fit(b.label, label_w))}</text>')
556
+ w = bw * b.share / peak
557
+ if b.share > 0:
558
+ w = max(w, 1.5)
559
+ out.append(f'<rect class="bar{kind}" x="{_n(bx)}" y="{_n(y + 3)}" width="{_n(w)}" '
560
+ f'height="12" rx="2"/>')
561
+ out.append(f'<text class="val" x="{_n(bx + w + 5)}" y="{_n(y + 13)}">'
562
+ f'{_pct(b.share)}</text></g>')
563
+ out.append("</svg>")
564
+ return "".join(out)
565
+
566
+
567
+ # -- two label distributions ------------------------------------------------------------------
568
+
569
+
570
+ @dataclass
571
+ class _Side:
572
+ """One side of :func:`levels_pair`: plain levels by label, the rest and the pooled bucket."""
573
+
574
+ shares: dict[str, float]
575
+ order: list[str]
576
+ rest: float
577
+ rest_count: int | None
578
+ pooled: float | None
579
+ n_pooled: int | None
580
+ stand_ins: bool
581
+ ordered: bool
582
+
583
+
584
+ def _side(l: Levels | None) -> _Side | None: # noqa: E741
585
+ if l is None or not has_data(l):
586
+ return None
587
+ shares: dict[str, float] = {}
588
+ order: list[str] = []
589
+ rest, rest_count, pooled = 0.0, 0, None
590
+ counted = True
591
+ for bar in l.bars or []:
592
+ s = _share(bar.share)
593
+ if bar.kind == "rest":
594
+ rest += s
595
+ if bar.count is None:
596
+ counted = False
597
+ else:
598
+ rest_count += max(int(bar.count), 0)
599
+ elif bar.kind == "pooled":
600
+ pooled = (pooled or 0.0) + s
601
+ else:
602
+ label = "" if bar.label is None else str(bar.label)
603
+ if label not in shares:
604
+ order.append(label)
605
+ shares[label] = 0.0
606
+ shares[label] += s
607
+ if rest > 0 and not counted and l.n_levels is not None:
608
+ n = int(l.n_levels) - len(shares)
609
+ rest_count, counted = (n, True) if n > 0 else (0, False)
610
+ return _Side(shares, order, rest, rest_count if counted and rest > 0 else None, pooled,
611
+ l.n_pooled, bool(l.stand_ins), bool(l.ordered))
612
+
613
+
614
+ def _as_profile(s: _Side | None) -> _Side | None:
615
+ """Stand-in labels are not comparable between two fingerprints: the side as its sorted
616
+ share profile, labelled by rank."""
617
+ if s is None:
618
+ return None
619
+ vals = sorted(s.shares.values(), reverse=True)
620
+ labels = [f"rank {i + 1}" for i in range(len(vals))]
621
+ return _Side(dict(zip(labels, vals, strict=True)), labels, s.rest, s.rest_count, s.pooled,
622
+ s.n_pooled, s.stand_ins, True)
623
+
624
+
625
+ def _pair_rows(a: _Side | None, b: _Side | None, max_bars: int
626
+ ) -> list[tuple[str, str, float | None, float | None]]:
627
+ """``(kind, label, share in a, share in b)`` rows: the largest labels, the rest, pooled."""
628
+ labels: list[str] = []
629
+ seen: set[str] = set()
630
+ for s in (a, b):
631
+ for lab in s.order if s is not None else []:
632
+ if lab not in seen:
633
+ seen.add(lab)
634
+ labels.append(lab)
635
+
636
+ def get(s: _Side | None, lab: str) -> float | None:
637
+ return None if s is None else s.shares.get(lab)
638
+
639
+ both_ordered = all(s is None or s.ordered for s in (a, b))
640
+ pos = {lab: i for i, lab in enumerate(labels)}
641
+ by_size = sorted(labels, key=lambda x: (-max(get(a, x) or 0.0, get(b, x) or 0.0), pos[x]))
642
+ limit = max(1, int(max_bars))
643
+ keep = set(by_size[:limit])
644
+ shown = [x for x in (labels if both_ordered else by_size) if x in keep]
645
+ hidden = [x for x in labels if x not in keep]
646
+ rows: list[tuple[str, str, float | None, float | None]] = [
647
+ ("level", lab, get(a, lab), get(b, lab)) for lab in shown]
648
+ rest_a = None if a is None else a.rest + sum(get(a, x) or 0.0 for x in hidden)
649
+ rest_b = None if b is None else b.rest + sum(get(b, x) or 0.0 for x in hidden)
650
+ if hidden or (rest_a or 0.0) > 0 or (rest_b or 0.0) > 0:
651
+ extra = max((s.rest_count or 0) if s is not None else 0 for s in (a, b))
652
+ n = len(hidden) + extra
653
+ label = fmt.plural(n, "more value") if n else "other values"
654
+ rows.append(("rest", label, rest_a, rest_b))
655
+ if (a is not None and a.pooled is not None) or (b is not None and b.pooled is not None):
656
+ rows.append(("pooled", "pooled rare values",
657
+ None if a is None else (a.pooled or 0.0),
658
+ None if b is None else (b.pooled or 0.0)))
659
+ return rows
660
+
661
+
662
+ def describe_levels_pair(a: Levels | None, b: Levels | None) -> str:
663
+ """The text alternative of :func:`levels_pair`: the three largest differences in words."""
664
+ sa, sb = _side(a), _side(b)
665
+ if sa is None and sb is None:
666
+ return NO_DATA
667
+ profile = (sa is not None and sa.stand_ins) or (sb is not None and sb.stand_ins)
668
+ if profile:
669
+ sa, sb = _as_profile(sa), _as_profile(sb)
670
+ rows = _pair_rows(sa, sb, 10 ** 6)
671
+ lead = ""
672
+ if profile:
673
+ lead = ("The labels are stand-in tokens, assigned independently in each fingerprint, so "
674
+ "the two are compared by rank: the most common value of each, then the second "
675
+ "most common, and so on. ")
676
+ if sa is None or sb is None:
677
+ only = "first" if sb is None else "second"
678
+ return lead + f"Only the {only} fingerprint has values for this column."
679
+ diffs = sorted(((abs((x or 0.0) - (y or 0.0)), lab, x, y) for _, lab, x, y in rows
680
+ if (x or 0.0) != (y or 0.0)), key=lambda t: -t[0])
681
+ if not diffs:
682
+ return lead + "The two distributions hold the same shares."
683
+ bits = []
684
+ for _, lab, x, y in diffs[:3]:
685
+ fx = fmt.share(x) if x is not None else "none"
686
+ fy = fmt.share(y) if y is not None else "none"
687
+ bits.append(f"{fmt.truncate(lab, 40)} {fx} in the first and {fy} in the second")
688
+ return lead + "Largest differences: " + "; ".join(bits) + "."
689
+
690
+
691
+ def levels_pair(a: Levels | None, b: Levels | None, *, uid: str, title: str, max_bars: int = 8,
692
+ compact: bool = False) -> str:
693
+ """Two label distributions on one chart: per label (the union of the two, ordered by the
694
+ larger of its two shares, at most ``max_bars``; then the rest, then the pooled bucket) two
695
+ thin bars, the first's filled (``bar``), the second's outlined (``bar second``), each with
696
+ its share after it; "–" for a side without the label. With stand-in tokens on either side
697
+ the labels are not comparable and the two sorted share profiles are drawn instead (rank 1,
698
+ 2, 3, ...). Without data: a small SVG with title and description and no marks."""
699
+ sa, sb = _side(a), _side(b)
700
+ if sa is None and sb is None:
701
+ return _empty(uid, "levels pair", title)
702
+ if (sa is not None and sa.stand_ins) or (sb is not None and sb.stand_ins):
703
+ sa, sb = _as_profile(sa), _as_profile(sb)
704
+ rows = _pair_rows(sa, sb, 3 if compact else max_bars)
705
+ bar_h = 7.0 if compact else 8.0
706
+ row = 30.0 if compact else 34.0
707
+ label_w = 118.0
708
+ bx = label_w + 6
709
+ bw = WIDTH - bx - 44
710
+ height = len(rows) * row + 2
711
+ peak = max((v for _, _, x, y in rows for v in (x, y) if v is not None), default=0.0) or 1.0
712
+ out = [_open(uid, "levels pair" + (" compact" if compact else ""), WIDTH, height, title,
713
+ describe_levels_pair(a, b))]
714
+ for i, (kind, label, x, y) in enumerate(rows):
715
+ top = 1 + i * row
716
+ k = "" if kind == "level" else f" {kind}"
717
+ tip = (f"{label}: first {fmt.share(x) if x is not None else '–'}, "
718
+ f"second {fmt.share(y) if y is not None else '–'}")
719
+ out.append(f"<g><title>{_text(tip, 300)}</title>")
720
+ out.append(f'<text class="lab{k}" x="0" y="{_n(top + row / 2 + 3)}">'
721
+ f'{_text(_fit(label, label_w))}</text>')
722
+ for j, (v, cls, vcls) in enumerate(((x, "bar", "val"), (y, "bar second", "val v2"))):
723
+ by = top + 4 + j * (bar_h + 7)
724
+ if v is None:
725
+ out.append(f'<text class="{vcls}" x="{_n(bx)}" y="{_n(by + bar_h)}">–</text>')
726
+ continue
727
+ w = bw * v / peak
728
+ if v > 0:
729
+ w = max(w, 1.5)
730
+ out.append(f'<rect class="{cls}{k}" x="{_n(bx)}" y="{_n(by)}" width="{_n(w)}" '
731
+ f'height="{_n(bar_h)}" rx="1.5"/>')
732
+ out.append(f'<text class="{vcls}" x="{_n(bx + w + 5)}" y="{_n(by + bar_h)}">'
733
+ f'{_pct(v)}</text>')
734
+ out.append("</g>")
735
+ out.append("</svg>")
736
+ return "".join(out)
737
+
738
+
739
+ # -- weekdays ---------------------------------------------------------------------------------
740
+
741
+ _DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
742
+ _DAY_NAMES = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
743
+
744
+
745
+ def weekdays(shares: Sequence[float] | None, *, uid: str, title: str) -> str:
746
+ """Seven vertical bars, Monday first, the largest and smallest labelled with their share.
747
+ Anything but seven numbers with a positive total gives the empty chart."""
748
+ vals = [_share(s) for s in (shares or [])]
749
+ if len(vals) != 7 or sum(vals) <= 0:
750
+ return _empty(uid, "weekdays", title, "No weekday pattern to draw.")
751
+ hi_i = max(range(7), key=lambda i: vals[i])
752
+ lo_i = min(range(7), key=lambda i: vals[i])
753
+ desc = (f"Most rows on {_DAY_NAMES[hi_i]} ({fmt.share(vals[hi_i])}), fewest on "
754
+ f"{_DAY_NAMES[lo_i]} ({fmt.share(vals[lo_i])}).")
755
+ top_y, ph = 18.0, 56.0
756
+ base = top_y + ph
757
+ height = base + 20
758
+ slot = WIDTH / 7
759
+ bw = 18.0
760
+ peak = max(vals)
761
+ out = [_open(uid, "weekdays", WIDTH, height, title, desc)]
762
+ out.append(f'<line class="axis" x1="0" x2="{WIDTH}" y1="{_n(base + 0.5)}" '
763
+ f'y2="{_n(base + 0.5)}"/>')
764
+ for i, s in enumerate(vals):
765
+ cx = slot * i + slot / 2
766
+ bh = max(ph * s / peak, 1.0) if s > 0 else 0.0
767
+ out.append(f"<g><title>{_DAY_NAMES[i]}: {_pct(s)}</title>")
768
+ if bh:
769
+ out.append(f'<rect class="bar" x="{_n(cx - bw / 2)}" y="{_n(base - bh)}" '
770
+ f'width="{_n(bw)}" height="{_n(bh)}" rx="2"/>')
771
+ if i in (hi_i, lo_i):
772
+ out.append(f'<text class="val" x="{_n(cx)}" y="{_n(base - bh - 4)}" '
773
+ f'text-anchor="middle">{_pct(s)}</text>')
774
+ out.append(f'<text class="tick" x="{_n(cx)}" y="{_n(base + 16)}" '
775
+ f'text-anchor="middle">{_DAYS[i]}</text></g>')
776
+ out.append("</svg>")
777
+ return "".join(out)
778
+
779
+
780
+ # -- matrix -----------------------------------------------------------------------------------
781
+
782
+ #: largest viewBox width of the matrix (narrower when it has few columns)
783
+ MATRIX_W = 600
784
+ MATRIX_MAX = 24
785
+ _LABEL_CHARS = 18
786
+
787
+
788
+ def _href(hrefs: Mapping[str, str] | None, name: str) -> str | None:
789
+ if not hrefs:
790
+ return None
791
+ h = hrefs.get(name)
792
+ return h if isinstance(h, str) and h.startswith("#") else None
793
+
794
+
795
+ def matrix(m: Matrix | None, *, uid: str, title: str,
796
+ hrefs: Mapping[str, str] | None = None) -> str:
797
+ """The lower triangle of a symmetric matrix of association strengths: one ``cell`` per
798
+ pair, its ``fill-opacity`` one of five steps of the strength (the stylesheet sets the hue);
799
+ a strength that is not a number is a ``cell none``. Row labels on the left, column labels
800
+ along the bottom at 45 degrees, linked when ``hrefs`` gives an anchor. At most 24 columns.
801
+ """
802
+ cols = [str(c) for c in (m.columns if m is not None else [])][:MATRIX_MAX]
803
+ n = len(cols)
804
+ if n < 2:
805
+ return _empty(uid, "matrix", title, "No pairs to draw.")
806
+ vals = m.values if m is not None else []
807
+
808
+ def val(i: int, j: int) -> float | None:
809
+ try:
810
+ v = _f(vals[i][j])
811
+ except (IndexError, TypeError, KeyError):
812
+ v = None
813
+ return None if v is None else min(max(abs(v), 0.0), 1.0)
814
+
815
+ label_w = _LABEL_CHARS * CHAR_W + 8
816
+ cell = min(28.0, max(12.0, (MATRIX_W - label_w - 90) / (n - 1)))
817
+ width = min(float(MATRIX_W), label_w + (n - 1) * cell + 90)
818
+ top = 4.0
819
+ grid_h = (n - 1) * cell
820
+ height = top + grid_h + _LABEL_CHARS * CHAR_W * 0.75 + 16
821
+ best: tuple[float, str, str] | None = None
822
+ cells = []
823
+ for i in range(1, n):
824
+ for j in range(i):
825
+ v = val(i, j)
826
+ x = label_w + j * cell
827
+ y = top + (i - 1) * cell
828
+ if v is None:
829
+ cells.append(f'<rect class="cell none" x="{_n(x + 1)}" y="{_n(y + 1)}" '
830
+ f'width="{_n(cell - 2)}" height="{_n(cell - 2)}" rx="1.5"><title>'
831
+ f'{_text(cols[i], 60)} and {_text(cols[j], 60)}: not measured'
832
+ f'</title></rect>')
833
+ continue
834
+ if best is None or v > best[0]:
835
+ best = (v, cols[i], cols[j])
836
+ step = min(4, int(v * 5)) + 1
837
+ cells.append(f'<rect class="cell" x="{_n(x + 1)}" y="{_n(y + 1)}" '
838
+ f'width="{_n(cell - 2)}" height="{_n(cell - 2)}" rx="1.5" '
839
+ f'fill-opacity="{step / 5:.1f}"><title>{_text(cols[i], 60)} and '
840
+ f'{_text(cols[j], 60)}: {v:.2f}</title></rect>')
841
+ desc = f"Association strengths of {n} columns, {n * (n - 1) // 2} pairs."
842
+ if best is not None:
843
+ desc += (f" The strongest is between {fmt.truncate(best[1], 60)} and "
844
+ f"{fmt.truncate(best[2], 60)} ({best[0]:.2f}).")
845
+ out = [_open(uid, "matrix", width, height, title, desc), *cells]
846
+
847
+ def label(name: str, body: str) -> str:
848
+ link = _href(hrefs, name)
849
+ return f'<a href="{_text(link)}">{body}</a>' if link else body
850
+
851
+ for i in range(1, n):
852
+ y = top + (i - 1) * cell + cell / 2 + 4
853
+ out.append(label(cols[i], f'<text class="lab" x="{_n(label_w - 6)}" y="{_n(y)}" '
854
+ f'text-anchor="end"><title>{_text(cols[i], 300)}</title>'
855
+ f'{_text(cols[i], _LABEL_CHARS)}</text>'))
856
+ ly = top + grid_h + 10
857
+ for j in range(n - 1):
858
+ x = label_w + j * cell + cell / 2 + 4
859
+ out.append(label(cols[j], f'<text class="lab" x="{_n(x)}" y="{_n(ly)}" '
860
+ f'text-anchor="end" transform="rotate(-45 {_n(x)} {_n(ly)})">'
861
+ f'<title>{_text(cols[j], 300)}</title>'
862
+ f'{_text(cols[j], _LABEL_CHARS)}</text>'))
863
+ out.append("</svg>")
864
+ return "".join(out)
865
+
866
+
867
+ # -- column strip -----------------------------------------------------------------------------
868
+
869
+
870
+ def strip(cells: Sequence[StripCell] | None, *, uid: str, title: str) -> str:
871
+ """One cell per column across a fixed viewBox (stretched to the page width with
872
+ ``preserveAspectRatio="none"``): a ``track``, an ``on`` or ``off`` bar as tall as the share
873
+ of rows that hold a value, a ``flag`` dot under a flagged column, each cell a link with a
874
+ tooltip. Cells lose their gap below about 1.2 units each, so 2,000 columns stay readable.
875
+ """
876
+ items = list(cells or [])
877
+ n = len(items)
878
+ extra = ' preserveAspectRatio="none"'
879
+ if n == 0:
880
+ return _open(uid, "strip", STRIP_W, STRIP_H, title, "No columns.", extra) + "</svg>"
881
+ cw = STRIP_W / n
882
+ gap = 1.0 if cw >= 4 else (0.3 * cw if cw >= 1.2 else 0.0)
883
+ w = max(cw - gap, 0.01)
884
+ track_h = 40.0
885
+ filled = [c for c in items if _f(c.present) is not None and _share(c.present) < 1]
886
+ off = sum(1 for c in items if c.state == "off")
887
+ flagged = sum(1 for c in items if c.flagged)
888
+ desc_bits = [f"{fmt.plural(n, 'column')}",
889
+ f"{fmt.plural(len(filled), 'column')} with empty cells"]
890
+ if off:
891
+ desc_bits.append(f"{off} not modeled")
892
+ if flagged:
893
+ desc_bits.append(f"{flagged} with an alert")
894
+ out = [_open(uid, "strip", STRIP_W, STRIP_H, title, ", ".join(desc_bits) + ".", extra)]
895
+ for i, c in enumerate(items):
896
+ x = i * cw + gap / 2
897
+ p = _f(c.present)
898
+ tip = _text(c.name, 80)
899
+ if p is None:
900
+ tip += ": emptiness not recorded"
901
+ else:
902
+ tip += f": {_pct(1 - _share(p))} empty"
903
+ if c.state == "off":
904
+ tip += ", not modeled"
905
+ if c.flagged:
906
+ tip += ", has an alert"
907
+ href = c.href if isinstance(c.href, str) and c.href.startswith("#") else ""
908
+ open_tag, close_tag = (f'<a href="{_text(href)}">', "</a>") if href else ("<g>", "</g>")
909
+ body = (f'{open_tag}<title>{tip}</title><rect class="track" x="{_n(x)}" y="2" '
910
+ f'width="{_n(w)}" height="{_n(track_h)}"/>')
911
+ if p is not None and _share(p) > 0:
912
+ hgt = track_h * _share(p)
913
+ state = "off" if c.state == "off" else "on"
914
+ body += (f'<rect class="{state}" x="{_n(x)}" y="{_n(2 + track_h - hgt)}" '
915
+ f'width="{_n(w)}" height="{_n(hgt)}"/>')
916
+ if c.flagged:
917
+ body += f'<circle class="flag" cx="{_n(i * cw + cw / 2)}" cy="49" r="2.4"/>'
918
+ out.append(body + close_tag)
919
+ out.append("</svg>")
920
+ return "".join(out)
921
+
922
+
923
+ # -- parts of a total -------------------------------------------------------------------------
924
+
925
+
926
+ def parts(labels: Sequence[str] | None, shares: Sequence[float] | None, *, uid: str,
927
+ title: str) -> str:
928
+ """One thin segmented bar (8 units high) of a total's parts, with 2-unit gaps, each
929
+ segment a ``seg a`` or ``seg b`` in turn, with a tooltip. Shares adding up to less than 1
930
+ leave the remainder of the ``track`` empty; more than 1 is rescaled."""
931
+ labs = [str(x) for x in (labels or [])]
932
+ vals = [_share(s) for s in (shares or [])][: len(labs)]
933
+ total = sum(vals)
934
+ height = 8.0
935
+ if not vals or total <= 0:
936
+ return _open(uid, "parts", WIDTH, height, title, "No parts to draw.") + "</svg>"
937
+ scale = WIDTH / max(total, 1.0)
938
+ desc = "; ".join(f"{fmt.truncate(lab, 40)} {fmt.share(v / max(total, 1.0))}"
939
+ for lab, v in zip(labs, vals, strict=False) if v > 0)
940
+ out = [_open(uid, "parts", WIDTH, height, title, desc + ".")]
941
+ out.append(f'<rect class="track" x="0" y="0" width="{WIDTH}" height="{_n(height)}" rx="2"/>')
942
+ x = 0.0
943
+ k = 0
944
+ for lab, v in zip(labs, vals, strict=False):
945
+ if v <= 0:
946
+ continue
947
+ w = v * scale
948
+ gap_l = 1.0 if x > 0 else 0.0
949
+ gap_r = 1.0 if x + w < WIDTH - 0.01 else 0.0
950
+ sw = max(w - gap_l - gap_r, 0.5)
951
+ cls = "seg a" if k % 2 == 0 else "seg b"
952
+ out.append(f'<rect class="{cls}" x="{_n(x + gap_l)}" y="0" width="{_n(sw)}" '
953
+ f'height="{_n(height)}" rx="2"><title>{_text(lab, 120)}: '
954
+ f'{_pct(v / max(total, 1.0))}</title></rect>')
955
+ x += w
956
+ k += 1
957
+ out.append("</svg>")
958
+ return "".join(out)
959
+
960
+
961
+ __all__ = [
962
+ "NO_DATA", "StripCell", "describe_histogram", "describe_levels", "has_data", "histogram",
963
+ "levels", "matrix", "parts", "strip", "weekdays",
964
+ ]