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/__init__.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""mintchip: word-sized graphics for numbers, in text, SVG and HTML, with no dependencies.
|
|
2
|
+
|
|
3
|
+
A chip is a small data record (``mintchip.spark([...])``); drawing happens when you render it
|
|
4
|
+
with ``.text()``, ``.svg()``, ``.html()`` or ``.markdown()``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from . import chips as _chips # noqa: F401 (registers every chip kind found in chips/)
|
|
13
|
+
from .chips.bar import bar
|
|
14
|
+
from .chips.ci import ci
|
|
15
|
+
from .chips.delta import delta
|
|
16
|
+
from .chips.dist import dist
|
|
17
|
+
from .chips.funnel import funnel
|
|
18
|
+
from .chips.gauge import gauge
|
|
19
|
+
from .chips.num import num
|
|
20
|
+
from .chips.rank import rank
|
|
21
|
+
from .chips.ratio import ratio
|
|
22
|
+
from .chips.share import share
|
|
23
|
+
from .chips.spark import spark
|
|
24
|
+
from .chips.strip import strip
|
|
25
|
+
from .chips.timeline import timeline
|
|
26
|
+
from .chips.waterfall import waterfall
|
|
27
|
+
from .scales import shared_domain, union_domain
|
|
28
|
+
from .spec import REGISTRY, Chip, ChipError, Kind, Param, catalog, from_dict
|
|
29
|
+
from .themes import THEMES, Theme, contrast_ratio, relative_luminance
|
|
30
|
+
|
|
31
|
+
# Importing `.spec` binds the internal `mintchip.render` subpackage onto this module; remove the
|
|
32
|
+
# attribute so `mintchip.render` resolves lazily to `mintchip.directives.render` while
|
|
33
|
+
# `from mintchip.render.html import ...` still works via `sys.modules`.
|
|
34
|
+
globals().pop("render", None)
|
|
35
|
+
|
|
36
|
+
__version__ = "0.2.0"
|
|
37
|
+
|
|
38
|
+
CATALOG = catalog()
|
|
39
|
+
|
|
40
|
+
# Loaded on first use, so `import mintchip` pays only for chips and text.
|
|
41
|
+
_LAZY = {
|
|
42
|
+
"Table": "tables",
|
|
43
|
+
"table": "tables",
|
|
44
|
+
"format_prose": "prose",
|
|
45
|
+
"lint": "prose",
|
|
46
|
+
"render": "directives",
|
|
47
|
+
"css": "render.html",
|
|
48
|
+
"document": "render.html",
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def __getattr__(name: str) -> Any:
|
|
53
|
+
module = _LAZY.get(name)
|
|
54
|
+
if module is None:
|
|
55
|
+
raise AttributeError(f"module 'mintchip' has no attribute {name!r}")
|
|
56
|
+
value = getattr(importlib.import_module(f"{__name__}.{module}"), name)
|
|
57
|
+
globals()[name] = value
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def __dir__() -> list[str]:
|
|
62
|
+
return sorted(__all__)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
__all__ = [
|
|
66
|
+
"CATALOG",
|
|
67
|
+
"REGISTRY",
|
|
68
|
+
"THEMES",
|
|
69
|
+
"Chip",
|
|
70
|
+
"ChipError",
|
|
71
|
+
"Kind",
|
|
72
|
+
"Param",
|
|
73
|
+
"Table",
|
|
74
|
+
"Theme",
|
|
75
|
+
"__version__",
|
|
76
|
+
"bar",
|
|
77
|
+
"ci",
|
|
78
|
+
"contrast_ratio",
|
|
79
|
+
"css",
|
|
80
|
+
"delta",
|
|
81
|
+
"dist",
|
|
82
|
+
"document",
|
|
83
|
+
"format_prose",
|
|
84
|
+
"from_dict",
|
|
85
|
+
"funnel",
|
|
86
|
+
"gauge",
|
|
87
|
+
"lint",
|
|
88
|
+
"num",
|
|
89
|
+
"rank",
|
|
90
|
+
"ratio",
|
|
91
|
+
"relative_luminance",
|
|
92
|
+
"render",
|
|
93
|
+
"share",
|
|
94
|
+
"shared_domain",
|
|
95
|
+
"spark",
|
|
96
|
+
"strip",
|
|
97
|
+
"table",
|
|
98
|
+
"timeline",
|
|
99
|
+
"union_domain",
|
|
100
|
+
"waterfall",
|
|
101
|
+
]
|
mintchip/__main__.py
ADDED
mintchip/chips/bar.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
"""bar: a value against a total, as a bullet bar on a context track.
|
|
2
|
+
|
|
3
|
+
Text: ``82% (target 90%) ██████▌│`` (compact drops the parenthesis): CELLS cells in eighths, the
|
|
4
|
+
rest of the track as ``·``, an unmet target as ``│`` on the track. A value above the total
|
|
5
|
+
fills the track and gains a ``+``: ``140% ████████+``, never a silent clip.
|
|
6
|
+
SVG: a context wash for the track (0 to total), an ink bar, and ink strokes: the target as a
|
|
7
|
+
tick across the track, the baseline as a short notch hanging under it (one kind of mark, told
|
|
8
|
+
apart by where it sits), and a chevron after the bar when the value overflows the total; only
|
|
9
|
+
then does the chip grow past the track, by ROOM, so the scale itself never moves.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from .. import fmt
|
|
15
|
+
from ..render.svg_base import Canvas
|
|
16
|
+
from ..render.text_base import REF, TRACK, Segment, TextOptions, TextOut, hbar
|
|
17
|
+
from ..spec import (
|
|
18
|
+
Built,
|
|
19
|
+
Chip,
|
|
20
|
+
ChipError,
|
|
21
|
+
Param,
|
|
22
|
+
chip,
|
|
23
|
+
domain_warnings,
|
|
24
|
+
own_scale,
|
|
25
|
+
svg_renderer,
|
|
26
|
+
text_renderer,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
CELLS = 8
|
|
30
|
+
OVER = "+" # appended to the text cells when the value exceeds the total or the domain
|
|
31
|
+
ROOM = 5.0 # width added after the track for an overflow chevron; the scale never moves
|
|
32
|
+
EDGE = 0.01 # a share this close to 0 or to the whole (but not on it) prints one decimal
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@chip(
|
|
36
|
+
"bar",
|
|
37
|
+
question="How much of a total, budget or capacity is used?",
|
|
38
|
+
have="A value against a total",
|
|
39
|
+
params=(
|
|
40
|
+
Param("value", "number", "Give the amount, 0 or more.", required=True, positional=True),
|
|
41
|
+
Param(
|
|
42
|
+
"total",
|
|
43
|
+
"number",
|
|
44
|
+
"Give the whole the value is measured against.",
|
|
45
|
+
positional=True,
|
|
46
|
+
default=1.0,
|
|
47
|
+
),
|
|
48
|
+
Param(
|
|
49
|
+
"baseline",
|
|
50
|
+
"number",
|
|
51
|
+
"Give an earlier or comparison value, drawn as a notch under the track.",
|
|
52
|
+
),
|
|
53
|
+
Param("target", "number", "Give a goal, drawn as a tick across the track."),
|
|
54
|
+
Param("percent", "bool", "Show the value as a percentage instead of value/total."),
|
|
55
|
+
Param("label", "string", "Say what is measured."),
|
|
56
|
+
Param("unit", "string", "Name the unit of value and total."),
|
|
57
|
+
),
|
|
58
|
+
example={"value": 0.82, "target": 0.9, "label": "Test coverage"},
|
|
59
|
+
size="m",
|
|
60
|
+
)
|
|
61
|
+
def bar(
|
|
62
|
+
value, total=1.0, *, baseline=None, target=None, percent=None, label=None, unit=None
|
|
63
|
+
) -> Built:
|
|
64
|
+
if total <= 0:
|
|
65
|
+
raise ChipError(
|
|
66
|
+
f"total must be positive; got {fmt.num(total)}.",
|
|
67
|
+
fix_hint="Pass the whole as total, e.g. mintchip.bar(412, 500).",
|
|
68
|
+
)
|
|
69
|
+
if value < 0:
|
|
70
|
+
raise ChipError(
|
|
71
|
+
f"value must be 0 or more; got {fmt.num(value)}.",
|
|
72
|
+
fix_hint="A bar starts at zero; for a signed change use mintchip.delta.",
|
|
73
|
+
)
|
|
74
|
+
for name, v in (("baseline", baseline), ("target", target)):
|
|
75
|
+
if v is not None and not 0 <= v <= total:
|
|
76
|
+
raise ChipError(
|
|
77
|
+
f"{name} {fmt.num(v)} must lie between 0 and the total {fmt.num(total)}.",
|
|
78
|
+
fix_hint=f"Pass {name}= on the same scale as value, at most total.",
|
|
79
|
+
)
|
|
80
|
+
if percent is None:
|
|
81
|
+
pct_mode = (unit is None and total == 1) or (unit == "%" and total == 100)
|
|
82
|
+
else:
|
|
83
|
+
pct_mode = percent
|
|
84
|
+
s = {
|
|
85
|
+
"value": value,
|
|
86
|
+
"total": total,
|
|
87
|
+
"frac": value / total,
|
|
88
|
+
"baseline": baseline,
|
|
89
|
+
"target": target,
|
|
90
|
+
"pct_mode": pct_mode,
|
|
91
|
+
"over": value > total,
|
|
92
|
+
}
|
|
93
|
+
f = _formatter(s, unit)
|
|
94
|
+
share = _pct(s["frac"])
|
|
95
|
+
|
|
96
|
+
warnings = []
|
|
97
|
+
if s["over"]:
|
|
98
|
+
of = "the total" if pct_mode else f"the total {f(total)} ({share})"
|
|
99
|
+
warnings.append(
|
|
100
|
+
f"value {f(value)} exceeds {of}; the bar fills the track and is marked {OVER} "
|
|
101
|
+
"in text and by a chevron in SVG."
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
def diff(d: float, signed: bool = False) -> str:
|
|
105
|
+
if pct_mode:
|
|
106
|
+
return fmt.pct(d / total, signed=signed).removesuffix("%") + " points"
|
|
107
|
+
return fmt.num(d, signed=signed, unit=unit)
|
|
108
|
+
|
|
109
|
+
facts = [f"{share} of the whole" if pct_mode else f"{share} of the total"]
|
|
110
|
+
if baseline is not None:
|
|
111
|
+
facts.append(f"{diff(value - baseline, True)} vs baseline {f(baseline)}")
|
|
112
|
+
if target is not None:
|
|
113
|
+
met = value >= target
|
|
114
|
+
facts.append(
|
|
115
|
+
f"meets the target {f(target)}"
|
|
116
|
+
if met
|
|
117
|
+
else f"{diff(target - value)} short of the target {f(target)}"
|
|
118
|
+
)
|
|
119
|
+
name = f"{label}: " if label else ""
|
|
120
|
+
return Built(
|
|
121
|
+
stats=s,
|
|
122
|
+
facts=facts,
|
|
123
|
+
warnings=warnings,
|
|
124
|
+
alt=f"{name}{fmt.num(value, unit=unit)} of {fmt.num(total, unit=unit)} ({share}).",
|
|
125
|
+
domain=(0.0, total),
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _pct(frac: float, dec: int | None = None) -> str:
|
|
130
|
+
"""A share of the total as a percentage. Within EDGE of 0 or of the total, but not on it,
|
|
131
|
+
one decimal at least (``99.5%``, not ``99%`` beside a true ``100%``), and more where needed:
|
|
132
|
+
a share that is not exactly 0 or 1 never prints as ``0%`` or ``100%``."""
|
|
133
|
+
near = 0 < frac <= EDGE or 1 - EDGE <= frac < 1
|
|
134
|
+
if dec is None and not near:
|
|
135
|
+
return fmt.pct(frac)
|
|
136
|
+
places = max(dec or 0, 1 if near else 0)
|
|
137
|
+
out = fmt.pct(frac, decimals=places)
|
|
138
|
+
while frac != 0 and not float(out.rstrip("%").replace(",", "")) and places < 6:
|
|
139
|
+
places += 1
|
|
140
|
+
out = fmt.pct(frac, decimals=places)
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _formatter(s: dict, unit: str | None, dec: int | None = None):
|
|
145
|
+
"""Percent of the total in percent mode, else the number with its unit; ``dec`` fixes the
|
|
146
|
+
decimal places (of the percentage in percent mode)."""
|
|
147
|
+
if s["pct_mode"]:
|
|
148
|
+
return lambda v: _pct(v / s["total"], dec)
|
|
149
|
+
if dec is not None:
|
|
150
|
+
return lambda v: fmt.fixed(v, dec, unit=unit)
|
|
151
|
+
return lambda v: fmt.num(v, unit=unit)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@domain_warnings("bar")
|
|
155
|
+
def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
|
|
156
|
+
"""A scale that ends before the value cuts the bar (a value over the total already warns)."""
|
|
157
|
+
s, (lo, hi) = chip.stats, domain
|
|
158
|
+
if lo <= s["value"] <= hi or s["over"]:
|
|
159
|
+
return []
|
|
160
|
+
f = _formatter(s, chip.unit)
|
|
161
|
+
how = (
|
|
162
|
+
f"it fills the track and is marked {OVER} in text and by a chevron in SVG"
|
|
163
|
+
if s["value"] > hi
|
|
164
|
+
else "the bar is empty"
|
|
165
|
+
)
|
|
166
|
+
return [f"domain {f(lo)} to {f(hi)} cuts the bar at {f(s['value'])}; {how}."]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# --- text -----------------------------------------------------------------------------------
|
|
170
|
+
@text_renderer("bar")
|
|
171
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
172
|
+
s = chip.stats
|
|
173
|
+
f = _formatter(s, chip.unit)
|
|
174
|
+
own = f(s["value"]) if s["pct_mode"] else fmt.num(s["value"])
|
|
175
|
+
dec = fmt.places(own) if o.decimals is None or fmt.places(own) is None else o.decimals
|
|
176
|
+
if s["pct_mode"]:
|
|
177
|
+
value = own if o.decimals is None else _formatter(s, None, dec)(s["value"])
|
|
178
|
+
notes = []
|
|
179
|
+
else:
|
|
180
|
+
num = _formatter(s, None, None if o.decimals is None else dec)
|
|
181
|
+
value = f"{num(s['value'])}/{fmt.with_unit(num(s['total']), chip.unit)}"
|
|
182
|
+
notes = [_pct(s["frac"])]
|
|
183
|
+
if not o.compact:
|
|
184
|
+
notes += [f"{k} {f(s[k])}" for k in ("baseline", "target") if s[k] is not None]
|
|
185
|
+
if notes:
|
|
186
|
+
value += f" ({', '.join(notes)})"
|
|
187
|
+
|
|
188
|
+
lo, hi = o.domain
|
|
189
|
+
scale = CELLS / (hi - lo)
|
|
190
|
+
cells = max(0.0, min(s["value"], hi) - lo) * scale
|
|
191
|
+
# ASCII has no eighths (▌ would become a "|" that reads as a tick): round to whole cells.
|
|
192
|
+
fill = "█" * round(cells) if o.ascii else hbar(cells)
|
|
193
|
+
end = round(max(0.0, min(s["total"], hi) - lo) * scale)
|
|
194
|
+
track = [TRACK] * max(0, end - len(fill))
|
|
195
|
+
t = s["target"]
|
|
196
|
+
if t is not None and lo <= t <= hi:
|
|
197
|
+
i = min(CELLS - 1, int((t - lo) * scale)) - len(fill)
|
|
198
|
+
if 0 <= i < len(track): # an unmet target shows on the track; a met one is covered
|
|
199
|
+
track[i] = REF
|
|
200
|
+
glyph: list[Segment] = [(fill, None), ("".join(track), "context")]
|
|
201
|
+
if s["value"] > min(s["total"], hi):
|
|
202
|
+
glyph.append((OVER, None))
|
|
203
|
+
return TextOut(value, [g for g in glyph if g[0]], dec)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
207
|
+
@svg_renderer("bar")
|
|
208
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
209
|
+
s = chip.stats
|
|
210
|
+
lo, hi = c.domain
|
|
211
|
+
if s["value"] > min(s["total"], hi): # room for the overflow chevron, after the track
|
|
212
|
+
c.width += ROOM
|
|
213
|
+
v = min(s["value"], hi)
|
|
214
|
+
x0 = c.left
|
|
215
|
+
c.rect(x0, 4, c.x(min(s["total"], hi)) - x0, 8, role="context")
|
|
216
|
+
title = _formatter(s, chip.unit)(s["value"])
|
|
217
|
+
if v > lo:
|
|
218
|
+
c.rect(x0, 5.5, c.x(v) - x0, 5, role="ink", title=title)
|
|
219
|
+
b, t = s["baseline"], s["target"]
|
|
220
|
+
if b is not None and c.contains(b): # a notch hanging under the track, like an axis tick
|
|
221
|
+
x = c.x(b)
|
|
222
|
+
c.line(x, 12, x, 15, title=f"baseline {_formatter(s, chip.unit)(b)}")
|
|
223
|
+
if t is not None and c.contains(t):
|
|
224
|
+
x = c.x(t)
|
|
225
|
+
c.line(x, 2, x, 14, title=f"target {_formatter(s, chip.unit)(t)}")
|
|
226
|
+
if s["value"] > min(s["total"], hi): # overflow: a chevron just past the bar's end
|
|
227
|
+
x = max(c.x(v), x0) + 1.5
|
|
228
|
+
y = c.mid
|
|
229
|
+
c.path([(x, y - 3), (x + 2.5, y), (x, y + 3)], width=1.25, title=f"over: {title}")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# A bar is a share of its own total: siblings keep their own scales unless the totals agree.
|
|
233
|
+
own_scale("bar")
|
mintchip/chips/ci.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""ci: an estimate with its interval, against a reference. The exemplar for an axis-position
|
|
2
|
+
chip (``[...]`` text track, x-domain, reference line).
|
|
3
|
+
|
|
4
|
+
Text: ``+0.08 (95% CI +0.05 to +0.11) [·│···├─●─┤·]``; compact drops the parenthesis. The dot is
|
|
5
|
+
hollow (``○``) when the interval crosses the reference: shape says it, not colour. The estimate
|
|
6
|
+
and both bounds share one decimal place: the fewest at which rounding moves none of them by more
|
|
7
|
+
than 3% of the interval width (``fmt.resolving``), so ``+0.031 (… +0.012 to +0.050)``.
|
|
8
|
+
SVG: a whisker with end ticks, a solid or hollow dot, a context reference line. Drawn alone, it
|
|
9
|
+
spans just its marks; the text track keeps a margin cell, which is axis, not blank.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from .. import fmt
|
|
15
|
+
from ..render.svg_base import Canvas
|
|
16
|
+
from ..render.text_base import CROSS, DOT, HOLLOW, REF, TextOptions, TextOut, Track
|
|
17
|
+
from ..scales import padded
|
|
18
|
+
from ..spec import (
|
|
19
|
+
Built,
|
|
20
|
+
Chip,
|
|
21
|
+
ChipError,
|
|
22
|
+
Param,
|
|
23
|
+
chip,
|
|
24
|
+
domain_warnings,
|
|
25
|
+
svg_renderer,
|
|
26
|
+
text_renderer,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
CELLS = 11
|
|
30
|
+
PAD = 0.16 # natural domain margin, as a fraction of the drawn extent (text track cells)
|
|
31
|
+
FIT = 0.02 # the SVG's margin when drawn on its own scale: room for a dot at an end
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@chip(
|
|
35
|
+
"ci",
|
|
36
|
+
question="What is the estimate, and how sure are we?",
|
|
37
|
+
have="An estimate with an interval",
|
|
38
|
+
params=(
|
|
39
|
+
Param("estimate", "number", "Give the point estimate.", required=True, positional=True),
|
|
40
|
+
Param(
|
|
41
|
+
"interval",
|
|
42
|
+
"range",
|
|
43
|
+
"Give the interval (lo, hi) around the estimate.",
|
|
44
|
+
required=True,
|
|
45
|
+
positional=True,
|
|
46
|
+
),
|
|
47
|
+
Param("level", "number", "State the interval's coverage, e.g. 0.95 for a 95% CI."),
|
|
48
|
+
Param("inner", "range", "Give a narrower inner interval (lo, hi), drawn thicker."),
|
|
49
|
+
Param(
|
|
50
|
+
"reference", "number", "Give the null value; None for no reference line.", default=0.0
|
|
51
|
+
),
|
|
52
|
+
Param("domain", "range", "Fix the x-range (lo, hi); share it so ci chips compare."),
|
|
53
|
+
Param("label", "string", "Say what is estimated."),
|
|
54
|
+
Param("unit", "string", "Name the unit of the estimate."),
|
|
55
|
+
),
|
|
56
|
+
example={"estimate": 0.08, "interval": (0.05, 0.11), "level": 0.95, "label": "Retrieval lift"},
|
|
57
|
+
size="m",
|
|
58
|
+
)
|
|
59
|
+
def ci(
|
|
60
|
+
estimate,
|
|
61
|
+
interval,
|
|
62
|
+
*,
|
|
63
|
+
level=None,
|
|
64
|
+
inner=None,
|
|
65
|
+
reference=0.0,
|
|
66
|
+
domain=None,
|
|
67
|
+
label=None,
|
|
68
|
+
unit=None,
|
|
69
|
+
) -> Built:
|
|
70
|
+
lo, hi = interval
|
|
71
|
+
if level is not None and not 0 < level < 1:
|
|
72
|
+
raise ChipError(
|
|
73
|
+
f"level must be between 0 and 1; got {level}.",
|
|
74
|
+
fix_hint="State the coverage as a fraction (level=0.95).",
|
|
75
|
+
)
|
|
76
|
+
if inner is not None and not lo <= inner[0] <= inner[1] <= hi:
|
|
77
|
+
raise ChipError(
|
|
78
|
+
f"inner {inner} must lie within interval {interval}.",
|
|
79
|
+
fix_hint="Pass the narrower interval as inner=, e.g. the 50% CI inside the 95% CI.",
|
|
80
|
+
)
|
|
81
|
+
s = {
|
|
82
|
+
"value": estimate,
|
|
83
|
+
"estimate": estimate,
|
|
84
|
+
"lo": lo,
|
|
85
|
+
"hi": hi,
|
|
86
|
+
"inner": inner,
|
|
87
|
+
"reference": reference,
|
|
88
|
+
"level": level,
|
|
89
|
+
"crosses": None if reference is None else lo <= reference <= hi,
|
|
90
|
+
"dec": fmt.resolving([estimate, lo, hi], hi - lo),
|
|
91
|
+
"signed": reference == 0,
|
|
92
|
+
}
|
|
93
|
+
ends = _ends(s)
|
|
94
|
+
natural = padded(min(ends), max(ends), PAD)
|
|
95
|
+
|
|
96
|
+
warnings = []
|
|
97
|
+
if level is None:
|
|
98
|
+
warnings.append(
|
|
99
|
+
"interval level not stated; state the interval's level (level=0.95) or its true "
|
|
100
|
+
"coverage."
|
|
101
|
+
)
|
|
102
|
+
if not lo <= estimate <= hi:
|
|
103
|
+
warnings.append(f"estimate {_f(s, estimate)} lies outside its interval.")
|
|
104
|
+
warnings += _cut_lines(s, unit, domain or natural)
|
|
105
|
+
|
|
106
|
+
what = f"{fmt.pct(level)} interval" if level is not None else "interval"
|
|
107
|
+
facts = [f"{what} width {fmt.fixed(hi - lo, s['dec'], unit=unit)}"]
|
|
108
|
+
if inner is not None:
|
|
109
|
+
facts.append(f"inner interval {_f(s, inner[0])} to {_f(s, inner[1], unit)}")
|
|
110
|
+
alt = f"estimate {_f(s, estimate, unit)}, {what} {_f(s, lo)} to {_f(s, hi, unit)}"
|
|
111
|
+
if reference is not None:
|
|
112
|
+
relation = "crosses" if s["crosses"] else "excludes"
|
|
113
|
+
facts.append(f"{relation} the reference {fmt.num(reference, unit=unit)}")
|
|
114
|
+
alt += f", {relation} {fmt.num(reference)}"
|
|
115
|
+
return Built(
|
|
116
|
+
stats=s,
|
|
117
|
+
facts=facts,
|
|
118
|
+
warnings=warnings,
|
|
119
|
+
alt=f"{label}: {alt}." if label else f"{alt[0].upper()}{alt[1:]}.",
|
|
120
|
+
domain=natural,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _ends(s: dict) -> list[float]:
|
|
125
|
+
ref = s["reference"]
|
|
126
|
+
return [s["lo"], s["hi"], s["estimate"]] + ([ref] if ref is not None else [])
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _cut_lines(s: dict, unit: str | None, domain: tuple[float, float]) -> list[str]:
|
|
130
|
+
ends = _ends(s)
|
|
131
|
+
if min(ends) >= domain[0] and max(ends) <= domain[1]:
|
|
132
|
+
return []
|
|
133
|
+
lo, hi = fmt.num(domain[0]), fmt.num(domain[1], unit=unit)
|
|
134
|
+
return [
|
|
135
|
+
(
|
|
136
|
+
f"domain {lo} to {hi} cuts the interval; the cut end is marked at the edge (< or > in "
|
|
137
|
+
"text, a chevron in SVG)."
|
|
138
|
+
)
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@domain_warnings("ci")
|
|
143
|
+
def _cuts(chip: Chip, domain: tuple[float, float], own: bool) -> list[str]:
|
|
144
|
+
return _cut_lines(chip.stats, chip.unit, domain)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _f(s: dict, v: float, unit: str | None = None, dec: int | None = None) -> str:
|
|
148
|
+
"""Every number in one ci shares a decimal place, set by the interval width."""
|
|
149
|
+
return fmt.fixed(v, s["dec"] if dec is None else dec, signed=s["signed"], unit=unit)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# --- text -----------------------------------------------------------------------------------
|
|
153
|
+
@text_renderer("ci")
|
|
154
|
+
def _text(chip: Chip, o: TextOptions) -> TextOut:
|
|
155
|
+
s = chip.stats
|
|
156
|
+
dec = s["dec"] if o.decimals is None else o.decimals
|
|
157
|
+
value = _f(s, s["estimate"], chip.unit, dec)
|
|
158
|
+
if not o.compact:
|
|
159
|
+
what = f"{fmt.pct(s['level'])} CI " if s["level"] is not None else ""
|
|
160
|
+
value += f" ({what}{_f(s, s['lo'], dec=dec)} to {_f(s, s['hi'], dec=dec)})"
|
|
161
|
+
|
|
162
|
+
t = Track(CELLS, o.domain)
|
|
163
|
+
ref = s["reference"]
|
|
164
|
+
if ref is not None and t.contains(ref):
|
|
165
|
+
t.put(ref, REF, "context")
|
|
166
|
+
t.span(s["lo"], s["hi"])
|
|
167
|
+
if s["crosses"] and t.contains(ref):
|
|
168
|
+
t.put(ref, CROSS)
|
|
169
|
+
t.put(s["estimate"], HOLLOW if s["crosses"] else DOT)
|
|
170
|
+
return TextOut(value, t.glyph(), dec)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# --- svg ------------------------------------------------------------------------------------
|
|
174
|
+
@svg_renderer("ci")
|
|
175
|
+
def _svg(chip: Chip, c: Canvas) -> None:
|
|
176
|
+
s = chip.stats
|
|
177
|
+
if c.natural: # alone: the scale spans the marks, so no blank margin sits in the sentence
|
|
178
|
+
ends = _ends(s)
|
|
179
|
+
c.domain = padded(min(ends), max(ends), FIT)
|
|
180
|
+
y = c.mid
|
|
181
|
+
ref = s["reference"]
|
|
182
|
+
if ref is not None and c.contains(ref):
|
|
183
|
+
x = c.x(ref)
|
|
184
|
+
c.line(x, 1.5, x, 14.5, role="context")
|
|
185
|
+
x1, x2 = c.x(s["lo"]), c.x(s["hi"])
|
|
186
|
+
c.line(x1, y, x2, y)
|
|
187
|
+
for end, x in ((s["lo"], x1), (s["hi"], x2)):
|
|
188
|
+
if c.contains(end): # a cut end gets the edge chevron instead of a tick
|
|
189
|
+
c.line(x, y - 3, x, y + 3)
|
|
190
|
+
if s["inner"] is not None:
|
|
191
|
+
c.line(c.x(s["inner"][0]), y, c.x(s["inner"][1]), y, width=3.5)
|
|
192
|
+
hollow = bool(s["crosses"])
|
|
193
|
+
title = _f(s, s["estimate"], chip.unit)
|
|
194
|
+
c.dot(c.x(s["estimate"]), y, r=2.5 if hollow else 2.75, hollow=hollow, title=title)
|