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
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
"""timeline() execution / phase span form for mint.explain.
|
|
2
|
+
|
|
3
|
+
Answers: "What ran when, how long did each stage take, and what was the bottleneck?"
|
|
4
|
+
Draws horizontal [start, end] interval bars (or milestone diamonds when start == end)
|
|
5
|
+
along a shared elapsed-time / schedule axis with direct duration labels and automatic
|
|
6
|
+
bottleneck & concurrency facts.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from collections.abc import Mapping, Sequence
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
from matplotlib.axes import Axes
|
|
16
|
+
from matplotlib.patches import Rectangle
|
|
17
|
+
from matplotlib.ticker import FuncFormatter, MaxNLocator
|
|
18
|
+
|
|
19
|
+
from .._tabular import extract_records, is_tabular
|
|
20
|
+
from ..themes import MINTFIG_THEME, Theme
|
|
21
|
+
from .core import (
|
|
22
|
+
MAX_COLORED_SERIES,
|
|
23
|
+
PT_TO_MM,
|
|
24
|
+
ExplainError,
|
|
25
|
+
Panel,
|
|
26
|
+
_bare_axes,
|
|
27
|
+
_base_spec,
|
|
28
|
+
_Ctx,
|
|
29
|
+
_formatter,
|
|
30
|
+
_guarded,
|
|
31
|
+
_is_strict,
|
|
32
|
+
_issue,
|
|
33
|
+
_jsonable,
|
|
34
|
+
_Measure,
|
|
35
|
+
_names,
|
|
36
|
+
_plain,
|
|
37
|
+
_record_adjustment,
|
|
38
|
+
_reference_line,
|
|
39
|
+
_Sizes,
|
|
40
|
+
_tick_label,
|
|
41
|
+
_to_float,
|
|
42
|
+
_with_unit,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
MAX_TIMELINE_SPANS = 20
|
|
46
|
+
COMFORTABLE_TIMELINE_SPANS = 12
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _normalize_spans(
|
|
50
|
+
spans: object,
|
|
51
|
+
*,
|
|
52
|
+
name: str | None = None,
|
|
53
|
+
start: str | None = None,
|
|
54
|
+
end: str | None = None,
|
|
55
|
+
group: str | None = None,
|
|
56
|
+
) -> list[dict[str, Any]]:
|
|
57
|
+
"""Normalize dict, tuple-list, or tidy rows into ``[{"name", "start", "end", "group"}]``."""
|
|
58
|
+
if is_tabular(spans):
|
|
59
|
+
cols, rows = extract_records(spans, what="timeline(spans)")
|
|
60
|
+
if not rows:
|
|
61
|
+
raise ExplainError("timeline(spans) is empty.", fix_hint="Pass at least one span.")
|
|
62
|
+
lower_map = {c.lower(): c for c in cols}
|
|
63
|
+
n_col = name or next((lower_map[k] for k in ("name", "stage", "task", "step", "label") if k in lower_map), None)
|
|
64
|
+
s_col = start or next((lower_map[k] for k in ("start", "t_start", "begin", "from") if k in lower_map), None)
|
|
65
|
+
e_col = end or next((lower_map[k] for k in ("end", "t_end", "finish", "stop", "to") if k in lower_map), None)
|
|
66
|
+
if not (n_col and s_col and e_col):
|
|
67
|
+
shown = ", ".join(repr(c) for c in cols[:8])
|
|
68
|
+
raise ExplainError(
|
|
69
|
+
f"timeline() needs name=, start=, and end= columns for row-shaped data (columns: {shown}).",
|
|
70
|
+
fix_hint='Pass timeline(rows, name="stage", start="start_s", end="end_s").',
|
|
71
|
+
)
|
|
72
|
+
for col, arg in ((n_col, "name"), (s_col, "start"), (e_col, "end")):
|
|
73
|
+
if col not in cols:
|
|
74
|
+
raise ExplainError(
|
|
75
|
+
f"timeline({arg}={col!r}) column not found.",
|
|
76
|
+
fix_hint=f"Available columns: {', '.join(map(repr, cols[:10]))}.",
|
|
77
|
+
)
|
|
78
|
+
if group is not None and group not in cols:
|
|
79
|
+
raise ExplainError(
|
|
80
|
+
f"timeline(group={group!r}) column not found.",
|
|
81
|
+
fix_hint=f"Available columns: {', '.join(map(repr, cols[:10]))}.",
|
|
82
|
+
)
|
|
83
|
+
out: list[dict[str, Any]] = []
|
|
84
|
+
for row in rows:
|
|
85
|
+
nm = str(row.get(n_col, "")).strip()
|
|
86
|
+
s_val = _to_float(row.get(s_col), f"timeline(start[{nm!r}])")
|
|
87
|
+
e_val = _to_float(row.get(e_col), f"timeline(end[{nm!r}])")
|
|
88
|
+
g_val = str(row[group]) if (group is not None and row.get(group) is not None) else None
|
|
89
|
+
out.append({"name": nm, "start": s_val, "end": e_val, "group": g_val})
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
if any(a is not None for a in (name, start, end, group)):
|
|
93
|
+
raise ExplainError(
|
|
94
|
+
"timeline(name=/start=/end=/group=) require row-shaped data (list of dicts or DataFrame).",
|
|
95
|
+
fix_hint='Pass rows=[{"stage": "build", "start": 0, "end": 45}, ...] or drop column args.',
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
if isinstance(spans, Mapping):
|
|
99
|
+
if not spans:
|
|
100
|
+
raise ExplainError("timeline(spans) is empty.", fix_hint="Pass at least one span.")
|
|
101
|
+
out = []
|
|
102
|
+
for raw_nm, bounds in spans.items():
|
|
103
|
+
nm = str(raw_nm)
|
|
104
|
+
if (
|
|
105
|
+
isinstance(bounds, (str, bytes))
|
|
106
|
+
or not isinstance(bounds, Sequence)
|
|
107
|
+
or len(bounds) not in {2, 3}
|
|
108
|
+
):
|
|
109
|
+
raise ExplainError(
|
|
110
|
+
f"timeline(spans[{nm!r}]) must be (start, end) or (start, end, group).",
|
|
111
|
+
fix_hint='e.g. {"build": (0, 45), "test": (45, 110)}.',
|
|
112
|
+
)
|
|
113
|
+
s_val = _to_float(bounds[0], f"timeline(spans[{nm!r}][0])")
|
|
114
|
+
e_val = _to_float(bounds[1], f"timeline(spans[{nm!r}][1])")
|
|
115
|
+
g_val = str(bounds[2]) if len(bounds) == 3 and bounds[2] is not None else None
|
|
116
|
+
out.append({"name": nm, "start": s_val, "end": e_val, "group": g_val})
|
|
117
|
+
return out
|
|
118
|
+
|
|
119
|
+
if isinstance(spans, Sequence) and not isinstance(spans, (str, bytes)):
|
|
120
|
+
if not spans:
|
|
121
|
+
raise ExplainError("timeline(spans) is empty.", fix_hint="Pass at least one span.")
|
|
122
|
+
out = []
|
|
123
|
+
for idx, item in enumerate(spans):
|
|
124
|
+
if (
|
|
125
|
+
isinstance(item, (str, bytes))
|
|
126
|
+
or not isinstance(item, Sequence)
|
|
127
|
+
or len(item) not in {3, 4}
|
|
128
|
+
):
|
|
129
|
+
raise ExplainError(
|
|
130
|
+
f"timeline(spans[{idx}]) must be (name, start, end) or (name, start, end, group).",
|
|
131
|
+
fix_hint='Pass [("build", 0, 45), ("test", 45, 110)] or a dict {name: (start, end)}.',
|
|
132
|
+
)
|
|
133
|
+
nm = str(item[0])
|
|
134
|
+
s_val = _to_float(item[1], f"timeline(spans[{nm!r}].start)")
|
|
135
|
+
e_val = _to_float(item[2], f"timeline(spans[{nm!r}].end)")
|
|
136
|
+
g_val = str(item[3]) if len(item) == 4 and item[3] is not None else None
|
|
137
|
+
out.append({"name": nm, "start": s_val, "end": e_val, "group": g_val})
|
|
138
|
+
return out
|
|
139
|
+
|
|
140
|
+
raise ExplainError(
|
|
141
|
+
f"timeline(spans) expected a dict, list of (name, start, end) tuples, or rows; got {type(spans).__name__}.",
|
|
142
|
+
fix_hint='e.g. mint.timeline({"checkout": (0, 12), "build": (12, 142)}).',
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _max_concurrency(records: Sequence[Mapping[str, Any]]) -> int:
|
|
147
|
+
"""Compute peak number of overlapping positive-duration spans."""
|
|
148
|
+
events: list[tuple[float, int]] = []
|
|
149
|
+
for rec in records:
|
|
150
|
+
if rec["end"] > rec["start"]:
|
|
151
|
+
events.append((float(rec["start"]), 1))
|
|
152
|
+
events.append((float(rec["end"]), -1))
|
|
153
|
+
# Process end (-1) before start (+1) at identical timestamps (back-to-back is not concurrent)
|
|
154
|
+
events.sort(key=lambda pair: (pair[0], pair[1]))
|
|
155
|
+
cur = peak = 0
|
|
156
|
+
for _t, delta in events:
|
|
157
|
+
cur += delta
|
|
158
|
+
peak = max(peak, cur)
|
|
159
|
+
return peak
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
@_guarded("timeline")
|
|
163
|
+
def timeline(
|
|
164
|
+
spans: (
|
|
165
|
+
Mapping[str, tuple[float, float]]
|
|
166
|
+
| Sequence[tuple[str, float, float]]
|
|
167
|
+
| Sequence[Mapping[str, Any]]
|
|
168
|
+
),
|
|
169
|
+
*,
|
|
170
|
+
name: str | None = None,
|
|
171
|
+
start: str | None = None,
|
|
172
|
+
end: str | None = None,
|
|
173
|
+
group: str | None = None,
|
|
174
|
+
title: str | None = None,
|
|
175
|
+
label: str | None = None,
|
|
176
|
+
unit: str | None = None,
|
|
177
|
+
x_label: str | None = None,
|
|
178
|
+
highlight: str | Sequence[str] | None = None,
|
|
179
|
+
reference: float | tuple[float, str] | None = None,
|
|
180
|
+
sort: bool = True,
|
|
181
|
+
fmt: str | None = None,
|
|
182
|
+
) -> Panel:
|
|
183
|
+
"""What ran when, how long did each stage take, and what was the bottleneck?
|
|
184
|
+
|
|
185
|
+
``spans`` accepts ``{stage: (start, end)}`` (or ``(start, end, group)``),
|
|
186
|
+
``[(stage, start, end), ...]``, or row-shaped data / DataFrame with
|
|
187
|
+
``name=``, ``start=``, ``end=`` (and optional ``group=`` for lane colour).
|
|
188
|
+
"""
|
|
189
|
+
records = _normalize_spans(spans, name=name, start=start, end=end, group=group)
|
|
190
|
+
for rec in records:
|
|
191
|
+
if rec["end"] < rec["start"]:
|
|
192
|
+
raise ExplainError(
|
|
193
|
+
f"timeline() span {rec['name']!r} ends ({rec['end']}) before it starts ({rec['start']}).",
|
|
194
|
+
fix_hint="Ensure end >= start for every span (equal values render as a milestone).",
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
if sort:
|
|
198
|
+
records.sort(
|
|
199
|
+
key=lambda r: (
|
|
200
|
+
r["start"],
|
|
201
|
+
0 if r["end"] == r["start"] else 1,
|
|
202
|
+
-(r["end"] - r["start"]),
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
if len(records) > MAX_TIMELINE_SPANS:
|
|
207
|
+
if not _is_strict():
|
|
208
|
+
req_hl = (
|
|
209
|
+
[highlight]
|
|
210
|
+
if isinstance(highlight, str)
|
|
211
|
+
else ([str(h) for h in highlight] if highlight is not None else [])
|
|
212
|
+
)
|
|
213
|
+
hl_req_set = set(req_hl)
|
|
214
|
+
must = [i for i, r in enumerate(records) if r["name"] in hl_req_set]
|
|
215
|
+
by_dur = sorted(
|
|
216
|
+
range(len(records)),
|
|
217
|
+
key=lambda i: records[i]["end"] - records[i]["start"],
|
|
218
|
+
reverse=True,
|
|
219
|
+
)
|
|
220
|
+
chosen = list(dict.fromkeys(must))
|
|
221
|
+
for idx in by_dur:
|
|
222
|
+
if len(chosen) >= MAX_TIMELINE_SPANS:
|
|
223
|
+
break
|
|
224
|
+
if idx not in chosen:
|
|
225
|
+
chosen.append(idx)
|
|
226
|
+
chosen.sort()
|
|
227
|
+
orig_n = len(records)
|
|
228
|
+
records = [records[i] for i in chosen]
|
|
229
|
+
_record_adjustment(f"timeline(): trimmed {orig_n} spans to {len(records)}")
|
|
230
|
+
else:
|
|
231
|
+
raise ExplainError(
|
|
232
|
+
f"timeline() got {len(records)} spans; beyond {MAX_TIMELINE_SPANS} a timeline is cramped.",
|
|
233
|
+
fix_hint=f"Keep at most {MAX_TIMELINE_SPANS} spans or aggregate sub-steps into phases.",
|
|
234
|
+
rule="too_many_items",
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
names_list = [r["name"] for r in records]
|
|
238
|
+
group_names = list(dict.fromkeys(r["group"] for r in records if r["group"] is not None))
|
|
239
|
+
if len(group_names) > MAX_COLORED_SERIES:
|
|
240
|
+
if not _is_strict():
|
|
241
|
+
kept_g = set(group_names[:MAX_COLORED_SERIES])
|
|
242
|
+
for r in records:
|
|
243
|
+
if r["group"] not in kept_g:
|
|
244
|
+
r["group"] = None
|
|
245
|
+
group_names = group_names[:MAX_COLORED_SERIES]
|
|
246
|
+
_record_adjustment(f"timeline(): limited coloured groups to {MAX_COLORED_SERIES}")
|
|
247
|
+
else:
|
|
248
|
+
raise ExplainError(
|
|
249
|
+
f"timeline() has {len(group_names)} groups; at most {MAX_COLORED_SERIES} group colours are legible.",
|
|
250
|
+
fix_hint=f"Merge into at most {MAX_COLORED_SERIES} groups, or drop group= and use highlight=.",
|
|
251
|
+
rule="too_many_series",
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
# highlight may name stages OR groups
|
|
255
|
+
hl_stages: list[str] = []
|
|
256
|
+
hl_groups: list[str] = []
|
|
257
|
+
if highlight is not None:
|
|
258
|
+
wanted = [highlight] if isinstance(highlight, str) else [str(h) for h in highlight]
|
|
259
|
+
if group_names and all(w in group_names for w in wanted):
|
|
260
|
+
hl_groups = _names(wanted, group_names, "timeline(highlight)")
|
|
261
|
+
else:
|
|
262
|
+
hl_stages = _names(wanted, names_list, "timeline(highlight)")
|
|
263
|
+
|
|
264
|
+
ref = _reference_line(reference, "timeline(reference)")
|
|
265
|
+
|
|
266
|
+
issues: list[dict[str, Any]] = []
|
|
267
|
+
if len(records) > COMFORTABLE_TIMELINE_SPANS:
|
|
268
|
+
issues.append(
|
|
269
|
+
_issue(
|
|
270
|
+
"many_items",
|
|
271
|
+
"warning",
|
|
272
|
+
f"{len(records)} spans is dense for one timeline.",
|
|
273
|
+
"Group minor steps into broader phases if the detail is not needed.",
|
|
274
|
+
)
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
t_min = min(r["start"] for r in records)
|
|
278
|
+
t_max = max(r["end"] for r in records)
|
|
279
|
+
wall = t_max - t_min
|
|
280
|
+
durations = [r["end"] - r["start"] for r in records]
|
|
281
|
+
total_work = sum(durations)
|
|
282
|
+
peak_conc = _max_concurrency(records)
|
|
283
|
+
|
|
284
|
+
dur_fmt = _formatter([*durations, wall, t_min, t_max], fmt, unit=unit)
|
|
285
|
+
|
|
286
|
+
def _u(v: float) -> str:
|
|
287
|
+
return _with_unit(dur_fmt(v), unit)
|
|
288
|
+
|
|
289
|
+
longest_idx = int(np.argmax(durations))
|
|
290
|
+
longest = records[longest_idx]
|
|
291
|
+
longest_dur = durations[longest_idx]
|
|
292
|
+
longest_pct = (100.0 * longest_dur / wall) if wall > 0 else 0.0
|
|
293
|
+
|
|
294
|
+
facts: list[str] = [
|
|
295
|
+
f"wall span: {_u(t_min)} to {_u(t_max)} ({_u(wall)} total across {len(records)} stages)",
|
|
296
|
+
(
|
|
297
|
+
f"longest stage: {longest['name']} ({_u(longest_dur)}, {longest_pct:.0f}% of wall span, "
|
|
298
|
+
f"{_u(longest['start'])} to {_u(longest['end'])})"
|
|
299
|
+
),
|
|
300
|
+
]
|
|
301
|
+
if peak_conc > 1 and wall > 0:
|
|
302
|
+
facts.append(
|
|
303
|
+
f"sum of stage durations: {_u(total_work)} ({total_work / wall:.2g}\N{MULTIPLICATION SIGN} "
|
|
304
|
+
f"wall span; peak {peak_conc} stages overlapping)"
|
|
305
|
+
)
|
|
306
|
+
else:
|
|
307
|
+
facts.append(f"sequential execution: sum of stage durations {_u(total_work)}")
|
|
308
|
+
|
|
309
|
+
for nm in hl_stages:
|
|
310
|
+
rec = next(r for r in records if r["name"] == nm)
|
|
311
|
+
d = rec["end"] - rec["start"]
|
|
312
|
+
pct = (100.0 * d / wall) if wall > 0 else 0.0
|
|
313
|
+
facts.append(f"{nm}: {_u(d)} ({pct:.0f}% of wall span, {_u(rec['start'])} to {_u(rec['end'])})")
|
|
314
|
+
if ref is not None:
|
|
315
|
+
diff = t_max - ref[0]
|
|
316
|
+
ref_nm = f" ({ref[1]})" if ref[1] else ""
|
|
317
|
+
if diff > 0:
|
|
318
|
+
facts.append(f"end {_u(t_max)} exceeds reference {_u(ref[0])}{ref_nm} by {_u(diff)}")
|
|
319
|
+
else:
|
|
320
|
+
facts.append(f"end {_u(t_max)} finishes {_u(abs(diff))} under reference {_u(ref[0])}{ref_nm}")
|
|
321
|
+
|
|
322
|
+
n_rows = len(records)
|
|
323
|
+
hl_stage_set = set(hl_stages)
|
|
324
|
+
hl_group_set = set(hl_groups)
|
|
325
|
+
focus_mode = bool(hl_stage_set or hl_group_set)
|
|
326
|
+
show_group_key = bool(group_names) and not bool(hl_stage_set)
|
|
327
|
+
effective_x_label = x_label or (f"Elapsed ({unit})" if unit else "Timeline")
|
|
328
|
+
|
|
329
|
+
def _wrapped(
|
|
330
|
+
cell_width_mm: float,
|
|
331
|
+
measure: _Measure,
|
|
332
|
+
sizes: _Sizes,
|
|
333
|
+
theme: Theme = MINTFIG_THEME,
|
|
334
|
+
) -> list[str]:
|
|
335
|
+
cell_pt = cell_width_mm * sizes.scale / PT_TO_MM
|
|
336
|
+
out: list[str] = []
|
|
337
|
+
for nm in names_list:
|
|
338
|
+
weight = "bold" if nm in hl_stage_set else "normal"
|
|
339
|
+
lines = measure.wrap(nm, 0.36 * cell_pt, sizes.body, weight)
|
|
340
|
+
if len(lines) > 2:
|
|
341
|
+
lines = [lines[0], " ".join(lines[1:])]
|
|
342
|
+
out.append("\n".join(lines))
|
|
343
|
+
return out
|
|
344
|
+
|
|
345
|
+
def _pitch(wrapped: list[str], tight: bool = False) -> float:
|
|
346
|
+
lines = max(nm.count("\n") + 1 for nm in wrapped)
|
|
347
|
+
if tight:
|
|
348
|
+
return {1: 4.7, 2: 7.2}.get(lines, 9.5)
|
|
349
|
+
return {1: 5.4, 2: 8.2}.get(lines, 10.5)
|
|
350
|
+
|
|
351
|
+
def _draw(ctx: _Ctx, ax: Axes) -> None:
|
|
352
|
+
sz = ctx.sizes
|
|
353
|
+
theme = ctx.theme
|
|
354
|
+
y = np.arange(n_rows, dtype=float)
|
|
355
|
+
bar_h = min(theme.bar_height, 0.62)
|
|
356
|
+
|
|
357
|
+
group_color: dict[str, str] = {}
|
|
358
|
+
for idx, g in enumerate(group_names):
|
|
359
|
+
if hl_group_set:
|
|
360
|
+
group_color[g] = (
|
|
361
|
+
ctx.colors.get(g, theme.accent_colors[hl_groups.index(g) % len(theme.accent_colors)])
|
|
362
|
+
if g in hl_group_set
|
|
363
|
+
else theme.context_fill
|
|
364
|
+
)
|
|
365
|
+
else:
|
|
366
|
+
group_color[g] = ctx.colors.get(g, theme.series_colors[idx % len(theme.series_colors)])
|
|
367
|
+
|
|
368
|
+
def _bar_color(rec: Mapping[str, Any]) -> str:
|
|
369
|
+
nm = rec["name"]
|
|
370
|
+
g = rec["group"]
|
|
371
|
+
if nm in hl_stage_set:
|
|
372
|
+
return ctx.colors.get(nm, theme.accent_colors[hl_stages.index(nm) % len(theme.accent_colors)])
|
|
373
|
+
if hl_stage_set:
|
|
374
|
+
return theme.context_fill
|
|
375
|
+
if g is not None:
|
|
376
|
+
return group_color[g]
|
|
377
|
+
return ctx.colors.get(nm, ctx.default_color)
|
|
378
|
+
|
|
379
|
+
lo = float(min(t_min, ref[0] if ref else t_min))
|
|
380
|
+
hi = float(max(t_max, ref[0] if ref else t_max))
|
|
381
|
+
span_x = (hi - lo) or abs(hi) or 1.0
|
|
382
|
+
ax.set_xlim(lo - 0.02 * span_x, hi + 0.20 * span_x)
|
|
383
|
+
top_y = -1.35 if show_group_key else -0.55
|
|
384
|
+
ax.set_ylim(n_rows - 0.45, top_y)
|
|
385
|
+
|
|
386
|
+
_bare_axes(ax)
|
|
387
|
+
ax.spines["bottom"].set_visible(True)
|
|
388
|
+
ax.spines["bottom"].set_color(theme.axis)
|
|
389
|
+
ax.spines["bottom"].set_linewidth(theme.axis_lw)
|
|
390
|
+
minus = theme.minus_sign
|
|
391
|
+
ax.xaxis.set_major_locator(MaxNLocator(nbins=5, steps=[1, 2, 2.5, 5, 10]))
|
|
392
|
+
ax.xaxis.set_major_formatter(
|
|
393
|
+
FuncFormatter(lambda v, _p, m=minus, a=ax.xaxis: _tick_label(v, m, a))
|
|
394
|
+
)
|
|
395
|
+
ax.tick_params(
|
|
396
|
+
axis="x",
|
|
397
|
+
length=theme.tick_length,
|
|
398
|
+
width=theme.tick_width,
|
|
399
|
+
color=theme.axis,
|
|
400
|
+
labelsize=sz.small,
|
|
401
|
+
labelcolor=theme.muted,
|
|
402
|
+
)
|
|
403
|
+
ax.set_xlabel(_plain(effective_x_label, theme), fontsize=sz.small, color=theme.muted, labelpad=3)
|
|
404
|
+
if theme.grid_style != "none" and theme.grid_lw > 0:
|
|
405
|
+
ax.grid(axis="x", color=theme.grid, linestyle=theme.grid_style, linewidth=theme.grid_lw)
|
|
406
|
+
ax.set_axisbelow(True)
|
|
407
|
+
|
|
408
|
+
value_notes: list[tuple[Any, float]] = []
|
|
409
|
+
for idx, rec in enumerate(records):
|
|
410
|
+
s_v = float(rec["start"])
|
|
411
|
+
e_v = float(rec["end"])
|
|
412
|
+
dur = e_v - s_v
|
|
413
|
+
col = _bar_color(rec)
|
|
414
|
+
is_focus = (
|
|
415
|
+
(rec["name"] in hl_stage_set)
|
|
416
|
+
or (rec["group"] in hl_group_set)
|
|
417
|
+
or not focus_mode
|
|
418
|
+
)
|
|
419
|
+
if dur <= 1e-12:
|
|
420
|
+
ax.scatter(
|
|
421
|
+
[s_v],
|
|
422
|
+
[idx],
|
|
423
|
+
marker="D",
|
|
424
|
+
s=(4.8 * sz.scale) ** 2,
|
|
425
|
+
color=col,
|
|
426
|
+
edgecolor=theme.background,
|
|
427
|
+
linewidth=0.6,
|
|
428
|
+
zorder=4,
|
|
429
|
+
)
|
|
430
|
+
d_txt = "milestone"
|
|
431
|
+
else:
|
|
432
|
+
ax.barh(
|
|
433
|
+
[idx],
|
|
434
|
+
[dur],
|
|
435
|
+
left=[s_v],
|
|
436
|
+
height=bar_h,
|
|
437
|
+
color=col,
|
|
438
|
+
edgecolor="none",
|
|
439
|
+
zorder=3 if is_focus else 2,
|
|
440
|
+
)
|
|
441
|
+
d_txt = _u(dur)
|
|
442
|
+
|
|
443
|
+
note = ax.annotate(
|
|
444
|
+
_plain(d_txt, theme),
|
|
445
|
+
(e_v, idx),
|
|
446
|
+
xytext=(5.0, 0.0),
|
|
447
|
+
textcoords="offset points",
|
|
448
|
+
ha="left",
|
|
449
|
+
va="center",
|
|
450
|
+
fontsize=sz.small,
|
|
451
|
+
fontweight="bold" if (rec["name"] in hl_stage_set or rec["group"] in hl_group_set) else "normal",
|
|
452
|
+
color=theme.ink if is_focus else theme.muted,
|
|
453
|
+
annotation_clip=False,
|
|
454
|
+
)
|
|
455
|
+
value_notes.append((note, s_v))
|
|
456
|
+
|
|
457
|
+
if ref is not None:
|
|
458
|
+
ax.axvline(
|
|
459
|
+
ref[0],
|
|
460
|
+
color=theme.ink,
|
|
461
|
+
linewidth=0.75,
|
|
462
|
+
linestyle=(0, (3, 2)),
|
|
463
|
+
zorder=4,
|
|
464
|
+
)
|
|
465
|
+
if ref[1]:
|
|
466
|
+
ax.annotate(
|
|
467
|
+
_plain(ref[1], theme),
|
|
468
|
+
(ref[0], 1.0),
|
|
469
|
+
xycoords=("data", "axes fraction"),
|
|
470
|
+
xytext=(0.0, 2.5),
|
|
471
|
+
textcoords="offset points",
|
|
472
|
+
ha="center",
|
|
473
|
+
va="bottom",
|
|
474
|
+
fontsize=sz.small,
|
|
475
|
+
color=theme.muted,
|
|
476
|
+
annotation_clip=False,
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# Frameless inline group colour key strip when colour encodes groups
|
|
480
|
+
if show_group_key:
|
|
481
|
+
key_y = top_y + 0.45
|
|
482
|
+
cell_w_pt = max(ctx.cell_width_mm * 0.65 / PT_TO_MM, 80.0)
|
|
483
|
+
cursor_frac = 0.0
|
|
484
|
+
swatch_w = 0.024
|
|
485
|
+
gap_frac = 0.045
|
|
486
|
+
for g in group_names:
|
|
487
|
+
g_focus = (not hl_group_set) or (g in hl_group_set)
|
|
488
|
+
wgt = "bold" if g in hl_group_set else "normal"
|
|
489
|
+
lbl_w_pt = ctx.measure.width_pt(_plain(g, theme), sz.small, wgt)
|
|
490
|
+
ax.add_patch(
|
|
491
|
+
Rectangle(
|
|
492
|
+
(cursor_frac, key_y - 0.22),
|
|
493
|
+
swatch_w,
|
|
494
|
+
0.44,
|
|
495
|
+
transform=ax.get_yaxis_transform(),
|
|
496
|
+
facecolor=group_color[g],
|
|
497
|
+
edgecolor="none",
|
|
498
|
+
zorder=5,
|
|
499
|
+
clip_on=False,
|
|
500
|
+
)
|
|
501
|
+
)
|
|
502
|
+
ax.text(
|
|
503
|
+
cursor_frac + swatch_w + 0.012,
|
|
504
|
+
key_y,
|
|
505
|
+
_plain(g, theme),
|
|
506
|
+
transform=ax.get_yaxis_transform(),
|
|
507
|
+
ha="left",
|
|
508
|
+
va="center",
|
|
509
|
+
fontsize=sz.small,
|
|
510
|
+
fontweight=wgt,
|
|
511
|
+
color=theme.ink if g_focus else theme.muted,
|
|
512
|
+
zorder=5,
|
|
513
|
+
clip_on=False,
|
|
514
|
+
)
|
|
515
|
+
cursor_frac += swatch_w + 0.012 + (lbl_w_pt / cell_w_pt) + gap_frac
|
|
516
|
+
|
|
517
|
+
shown_names = _wrapped(ctx.cell_width_mm, ctx.measure, sz, theme)
|
|
518
|
+
ax.set_yticks(y, [_plain(nm, theme) for nm in shown_names])
|
|
519
|
+
ax.tick_params(axis="y", length=0, labelsize=sz.body, labelcolor=theme.ink, pad=5)
|
|
520
|
+
for tick, rec in zip(ax.get_yticklabels(), records, strict=True):
|
|
521
|
+
tick.set_linespacing(1.05)
|
|
522
|
+
if rec["name"] in hl_stage_set:
|
|
523
|
+
tick.set_fontweight("bold")
|
|
524
|
+
elif focus_mode and rec["group"] not in hl_group_set:
|
|
525
|
+
tick.set_color(theme.muted)
|
|
526
|
+
|
|
527
|
+
if ref is None:
|
|
528
|
+
return None
|
|
529
|
+
ref_x = ref[0]
|
|
530
|
+
|
|
531
|
+
def _clear_reference() -> None:
|
|
532
|
+
renderer = ctx.fig.canvas.get_renderer()
|
|
533
|
+
k = ctx.pt_per_px
|
|
534
|
+
cell = ax.get_tightbbox(renderer)
|
|
535
|
+
frame = ax.get_window_extent(renderer)
|
|
536
|
+
right_limit = max(frame.x1, cell.x1 if cell is not None else frame.x1)
|
|
537
|
+
line_px = float(ax.transData.transform((ref_x, 0.0))[0])
|
|
538
|
+
gap = 3.0 / k
|
|
539
|
+
for note, left_anchor in value_notes:
|
|
540
|
+
box = note.get_window_extent(renderer)
|
|
541
|
+
if not (box.x0 - 1 <= line_px <= box.x1 + 1):
|
|
542
|
+
continue
|
|
543
|
+
dx, dy = note.xyann
|
|
544
|
+
shift = (line_px + gap - box.x0) * k
|
|
545
|
+
note.set_position((dx + shift, dy))
|
|
546
|
+
moved = note.get_window_extent(renderer)
|
|
547
|
+
if moved.x1 <= right_limit + 1:
|
|
548
|
+
continue
|
|
549
|
+
note.xy = (left_anchor, note.xy[1])
|
|
550
|
+
note.set_horizontalalignment("right")
|
|
551
|
+
note.set_position((-5.0, dy))
|
|
552
|
+
|
|
553
|
+
return _clear_reference
|
|
554
|
+
|
|
555
|
+
spec_spans = [
|
|
556
|
+
[r["name"], _jsonable(r["start"]), _jsonable(r["end"]), r["group"]]
|
|
557
|
+
if r["group"] is not None
|
|
558
|
+
else [r["name"], _jsonable(r["start"]), _jsonable(r["end"])]
|
|
559
|
+
for r in records
|
|
560
|
+
]
|
|
561
|
+
spec = _base_spec(
|
|
562
|
+
title,
|
|
563
|
+
label,
|
|
564
|
+
unit,
|
|
565
|
+
spans=spec_spans,
|
|
566
|
+
x_label=x_label,
|
|
567
|
+
highlight=(hl_groups or hl_stages) or None,
|
|
568
|
+
reference=list(ref) if ref else None,
|
|
569
|
+
sort=sort if not sort else None,
|
|
570
|
+
fmt=fmt,
|
|
571
|
+
)
|
|
572
|
+
describe = (
|
|
573
|
+
f"Timeline of {len(records)} stages"
|
|
574
|
+
+ (f" ({label})" if label else "")
|
|
575
|
+
+ f" spanning {_u(t_min)} to {_u(t_max)}"
|
|
576
|
+
)
|
|
577
|
+
extra_mm = (7.0 if show_group_key else 1.0) + 9.0 + (4.0 if ref and ref[1] else 0.0)
|
|
578
|
+
return Panel(
|
|
579
|
+
kind="timeline",
|
|
580
|
+
title=title,
|
|
581
|
+
label=label,
|
|
582
|
+
unit=unit if label else None,
|
|
583
|
+
spec=spec,
|
|
584
|
+
facts=facts,
|
|
585
|
+
describe=describe,
|
|
586
|
+
issues=issues,
|
|
587
|
+
_height_mm=lambda w, m, s, t: n_rows * _pitch(_wrapped(w, m, s, t)) + extra_mm,
|
|
588
|
+
_min_height_mm=lambda w, m, s, t: n_rows * _pitch(_wrapped(w, m, s, t), tight=True) + extra_mm * 0.85,
|
|
589
|
+
_draw=_draw,
|
|
590
|
+
color_items=tuple(dict.fromkeys([*group_names, *names_list])),
|
|
591
|
+
color_focus=tuple(hl_groups or hl_stages or group_names),
|
|
592
|
+
color_mode="highlight" if (hl_groups or hl_stages) else ("series" if group_names else "uniform"),
|
|
593
|
+
uses_default=not group_names and not hl_stages,
|
|
594
|
+
alt_facts=facts[: min(3, len(facts))],
|
|
595
|
+
)
|