mintfig 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.
- mintfig/__init__.py +162 -0
- mintfig/_explain/__init__.py +1 -0
- mintfig/_explain/change.py +392 -0
- mintfig/_explain/compare.py +1308 -0
- mintfig/_explain/compare_grouped.py +472 -0
- mintfig/_explain/core.py +2005 -0
- mintfig/_explain/distribution.py +1268 -0
- mintfig/_explain/flow.py +508 -0
- mintfig/_explain/layout.py +2012 -0
- mintfig/_explain/matrix.py +623 -0
- mintfig/_explain/relate.py +1318 -0
- mintfig/_explain/timeline.py +595 -0
- mintfig/_explain/trend.py +2557 -0
- mintfig/_explain/waterfall.py +459 -0
- mintfig/_table.py +691 -0
- mintfig/_tabular.py +738 -0
- mintfig/annotations.py +1165 -0
- mintfig/assets/AGENTS_SNIPPET.md +11 -0
- mintfig/assets/SKILL.md +143 -0
- mintfig/assets/__init__.py +1 -0
- mintfig/assets/references/publication.md +79 -0
- mintfig/assets/references/scientific_and_recipes.md +213 -0
- mintfig/audit.py +179 -0
- mintfig/brief.py +518 -0
- mintfig/bundle.py +333 -0
- mintfig/cli.py +1300 -0
- mintfig/edit.py +347 -0
- mintfig/epistemic.py +1083 -0
- mintfig/explainer.py +194 -0
- mintfig/export.py +247 -0
- mintfig/inspect_data.py +583 -0
- mintfig/interactive.py +1028 -0
- mintfig/palettes.py +233 -0
- mintfig/plate.py +784 -0
- mintfig/preflight.py +2398 -0
- mintfig/proof.py +627 -0
- mintfig/runner.py +403 -0
- mintfig/skill.py +167 -0
- mintfig/specs.py +291 -0
- mintfig/style.py +151 -0
- mintfig/terminal.py +785 -0
- mintfig/themes.py +660 -0
- mintfig-0.2.0.dist-info/METADATA +239 -0
- mintfig-0.2.0.dist-info/RECORD +47 -0
- mintfig-0.2.0.dist-info/WHEEL +4 -0
- mintfig-0.2.0.dist-info/entry_points.txt +2 -0
- mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/_explain/flow.py
ADDED
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
"""flow() quantitative attrition / cohort / funnel form for mint.explain.
|
|
2
|
+
|
|
3
|
+
Answers: "How much survives each stage of a pipeline or cohort, where is the
|
|
4
|
+
biggest drop, and why?"
|
|
5
|
+
Draws sequential top-to-bottom horizontal bars (preserving stage order, always
|
|
6
|
+
grounded at zero) with remaining count + % of start beside each bar and
|
|
7
|
+
drop-off callouts (count, % of prior stage, optional exclusion reason) in the
|
|
8
|
+
lane between consecutive stages.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from matplotlib.axes import Axes
|
|
18
|
+
|
|
19
|
+
from .._tabular import extract_records, is_tabular
|
|
20
|
+
from ..themes import MINTFIG_THEME, Theme
|
|
21
|
+
from .core import (
|
|
22
|
+
PT_TO_MM,
|
|
23
|
+
ExplainError,
|
|
24
|
+
Panel,
|
|
25
|
+
_bare_axes,
|
|
26
|
+
_base_spec,
|
|
27
|
+
_Ctx,
|
|
28
|
+
_diff_with_unit,
|
|
29
|
+
_formatter,
|
|
30
|
+
_guarded,
|
|
31
|
+
_is_strict,
|
|
32
|
+
_issue,
|
|
33
|
+
_jsonable,
|
|
34
|
+
_Measure,
|
|
35
|
+
_names,
|
|
36
|
+
_plain,
|
|
37
|
+
_record_adjustment,
|
|
38
|
+
_signed,
|
|
39
|
+
_Sizes,
|
|
40
|
+
_to_float,
|
|
41
|
+
_with_unit,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
MAX_FLOW_STAGES = 12
|
|
45
|
+
COMFORTABLE_FLOW_STAGES = 8
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _normalize_stages(
|
|
49
|
+
stages: object,
|
|
50
|
+
*,
|
|
51
|
+
name: str | None = None,
|
|
52
|
+
value: str | None = None,
|
|
53
|
+
reason: str | None = None,
|
|
54
|
+
) -> list[dict[str, Any]]:
|
|
55
|
+
"""Normalize dict, tuple list, or tidy rows into ``[{"name", "value", "reason"}]``."""
|
|
56
|
+
if is_tabular(stages):
|
|
57
|
+
cols, rows = extract_records(stages, what="flow(stages)")
|
|
58
|
+
if not rows:
|
|
59
|
+
raise ExplainError("flow(stages) is empty.", fix_hint="Pass at least two stages.")
|
|
60
|
+
lower_map = {c.lower(): c for c in cols}
|
|
61
|
+
n_col = name or next(
|
|
62
|
+
(lower_map[k] for k in ("stage", "step", "name", "phase", "label") if k in lower_map),
|
|
63
|
+
None,
|
|
64
|
+
)
|
|
65
|
+
v_col = value or next(
|
|
66
|
+
(
|
|
67
|
+
lower_map[k]
|
|
68
|
+
for k in ("count", "value", "n", "remaining", "users", "samples", "items")
|
|
69
|
+
if k in lower_map
|
|
70
|
+
),
|
|
71
|
+
None,
|
|
72
|
+
)
|
|
73
|
+
r_col = reason or next(
|
|
74
|
+
(
|
|
75
|
+
lower_map[k]
|
|
76
|
+
for k in ("reason", "drop_reason", "exclusion", "excluded", "cause", "note")
|
|
77
|
+
if k in lower_map
|
|
78
|
+
),
|
|
79
|
+
None,
|
|
80
|
+
)
|
|
81
|
+
if not (n_col and v_col):
|
|
82
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
83
|
+
raise ExplainError(
|
|
84
|
+
f"flow() needs name= and value= columns for row-shaped data (columns: {shown}).",
|
|
85
|
+
fix_hint='Pass flow(rows, name="stage", value="count", reason="drop_reason").',
|
|
86
|
+
)
|
|
87
|
+
for col, arg in ((n_col, "name"), (v_col, "value")):
|
|
88
|
+
if col not in cols:
|
|
89
|
+
raise ExplainError(
|
|
90
|
+
f"flow({arg}={col!r}) column not found.",
|
|
91
|
+
fix_hint=f"Available columns: {', '.join(map(repr, cols[:10]))}.",
|
|
92
|
+
)
|
|
93
|
+
if reason is not None and reason not in cols:
|
|
94
|
+
raise ExplainError(
|
|
95
|
+
f"flow(reason={reason!r}) column not found.",
|
|
96
|
+
fix_hint=f"Available columns: {', '.join(map(repr, cols[:10]))}.",
|
|
97
|
+
)
|
|
98
|
+
out: list[dict[str, Any]] = []
|
|
99
|
+
for row in rows:
|
|
100
|
+
nm = str(row.get(n_col, "")).strip()
|
|
101
|
+
val = _to_float(row.get(v_col), f"flow(value[{nm!r}])")
|
|
102
|
+
rsn_raw = row.get(r_col) if r_col is not None else None
|
|
103
|
+
rsn = str(rsn_raw).strip() if rsn_raw is not None and str(rsn_raw).strip() else None
|
|
104
|
+
out.append({"name": nm, "value": val, "reason": rsn})
|
|
105
|
+
return out
|
|
106
|
+
|
|
107
|
+
if any(a is not None for a in (name, value, reason)):
|
|
108
|
+
raise ExplainError(
|
|
109
|
+
"flow(name=/value=/reason=) require row-shaped data (list of dicts or DataFrame).",
|
|
110
|
+
fix_hint='Pass rows=[{"stage": "Screened", "count": 1240}, ...] or drop column args.',
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
if isinstance(stages, Mapping):
|
|
114
|
+
if not stages:
|
|
115
|
+
raise ExplainError("flow(stages) is empty.", fix_hint="Pass at least two stages.")
|
|
116
|
+
out = []
|
|
117
|
+
for raw_nm, raw_val in stages.items():
|
|
118
|
+
nm = str(raw_nm)
|
|
119
|
+
if (
|
|
120
|
+
isinstance(raw_val, Sequence)
|
|
121
|
+
and not isinstance(raw_val, (str, bytes))
|
|
122
|
+
and len(raw_val) == 2
|
|
123
|
+
):
|
|
124
|
+
val = _to_float(raw_val[0], f"flow(stages[{nm!r}][0])")
|
|
125
|
+
rsn = str(raw_val[1]).strip() if raw_val[1] is not None and str(raw_val[1]).strip() else None
|
|
126
|
+
else:
|
|
127
|
+
val = _to_float(raw_val, f"flow(stages[{nm!r}])")
|
|
128
|
+
rsn = None
|
|
129
|
+
out.append({"name": nm, "value": val, "reason": rsn})
|
|
130
|
+
return out
|
|
131
|
+
|
|
132
|
+
if isinstance(stages, Sequence) and not isinstance(stages, (str, bytes)):
|
|
133
|
+
if not stages:
|
|
134
|
+
raise ExplainError("flow(stages) is empty.", fix_hint="Pass at least two stages.")
|
|
135
|
+
out = []
|
|
136
|
+
for idx, entry in enumerate(stages):
|
|
137
|
+
if (
|
|
138
|
+
isinstance(entry, (str, bytes))
|
|
139
|
+
or not isinstance(entry, Sequence)
|
|
140
|
+
or len(entry) not in {2, 3}
|
|
141
|
+
):
|
|
142
|
+
raise ExplainError(
|
|
143
|
+
f"flow(stages[{idx}]) must be (name, count) or (name, count, reason).",
|
|
144
|
+
fix_hint='e.g. [("Screened", 1240), ("Eligible", 912, "missing baseline")].',
|
|
145
|
+
)
|
|
146
|
+
nm = str(entry[0])
|
|
147
|
+
val = _to_float(entry[1], f"flow(stages[{nm!r}])")
|
|
148
|
+
rsn = (
|
|
149
|
+
str(entry[2]).strip()
|
|
150
|
+
if len(entry) == 3 and entry[2] is not None and str(entry[2]).strip()
|
|
151
|
+
else None
|
|
152
|
+
)
|
|
153
|
+
out.append({"name": nm, "value": val, "reason": rsn})
|
|
154
|
+
return out
|
|
155
|
+
|
|
156
|
+
raise ExplainError(
|
|
157
|
+
f"flow(stages) expected a dict, list of (stage, count[, reason]) tuples, or rows; got {type(stages).__name__}.",
|
|
158
|
+
fix_hint='e.g. mint.flow([("Screened", 1240), ("Eligible", 912, "missing baseline")]).',
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@_guarded("flow")
|
|
163
|
+
def flow(
|
|
164
|
+
stages: (
|
|
165
|
+
Mapping[str, float]
|
|
166
|
+
| Sequence[tuple[str, float]]
|
|
167
|
+
| Sequence[tuple[str, float, str | None]]
|
|
168
|
+
| Sequence[Mapping[str, Any]]
|
|
169
|
+
),
|
|
170
|
+
*,
|
|
171
|
+
name: str | None = None,
|
|
172
|
+
value: str | None = None,
|
|
173
|
+
reason: str | None = None,
|
|
174
|
+
title: str | None = None,
|
|
175
|
+
label: str | None = None,
|
|
176
|
+
unit: str | None = None,
|
|
177
|
+
highlight: str | Sequence[str] | None = None,
|
|
178
|
+
show_pct: bool = True,
|
|
179
|
+
fmt: str | None = None,
|
|
180
|
+
) -> Panel:
|
|
181
|
+
"""How much survives each stage of a pipeline or cohort, where is the biggest drop, and why?
|
|
182
|
+
|
|
183
|
+
``stages`` preserves sequential top-to-bottom order and accepts ``{stage: count}``,
|
|
184
|
+
``[(stage, count[, drop_reason]), ...]``, or row-shaped data with ``name=``, ``value=``,
|
|
185
|
+
and optional ``reason=`` (explaining the drop entering each stage).
|
|
186
|
+
"""
|
|
187
|
+
records = _normalize_stages(stages, name=name, value=value, reason=reason)
|
|
188
|
+
if len(records) < 2:
|
|
189
|
+
raise ExplainError(
|
|
190
|
+
"flow() needs at least two stages to show retention or attrition.",
|
|
191
|
+
fix_hint="Pass two or more ordered stages, or use compare() for a single snapshot.",
|
|
192
|
+
)
|
|
193
|
+
for rec in records:
|
|
194
|
+
if rec["value"] < 0:
|
|
195
|
+
raise ExplainError(
|
|
196
|
+
f"flow() stage {rec['name']!r} has negative value {rec['value']}.",
|
|
197
|
+
fix_hint="flow() requires non-negative counts; use waterfall() for signed deltas.",
|
|
198
|
+
)
|
|
199
|
+
if records[0]["value"] <= 0:
|
|
200
|
+
raise ExplainError(
|
|
201
|
+
f"flow() first stage {records[0]['name']!r} must be positive (got {records[0]['value']}).",
|
|
202
|
+
fix_hint="Start the flow with a positive initial cohort or total.",
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
if len(records) > MAX_FLOW_STAGES:
|
|
206
|
+
if not _is_strict():
|
|
207
|
+
orig_n = len(records)
|
|
208
|
+
# Keep first, last, and intermediate stages with largest drops
|
|
209
|
+
req_hl = (
|
|
210
|
+
[highlight]
|
|
211
|
+
if isinstance(highlight, str)
|
|
212
|
+
else ([str(h) for h in highlight] if highlight is not None else [])
|
|
213
|
+
)
|
|
214
|
+
hl_req = set(req_hl)
|
|
215
|
+
must = {0, orig_n - 1} | {i for i, r in enumerate(records) if r["name"] in hl_req}
|
|
216
|
+
drops = sorted(
|
|
217
|
+
range(1, orig_n - 1),
|
|
218
|
+
key=lambda i: abs(records[i]["value"] - records[i - 1]["value"]),
|
|
219
|
+
reverse=True,
|
|
220
|
+
)
|
|
221
|
+
chosen = set(must)
|
|
222
|
+
for idx in drops:
|
|
223
|
+
if len(chosen) >= MAX_FLOW_STAGES:
|
|
224
|
+
break
|
|
225
|
+
chosen.add(idx)
|
|
226
|
+
records = [records[i] for i in sorted(chosen)]
|
|
227
|
+
_record_adjustment(f"flow(): kept {len(records)} of {orig_n} stages (first, last, and largest drops)")
|
|
228
|
+
else:
|
|
229
|
+
raise ExplainError(
|
|
230
|
+
f"flow() got {len(records)} stages; more than {MAX_FLOW_STAGES} is crowded in one funnel.",
|
|
231
|
+
fix_hint=f"Group minor intermediate steps into at most {MAX_FLOW_STAGES} stages.",
|
|
232
|
+
rule="too_many_items",
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
stage_names = [r["name"] for r in records]
|
|
236
|
+
vals = [float(r["value"]) for r in records]
|
|
237
|
+
hl = _names(highlight, stage_names, "flow(highlight)")
|
|
238
|
+
|
|
239
|
+
issues: list[dict[str, Any]] = []
|
|
240
|
+
if len(records) > COMFORTABLE_FLOW_STAGES:
|
|
241
|
+
issues.append(
|
|
242
|
+
_issue(
|
|
243
|
+
"many_items",
|
|
244
|
+
"warning",
|
|
245
|
+
f"{len(records)} flow stages is long for one glance.",
|
|
246
|
+
"Combine minor intermediate filters if the detail is not needed.",
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
start_val = vals[0]
|
|
251
|
+
end_val = vals[-1]
|
|
252
|
+
max_val = max(vals)
|
|
253
|
+
transitions: list[tuple[int, float, float, str | None]] = []
|
|
254
|
+
for i in range(1, len(records)):
|
|
255
|
+
prev_v = vals[i - 1]
|
|
256
|
+
delta = vals[i] - prev_v
|
|
257
|
+
step_pct = (100.0 * delta / prev_v) if prev_v > 0 else 0.0
|
|
258
|
+
transitions.append((i, delta, step_pct, records[i]["reason"]))
|
|
259
|
+
|
|
260
|
+
all_nums = [*vals, *(abs(d) for _, d, _, _ in transitions if d != 0)]
|
|
261
|
+
val_fmt = _formatter(all_nums, fmt, unit=unit)
|
|
262
|
+
|
|
263
|
+
def _v(x: float) -> str:
|
|
264
|
+
return _with_unit(val_fmt(x), unit)
|
|
265
|
+
|
|
266
|
+
def _pct_str(p: float) -> str:
|
|
267
|
+
ap = abs(p)
|
|
268
|
+
if ap >= 10 or abs(p - round(p)) < 0.05:
|
|
269
|
+
return f"{p:.0f}%"
|
|
270
|
+
return f"{p:.1f}%"
|
|
271
|
+
|
|
272
|
+
def _signed_pct(p: float) -> str:
|
|
273
|
+
if p < 0:
|
|
274
|
+
return f"\N{MINUS SIGN}{_pct_str(abs(p))}"
|
|
275
|
+
if p > 0:
|
|
276
|
+
return f"+{_pct_str(abs(p))}"
|
|
277
|
+
return "0%"
|
|
278
|
+
|
|
279
|
+
# Facts
|
|
280
|
+
ret_pct = 100.0 * end_val / start_val
|
|
281
|
+
net_drop = start_val - end_val
|
|
282
|
+
facts: list[str] = [
|
|
283
|
+
(
|
|
284
|
+
f"{stage_names[0]} {_v(start_val)} \N{RIGHTWARDS ARROW} {stage_names[-1]} {_v(end_val)} "
|
|
285
|
+
f"({ret_pct:.1f}% retained; {_v(net_drop)} dropped across {len(records) - 1} steps)"
|
|
286
|
+
if net_drop >= 0
|
|
287
|
+
else f"{stage_names[0]} {_v(start_val)} \N{RIGHTWARDS ARROW} {stage_names[-1]} {_v(end_val)} "
|
|
288
|
+
f"({ret_pct:.1f}% of initial across {len(records) - 1} steps)"
|
|
289
|
+
)
|
|
290
|
+
]
|
|
291
|
+
|
|
292
|
+
drop_transitions = [t for t in transitions if t[1] < 0]
|
|
293
|
+
biggest_drop_idx: int | None = None
|
|
294
|
+
if drop_transitions:
|
|
295
|
+
worst = min(drop_transitions, key=lambda t: t[1])
|
|
296
|
+
biggest_drop_idx = worst[0]
|
|
297
|
+
wi, wd, wp, wrsn = worst
|
|
298
|
+
rsn_suffix = f" ({wrsn})" if wrsn else ""
|
|
299
|
+
facts.append(
|
|
300
|
+
f"largest drop: {stage_names[wi - 1]} \N{RIGHTWARDS ARROW} {stage_names[wi]} "
|
|
301
|
+
f"({_diff_with_unit(_signed(val_fmt(wd)), unit)}, {_signed_pct(wp)} of prior stage){rsn_suffix}"
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
for nm in hl:
|
|
305
|
+
idx = stage_names.index(nm)
|
|
306
|
+
p_init = 100.0 * vals[idx] / start_val
|
|
307
|
+
extra = ""
|
|
308
|
+
if idx > 0:
|
|
309
|
+
prev_v = vals[idx - 1]
|
|
310
|
+
d = vals[idx] - prev_v
|
|
311
|
+
sp = (100.0 * d / prev_v) if prev_v > 0 else 0.0
|
|
312
|
+
rsn = records[idx]["reason"]
|
|
313
|
+
extra = f", {_diff_with_unit(_signed(val_fmt(d)), unit)} ({_signed_pct(sp)}) from {stage_names[idx - 1]}"
|
|
314
|
+
if rsn:
|
|
315
|
+
extra += f": {rsn}"
|
|
316
|
+
facts.append(f"{nm}: {_v(vals[idx])} ({p_init:.1f}% of {stage_names[0]}{extra})")
|
|
317
|
+
|
|
318
|
+
n_rows = len(records)
|
|
319
|
+
hl_set = set(hl)
|
|
320
|
+
has_reasons = any(r["reason"] for r in records[1:])
|
|
321
|
+
|
|
322
|
+
def _wrapped(
|
|
323
|
+
cell_width_mm: float,
|
|
324
|
+
measure: _Measure,
|
|
325
|
+
sizes: _Sizes,
|
|
326
|
+
theme: Theme = MINTFIG_THEME,
|
|
327
|
+
) -> list[str]:
|
|
328
|
+
cell_pt = cell_width_mm * sizes.scale / PT_TO_MM
|
|
329
|
+
out: list[str] = []
|
|
330
|
+
for idx, nm in enumerate(stage_names):
|
|
331
|
+
weight = "bold" if (nm in hl_set or idx in {0, n_rows - 1}) else "normal"
|
|
332
|
+
lines = measure.wrap(nm, 0.34 * cell_pt, sizes.body, weight)
|
|
333
|
+
if len(lines) > 2:
|
|
334
|
+
lines = [lines[0], " ".join(lines[1:])]
|
|
335
|
+
out.append("\n".join(lines))
|
|
336
|
+
return out
|
|
337
|
+
|
|
338
|
+
def _pitch(wrapped: list[str], tight: bool = False) -> float:
|
|
339
|
+
lines = max(nm.count("\n") + 1 for nm in wrapped)
|
|
340
|
+
if tight:
|
|
341
|
+
return 8.6 if lines == 1 else 10.2
|
|
342
|
+
return 9.6 if lines == 1 else 11.4
|
|
343
|
+
|
|
344
|
+
def _draw(ctx: _Ctx, ax: Axes) -> None:
|
|
345
|
+
sz = ctx.sizes
|
|
346
|
+
theme = ctx.theme
|
|
347
|
+
y = np.arange(n_rows, dtype=float)
|
|
348
|
+
bar_h = 0.44
|
|
349
|
+
focus_mode = bool(hl_set)
|
|
350
|
+
accent_drop = theme.accent_colors[0] if theme.accent_colors else theme.series_colors[1]
|
|
351
|
+
|
|
352
|
+
pad_r = (0.44 if has_reasons else 0.30) * max_val
|
|
353
|
+
ax.set_xlim(0.0, max_val + pad_r)
|
|
354
|
+
ax.set_ylim(n_rows - 0.55, -0.50)
|
|
355
|
+
_bare_axes(ax)
|
|
356
|
+
ax.xaxis.set_visible(False)
|
|
357
|
+
|
|
358
|
+
conn_x: list[float] = []
|
|
359
|
+
conn_y0: list[float] = []
|
|
360
|
+
conn_y1: list[float] = []
|
|
361
|
+
|
|
362
|
+
for idx, rec in enumerate(records):
|
|
363
|
+
nm = rec["name"]
|
|
364
|
+
val = vals[idx]
|
|
365
|
+
if nm in hl_set:
|
|
366
|
+
col = ctx.colors.get(nm, accent_drop)
|
|
367
|
+
alpha = 1.0
|
|
368
|
+
elif focus_mode:
|
|
369
|
+
col = theme.context_fill
|
|
370
|
+
alpha = 1.0
|
|
371
|
+
elif idx == n_rows - 1:
|
|
372
|
+
col = theme.ink
|
|
373
|
+
alpha = 0.90
|
|
374
|
+
else:
|
|
375
|
+
col = ctx.default_color
|
|
376
|
+
alpha = 0.92 if idx == 0 else 0.78
|
|
377
|
+
|
|
378
|
+
if val > 0:
|
|
379
|
+
ax.barh(
|
|
380
|
+
[idx],
|
|
381
|
+
[val],
|
|
382
|
+
height=bar_h,
|
|
383
|
+
color=col,
|
|
384
|
+
alpha=alpha,
|
|
385
|
+
edgecolor="none",
|
|
386
|
+
zorder=2,
|
|
387
|
+
)
|
|
388
|
+
|
|
389
|
+
# Value + % of initial label beside bar
|
|
390
|
+
pct_init = 100.0 * val / start_val
|
|
391
|
+
val_txt = _v(val)
|
|
392
|
+
if show_pct:
|
|
393
|
+
val_txt = f"{val_txt} ({_pct_str(pct_init)})"
|
|
394
|
+
is_bold = nm in hl_set or idx in {0, n_rows - 1}
|
|
395
|
+
ax.annotate(
|
|
396
|
+
_plain(val_txt, theme),
|
|
397
|
+
(val, idx),
|
|
398
|
+
xytext=(5.0, 0.0),
|
|
399
|
+
textcoords="offset points",
|
|
400
|
+
ha="left",
|
|
401
|
+
va="center",
|
|
402
|
+
fontsize=sz.small,
|
|
403
|
+
fontweight="bold" if is_bold else "normal",
|
|
404
|
+
color=theme.ink if (is_bold or not focus_mode) else theme.muted,
|
|
405
|
+
annotation_clip=False,
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
# Step-down connector & drop callout in the dedicated lane y = idx - 0.5
|
|
409
|
+
if idx > 0:
|
|
410
|
+
prev_v = vals[idx - 1]
|
|
411
|
+
delta = val - prev_v
|
|
412
|
+
step_pct = (100.0 * delta / prev_v) if prev_v > 0 else 0.0
|
|
413
|
+
rsn = rec["reason"]
|
|
414
|
+
anchor_x = min(val, prev_v)
|
|
415
|
+
conn_x.append(anchor_x)
|
|
416
|
+
conn_y0.append(idx - 1 + bar_h * 0.5)
|
|
417
|
+
conn_y1.append(idx - bar_h * 0.5)
|
|
418
|
+
|
|
419
|
+
if delta != 0 or rsn:
|
|
420
|
+
d_str = _diff_with_unit(_signed(val_fmt(delta)), unit)
|
|
421
|
+
p_str = _signed_pct(step_pct)
|
|
422
|
+
drop_txt = f"{d_str} ({p_str})"
|
|
423
|
+
if rsn:
|
|
424
|
+
drop_txt += f" \N{MIDDLE DOT} {rsn}"
|
|
425
|
+
is_key_drop = (nm in hl_set) or (not focus_mode and idx == biggest_drop_idx)
|
|
426
|
+
# Keep long drop reasons inside the plot area when anchor is near max_val
|
|
427
|
+
text_x = min(anchor_x, 0.72 * max_val) if rsn else anchor_x
|
|
428
|
+
ax.annotate(
|
|
429
|
+
_plain(drop_txt, theme),
|
|
430
|
+
(text_x, idx - 0.5),
|
|
431
|
+
xytext=(6.0, 0.0),
|
|
432
|
+
textcoords="offset points",
|
|
433
|
+
ha="left",
|
|
434
|
+
va="center",
|
|
435
|
+
fontsize=sz.small,
|
|
436
|
+
fontweight="bold" if is_key_drop else "normal",
|
|
437
|
+
color=ctx.text_color(accent_drop) if is_key_drop else theme.muted,
|
|
438
|
+
annotation_clip=False,
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
if conn_x:
|
|
442
|
+
ax.vlines(
|
|
443
|
+
conn_x,
|
|
444
|
+
conn_y0,
|
|
445
|
+
conn_y1,
|
|
446
|
+
color=theme.axis,
|
|
447
|
+
linewidth=0.75 * sz.scale,
|
|
448
|
+
linestyle=(0, (2, 2)),
|
|
449
|
+
zorder=1,
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
ax.vlines(
|
|
453
|
+
[0.0],
|
|
454
|
+
[-0.45],
|
|
455
|
+
[n_rows - 0.55],
|
|
456
|
+
color=theme.zero_line,
|
|
457
|
+
linewidth=theme.zero_line_lw,
|
|
458
|
+
zorder=3,
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
shown_names = _wrapped(ctx.cell_width_mm, ctx.measure, sz, theme)
|
|
462
|
+
ax.set_yticks(y, [_plain(nm, theme) for nm in shown_names])
|
|
463
|
+
ax.tick_params(axis="y", length=0, labelsize=sz.body, labelcolor=theme.ink, pad=5)
|
|
464
|
+
for tick, (idx, nm) in zip(ax.get_yticklabels(), enumerate(stage_names), strict=True):
|
|
465
|
+
tick.set_linespacing(1.05)
|
|
466
|
+
if nm in hl_set or idx in {0, n_rows - 1}:
|
|
467
|
+
tick.set_fontweight("bold")
|
|
468
|
+
elif focus_mode:
|
|
469
|
+
tick.set_color(theme.muted)
|
|
470
|
+
|
|
471
|
+
spec_stages = [
|
|
472
|
+
[r["name"], _jsonable(r["value"]), r["reason"]]
|
|
473
|
+
if r["reason"] is not None
|
|
474
|
+
else [r["name"], _jsonable(r["value"])]
|
|
475
|
+
for r in records
|
|
476
|
+
]
|
|
477
|
+
spec = _base_spec(
|
|
478
|
+
title,
|
|
479
|
+
label,
|
|
480
|
+
unit,
|
|
481
|
+
stages=spec_stages,
|
|
482
|
+
highlight=hl or None,
|
|
483
|
+
show_pct=None if show_pct else False,
|
|
484
|
+
fmt=fmt,
|
|
485
|
+
)
|
|
486
|
+
describe = (
|
|
487
|
+
f"Sequential attrition flow of {label or 'counts'}"
|
|
488
|
+
+ (f" ({unit})" if unit else "")
|
|
489
|
+
+ f" across {len(records)} stages ({stage_names[0]} to {stage_names[-1]})"
|
|
490
|
+
)
|
|
491
|
+
return Panel(
|
|
492
|
+
kind="flow",
|
|
493
|
+
title=title,
|
|
494
|
+
label=label,
|
|
495
|
+
unit=unit,
|
|
496
|
+
spec=spec,
|
|
497
|
+
facts=facts,
|
|
498
|
+
describe=describe,
|
|
499
|
+
issues=issues,
|
|
500
|
+
_height_mm=lambda w, m, s, t: n_rows * _pitch(_wrapped(w, m, s, t)) + 1.5,
|
|
501
|
+
_min_height_mm=lambda w, m, s, t: n_rows * _pitch(_wrapped(w, m, s, t), tight=True) + 1.0,
|
|
502
|
+
_draw=_draw,
|
|
503
|
+
color_items=tuple(stage_names),
|
|
504
|
+
color_focus=tuple(hl),
|
|
505
|
+
color_mode="highlight" if hl else "uniform",
|
|
506
|
+
uses_default=not hl,
|
|
507
|
+
alt_facts=facts[: min(3, len(facts))],
|
|
508
|
+
)
|