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,257 @@
1
+ """timeline: where the time went, as phases along one wall clock.
2
+
3
+ Text: ``7.5 s (solve 64%) ██▏██████▏██``: the wall-clock total and the longest phase's share
4
+ of it, then CELLS cells split among the phases in time order, separated by thin gaps; the
5
+ longest phase is in accent. Idle time between phases is empty track (``·``), not closed up.
6
+ A phase too short to earn a cell gets one half-height cell (``▄``) and a warning.
7
+ SVG: bars with gaps on the same clock, the longest in accent, idle time as a context line.
8
+
9
+ Overlapping phases (given as ``name → (start, end)``): the SVG packs them into up to
10
+ MAX_LANES lanes, so every phase keeps its true length. The text has one line, so it draws one
11
+ lane where the later-starting phase covers the overlap, and announces it as ``overlap 0.4 s``.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import itertools
17
+
18
+ from .. import fmt
19
+ from ..render.svg_base import Canvas
20
+ from ..render.text_base import GAP, TRACK, TextOptions, TextOut, largest_remainder
21
+ from ..spec import Built, Chip, ChipError, Param, chip, svg_renderer, text_renderer
22
+ from .share import SMALL
23
+
24
+ CELLS = 10 # text cells for the whole wall clock
25
+ MAX_LANES = 3 # parallel phases the SVG can stack and still read at 1x
26
+ LANES = { # SVG bar (top, height) per lane, by lane count
27
+ 1: ((4.0, 8.0),),
28
+ 2: ((3.0, 4.5), (8.5, 4.5)),
29
+ 3: ((2.5, 3.0), (6.5, 3.0), (10.5, 3.0)),
30
+ }
31
+ INSET = 0.75 # SVG bars are inset this much at each end, leaving a gap between neighbours
32
+ MIN_W = 1.5
33
+ HINT = 'Pass durations in order, {"fetch": 1.2, "solve": 4.8}, or spans, {"fetch": (0, 1.2)}.'
34
+
35
+
36
+ @chip(
37
+ "timeline",
38
+ question="Where did the time go?",
39
+ have="Durations of phases",
40
+ params=(
41
+ Param(
42
+ "stages",
43
+ "mapping",
44
+ "Give each phase's duration in order, or its (start, end), by name.",
45
+ required=True,
46
+ positional=True,
47
+ ),
48
+ Param("label", "string", "Say what was timed."),
49
+ Param("unit", "string", "Name the unit of the times.", default="s"),
50
+ ),
51
+ example={"stages": {"fetch": 1.2, "solve": 4.8, "write": 1.5}, "label": "Agent step"},
52
+ size="m",
53
+ )
54
+ def timeline(stages, *, label=None, unit="s") -> Built:
55
+ if not stages:
56
+ raise ChipError("needs at least 1 phase; got none.", fix_hint=HINT)
57
+ if len(stages) > CELLS:
58
+ raise ChipError(
59
+ f"shows at most {CELLS} phases; got {len(stages)}.",
60
+ fix_hint="Group short phases together, e.g. 'setup' for the first few.",
61
+ )
62
+ kinds = {isinstance(v, tuple) for v in stages.values()}
63
+ if len(kinds) > 1:
64
+ raise ChipError("phases must be all durations or all (start, end) spans.", fix_hint=HINT)
65
+ names = list(stages)
66
+ if kinds == {True}:
67
+ spans = [stages[n] for n in names]
68
+ else:
69
+ ends = list(itertools.accumulate(stages.values(), initial=0.0))
70
+ spans = list(itertools.pairwise(ends)) # back to back, with no float sliver between
71
+ for name, (a, b) in zip(names, spans, strict=True):
72
+ if not b > a:
73
+ raise ChipError(
74
+ f"phase {name!r} must take positive time; got {fmt.num(b - a)}.",
75
+ fix_hint="Leave out phases that took no time; give spans as (start, end).",
76
+ )
77
+ order = sorted(range(len(spans)), key=lambda i: spans[i][0]) # stable
78
+ names = [names[i] for i in order]
79
+ spans = [spans[i] for i in order]
80
+ t0, t1 = spans[0][0], max(b for _, b in spans)
81
+ wall = t1 - t0
82
+ durs = [b - a for a, b in spans]
83
+ longest = max(range(len(durs)), key=lambda i: (durs[i], -i))
84
+
85
+ pieces, idle, overlap, peak = _sweep(spans)
86
+ lanes = _lanes(spans)
87
+ if max(lanes) + 1 > MAX_LANES:
88
+ raise ChipError(
89
+ f"{peak} phases run at once; a timeline stacks at most {MAX_LANES}.",
90
+ fix_hint="Group parallel phases into one, or show each group as its own timeline.",
91
+ )
92
+ text, small = _text_pieces(pieces, len(spans))
93
+
94
+ warnings = []
95
+ if overlap > 0:
96
+ warnings.append(
97
+ f"phases overlap for {fmt.num(overlap, unit=unit)} (up to {peak} at once); the SVG "
98
+ f"stacks them in {max(lanes) + 1} lanes, the one-line text lets the later phase "
99
+ f"cover the overlap (marked overlap {fmt.num(overlap, unit=unit)})."
100
+ )
101
+ for i in small:
102
+ warnings.append(
103
+ f"phase {names[i]!r} ({fmt.num(durs[i], unit=unit)}, {fmt.pct(durs[i] / wall)}) is "
104
+ f"under one text cell of {CELLS}; it is drawn as one half-height cell ({SMALL}), "
105
+ "and as a half-height bar in SVG if it is narrower than the minimum."
106
+ )
107
+
108
+ facts = [
109
+ f"{n} {fmt.num(d, unit=unit)} ({fmt.pct(d / wall)})"
110
+ for n, d in zip(names, durs, strict=True)
111
+ ]
112
+ idle_time = sum(b - a for a, b in idle)
113
+ if idle_time > 0:
114
+ facts.append(f"idle {fmt.num(idle_time, unit=unit)} ({fmt.pct(idle_time / wall)})")
115
+ if overlap > 0:
116
+ facts.append(f"overlap {fmt.num(overlap, unit=unit)}, up to {peak} phases at once")
117
+ name = f"{label}: " if label else ""
118
+ return Built(
119
+ stats={
120
+ "value": wall,
121
+ "total": wall,
122
+ "start": t0,
123
+ "names": names,
124
+ "spans": spans,
125
+ "longest": longest,
126
+ "share": durs[longest] / wall,
127
+ "lanes": lanes,
128
+ "idle": idle,
129
+ "overlap": overlap,
130
+ "text": text,
131
+ },
132
+ facts=facts,
133
+ warnings=warnings,
134
+ alt=f"{name}{fmt.num(wall, unit=unit)} over {len(spans)} phases; {names[longest]} is "
135
+ f"longest at {fmt.num(durs[longest], unit=unit)} ({fmt.pct(durs[longest] / wall)}).",
136
+ )
137
+
138
+
139
+ def _sweep(spans: list[tuple[float, float]]):
140
+ """Walk the clock once. Returns the one-lane pieces ``[owner, seconds]`` (owner is the
141
+ latest-started running phase, or None when idle), the idle spans, the time with two or
142
+ more phases running, and the most phases running at once."""
143
+ bounds = sorted({t for span in spans for t in span})
144
+ pieces: list[list] = []
145
+ idle, overlap, peak = [], 0.0, 0
146
+ for a, b in itertools.pairwise(bounds):
147
+ running = [i for i, (s, e) in enumerate(spans) if s <= a and e >= b]
148
+ owner = max(running) if running else None # spans are sorted by start
149
+ peak = max(peak, len(running))
150
+ if len(running) > 1:
151
+ overlap += b - a
152
+ if owner is None:
153
+ idle.append((a, b))
154
+ if pieces and pieces[-1][0] == owner:
155
+ pieces[-1][1] += b - a
156
+ else:
157
+ pieces.append([owner, b - a])
158
+ return pieces, idle, overlap, peak
159
+
160
+
161
+ def _lanes(spans: list[tuple[float, float]]) -> list[int]:
162
+ """Greedy lane per phase (spans sorted by start): the first lane free by its start."""
163
+ ends: list[float] = []
164
+ lanes = []
165
+ for a, b in spans:
166
+ k = next((k for k, e in enumerate(ends) if e <= a), len(ends))
167
+ ends[k : k + 1] = [b]
168
+ lanes.append(k)
169
+ return lanes
170
+
171
+
172
+ def _text_pieces(pieces: list[list], phases: int) -> tuple[list[list], list[int]]:
173
+ """``[owner, cells, small]`` runs for the text line, and the phases drawn small.
174
+
175
+ Cells go to pieces by largest remainder; a phase left with no cell at all gets one
176
+ half-height cell, taken from the piece with the most cells. Pieces left with none (idle
177
+ or a phase's sliver) are dropped and their neighbours merged."""
178
+ owners = [o for o, _ in pieces]
179
+ cells = largest_remainder([d for _, d in pieces], CELLS)
180
+ flag = [False] * len(pieces)
181
+
182
+ def spare(j: int) -> bool: # can piece j give up a cell without hiding its phase?
183
+ if flag[j] or not cells[j]:
184
+ return False
185
+ o = owners[j]
186
+ return (
187
+ cells[j] > 1
188
+ or o is None
189
+ or any(cells[k] for k in range(len(pieces)) if k != j and owners[k] == o)
190
+ )
191
+
192
+ has = {o for o, n in zip(owners, cells, strict=True) if n and o is not None}
193
+ small = [i for i in range(phases) if i not in has]
194
+ for i in small: # at most CELLS phases, so a spare cell always exists
195
+ k = max((j for j, o in enumerate(owners) if o == i), key=lambda j: pieces[j][1])
196
+ donor = max((j for j in range(len(cells)) if spare(j)), key=lambda j: (cells[j], -j))
197
+ cells[donor] -= 1
198
+ cells[k], flag[k] = 1, True
199
+ out: list[list] = []
200
+ for (owner, _), n, f in zip(pieces, cells, flag, strict=True):
201
+ if not n:
202
+ continue
203
+ if out and out[-1][0] == owner and not f and not out[-1][2]:
204
+ out[-1][1] += n
205
+ else:
206
+ out.append([owner, n, f])
207
+ return out, small
208
+
209
+
210
+ # --- text -----------------------------------------------------------------------------------
211
+ @text_renderer("timeline")
212
+ def _text(chip: Chip, o: TextOptions) -> TextOut:
213
+ s = chip.stats
214
+ dec = fmt.places(fmt.num(s["total"]))
215
+ if o.decimals is not None and dec is not None: # scientific notation keeps its form
216
+ dec = o.decimals
217
+ total = fmt.fixed(s["total"], dec, unit=chip.unit)
218
+ else:
219
+ total = fmt.num(s["total"], unit=chip.unit)
220
+ value = total if o.compact else f"{total} ({s['names'][s['longest']]} {fmt.pct(s['share'])})"
221
+ glyph: list[tuple[str, str | None]] = []
222
+ prev = None
223
+ for owner, n, small in s["text"]:
224
+ if owner is None:
225
+ glyph.append((TRACK * n, "context"))
226
+ else:
227
+ if prev is not None:
228
+ glyph.append((GAP, None))
229
+ role = "accent" if owner == s["longest"] else None
230
+ glyph.append((SMALL if small else "█" * n, role))
231
+ prev = owner
232
+ if s["overlap"] > 0:
233
+ glyph.append((f" overlap {fmt.num(s['overlap'], unit=chip.unit)}", None))
234
+ return TextOut(value, glyph, dec)
235
+
236
+
237
+ # --- svg ------------------------------------------------------------------------------------
238
+ @svg_renderer("timeline")
239
+ def _svg(chip: Chip, c: Canvas) -> None:
240
+ s = chip.stats
241
+ t0, wall = s["start"], s["total"]
242
+
243
+ def x(t: float) -> float:
244
+ return c.fx((t - t0) / wall)
245
+
246
+ for a, b in s["idle"]: # idle time keeps its length, as empty track
247
+ c.line(x(a), c.mid, x(b), c.mid, role="context", width=1.25)
248
+ rows = LANES[max(s["lanes"]) + 1]
249
+ for i, ((a, b), lane) in enumerate(zip(s["spans"], s["lanes"], strict=True)):
250
+ x1, x2 = x(a) + INSET, x(b) - INSET
251
+ top, h = rows[lane]
252
+ if x2 - x1 < MIN_W: # too short to draw: minimum width, half height, like ▄ in text
253
+ x1, x2 = (x1 + x2 - MIN_W) / 2, (x1 + x2 + MIN_W) / 2
254
+ top, h = top + h / 2, h / 2
255
+ tip = f"{s['names'][i]}: {fmt.num(b - a, unit=chip.unit)}"
256
+ role = "accent" if i == s["longest"] else "ink"
257
+ c.rect(x1, top, x2 - x1, h, role=role, title=tip)
@@ -0,0 +1,212 @@
1
+ """waterfall: signed contributions from a start to a total.
2
+
3
+ Text prints the arithmetic and no glyph (design rule 6): ``0.63 +0.13 +0.08 −0.02 = 0.82``
4
+ (the start is left out when it is 0; the unit goes on the total). With more than TEXT_TERMS
5
+ steps the text keeps the TEXT_TERMS − 1 largest steps, in their order, and folds the rest into
6
+ one summed term, ``+0.03 (4 others)``, so the line still adds up; a warning says so.
7
+ Compact: ``0.63→0.82 (+0.19)``, or ``0.19 (3 steps)`` from a zero start. Numbers share one
8
+ decimal place, enough to show the smallest step shown to one significant figure.
9
+
10
+ SVG: a stepped bridge on its own y-scale (the levels' extent, not zero-based): a level mark for
11
+ the start, one floating bar per step, a heavier level mark for the total. Bars are ink, and
12
+ direction is read from position; they turn good/bad only when the caller passes
13
+ ``higher_is_better``. More than SVG_BARS steps fold the same way.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ from .. import fmt
21
+ from ..render.svg_base import Canvas
22
+ from ..render.text_base import TextOptions, TextOut
23
+ from ..spec import Built, Chip, ChipError, Param, chip, svg_renderer, text_renderer
24
+
25
+ TEXT_TERMS = 4 # most step terms in the text line, a folded remainder included
26
+ SVG_BARS = 12 # most step bars in the SVG, a folded remainder included
27
+
28
+
29
+ @chip(
30
+ "waterfall",
31
+ question="Which contributions took a value from its start to its total?",
32
+ have="Signed contributions from a start to a total",
33
+ params=(
34
+ Param(
35
+ "steps",
36
+ "mapping",
37
+ "Give the signed contributions in order, name → change.",
38
+ required=True,
39
+ positional=True,
40
+ ),
41
+ Param("start", "number", "Give the starting level the steps add to.", default=0.0),
42
+ Param("higher_is_better", "bool", "Declare a direction: steps turn good or bad."),
43
+ Param("label", "string", "Say what the steps add up to."),
44
+ Param("unit", "string", "Name the unit of the values."),
45
+ ),
46
+ example={
47
+ "steps": {"retrieval": 0.13, "reranker": 0.08, "latency cap": -0.02},
48
+ "start": 0.63,
49
+ "label": "Accuracy",
50
+ },
51
+ size="m",
52
+ )
53
+ def waterfall(steps, *, start=0.0, higher_is_better=None, label=None, unit=None) -> Built:
54
+ if not steps:
55
+ raise ChipError(
56
+ "needs at least 1 step.",
57
+ fix_hint='Pass named changes, e.g. mintchip.waterfall({"gain": 0.12, "drag": -0.02}).',
58
+ )
59
+ for name, d in steps.items():
60
+ if isinstance(d, tuple):
61
+ raise ChipError(
62
+ f"step {name!r} must be one signed number; got the pair {d!r}.",
63
+ fix_hint="Give each step's change, not its (start, end).",
64
+ )
65
+ items = [[name, d] for name, d in steps.items()]
66
+ levels = [start]
67
+ for _, d in items:
68
+ levels.append(levels[-1] + d)
69
+ total = levels[-1]
70
+ text_terms = _fold(items, TEXT_TERMS)
71
+ svg_terms = _fold(items, SVG_BARS)
72
+ s = {
73
+ "value": total,
74
+ "start": start,
75
+ "total": total,
76
+ "steps": items,
77
+ "text_terms": text_terms,
78
+ "svg_terms": svg_terms,
79
+ "dec": _decimals([d for _, d in text_terms]),
80
+ "higher_is_better": higher_is_better,
81
+ }
82
+
83
+ warnings = []
84
+ if len(text_terms) < len(items):
85
+ rest = text_terms[-1]
86
+ warnings.append(
87
+ f"text shows the {TEXT_TERMS - 1} largest of {len(items)} steps and sums the other "
88
+ f"{len(items) - TEXT_TERMS + 1} into one term ({_term(s, rest[1])} ({rest[0]}))."
89
+ )
90
+ if len(svg_terms) < len(items):
91
+ warnings.append(
92
+ f"SVG draws the {SVG_BARS - 1} largest of {len(items)} steps and the other "
93
+ f"{len(items) - SVG_BARS + 1} as one bar, last."
94
+ )
95
+
96
+ net = total - start
97
+ big = max(items, key=lambda kv: abs(kv[1]))
98
+ facts = [
99
+ f"{_n(s, start)} to {_n(s, total, unit)} ({_term(s, net)}) over {len(items)} step"
100
+ + ("s" if len(items) > 1 else ""),
101
+ f"largest step: {big[0]} {_term(s, big[1], unit)}",
102
+ ]
103
+ if higher_is_better is not None:
104
+ helps = sum(1 for _, d in items if d and (d > 0) == higher_is_better)
105
+ hurts = sum(1 for _, d in items if d and (d > 0) != higher_is_better)
106
+ way = "higher" if higher_is_better else "lower"
107
+ facts.append(f"{helps} step(s) help, {hurts} hurt; {way} is better")
108
+ alt = f"from {_n(s, start)} through {len(items)} steps to {_n(s, total, unit)}"
109
+ return Built(
110
+ stats=s,
111
+ facts=facts,
112
+ warnings=warnings,
113
+ alt=f"{label}: {alt}." if label else f"{alt[0].upper()}{alt[1:]}.",
114
+ )
115
+
116
+
117
+ def _fold(items: list[list], most: int) -> list[list]:
118
+ """At most ``most`` terms: the ``most − 1`` largest steps in their order, then the rest
119
+ summed as ``["N others", sum]``."""
120
+ if len(items) <= most:
121
+ return [list(kv) for kv in items]
122
+ keep = sorted(range(len(items)), key=lambda i: -abs(items[i][1]))[: most - 1]
123
+ rest = [items[i][1] for i in range(len(items)) if i not in keep]
124
+ return [list(items[i]) for i in sorted(keep)] + [[f"{len(rest)} others", sum(rest)]]
125
+
126
+
127
+ def _decimals(changes: list[float]) -> int | None:
128
+ """Decimal places that show the smallest step to one significant figure, one more when
129
+ that leaves any step more than 5% off, and at most two more than the largest step needs;
130
+ None when every step is zero."""
131
+ sizes = [abs(d) for d in changes if d]
132
+ if not sizes:
133
+ return None
134
+ dec = -math.floor(math.log10(min(sizes)))
135
+ if any(abs(round(d, dec) - d) > 0.05 * d for d in sizes):
136
+ dec += 1
137
+ return max(0, min(dec, 2 - math.floor(math.log10(max(sizes)))))
138
+
139
+
140
+ def _n(s: dict, v: float, unit: str | None = None) -> str:
141
+ if s["dec"] is None:
142
+ return fmt.num(v, unit=unit)
143
+ return fmt.fixed(v, s["dec"], unit=unit)
144
+
145
+
146
+ def _term(s: dict, d: float, unit: str | None = None) -> str:
147
+ if d == 0:
148
+ return fmt.with_unit("±0", unit)
149
+ if s["dec"] is None:
150
+ return fmt.num(d, signed=True, unit=unit)
151
+ return fmt.fixed(d, s["dec"], signed=True, unit=unit)
152
+
153
+
154
+ def _role(s: dict, d: float) -> str:
155
+ if s["higher_is_better"] is None or d == 0:
156
+ return "ink"
157
+ return "good" if (d > 0) == s["higher_is_better"] else "bad"
158
+
159
+
160
+ # --- text -----------------------------------------------------------------------------------
161
+ @text_renderer("waterfall")
162
+ def _text(chip: Chip, o: TextOptions) -> TextOut:
163
+ s = chip.stats
164
+ if o.decimals is not None: # one place for every number, as the chip's own dec is
165
+ s = {**s, "dec": o.decimals}
166
+ total = _n(s, s["total"], chip.unit)
167
+ dec = s["dec"] if s["dec"] is not None else fmt.places(total)
168
+ if o.compact:
169
+ net = _term(s, s["total"] - s["start"])
170
+ if s["start"]:
171
+ return TextOut(f"{_n(s, s['start'])}→{total} ({net})", "", dec)
172
+ n = len(s["steps"])
173
+ return TextOut(f"{total} ({n} step{'s' if n > 1 else ''})", "", dec)
174
+ terms = [_n(s, s["start"])] if s["start"] else []
175
+ folded = len(s["text_terms"]) < len(s["steps"])
176
+ for i, (name, d) in enumerate(s["text_terms"]):
177
+ last = folded and i == len(s["text_terms"]) - 1
178
+ terms.append(_term(s, d) + (f" ({name})" if last else ""))
179
+ return TextOut(f"{' '.join(terms)} = {total}", "", dec)
180
+
181
+
182
+ # --- svg ------------------------------------------------------------------------------------
183
+ @svg_renderer("waterfall")
184
+ def _svg(chip: Chip, c: Canvas) -> None:
185
+ s = chip.stats
186
+ terms = s["svg_terms"]
187
+ levels = [s["start"]]
188
+ for _, d in terms:
189
+ levels.append(levels[-1] + d)
190
+ lo, hi = min(levels), max(levels)
191
+
192
+ def y(v: float) -> float:
193
+ return c.fy(0.5 if hi == lo else (v - lo) / (hi - lo))
194
+
195
+ slots = len(terms) + 2 # start mark, one bar per step, total mark
196
+ slot = (c.right - c.left) / slots
197
+ gap = min(1.5, slot * 0.3)
198
+ w = slot - gap
199
+
200
+ def x(i: int) -> float:
201
+ return c.left + i * slot + gap / 2
202
+
203
+ ys = y(s["start"])
204
+ c.line(x(0), ys, x(0) + w, ys, title=f"start {_n(s, s['start'], chip.unit)}")
205
+ for i, (name, d) in enumerate(terms, start=1):
206
+ y0, y1 = y(levels[i - 1]), y(levels[i])
207
+ h = abs(y1 - y0)
208
+ top = min(y0, y1) - max(0.0, 1.5 - h) / 2 # a tiny step keeps a visible sliver
209
+ tip = f"{name}: {_term(s, d, chip.unit)} → {_n(s, levels[i], chip.unit)}"
210
+ c.rect(x(i), top, w, max(h, 1.5), role=_role(s, d), title=tip)
211
+ yt, xt = y(s["total"]), x(slots - 1)
212
+ c.line(xt, yt, xt + w, yt, width=2.5, title=f"total {_n(s, s['total'], chip.unit)}")