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.
- mintchip/__init__.py +101 -0
- mintchip/__main__.py +7 -0
- mintchip/chips/__init__.py +7 -0
- mintchip/chips/bar.py +233 -0
- mintchip/chips/ci.py +194 -0
- mintchip/chips/delta.py +164 -0
- mintchip/chips/dist.py +384 -0
- mintchip/chips/funnel.py +129 -0
- mintchip/chips/gauge.py +197 -0
- mintchip/chips/num.py +55 -0
- mintchip/chips/rank.py +182 -0
- mintchip/chips/ratio.py +141 -0
- mintchip/chips/share.py +164 -0
- mintchip/chips/spark.py +278 -0
- mintchip/chips/strip.py +173 -0
- mintchip/chips/timeline.py +257 -0
- mintchip/chips/waterfall.py +212 -0
- mintchip/cli.py +691 -0
- mintchip/diff.py +645 -0
- mintchip/directives.py +782 -0
- mintchip/doctor.py +145 -0
- mintchip/fmt.py +135 -0
- mintchip/guide.py +189 -0
- mintchip/ingest.py +725 -0
- mintchip/prose.py +225 -0
- mintchip/render/__init__.py +1 -0
- mintchip/render/html.py +295 -0
- mintchip/render/svg_base.py +337 -0
- mintchip/render/text_base.py +215 -0
- mintchip/scales.py +117 -0
- mintchip/skill.py +332 -0
- mintchip/spec.py +659 -0
- mintchip/tables.py +1043 -0
- mintchip/themes.py +102 -0
- mintchip-0.2.0.dist-info/METADATA +274 -0
- mintchip-0.2.0.dist-info/RECORD +39 -0
- mintchip-0.2.0.dist-info/WHEEL +4 -0
- mintchip-0.2.0.dist-info/entry_points.txt +2 -0
- mintchip-0.2.0.dist-info/licenses/LICENSE +21 -0
mintchip/chips/share.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""share: parts of a whole, as one run of ink in opacity steps, largest first by default.
|
|
2
|
+
|
|
3
|
+
Text: ``62·28·10% ██████▏███▏█``: the parts' percentages, then CELLS cells split among them,
|
|
4
|
+
separated by thin gaps. SVG: one bar of segments in ink at falling opacity, with gaps.
|
|
5
|
+
Never categorical colours, never textures.
|
|
6
|
+
|
|
7
|
+
``sort=False`` keeps the caller's order instead, and the opacity steps follow position, so in
|
|
8
|
+
a table column of rows with the same parts each part has the same place and shade in every row
|
|
9
|
+
(``mintchip.table`` does this by itself when the rows' part names agree).
|
|
10
|
+
|
|
11
|
+
At most MAX_SEGMENTS segments: with more parts than that, the first MAX_SEGMENTS − 1 (the
|
|
12
|
+
largest, or the first given with ``sort=False``) are shown and the rest are folded into one
|
|
13
|
+
"other" segment, drawn last and announced as ``other=N`` after the glyph. A part too small to
|
|
14
|
+
earn a cell gets one half-height cell (``▄``) taken from the largest part, and a warning.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from .. import fmt
|
|
20
|
+
from ..render.svg_base import Canvas
|
|
21
|
+
from ..render.text_base import GAP, TextOptions, TextOut, cell_counts
|
|
22
|
+
from ..spec import Built, Chip, ChipError, Param, chip, svg_renderer, text_renderer
|
|
23
|
+
|
|
24
|
+
CELLS = 10 # text cells for the whole; each is 10%
|
|
25
|
+
MAX_SEGMENTS = 4 # beyond this, opacity steps stop reading at 1x
|
|
26
|
+
OPACITY = (1.0, 0.66, 0.44, 0.28) # segment i's ink opacity, by position
|
|
27
|
+
SMALL = "▄" # a part under one cell, drawn as a half-height cell
|
|
28
|
+
BAR = (4.0, 8.0) # SVG bar top and height
|
|
29
|
+
GAP_W = 1.5 # SVG gap between segments
|
|
30
|
+
MIN_W = 1.5 # SVG minimum segment width
|
|
31
|
+
HINT = 'Pass sizes by name, e.g. mintchip.share({"code": 62, "docs": 28, "tests": 10}).'
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@chip(
|
|
35
|
+
"share",
|
|
36
|
+
question="How is a whole split into parts?",
|
|
37
|
+
have="Parts of a whole",
|
|
38
|
+
params=(
|
|
39
|
+
Param(
|
|
40
|
+
"parts",
|
|
41
|
+
"mapping",
|
|
42
|
+
"Give each part's size by name; they are shown as shares of their sum.",
|
|
43
|
+
required=True,
|
|
44
|
+
positional=True,
|
|
45
|
+
),
|
|
46
|
+
Param(
|
|
47
|
+
"sort",
|
|
48
|
+
"bool",
|
|
49
|
+
"Order parts largest first; False keeps your order, so rows of a table compare.",
|
|
50
|
+
default=True,
|
|
51
|
+
),
|
|
52
|
+
Param("label", "string", "Say what the whole is."),
|
|
53
|
+
Param("unit", "string", "Name the unit of the part sizes."),
|
|
54
|
+
),
|
|
55
|
+
example={"parts": {"code": 62, "docs": 28, "tests": 10}, "label": "Changed lines"},
|
|
56
|
+
size="m",
|
|
57
|
+
)
|
|
58
|
+
def share(parts, *, sort=True, label=None, unit=None) -> Built:
|
|
59
|
+
if not parts:
|
|
60
|
+
raise ChipError("needs at least 1 part; got none.", fix_hint=HINT)
|
|
61
|
+
for name, v in parts.items():
|
|
62
|
+
if isinstance(v, tuple):
|
|
63
|
+
raise ChipError(
|
|
64
|
+
f"part {name!r} must be one size; got the pair {v}.",
|
|
65
|
+
fix_hint="Pass one number per part; (start, end) spans belong to timeline.",
|
|
66
|
+
)
|
|
67
|
+
if v <= 0:
|
|
68
|
+
raise ChipError(
|
|
69
|
+
f"part {name!r} must be positive; got {fmt.num(v)}.",
|
|
70
|
+
fix_hint="Leave out parts of size 0; a share is a positive size.",
|
|
71
|
+
)
|
|
72
|
+
total = sum(parts.values())
|
|
73
|
+
ranked = list(parts.items())
|
|
74
|
+
if sort:
|
|
75
|
+
ranked.sort(key=lambda kv: -kv[1]) # stable: ties keep their order
|
|
76
|
+
folded = 0
|
|
77
|
+
if len(ranked) > MAX_SEGMENTS:
|
|
78
|
+
rest = ranked[MAX_SEGMENTS - 1 :]
|
|
79
|
+
folded = len(rest)
|
|
80
|
+
ranked = [*ranked[: MAX_SEGMENTS - 1], ("other", sum(v for _, v in rest))]
|
|
81
|
+
names = [n for n, _ in ranked]
|
|
82
|
+
sizes = [v for _, v in ranked]
|
|
83
|
+
fracs = [v / total for v in sizes]
|
|
84
|
+
cells, small = cell_counts(fracs, CELLS)
|
|
85
|
+
|
|
86
|
+
warnings = []
|
|
87
|
+
if folded:
|
|
88
|
+
warnings.append(
|
|
89
|
+
f"{folded} parts beyond the {'largest' if sort else 'first'} {MAX_SEGMENTS - 1} are "
|
|
90
|
+
f"folded into one 'other' segment ({fmt.pct(fracs[-1])}), drawn last (marked other={folded})."
|
|
91
|
+
)
|
|
92
|
+
for i in (i for i, s in enumerate(small) if s):
|
|
93
|
+
warnings.append(
|
|
94
|
+
f"{_who(names, i, folded)} ({fmt.pct(fracs[i])}) is under one text cell of "
|
|
95
|
+
f"{CELLS}; it is drawn as one half-height cell ({SMALL}) taken from the largest part."
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
facts = [
|
|
99
|
+
f"{_who(names, i, folded)} {fmt.num(v, unit=unit)} ({fmt.pct(f)})"
|
|
100
|
+
for i, (v, f) in enumerate(zip(sizes, fracs, strict=True))
|
|
101
|
+
]
|
|
102
|
+
facts.append(f"total {fmt.num(total, unit=unit)}")
|
|
103
|
+
name = f"{label}: " if label else ""
|
|
104
|
+
split = ", ".join(f"{_who(names, i, folded)} {fmt.pct(f)}" for i, f in enumerate(fracs))
|
|
105
|
+
return Built(
|
|
106
|
+
stats={
|
|
107
|
+
"value": fracs[0],
|
|
108
|
+
"names": names,
|
|
109
|
+
"sizes": sizes,
|
|
110
|
+
"fracs": fracs,
|
|
111
|
+
"cells": cells,
|
|
112
|
+
"small": small,
|
|
113
|
+
"folded": folded,
|
|
114
|
+
"total": total,
|
|
115
|
+
},
|
|
116
|
+
facts=facts,
|
|
117
|
+
warnings=warnings,
|
|
118
|
+
alt=f"{name}{len(parts)} parts of a whole: {split}.",
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _who(names: list[str], i: int, folded: int) -> str:
|
|
123
|
+
if folded and i == len(names) - 1:
|
|
124
|
+
return f"other ({folded} parts)"
|
|
125
|
+
return names[i]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _pct(f: float) -> str:
|
|
129
|
+
return fmt.pct(f)[:-1]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# --- text -----------------------------------------------------------------------------------
|
|
133
|
+
@text_renderer("share")
|
|
134
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
135
|
+
s = chip.stats
|
|
136
|
+
sep = "/" if o.ascii else "·" # "62.28.10%" would read as one decimal number
|
|
137
|
+
value = sep.join(_pct(f) for f in s["fracs"]) + "%"
|
|
138
|
+
glyph: list[tuple[str, str | None]] = []
|
|
139
|
+
last = len(s["cells"]) - 1
|
|
140
|
+
for i, (n, small) in enumerate(zip(s["cells"], s["small"], strict=True)):
|
|
141
|
+
if i:
|
|
142
|
+
glyph.append((GAP, None))
|
|
143
|
+
role = "context" if s["folded"] and i == last else None
|
|
144
|
+
glyph.append((SMALL if small else "█" * n, role))
|
|
145
|
+
if s["folded"]:
|
|
146
|
+
glyph.append((f" other={s['folded']}", None))
|
|
147
|
+
return TextOut(value, glyph)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
151
|
+
@svg_renderer("share")
|
|
152
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
153
|
+
s = chip.stats
|
|
154
|
+
fracs = s["fracs"]
|
|
155
|
+
room = c.right - c.left - GAP_W * (len(fracs) - 1)
|
|
156
|
+
widths = [max(MIN_W, f * room) for f in fracs]
|
|
157
|
+
big = widths.index(max(widths))
|
|
158
|
+
widths[big] -= sum(widths) - room # a part lifted to MIN_W is paid for by the largest
|
|
159
|
+
x = c.left
|
|
160
|
+
for i, (w, f) in enumerate(zip(widths, fracs, strict=True)):
|
|
161
|
+
name = _who(s["names"], i, s["folded"])
|
|
162
|
+
tip = f"{name}: {fmt.num(s['sizes'][i], unit=chip.unit)} ({fmt.pct(f)})"
|
|
163
|
+
c.rect(x, BAR[0], w, BAR[1], role="ink", opacity=OPACITY[i], title=tip)
|
|
164
|
+
x += w + GAP_W
|
mintchip/chips/spark.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""spark: a series as a word-sized line. The exemplar for a run-of-marks chip.
|
|
2
|
+
|
|
3
|
+
Text: ``0.42 (range 0.42 to 1.84) ▇▅▃▂▁▁▁▁▁`` (one cell per point, at most CELLS cells): the
|
|
4
|
+
value is the latest point, and the full form adds the series' range so a spike is in the
|
|
5
|
+
numbers too; compact is the bare ``0.42``. With ``vs``: ``0.42 vs 0.61 ▇▅▃▂▁▁▁ ▇▆▅▄▃▃▃``.
|
|
6
|
+
SVG: one ink line with an accent end point; ``vs`` in context ink; ``band`` as a context wash,
|
|
7
|
+
at least BAND_H tall about its true centre so a narrow band stays visible; ``reference`` as a
|
|
8
|
+
dashed context line.
|
|
9
|
+
|
|
10
|
+
Distortions are announced (design rule 7): a range under 2% of the level adds ``±x%`` to the
|
|
11
|
+
text and an axis-break mark to the SVG; a series longer than CELLS adds ``n=…`` to the text;
|
|
12
|
+
values outside an explicit domain become ``^``/``v`` cells and edge chevrons.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
|
|
19
|
+
from .. import fmt
|
|
20
|
+
from ..render.svg_base import Canvas
|
|
21
|
+
from ..render.text_base import TRACK, TextOptions, TextOut, level
|
|
22
|
+
from ..scales import downsample_minmax, padded
|
|
23
|
+
from ..spec import (
|
|
24
|
+
Built,
|
|
25
|
+
Chip,
|
|
26
|
+
ChipError,
|
|
27
|
+
Param,
|
|
28
|
+
chip,
|
|
29
|
+
domain_warnings,
|
|
30
|
+
svg_renderer,
|
|
31
|
+
text_renderer,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
CELLS = 12 # most text cells per series; longer series are downsampled, keeping spikes
|
|
35
|
+
END_R = 2.25 # radius of the accent end point
|
|
36
|
+
LOW_VARIATION = 0.02 # a domain narrower than this fraction of its level is "zoomed"
|
|
37
|
+
BAND_H = 3.0 # least drawn height of a band, about its true centre (facts give the true bounds)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@chip(
|
|
41
|
+
"spark",
|
|
42
|
+
question="How did a value evolve over steps or time?",
|
|
43
|
+
have="A series over time or steps",
|
|
44
|
+
params=(
|
|
45
|
+
Param(
|
|
46
|
+
"values",
|
|
47
|
+
"numbers",
|
|
48
|
+
"Give the series, oldest first; None marks a gap.",
|
|
49
|
+
required=True,
|
|
50
|
+
positional=True,
|
|
51
|
+
),
|
|
52
|
+
Param("vs", "numbers", "Give a second series over the same steps, to compare."),
|
|
53
|
+
Param("band", "range", "Give a target or normal range (lo, hi), drawn as a wash."),
|
|
54
|
+
Param("reference", "number", "Give a reference level, drawn as a dashed line."),
|
|
55
|
+
Param("domain", "range", "Fix the y-range (lo, hi); share it so sparks compare."),
|
|
56
|
+
Param("label", "string", "Say what the series measures."),
|
|
57
|
+
Param("unit", "string", "Name the unit of the values."),
|
|
58
|
+
Param("higher_is_better", "bool", "Declare a direction: the end point turns good/bad."),
|
|
59
|
+
),
|
|
60
|
+
example={
|
|
61
|
+
"values": [1.84, 1.32, 0.96, 0.74, 0.61, 0.52, 0.46, 0.43, 0.42],
|
|
62
|
+
"band": (0.38, 0.48),
|
|
63
|
+
},
|
|
64
|
+
size="m",
|
|
65
|
+
)
|
|
66
|
+
def spark(
|
|
67
|
+
values,
|
|
68
|
+
*,
|
|
69
|
+
vs=None,
|
|
70
|
+
band=None,
|
|
71
|
+
reference=None,
|
|
72
|
+
domain=None,
|
|
73
|
+
label=None,
|
|
74
|
+
unit=None,
|
|
75
|
+
higher_is_better=None,
|
|
76
|
+
) -> Built:
|
|
77
|
+
pts = [v for v in values if v is not None]
|
|
78
|
+
if len(pts) < 2:
|
|
79
|
+
raise ChipError(
|
|
80
|
+
f"needs at least 2 numbers in values; got {len(pts)}.",
|
|
81
|
+
fix_hint="Pass a series, e.g. mintchip.spark([0.9, 0.6, 0.4]).",
|
|
82
|
+
)
|
|
83
|
+
others = [v for v in (vs or []) if v is not None]
|
|
84
|
+
if vs is not None and (len(vs) != len(values) or len(others) < 2):
|
|
85
|
+
raise ChipError(
|
|
86
|
+
f"vs must have the same length as values ({len(values)}) and 2+ numbers.",
|
|
87
|
+
fix_hint="Align vs to the same steps, with None where a step is missing.",
|
|
88
|
+
)
|
|
89
|
+
if band is not None and band[0] == band[1]:
|
|
90
|
+
raise ChipError("band must have lo < hi.", fix_hint="Use reference= for a single level.")
|
|
91
|
+
|
|
92
|
+
drawn = pts + others + list(band or ()) + ([reference] if reference is not None else [])
|
|
93
|
+
lo, hi = min(drawn), max(drawn)
|
|
94
|
+
natural = (lo, hi) if hi > lo else padded(lo, hi)
|
|
95
|
+
first, last = pts[0], pts[-1]
|
|
96
|
+
better = None
|
|
97
|
+
if higher_is_better is not None and last != first:
|
|
98
|
+
better = "good" if (last > first) == higher_is_better else "bad"
|
|
99
|
+
sig = _sig(pts + others)
|
|
100
|
+
|
|
101
|
+
warnings = _cut_lines(values, vs, unit, domain or natural)
|
|
102
|
+
if len(values) > CELLS:
|
|
103
|
+
warnings.append(
|
|
104
|
+
f"text shows {len(values)} points in {CELLS} cells, keeping each cell's most "
|
|
105
|
+
f"extreme value (marked n={len(values)})."
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
name = f"{label}: " if label else ""
|
|
109
|
+
change = fmt.num(last - first, sig=sig, signed=True, unit=unit)
|
|
110
|
+
facts = [
|
|
111
|
+
(
|
|
112
|
+
f"{len(pts)} points, {fmt.num(first, sig=sig, unit=unit)} → "
|
|
113
|
+
f"{fmt.num(last, sig=sig, unit=unit)} ({change})"
|
|
114
|
+
),
|
|
115
|
+
f"range {_range((min(pts), max(pts)), unit, sig)}",
|
|
116
|
+
]
|
|
117
|
+
if vs is not None:
|
|
118
|
+
facts.append(f"vs series ends at {fmt.num(others[-1], sig=sig, unit=unit)}")
|
|
119
|
+
if band is not None:
|
|
120
|
+
where = "inside" if band[0] <= last <= band[1] else "outside"
|
|
121
|
+
facts.append(f"latest value is {where} the band {_range(band, unit)}")
|
|
122
|
+
if reference is not None:
|
|
123
|
+
facts.append(f"reference {fmt.num(reference, unit=unit)}")
|
|
124
|
+
return Built(
|
|
125
|
+
stats={
|
|
126
|
+
"values": values,
|
|
127
|
+
"vs": vs,
|
|
128
|
+
"band": band,
|
|
129
|
+
"reference": reference,
|
|
130
|
+
"first": first,
|
|
131
|
+
"value": last,
|
|
132
|
+
"last": last,
|
|
133
|
+
"vs_last": others[-1] if others else None,
|
|
134
|
+
"sig": sig,
|
|
135
|
+
"better": better,
|
|
136
|
+
},
|
|
137
|
+
facts=facts,
|
|
138
|
+
warnings=warnings,
|
|
139
|
+
alt=f"{name}sparkline of {len(pts)} points from {fmt.num(first, sig=sig)} "
|
|
140
|
+
f"to {fmt.num(last, sig=sig)}.",
|
|
141
|
+
domain=natural,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _cut_lines(values, vs, unit: str | None, dom: tuple[float, float]) -> list[str]:
|
|
146
|
+
"""The warnings that depend on the y-scale: values it cuts, and a zoomed-in scale."""
|
|
147
|
+
out = []
|
|
148
|
+
cut = [v for v in [*values, *(vs or ())] if v is not None and not dom[0] <= v <= dom[1]]
|
|
149
|
+
if cut:
|
|
150
|
+
out.append(
|
|
151
|
+
f"domain {_range(dom, unit)} cuts {len(cut)} value(s); they are pinned to the edge "
|
|
152
|
+
"and marked (^ or v in text, a chevron in SVG)."
|
|
153
|
+
)
|
|
154
|
+
zoom = _zoom(dom)
|
|
155
|
+
if zoom:
|
|
156
|
+
out.append(
|
|
157
|
+
f"the series spans only ±{zoom} of its level, stretched to full height "
|
|
158
|
+
f"(marked ±{zoom} in text, an axis break in SVG)."
|
|
159
|
+
)
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@domain_warnings("spark")
|
|
164
|
+
def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
|
|
165
|
+
return _cut_lines(chip.stats["values"], chip.stats["vs"], chip.unit, domain)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _sig(values: list[float]) -> int:
|
|
169
|
+
"""Significant figures for the value: 3, or more when the series varies in a later digit
|
|
170
|
+
(0.4200 → 0.4206 prints as 0.4206, not 0.421)."""
|
|
171
|
+
spread, size = max(values) - min(values), max(abs(v) for v in values)
|
|
172
|
+
if spread == 0:
|
|
173
|
+
return 3
|
|
174
|
+
return min(6, max(3, math.ceil(math.log10(size / spread)) + 1))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _range(r: tuple[float, float], unit: str | None, sig: int = 3) -> str:
|
|
178
|
+
return f"{fmt.num(r[0], sig=sig)} to {fmt.num(r[1], sig=sig, unit=unit)}"
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _zoom(domain: tuple[float, float]) -> str | None:
|
|
182
|
+
"""``"0.071%"`` when the domain is under LOW_VARIATION of its level, else None."""
|
|
183
|
+
lo, hi = domain
|
|
184
|
+
mid = (lo + hi) / 2
|
|
185
|
+
if hi <= lo or mid == 0 or hi - lo >= LOW_VARIATION * max(abs(lo), abs(hi)):
|
|
186
|
+
return None
|
|
187
|
+
return fmt.pct((hi - lo) / 2 / abs(mid))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _end_role(chip: Chip) -> str:
|
|
191
|
+
return chip.stats["better"] or "accent"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# --- text -----------------------------------------------------------------------------------
|
|
195
|
+
@text_renderer("spark")
|
|
196
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
197
|
+
s = chip.stats
|
|
198
|
+
lo, hi = o.domain
|
|
199
|
+
dec = fmt.places(fmt.num(s["last"], sig=s["sig"]))
|
|
200
|
+
fixed = o.decimals is not None and dec is not None # scientific notation keeps its form
|
|
201
|
+
dec = o.decimals if fixed else dec
|
|
202
|
+
|
|
203
|
+
def f(v: float) -> str:
|
|
204
|
+
if fixed:
|
|
205
|
+
return fmt.fixed(v, dec, unit=chip.unit)
|
|
206
|
+
return fmt.num(v, sig=s["sig"], unit=chip.unit)
|
|
207
|
+
|
|
208
|
+
def _end(v: float, dec: int | None) -> str:
|
|
209
|
+
"""A range end: at least the value's decimals (0.4200 beside 0.4206), more if needed."""
|
|
210
|
+
t = fmt.num(v, sig=s["sig"])
|
|
211
|
+
shown = fmt.places(t)
|
|
212
|
+
return fmt.fixed(v, dec) if dec is not None and shown is not None and shown < dec else t
|
|
213
|
+
|
|
214
|
+
value = f(s["last"])
|
|
215
|
+
if s["vs"] is not None and not o.compact:
|
|
216
|
+
value += f" vs {f(s['vs_last'])}"
|
|
217
|
+
elif not o.compact: # the latest value alone would hide a spike the glyph shows
|
|
218
|
+
pts = [v for v in s["values"] if v is not None]
|
|
219
|
+
if min(pts) < max(pts):
|
|
220
|
+
value += f" (range {_end(min(pts), dec)} to {_end(max(pts), dec)})"
|
|
221
|
+
|
|
222
|
+
def cells(series: list[float | None]) -> str:
|
|
223
|
+
out = []
|
|
224
|
+
for v in downsample_minmax(series, CELLS):
|
|
225
|
+
out.append(
|
|
226
|
+
TRACK if v is None else "^" if v > hi else "v" if v < lo else level(v, lo, hi)
|
|
227
|
+
)
|
|
228
|
+
return "".join(out)
|
|
229
|
+
|
|
230
|
+
run = cells(s["values"])
|
|
231
|
+
glyph = [(run[:-1], None), (run[-1], _end_role(chip))]
|
|
232
|
+
if s["vs"] is not None:
|
|
233
|
+
glyph.append((" " + cells(s["vs"]), "context"))
|
|
234
|
+
zoom = _zoom((lo, hi))
|
|
235
|
+
if zoom:
|
|
236
|
+
glyph.append((f" ±{zoom}", None))
|
|
237
|
+
if len(s["values"]) > CELLS:
|
|
238
|
+
glyph.append((f" n={len(s['values'])}", None))
|
|
239
|
+
return TextOut(value, glyph, dec)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
243
|
+
@svg_renderer("spark")
|
|
244
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
245
|
+
s = chip.stats
|
|
246
|
+
c.right -= END_R # the end point's radius, so the chip ends a pad after it, as others do
|
|
247
|
+
zoomed = _zoom(c.domain) is not None
|
|
248
|
+
if zoomed: # axis break at the left: two short slashes in the space the plot gives up
|
|
249
|
+
c.left += 4
|
|
250
|
+
for x in (1.0, 3.0): # the first slash's stroke and cap stay inside x = 0
|
|
251
|
+
c.line(x, c.bottom, x + 2, c.bottom - 5, role="context", width=1.25)
|
|
252
|
+
|
|
253
|
+
def points(series: list[float | None]) -> list[tuple[float, float] | None]:
|
|
254
|
+
series = downsample_minmax(series, int(2 * c.width))
|
|
255
|
+
last = len(series) - 1
|
|
256
|
+
xs = [c.fx(i / last) for i in range(len(series))]
|
|
257
|
+
return [None if v is None else (x, c.y(v, at=x)) for x, v in zip(xs, series, strict=True)]
|
|
258
|
+
|
|
259
|
+
if s["band"] is not None: # a band is context, not data: trim it to the domain, no chevron
|
|
260
|
+
lo, hi = max(s["band"][0], c.domain[0]), min(s["band"][1], c.domain[1])
|
|
261
|
+
if lo < hi:
|
|
262
|
+
top, bottom = c.y(hi), c.y(lo)
|
|
263
|
+
narrow = bottom - top < BAND_H
|
|
264
|
+
if narrow: # a given band is always visible: widen it about its true centre
|
|
265
|
+
mid = (top + bottom) / 2
|
|
266
|
+
top, bottom = max(mid - BAND_H / 2, 0.5), min(mid + BAND_H / 2, c.height - 0.5)
|
|
267
|
+
c.rect(c.left, top, c.right - c.left, bottom - top, role="context", narrow=narrow)
|
|
268
|
+
if s["reference"] is not None and c.contains(s["reference"]):
|
|
269
|
+
y = c.y(s["reference"])
|
|
270
|
+
c.line(c.left, y, c.right, y, role="context", dash=(2, 1.5))
|
|
271
|
+
if s["vs"] is not None:
|
|
272
|
+
c.path(points(s["vs"]), role="context")
|
|
273
|
+
line = points(s["values"])
|
|
274
|
+
c.path(line)
|
|
275
|
+
end = next(p for p in reversed(line) if p is not None)
|
|
276
|
+
c.dot(
|
|
277
|
+
*end, r=END_R, role=_end_role(chip), title=fmt.num(s["last"], sig=s["sig"], unit=chip.unit)
|
|
278
|
+
)
|
mintchip/chips/strip.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""strip: pass / warn / fail / skip per item, readable without colour.
|
|
2
|
+
|
|
3
|
+
Text: ``5/8 pass (1 fail, 1 warn, 1 skip) ███▄█×█·``; compact drops the parenthesis. The
|
|
4
|
+
denominator is every item given, skipped ones included. The glyph carries the state (pass full
|
|
5
|
+
``█``, warn half ``▄``, fail ``×``, skip a dot ``·``) and colour repeats it (good / warn / bad,
|
|
6
|
+
skip in context ink). More than CELLS items are bucketed, each cell showing
|
|
7
|
+
its bucket's worst state, and the text gains ``n=…``.
|
|
8
|
+
SVG: one cell per item at the same four heights, the canvas cut to fit them; skip is a hollow
|
|
9
|
+
context ring.
|
|
10
|
+
|
|
11
|
+
There is no numeric heat-strip mode: heights here mean states, so numbers drawn as heights would
|
|
12
|
+
read as states (a ▄ would be a warning). A series of numbers is a spark.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from .. import fmt
|
|
18
|
+
from ..render.svg_base import Canvas
|
|
19
|
+
from ..render.text_base import TRACK, Segment, TextOptions, TextOut
|
|
20
|
+
from ..spec import Built, Chip, ChipError, Param, chip, svg_renderer, text_renderer
|
|
21
|
+
|
|
22
|
+
CELLS = 20 # most cells; longer strips are bucketed by worst state
|
|
23
|
+
TOKENS = {
|
|
24
|
+
"pass": ("pass", "passed", "ok", "true", "yes", "good", "success"),
|
|
25
|
+
"warn": ("warn", "warning", "flaky", "partial"),
|
|
26
|
+
"fail": ("fail", "failed", "failure", "error", "false", "no", "bad"),
|
|
27
|
+
"skip": ("skip", "skipped", "na", "n/a", "none", "missing", "pending"),
|
|
28
|
+
}
|
|
29
|
+
STATE = {tok: state for state, toks in TOKENS.items() for tok in toks}
|
|
30
|
+
GLYPH = {"pass": "█", "warn": "▄", "fail": "×", "skip": TRACK} # × is x in ASCII
|
|
31
|
+
ROLE = {"pass": "good", "warn": "warn", "fail": "bad", "skip": "context"}
|
|
32
|
+
WORST = {"skip": 0, "pass": 1, "warn": 2, "fail": 3}
|
|
33
|
+
HEIGHT = {"pass": 11.0, "warn": 5.5, "fail": 2.0} # viewBox units, standing on the floor
|
|
34
|
+
PITCH = 8.0 # widest cell pitch (8 items fill size m); more items compress it
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@chip(
|
|
38
|
+
"strip",
|
|
39
|
+
question="Which items passed, warned, failed or were skipped?",
|
|
40
|
+
have="A pass/warn/fail/skip result per item",
|
|
41
|
+
params=(
|
|
42
|
+
Param(
|
|
43
|
+
"values",
|
|
44
|
+
"values",
|
|
45
|
+
"Give one result per item: True/False, 'pass', 'warn', 'fail', 'skip' or None.",
|
|
46
|
+
required=True,
|
|
47
|
+
positional=True,
|
|
48
|
+
),
|
|
49
|
+
Param("names", "strings", "Name each item, in the same order as values."),
|
|
50
|
+
Param("label", "string", "Say what was checked."),
|
|
51
|
+
),
|
|
52
|
+
example={"values": [True, True, True, "warn", True, False, True, None], "label": "Suites"},
|
|
53
|
+
size="m",
|
|
54
|
+
)
|
|
55
|
+
def strip(values, *, names=None, label=None) -> Built:
|
|
56
|
+
if not values:
|
|
57
|
+
raise ChipError(
|
|
58
|
+
"needs at least 1 item in values.",
|
|
59
|
+
fix_hint="Pass one result per item, e.g. mintchip.strip([True, 'warn', False]).",
|
|
60
|
+
)
|
|
61
|
+
states = [_state(v, i) for i, v in enumerate(values)]
|
|
62
|
+
if names is not None and len(names) != len(values):
|
|
63
|
+
raise ChipError(
|
|
64
|
+
f"names has {len(names)} entries but values has {len(values)}.",
|
|
65
|
+
fix_hint="Pass exactly one name per value, in the same order.",
|
|
66
|
+
)
|
|
67
|
+
counts = {k: states.count(k) for k in TOKENS}
|
|
68
|
+
active = len(states) - counts["skip"]
|
|
69
|
+
s = {
|
|
70
|
+
"value": counts["pass"] / len(states) if active else None,
|
|
71
|
+
"states": states,
|
|
72
|
+
"names": names,
|
|
73
|
+
"counts": counts,
|
|
74
|
+
"active": active,
|
|
75
|
+
}
|
|
76
|
+
warnings = []
|
|
77
|
+
if len(states) > CELLS:
|
|
78
|
+
warnings.append(
|
|
79
|
+
f"{len(states)} items shown in {CELLS} cells, each the worst state of its bucket "
|
|
80
|
+
f"(marked n={len(states)})."
|
|
81
|
+
)
|
|
82
|
+
who = names or [f"item {i + 1}" for i in range(len(states))]
|
|
83
|
+
facts = [_tally(counts) or f"{active} pass"]
|
|
84
|
+
for state in ("fail", "warn"):
|
|
85
|
+
hit = [w for w, st in zip(who, states, strict=True) if st == state]
|
|
86
|
+
if hit:
|
|
87
|
+
shown = ", ".join(hit[:5]) + (f" and {len(hit) - 5} more" if len(hit) > 5 else "")
|
|
88
|
+
facts.append(f"{state}: {shown}")
|
|
89
|
+
name = f"{label}: " if label else ""
|
|
90
|
+
return Built(
|
|
91
|
+
stats=s,
|
|
92
|
+
facts=facts,
|
|
93
|
+
warnings=warnings,
|
|
94
|
+
alt=f"{name}{_value(s)} across {len(states)} items.",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _state(v, i: int) -> str:
|
|
99
|
+
if v is None:
|
|
100
|
+
return "skip"
|
|
101
|
+
if isinstance(v, bool):
|
|
102
|
+
return "pass" if v else "fail"
|
|
103
|
+
if isinstance(v, str) and v.strip().lower() in STATE:
|
|
104
|
+
return STATE[v.strip().lower()]
|
|
105
|
+
hint = "Pass True/False, 'pass', 'warn', 'fail', 'skip' or None"
|
|
106
|
+
if isinstance(v, str):
|
|
107
|
+
raise ChipError(f"values[{i}] is {v!r}, not a known state.", fix_hint=hint + ".")
|
|
108
|
+
raise ChipError(
|
|
109
|
+
f"values[{i}] is the number {fmt.num(v)}; strip shows states, not numbers.",
|
|
110
|
+
fix_hint=hint + "; for a series of numbers use mintchip.spark.",
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _tally(counts: dict[str, int]) -> str:
|
|
115
|
+
return ", ".join(f"{counts[k]} {k}" for k in ("fail", "warn", "skip") if counts[k])
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _value(s: dict) -> str:
|
|
119
|
+
if not s["active"]:
|
|
120
|
+
return f"all {s['counts']['skip']} skipped"
|
|
121
|
+
return f"{s['counts']['pass']}/{len(s['states'])} pass"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _cells(s: dict) -> list[tuple[str, list[int]]]:
|
|
125
|
+
"""(state, item indices) per cell: one item each, or the worst of each bucket."""
|
|
126
|
+
states, n = s["states"], len(s["states"])
|
|
127
|
+
if n <= CELLS:
|
|
128
|
+
return [(st, [i]) for i, st in enumerate(states)]
|
|
129
|
+
out = []
|
|
130
|
+
for b in range(CELLS):
|
|
131
|
+
idx = list(range(b * n // CELLS, (b + 1) * n // CELLS))
|
|
132
|
+
out.append((max((states[i] for i in idx), key=WORST.__getitem__), idx))
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# --- text -----------------------------------------------------------------------------------
|
|
137
|
+
@text_renderer("strip")
|
|
138
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
139
|
+
s = chip.stats
|
|
140
|
+
value = _value(s)
|
|
141
|
+
tally = _tally(s["counts"]) if s["active"] else ""
|
|
142
|
+
if tally and not o.compact:
|
|
143
|
+
value += f" ({tally})"
|
|
144
|
+
glyph: list[Segment] = []
|
|
145
|
+
for state, _ in _cells(s):
|
|
146
|
+
ch, role = GLYPH[state], ROLE[state]
|
|
147
|
+
if glyph and glyph[-1][1] == role:
|
|
148
|
+
glyph[-1] = (glyph[-1][0] + ch, role)
|
|
149
|
+
else:
|
|
150
|
+
glyph.append((ch, role))
|
|
151
|
+
if len(s["states"]) > CELLS:
|
|
152
|
+
glyph.append((f" n={len(s['states'])}", None))
|
|
153
|
+
return TextOut(value, glyph)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
157
|
+
@svg_renderer("strip")
|
|
158
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
159
|
+
s = chip.stats
|
|
160
|
+
cells = _cells(s)
|
|
161
|
+
pitch = min(PITCH, (c.right - c.left) / len(cells))
|
|
162
|
+
w = pitch - max(1.25, 0.3 * pitch)
|
|
163
|
+
names = s["names"] or [f"item {i + 1}" for i in range(len(s["states"]))]
|
|
164
|
+
for k, (state, idx) in enumerate(cells):
|
|
165
|
+
x = c.left + k * pitch
|
|
166
|
+
who = names[idx[0]] if len(idx) == 1 else f"{names[idx[0]]} to {names[idx[-1]]}"
|
|
167
|
+
title = f"{who}: {state}"
|
|
168
|
+
if state == "skip":
|
|
169
|
+
c.dot(x + w / 2, c.bottom - 1.75, r=1.75, role="context", hollow=True, title=title)
|
|
170
|
+
else:
|
|
171
|
+
h = HEIGHT[state]
|
|
172
|
+
c.rect(x, c.bottom - h, w, h, role=ROLE[state], title=title)
|
|
173
|
+
c.fit()
|