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/gauge.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""gauge: a reading against its normal range, with an optional wider warn range.
|
|
2
|
+
|
|
3
|
+
Text: ``7.38 (normal 7.35 to 7.45) [··├─●───┤··]``; compact drops the parenthesis, which also
|
|
4
|
+
says ``high`` or ``low`` when the reading is outside the normal range. Warn edges are ``│``.
|
|
5
|
+
SVG: the normal range as a thick context band, the warn range as a thin context line either
|
|
6
|
+
side of it, and the reading as a dot coloured good / warn / bad by which band it falls in,
|
|
7
|
+
so the colour always repeats what the position shows. Drawn alone, the scale spans just the
|
|
8
|
+
marks, so no blank margin sits in the sentence; the text track keeps its margin cells.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from .. import fmt
|
|
14
|
+
from ..render.svg_base import Canvas
|
|
15
|
+
from ..render.text_base import DOT, REF, TextOptions, TextOut, Track
|
|
16
|
+
from ..scales import padded
|
|
17
|
+
from ..spec import (
|
|
18
|
+
Built,
|
|
19
|
+
Chip,
|
|
20
|
+
ChipError,
|
|
21
|
+
Param,
|
|
22
|
+
chip,
|
|
23
|
+
domain_warnings,
|
|
24
|
+
svg_renderer,
|
|
25
|
+
text_renderer,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
CELLS = 11
|
|
29
|
+
BAND = 4.0 # stroke width of the normal band
|
|
30
|
+
DOT_R = 3.0
|
|
31
|
+
FIT = 0.015 # the SVG's margin when drawn on its own scale: room for the dot at an end
|
|
32
|
+
ROLE = {"normal": "good", "warn": "warn", "low": "bad", "high": "bad"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@chip(
|
|
36
|
+
"gauge",
|
|
37
|
+
question="Is a reading inside its normal range?",
|
|
38
|
+
have="A reading with a normal range",
|
|
39
|
+
params=(
|
|
40
|
+
Param("value", "number", "Give the reading.", required=True, positional=True),
|
|
41
|
+
Param(
|
|
42
|
+
"normal",
|
|
43
|
+
"range",
|
|
44
|
+
"Give the normal range (lo, hi).",
|
|
45
|
+
required=True,
|
|
46
|
+
positional=True,
|
|
47
|
+
),
|
|
48
|
+
Param("warn", "range", "Give a wider caution range (lo, hi) that contains normal."),
|
|
49
|
+
Param("domain", "range", "Fix the x-range (lo, hi); share it so gauges compare."),
|
|
50
|
+
Param("label", "string", "Say what is read."),
|
|
51
|
+
Param("unit", "string", "Name the unit of the reading."),
|
|
52
|
+
),
|
|
53
|
+
example={"value": 7.38, "normal": (7.35, 7.45), "label": "Blood pH"},
|
|
54
|
+
size="m",
|
|
55
|
+
)
|
|
56
|
+
def gauge(value, normal, *, warn=None, domain=None, label=None, unit=None) -> Built:
|
|
57
|
+
n_lo, n_hi = normal
|
|
58
|
+
if not n_lo < n_hi:
|
|
59
|
+
raise ChipError(
|
|
60
|
+
f"normal must have lo < hi; got ({n_lo:g}, {n_hi:g}).",
|
|
61
|
+
fix_hint="Pass the normal range as normal=(lo, hi), e.g. (7.35, 7.45).",
|
|
62
|
+
)
|
|
63
|
+
if warn is not None and not warn[0] <= n_lo < n_hi <= warn[1]:
|
|
64
|
+
raise ChipError(
|
|
65
|
+
f"warn ({warn[0]:g}, {warn[1]:g}) must contain normal ({n_lo:g}, {n_hi:g}).",
|
|
66
|
+
fix_hint="Pass warn= as the wider caution range around normal, e.g. (7.3, 7.5).",
|
|
67
|
+
)
|
|
68
|
+
if n_lo <= value <= n_hi:
|
|
69
|
+
status = "normal"
|
|
70
|
+
elif warn is not None and warn[0] <= value <= warn[1]:
|
|
71
|
+
status = "warn"
|
|
72
|
+
else:
|
|
73
|
+
status = "high" if value > n_hi else "low"
|
|
74
|
+
side = "high" if value > n_hi else "low" if value < n_lo else None
|
|
75
|
+
s = {
|
|
76
|
+
"value": value,
|
|
77
|
+
"normal": normal,
|
|
78
|
+
"warn": warn,
|
|
79
|
+
"status": status,
|
|
80
|
+
"side": side,
|
|
81
|
+
}
|
|
82
|
+
ends = _ends(s)
|
|
83
|
+
# The range's own precision, or more when rounding would move the reading or a limit by
|
|
84
|
+
# over 3% of the normal width (7.384 in 7.35 to 7.45 needs the third place).
|
|
85
|
+
s["dec"] = max(0, fmt.decimals(n_hi - n_lo), fmt.resolving(ends, n_hi - n_lo))
|
|
86
|
+
lo, hi = min(ends), max(ends)
|
|
87
|
+
pad = max(0.2 * (hi - lo), 0.5 * (n_hi - n_lo))
|
|
88
|
+
natural = (lo - pad, hi + pad)
|
|
89
|
+
|
|
90
|
+
def f(v: float, u: str | None = None) -> str:
|
|
91
|
+
return fmt.fixed(v, s["dec"], unit=u)
|
|
92
|
+
|
|
93
|
+
warnings = _cut_lines(s, unit, domain or natural)
|
|
94
|
+
|
|
95
|
+
rel = {None: "within", "high": "above", "low": "below"}[side]
|
|
96
|
+
alt = f"{f(value, unit)}, {rel} the normal range {f(n_lo)} to {f(n_hi, unit)}"
|
|
97
|
+
if side is None:
|
|
98
|
+
facts = [f"{f(min(value - n_lo, n_hi - value), unit)} inside the nearest normal limit"]
|
|
99
|
+
else:
|
|
100
|
+
gap = value - n_hi if side == "high" else n_lo - value
|
|
101
|
+
facts = [f"{f(gap, unit)} {rel} the normal range"]
|
|
102
|
+
if warn is not None:
|
|
103
|
+
inside = "inside" if warn[0] <= value <= warn[1] else "outside"
|
|
104
|
+
facts.append(f"{inside} the warn range {f(warn[0])} to {f(warn[1], unit)}")
|
|
105
|
+
if side is not None:
|
|
106
|
+
alt += f", {inside} the warn range"
|
|
107
|
+
return Built(
|
|
108
|
+
stats=s,
|
|
109
|
+
facts=facts,
|
|
110
|
+
warnings=warnings,
|
|
111
|
+
alt=f"{label}: {alt}." if label else f"{alt}.",
|
|
112
|
+
domain=natural,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _ends(s: dict) -> list[float]:
|
|
117
|
+
return [s["value"], *s["normal"], *(s["warn"] or ())]
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _cut_lines(s: dict, unit: str | None, domain: tuple[float, float]) -> list[str]:
|
|
121
|
+
ends = _ends(s)
|
|
122
|
+
if min(ends) >= domain[0] and max(ends) <= domain[1]:
|
|
123
|
+
return []
|
|
124
|
+
lo, hi = fmt.num(domain[0]), fmt.num(domain[1])
|
|
125
|
+
return [
|
|
126
|
+
(
|
|
127
|
+
f"domain {lo} to {fmt.with_unit(hi, unit)} cuts the reading or its ranges; a cut "
|
|
128
|
+
"reading is pinned to the edge and marked (< or > in text, a chevron in SVG)."
|
|
129
|
+
)
|
|
130
|
+
]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@domain_warnings("gauge")
|
|
134
|
+
def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
|
|
135
|
+
return _cut_lines(chip.stats, chip.unit, domain)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# --- text -----------------------------------------------------------------------------------
|
|
139
|
+
@text_renderer("gauge")
|
|
140
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
141
|
+
s = chip.stats
|
|
142
|
+
dec, unit = s["dec"] if o.decimals is None else o.decimals, chip.unit
|
|
143
|
+
value = fmt.fixed(s["value"], dec, unit=unit)
|
|
144
|
+
if not o.compact:
|
|
145
|
+
n_lo, n_hi = s["normal"]
|
|
146
|
+
side = f"{s['side']}; " if s["side"] else ""
|
|
147
|
+
value += f" ({side}normal {fmt.fixed(n_lo, dec)} to {fmt.fixed(n_hi, dec)})"
|
|
148
|
+
|
|
149
|
+
t = Track(CELLS, o.domain)
|
|
150
|
+
if s["warn"] is not None:
|
|
151
|
+
for edge in s["warn"]:
|
|
152
|
+
if t.contains(edge):
|
|
153
|
+
t.put(edge, REF, "context")
|
|
154
|
+
t.span(*s["normal"], role="context")
|
|
155
|
+
t.put(s["value"], DOT, ROLE[s["status"]])
|
|
156
|
+
return TextOut(value, t.glyph(), dec)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
160
|
+
@svg_renderer("gauge")
|
|
161
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
162
|
+
s = chip.stats
|
|
163
|
+
if c.natural: # alone: the scale spans the marks, so no blank margin sits in the sentence
|
|
164
|
+
ends = _ends(s)
|
|
165
|
+
c.domain = padded(min(ends), max(ends), FIT)
|
|
166
|
+
lo, hi = c.domain
|
|
167
|
+
v = s["value"]
|
|
168
|
+
cut = -1 if v < lo else 1 if v > hi else 0
|
|
169
|
+
if cut < 0:
|
|
170
|
+
c.left += DOT_R + 4
|
|
171
|
+
if cut > 0:
|
|
172
|
+
c.right -= DOT_R + 4
|
|
173
|
+
|
|
174
|
+
def span(a: float, b: float, width: float) -> None:
|
|
175
|
+
"""A context stroke over [a, b] trimmed to the domain; the round caps end on a, b."""
|
|
176
|
+
a, b = max(a, lo), min(b, hi)
|
|
177
|
+
if b <= a:
|
|
178
|
+
return
|
|
179
|
+
x1, x2 = c.x(a) + width / 2, c.x(b) - width / 2
|
|
180
|
+
if x2 < x1: # narrower than the stroke: a round dab centred on the range
|
|
181
|
+
x1 = x2 = (x1 + x2) / 2
|
|
182
|
+
c.line(x1, c.mid, x2, c.mid, role="context", width=width)
|
|
183
|
+
|
|
184
|
+
n_lo, n_hi = s["normal"]
|
|
185
|
+
if s["warn"] is not None:
|
|
186
|
+
span(s["warn"][0], n_lo, 1.5)
|
|
187
|
+
span(n_hi, s["warn"][1], 1.5)
|
|
188
|
+
span(n_lo, n_hi, BAND)
|
|
189
|
+
x = c.x(min(max(v, lo), hi))
|
|
190
|
+
role = ROLE[s["status"]]
|
|
191
|
+
c.dot(x, c.mid, r=DOT_R, role=role, title=fmt.fixed(v, s["dec"], unit=chip.unit))
|
|
192
|
+
if cut: # a reading off the scale: the dot sits on the edge with a chevron beyond it
|
|
193
|
+
back = x + cut * (DOT_R + 1.25)
|
|
194
|
+
c.path(
|
|
195
|
+
[(back, c.mid - 3), (back + cut * 2.5, c.mid), (back, c.mid + 3)],
|
|
196
|
+
width=1.25,
|
|
197
|
+
)
|
mintchip/chips/num.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""num: a formatted number with unit, significant figures and optional ±. It has no graphic,
|
|
2
|
+
so it registers no SVG renderer and ``svg()`` returns ""."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from .. import fmt
|
|
7
|
+
from ..render.text_base import TextOptions, TextOut
|
|
8
|
+
from ..spec import Built, Chip, ChipError, Param, chip, text_renderer
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@chip(
|
|
12
|
+
"num",
|
|
13
|
+
question="What is the value?",
|
|
14
|
+
have="One number, no context",
|
|
15
|
+
params=(
|
|
16
|
+
Param("value", "number", "Give the number to show.", required=True, positional=True),
|
|
17
|
+
Param("unit", "string", "Name the unit printed after the number, e.g. ms or %."),
|
|
18
|
+
Param("sig", "int", "Set significant figures (pm, if given, sets precision).", default=3),
|
|
19
|
+
Param("pm", "number", "Give a ± uncertainty; the value is rounded to match it."),
|
|
20
|
+
Param("signed", "bool", "Print + before positive values.", default=False),
|
|
21
|
+
Param("label", "string", "Say what the number measures."),
|
|
22
|
+
),
|
|
23
|
+
example={"value": 0.82, "pm": 0.03, "label": "Accuracy"},
|
|
24
|
+
size="s",
|
|
25
|
+
)
|
|
26
|
+
def num(value, *, unit=None, sig=3, pm=None, signed=False, label=None) -> Built:
|
|
27
|
+
if not 1 <= sig <= 15:
|
|
28
|
+
raise ChipError(f"sig must be between 1 and 15; got {sig}.", fix_hint="Pass sig=3.")
|
|
29
|
+
if pm is not None and pm < 0:
|
|
30
|
+
raise ChipError(f"pm must be zero or positive; got {pm}.", fix_hint="Pass pm=abs(pm).")
|
|
31
|
+
shown = _value(value, pm, sig, signed, unit)
|
|
32
|
+
return Built(
|
|
33
|
+
stats={"value": value, "pm": pm, "sig": sig, "signed": signed},
|
|
34
|
+
facts=(f"exact value {value!r}" + (f" ± {pm!r}" if pm else ""),),
|
|
35
|
+
alt=f"{label}: {shown}" if label else shown,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _value(value: float, pm: float | None, sig: int, signed: bool, unit: str | None) -> str:
|
|
40
|
+
if pm:
|
|
41
|
+
return fmt.pm(value, pm, signed=signed, unit=unit)
|
|
42
|
+
return fmt.num(value, sig=sig, signed=signed, unit=unit)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@text_renderer("num")
|
|
46
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
47
|
+
s = chip.stats
|
|
48
|
+
own = _value(s["value"], s["pm"], s["sig"], s["signed"], None)
|
|
49
|
+
dec = fmt.places(own)
|
|
50
|
+
if o.decimals is None or dec is None: # scientific notation keeps its form
|
|
51
|
+
return TextOut(_value(s["value"], s["pm"], s["sig"], s["signed"], chip.unit), "", dec)
|
|
52
|
+
shown = fmt.fixed(s["value"], o.decimals, signed=s["signed"])
|
|
53
|
+
if s["pm"]:
|
|
54
|
+
shown += f" ± {fmt.fixed(s['pm'], o.decimals)}"
|
|
55
|
+
return TextOut(fmt.with_unit(shown, chip.unit), "", o.decimals)
|
mintchip/chips/rank.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""rank: a position in a field, as ``rank(position, total)`` or from ``values=`` and ``value=``.
|
|
2
|
+
|
|
3
|
+
Text: ``#2/18 [········●·]``; from values, ``#2/5 (0.85) [·······●··]`` (compact drops the
|
|
4
|
+
parenthesis). SVG: one context ruler with end ticks and one ink dot. The best end is always
|
|
5
|
+
the right, and the facts say so.
|
|
6
|
+
|
|
7
|
+
Two rulers, one per way of calling it:
|
|
8
|
+
- ``rank(position, total)``: the ruler is the order of the field, last place at the left and #1
|
|
9
|
+
at the right. It is a fixed scale, so every rank chip already compares; ``domain`` is None and
|
|
10
|
+
a render-time ``domain=`` is ignored.
|
|
11
|
+
- ``rank(values=..., value=...)``: the ruler is the value axis over the field's extent
|
|
12
|
+
(``chip.domain``), so the gap to the leader shows. With ``higher_is_better=False`` the axis
|
|
13
|
+
runs high to low, so the best (lowest) value is still at the right. A render-time
|
|
14
|
+
``domain=`` puts several fields on one value scale.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
|
|
21
|
+
from .. import fmt
|
|
22
|
+
from ..render.svg_base import Canvas
|
|
23
|
+
from ..render.text_base import DOT, TextOptions, TextOut, Track
|
|
24
|
+
from ..scales import padded
|
|
25
|
+
from ..spec import Built, Chip, ChipError, Param, chip, domain_warnings, svg_renderer, text_renderer
|
|
26
|
+
|
|
27
|
+
CELLS = 10
|
|
28
|
+
_HINT = "Call mintchip.rank(2, 18) or mintchip.rank(values=scores, value=0.88)."
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@chip(
|
|
32
|
+
"rank",
|
|
33
|
+
question="Where does one item stand in its field?",
|
|
34
|
+
have="A position in a ranked field",
|
|
35
|
+
params=(
|
|
36
|
+
Param("position", "int", "Give the 1-based rank, 1 being best.", positional=True),
|
|
37
|
+
Param("total", "int", "Give the size of the field.", positional=True),
|
|
38
|
+
Param("values", "numbers", "Give the field's values, to rank value among them."),
|
|
39
|
+
Param("value", "number", "Give the value to rank within values."),
|
|
40
|
+
Param(
|
|
41
|
+
"higher_is_better",
|
|
42
|
+
"bool",
|
|
43
|
+
"Say whether a higher value ranks first (values= only).",
|
|
44
|
+
default=True,
|
|
45
|
+
),
|
|
46
|
+
Param("label", "string", "Say what is ranked."),
|
|
47
|
+
),
|
|
48
|
+
example={"position": 2, "total": 18, "label": "Leaderboard"},
|
|
49
|
+
size="m",
|
|
50
|
+
)
|
|
51
|
+
def rank(
|
|
52
|
+
position=None,
|
|
53
|
+
total=None,
|
|
54
|
+
*,
|
|
55
|
+
values=None,
|
|
56
|
+
value=None,
|
|
57
|
+
higher_is_better=True,
|
|
58
|
+
label=None,
|
|
59
|
+
) -> Built:
|
|
60
|
+
by_position = position is not None or total is not None
|
|
61
|
+
by_value = values is not None or value is not None
|
|
62
|
+
if by_position == by_value:
|
|
63
|
+
raise ChipError(
|
|
64
|
+
"needs either (position, total) or (values=, value=), "
|
|
65
|
+
+ ("not both." if by_position else "and got neither."),
|
|
66
|
+
fix_hint=_HINT,
|
|
67
|
+
)
|
|
68
|
+
warnings: list[str] = []
|
|
69
|
+
facts: list[str] = []
|
|
70
|
+
if by_position:
|
|
71
|
+
if position is None or total is None:
|
|
72
|
+
raise ChipError("needs both position and total.", fix_hint=_HINT)
|
|
73
|
+
if total < 1 or not 1 <= position <= total:
|
|
74
|
+
raise ChipError(
|
|
75
|
+
f"position must be between 1 and total; got {position} of {total}.",
|
|
76
|
+
fix_hint="Pass a 1-based rank, e.g. mintchip.rank(2, 18).",
|
|
77
|
+
)
|
|
78
|
+
if not higher_is_better:
|
|
79
|
+
raise ChipError(
|
|
80
|
+
"higher_is_better applies only to values=; position 1 is always best.",
|
|
81
|
+
fix_hint="Drop higher_is_better, or rank from values= and value=.",
|
|
82
|
+
)
|
|
83
|
+
score, domain, ties = None, None, 0
|
|
84
|
+
facts.append("right end is best (#1); left end is last")
|
|
85
|
+
else:
|
|
86
|
+
if values is None or value is None:
|
|
87
|
+
raise ChipError("needs both values= and value=.", fix_hint=_HINT)
|
|
88
|
+
field = [v for v in values if v is not None]
|
|
89
|
+
if not any(math.isclose(v, value, rel_tol=1e-9, abs_tol=1e-12) for v in field):
|
|
90
|
+
field.append(value)
|
|
91
|
+
warnings.append(
|
|
92
|
+
f"value {fmt.num(value)} is not in values; ranked as an extra entry "
|
|
93
|
+
f"(field of {len(field)})."
|
|
94
|
+
)
|
|
95
|
+
if len(field) < 2:
|
|
96
|
+
raise ChipError(
|
|
97
|
+
f"needs a field of at least 2 values; got {len(field)}.",
|
|
98
|
+
fix_hint="Pass the whole field, e.g. values=[0.72, 0.81, 0.88].",
|
|
99
|
+
)
|
|
100
|
+
ahead = [v for v in field if (v > value if higher_is_better else v < value)]
|
|
101
|
+
same = [v for v in field if math.isclose(v, value, rel_tol=1e-9, abs_tol=1e-12)]
|
|
102
|
+
position, total, score, ties = len(ahead) + 1, len(field), value, len(same) - 1
|
|
103
|
+
lo, hi = min(field), max(field)
|
|
104
|
+
domain = (lo, hi) if hi > lo else padded(lo, hi)
|
|
105
|
+
ends = (lo, hi) if higher_is_better else (hi, lo)
|
|
106
|
+
facts.append(
|
|
107
|
+
f"right end is best ({'highest' if higher_is_better else 'lowest'} value); "
|
|
108
|
+
f"ruler runs {fmt.num(ends[0])} to {fmt.num(ends[1])}"
|
|
109
|
+
)
|
|
110
|
+
if ties:
|
|
111
|
+
facts.append(f"tied with {ties} other(s) at #{position}")
|
|
112
|
+
s = {
|
|
113
|
+
"value": float(position),
|
|
114
|
+
"position": position,
|
|
115
|
+
"total": total,
|
|
116
|
+
"frac": 1.0 if total == 1 else (total - position) / (total - 1),
|
|
117
|
+
"score": score,
|
|
118
|
+
"higher_is_better": higher_is_better,
|
|
119
|
+
}
|
|
120
|
+
behind = total - position - ties
|
|
121
|
+
facts.insert(0, f"{position - 1} ahead, {behind} behind" if total > 1 else "alone in the field")
|
|
122
|
+
alt = f"rank {position} of {total}"
|
|
123
|
+
return Built(
|
|
124
|
+
stats=s,
|
|
125
|
+
facts=facts,
|
|
126
|
+
warnings=warnings,
|
|
127
|
+
alt=f"{label}: {alt}." if label else f"{alt[0].upper()}{alt[1:]}.",
|
|
128
|
+
domain=domain,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@domain_warnings("rank")
|
|
133
|
+
def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
|
|
134
|
+
"""A ruler that ends before the score (ranked by value) cuts it."""
|
|
135
|
+
score = chip.stats["score"]
|
|
136
|
+
if score is None or domain[0] <= score <= domain[1]:
|
|
137
|
+
return []
|
|
138
|
+
return [
|
|
139
|
+
(
|
|
140
|
+
f"domain {fmt.num(domain[0])} to {fmt.num(domain[1])} cuts the value {fmt.num(score)}; "
|
|
141
|
+
"it is pinned to the end of the ruler and marked (< or > in text, a chevron in SVG)."
|
|
142
|
+
)
|
|
143
|
+
]
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# --- text -----------------------------------------------------------------------------------
|
|
147
|
+
@text_renderer("rank")
|
|
148
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
149
|
+
s = chip.stats
|
|
150
|
+
value = f"#{s['position']}/{s['total']}"
|
|
151
|
+
if s["score"] is None:
|
|
152
|
+
t = Track(CELLS, (0.0, 1.0))
|
|
153
|
+
t.put(s["frac"], DOT)
|
|
154
|
+
else:
|
|
155
|
+
if not o.compact:
|
|
156
|
+
value += f" ({fmt.num(s['score'])})"
|
|
157
|
+
t = Track(CELLS, o.domain)
|
|
158
|
+
t.put(_onto(s, o.domain), DOT)
|
|
159
|
+
return TextOut(value, t.glyph())
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _onto(s: dict, domain: tuple[float, float]) -> float:
|
|
163
|
+
"""The score's place on the ruler: mirrored within the domain when lower is better, so
|
|
164
|
+
the best end is always the right."""
|
|
165
|
+
lo, hi = domain
|
|
166
|
+
return s["score"] if s["higher_is_better"] else lo + hi - s["score"]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
170
|
+
@svg_renderer("rank")
|
|
171
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
172
|
+
s = chip.stats
|
|
173
|
+
y = c.mid
|
|
174
|
+
c.line(c.left, y, c.right, y, role="context")
|
|
175
|
+
for x in (c.left, c.right): # the ruler's two ends: the field's extent
|
|
176
|
+
c.line(x, y - 2.5, x, y + 2.5, role="context", width=1.25)
|
|
177
|
+
if s["score"] is None:
|
|
178
|
+
x, tip = c.fx(s["frac"]), f"#{s['position']} of {s['total']}"
|
|
179
|
+
else:
|
|
180
|
+
x = c.x(_onto(s, c.domain))
|
|
181
|
+
tip = f"#{s['position']} of {s['total']}: {fmt.num(s['score'])}"
|
|
182
|
+
c.dot(x, y, r=2.75, title=tip)
|
mintchip/chips/ratio.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""ratio: k out of n as an icon array (natural frequencies).
|
|
2
|
+
|
|
3
|
+
Text: ``3/10 ●●●○○○○○○○``: one icon per item when the total is at most ``units``; a larger
|
|
4
|
+
total, or a probability (``ratio(0.24)``), is drawn as ``units`` icons with the exact fraction
|
|
5
|
+
kept in the value. When whole icons would change the fraction materially (off by a quarter
|
|
6
|
+
icon or more, or showing none or all when the truth is neither), the boundary icon is drawn
|
|
7
|
+
as a partial icon (``·`` in text, a small dot in SVG) and a warning says so.
|
|
8
|
+
SVG: filled dots, then thin open rings in context ink (the rest of the whole, like a bar's
|
|
9
|
+
track), in one row cut to fit; ``units`` stops at 10, the most icons that still read as
|
|
10
|
+
separate marks at 1x in a word-sized chip.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
|
|
17
|
+
from .. import fmt
|
|
18
|
+
from ..render.svg_base import Canvas
|
|
19
|
+
from ..render.text_base import DOT, HOLLOW, TRACK, TextOptions, TextOut
|
|
20
|
+
from ..spec import Built, Chip, ChipError, Param, chip, svg_renderer, text_renderer
|
|
21
|
+
|
|
22
|
+
MAX_UNITS = 10 # icons in a word-sized array that still read one by one at 1x
|
|
23
|
+
MATERIAL = 0.25 # rounding by at least this many icons is announced
|
|
24
|
+
PITCH = 6.75
|
|
25
|
+
R_FULL, R_RING, R_PART = 2.5, 2.25, 1.75
|
|
26
|
+
RING = 1.25 # ring stroke: the thinnest allowed, so the hole stays open at 1x
|
|
27
|
+
HINT = "Pass a count with its total, ratio(3, 10), or a probability alone, ratio(0.24)."
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@chip(
|
|
31
|
+
"ratio",
|
|
32
|
+
question="How many out of how many?",
|
|
33
|
+
have="A count out of a total, or a probability",
|
|
34
|
+
params=(
|
|
35
|
+
Param(
|
|
36
|
+
"count",
|
|
37
|
+
"number",
|
|
38
|
+
"Give the count k (with total), or a probability in [0, 1] (without).",
|
|
39
|
+
required=True,
|
|
40
|
+
positional=True,
|
|
41
|
+
),
|
|
42
|
+
Param("total", "int", "Give the total n that count is out of.", positional=True),
|
|
43
|
+
Param(
|
|
44
|
+
"units",
|
|
45
|
+
"int",
|
|
46
|
+
"Set how many icons stand for the whole when there is no total or it is larger.",
|
|
47
|
+
default=10,
|
|
48
|
+
),
|
|
49
|
+
Param("label", "string", "Say what is counted."),
|
|
50
|
+
),
|
|
51
|
+
example={"count": 3, "total": 10, "label": "Runs that diverged"},
|
|
52
|
+
size="m",
|
|
53
|
+
)
|
|
54
|
+
def ratio(count, total=None, *, units=10, label=None) -> Built:
|
|
55
|
+
if not 2 <= units <= MAX_UNITS:
|
|
56
|
+
raise ChipError(
|
|
57
|
+
f"units must be between 2 and {MAX_UNITS}; got {units}.",
|
|
58
|
+
fix_hint="Pass units=10 or fewer; the exact fraction stays in the value.",
|
|
59
|
+
)
|
|
60
|
+
if total is not None:
|
|
61
|
+
if total < 1:
|
|
62
|
+
raise ChipError(f"total must be at least 1; got {total}.", fix_hint=HINT)
|
|
63
|
+
if not count.is_integer() or not 0 <= count <= total:
|
|
64
|
+
raise ChipError(
|
|
65
|
+
f"count must be a whole number from 0 to total ({total}); got {fmt.num(count)}.",
|
|
66
|
+
fix_hint=HINT,
|
|
67
|
+
)
|
|
68
|
+
frac = count / total
|
|
69
|
+
elif not 0 <= count <= 1:
|
|
70
|
+
raise ChipError(
|
|
71
|
+
f"without a total, count is a probability and must lie in [0, 1]; "
|
|
72
|
+
f"got {fmt.num(count)}.",
|
|
73
|
+
fix_hint=HINT,
|
|
74
|
+
)
|
|
75
|
+
else:
|
|
76
|
+
frac = count
|
|
77
|
+
|
|
78
|
+
icons = total if total is not None and total <= units else units
|
|
79
|
+
exact = frac * icons
|
|
80
|
+
whole = math.floor(exact + 0.5) # half up
|
|
81
|
+
partial = exact != whole and (abs(exact - whole) >= MATERIAL or whole == 0 or whole == icons)
|
|
82
|
+
full = math.floor(exact) if partial else whole
|
|
83
|
+
|
|
84
|
+
if total is not None:
|
|
85
|
+
said = f"{fmt.count(count)} out of {fmt.count(total)} ({fmt.pct(frac)})"
|
|
86
|
+
else:
|
|
87
|
+
about = "" if exact == whole else "about "
|
|
88
|
+
said = f"{fmt.pct(frac)}, {about}{whole} in {icons}"
|
|
89
|
+
facts = [said]
|
|
90
|
+
if icons != total:
|
|
91
|
+
each = "" if total is None else f"; each icon stands for {fmt.num(total / icons)}"
|
|
92
|
+
facts.append(f"drawn as {fmt.num(exact)} of {icons} icons{each}")
|
|
93
|
+
warnings = []
|
|
94
|
+
if partial:
|
|
95
|
+
warnings.append(
|
|
96
|
+
f"{fmt.pct(frac)} is {fmt.num(exact)} of {icons} icons; rounding to {whole} would "
|
|
97
|
+
f"misstate it, so the boundary icon is drawn as a partial icon ({TRACK} in text, "
|
|
98
|
+
"a small dot in SVG)."
|
|
99
|
+
)
|
|
100
|
+
name = f"{label}: " if label else ""
|
|
101
|
+
return Built(
|
|
102
|
+
stats={
|
|
103
|
+
"value": frac,
|
|
104
|
+
"count": count,
|
|
105
|
+
"total": total,
|
|
106
|
+
"icons": icons,
|
|
107
|
+
"full": full,
|
|
108
|
+
"partial": partial,
|
|
109
|
+
},
|
|
110
|
+
facts=facts,
|
|
111
|
+
warnings=warnings,
|
|
112
|
+
alt=f"{name}{said}.",
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# --- text -----------------------------------------------------------------------------------
|
|
117
|
+
@text_renderer("ratio")
|
|
118
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
119
|
+
s = chip.stats
|
|
120
|
+
if s["total"] is None:
|
|
121
|
+
value = fmt.pct(s["value"])
|
|
122
|
+
else:
|
|
123
|
+
value = f"{fmt.count(s['count'])}/{fmt.count(s['total'])}"
|
|
124
|
+
rest = s["icons"] - s["full"] - s["partial"]
|
|
125
|
+
return TextOut(value, DOT * s["full"] + TRACK * s["partial"] + HOLLOW * rest)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
129
|
+
@svg_renderer("ratio")
|
|
130
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
131
|
+
s = chip.stats
|
|
132
|
+
y = c.mid
|
|
133
|
+
for i in range(s["icons"]):
|
|
134
|
+
x = c.left + R_RING + RING / 2 + i * PITCH
|
|
135
|
+
if i < s["full"]:
|
|
136
|
+
c.dot(x, y, r=R_FULL)
|
|
137
|
+
elif i == s["full"] and s["partial"]:
|
|
138
|
+
c.dot(x, y, r=R_PART)
|
|
139
|
+
else:
|
|
140
|
+
c.dot(x, y, r=R_RING, hollow=True, stroke=RING, role="context") # the track
|
|
141
|
+
c.fit()
|