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,164 @@
1
+ """delta: a before and an after on one axis.
2
+
3
+ Text: ``0.74→0.82 (+0.08) [··○────●··]``; compact drops the parenthesis. Direction is carried
4
+ by hollow-then-solid and by the numbers, never by an arrowhead glyph. SVG: a context axis, a
5
+ connecting line, a hollow start and a solid end. The line and end turn good/bad only when the
6
+ caller passes ``higher_is_better``; otherwise the chip is ink only.
7
+
8
+ The natural domain pads the pair by half its gap on each side, so a lone delta fills the middle
9
+ of its axis; pass one ``domain=`` (``mintchip.shared_domain(a, b)``) to compare several.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+
16
+ from .. import fmt
17
+ from ..render.svg_base import Canvas
18
+ from ..render.text_base import DOT, HOLLOW, TextOptions, TextOut, Track
19
+ from ..scales import padded
20
+ from ..spec import Built, Chip, Param, chip, domain_warnings, svg_renderer, text_renderer
21
+
22
+ CELLS = 10
23
+ PAD = 0.5 # natural domain margin on each side, as a fraction of |after − before|
24
+ INSET = 0.75 # SVG plot inset beyond the Canvas pad, room for a dot pinned at the edge
25
+
26
+
27
+ @chip(
28
+ "delta",
29
+ question="How much did a value change from before to after?",
30
+ have="A before and an after value",
31
+ params=(
32
+ Param("before", "number", "Give the starting value.", required=True, positional=True),
33
+ Param("after", "number", "Give the ending value.", required=True, positional=True),
34
+ Param("domain", "range", "Fix the x-range (lo, hi); share it so deltas compare."),
35
+ Param("higher_is_better", "bool", "Declare a direction: the change turns good or bad."),
36
+ Param("label", "string", "Say what changed."),
37
+ Param("unit", "string", "Name the unit of the values."),
38
+ ),
39
+ example={"before": 0.74, "after": 0.82, "higher_is_better": True, "label": "Accuracy"},
40
+ size="m",
41
+ )
42
+ def delta(
43
+ before,
44
+ after,
45
+ *,
46
+ domain=None,
47
+ higher_is_better=None,
48
+ label=None,
49
+ unit=None,
50
+ ) -> Built:
51
+ change = after - before
52
+ better = None
53
+ if higher_is_better is not None and change != 0:
54
+ better = "good" if (change > 0) == higher_is_better else "bad"
55
+ s = {
56
+ "value": change,
57
+ "before": before,
58
+ "after": after,
59
+ "change": change,
60
+ "dec": _decimals(before, after),
61
+ "better": better,
62
+ }
63
+ lo, hi = min(before, after), max(before, after)
64
+ natural = padded(lo, hi, PAD)
65
+ warnings = _cut_lines(s, unit, domain or natural)
66
+
67
+ word = "up" if change > 0 else "down" if change < 0 else "unchanged"
68
+ facts = [f"{word} {_f(s, abs(change), unit)}" if change else "unchanged"]
69
+ if change and before != 0:
70
+ facts[0] += f" ({fmt.pct(change / abs(before), signed=True)} of the start)"
71
+ if higher_is_better is not None:
72
+ facts.append("higher is better" if higher_is_better else "lower is better")
73
+ alt = f"{_f(s, before)} to {_f(s, after, unit)}, {facts[0]}"
74
+ return Built(
75
+ stats=s,
76
+ facts=facts,
77
+ warnings=warnings,
78
+ alt=f"{label}: {alt}." if label else f"{alt[0].upper()}{alt[1:]}.",
79
+ domain=natural,
80
+ )
81
+
82
+
83
+ def _cut_lines(s: dict, unit: str | None, domain: tuple[float, float]) -> list[str]:
84
+ if domain[0] <= min(s["before"], s["after"]) and max(s["before"], s["after"]) <= domain[1]:
85
+ return []
86
+ lo, hi = fmt.num(domain[0]), fmt.num(domain[1], unit=unit)
87
+ return [
88
+ (
89
+ f"domain {lo} to {hi} cuts the change; the cut end is pinned to the edge and marked "
90
+ "(< or > in text, a chevron in SVG)."
91
+ )
92
+ ]
93
+
94
+
95
+ @domain_warnings("delta")
96
+ def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
97
+ return _cut_lines(chip.stats, chip.unit, domain)
98
+
99
+
100
+ def _decimals(before: float, after: float) -> int | None:
101
+ """One decimal place for before, after and change, set by the size of the change: one
102
+ significant figure of it (0.08), or two when one would be more than 5% off (3.8, 0.013),
103
+ or more when rounding would move any of the three by over 3% of the change (0.744→0.821
104
+ needs 0.077, not 0.08); None when nothing changed."""
105
+ change = after - before
106
+ if not change:
107
+ return None
108
+ dec = -math.floor(math.log10(abs(change)))
109
+ if abs(round(change, dec) - change) > 0.05 * abs(change):
110
+ dec += 1
111
+ return max(0, dec, fmt.resolving([before, after, change], abs(change)))
112
+
113
+
114
+ def _f(
115
+ s: dict, v: float, unit: str | None = None, *, signed: bool = False, dec: int | None = None
116
+ ) -> str:
117
+ dec = s["dec"] if dec is None else dec
118
+ if dec is None:
119
+ return fmt.num(v, signed=signed, unit=unit)
120
+ return fmt.fixed(v, dec, signed=signed, unit=unit)
121
+
122
+
123
+ def _change(s: dict, unit: str | None, dec: int | None = None) -> str:
124
+ if not s["change"]:
125
+ return f"±{_f(s, 0, unit, dec=dec)}"
126
+ return _f(s, s["change"], unit, signed=True, dec=dec)
127
+
128
+
129
+ # --- text -----------------------------------------------------------------------------------
130
+ @text_renderer("delta")
131
+ def _text(chip: Chip, o: TextOptions) -> TextOut:
132
+ s = chip.stats
133
+ dec = o.decimals if o.decimals is not None else s["dec"]
134
+ value = f"{_f(s, s['before'], dec=dec)}→{_f(s, s['after'], chip.unit, dec=dec)}"
135
+ if not o.compact:
136
+ value += f" ({_change(s, chip.unit, dec)})"
137
+ t = Track(CELLS, o.domain)
138
+ t.span(s["before"], s["after"], ends=False, role=s["better"])
139
+ t.put(s["before"], HOLLOW)
140
+ t.put(s["after"], DOT, s["better"]) # unchanged: the solid end covers the hollow start
141
+ shown = dec if dec is not None else fmt.places(fmt.num(s["after"]))
142
+ return TextOut(value, t.glyph(), shown)
143
+
144
+
145
+ # --- svg ------------------------------------------------------------------------------------
146
+ @svg_renderer("delta")
147
+ def _svg(chip: Chip, c: Canvas) -> None:
148
+ s = chip.stats
149
+ y = c.mid
150
+ # The plot ends INSET inside the pad, so a dot pinned at an edge (the hollow start reaches
151
+ # 3.25 with its stroke) stays inside the chip.
152
+ c.left, c.right = c.left + INSET, c.right - INSET
153
+ c.line(c.left, y, c.right, y, role="context", width=1.25)
154
+ xb, xa = c.x(s["before"]), c.x(s["after"])
155
+ role = s["better"] or "ink"
156
+ start, end = _f(s, s["before"], chip.unit), _f(s, s["after"], chip.unit)
157
+ if abs(xa - xb) < 1: # unchanged at this scale: a ring around a dot
158
+ xb = xa = min(max(xb, c.left + 0.75), c.right - 0.75) # the ring reaches 4.0
159
+ c.dot(xb, y, r=3.25, hollow=True, title=start)
160
+ c.dot(xa, y, r=1.75, title=end)
161
+ return
162
+ c.line(xb, y, xa, y, role=role, width=1.75)
163
+ c.dot(xb, y, r=2.5, hollow=True, title=start)
164
+ c.dot(xa, y, r=2.75, role=role, title=f"{end} ({_change(s, chip.unit)})")
mintchip/chips/dist.py ADDED
@@ -0,0 +1,384 @@
1
+ """dist: raw samples as a word-sized distribution, with outliers kept off the scale.
2
+
3
+ Text: ``med 20.3 ms (n=10, IQR 19.9 to 21.4) [▃▃▃█·▃▃··▃]→47.8``; compact drops the
4
+ parenthesis. One histogram cell per tenth of the domain, ``·`` where a cell is empty.
5
+ With ``threshold=`` the value is the exceedance probability, ``P>25 ms 15% (3 of 20)``, and a
6
+ ``│`` is inserted at the threshold.
7
+
8
+ SVG: for n ≤ DOTS a rug, one ink tick per sample (samples too close to tell apart share one
9
+ tick, as much wider as they are many), with the median as an accent dot under it; above DOTS a
10
+ quantile dotplot of DOTS dots (each dot is 1/DOTS of the samples), stacked from the floor, which
11
+ shows where samples pile up better than a rug of that many ticks would at 1×. Threshold as a
12
+ context line, with the marks above it in accent (and no median dot: the value is then the
13
+ share above); reference as a dashed context line.
14
+
15
+ Outliers beyond FENCE × IQR do not stretch the scale (v0.1 let one 47.8 squeeze ten points
16
+ into a blob). They lie outside the natural domain, so both renderers clip them to an edge
17
+ marker: ``→47.8`` in text, a chevron in SVG, and a line in ``warnings``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+
24
+ from .. import fmt
25
+ from ..render.svg_base import Canvas
26
+ from ..render.text_base import REF, TRACK, Segment, TextOptions, TextOut, level
27
+ from ..scales import padded, quantile, robust_extent
28
+ from ..spec import (
29
+ Built,
30
+ Chip,
31
+ ChipError,
32
+ Param,
33
+ chip,
34
+ domain_warnings,
35
+ svg_renderer,
36
+ text_renderer,
37
+ )
38
+
39
+ CELLS = 10 # text histogram cells across the domain
40
+ DOTS = 20 # raw dots up to this many samples; above, this many quantile dots
41
+ FENCE = 3.0 # samples beyond FENCE × IQR from the quartiles are outliers
42
+ PAD = 0.06 # natural domain margin, as a fraction of the drawn extent
43
+ R = 1.75 # dot radius
44
+ PITCH = 2 * R + 0.5 # dots closer than this share a stack
45
+ WEIGHT = 1.5 # rug tick width per sample it stands for
46
+ TICK_MAX = 4.5 # widest rug tick (three or more samples in one place)
47
+ TICK_PITCH = 2.5 # rug ticks whose centres are closer than this merge into one, wider
48
+ RUG = (2.0, 10.5) # rug tick top and bottom, leaving room under it for the median
49
+ MEDIAN_Y = 13.75 # the median: an accent dot under the rug, on the text baseline
50
+ EDGE = 6.0 # plot inset on a clipped side, room for the chevron
51
+
52
+
53
+ @chip(
54
+ "dist",
55
+ question="How are the samples spread, and are there outliers?",
56
+ have="Raw samples of one measurement",
57
+ params=(
58
+ Param(
59
+ "samples",
60
+ "numbers",
61
+ "Give the raw samples; None or NaN is skipped and counted.",
62
+ required=True,
63
+ positional=True,
64
+ ),
65
+ Param("threshold", "number", "Give a cutoff; the value becomes P(sample > cutoff)."),
66
+ Param("reference", "number", "Give a reference value, drawn as a dashed line."),
67
+ Param("domain", "range", "Fix the x-range (lo, hi); share it so dist chips compare."),
68
+ Param("label", "string", "Say what was sampled."),
69
+ Param("unit", "string", "Name the unit of the samples."),
70
+ ),
71
+ example={
72
+ "samples": [18.9, 19.4, 19.8, 20.1, 20.3, 20.3, 20.9, 21.6, 22.8, 47.8],
73
+ "unit": "ms",
74
+ "label": "Request latency",
75
+ },
76
+ size="m",
77
+ )
78
+ def dist(
79
+ samples,
80
+ *,
81
+ threshold=None,
82
+ reference=None,
83
+ domain=None,
84
+ label=None,
85
+ unit=None,
86
+ ) -> Built:
87
+ xs = sorted(v for v in samples if v is not None)
88
+ missing = len(samples) - len(xs)
89
+ if len(xs) < 2:
90
+ raise ChipError(
91
+ f"needs at least 2 numbers in samples; got {len(xs)}.",
92
+ fix_hint="Pass the raw observations, e.g. mintchip.dist([19.8, 20.3, 21.1, 47.8]).",
93
+ )
94
+ n = len(xs)
95
+ q1, med, q3 = (quantile(xs, q) for q in (0.25, 0.5, 0.75))
96
+ core = robust_extent(xs, FENCE)
97
+ outliers = [v for v in xs if not core[0] <= v <= core[1]]
98
+ drawn = [*core] + [v for v in (threshold, reference) if v is not None]
99
+ natural = padded(min(drawn), max(drawn), PAD)
100
+ sig = _sig(q1, q3) if q3 > q1 else _sig(xs[0], xs[-1])
101
+ dec = _decimals([q1, med, q3], sig, q3 - q1 if q3 > q1 else xs[-1] - xs[0])
102
+ s = {
103
+ "n": n,
104
+ "samples": xs,
105
+ "quantiles": [quantile(xs, (k + 0.5) / DOTS) for k in range(DOTS)] if n > DOTS else None,
106
+ "median": med,
107
+ "q1": q1,
108
+ "q3": q3,
109
+ "min": xs[0],
110
+ "max": xs[-1],
111
+ "mean": math.fsum(xs) / n,
112
+ "outliers": outliers,
113
+ "threshold": threshold,
114
+ "reference": reference,
115
+ "above": None,
116
+ "p": None,
117
+ "sig": sig,
118
+ "dec": dec,
119
+ "missing": missing,
120
+ }
121
+ if threshold is not None:
122
+ s["above"] = sum(v > threshold for v in xs)
123
+ s["p"] = s["above"] / n
124
+ s["value"] = s["p"] if threshold is not None else med
125
+
126
+ def f(v: float, u: str | None = None) -> str:
127
+ return _f(s, v, u)
128
+
129
+ def far(v: float) -> str:
130
+ return fmt.num(v, sig=sig)
131
+
132
+ warnings = []
133
+ if missing:
134
+ warnings.append(f"{missing} missing sample(s) skipped; n={n} counts the rest.")
135
+ warnings += _cut_lines(s, unit, domain or natural, domain is None)
136
+
137
+ name = f"{label}: " if label else ""
138
+ facts = [
139
+ f"n={n}, median {f(med, unit)}, IQR {f(q1)} to {f(q3, unit)}",
140
+ f"range {f(xs[0])} to {f(xs[-1], unit)}",
141
+ ]
142
+ if outliers:
143
+ facts.append(f"{len(outliers)} outlier(s) beyond {FENCE:g}×IQR: {_list(outliers, far)}")
144
+ alt = f"{name}distribution of {n} samples, median {f(med, unit)}"
145
+ if threshold is not None:
146
+ share, cut_at = fmt.pct(s["p"]), fmt.num(threshold, sig=sig, unit=unit)
147
+ facts.append(f"{s['above']} of {n} samples above {cut_at} ({share})")
148
+ alt += f", {share} above {cut_at}"
149
+ if reference is not None:
150
+ facts.append(f"reference {fmt.num(reference, sig=sig, unit=unit)}")
151
+ return Built(stats=s, facts=facts, warnings=warnings, alt=alt + ".", domain=natural)
152
+
153
+
154
+ def _cut_lines(s: dict, unit: str | None, dom: tuple[float, float], own: bool) -> list[str]:
155
+ cut = [v for v in s["samples"] if not dom[0] <= v <= dom[1]]
156
+ if not cut:
157
+ return []
158
+ what = f"{len(cut)} sample(s) ({_list(cut, lambda v: fmt.num(v, sig=s['sig']))})"
159
+ why = (
160
+ f"{what} beyond {FENCE:g}×IQR clipped so they do not flatten the scale"
161
+ if own
162
+ else f"domain {fmt.num(dom[0])} to {fmt.num(dom[1], unit=unit)} cuts {what}"
163
+ )
164
+ return [
165
+ (
166
+ f"{why}; their values are printed past the brackets in text and a chevron marks "
167
+ "the edge in SVG."
168
+ )
169
+ ]
170
+
171
+
172
+ @domain_warnings("dist")
173
+ def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
174
+ return _cut_lines(chip.stats, chip.unit, domain, own)
175
+
176
+
177
+ def _sig(lo: float, hi: float) -> int:
178
+ """Significant figures that resolve the spread: 3, or more for a narrow spread at a high
179
+ level (1000.2 to 1000.6 prints as 1000.4, not 1,000)."""
180
+ spread, size = hi - lo, max(abs(lo), abs(hi))
181
+ if spread <= 0 or size == 0:
182
+ return 3
183
+ return min(6, max(3, math.ceil(math.log10(size / spread)) + 1))
184
+
185
+
186
+ def _decimals(values: list[float], sig: int, width: float) -> int | None:
187
+ """One decimal place for every number in a dist, so 17.0 and 23.9 line up: what ``sig``
188
+ figures give, or more when rounding would move a quartile by over 3% of ``width`` (the
189
+ IQR); None when a value needs scientific notation."""
190
+ places = []
191
+ for v in values:
192
+ t = fmt.num(v, sig=sig)
193
+ if "e" in t:
194
+ return None
195
+ places.append(len(t.split(".")[1]) if "." in t else 0)
196
+ return max(*places, fmt.resolving(values, width))
197
+
198
+
199
+ def _f(s: dict, v: float, unit: str | None = None, dec: int | None = None) -> str:
200
+ dec = s["dec"] if dec is None else dec
201
+ if dec is None:
202
+ return fmt.num(v, sig=s["sig"], unit=unit)
203
+ return fmt.fixed(v, dec, unit=unit)
204
+
205
+
206
+ def _list(values: list[float], f) -> str:
207
+ shown = ", ".join(f(v) for v in values[:3])
208
+ return shown + (f" and {len(values) - 3} more" if len(values) > 3 else "")
209
+
210
+
211
+ def _clip_text(values: list[float], f) -> str:
212
+ """The clipped samples on one side: the one value, or nearest..farthest."""
213
+ if len(values) == 1:
214
+ return f(values[0])
215
+ return f"{f(values[0])}..{f(values[-1])}"
216
+
217
+
218
+ # --- text -----------------------------------------------------------------------------------
219
+ @text_renderer("dist")
220
+ def _text(chip: Chip, o: TextOptions) -> TextOut:
221
+ s = chip.stats
222
+ dec = s["dec"] if o.decimals is None or s["dec"] is None else o.decimals
223
+
224
+ def f(v: float, u: str | None = None) -> str:
225
+ return _f(s, v, u, dec)
226
+
227
+ t = s["threshold"]
228
+ if t is not None:
229
+ value = f"P>{fmt.num(t, sig=s['sig'], unit=chip.unit)} {fmt.pct(s['p'])}"
230
+ if not o.compact:
231
+ value += f" ({s['above']} of {s['n']})"
232
+ else:
233
+ value = f"med {f(s['median'], chip.unit)}"
234
+ if not o.compact:
235
+ value += f" (n={s['n']}, IQR {f(s['q1'])} to {f(s['q3'])})"
236
+
237
+ lo, hi = o.domain
238
+ xs = s["samples"]
239
+ counts = [0] * CELLS
240
+ for v in xs:
241
+ if lo <= v <= hi:
242
+ counts[min(CELLS - 1, int((v - lo) / (hi - lo) * CELLS))] += 1
243
+ peak = max(counts)
244
+ cells: list[Segment] = [(level(k, 0, peak) if k else TRACK, None) for k in counts]
245
+ ref = s["reference"]
246
+ if ref is not None and lo <= ref <= hi:
247
+ i = min(CELLS - 1, int((ref - lo) / (hi - lo) * CELLS))
248
+ if not counts[i]: # data wins over context, as in ci
249
+ cells[i] = (REF, "context")
250
+ if t is not None and lo <= t <= hi:
251
+ b = round((t - lo) / (hi - lo) * CELLS)
252
+ tail = [(ch, "accent" if role is None else role) for ch, role in cells[b:]]
253
+ cells = [*cells[:b], (REF, "context"), *tail]
254
+
255
+ below = [v for v in xs if v < lo]
256
+ above = [v for v in xs if v > hi]
257
+
258
+ def far(v: float) -> str: # clipped values sit far from the core: no shared decimals
259
+ return fmt.num(v, sig=s["sig"])
260
+
261
+ glyph: list[Segment] = []
262
+ if below:
263
+ glyph.append((f"{_clip_text(below[::-1], far)}→", None))
264
+ glyph += [("[", None), *cells, ("]", None)]
265
+ if above:
266
+ glyph.append((f"→{_clip_text(above, far)}", None))
267
+ shown = None if t is not None else dec if dec is not None else fmt.places(value)
268
+ return TextOut(value, _merge(glyph), shown)
269
+
270
+
271
+ def _merge(segs: list[Segment]) -> list[Segment]:
272
+ out: list[Segment] = []
273
+ for text, role in segs:
274
+ if out and out[-1][1] == role:
275
+ out[-1] = (out[-1][0] + text, role)
276
+ else:
277
+ out.append((text, role))
278
+ return out
279
+
280
+
281
+ # --- svg ------------------------------------------------------------------------------------
282
+ @svg_renderer("dist")
283
+ def _svg(chip: Chip, c: Canvas) -> None:
284
+ s = chip.stats
285
+ lo, hi = c.domain
286
+ xs = s["samples"]
287
+ below = [v for v in xs if v < lo]
288
+ above = [v for v in xs if v > hi]
289
+ if below:
290
+ c.left += EDGE
291
+ if above:
292
+ c.right -= EDGE
293
+
294
+ t, ref = s["threshold"], s["reference"]
295
+ if ref is not None and c.contains(ref):
296
+ x = c.x(ref)
297
+ c.line(x, 1.5, x, 14.5, role="context", dash=(2, 1.5))
298
+ if t is not None and c.contains(t):
299
+ x = c.x(t)
300
+ c.line(x, 1.5, x, 14.5, role="context")
301
+
302
+ if s["quantiles"] is None:
303
+ _rug(chip, c, [v for v in xs if lo <= v <= hi])
304
+ else:
305
+ _dotplot(c, [v for v in s["quantiles"] if lo <= v <= hi], t)
306
+
307
+ if below:
308
+ far = fmt.num(below[0], sig=s["sig"], unit=chip.unit)
309
+ _chevron(c, c.left - R - 1.25, -1, f"{len(below)} below the scale, to {far}")
310
+ if above:
311
+ far = fmt.num(above[-1], sig=s["sig"], unit=chip.unit)
312
+ _chevron(c, c.right + R + 1.25, 1, f"{len(above)} above the scale, to {far}")
313
+
314
+
315
+ def _rug(chip: Chip, c: Canvas, pts: list[float]) -> None:
316
+ """One ink tick per sample; samples closer than TICK_PITCH share one tick at their mean,
317
+ as wide as their count (WEIGHT per sample, at most TICK_MAX), so a tie reads as two.
318
+ With a threshold the ticks past it are accent; without, an accent dot under the rug marks
319
+ the median, the number the value prints."""
320
+ s, t = chip.stats, chip.stats["threshold"]
321
+ groups = [g for side in _sides(pts, t) for g in _groups(c, side, TICK_PITCH)]
322
+ for x, members in groups:
323
+ role = "accent" if t is not None and members[0] > t else "ink"
324
+ k, a, b = len(members), members[0], members[-1]
325
+ title = _f(s, a, chip.unit)
326
+ if k > 1:
327
+ title = f"{title} ×{k}" if a == b else f"{_f(s, a)} to {_f(s, b, chip.unit)} ({k})"
328
+ w = min(WEIGHT * k, TICK_MAX)
329
+ inset = (w - WEIGHT) / 2 # round caps: a heavier tick keeps the same visible length
330
+ c.line(x, RUG[0] + inset, x, RUG[1] - inset, role=role, width=w, title=title)
331
+ if t is None and c.contains(s["median"]):
332
+ x = c.x(s["median"])
333
+ tip = f"median {_f(s, s['median'], chip.unit)}"
334
+ c.dot(x, MEDIAN_Y, r=R, role="accent", title=tip)
335
+
336
+
337
+ def _sides(pts: list[float], t: float | None) -> list[list[float]]:
338
+ return [pts] if t is None else [[v for v in pts if v <= t], [v for v in pts if v > t]]
339
+
340
+
341
+ def _groups(c: Canvas, values: list[float], pitch: float) -> list[tuple[float, list[float]]]:
342
+ """A value within ``pitch`` of its group's first value joins that group; the group sits at
343
+ the mean x of its members."""
344
+ groups: list[tuple[float, list[float], list[float]]] = []
345
+ for v in sorted(values):
346
+ x = c.x(v)
347
+ if groups and x - groups[-1][0] < pitch:
348
+ groups[-1][1].append(x)
349
+ groups[-1][2].append(v)
350
+ else:
351
+ groups.append((x, [x], [v]))
352
+ return [(sum(px) / len(px), vs) for _, px, vs in groups]
353
+
354
+
355
+ def _dotplot(c: Canvas, pts: list[float], t: float | None) -> None:
356
+ """DOTS quantile dots (each 1/DOTS of the samples), stacked from the floor."""
357
+ stacks = _spread([g for side in _sides(pts, t) for g in _groups(c, side, PITCH)],
358
+ c.left, c.right) # fmt: skip
359
+ tallest = max((len(m) for _, m in stacks), default=1)
360
+ dy = 2 * R + 0.25 if tallest <= 3 else (c.bottom - c.top - 2 * R) / (tallest - 1)
361
+ for x, members in stacks:
362
+ for i, v in enumerate(members):
363
+ role = "accent" if t is not None and v > t else "ink"
364
+ c.dot(x, c.bottom - R - i * dy, r=R, role=role)
365
+
366
+
367
+ def _spread(stacks: list[tuple[float, list[float]]], left: float, right: float):
368
+ """Push stacks apart to at least PITCH, then back inside [left, right]."""
369
+ xs = [x for x, _ in stacks]
370
+ for i in range(1, len(xs)):
371
+ xs[i] = max(xs[i], xs[i - 1] + PITCH)
372
+ if xs and xs[-1] > right:
373
+ xs[-1] = right
374
+ for i in range(len(xs) - 2, -1, -1):
375
+ xs[i] = min(xs[i], xs[i + 1] - PITCH)
376
+ xs = [max(x, left) for x in xs]
377
+ return [(x, m) for x, (_, m) in zip(xs, stacks, strict=True)]
378
+
379
+
380
+ def _chevron(c: Canvas, x: float, d: int, title: str) -> None:
381
+ """An edge marker for clipped samples: an arrowhead pointing off the plot, its back at
382
+ ``x`` and its tip 2.5 units further in direction ``d`` (-1 left, 1 right)."""
383
+ y = c.mid
384
+ c.path([(x, y - 3), (x + 2.5 * d, y), (x, y + 3)], width=1.25, title=title)
@@ -0,0 +1,129 @@
1
+ """funnel: counts through stages.
2
+
3
+ Text prints the counts and the overall retention and no glyph (design rule 6):
4
+ ``1,200 → 520 → 350 → 290 (24%)``; compact keeps the first and last stage,
5
+ ``1,200 → 290 (24%)``. A stage larger than the one before is announced, not hidden: it is
6
+ marked ``!`` in text (and compact falls back to the full line), drawn as an outlined bar in SVG,
7
+ and named in ``warnings``.
8
+
9
+ SVG: one bar per stage on a zero baseline, heights linear in the count. The stage after the
10
+ steepest drop, the largest fraction lost from one stage to the next, is in accent.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import itertools
16
+
17
+ from .. import fmt
18
+ from ..render.svg_base import Canvas
19
+ from ..render.text_base import TextOptions, TextOut
20
+ from ..spec import Built, Chip, ChipError, Param, chip, svg_renderer, text_renderer
21
+
22
+ _HINT = (
23
+ 'Pass 2+ stages with counts, first > 0, e.g. mintchip.funnel({"visited": 1200, "paid": 290}).'
24
+ )
25
+
26
+
27
+ @chip(
28
+ "funnel",
29
+ question="How many make it through each stage?",
30
+ have="Counts through ordered stages",
31
+ params=(
32
+ Param(
33
+ "stages",
34
+ "mapping",
35
+ "Give the stages in order, name → count.",
36
+ required=True,
37
+ positional=True,
38
+ ),
39
+ Param("label", "string", "Say what flows through the stages."),
40
+ ),
41
+ example={"stages": {"visited": 1200, "signed up": 520, "activated": 350, "retained": 290}},
42
+ size="m",
43
+ )
44
+ def funnel(stages, *, label=None) -> Built:
45
+ if len(stages) < 2:
46
+ raise ChipError(f"needs at least 2 stages; got {len(stages)}.", fix_hint=_HINT)
47
+ for name, n in stages.items():
48
+ if isinstance(n, tuple) or n < 0:
49
+ raise ChipError(
50
+ f"stage {name!r} must be a count of zero or more; got {n!r}.", fix_hint=_HINT
51
+ )
52
+ names, counts = list(stages), list(stages.values())
53
+ if counts[0] <= 0:
54
+ raise ChipError(f"the first stage {names[0]!r} must be positive.", fix_hint=_HINT)
55
+
56
+ kept = [b / a if a else None for a, b in itertools.pairwise(counts)] # stage conversion
57
+ losses = [(1 - k, i + 1) for i, k in enumerate(kept) if k is not None and k < 1]
58
+ steepest = max(losses)[1] if losses else None
59
+ rises = [i for i in range(1, len(counts)) if counts[i] > counts[i - 1]]
60
+ s = {
61
+ "value": counts[-1] / counts[0],
62
+ "names": names,
63
+ "counts": counts,
64
+ "retention": counts[-1] / counts[0],
65
+ "steepest": steepest,
66
+ "rises": rises,
67
+ "whole": all(float(n).is_integer() for n in counts),
68
+ }
69
+
70
+ warnings = [
71
+ f"stage {names[i]!r} ({_c(s, counts[i])}) is larger than {names[i - 1]!r} "
72
+ f"({_c(s, counts[i - 1])}); marked ! in text and outlined in SVG."
73
+ for i in rises
74
+ ]
75
+ facts = [f"{len(counts)} stages, {fmt.pct(s['retention'])} of {names[0]} reach {names[-1]}"]
76
+ if steepest is not None:
77
+ a, b = steepest - 1, steepest
78
+ facts.append(
79
+ f"steepest drop: {names[a]} → {names[b]}, {fmt.pct(1 - kept[a])} lost "
80
+ f"({_c(s, counts[a] - counts[b])})"
81
+ )
82
+ facts.append("stage conversion " + ", ".join("—" if k is None else fmt.pct(k) for k in kept))
83
+ alt = f"funnel of {len(counts)} stages from {_c(s, counts[0])} to {_c(s, counts[-1])}, "
84
+ alt += f"{fmt.pct(s['retention'])} retained"
85
+ return Built(
86
+ stats=s,
87
+ facts=facts,
88
+ warnings=warnings,
89
+ alt=f"{label}: {alt}." if label else f"{alt[0].upper()}{alt[1:]}.",
90
+ )
91
+
92
+
93
+ def _c(s: dict, n: float) -> str:
94
+ return fmt.count(n) if s["whole"] else fmt.num(n)
95
+
96
+
97
+ # --- text -----------------------------------------------------------------------------------
98
+ @text_renderer("funnel")
99
+ def _text(chip: Chip, o: TextOptions) -> TextOut:
100
+ s = chip.stats
101
+ shown = [_c(s, n) + ("!" if i in s["rises"] else "") for i, n in enumerate(s["counts"])]
102
+ if o.compact and not s["rises"]:
103
+ shown = [shown[0], shown[-1]]
104
+ return TextOut(f"{' → '.join(shown)} ({fmt.pct(s['retention'])})")
105
+
106
+
107
+ # --- svg ------------------------------------------------------------------------------------
108
+ @svg_renderer("funnel")
109
+ def _svg(chip: Chip, c: Canvas) -> None:
110
+ s = chip.stats
111
+ counts = s["counts"]
112
+ top = max(counts)
113
+ slot = (c.right - c.left) / len(counts)
114
+ gap = min(2.0, slot * 0.3)
115
+ w = slot - gap
116
+ for i, (name, n) in enumerate(zip(s["names"], counts, strict=True)):
117
+ x = c.left + i * slot + gap / 2
118
+ tip = f"{name}: {_c(s, n)} ({fmt.pct(n / counts[0])})"
119
+ if n == 0: # nothing left: a context floor, so the stage is still seen
120
+ c.line(x, c.bottom, x + w, c.bottom, role="context", title=tip)
121
+ continue
122
+ h = max(c.bottom - c.fy(n / top), 1.5)
123
+ y = c.bottom - h
124
+ if i in s["rises"]: # announced distortion: an outlined bar
125
+ pts = [(x + 0.75, c.bottom), (x + 0.75, y + 0.75), (x + w - 0.75, y + 0.75),
126
+ (x + w - 0.75, c.bottom)] # fmt: skip
127
+ c.path(pts, width=1.5, title=tip)
128
+ continue
129
+ c.rect(x, y, w, h, role="accent" if i == s["steepest"] else "ink", title=tip)