mintchip 0.2.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.
@@ -0,0 +1,337 @@
1
+ """SVG tier: the Canvas every SVG renderer draws on, and the root wrapper.
2
+
3
+ An SVG renderer has the signature ``render(chip, c: Canvas) -> None`` and draws only through
4
+ the Canvas methods below. They enforce the design rules: paint by role only (there is no way to
5
+ name a colour, let alone a background), stroke ≥ 1.25 and dot radius ≥ 1.75 viewBox units,
6
+ lines stop at the edge of hollow dots, and data mapped outside the domain is pinned to the edge
7
+ with a chevron marking the cut.
8
+
9
+ Coordinates are viewBox units: the canvas is ``width`` × 16, and 16 units render as 1em.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import itertools
16
+ import json
17
+ import math
18
+ from collections.abc import Iterable, Mapping
19
+ from typing import Any
20
+
21
+ from ..themes import DARK_INK, LIGHT_INK, Theme
22
+
23
+ __all__ = ["HEIGHT", "MIN_RADIUS", "MIN_STROKE", "SIZES", "Canvas", "svg_root"]
24
+
25
+ SIZES = {"s": 40, "m": 72, "l": 104}
26
+ HEIGHT = 16
27
+ MIN_STROKE = 1.25
28
+ MIN_RADIUS = 1.75
29
+ PAD = 2.5
30
+ CONTEXT_OPACITY = 0.45 # context strokes: axes, references, a comparison series
31
+ MARK_OPACITY = 0.6 # context dots and strokes under 1.5 wide: fainter would vanish at 1x
32
+ WASH_OPACITY = 0.16 # context fills: bands, normal ranges
33
+ BAND_OPACITY = 0.3 # a context fill only a few units tall (a narrow target band): 0.16 vanishes
34
+
35
+ Point = tuple[float, float]
36
+
37
+
38
+ def _n(v: float) -> str:
39
+ s = f"{v:.2f}".rstrip("0").rstrip(".")
40
+ return "0" if s in ("-0", "") else s
41
+
42
+
43
+ class Canvas:
44
+ """A ``width`` × 16 drawing surface with a plot area inset by ``pad`` on every side.
45
+
46
+ ``domain`` is the resolved scale for the chip (render argument, then ``args["domain"]``,
47
+ then ``chip.domain``): the x-extent for position chips, the y-extent for ``spark``.
48
+ ``natural`` is True when that is the chip's own scale, not one imposed for comparison: a
49
+ renderer may then tighten it to its marks, so a lone chip carries no blank margin into the
50
+ sentence (an imposed scale must be kept as given, or a table column stops lining up).
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ width: float,
56
+ theme: Theme,
57
+ domain: tuple[float, float] | None = None,
58
+ *,
59
+ pad: float = PAD,
60
+ natural: bool = False,
61
+ ) -> None:
62
+ self.width, self.height = float(width), float(HEIGHT)
63
+ self.theme = theme
64
+ self.domain = domain
65
+ self.natural = natural
66
+ self.pad = pad
67
+ self.left, self.right = pad, width - pad
68
+ self.top, self.bottom = pad, HEIGHT - pad
69
+ self.mid = HEIGHT / 2
70
+ self.clipped: set[str] = set() # sides where x()/y() pinned data: left/right/top/bottom
71
+ self._cuts: list[tuple[str, float | None]] = []
72
+ self._marks: list[tuple[str, Any]] = []
73
+ self._holes: list[tuple[float, float, float]] = []
74
+
75
+ # --- scales -----------------------------------------------------------------------------
76
+ def fx(self, t: float) -> float:
77
+ """Fraction 0..1 of the plot width → x."""
78
+ return self.left + t * (self.right - self.left)
79
+
80
+ def fy(self, t: float) -> float:
81
+ """Fraction 0..1 of the plot height → y (0 is the bottom)."""
82
+ return self.bottom - t * (self.bottom - self.top)
83
+
84
+ def _t(self, v: float, sides: tuple[str, str], at: float | None) -> float:
85
+ if self.domain is None:
86
+ raise ValueError("this chip has no domain; use fx()/fy() for fractions")
87
+ lo, hi = self.domain
88
+ t = (v - lo) / (hi - lo)
89
+ if -1e-9 <= t <= 1 + 1e-9:
90
+ return t
91
+ side = sides[0] if t < 0 else sides[1]
92
+ self.clipped.add(side)
93
+ if (side, at) not in self._cuts:
94
+ self._cuts.append((side, at))
95
+ return 0.0 if t < 0 else 1.0
96
+
97
+ def x(self, v: float, *, at: float | None = None) -> float:
98
+ """Domain value → x. Outside the domain it is pinned to the edge and a chevron is drawn
99
+ there, at height ``at`` (default: middle)."""
100
+ return self.fx(self._t(v, ("left", "right"), at))
101
+
102
+ def y(self, v: float, *, at: float | None = None) -> float:
103
+ """Domain value → y. Outside the domain it is pinned to the edge and a chevron is drawn
104
+ there, at x position ``at`` (default: centre); pass the point's x."""
105
+ return self.fy(self._t(v, ("bottom", "top"), at))
106
+
107
+ def contains(self, v: float) -> bool:
108
+ """Whether ``v`` is inside the domain. Draw a reference only when it is: a reference
109
+ pinned to the edge would mislead."""
110
+ return self.domain is not None and self.domain[0] <= v <= self.domain[1]
111
+
112
+ # --- marks ------------------------------------------------------------------------------
113
+ def line(
114
+ self,
115
+ x1: float,
116
+ y1: float,
117
+ x2: float,
118
+ y2: float,
119
+ *,
120
+ role: str = "ink",
121
+ width: float = 1.5,
122
+ dash: tuple[float, float] | None = None,
123
+ title: str | None = None,
124
+ ) -> None:
125
+ """A straight stroke."""
126
+ self.path([(x1, y1), (x2, y2)], role=role, width=width, dash=dash, title=title)
127
+
128
+ def path(
129
+ self,
130
+ points: Iterable[Point | None],
131
+ *,
132
+ role: str = "ink",
133
+ width: float = 1.5,
134
+ dash: tuple[float, float] | None = None,
135
+ title: str | None = None,
136
+ ) -> None:
137
+ """A polyline through ``points``; a None entry breaks it (a gap in the data)."""
138
+ _check_stroke(width)
139
+ runs: list[list[Point]] = [[]]
140
+ for p in points:
141
+ if p is None:
142
+ runs.append([])
143
+ else:
144
+ runs[-1].append((float(p[0]), float(p[1])))
145
+ segs = [(a, b) for run in runs for a, b in itertools.pairwise(run)]
146
+ self._marks.append(("path", (segs, role, width, dash, title)))
147
+
148
+ def dot(
149
+ self,
150
+ x: float,
151
+ y: float,
152
+ *,
153
+ role: str = "ink",
154
+ r: float = 2.25,
155
+ hollow: bool = False,
156
+ stroke: float = 1.5,
157
+ title: str | None = None,
158
+ ) -> None:
159
+ """A point. ``hollow=True`` draws a ring (fill:none, ``stroke`` wide) and every line
160
+ stops at its edge."""
161
+ if r < MIN_RADIUS:
162
+ raise ValueError(f"dot radius {r} is below the {MIN_RADIUS} minimum")
163
+ _check_stroke(stroke)
164
+ if hollow:
165
+ self._holes.append((x, y, r + stroke / 2))
166
+ self._marks.append(("dot", (x, y, r, role, hollow, title, stroke)))
167
+
168
+ def rect(
169
+ self,
170
+ x: float,
171
+ y: float,
172
+ w: float,
173
+ h: float,
174
+ *,
175
+ role: str = "context",
176
+ opacity: float = 1.0,
177
+ narrow: bool = False,
178
+ title: str | None = None,
179
+ ) -> None:
180
+ """A filled area. ``role="context"`` is a light wash (bands, ranges), or with
181
+ ``narrow=True`` a firmer one for a band only a few units tall; ``opacity`` steps ink for
182
+ parts of a whole (keep it ≥ 0.2)."""
183
+ if not 0.2 <= opacity <= 1:
184
+ raise ValueError(f"rect opacity {opacity} is outside 0.2..1")
185
+ if narrow:
186
+ opacity *= BAND_OPACITY / WASH_OPACITY if role == "context" else 1
187
+ self._marks.append(("rect", (x, y, max(w, 0.0), max(h, 0.0), role, opacity, title)))
188
+
189
+ def chevron(self, side: str, *, at: float | None = None, role: str = "ink") -> None:
190
+ """A small arrowhead on the plot edge ``side`` (left/right/top/bottom) saying the data
191
+ continue past it; ``at`` is its position along that edge. ``x()``/``y()`` draw these
192
+ automatically for pinned data, so renderers rarely call this. Its arms are kept inside
193
+ the canvas, so a cut at a corner does not reach into the neighbouring text."""
194
+ reach = 3 + MIN_STROKE / 2 # half the chevron's spread, plus half its stroke
195
+ if side in ("left", "right"):
196
+ tip = self.left - 1 if side == "left" else self.right + 1
197
+ back = tip + (2.5 if side == "left" else -2.5)
198
+ y = self.mid if at is None else min(max(at, reach), self.height - reach)
199
+ pts = [(back, y - 3), (tip, y), (back, y + 3)]
200
+ elif side in ("top", "bottom"):
201
+ tip = self.top - 1.5 if side == "top" else self.bottom + 1.5
202
+ back = tip + (2.5 if side == "top" else -2.5)
203
+ x = (self.left + self.right) / 2 if at is None else at
204
+ x = min(max(x, reach), self.width - reach)
205
+ pts = [(x - 3, back), (x, tip), (x + 3, back)]
206
+ else:
207
+ raise ValueError(f"unknown side {side!r}")
208
+ self.path(pts, role=role, width=MIN_STROKE)
209
+
210
+ def fit(self) -> None:
211
+ """Make the canvas end ``pad`` after the rightmost mark drawn so far, so a chip with few
212
+ marks leaves no blank run in the sentence (and one with many does not run into the
213
+ next word). Call it after drawing; the width stays in em."""
214
+ right = 0.0
215
+ for kind, data in self._marks:
216
+ if kind == "path":
217
+ segs, _, width, _, _ = data
218
+ right = max([right] + [p[0] + width / 2 for seg in segs for p in seg])
219
+ elif kind == "dot":
220
+ x, _, r, _, hollow, _, stroke = data
221
+ right = max(right, x + r + (stroke / 2 if hollow else 0))
222
+ else:
223
+ right = max(right, data[0] + data[2])
224
+ if right and "right" not in self.clipped:
225
+ self.width, self.right = right + self.pad, right
226
+
227
+ # --- output -----------------------------------------------------------------------------
228
+ def body(self) -> str:
229
+ """The SVG elements drawn so far, with edge chevrons for any clipped data."""
230
+ for side, at in self._cuts:
231
+ self.chevron(side, at=at)
232
+ self._cuts.clear()
233
+ return "".join(self._emit(kind, data) for kind, data in self._marks)
234
+
235
+ def _stroke(
236
+ self,
237
+ role: str,
238
+ width: float,
239
+ dash: tuple[float, float] | None = None,
240
+ *,
241
+ mark: bool = False,
242
+ ) -> str:
243
+ cap = "butt" if dash else "round"
244
+ s = f"fill:none;stroke:{self.theme.paint(role)};stroke-width:{_n(width)}"
245
+ s += f";stroke-linecap:{cap};stroke-linejoin:round"
246
+ if role == "context": # a dot or a thin line is a mark, and needs more than an axis
247
+ s += f";stroke-opacity:{MARK_OPACITY if mark or width < 1.5 else CONTEXT_OPACITY}"
248
+ if dash:
249
+ s += f";stroke-dasharray:{_n(dash[0])} {_n(dash[1])}"
250
+ return s
251
+
252
+ def _fill(self, role: str, opacity: float = 1.0, *, mark: bool = False) -> str:
253
+ a = opacity * ((MARK_OPACITY if mark else WASH_OPACITY) if role == "context" else 1.0)
254
+ return f"fill:{self.theme.paint(role)}" + ("" if a == 1 else f";fill-opacity:{_n(a)}")
255
+
256
+ def _emit(self, kind: str, data: Any) -> str:
257
+ if kind == "path":
258
+ segs, role, width, dash, title = data
259
+ d = _path_d(self._cut(segs))
260
+ if not d:
261
+ return ""
262
+ return _el("path", f'd="{d}" style="{self._stroke(role, width, dash)}"', title)
263
+ if kind == "dot":
264
+ x, y, r, role, hollow, title, stroke = data
265
+ style = self._stroke(role, stroke, mark=True) if hollow else self._fill(role, mark=True)
266
+ return _el("circle", f'cx="{_n(x)}" cy="{_n(y)}" r="{_n(r)}" style="{style}"', title)
267
+ x, y, w, h, role, opacity, title = data
268
+ geo = f'x="{_n(x)}" y="{_n(y)}" width="{_n(w)}" height="{_n(h)}"'
269
+ return _el("rect", f'{geo} style="{self._fill(role, opacity)}"', title)
270
+
271
+ def _cut(self, segs: list[tuple[Point, Point]]) -> list[tuple[Point, Point]]:
272
+ """Remove the parts of each segment that fall inside a hollow dot."""
273
+ for cx, cy, rad in self._holes:
274
+ out = []
275
+ for (x1, y1), (x2, y2) in segs:
276
+ dx, dy, fx, fy = x2 - x1, y2 - y1, x1 - cx, y1 - cy
277
+ a, b, c = dx * dx + dy * dy, 2 * (fx * dx + fy * dy), fx * fx + fy * fy - rad * rad
278
+ disc = b * b - 4 * a * c
279
+ if a == 0 or disc <= 0:
280
+ out.append(((x1, y1), (x2, y2)))
281
+ continue
282
+ t1, t2 = (-b - math.sqrt(disc)) / (2 * a), (-b + math.sqrt(disc)) / (2 * a)
283
+ for lo, hi in ((0.0, min(t1, 1.0)), (max(t2, 0.0), 1.0)):
284
+ if hi - lo > 1e-3:
285
+ p = (x1 + dx * lo, y1 + dy * lo)
286
+ q = (x1 + dx * hi, y1 + dy * hi)
287
+ out.append((p, q))
288
+ segs = out
289
+ return segs
290
+
291
+
292
+ def _check_stroke(width: float) -> None:
293
+ if width < MIN_STROKE:
294
+ raise ValueError(f"stroke width {width} is below the {MIN_STROKE} minimum")
295
+
296
+
297
+ def _path_d(segs: list[tuple[Point, Point]]) -> str:
298
+ d: list[str] = []
299
+ last: Point | None = None
300
+ for p, q in segs:
301
+ if last is None or abs(last[0] - p[0]) > 1e-6 or abs(last[1] - p[1]) > 1e-6:
302
+ d.append(f"M{_n(p[0])} {_n(p[1])}")
303
+ d.append(f"L{_n(q[0])} {_n(q[1])}")
304
+ last = q
305
+ return "".join(d)
306
+
307
+
308
+ def _el(tag: str, attrs: str, title: str | None) -> str:
309
+ if title:
310
+ return f"<{tag} {attrs}><title>{html.escape(title)}</title></{tag}>"
311
+ return f"<{tag} {attrs}/>"
312
+
313
+
314
+ def svg_root(
315
+ c: Canvas,
316
+ *,
317
+ alt: str,
318
+ facts: Iterable[str],
319
+ spec: Mapping[str, Any],
320
+ standalone: bool = False,
321
+ ) -> str:
322
+ """Wrap a drawn Canvas in the contract's root element, title, desc and data-mc spec."""
323
+ data = json.dumps(spec, ensure_ascii=False, separators=(",", ":"))
324
+ style = ""
325
+ if standalone:
326
+ style = (
327
+ f"<style>svg{{color:{LIGHT_INK}}}"
328
+ f"@media (prefers-color-scheme:dark){{svg{{color:{DARK_INK}}}}}</style>"
329
+ )
330
+ return (
331
+ f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {_n(c.width)} 16" '
332
+ f'width="{_n(c.width / 16)}em" height="1em" role="img" '
333
+ f'aria-label="{html.escape(alt, quote=True)}" data-mc="{html.escape(data, quote=True)}" '
334
+ f'style="vertical-align:-0.15em;overflow:visible">'
335
+ f"<title>{html.escape(alt)}</title><desc>{html.escape('; '.join(facts))}</desc>"
336
+ f"{style}{c.body()}</svg>"
337
+ )
@@ -0,0 +1,215 @@
1
+ """Text tier: glyphs, cell helpers, ASCII transliteration and ANSI colour.
2
+
3
+ A text renderer has the signature ``render(chip, o: TextOptions) -> TextOut``. It writes the
4
+ Unicode tier only, from the glyphs below; ``Chip.text(ascii=True)`` transliterates the whole
5
+ output through ``ASCII``, so renderers branch on ``o.ascii`` only when the transliteration of a
6
+ specific glyph would read badly.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+
15
+ __all__ = [
16
+ "ALLOWED",
17
+ "ASCII",
18
+ "CROSS",
19
+ "DOT",
20
+ "EIGHTHS",
21
+ "GAP",
22
+ "HI_END",
23
+ "HOLLOW",
24
+ "LEVELS",
25
+ "LO_END",
26
+ "REF",
27
+ "RULE",
28
+ "TRACK",
29
+ "Glyph",
30
+ "Segment",
31
+ "TextOptions",
32
+ "TextOut",
33
+ "Track",
34
+ "ansi",
35
+ "cell_counts",
36
+ "hbar",
37
+ "largest_remainder",
38
+ "level",
39
+ "plain",
40
+ "to_ascii",
41
+ ]
42
+
43
+ # --- the Unicode tier's whole alphabet (CONTRACT section 5) ---------------------------------
44
+ LEVELS = "▁▂▃▄▅▆▇█" # eight heights, for runs of values
45
+ EIGHTHS = "▏▎▍▌▋▊▉█" # left-aligned partial cells, for lengths
46
+ TRACK = "·" # an empty cell on an axis, or a missing value in a run
47
+ RULE = "─" # a span along an axis
48
+ REF = "│" # a reference position on an axis
49
+ CROSS = "┼" # a reference position inside a span
50
+ LO_END, HI_END = "├", "┤" # the two ends of a span
51
+ DOT, HOLLOW = "●", "○" # a point; hollow when it is not distinguishable from the reference
52
+ GAP = "▏" # thin separator between parts of a whole
53
+ ALLOWED = frozenset(LEVELS + EIGHTHS + "─│├┤┼●○·−→±×")
54
+
55
+ # Transliteration applied to every character of ``text(ascii=True)``.
56
+ ASCII: dict[str, str] = {
57
+ **dict(zip(LEVELS, "_.-~=+*#", strict=True)),
58
+ "▏": "|", "▎": "|", "▍": "|", "▌": "|", "▋": "#", "▊": "#", "▉": "#",
59
+ "·": ".", "─": "-", "│": "|", "┼": "+", "├": "(", "┤": ")", "●": "*", "○": "o",
60
+ "−": "-", "→": "->", "±": "+/-", "×": "x",
61
+ "–": "-", "—": "-", "…": "...", "µ": "u", "μ": "u", "°": "deg", "≤": "<=", "≥": ">=",
62
+ } # fmt: skip
63
+
64
+ _SGR = {"accent": "34", "good": "32", "bad": "31", "warn": "33", "context": "2"}
65
+
66
+ Segment = tuple[str, str | None] # (text, role)
67
+ Glyph = str | Sequence[Segment]
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class TextOptions:
72
+ """What a text renderer is asked for. ``domain`` is already resolved (render argument,
73
+ then ``args["domain"]``, then ``chip.domain``). ``decimals``, when given, is the decimal
74
+ places for the primary value (a table column passes one count to all its cells); kinds
75
+ whose value is not a decimal number ignore it."""
76
+
77
+ ascii: bool = False
78
+ compact: bool = False
79
+ domain: tuple[float, float] | None = None
80
+ decimals: int | None = None
81
+
82
+
83
+ @dataclass(frozen=True)
84
+ class TextOut:
85
+ """``value`` is the number part; ``glyph`` is a string or ``(text, role)`` segments, with
86
+ role one of None, "accent", "good", "bad", "warn", "context". Empty glyph means none.
87
+ ``decimals`` is the decimal places the primary value was printed with, for kinds that
88
+ honour ``TextOptions.decimals`` (None for the others)."""
89
+
90
+ value: str
91
+ glyph: Glyph = ""
92
+ decimals: int | None = None
93
+
94
+
95
+ def to_ascii(s: str) -> str:
96
+ """Transliterate to pure ASCII; anything unknown becomes ``?``."""
97
+ return "".join(ch if ch.isascii() else ASCII.get(ch, "?") for ch in s)
98
+
99
+
100
+ def _segments(glyph: Glyph) -> list[Segment]:
101
+ return [(glyph, None)] if isinstance(glyph, str) else list(glyph)
102
+
103
+
104
+ def plain(glyph: Glyph, *, ascii: bool = False) -> str:
105
+ """Join segments without colour."""
106
+ s = "".join(t for t, _ in _segments(glyph))
107
+ return to_ascii(s) if ascii else s
108
+
109
+
110
+ def ansi(glyph: Glyph, *, ascii: bool = False) -> str:
111
+ """Join segments, wrapping each coloured role in an ANSI SGR code."""
112
+ out = []
113
+ for text, role in _segments(glyph):
114
+ text = to_ascii(text) if ascii else text
115
+ out.append(f"\x1b[{_SGR[role]}m{text}\x1b[0m" if role and text else text)
116
+ return "".join(out)
117
+
118
+
119
+ def level(v: float, lo: float, hi: float) -> str:
120
+ """The LEVELS block for ``v`` on ``[lo, hi]`` (clamped; check clipping yourself)."""
121
+ t = 0.5 if hi <= lo else (v - lo) / (hi - lo)
122
+ return LEVELS[min(7, max(0, round(t * 7)))]
123
+
124
+
125
+ def hbar(cells: float) -> str:
126
+ """A horizontal length of ``cells`` cells, in eighths: hbar(2.5) == "██▌"."""
127
+ whole = math.floor(cells)
128
+ part = round((cells - whole) * 8)
129
+ if part == 8:
130
+ whole, part = whole + 1, 0
131
+ return "█" * whole + (EIGHTHS[part - 1] if part else "")
132
+
133
+
134
+ def largest_remainder(weights: list[float], cells: int) -> list[int]:
135
+ """Split ``cells`` whole cells among ``weights`` in proportion (largest remainder)."""
136
+ total = sum(weights)
137
+ raw = [w / total * cells for w in weights]
138
+ out = [math.floor(r) for r in raw]
139
+ order = sorted(range(len(raw)), key=lambda i: (out[i] - raw[i], i))
140
+ for i in order[: cells - sum(out)]:
141
+ out[i] += 1
142
+ return out
143
+
144
+
145
+ def cell_counts(weights: list[float], cells: int) -> tuple[list[int], list[bool]]:
146
+ """``largest_remainder``, then a weight that got no cell is given one (flagged True in the
147
+ second list), taken from the weight holding the most. Needs ``len(weights) <= cells / 2``."""
148
+ out = largest_remainder(weights, cells)
149
+ small = [n == 0 for n in out]
150
+ for i in (i for i, s in enumerate(small) if s):
151
+ donor = max(range(len(out)), key=lambda j: (out[j], -j))
152
+ out[donor] -= 1
153
+ out[i] = 1
154
+ return out, small
155
+
156
+
157
+ class Track:
158
+ """A bracketed axis of ``cells`` cells over ``domain``, for position chips.
159
+
160
+ ``Track(11, (lo, hi))``, then ``span``/``put`` marks in drawing order (later wins), then
161
+ ``glyph()``. A value outside the domain lands on the end cell and turns that end's bracket
162
+ into ``<`` or ``>``, so a cut is always visible.
163
+ """
164
+
165
+ def __init__(self, cells: int, domain: tuple[float, float]) -> None:
166
+ self.cells = cells
167
+ self.lo, self.hi = domain
168
+ self._chars = [TRACK] * cells
169
+ self._roles: list[str | None] = [None] * cells
170
+ self.clipped_lo = self.clipped_hi = False
171
+
172
+ def contains(self, v: float) -> bool:
173
+ """Whether ``v`` is inside the domain. Place a reference only when it is."""
174
+ return self.lo <= v <= self.hi
175
+
176
+ def cell(self, v: float) -> int:
177
+ """Cell index of ``v``; records clipping when ``v`` is outside the domain."""
178
+ if v < self.lo:
179
+ self.clipped_lo = True
180
+ return 0
181
+ if v > self.hi:
182
+ self.clipped_hi = True
183
+ return self.cells - 1
184
+ return round((v - self.lo) / (self.hi - self.lo) * (self.cells - 1))
185
+
186
+ def span(self, a: float, b: float, *, ends: bool = True, role: str | None = None) -> None:
187
+ """``├───┤`` from ``a`` to ``b`` (``─`` throughout when ``ends`` is False)."""
188
+ a, b = sorted((a, b))
189
+ i, j = self.cell(a), self.cell(b)
190
+ for k in range(i, j + 1):
191
+ self.set(k, RULE, role)
192
+ if ends and j > i: # no end cap where the span runs past the domain
193
+ if a >= self.lo:
194
+ self.set(i, LO_END, role)
195
+ if b <= self.hi:
196
+ self.set(j, HI_END, role)
197
+
198
+ def put(self, v: float, ch: str, role: str | None = None) -> int:
199
+ """Place one glyph at ``v``; returns the cell index."""
200
+ k = self.cell(v)
201
+ self.set(k, ch, role)
202
+ return k
203
+
204
+ def set(self, k: int, ch: str, role: str | None = None) -> None:
205
+ self._chars[k], self._roles[k] = ch, role
206
+
207
+ def glyph(self) -> list[Segment]:
208
+ segs: list[Segment] = [("<" if self.clipped_lo else "[", None)]
209
+ for ch, role in zip(self._chars, self._roles, strict=True):
210
+ if segs and segs[-1][1] == role:
211
+ segs[-1] = (segs[-1][0] + ch, role)
212
+ else:
213
+ segs.append((ch, role))
214
+ segs.append((">" if self.clipped_hi else "]", None))
215
+ return segs
mintchip/scales.py ADDED
@@ -0,0 +1,117 @@
1
+ """Scales shared across chips: common domains, quantiles, robust extents, downsampling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Iterable, Sequence
7
+ from typing import Any
8
+
9
+ from .spec import Chip, ChipError
10
+
11
+ __all__ = [
12
+ "downsample_minmax",
13
+ "padded",
14
+ "quantile",
15
+ "robust_extent",
16
+ "shared_domain",
17
+ "union_domain",
18
+ ]
19
+
20
+ Domain = tuple[float, float]
21
+
22
+
23
+ def padded(lo: float, hi: float, frac: float = 0.08) -> Domain:
24
+ """Widen ``(lo, hi)`` by ``frac`` of its span on each side; a zero span gets a small width."""
25
+ span = hi - lo
26
+ margin = span * frac if span > 0 else max(abs(lo) * 0.05, 1e-9)
27
+ return lo - margin, hi + margin
28
+
29
+
30
+ def union_domain(*domains: Domain | None) -> Domain | None:
31
+ """The smallest ``(lo, hi)`` covering every non-None domain, or None if there are none."""
32
+ ds = [d for d in domains if d is not None]
33
+ if not ds:
34
+ return None
35
+ return min(d[0] for d in ds), max(d[1] for d in ds)
36
+
37
+
38
+ def shared_domain(*items: Any, reference: float | None = None, pad: float = 0.08) -> Domain:
39
+ """One ``(lo, hi)`` for sibling chips, to pass as ``domain=`` when rendering them.
40
+
41
+ Each item is a chip (contributes its own domain, already padded), a number, or any iterable
42
+ of numbers (lists, tuples, NumPy arrays, generators; None and NaN are skipped). Raw numbers
43
+ are padded by ``pad`` × their span; ``reference`` is included as a raw number.
44
+ """
45
+ hint = "Pass chips, numbers or lists of numbers, e.g. mintchip.shared_domain(a, b)."
46
+ raw: list[float] = []
47
+ chip_domains: list[Domain | None] = []
48
+ for item in items:
49
+ if isinstance(item, Chip):
50
+ dom = item.args.get("domain") or item.domain
51
+ chip_domains.append((dom[0], dom[1]) if dom is not None else None)
52
+ continue
53
+ if isinstance(item, (str, bytes)) or not isinstance(item, Iterable):
54
+ item = [item]
55
+ for v in item:
56
+ if v is None:
57
+ continue
58
+ try:
59
+ if isinstance(v, (str, bytes, bool)):
60
+ raise TypeError
61
+ f = float(v)
62
+ except (TypeError, ValueError):
63
+ raise ChipError(
64
+ f"mintchip.shared_domain: {v!r} is not a number.", fix_hint=hint
65
+ ) from None
66
+ if math.isfinite(f):
67
+ raw.append(f)
68
+ if reference is not None:
69
+ raw.append(float(reference))
70
+ dom = union_domain(padded(min(raw), max(raw), pad) if raw else None, *chip_domains)
71
+ if dom is None:
72
+ raise ChipError("mintchip.shared_domain: no finite number or domain given.", fix_hint=hint)
73
+ return dom
74
+
75
+
76
+ def quantile(sorted_values: Sequence[float], q: float) -> float:
77
+ """Linear-interpolation quantile (type 7) of already-sorted values."""
78
+ n = len(sorted_values)
79
+ if n == 0:
80
+ raise ValueError("quantile of an empty sequence")
81
+ pos = q * (n - 1)
82
+ lo = math.floor(pos)
83
+ hi = min(lo + 1, n - 1)
84
+ return sorted_values[lo] + (sorted_values[hi] - sorted_values[lo]) * (pos - lo)
85
+
86
+
87
+ def robust_extent(values: Iterable[float], k: float = 3.0) -> Domain:
88
+ """``(lo, hi)`` of the values that lie within ``k`` × IQR of the quartiles.
89
+
90
+ Values outside are outliers for the caller to mark at an edge. With a zero IQR the full
91
+ extent is returned, since every non-median value would otherwise count as an outlier.
92
+ """
93
+ s = sorted(float(v) for v in values)
94
+ q1, q3 = quantile(s, 0.25), quantile(s, 0.75)
95
+ iqr = q3 - q1
96
+ if iqr <= 0:
97
+ return s[0], s[-1]
98
+ lo_fence, hi_fence = q1 - k * iqr, q3 + k * iqr
99
+ inside = [v for v in s if lo_fence <= v <= hi_fence]
100
+ return inside[0], inside[-1]
101
+
102
+
103
+ def downsample_minmax(values: Sequence[float | None], n: int) -> list[float | None]:
104
+ """Reduce a series to ``n`` buckets, keeping in each the value farthest from the series
105
+ median, so a single spike survives. All-gap buckets stay None. Shorter series pass through.
106
+ """
107
+ if len(values) <= n:
108
+ return list(values)
109
+ finite = sorted(v for v in values if v is not None)
110
+ med = quantile(finite, 0.5) if finite else 0.0
111
+ out: list[float | None] = []
112
+ for b in range(n):
113
+ bucket = [
114
+ v for v in values[b * len(values) // n : (b + 1) * len(values) // n] if v is not None
115
+ ]
116
+ out.append(max(bucket, key=lambda v: abs(v - med)) if bucket else None)
117
+ return out