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/preflight.py
ADDED
|
@@ -0,0 +1,2398 @@
|
|
|
1
|
+
"""Automated preflight compliance linter for Matplotlib figures and exported PDFs."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import re
|
|
7
|
+
import warnings
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
import matplotlib.pyplot as plt
|
|
13
|
+
import numpy as np
|
|
14
|
+
from matplotlib import font_manager
|
|
15
|
+
from matplotlib.backends.backend_agg import FigureCanvasAgg
|
|
16
|
+
from matplotlib.cm import ScalarMappable
|
|
17
|
+
from matplotlib.collections import Collection, LineCollection, PolyCollection
|
|
18
|
+
from matplotlib.colors import to_hex, to_rgb, to_rgba
|
|
19
|
+
from matplotlib.container import BarContainer
|
|
20
|
+
from matplotlib.figure import Figure
|
|
21
|
+
from matplotlib.lines import Line2D
|
|
22
|
+
from matplotlib.spines import Spine
|
|
23
|
+
from matplotlib.text import Text
|
|
24
|
+
from pypdf import PdfReader
|
|
25
|
+
|
|
26
|
+
from .palettes import BANNED_COLORMAPS, simulate_cvd
|
|
27
|
+
from .specs import MM_PER_INCH, JournalSpec, get_spec, in_to_mm
|
|
28
|
+
|
|
29
|
+
CheckStatus = Literal["pass", "warn", "fail"]
|
|
30
|
+
CheckSeverity = Literal["ok", "warning", "error"]
|
|
31
|
+
|
|
32
|
+
_SERIF_SUBSTRINGS = (
|
|
33
|
+
"times",
|
|
34
|
+
"georgia",
|
|
35
|
+
"palatino",
|
|
36
|
+
"garamond",
|
|
37
|
+
"cambria",
|
|
38
|
+
"baskerville",
|
|
39
|
+
"bookman",
|
|
40
|
+
"charter",
|
|
41
|
+
"century",
|
|
42
|
+
"minion",
|
|
43
|
+
"caslon",
|
|
44
|
+
"hoefler",
|
|
45
|
+
"didot",
|
|
46
|
+
"bodoni",
|
|
47
|
+
"computer modern",
|
|
48
|
+
"stixgeneral",
|
|
49
|
+
"dejavuserif",
|
|
50
|
+
"liberationserif",
|
|
51
|
+
"notoserif",
|
|
52
|
+
"sourceserif",
|
|
53
|
+
"ptserif",
|
|
54
|
+
"nimbusrom",
|
|
55
|
+
"urwbookman",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
_SERIF_TOKEN_RE = re.compile(
|
|
59
|
+
r"(?:^|[^a-z])(cmr|cmmi|cmsy|cmex|cmti|cmbx|cmsl|cmtt|stix|serif)(?:[^a-z]|$)",
|
|
60
|
+
re.IGNORECASE,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
_CANONICAL_WIDTH_PRIORITY = ("single", "mid", "double", "full", "1.5col", "2col", "3col")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class CheckResult:
|
|
68
|
+
"""Result of a single preflight compliance check."""
|
|
69
|
+
|
|
70
|
+
rule: str
|
|
71
|
+
status: CheckStatus
|
|
72
|
+
message: str
|
|
73
|
+
details: dict[str, Any] = field(default_factory=dict)
|
|
74
|
+
panel: str | None = None
|
|
75
|
+
elements: list[str] = field(default_factory=list)
|
|
76
|
+
fix_hint: str | None = None
|
|
77
|
+
panels: list[str] = field(default_factory=list)
|
|
78
|
+
element_locations: list[dict[str, str | None]] = field(default_factory=list)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def severity(self) -> CheckSeverity:
|
|
82
|
+
"""Return v0.2 severity level ('error', 'warning', or 'ok')."""
|
|
83
|
+
if self.status == "fail":
|
|
84
|
+
return "error"
|
|
85
|
+
if self.status == "warn":
|
|
86
|
+
return "warning"
|
|
87
|
+
return "ok"
|
|
88
|
+
|
|
89
|
+
def to_dict(self) -> dict[str, Any]:
|
|
90
|
+
"""Return a JSON-serializable dictionary representation."""
|
|
91
|
+
return {
|
|
92
|
+
"rule": self.rule,
|
|
93
|
+
"status": self.status,
|
|
94
|
+
"severity": self.severity,
|
|
95
|
+
"panel": self.panel,
|
|
96
|
+
"panels": list(self.panels),
|
|
97
|
+
"elements": list(self.elements),
|
|
98
|
+
"element_locations": [dict(loc) for loc in self.element_locations],
|
|
99
|
+
"message": self.message,
|
|
100
|
+
"fix_hint": self.fix_hint,
|
|
101
|
+
"details": self.details,
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def to_issue_dict(self) -> dict[str, Any]:
|
|
105
|
+
"""Return the concise v0.2 agent issue payload for non-passing checks."""
|
|
106
|
+
return {
|
|
107
|
+
"rule": self.rule,
|
|
108
|
+
"severity": self.severity,
|
|
109
|
+
"panel": self.panel,
|
|
110
|
+
"panels": list(self.panels),
|
|
111
|
+
"elements": list(self.elements),
|
|
112
|
+
"element_locations": [dict(loc) for loc in self.element_locations],
|
|
113
|
+
"message": self.message,
|
|
114
|
+
"fix_hint": self.fix_hint,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class PreflightReport:
|
|
120
|
+
"""Aggregated compliance report for a figure or PDF against a journal spec."""
|
|
121
|
+
|
|
122
|
+
journal: str
|
|
123
|
+
checks: list[CheckResult]
|
|
124
|
+
width_mm: float
|
|
125
|
+
height_mm: float
|
|
126
|
+
spec_version: str = ""
|
|
127
|
+
spec_source_url: str = ""
|
|
128
|
+
recommended_max_loops: int = 2
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def passed(self) -> bool:
|
|
132
|
+
"""Return True if no check failed."""
|
|
133
|
+
return not any(check.status == "fail" for check in self.checks)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def warnings(self) -> list[CheckResult]:
|
|
137
|
+
"""Return all checks with warning status."""
|
|
138
|
+
return [check for check in self.checks if check.status == "warn"]
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def failures(self) -> list[CheckResult]:
|
|
142
|
+
"""Return all checks with fail status."""
|
|
143
|
+
return [check for check in self.checks if check.status == "fail"]
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def issues(self) -> list[CheckResult]:
|
|
147
|
+
"""Return all failing and warning checks (errors first)."""
|
|
148
|
+
return [*self.failures, *self.warnings]
|
|
149
|
+
|
|
150
|
+
def summary(self) -> str:
|
|
151
|
+
"""Render a crisp, readable scorecard string."""
|
|
152
|
+
try:
|
|
153
|
+
display = get_spec(self.journal).display_name
|
|
154
|
+
except (KeyError, ValueError):
|
|
155
|
+
display = self.journal
|
|
156
|
+
|
|
157
|
+
overall = "PASS" if self.passed else "FAIL"
|
|
158
|
+
header = (
|
|
159
|
+
f"mintfig preflight — {display} "
|
|
160
|
+
f"({self.width_mm:.1f} × {self.height_mm:.1f} mm) — {overall}"
|
|
161
|
+
)
|
|
162
|
+
rule_width = max((len(c.rule) for c in self.checks), default=14)
|
|
163
|
+
divider = "─" * max(len(header), 64)
|
|
164
|
+
lines = [header, divider]
|
|
165
|
+
|
|
166
|
+
tag_map = {"pass": "[PASS]", "warn": "[WARN]", "fail": "[FAIL]"}
|
|
167
|
+
for check in self.checks:
|
|
168
|
+
tag = tag_map[check.status]
|
|
169
|
+
if len(check.panels) > 1:
|
|
170
|
+
panel_note = f" [panels {', '.join(check.panels)}]"
|
|
171
|
+
else:
|
|
172
|
+
panel_note = f" [panel {check.panel}]" if check.panel else ""
|
|
173
|
+
lines.append(f"{tag} {check.rule:<{rule_width}} {check.message}{panel_note}")
|
|
174
|
+
|
|
175
|
+
n_pass = sum(1 for c in self.checks if c.status == "pass")
|
|
176
|
+
n_warn = len(self.warnings)
|
|
177
|
+
n_fail = len(self.failures)
|
|
178
|
+
lines.append(divider)
|
|
179
|
+
lines.append(f"Summary: {n_pass} passed, {n_warn} warnings, {n_fail} failures")
|
|
180
|
+
return "\n".join(lines)
|
|
181
|
+
|
|
182
|
+
def to_agent_dict(
|
|
183
|
+
self,
|
|
184
|
+
*,
|
|
185
|
+
artifacts: dict[str, str | None] | None = None,
|
|
186
|
+
) -> dict[str, Any]:
|
|
187
|
+
"""Return the structured v0.2 agent-consumable JSON contract."""
|
|
188
|
+
return {
|
|
189
|
+
"schema_version": "0.2",
|
|
190
|
+
"ok": self.passed,
|
|
191
|
+
"journal": self.journal,
|
|
192
|
+
"spec_version": self.spec_version,
|
|
193
|
+
"spec_source_url": self.spec_source_url,
|
|
194
|
+
"dimensions_mm": {
|
|
195
|
+
"width": round(float(self.width_mm), 2),
|
|
196
|
+
"height": round(float(self.height_mm), 2),
|
|
197
|
+
},
|
|
198
|
+
"summary": {
|
|
199
|
+
"errors": len(self.failures),
|
|
200
|
+
"warnings": len(self.warnings),
|
|
201
|
+
"passed": sum(1 for c in self.checks if c.status == "pass"),
|
|
202
|
+
},
|
|
203
|
+
"recommended_max_loops": self.recommended_max_loops,
|
|
204
|
+
"issues": [check.to_issue_dict() for check in self.issues],
|
|
205
|
+
"artifacts": dict(artifacts) if artifacts is not None else {},
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
def to_dict(self) -> dict[str, Any]:
|
|
209
|
+
"""Return a JSON-serializable dictionary preserving v0.1 + v0.2 fields."""
|
|
210
|
+
agent_payload = self.to_agent_dict()
|
|
211
|
+
return {
|
|
212
|
+
**agent_payload,
|
|
213
|
+
"width_mm": round(float(self.width_mm), 3),
|
|
214
|
+
"height_mm": round(float(self.height_mm), 3),
|
|
215
|
+
"passed": self.passed,
|
|
216
|
+
"num_passed": agent_payload["summary"]["passed"],
|
|
217
|
+
"num_warnings": agent_payload["summary"]["warnings"],
|
|
218
|
+
"num_failures": agent_payload["summary"]["errors"],
|
|
219
|
+
"checks": [c.to_dict() for c in self.checks],
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _is_serif_font_name(name: str) -> bool:
|
|
224
|
+
"""Return True if a font name or file stem indicates a serif typeface."""
|
|
225
|
+
if not name:
|
|
226
|
+
return False
|
|
227
|
+
# Strip PDF subset prefix like "ABCDEF+Helvetica"
|
|
228
|
+
cleaned = re.sub(r"^[A-Z]{6}\+", "", name.strip())
|
|
229
|
+
low = cleaned.lower()
|
|
230
|
+
compact = re.sub(r"[\s_\-]+", "", low)
|
|
231
|
+
|
|
232
|
+
if "sans" in compact:
|
|
233
|
+
return False
|
|
234
|
+
|
|
235
|
+
if any(sub in compact or sub in low for sub in _SERIF_SUBSTRINGS):
|
|
236
|
+
return True
|
|
237
|
+
|
|
238
|
+
# Computer Modern PDF/Type1 font names like CMR10, CMMI7, CMSY10
|
|
239
|
+
if re.match(r"^(cmr|cmmi|cmsy|cmex|cmti|cmbx|cmsl)\d*", compact):
|
|
240
|
+
return True
|
|
241
|
+
|
|
242
|
+
return bool(_SERIF_TOKEN_RE.search(low))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _canonical_preset_for_width(spec: JournalSpec, width_mm: float) -> tuple[str, float]:
|
|
246
|
+
"""Return the nearest canonical (preset_name, target_width_mm) for ``width_mm``."""
|
|
247
|
+
order = {name: i for i, name in enumerate(_CANONICAL_WIDTH_PRIORITY)}
|
|
248
|
+
candidates = sorted(
|
|
249
|
+
spec.widths_mm.items(),
|
|
250
|
+
key=lambda kv: (abs(width_mm - kv[1]), order.get(kv[0], 99), kv[0]),
|
|
251
|
+
)
|
|
252
|
+
return candidates[0]
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _build_axes_panel_map(fig: Figure) -> dict[int, str]:
|
|
256
|
+
"""Map axes ``id(ax)`` to a panel key (``_mintfig_panel_key`` or ``ax{idx}``)."""
|
|
257
|
+
mapping: dict[int, str] = {}
|
|
258
|
+
has_plate_keys = False
|
|
259
|
+
for ax in fig.axes:
|
|
260
|
+
key = getattr(ax, "_mintfig_panel_key", None)
|
|
261
|
+
if key is not None:
|
|
262
|
+
mapping[id(ax)] = str(key)
|
|
263
|
+
has_plate_keys = True
|
|
264
|
+
|
|
265
|
+
if len(fig.axes) > 1:
|
|
266
|
+
for idx, ax in enumerate(fig.axes):
|
|
267
|
+
if id(ax) not in mapping:
|
|
268
|
+
# Colorbars / insets on a Plate still get a deterministic fallback key
|
|
269
|
+
parent = getattr(ax, "_parent_axes", None)
|
|
270
|
+
if has_plate_keys and parent is not None and id(parent) in mapping:
|
|
271
|
+
mapping[id(ax)] = mapping[id(parent)]
|
|
272
|
+
else:
|
|
273
|
+
mapping[id(ax)] = f"ax{idx}"
|
|
274
|
+
return mapping
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _artist_panel(artist: Any, panel_map: dict[int, str]) -> str | None:
|
|
278
|
+
"""Resolve the panel key owning ``artist``, or ``None`` for figure-level artists."""
|
|
279
|
+
ax = getattr(artist, "axes", None)
|
|
280
|
+
if ax is None:
|
|
281
|
+
return None
|
|
282
|
+
key = getattr(ax, "_mintfig_panel_key", None)
|
|
283
|
+
if key is not None:
|
|
284
|
+
return str(key)
|
|
285
|
+
return panel_map.get(id(ax))
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _distinct_panels(panels: Any) -> list[str]:
|
|
289
|
+
"""Return distinct non-empty panel keys in first-seen order."""
|
|
290
|
+
out: list[str] = []
|
|
291
|
+
for panel in panels:
|
|
292
|
+
if panel and panel not in out:
|
|
293
|
+
out.append(str(panel))
|
|
294
|
+
return out
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _locate(pairs: Any) -> list[dict[str, str | None]]:
|
|
298
|
+
"""Build ``element_locations`` entries from ``(element, panel)`` pairs."""
|
|
299
|
+
return [{"element": element, "panel": panel} for element, panel in pairs]
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _check_dimensions(
|
|
303
|
+
width_mm: float,
|
|
304
|
+
height_mm: float,
|
|
305
|
+
spec: JournalSpec,
|
|
306
|
+
*,
|
|
307
|
+
tol_mm: float = 0.5,
|
|
308
|
+
) -> CheckResult:
|
|
309
|
+
"""Validate physical figure width and height against journal column specs."""
|
|
310
|
+
nearest_preset, nearest_width = _canonical_preset_for_width(spec, width_mm)
|
|
311
|
+
width_ok = abs(width_mm - nearest_width) <= tol_mm
|
|
312
|
+
matched_preset = nearest_preset if width_ok else None
|
|
313
|
+
matched_width = nearest_width if width_ok else None
|
|
314
|
+
|
|
315
|
+
unique_widths = sorted(set(spec.widths_mm.values()))
|
|
316
|
+
|
|
317
|
+
height_status: CheckStatus
|
|
318
|
+
if height_mm > spec.max_page_height_mm + tol_mm:
|
|
319
|
+
height_status = "fail"
|
|
320
|
+
height_note = (
|
|
321
|
+
f"height {height_mm:.1f} mm exceeds max page height "
|
|
322
|
+
f"{spec.max_page_height_mm:.1f} mm"
|
|
323
|
+
)
|
|
324
|
+
elif height_mm > spec.max_height_mm + tol_mm:
|
|
325
|
+
height_status = "warn"
|
|
326
|
+
height_note = (
|
|
327
|
+
f"height {height_mm:.1f} mm exceeds standard {spec.max_height_mm:.1f} mm "
|
|
328
|
+
f"(within page max {spec.max_page_height_mm:.1f} mm)"
|
|
329
|
+
)
|
|
330
|
+
else:
|
|
331
|
+
height_status = "pass"
|
|
332
|
+
height_note = f"height {height_mm:.1f} mm <= {spec.max_height_mm:.1f} mm"
|
|
333
|
+
|
|
334
|
+
if width_ok and matched_width is not None:
|
|
335
|
+
width_note = f"width {width_mm:.1f} mm matches '{matched_preset}' ({matched_width:.1f} mm)"
|
|
336
|
+
else:
|
|
337
|
+
allowed_str = ", ".join(f"{w:.0f}" for w in unique_widths)
|
|
338
|
+
width_note = (
|
|
339
|
+
f"width {width_mm:.1f} mm does not match allowed {spec.name} widths "
|
|
340
|
+
f"[{allowed_str}] mm (±{tol_mm:.1f} mm)"
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
if not width_ok or height_status == "fail":
|
|
344
|
+
status: CheckStatus = "fail"
|
|
345
|
+
elif height_status == "warn":
|
|
346
|
+
status = "warn"
|
|
347
|
+
else:
|
|
348
|
+
status = "pass"
|
|
349
|
+
|
|
350
|
+
elements: list[str] = []
|
|
351
|
+
fix_hint: str | None = None
|
|
352
|
+
if status != "pass":
|
|
353
|
+
elements = [f"{width_mm:.1f}x{height_mm:.1f}mm"]
|
|
354
|
+
suggested_h = min(round(height_mm, 1), spec.max_height_mm)
|
|
355
|
+
if not width_ok and height_status == "fail":
|
|
356
|
+
fix_hint = (
|
|
357
|
+
f"Use mint.Plate(journal={spec.name!r}, width={nearest_preset!r}, "
|
|
358
|
+
f"height_mm={spec.max_height_mm:.0f}) to match {nearest_width:.1f} mm "
|
|
359
|
+
f"width and keep height <= {spec.max_height_mm:.0f} mm."
|
|
360
|
+
)
|
|
361
|
+
elif not width_ok:
|
|
362
|
+
fix_hint = (
|
|
363
|
+
f"Use mint.Plate(journal={spec.name!r}, width={nearest_preset!r}, "
|
|
364
|
+
f"height_mm={suggested_h:.1f}) (target {nearest_width:.1f} mm)."
|
|
365
|
+
)
|
|
366
|
+
elif height_status == "fail":
|
|
367
|
+
fix_hint = (
|
|
368
|
+
f"Reduce height_mm from {height_mm:.1f} mm to <= {spec.max_height_mm:.0f} mm "
|
|
369
|
+
f"(e.g. mint.Plate(journal={spec.name!r}, width={nearest_preset!r}, "
|
|
370
|
+
f"height_mm={spec.max_height_mm:.0f}))."
|
|
371
|
+
)
|
|
372
|
+
else:
|
|
373
|
+
fix_hint = (
|
|
374
|
+
f"Reduce height_mm from {height_mm:.1f} mm to <= {spec.max_height_mm:.0f} mm "
|
|
375
|
+
"to leave space for the figure caption."
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
return CheckResult(
|
|
379
|
+
rule="dimensions",
|
|
380
|
+
status=status,
|
|
381
|
+
message=f"{width_note}; {height_note}",
|
|
382
|
+
details={
|
|
383
|
+
"width_mm": round(width_mm, 3),
|
|
384
|
+
"height_mm": round(height_mm, 3),
|
|
385
|
+
"matched_preset": matched_preset,
|
|
386
|
+
"nearest_preset": nearest_preset,
|
|
387
|
+
"nearest_width_mm": nearest_width,
|
|
388
|
+
"allowed_widths_mm": unique_widths,
|
|
389
|
+
"max_height_mm": spec.max_height_mm,
|
|
390
|
+
"max_page_height_mm": spec.max_page_height_mm,
|
|
391
|
+
},
|
|
392
|
+
panel=None,
|
|
393
|
+
elements=elements,
|
|
394
|
+
fix_hint=fix_hint,
|
|
395
|
+
)
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
@dataclass(frozen=True)
|
|
399
|
+
class _TextRecord:
|
|
400
|
+
"""Measured visible Text artist with bounding box, panel, and semantic role."""
|
|
401
|
+
|
|
402
|
+
artist: Text
|
|
403
|
+
bbox: Any
|
|
404
|
+
text: str
|
|
405
|
+
panel: str | None
|
|
406
|
+
role: Literal["tick", "legend", "title", "axis_label", "panel_label", "annotation"]
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _iter_visible_texts(
|
|
410
|
+
fig: Figure,
|
|
411
|
+
renderer: Any,
|
|
412
|
+
panel_map: dict[int, str],
|
|
413
|
+
) -> list[_TextRecord]:
|
|
414
|
+
"""Collect visible, non-empty, actually rendered Text artists and their pixel bboxes."""
|
|
415
|
+
all_tick_label_ids: set[int] = set()
|
|
416
|
+
active_tick_label_ids: set[int] = set()
|
|
417
|
+
inactive_offset_ids: set[int] = set()
|
|
418
|
+
axis_label_ids: set[int] = set()
|
|
419
|
+
title_ids: set[int] = set()
|
|
420
|
+
legend_text_ids: set[int] = set()
|
|
421
|
+
hidden_legend_text_ids: set[int] = set()
|
|
422
|
+
|
|
423
|
+
for ax in fig.axes:
|
|
424
|
+
ax_visible = ax.get_visible()
|
|
425
|
+
ax_axis_on = bool(getattr(ax, "axison", True))
|
|
426
|
+
axis_label_ids.add(id(ax.xaxis.label))
|
|
427
|
+
axis_label_ids.add(id(ax.yaxis.label))
|
|
428
|
+
title_ids.add(id(ax.title))
|
|
429
|
+
for attr in ("_left_title", "_right_title"):
|
|
430
|
+
sub_title = getattr(ax, attr, None)
|
|
431
|
+
if sub_title is not None:
|
|
432
|
+
title_ids.add(id(sub_title))
|
|
433
|
+
|
|
434
|
+
for axis in (ax.xaxis, ax.yaxis):
|
|
435
|
+
axis_visible = ax_visible and ax_axis_on and axis.get_visible()
|
|
436
|
+
v0, v1 = axis.get_view_interval()
|
|
437
|
+
lo, hi = (v0, v1) if v0 <= v1 else (v1, v0)
|
|
438
|
+
span = abs(hi - lo)
|
|
439
|
+
# Relative tolerance only: an absolute floor would count off-view ticks as
|
|
440
|
+
# active on axes whose data are tiny (1e-13 A leakage currents).
|
|
441
|
+
eps = span * 1e-6 if span > 0 else 1e-12 * max(abs(lo), 1e-300)
|
|
442
|
+
|
|
443
|
+
if not axis_visible:
|
|
444
|
+
inactive_offset_ids.add(id(axis.get_offset_text()))
|
|
445
|
+
inactive_offset_ids.add(id(axis.label))
|
|
446
|
+
|
|
447
|
+
ticks = list(axis.get_major_ticks()) + list(axis.get_minor_ticks())
|
|
448
|
+
for tick in ticks:
|
|
449
|
+
all_tick_label_ids.add(id(tick.label1))
|
|
450
|
+
all_tick_label_ids.add(id(tick.label2))
|
|
451
|
+
if not axis_visible or not tick.get_visible():
|
|
452
|
+
continue
|
|
453
|
+
loc = tick.get_loc()
|
|
454
|
+
if not np.isfinite(loc) or loc < lo - eps or loc > hi + eps:
|
|
455
|
+
continue
|
|
456
|
+
if tick.label1.get_visible() and tick.label1.get_text().strip():
|
|
457
|
+
active_tick_label_ids.add(id(tick.label1))
|
|
458
|
+
if tick.label2.get_visible() and tick.label2.get_text().strip():
|
|
459
|
+
active_tick_label_ids.add(id(tick.label2))
|
|
460
|
+
|
|
461
|
+
for leg in list(fig.legends) + [ax.get_legend() for ax in fig.axes]:
|
|
462
|
+
if leg is None:
|
|
463
|
+
continue
|
|
464
|
+
leg_visible = leg.get_visible()
|
|
465
|
+
for t in leg.get_texts():
|
|
466
|
+
legend_text_ids.add(id(t))
|
|
467
|
+
if not leg_visible:
|
|
468
|
+
hidden_legend_text_ids.add(id(t))
|
|
469
|
+
leg_title = leg.get_title()
|
|
470
|
+
legend_text_ids.add(id(leg_title))
|
|
471
|
+
if not leg_visible:
|
|
472
|
+
hidden_legend_text_ids.add(id(leg_title))
|
|
473
|
+
|
|
474
|
+
results: list[_TextRecord] = []
|
|
475
|
+
seen_ids: set[int] = set()
|
|
476
|
+
|
|
477
|
+
for text_artist in fig.findobj(Text):
|
|
478
|
+
tid = id(text_artist)
|
|
479
|
+
if tid in seen_ids:
|
|
480
|
+
continue
|
|
481
|
+
seen_ids.add(tid)
|
|
482
|
+
|
|
483
|
+
if tid in hidden_legend_text_ids or tid in inactive_offset_ids:
|
|
484
|
+
continue
|
|
485
|
+
if tid in all_tick_label_ids and tid not in active_tick_label_ids:
|
|
486
|
+
continue
|
|
487
|
+
|
|
488
|
+
if not text_artist.get_visible():
|
|
489
|
+
continue
|
|
490
|
+
alpha = text_artist.get_alpha()
|
|
491
|
+
if alpha is not None and alpha <= 0:
|
|
492
|
+
continue
|
|
493
|
+
if text_artist.axes is not None and not text_artist.axes.get_visible():
|
|
494
|
+
continue
|
|
495
|
+
|
|
496
|
+
content = text_artist.get_text()
|
|
497
|
+
if not content or not content.strip():
|
|
498
|
+
continue
|
|
499
|
+
|
|
500
|
+
try:
|
|
501
|
+
bbox = text_artist.get_window_extent(renderer=renderer)
|
|
502
|
+
except (RuntimeError, ValueError):
|
|
503
|
+
continue
|
|
504
|
+
|
|
505
|
+
if not np.all(np.isfinite([bbox.x0, bbox.y0, bbox.x1, bbox.y1])):
|
|
506
|
+
continue
|
|
507
|
+
if bbox.width <= 0.5 or bbox.height <= 0.5:
|
|
508
|
+
continue
|
|
509
|
+
|
|
510
|
+
# If artist is clipped to an axes/clip_box and lies completely outside it, skip.
|
|
511
|
+
if text_artist.get_clip_on():
|
|
512
|
+
clip_box = text_artist.get_clip_box()
|
|
513
|
+
if clip_box is not None and not bbox.overlaps(clip_box):
|
|
514
|
+
continue
|
|
515
|
+
|
|
516
|
+
if bool(getattr(text_artist, "_mintfig_panel_label", False)):
|
|
517
|
+
role: Literal[
|
|
518
|
+
"tick", "legend", "title", "axis_label", "panel_label", "annotation"
|
|
519
|
+
] = "panel_label"
|
|
520
|
+
elif tid in active_tick_label_ids:
|
|
521
|
+
role = "tick"
|
|
522
|
+
elif tid in legend_text_ids:
|
|
523
|
+
role = "legend"
|
|
524
|
+
elif tid in title_ids:
|
|
525
|
+
role = "title"
|
|
526
|
+
elif tid in axis_label_ids:
|
|
527
|
+
role = "axis_label"
|
|
528
|
+
else:
|
|
529
|
+
role = "annotation"
|
|
530
|
+
|
|
531
|
+
label = content.strip().replace("\n", " ")[:48]
|
|
532
|
+
results.append(
|
|
533
|
+
_TextRecord(
|
|
534
|
+
artist=text_artist,
|
|
535
|
+
bbox=bbox,
|
|
536
|
+
text=label,
|
|
537
|
+
panel=_artist_panel(text_artist, panel_map),
|
|
538
|
+
role=role,
|
|
539
|
+
)
|
|
540
|
+
)
|
|
541
|
+
|
|
542
|
+
return results
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _check_font_sizes(
|
|
546
|
+
visible_texts: list[_TextRecord],
|
|
547
|
+
spec: JournalSpec,
|
|
548
|
+
) -> CheckResult:
|
|
549
|
+
"""Verify all visible text artists respect journal minimum and maximum font sizes."""
|
|
550
|
+
if not visible_texts:
|
|
551
|
+
return CheckResult(
|
|
552
|
+
rule="font_sizes",
|
|
553
|
+
status="pass",
|
|
554
|
+
message="No visible text artists found",
|
|
555
|
+
details={"count": 0},
|
|
556
|
+
)
|
|
557
|
+
|
|
558
|
+
too_small: list[dict[str, Any]] = []
|
|
559
|
+
too_large: list[dict[str, Any]] = []
|
|
560
|
+
sizes: list[float] = []
|
|
561
|
+
|
|
562
|
+
for rec in visible_texts:
|
|
563
|
+
pt = float(rec.artist.get_fontsize())
|
|
564
|
+
sizes.append(pt)
|
|
565
|
+
is_panel = rec.role == "panel_label"
|
|
566
|
+
max_pt = (spec.panel_label_pt + 0.5) if is_panel else (spec.font_max_pt + 0.5)
|
|
567
|
+
|
|
568
|
+
if pt < spec.font_min_pt - 0.1:
|
|
569
|
+
too_small.append(
|
|
570
|
+
{
|
|
571
|
+
"text": rec.text,
|
|
572
|
+
"size_pt": round(pt, 2),
|
|
573
|
+
"panel": rec.panel,
|
|
574
|
+
"role": rec.role,
|
|
575
|
+
}
|
|
576
|
+
)
|
|
577
|
+
elif pt > max_pt:
|
|
578
|
+
too_large.append(
|
|
579
|
+
{
|
|
580
|
+
"text": rec.text,
|
|
581
|
+
"size_pt": round(pt, 2),
|
|
582
|
+
"panel": rec.panel,
|
|
583
|
+
"is_panel_label": is_panel,
|
|
584
|
+
"role": rec.role,
|
|
585
|
+
}
|
|
586
|
+
)
|
|
587
|
+
|
|
588
|
+
min_obs = min(sizes)
|
|
589
|
+
max_obs = max(sizes)
|
|
590
|
+
|
|
591
|
+
if too_small or too_large:
|
|
592
|
+
small_elems = [f"{item['text']} ({item['size_pt']} pt)" for item in too_small[:6]]
|
|
593
|
+
large_elems = [f"{item['text']} ({item['size_pt']} pt)" for item in too_large[:6]]
|
|
594
|
+
elements = small_elems + large_elems
|
|
595
|
+
located = [*too_small[:6], *too_large[:6]]
|
|
596
|
+
offenders = [*too_small, *too_large]
|
|
597
|
+
panels = _distinct_panels(item["panel"] for item in offenders)
|
|
598
|
+
|
|
599
|
+
parts: list[str] = []
|
|
600
|
+
hints: list[str] = []
|
|
601
|
+
if too_small:
|
|
602
|
+
sample = ", ".join(
|
|
603
|
+
f"'{item['text']}' ({item['size_pt']} pt)" for item in too_small[:4]
|
|
604
|
+
)
|
|
605
|
+
parts.append(
|
|
606
|
+
f"{len(too_small)} text artist(s) below {spec.font_min_pt:.1f} pt minimum: "
|
|
607
|
+
f"{sample}"
|
|
608
|
+
)
|
|
609
|
+
hints.append(
|
|
610
|
+
f"Increase font size of {small_elems[0]} to >= {spec.font_min_pt:.1f} pt "
|
|
611
|
+
f"(recommended body={spec.body_pt:.1f} pt, ticks={spec.tick_pt:.1f} pt) "
|
|
612
|
+
f"or remove tiny fontsize overrides."
|
|
613
|
+
)
|
|
614
|
+
if too_large:
|
|
615
|
+
sample = ", ".join(
|
|
616
|
+
f"'{item['text']}' ({item['size_pt']} pt)" for item in too_large[:4]
|
|
617
|
+
)
|
|
618
|
+
parts.append(
|
|
619
|
+
f"{len(too_large)} text artist(s) above {spec.font_max_pt:.1f} pt maximum: "
|
|
620
|
+
f"{sample}"
|
|
621
|
+
)
|
|
622
|
+
hints.append(
|
|
623
|
+
f"Reduce font size to <= {spec.font_max_pt:.1f} pt (body={spec.body_pt:.1f} pt) "
|
|
624
|
+
f"by building inside mint.Plate(journal={spec.name!r}) or mint.use({spec.name!r})."
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
# The first offender's panel: too-small text first (it drives the error).
|
|
628
|
+
panel = next((item["panel"] for item in offenders if item["panel"]), None)
|
|
629
|
+
return CheckResult(
|
|
630
|
+
rule="font_sizes",
|
|
631
|
+
status="fail" if too_small else "warn",
|
|
632
|
+
message="; ".join(parts),
|
|
633
|
+
details={
|
|
634
|
+
"count": len(visible_texts),
|
|
635
|
+
"min_pt": round(min_obs, 2),
|
|
636
|
+
"max_pt": round(max_obs, 2),
|
|
637
|
+
"too_small": too_small[:20],
|
|
638
|
+
"too_large": too_large[:20],
|
|
639
|
+
},
|
|
640
|
+
panel=panel,
|
|
641
|
+
elements=elements,
|
|
642
|
+
fix_hint=" Also: ".join(hints),
|
|
643
|
+
panels=panels,
|
|
644
|
+
element_locations=_locate(
|
|
645
|
+
zip(elements, (item["panel"] for item in located), strict=True)
|
|
646
|
+
),
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
return CheckResult(
|
|
650
|
+
rule="font_sizes",
|
|
651
|
+
status="pass",
|
|
652
|
+
message=(
|
|
653
|
+
f"All {len(visible_texts)} text artists in range "
|
|
654
|
+
f"({min_obs:.1f}–{max_obs:.1f} pt; min {spec.font_min_pt:.1f} pt)"
|
|
655
|
+
),
|
|
656
|
+
details={
|
|
657
|
+
"count": len(visible_texts),
|
|
658
|
+
"min_pt": round(min_obs, 2),
|
|
659
|
+
"max_pt": round(max_obs, 2),
|
|
660
|
+
},
|
|
661
|
+
)
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def _check_font_family(
|
|
665
|
+
visible_texts: list[_TextRecord],
|
|
666
|
+
spec: JournalSpec,
|
|
667
|
+
) -> CheckResult:
|
|
668
|
+
"""Verify sans-serif font usage across visible text artists and mathtext."""
|
|
669
|
+
serif_hits: list[dict[str, Any]] = []
|
|
670
|
+
resolved_fonts: set[str] = set()
|
|
671
|
+
|
|
672
|
+
for rec in visible_texts:
|
|
673
|
+
if getattr(rec.artist, "_mintfig_allow_serif", False):
|
|
674
|
+
continue
|
|
675
|
+
families = rec.artist.get_fontfamily()
|
|
676
|
+
if isinstance(families, str):
|
|
677
|
+
families = [families]
|
|
678
|
+
|
|
679
|
+
font_name = rec.artist.get_fontname()
|
|
680
|
+
try:
|
|
681
|
+
font_path = font_manager.findfont(
|
|
682
|
+
rec.artist.get_fontproperties(), fallback_to_default=True
|
|
683
|
+
)
|
|
684
|
+
font_stem = Path(font_path).stem
|
|
685
|
+
except (RuntimeError, ValueError):
|
|
686
|
+
font_stem = font_name
|
|
687
|
+
|
|
688
|
+
resolved_fonts.add(font_stem)
|
|
689
|
+
|
|
690
|
+
flagged_font: str | None = None
|
|
691
|
+
for candidate in (*families, font_name, font_stem):
|
|
692
|
+
if _is_serif_font_name(str(candidate)):
|
|
693
|
+
flagged_font = str(candidate)
|
|
694
|
+
break
|
|
695
|
+
|
|
696
|
+
# Mathtext font set is captured per artist (FontProperties.math_fontfamily,
|
|
697
|
+
# taken from rcParams when the Text was created) and used at draw time, so
|
|
698
|
+
# read it from the artist rather than from the live global rcParams.
|
|
699
|
+
mathtext_fontset = ""
|
|
700
|
+
if flagged_font is None and rec.text.count("$") >= 2:
|
|
701
|
+
try:
|
|
702
|
+
mathtext_fontset = str(
|
|
703
|
+
rec.artist.get_fontproperties().get_math_fontfamily()
|
|
704
|
+
).lower()
|
|
705
|
+
except AttributeError:
|
|
706
|
+
mathtext_fontset = str(plt.rcParams.get("mathtext.fontset", "")).lower()
|
|
707
|
+
if flagged_font is None and mathtext_fontset in {"cm", "stix"}:
|
|
708
|
+
flagged_font = f"mathtext:{mathtext_fontset}"
|
|
709
|
+
|
|
710
|
+
if flagged_font is not None:
|
|
711
|
+
serif_hits.append(
|
|
712
|
+
{"text": rec.text, "font": flagged_font, "panel": rec.panel}
|
|
713
|
+
)
|
|
714
|
+
|
|
715
|
+
if serif_hits:
|
|
716
|
+
unique_bad = sorted({hit["font"] for hit in serif_hits})
|
|
717
|
+
sample = ", ".join(unique_bad[:4])
|
|
718
|
+
panel = next((hit["panel"] for hit in serif_hits if hit["panel"]), None)
|
|
719
|
+
elements = [f"{hit['text']} ({hit['font']})" for hit in serif_hits[:6]]
|
|
720
|
+
family_panels = _distinct_panels(hit["panel"] for hit in serif_hits)
|
|
721
|
+
family_locations = _locate(
|
|
722
|
+
zip(elements, (hit["panel"] for hit in serif_hits[:6]), strict=True)
|
|
723
|
+
)
|
|
724
|
+
return CheckResult(
|
|
725
|
+
rule="font_family",
|
|
726
|
+
status="warn",
|
|
727
|
+
message=(
|
|
728
|
+
f"Detected serif font(s) on {len(serif_hits)} text artist(s): {sample} "
|
|
729
|
+
"(sans-serif required)"
|
|
730
|
+
),
|
|
731
|
+
details={"serif_hits": serif_hits[:20], "resolved_fonts": sorted(resolved_fonts)},
|
|
732
|
+
panel=panel,
|
|
733
|
+
elements=elements,
|
|
734
|
+
fix_hint=(
|
|
735
|
+
f"Remove explicit serif font overrides and wrap plotting in mint.use({spec.name!r}) "
|
|
736
|
+
f"or mint.Plate(journal={spec.name!r}) to enforce sans-serif ({spec.font_family[0]}/Arial) "
|
|
737
|
+
"text and mathtext."
|
|
738
|
+
),
|
|
739
|
+
panels=family_panels,
|
|
740
|
+
element_locations=family_locations,
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
fonts_str = ", ".join(sorted(resolved_fonts)[:4]) if resolved_fonts else "sans-serif"
|
|
744
|
+
return CheckResult(
|
|
745
|
+
rule="font_family",
|
|
746
|
+
status="pass",
|
|
747
|
+
message=f"All text artists use sans-serif typography ({fonts_str})",
|
|
748
|
+
details={"resolved_fonts": sorted(resolved_fonts)},
|
|
749
|
+
)
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def _overlap_fix_hint(role_a: str, role_b: str, panel: str | None) -> str:
|
|
753
|
+
"""Return a context-aware fix hint for an overlapping pair of text roles."""
|
|
754
|
+
roles = {role_a, role_b}
|
|
755
|
+
where = f" in panel '{panel}'" if panel else ""
|
|
756
|
+
if roles == {"tick"}:
|
|
757
|
+
return (
|
|
758
|
+
f"Reduce tick density{where} with ax.xaxis.set_major_locator(MaxNLocator(4)), "
|
|
759
|
+
"rotate tick labels (rotation=30, ha='right'), or increase figure width/gap_mm."
|
|
760
|
+
)
|
|
761
|
+
if "legend" in roles:
|
|
762
|
+
return (
|
|
763
|
+
f"Replace the overlapping legend{where} with mint.direct_labels(ax), "
|
|
764
|
+
"move it with loc='best' / bbox_to_anchor outside the data, or expand ylim."
|
|
765
|
+
)
|
|
766
|
+
if "panel_label" in roles:
|
|
767
|
+
return (
|
|
768
|
+
f"Increase Plate margin_mm or gap_mm{where} and call plate.label_panels() "
|
|
769
|
+
"after setting titles and axis labels."
|
|
770
|
+
)
|
|
771
|
+
if roles & {"axis_label", "title"}:
|
|
772
|
+
return (
|
|
773
|
+
f"Increase Plate gap_mm (e.g. gap_mm=8.0) or height_mm{where}, "
|
|
774
|
+
"or shorten axis labels/titles."
|
|
775
|
+
)
|
|
776
|
+
return (
|
|
777
|
+
f"Reposition colliding annotations{where} to non-overlapping coordinates, "
|
|
778
|
+
"use mint.direct_labels(ax), or increase ylim/xlim padding."
|
|
779
|
+
)
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _overlap_elements(
|
|
783
|
+
pairs: list[dict[str, Any]],
|
|
784
|
+
) -> tuple[list[str], list[dict[str, str | None]], list[str]]:
|
|
785
|
+
"""Return (elements, element_locations, panels) for overlapping text pairs."""
|
|
786
|
+
elements: list[str] = []
|
|
787
|
+
located: list[tuple[str, str | None]] = []
|
|
788
|
+
for item in pairs[:3]:
|
|
789
|
+
for txt, pnl in ((item["text_a"], item["panel_a"]), (item["text_b"], item["panel_b"])):
|
|
790
|
+
if txt not in elements:
|
|
791
|
+
elements.append(txt)
|
|
792
|
+
located.append((txt, pnl))
|
|
793
|
+
panels = _distinct_panels(
|
|
794
|
+
pnl for item in pairs for pnl in (item["panel"], item["panel_a"], item["panel_b"])
|
|
795
|
+
)
|
|
796
|
+
return elements, _locate(located), panels
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def _check_text_overlaps(visible_texts: list[_TextRecord]) -> CheckResult:
|
|
800
|
+
"""Detect colliding visible Text artists with high precision (zero grazing FPs)."""
|
|
801
|
+
severe: list[dict[str, Any]] = []
|
|
802
|
+
moderate: list[dict[str, Any]] = []
|
|
803
|
+
|
|
804
|
+
n = len(visible_texts)
|
|
805
|
+
for i in range(n):
|
|
806
|
+
rec_a = visible_texts[i]
|
|
807
|
+
ba = rec_a.bbox
|
|
808
|
+
ax0, ay0, ax1, ay1 = float(ba.x0), float(ba.y0), float(ba.x1), float(ba.y1)
|
|
809
|
+
area_a = max(0.0, ax1 - ax0) * max(0.0, ay1 - ay0)
|
|
810
|
+
if area_a <= 0.0:
|
|
811
|
+
continue
|
|
812
|
+
|
|
813
|
+
for j in range(i + 1, n):
|
|
814
|
+
rec_b = visible_texts[j]
|
|
815
|
+
if rec_a.artist is rec_b.artist:
|
|
816
|
+
continue
|
|
817
|
+
bb = rec_b.bbox
|
|
818
|
+
bx0, by0, bx1, by1 = float(bb.x0), float(bb.y0), float(bb.x1), float(bb.y1)
|
|
819
|
+
area_b = max(0.0, bx1 - bx0) * max(0.0, by1 - by0)
|
|
820
|
+
if area_b <= 0.0:
|
|
821
|
+
continue
|
|
822
|
+
|
|
823
|
+
iw = min(ax1, bx1) - max(ax0, bx0)
|
|
824
|
+
ih = min(ay1, by1) - max(ay0, by0)
|
|
825
|
+
if iw < 3.0 or ih < 3.0:
|
|
826
|
+
continue
|
|
827
|
+
|
|
828
|
+
inter_area = iw * ih
|
|
829
|
+
min_area = min(area_a, area_b)
|
|
830
|
+
ratio = inter_area / min_area if min_area > 0.0 else 0.0
|
|
831
|
+
if ratio < 0.20:
|
|
832
|
+
continue
|
|
833
|
+
|
|
834
|
+
panel = rec_a.panel if rec_a.panel == rec_b.panel else (rec_a.panel or rec_b.panel)
|
|
835
|
+
entry = {
|
|
836
|
+
"text_a": rec_a.text,
|
|
837
|
+
"text_b": rec_b.text,
|
|
838
|
+
"role_a": rec_a.role,
|
|
839
|
+
"role_b": rec_b.role,
|
|
840
|
+
"panel": panel,
|
|
841
|
+
"panel_a": rec_a.panel,
|
|
842
|
+
"panel_b": rec_b.panel,
|
|
843
|
+
"overlap_ratio": round(ratio, 3),
|
|
844
|
+
"intersect_px": [round(iw, 1), round(ih, 1)],
|
|
845
|
+
}
|
|
846
|
+
if ratio >= 0.35:
|
|
847
|
+
severe.append(entry)
|
|
848
|
+
else:
|
|
849
|
+
moderate.append(entry)
|
|
850
|
+
|
|
851
|
+
severe.sort(key=lambda item: item["overlap_ratio"], reverse=True)
|
|
852
|
+
moderate.sort(key=lambda item: item["overlap_ratio"], reverse=True)
|
|
853
|
+
|
|
854
|
+
if severe:
|
|
855
|
+
worst = severe[0]
|
|
856
|
+
pairs = ", ".join(
|
|
857
|
+
f"'{o['text_a']}' vs '{o['text_b']}'" for o in severe[:4]
|
|
858
|
+
)
|
|
859
|
+
extra = f" (+{len(severe) - 4} more)" if len(severe) > 4 else ""
|
|
860
|
+
elements, locations, panels = _overlap_elements(severe)
|
|
861
|
+
return CheckResult(
|
|
862
|
+
rule="text_overlaps",
|
|
863
|
+
status="fail",
|
|
864
|
+
message=f"{len(severe)} severe overlapping text pair(s): {pairs}{extra}",
|
|
865
|
+
details={"overlaps": severe[:20], "moderate_overlaps": moderate[:20]},
|
|
866
|
+
panel=worst["panel"],
|
|
867
|
+
elements=elements,
|
|
868
|
+
fix_hint=_overlap_fix_hint(worst["role_a"], worst["role_b"], worst["panel"]),
|
|
869
|
+
panels=panels,
|
|
870
|
+
element_locations=locations,
|
|
871
|
+
)
|
|
872
|
+
|
|
873
|
+
if moderate:
|
|
874
|
+
worst = moderate[0]
|
|
875
|
+
pairs = ", ".join(
|
|
876
|
+
f"'{o['text_a']}' vs '{o['text_b']}'" for o in moderate[:4]
|
|
877
|
+
)
|
|
878
|
+
elements, locations, panels = _overlap_elements(moderate)
|
|
879
|
+
return CheckResult(
|
|
880
|
+
rule="text_overlaps",
|
|
881
|
+
status="warn",
|
|
882
|
+
message=f"{len(moderate)} moderate text overlap(s) (20–35%): {pairs}",
|
|
883
|
+
details={"overlaps": [], "moderate_overlaps": moderate[:20]},
|
|
884
|
+
panel=worst["panel"],
|
|
885
|
+
elements=elements,
|
|
886
|
+
fix_hint=_overlap_fix_hint(worst["role_a"], worst["role_b"], worst["panel"]),
|
|
887
|
+
panels=panels,
|
|
888
|
+
element_locations=locations,
|
|
889
|
+
)
|
|
890
|
+
|
|
891
|
+
return CheckResult(
|
|
892
|
+
rule="text_overlaps",
|
|
893
|
+
status="pass",
|
|
894
|
+
message=f"No text collisions across {len(visible_texts)} visible text artists",
|
|
895
|
+
details={"checked_count": len(visible_texts)},
|
|
896
|
+
)
|
|
897
|
+
|
|
898
|
+
|
|
899
|
+
def _check_canvas_clipping(
|
|
900
|
+
fig: Figure,
|
|
901
|
+
visible_texts: list[_TextRecord],
|
|
902
|
+
*,
|
|
903
|
+
margin_px: float = 2.5,
|
|
904
|
+
) -> CheckResult:
|
|
905
|
+
"""Flag visible text artists extending outside the figure canvas bounds."""
|
|
906
|
+
fig_w_px = float(fig.bbox.width)
|
|
907
|
+
fig_h_px = float(fig.bbox.height)
|
|
908
|
+
clipped: list[dict[str, Any]] = []
|
|
909
|
+
|
|
910
|
+
for rec in visible_texts:
|
|
911
|
+
bbox = rec.bbox
|
|
912
|
+
edges: list[tuple[str, float]] = [
|
|
913
|
+
("left", max(0.0, -float(bbox.x0))),
|
|
914
|
+
("bottom", max(0.0, -float(bbox.y0))),
|
|
915
|
+
("right", max(0.0, float(bbox.x1) - fig_w_px)),
|
|
916
|
+
("top", max(0.0, float(bbox.y1) - fig_h_px)),
|
|
917
|
+
]
|
|
918
|
+
bad_edges = [(edge, ov) for edge, ov in edges if ov > margin_px]
|
|
919
|
+
if bad_edges:
|
|
920
|
+
worst_edge, max_overflow = max(bad_edges, key=lambda pair: pair[1])
|
|
921
|
+
clipped.append(
|
|
922
|
+
{
|
|
923
|
+
"text": rec.text,
|
|
924
|
+
"panel": rec.panel,
|
|
925
|
+
"edges": [e for e, _ in bad_edges],
|
|
926
|
+
"worst_edge": worst_edge,
|
|
927
|
+
"overflow_px": round(max_overflow, 1),
|
|
928
|
+
}
|
|
929
|
+
)
|
|
930
|
+
|
|
931
|
+
if clipped:
|
|
932
|
+
sample = ", ".join(
|
|
933
|
+
f"'{c['text']}' ({c['worst_edge']} +{c['overflow_px']} px)" for c in clipped[:4]
|
|
934
|
+
)
|
|
935
|
+
panel = next((c["panel"] for c in clipped if c["panel"]), None)
|
|
936
|
+
elements = [c["text"] for c in clipped[:6]]
|
|
937
|
+
all_edges = sorted({e for c in clipped for e in c["edges"]})
|
|
938
|
+
edges_str = "/".join(all_edges)
|
|
939
|
+
if set(all_edges) & {"top", "bottom"}:
|
|
940
|
+
extra_hint = "increase height_mm or margin_mm, wrap/shorten axis labels, or enable layout='constrained' (mint.Plate)."
|
|
941
|
+
else:
|
|
942
|
+
extra_hint = "move out-of-bounds annotations inside axes, shorten/wrap labels, or enable layout='constrained' (mint.Plate) with larger margin_mm."
|
|
943
|
+
return CheckResult(
|
|
944
|
+
rule="canvas_clipping",
|
|
945
|
+
status="fail",
|
|
946
|
+
message=f"{len(clipped)} text artist(s) clipped at {edges_str} edge: {sample}",
|
|
947
|
+
details={
|
|
948
|
+
"clipped": clipped[:20],
|
|
949
|
+
"canvas_px": [round(fig_w_px, 1), round(fig_h_px, 1)],
|
|
950
|
+
},
|
|
951
|
+
panel=panel,
|
|
952
|
+
elements=elements,
|
|
953
|
+
fix_hint=f"Text clipped at {edges_str} edge: {extra_hint}",
|
|
954
|
+
panels=_distinct_panels(c["panel"] for c in clipped),
|
|
955
|
+
element_locations=_locate((c["text"], c["panel"]) for c in clipped[:6]),
|
|
956
|
+
)
|
|
957
|
+
|
|
958
|
+
return CheckResult(
|
|
959
|
+
rule="canvas_clipping",
|
|
960
|
+
status="pass",
|
|
961
|
+
message="All visible text artists fit cleanly inside canvas bounds",
|
|
962
|
+
details={"canvas_px": [round(fig_w_px, 1), round(fig_h_px, 1)]},
|
|
963
|
+
)
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def _axis_line_span(ax: Any, renderer: Any) -> tuple[float, float, float, float]:
|
|
967
|
+
"""Display extent (x0, x1, y0, y1) the plotted marks may occupy: the visible axis
|
|
968
|
+
lines (bottom/top spine for x, left/right for y, including ``set_bounds`` trims),
|
|
969
|
+
falling back to the axes box where no axis line is drawn."""
|
|
970
|
+
box = ax.get_window_extent(renderer)
|
|
971
|
+
x0, x1, y0, y1 = float(box.x0), float(box.x1), float(box.y0), float(box.y1)
|
|
972
|
+
|
|
973
|
+
def _spine_extent(names: tuple[str, ...]) -> Any:
|
|
974
|
+
for name in names:
|
|
975
|
+
spine = ax.spines.get(name)
|
|
976
|
+
if spine is None or not spine.get_visible() or spine.get_linewidth() <= 0:
|
|
977
|
+
continue
|
|
978
|
+
path = spine.get_transform().transform_path(spine.get_path())
|
|
979
|
+
return path.get_extents()
|
|
980
|
+
return None
|
|
981
|
+
|
|
982
|
+
sx = _spine_extent(("bottom", "top"))
|
|
983
|
+
if sx is not None and sx.width > 1.0:
|
|
984
|
+
x0, x1 = max(x0, float(sx.x0)), min(x1, float(sx.x1))
|
|
985
|
+
sy = _spine_extent(("left", "right"))
|
|
986
|
+
if sy is not None and sy.height > 1.0:
|
|
987
|
+
y0, y1 = max(y0, float(sy.y0)), min(y1, float(sy.y1))
|
|
988
|
+
return x0, x1, y0, y1
|
|
989
|
+
|
|
990
|
+
|
|
991
|
+
def _check_lines_past_axes(
|
|
992
|
+
fig: Figure,
|
|
993
|
+
panel_map: dict[int, str],
|
|
994
|
+
*,
|
|
995
|
+
tol_pt: float = 1.5,
|
|
996
|
+
) -> CheckResult:
|
|
997
|
+
"""Fail lines, bands and line collections drawn past their axis lines or the canvas.
|
|
998
|
+
|
|
999
|
+
A full-width reference line (``axhline``) on an axes whose x range was widened for
|
|
1000
|
+
direct labels, or whose spine is trimmed to the data, runs on past the end of the
|
|
1001
|
+
axis into empty space; with ``clip_on=False`` it can leave the figure. Text checks
|
|
1002
|
+
do not see this, so it is checked on the drawn geometry of every ``Line2D``,
|
|
1003
|
+
``LineCollection`` and ``PolyCollection`` (markers, scatter and text excluded).
|
|
1004
|
+
Artists with a gid starting ``mintfig-margin`` (``range_frame`` rugs) are exempt.
|
|
1005
|
+
"""
|
|
1006
|
+
renderer = fig.canvas.get_renderer()
|
|
1007
|
+
px_per_pt = float(fig.dpi) / 72.0
|
|
1008
|
+
canvas = fig.bbox
|
|
1009
|
+
offenders: list[dict[str, Any]] = []
|
|
1010
|
+
for ax in fig.axes:
|
|
1011
|
+
if not ax.get_visible() or not ax.axison:
|
|
1012
|
+
continue
|
|
1013
|
+
sx0, sx1, sy0, sy1 = _axis_line_span(ax, renderer)
|
|
1014
|
+
clip = ax.bbox
|
|
1015
|
+
for artist in [*ax.lines, *ax.collections]:
|
|
1016
|
+
if not artist.get_visible() or artist.get_alpha() == 0:
|
|
1017
|
+
continue
|
|
1018
|
+
if str(artist.get_gid() or "").startswith("mintfig-margin"):
|
|
1019
|
+
continue # deliberate margin marks (range_frame rugs)
|
|
1020
|
+
if isinstance(artist, Line2D):
|
|
1021
|
+
if artist.get_linestyle() in ("None", "", " ") or artist.get_linewidth() <= 0:
|
|
1022
|
+
continue
|
|
1023
|
+
paths = [artist.get_transform().transform_path(artist.get_path())]
|
|
1024
|
+
width_px = float(artist.get_linewidth()) * px_per_pt
|
|
1025
|
+
name = artist.get_label()
|
|
1026
|
+
elif isinstance(artist, (LineCollection, PolyCollection)):
|
|
1027
|
+
tr = artist.get_transform()
|
|
1028
|
+
paths = [tr.transform_path(p) for p in artist.get_paths()]
|
|
1029
|
+
lws = np.atleast_1d(artist.get_linewidths())
|
|
1030
|
+
width_px = float(np.max(lws)) * px_per_pt if lws.size else 0.0
|
|
1031
|
+
name = artist.get_label()
|
|
1032
|
+
else:
|
|
1033
|
+
continue
|
|
1034
|
+
verts = [p.vertices for p in paths if len(p.vertices)]
|
|
1035
|
+
if not verts:
|
|
1036
|
+
continue
|
|
1037
|
+
v = np.concatenate(verts)
|
|
1038
|
+
v = v[np.all(np.isfinite(v), axis=1)]
|
|
1039
|
+
if not v.size:
|
|
1040
|
+
continue
|
|
1041
|
+
if artist.get_clip_on():
|
|
1042
|
+
cb = artist.get_clip_box() or clip
|
|
1043
|
+
v = np.column_stack(
|
|
1044
|
+
[np.clip(v[:, 0], cb.x0, cb.x1), np.clip(v[:, 1], cb.y0, cb.y1)]
|
|
1045
|
+
)
|
|
1046
|
+
tol = tol_pt * px_per_pt + width_px / 2.0
|
|
1047
|
+
over = {
|
|
1048
|
+
"right": float(v[:, 0].max()) - sx1,
|
|
1049
|
+
"left": sx0 - float(v[:, 0].min()),
|
|
1050
|
+
"top": float(v[:, 1].max()) - sy1,
|
|
1051
|
+
"bottom": sy0 - float(v[:, 1].min()),
|
|
1052
|
+
}
|
|
1053
|
+
off_canvas = (
|
|
1054
|
+
float(v[:, 0].max()) > canvas.x1 + tol
|
|
1055
|
+
or float(v[:, 0].min()) < canvas.x0 - tol
|
|
1056
|
+
or float(v[:, 1].max()) > canvas.y1 + tol
|
|
1057
|
+
or float(v[:, 1].min()) < canvas.y0 - tol
|
|
1058
|
+
)
|
|
1059
|
+
bad = {edge: o for edge, o in over.items() if o > tol}
|
|
1060
|
+
if bad or off_canvas:
|
|
1061
|
+
edge, amount = max(bad.items(), key=lambda kv: kv[1]) if bad else ("canvas", 0.0)
|
|
1062
|
+
label = name if name and not str(name).startswith("_") else type(artist).__name__
|
|
1063
|
+
offenders.append(
|
|
1064
|
+
{
|
|
1065
|
+
"artist": str(label),
|
|
1066
|
+
"panel": panel_map.get(id(ax)),
|
|
1067
|
+
"edge": edge,
|
|
1068
|
+
"overflow_pt": round(amount / px_per_pt, 1),
|
|
1069
|
+
"off_canvas": off_canvas,
|
|
1070
|
+
}
|
|
1071
|
+
)
|
|
1072
|
+
if offenders:
|
|
1073
|
+
sample = ", ".join(
|
|
1074
|
+
f"{o['artist']} ({'off the canvas' if o['off_canvas'] else o['edge']} "
|
|
1075
|
+
f"+{o['overflow_pt']} pt)" for o in offenders[:4]
|
|
1076
|
+
)
|
|
1077
|
+
return CheckResult(
|
|
1078
|
+
rule="line_past_axis",
|
|
1079
|
+
status="fail",
|
|
1080
|
+
message=f"{len(offenders)} line(s) or band(s) run past their axis line: {sample}",
|
|
1081
|
+
details={"offenders": offenders[:20]},
|
|
1082
|
+
panel=next((o["panel"] for o in offenders if o["panel"]), None),
|
|
1083
|
+
elements=[o["artist"] for o in offenders[:6]],
|
|
1084
|
+
fix_hint=(
|
|
1085
|
+
"Bound reference lines to the data range (ax.hlines(y, x0, x1) instead of "
|
|
1086
|
+
"ax.axhline, or draw them before mint.direct_labels, which bounds them), keep "
|
|
1087
|
+
"curves and bands inside the axis range, and leave clip_on on."
|
|
1088
|
+
),
|
|
1089
|
+
panels=_distinct_panels(o["panel"] for o in offenders),
|
|
1090
|
+
element_locations=_locate((o["artist"], o["panel"]) for o in offenders[:6]),
|
|
1091
|
+
)
|
|
1092
|
+
return CheckResult(
|
|
1093
|
+
rule="line_past_axis",
|
|
1094
|
+
status="pass",
|
|
1095
|
+
message="Every line and band stays within its axis lines and the canvas",
|
|
1096
|
+
)
|
|
1097
|
+
|
|
1098
|
+
|
|
1099
|
+
def _has_visible_rgba(color: Any) -> bool:
|
|
1100
|
+
"""Return True if a Matplotlib color specification has non-zero alpha."""
|
|
1101
|
+
if color is None:
|
|
1102
|
+
return False
|
|
1103
|
+
if isinstance(color, str) and color.lower() in {"none", ""}:
|
|
1104
|
+
return False
|
|
1105
|
+
try:
|
|
1106
|
+
rgba = to_rgba(color)
|
|
1107
|
+
return float(rgba[3]) > 0.0
|
|
1108
|
+
except (TypeError, ValueError):
|
|
1109
|
+
return True
|
|
1110
|
+
|
|
1111
|
+
|
|
1112
|
+
def _check_hairline_strokes(
|
|
1113
|
+
fig: Figure,
|
|
1114
|
+
spec: JournalSpec,
|
|
1115
|
+
panel_map: dict[int, str],
|
|
1116
|
+
) -> CheckResult:
|
|
1117
|
+
"""Detect visible non-zero strokes thinner than the journal minimum linewidth.
|
|
1118
|
+
|
|
1119
|
+
Skips invisible artists, zero-alpha or zero-linewidth strokes, and scatter
|
|
1120
|
+
``PathCollection`` marker outlines to avoid false positives.
|
|
1121
|
+
"""
|
|
1122
|
+
min_lw = spec.min_linewidth_pt
|
|
1123
|
+
eps = 1e-6
|
|
1124
|
+
violations: list[dict[str, Any]] = []
|
|
1125
|
+
|
|
1126
|
+
# 1. Spines
|
|
1127
|
+
for ax in fig.axes:
|
|
1128
|
+
if not ax.get_visible():
|
|
1129
|
+
continue
|
|
1130
|
+
panel = _artist_panel(ax, panel_map)
|
|
1131
|
+
for name, spine in ax.spines.items():
|
|
1132
|
+
if not isinstance(spine, Spine) or not spine.get_visible():
|
|
1133
|
+
continue
|
|
1134
|
+
alpha = spine.get_alpha()
|
|
1135
|
+
if alpha is not None and alpha <= 0:
|
|
1136
|
+
continue
|
|
1137
|
+
if not _has_visible_rgba(spine.get_edgecolor()):
|
|
1138
|
+
continue
|
|
1139
|
+
lw = float(spine.get_linewidth())
|
|
1140
|
+
if 0.0 < lw < min_lw - eps:
|
|
1141
|
+
violations.append(
|
|
1142
|
+
{
|
|
1143
|
+
"artist": f"spine:{name}",
|
|
1144
|
+
"linewidth_pt": round(lw, 3),
|
|
1145
|
+
"panel": panel,
|
|
1146
|
+
}
|
|
1147
|
+
)
|
|
1148
|
+
|
|
1149
|
+
# 2. Line2D artists (data lines, errorbars, ticks, brackets)
|
|
1150
|
+
for line in fig.findobj(Line2D):
|
|
1151
|
+
if not line.get_visible():
|
|
1152
|
+
continue
|
|
1153
|
+
if line.axes is not None and not line.axes.get_visible():
|
|
1154
|
+
continue
|
|
1155
|
+
alpha = line.get_alpha()
|
|
1156
|
+
if alpha is not None and alpha <= 0:
|
|
1157
|
+
continue
|
|
1158
|
+
ls = line.get_linestyle()
|
|
1159
|
+
if ls in ("None", "none", "", " "):
|
|
1160
|
+
continue
|
|
1161
|
+
if not _has_visible_rgba(line.get_color()):
|
|
1162
|
+
continue
|
|
1163
|
+
xdata = line.get_xdata(orig=False)
|
|
1164
|
+
if xdata is not None and len(xdata) == 0:
|
|
1165
|
+
continue
|
|
1166
|
+
lw = float(line.get_linewidth())
|
|
1167
|
+
if 0.0 < lw < min_lw - eps:
|
|
1168
|
+
label = line.get_label()
|
|
1169
|
+
desc = f"Line2D({label})" if label and not label.startswith("_") else "Line2D"
|
|
1170
|
+
violations.append(
|
|
1171
|
+
{
|
|
1172
|
+
"artist": desc,
|
|
1173
|
+
"linewidth_pt": round(lw, 3),
|
|
1174
|
+
"panel": _artist_panel(line, panel_map),
|
|
1175
|
+
}
|
|
1176
|
+
)
|
|
1177
|
+
|
|
1178
|
+
# 3. LineCollection and PolyCollection strokes (explicitly excluding PathCollection scatter)
|
|
1179
|
+
for col in fig.findobj(Collection):
|
|
1180
|
+
if not isinstance(col, (LineCollection, PolyCollection)):
|
|
1181
|
+
continue
|
|
1182
|
+
if not col.get_visible():
|
|
1183
|
+
continue
|
|
1184
|
+
if col.axes is not None and not col.axes.get_visible():
|
|
1185
|
+
continue
|
|
1186
|
+
alpha = col.get_alpha()
|
|
1187
|
+
if alpha is not None and alpha <= 0:
|
|
1188
|
+
continue
|
|
1189
|
+
|
|
1190
|
+
if isinstance(col, LineCollection):
|
|
1191
|
+
colors = col.get_colors()
|
|
1192
|
+
has_stroke_color = len(colors) > 0 and bool(np.any(colors[:, 3] > 0))
|
|
1193
|
+
else:
|
|
1194
|
+
edgecolors = col.get_edgecolors()
|
|
1195
|
+
has_stroke_color = len(edgecolors) > 0 and bool(np.any(edgecolors[:, 3] > 0))
|
|
1196
|
+
|
|
1197
|
+
if not has_stroke_color:
|
|
1198
|
+
continue
|
|
1199
|
+
|
|
1200
|
+
lws = col.get_linewidths()
|
|
1201
|
+
for lw_val in np.atleast_1d(lws):
|
|
1202
|
+
lw = float(lw_val)
|
|
1203
|
+
if 0.0 < lw < min_lw - eps:
|
|
1204
|
+
violations.append(
|
|
1205
|
+
{
|
|
1206
|
+
"artist": type(col).__name__,
|
|
1207
|
+
"linewidth_pt": round(lw, 3),
|
|
1208
|
+
"panel": _artist_panel(col, panel_map),
|
|
1209
|
+
}
|
|
1210
|
+
)
|
|
1211
|
+
break
|
|
1212
|
+
|
|
1213
|
+
if violations:
|
|
1214
|
+
min_found = min(v["linewidth_pt"] for v in violations)
|
|
1215
|
+
sample = ", ".join(
|
|
1216
|
+
f"{v['artist']} ({v['linewidth_pt']} pt)" for v in violations[:4]
|
|
1217
|
+
)
|
|
1218
|
+
panel = next((v["panel"] for v in violations if v["panel"]), None)
|
|
1219
|
+
elements = [f"{v['artist']} ({v['linewidth_pt']} pt)" for v in violations[:6]]
|
|
1220
|
+
return CheckResult(
|
|
1221
|
+
rule="hairline_strokes",
|
|
1222
|
+
status="warn",
|
|
1223
|
+
message=(
|
|
1224
|
+
f"{len(violations)} stroke(s) below {min_lw:.2f} pt minimum "
|
|
1225
|
+
f"(thinnest {min_found:.2f} pt): {sample}"
|
|
1226
|
+
),
|
|
1227
|
+
details={"min_linewidth_pt": min_lw, "violations": violations[:20]},
|
|
1228
|
+
panel=panel,
|
|
1229
|
+
elements=elements,
|
|
1230
|
+
fix_hint=(
|
|
1231
|
+
f"Increase linewidth from {min_found:.2f} pt to >= {min_lw:.2f} pt "
|
|
1232
|
+
f"(recommended axes={spec.axes_linewidth_pt:.2f} pt, "
|
|
1233
|
+
f"data={spec.data_linewidth_pt:.2f} pt)."
|
|
1234
|
+
),
|
|
1235
|
+
panels=_distinct_panels(v["panel"] for v in violations),
|
|
1236
|
+
element_locations=_locate(
|
|
1237
|
+
zip(elements, (v["panel"] for v in violations[:6]), strict=True)
|
|
1238
|
+
),
|
|
1239
|
+
)
|
|
1240
|
+
|
|
1241
|
+
return CheckResult(
|
|
1242
|
+
rule="hairline_strokes",
|
|
1243
|
+
status="pass",
|
|
1244
|
+
message=f"All visible strokes meet >= {min_lw:.2f} pt print minimum",
|
|
1245
|
+
details={"min_linewidth_pt": min_lw},
|
|
1246
|
+
)
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
def _maps_data_to_color(mappable: ScalarMappable) -> bool:
|
|
1250
|
+
"""Return True if ``mappable`` actually maps scalar data through its colormap.
|
|
1251
|
+
|
|
1252
|
+
A ScalarMappable always carries a colormap (``rcParams['image.cmap']`` by
|
|
1253
|
+
default), even a solid-colour ``scatter(color=...)`` or an RGB(A) ``imshow``
|
|
1254
|
+
whose colormap is never drawn. Only artists with a non-empty scalar data
|
|
1255
|
+
array use the colormap.
|
|
1256
|
+
"""
|
|
1257
|
+
try:
|
|
1258
|
+
arr = mappable.get_array()
|
|
1259
|
+
except (AttributeError, TypeError, ValueError):
|
|
1260
|
+
return False
|
|
1261
|
+
if arr is None:
|
|
1262
|
+
return False
|
|
1263
|
+
size = int(np.size(arr))
|
|
1264
|
+
if size == 0:
|
|
1265
|
+
return False
|
|
1266
|
+
if np.ndim(arr) >= 3:
|
|
1267
|
+
# RGB(A) image data is drawn directly; the colormap is not applied.
|
|
1268
|
+
return False
|
|
1269
|
+
# A fully masked array draws nothing through the colormap.
|
|
1270
|
+
return not (np.ma.isMaskedArray(arr) and bool(np.ma.getmaskarray(arr).all()))
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
def _check_colormaps(fig: Figure, panel_map: dict[int, str]) -> CheckResult:
|
|
1274
|
+
"""Reject banned non-perceptual colormap names (jet, rainbow, hsv, etc.).
|
|
1275
|
+
|
|
1276
|
+
Only artists that map data to colour are considered. This is a name check
|
|
1277
|
+
against a blocklist; it does not measure perceptual uniformity.
|
|
1278
|
+
"""
|
|
1279
|
+
found_cmaps: set[str] = set()
|
|
1280
|
+
banned_hits: list[dict[str, Any]] = []
|
|
1281
|
+
|
|
1282
|
+
seen_ids: set[int] = set()
|
|
1283
|
+
mappables: list[ScalarMappable] = list(
|
|
1284
|
+
fig.findobj(lambda artist: isinstance(artist, ScalarMappable))
|
|
1285
|
+
)
|
|
1286
|
+
for ax in fig.axes:
|
|
1287
|
+
for obj in list(ax.images) + list(ax.collections):
|
|
1288
|
+
if isinstance(obj, ScalarMappable):
|
|
1289
|
+
mappables.append(obj)
|
|
1290
|
+
|
|
1291
|
+
for mappable in mappables:
|
|
1292
|
+
mid = id(mappable)
|
|
1293
|
+
if mid in seen_ids:
|
|
1294
|
+
continue
|
|
1295
|
+
seen_ids.add(mid)
|
|
1296
|
+
if hasattr(mappable, "get_visible") and not mappable.get_visible():
|
|
1297
|
+
continue
|
|
1298
|
+
if not _maps_data_to_color(mappable):
|
|
1299
|
+
continue
|
|
1300
|
+
|
|
1301
|
+
cmap = mappable.get_cmap()
|
|
1302
|
+
if cmap is None:
|
|
1303
|
+
continue
|
|
1304
|
+
cmap_name = str(cmap.name)
|
|
1305
|
+
base_name = cmap_name.removesuffix("_r")
|
|
1306
|
+
found_cmaps.add(cmap_name)
|
|
1307
|
+
|
|
1308
|
+
if base_name.lower() in BANNED_COLORMAPS:
|
|
1309
|
+
banned_hits.append(
|
|
1310
|
+
{
|
|
1311
|
+
"artist": type(mappable).__name__,
|
|
1312
|
+
"colormap": cmap_name,
|
|
1313
|
+
"panel": _artist_panel(mappable, panel_map),
|
|
1314
|
+
}
|
|
1315
|
+
)
|
|
1316
|
+
|
|
1317
|
+
if banned_hits:
|
|
1318
|
+
bad_names = sorted({h["colormap"] for h in banned_hits})
|
|
1319
|
+
panel = next((h["panel"] for h in banned_hits if h["panel"]), None)
|
|
1320
|
+
# One location per distinct (colormap, panel) pair, in element order.
|
|
1321
|
+
located: list[tuple[str, str | None]] = []
|
|
1322
|
+
for name in bad_names:
|
|
1323
|
+
for hit in banned_hits:
|
|
1324
|
+
pair = (name, hit["panel"])
|
|
1325
|
+
if hit["colormap"] == name and pair not in located:
|
|
1326
|
+
located.append(pair)
|
|
1327
|
+
return CheckResult(
|
|
1328
|
+
rule="colormaps",
|
|
1329
|
+
status="fail",
|
|
1330
|
+
message=(
|
|
1331
|
+
f"Banned non-perceptual colormap(s) detected: {', '.join(bad_names)} "
|
|
1332
|
+
"(use viridis, magma, cividis, or plasma)"
|
|
1333
|
+
),
|
|
1334
|
+
details={"banned": banned_hits, "colormaps": sorted(found_cmaps)},
|
|
1335
|
+
panel=panel,
|
|
1336
|
+
elements=bad_names,
|
|
1337
|
+
fix_hint=(
|
|
1338
|
+
f"Replace cmap={bad_names[0]!r} with 'viridis', 'magma', or 'cividis'."
|
|
1339
|
+
),
|
|
1340
|
+
panels=_distinct_panels(h["panel"] for h in banned_hits),
|
|
1341
|
+
element_locations=_locate(located),
|
|
1342
|
+
)
|
|
1343
|
+
|
|
1344
|
+
if found_cmaps:
|
|
1345
|
+
msg = (
|
|
1346
|
+
f"Name check only: no banned rainbow colormap among {len(found_cmaps)} in use "
|
|
1347
|
+
f"({', '.join(sorted(found_cmaps))}); perceptual uniformity not measured"
|
|
1348
|
+
)
|
|
1349
|
+
else:
|
|
1350
|
+
msg = "No colormapped data artists found (pass)"
|
|
1351
|
+
|
|
1352
|
+
return CheckResult(
|
|
1353
|
+
rule="colormaps",
|
|
1354
|
+
status="pass",
|
|
1355
|
+
message=msg,
|
|
1356
|
+
details={"colormaps": sorted(found_cmaps), "method": "name_blocklist"},
|
|
1357
|
+
)
|
|
1358
|
+
|
|
1359
|
+
|
|
1360
|
+
def _check_vector_fonts(spec: JournalSpec, fig: Figure | None = None) -> CheckResult:
|
|
1361
|
+
"""Predict, from the *current* rcParams, whether a plain save emits editable fonts.
|
|
1362
|
+
|
|
1363
|
+
This is only a prediction about a future ``fig.savefig``: ``pdf.fonttype`` and
|
|
1364
|
+
``svg.fonttype`` are read at save time, and mintfig's own exporters
|
|
1365
|
+
(``mint.save_figure``, ``plate.save``, ``mintfig run --bundle``) always force
|
|
1366
|
+
``pdf.fonttype=42`` / ``svg.fonttype='none'``. The authoritative check is
|
|
1367
|
+
:func:`preflight_pdf` on the exported file.
|
|
1368
|
+
|
|
1369
|
+
* rcParams already editable -> pass.
|
|
1370
|
+
* Figure built by mintfig (``mint.Plate`` / ``mint.figure``, tagged with
|
|
1371
|
+
``_mintfig_journal``) -> pass: its export path forces Type 42, so a warning
|
|
1372
|
+
would only send an agent chasing a non-problem.
|
|
1373
|
+
* Any other figure -> warn, because a plain ``fig.savefig`` with these
|
|
1374
|
+
rcParams really would embed Type 3 / outlined text.
|
|
1375
|
+
"""
|
|
1376
|
+
pdf_ft = plt.rcParams.get("pdf.fonttype")
|
|
1377
|
+
svg_ft = plt.rcParams.get("svg.fonttype")
|
|
1378
|
+
issues: list[str] = []
|
|
1379
|
+
if pdf_ft != 42:
|
|
1380
|
+
issues.append(f"pdf.fonttype={pdf_ft!r} (expected 42)")
|
|
1381
|
+
if svg_ft != "none":
|
|
1382
|
+
issues.append(f"svg.fonttype={svg_ft!r} (expected 'none')")
|
|
1383
|
+
|
|
1384
|
+
details: dict[str, Any] = {
|
|
1385
|
+
"pdf.fonttype": pdf_ft,
|
|
1386
|
+
"svg.fonttype": svg_ft,
|
|
1387
|
+
"basis": "current_rcparams",
|
|
1388
|
+
"authoritative": False,
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
if not issues:
|
|
1392
|
+
return CheckResult(
|
|
1393
|
+
rule="vector_fonts",
|
|
1394
|
+
status="pass",
|
|
1395
|
+
message="Editable vector fonts active (pdf.fonttype=42, svg.fonttype='none')",
|
|
1396
|
+
details=details,
|
|
1397
|
+
)
|
|
1398
|
+
|
|
1399
|
+
mintfig_journal = getattr(fig, "_mintfig_journal", None) if fig is not None else None
|
|
1400
|
+
if mintfig_journal:
|
|
1401
|
+
details["basis"] = "mintfig_export"
|
|
1402
|
+
return CheckResult(
|
|
1403
|
+
rule="vector_fonts",
|
|
1404
|
+
status="pass",
|
|
1405
|
+
message=(
|
|
1406
|
+
"mintfig-built figure: mint.save_figure / plate.save / mintfig run --bundle "
|
|
1407
|
+
"force pdf.fonttype=42 and svg.fonttype='none' "
|
|
1408
|
+
f"(current rcParams: {'; '.join(issues)} only affect a raw fig.savefig)"
|
|
1409
|
+
),
|
|
1410
|
+
details=details,
|
|
1411
|
+
)
|
|
1412
|
+
|
|
1413
|
+
return CheckResult(
|
|
1414
|
+
rule="vector_fonts",
|
|
1415
|
+
status="warn",
|
|
1416
|
+
message=(
|
|
1417
|
+
f"Current rcParams would embed non-editable text on a plain fig.savefig: "
|
|
1418
|
+
f"{'; '.join(issues)}. Exports through mint.save_figure / plate.save / "
|
|
1419
|
+
"mintfig run --bundle force Type 42 regardless; preflight_pdf on the "
|
|
1420
|
+
"exported PDF is authoritative"
|
|
1421
|
+
),
|
|
1422
|
+
details=details,
|
|
1423
|
+
panel=None,
|
|
1424
|
+
elements=issues,
|
|
1425
|
+
fix_hint=(
|
|
1426
|
+
"No plotting change needed if you export with mint.save_figure(...), plate.save(...) "
|
|
1427
|
+
"or mintfig run --bundle (they force pdf.fonttype=42). If you save with plain "
|
|
1428
|
+
f"fig.savefig, call mint.apply({spec.name!r}) or set "
|
|
1429
|
+
"plt.rcParams['pdf.fonttype'] = 42 and plt.rcParams['svg.fonttype'] = 'none' "
|
|
1430
|
+
"before saving."
|
|
1431
|
+
),
|
|
1432
|
+
)
|
|
1433
|
+
|
|
1434
|
+
|
|
1435
|
+
_LAYOUT_COLLAPSE_PATTERNS = (
|
|
1436
|
+
"constrained_layout not applied",
|
|
1437
|
+
"collapsed to zero",
|
|
1438
|
+
"tight_layout not applied",
|
|
1439
|
+
)
|
|
1440
|
+
|
|
1441
|
+
_LINESTYLE_CANON = {
|
|
1442
|
+
"-": "-",
|
|
1443
|
+
"solid": "-",
|
|
1444
|
+
"--": "--",
|
|
1445
|
+
"dashed": "--",
|
|
1446
|
+
":": ":",
|
|
1447
|
+
"dotted": ":",
|
|
1448
|
+
"-.": "-.",
|
|
1449
|
+
"dashdot": "-.",
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
|
|
1453
|
+
def _normalize_linestyle(ls: Any) -> str:
|
|
1454
|
+
if isinstance(ls, tuple):
|
|
1455
|
+
return str(ls)
|
|
1456
|
+
return _LINESTYLE_CANON.get(str(ls).strip().lower(), str(ls))
|
|
1457
|
+
|
|
1458
|
+
|
|
1459
|
+
def _normalize_marker(marker: Any) -> str:
|
|
1460
|
+
if marker is None:
|
|
1461
|
+
return ""
|
|
1462
|
+
s = str(marker).strip()
|
|
1463
|
+
return "" if s in {"", "None", "none", " "} else s
|
|
1464
|
+
|
|
1465
|
+
|
|
1466
|
+
def _check_layout_collapse(
|
|
1467
|
+
fig: Figure,
|
|
1468
|
+
layout_warnings: list[str],
|
|
1469
|
+
panel_map: dict[int, str],
|
|
1470
|
+
) -> CheckResult:
|
|
1471
|
+
"""Detect collapsed constrained/tight layouts or zero-size visible axes."""
|
|
1472
|
+
collapsed_axes: list[dict[str, Any]] = []
|
|
1473
|
+
for ax in fig.axes:
|
|
1474
|
+
if not ax.get_visible():
|
|
1475
|
+
continue
|
|
1476
|
+
bbox = ax.bbox
|
|
1477
|
+
w_px = float(bbox.width)
|
|
1478
|
+
h_px = float(bbox.height)
|
|
1479
|
+
if not (np.isfinite(w_px) and np.isfinite(h_px)) or w_px < 4.0 or h_px < 4.0:
|
|
1480
|
+
panel = _artist_panel(ax, panel_map)
|
|
1481
|
+
collapsed_axes.append(
|
|
1482
|
+
{
|
|
1483
|
+
"panel": panel,
|
|
1484
|
+
"width_px": round(w_px, 1) if np.isfinite(w_px) else None,
|
|
1485
|
+
"height_px": round(h_px, 1) if np.isfinite(h_px) else None,
|
|
1486
|
+
}
|
|
1487
|
+
)
|
|
1488
|
+
|
|
1489
|
+
if layout_warnings or collapsed_axes:
|
|
1490
|
+
panels = _distinct_panels(item["panel"] for item in collapsed_axes)
|
|
1491
|
+
elements: list[str] = []
|
|
1492
|
+
located: list[tuple[str, str | None]] = []
|
|
1493
|
+
for item in collapsed_axes[:6]:
|
|
1494
|
+
desc = (
|
|
1495
|
+
f"{item['panel'] or 'axes'} ({item['width_px']}x{item['height_px']} px)"
|
|
1496
|
+
)
|
|
1497
|
+
elements.append(desc)
|
|
1498
|
+
located.append((desc, item["panel"]))
|
|
1499
|
+
for msg in layout_warnings[:3]:
|
|
1500
|
+
short = msg.strip().replace("\n", " ")[:72]
|
|
1501
|
+
if short not in elements:
|
|
1502
|
+
elements.append(short)
|
|
1503
|
+
located.append((short, panels[0] if panels else None))
|
|
1504
|
+
|
|
1505
|
+
reasons: list[str] = []
|
|
1506
|
+
if layout_warnings:
|
|
1507
|
+
reasons.append(f"{len(layout_warnings)} layout-collapse warning(s)")
|
|
1508
|
+
if collapsed_axes:
|
|
1509
|
+
reasons.append(f"{len(collapsed_axes)} collapsed axes (< 4 px)")
|
|
1510
|
+
return CheckResult(
|
|
1511
|
+
rule="layout_collapse",
|
|
1512
|
+
status="fail",
|
|
1513
|
+
message=f"Layout engine failed to fit panels: {', '.join(reasons)}",
|
|
1514
|
+
details={
|
|
1515
|
+
"warnings": layout_warnings[:10],
|
|
1516
|
+
"collapsed_axes": collapsed_axes[:10],
|
|
1517
|
+
},
|
|
1518
|
+
panel=panels[0] if panels else None,
|
|
1519
|
+
elements=elements,
|
|
1520
|
+
fix_hint=(
|
|
1521
|
+
"Matplotlib could not fit constrained_layout (axes collapsed). "
|
|
1522
|
+
"Use uniform mosaic column splits, reduce gap_mm, shorten long y-axis "
|
|
1523
|
+
"labels, or increase Plate(..., height_mm=...)."
|
|
1524
|
+
),
|
|
1525
|
+
panels=panels,
|
|
1526
|
+
element_locations=_locate(located),
|
|
1527
|
+
)
|
|
1528
|
+
|
|
1529
|
+
return CheckResult(
|
|
1530
|
+
rule="layout_collapse",
|
|
1531
|
+
status="pass",
|
|
1532
|
+
message="All visible panels laid out without constrained_layout collapse",
|
|
1533
|
+
details={"axes_count": sum(1 for ax in fig.axes if ax.get_visible())},
|
|
1534
|
+
)
|
|
1535
|
+
|
|
1536
|
+
|
|
1537
|
+
def _check_color_separation(
|
|
1538
|
+
fig: Figure,
|
|
1539
|
+
panel_map: dict[int, str],
|
|
1540
|
+
) -> CheckResult:
|
|
1541
|
+
"""Clarity warning: flag same-style labeled series indistinguishable in CVD/grayscale."""
|
|
1542
|
+
confusable: list[dict[str, Any]] = []
|
|
1543
|
+
|
|
1544
|
+
for ax in fig.axes:
|
|
1545
|
+
if not ax.get_visible() or getattr(ax, "_colorbar", None) is not None:
|
|
1546
|
+
continue
|
|
1547
|
+
series: list[tuple[str, str, str, str, np.ndarray]] = []
|
|
1548
|
+
seen_labels: set[str] = set()
|
|
1549
|
+
for line in ax.get_lines():
|
|
1550
|
+
if not line.get_visible():
|
|
1551
|
+
continue
|
|
1552
|
+
alpha = line.get_alpha()
|
|
1553
|
+
if alpha is not None and alpha <= 0:
|
|
1554
|
+
continue
|
|
1555
|
+
ls = _normalize_linestyle(line.get_linestyle())
|
|
1556
|
+
if ls in {"none", "", " "}:
|
|
1557
|
+
continue
|
|
1558
|
+
label = str(line.get_label() or "").strip()
|
|
1559
|
+
if not label or label.startswith("_") or label in seen_labels:
|
|
1560
|
+
continue
|
|
1561
|
+
try:
|
|
1562
|
+
rgb = np.array(to_rgb(line.get_color()), dtype=np.float64)
|
|
1563
|
+
hex_c = to_hex(rgb)
|
|
1564
|
+
except (TypeError, ValueError):
|
|
1565
|
+
continue
|
|
1566
|
+
seen_labels.add(label)
|
|
1567
|
+
series.append((label, hex_c, ls, _normalize_marker(line.get_marker()), rgb))
|
|
1568
|
+
|
|
1569
|
+
if len(series) < 2:
|
|
1570
|
+
continue
|
|
1571
|
+
|
|
1572
|
+
panel = _artist_panel(ax, panel_map)
|
|
1573
|
+
rgb_stack = np.stack([item[4] for item in series], axis=0)[np.newaxis, :, :]
|
|
1574
|
+
gray = simulate_cvd(rgb_stack, "grayscale")[0, :, 0]
|
|
1575
|
+
deut = simulate_cvd(rgb_stack, "deuteranopia")[0]
|
|
1576
|
+
prot = simulate_cvd(rgb_stack, "protanopia")[0]
|
|
1577
|
+
|
|
1578
|
+
for i in range(len(series)):
|
|
1579
|
+
for j in range(i + 1, len(series)):
|
|
1580
|
+
lbl_a, hex_a, ls_a, mk_a, _ = series[i]
|
|
1581
|
+
lbl_b, hex_b, ls_b, mk_b, _ = series[j]
|
|
1582
|
+
# Skip when lines already carry distinct linestyle or marker encoding.
|
|
1583
|
+
if ls_a != ls_b or mk_a != mk_b:
|
|
1584
|
+
continue
|
|
1585
|
+
gray_diff = float(abs(gray[i] - gray[j]))
|
|
1586
|
+
deut_dist = float(np.linalg.norm(deut[i] - deut[j]))
|
|
1587
|
+
prot_dist = float(np.linalg.norm(prot[i] - prot[j]))
|
|
1588
|
+
min_cvd = min(deut_dist, prot_dist)
|
|
1589
|
+
if gray_diff < 0.05 or min_cvd < 0.12:
|
|
1590
|
+
confusable.append(
|
|
1591
|
+
{
|
|
1592
|
+
"panel": panel,
|
|
1593
|
+
"series_a": lbl_a,
|
|
1594
|
+
"hex_a": hex_a,
|
|
1595
|
+
"series_b": lbl_b,
|
|
1596
|
+
"hex_b": hex_b,
|
|
1597
|
+
"gray_delta": round(gray_diff, 3),
|
|
1598
|
+
"min_cvd_dist": round(min_cvd, 3),
|
|
1599
|
+
}
|
|
1600
|
+
)
|
|
1601
|
+
|
|
1602
|
+
if confusable:
|
|
1603
|
+
first = confusable[0]
|
|
1604
|
+
sample = ", ".join(
|
|
1605
|
+
f"'{c['series_a']}' ({c['hex_a']}) vs '{c['series_b']}' ({c['hex_b']})"
|
|
1606
|
+
for c in confusable[:3]
|
|
1607
|
+
)
|
|
1608
|
+
elements = [f"{c['series_a']} vs {c['series_b']}" for c in confusable[:6]]
|
|
1609
|
+
panels = _distinct_panels(c["panel"] for c in confusable)
|
|
1610
|
+
where = f" in panel '{first['panel']}'" if first["panel"] else ""
|
|
1611
|
+
return CheckResult(
|
|
1612
|
+
rule="color_separation",
|
|
1613
|
+
status="warn",
|
|
1614
|
+
message=(
|
|
1615
|
+
f"{len(confusable)} same-style series pair(s) have low CVD/grayscale "
|
|
1616
|
+
f"separation: {sample}"
|
|
1617
|
+
),
|
|
1618
|
+
details={"confusable_pairs": confusable[:20]},
|
|
1619
|
+
panel=first["panel"],
|
|
1620
|
+
elements=elements,
|
|
1621
|
+
fix_hint=(
|
|
1622
|
+
f"Distinguish '{first['series_a']}' and '{first['series_b']}'{where} "
|
|
1623
|
+
"using a dashed linestyle (ls='--'), distinct marker, or high-contrast "
|
|
1624
|
+
"palette (palette='okabe_ito')."
|
|
1625
|
+
),
|
|
1626
|
+
panels=panels,
|
|
1627
|
+
element_locations=_locate(
|
|
1628
|
+
zip(elements, (c["panel"] for c in confusable[:6]), strict=True)
|
|
1629
|
+
),
|
|
1630
|
+
)
|
|
1631
|
+
|
|
1632
|
+
return CheckResult(
|
|
1633
|
+
rule="color_separation",
|
|
1634
|
+
status="pass",
|
|
1635
|
+
message="Labeled line series are distinguishable under CVD and grayscale",
|
|
1636
|
+
details={},
|
|
1637
|
+
)
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
def _check_clarity_metadata(
|
|
1641
|
+
fig: Figure,
|
|
1642
|
+
panel_map: dict[int, str],
|
|
1643
|
+
) -> CheckResult:
|
|
1644
|
+
"""Clarity warning: flag colormapped panels without colorbars or completely unlabeled axes."""
|
|
1645
|
+
missing_cbars: list[dict[str, Any]] = []
|
|
1646
|
+
unlabeled_axes: list[dict[str, Any]] = []
|
|
1647
|
+
|
|
1648
|
+
for ax in fig.axes:
|
|
1649
|
+
if not ax.get_visible():
|
|
1650
|
+
continue
|
|
1651
|
+
if getattr(ax, "_colorbar", None) is not None or ax.get_label() == "<colorbar>":
|
|
1652
|
+
continue
|
|
1653
|
+
if getattr(ax, "_mintfig_decorative", False):
|
|
1654
|
+
continue
|
|
1655
|
+
pos = ax.get_position()
|
|
1656
|
+
is_inset = getattr(ax, "_parent_axes", None) is not None
|
|
1657
|
+
panel = _artist_panel(ax, panel_map)
|
|
1658
|
+
|
|
1659
|
+
# 1. Colormapped data panel missing a colorbar (skip thin decorative strips & insets).
|
|
1660
|
+
if not is_inset and pos.height >= 0.12 and pos.width >= 0.08:
|
|
1661
|
+
scalar_mappables = [
|
|
1662
|
+
obj
|
|
1663
|
+
for obj in list(ax.images) + list(ax.collections)
|
|
1664
|
+
if isinstance(obj, ScalarMappable)
|
|
1665
|
+
and obj.get_visible()
|
|
1666
|
+
and _maps_data_to_color(obj)
|
|
1667
|
+
]
|
|
1668
|
+
if scalar_mappables and all(
|
|
1669
|
+
getattr(m, "colorbar", None) is None for m in scalar_mappables
|
|
1670
|
+
):
|
|
1671
|
+
missing_cbars.append(
|
|
1672
|
+
{
|
|
1673
|
+
"panel": panel,
|
|
1674
|
+
"colormap": str(scalar_mappables[0].get_cmap().name),
|
|
1675
|
+
}
|
|
1676
|
+
)
|
|
1677
|
+
|
|
1678
|
+
# 2. Primary quantitative plot axes missing BOTH xlabel and ylabel.
|
|
1679
|
+
if (
|
|
1680
|
+
not is_inset
|
|
1681
|
+
and ax.axison
|
|
1682
|
+
and not ax.images
|
|
1683
|
+
and not getattr(ax, "_mintfig_has_scalebar", False)
|
|
1684
|
+
and (ax.lines or ax.collections or ax.patches)
|
|
1685
|
+
):
|
|
1686
|
+
# A hidden axis draws no tick labels even though each label still
|
|
1687
|
+
# reports itself visible, so it cannot count as an unlabeled scale.
|
|
1688
|
+
has_xticks = ax.xaxis.get_visible() and any(
|
|
1689
|
+
t.label1.get_visible() and t.label1.get_text().strip()
|
|
1690
|
+
for t in ax.xaxis.get_major_ticks()
|
|
1691
|
+
)
|
|
1692
|
+
has_yticks = ax.yaxis.get_visible() and any(
|
|
1693
|
+
t.label1.get_visible() and t.label1.get_text().strip()
|
|
1694
|
+
for t in ax.yaxis.get_major_ticks()
|
|
1695
|
+
)
|
|
1696
|
+
# mint.explain() names the measure in a horizontal line above the
|
|
1697
|
+
# plot instead of a rotated axis label.
|
|
1698
|
+
named_above = bool(getattr(ax, "_mintfig_measure_label", None))
|
|
1699
|
+
if (
|
|
1700
|
+
has_xticks
|
|
1701
|
+
and has_yticks
|
|
1702
|
+
and not named_above
|
|
1703
|
+
and not ax.get_xlabel().strip()
|
|
1704
|
+
and not ax.get_ylabel().strip()
|
|
1705
|
+
):
|
|
1706
|
+
unlabeled_axes.append({"panel": panel})
|
|
1707
|
+
|
|
1708
|
+
if missing_cbars or unlabeled_axes:
|
|
1709
|
+
parts: list[str] = []
|
|
1710
|
+
hints: list[str] = []
|
|
1711
|
+
elements: list[str] = []
|
|
1712
|
+
located: list[tuple[str, str | None]] = []
|
|
1713
|
+
|
|
1714
|
+
if missing_cbars:
|
|
1715
|
+
c_panels = ", ".join(c["panel"] or "axes" for c in missing_cbars[:4])
|
|
1716
|
+
parts.append(
|
|
1717
|
+
f"{len(missing_cbars)} colormapped panel(s) lack a colorbar ({c_panels})"
|
|
1718
|
+
)
|
|
1719
|
+
hints.append(
|
|
1720
|
+
"Add a colorbar via cbar = fig.colorbar(im, ax=ax); mint.style_colorbar(cbar, label='...')."
|
|
1721
|
+
)
|
|
1722
|
+
for c in missing_cbars[:4]:
|
|
1723
|
+
el = f"missing colorbar ({c['colormap']})"
|
|
1724
|
+
elements.append(el)
|
|
1725
|
+
located.append((el, c["panel"]))
|
|
1726
|
+
|
|
1727
|
+
if unlabeled_axes:
|
|
1728
|
+
u_panels = ", ".join(u["panel"] or "axes" for u in unlabeled_axes[:4])
|
|
1729
|
+
parts.append(
|
|
1730
|
+
f"{len(unlabeled_axes)} data panel(s) have neither xlabel nor ylabel ({u_panels})"
|
|
1731
|
+
)
|
|
1732
|
+
hints.append(
|
|
1733
|
+
"Add descriptive axis labels with units via ax.set_xlabel(...) and ax.set_ylabel(...)."
|
|
1734
|
+
)
|
|
1735
|
+
for u in unlabeled_axes[:4]:
|
|
1736
|
+
el = f"missing axis labels ({u['panel'] or 'axes'})"
|
|
1737
|
+
elements.append(el)
|
|
1738
|
+
located.append((el, u["panel"]))
|
|
1739
|
+
|
|
1740
|
+
all_panels = _distinct_panels(
|
|
1741
|
+
[c["panel"] for c in missing_cbars] + [u["panel"] for u in unlabeled_axes]
|
|
1742
|
+
)
|
|
1743
|
+
return CheckResult(
|
|
1744
|
+
rule="clarity_metadata",
|
|
1745
|
+
status="warn",
|
|
1746
|
+
message="; ".join(parts),
|
|
1747
|
+
details={
|
|
1748
|
+
"missing_colorbars": missing_cbars,
|
|
1749
|
+
"unlabeled_axes": unlabeled_axes,
|
|
1750
|
+
},
|
|
1751
|
+
panel=all_panels[0] if all_panels else None,
|
|
1752
|
+
elements=elements,
|
|
1753
|
+
fix_hint=" ".join(hints),
|
|
1754
|
+
panels=all_panels,
|
|
1755
|
+
element_locations=_locate(located),
|
|
1756
|
+
)
|
|
1757
|
+
|
|
1758
|
+
return CheckResult(
|
|
1759
|
+
rule="clarity_metadata",
|
|
1760
|
+
status="pass",
|
|
1761
|
+
message="Data panels include axis labels and colorbars where colormapped",
|
|
1762
|
+
details={},
|
|
1763
|
+
)
|
|
1764
|
+
|
|
1765
|
+
|
|
1766
|
+
def _check_bar_baseline_nonzero(
|
|
1767
|
+
fig: Figure,
|
|
1768
|
+
panel_map: dict[int, str],
|
|
1769
|
+
) -> CheckResult:
|
|
1770
|
+
"""Tufte lie-factor guard: warn when positive bar charts truncate the zero baseline."""
|
|
1771
|
+
truncated: list[dict[str, Any]] = []
|
|
1772
|
+
|
|
1773
|
+
for ax in fig.axes:
|
|
1774
|
+
if not ax.get_visible() or getattr(ax, "_colorbar", None) is not None:
|
|
1775
|
+
continue
|
|
1776
|
+
bar_containers = [c for c in ax.containers if isinstance(c, BarContainer)]
|
|
1777
|
+
if not bar_containers:
|
|
1778
|
+
continue
|
|
1779
|
+
|
|
1780
|
+
orientation = getattr(bar_containers[0], "orientation", "vertical")
|
|
1781
|
+
values: list[float] = []
|
|
1782
|
+
bases: list[float] = []
|
|
1783
|
+
for bc in bar_containers:
|
|
1784
|
+
for rect in bc.patches:
|
|
1785
|
+
if not rect.get_visible():
|
|
1786
|
+
continue
|
|
1787
|
+
if orientation == "horizontal":
|
|
1788
|
+
values.append(float(rect.get_width()))
|
|
1789
|
+
bases.append(float(rect.get_x()))
|
|
1790
|
+
else:
|
|
1791
|
+
values.append(float(rect.get_height()))
|
|
1792
|
+
bases.append(float(rect.get_y()))
|
|
1793
|
+
|
|
1794
|
+
if not values:
|
|
1795
|
+
continue
|
|
1796
|
+
# Only apply to non-negative bars anchored at 0 (skip diverging +/- or stacked offsets)
|
|
1797
|
+
if min(values) < 0.0 or max(values) <= 0.0 or min(bases) < -1e-9:
|
|
1798
|
+
continue
|
|
1799
|
+
|
|
1800
|
+
scale = ax.get_xscale() if orientation == "horizontal" else ax.get_yscale()
|
|
1801
|
+
if scale == "log":
|
|
1802
|
+
continue
|
|
1803
|
+
|
|
1804
|
+
lo, hi = ax.get_xlim() if orientation == "horizontal" else ax.get_ylim()
|
|
1805
|
+
axis_min = min(float(lo), float(hi))
|
|
1806
|
+
max_val = max(values)
|
|
1807
|
+
if axis_min > 0.01 * max_val:
|
|
1808
|
+
panel = _artist_panel(ax, panel_map)
|
|
1809
|
+
truncated.append(
|
|
1810
|
+
{
|
|
1811
|
+
"panel": panel,
|
|
1812
|
+
"axis": "x" if orientation == "horizontal" else "y",
|
|
1813
|
+
"baseline": round(axis_min, 3),
|
|
1814
|
+
"max_bar": round(max_val, 3),
|
|
1815
|
+
}
|
|
1816
|
+
)
|
|
1817
|
+
|
|
1818
|
+
if truncated:
|
|
1819
|
+
first = truncated[0]
|
|
1820
|
+
panels = _distinct_panels(t["panel"] for t in truncated)
|
|
1821
|
+
elements = [
|
|
1822
|
+
f"{t['panel'] or 'axes'} ({t['axis']}_min={t['baseline']})" for t in truncated[:6]
|
|
1823
|
+
]
|
|
1824
|
+
where = f" in panel '{first['panel']}'" if first["panel"] else ""
|
|
1825
|
+
setter = "set_xlim(left=0)" if first["axis"] == "x" else "set_ylim(bottom=0)"
|
|
1826
|
+
return CheckResult(
|
|
1827
|
+
rule="bar_baseline_nonzero",
|
|
1828
|
+
status="warn",
|
|
1829
|
+
message=(
|
|
1830
|
+
f"{len(truncated)} positive bar panel(s) truncate the zero baseline: "
|
|
1831
|
+
+ ", ".join(elements[:4])
|
|
1832
|
+
),
|
|
1833
|
+
details={"truncated_bars": truncated},
|
|
1834
|
+
panel=first["panel"],
|
|
1835
|
+
elements=elements,
|
|
1836
|
+
fix_hint=(
|
|
1837
|
+
f"Call ax.{setter}{where} so bar length stays proportional to magnitude "
|
|
1838
|
+
"(or switch to a dot/range plot if zero is outside the meaningful scale)."
|
|
1839
|
+
),
|
|
1840
|
+
panels=panels,
|
|
1841
|
+
element_locations=_locate(
|
|
1842
|
+
zip(elements, (t["panel"] for t in truncated[:6]), strict=True)
|
|
1843
|
+
),
|
|
1844
|
+
)
|
|
1845
|
+
|
|
1846
|
+
return CheckResult(
|
|
1847
|
+
rule="bar_baseline_nonzero",
|
|
1848
|
+
status="pass",
|
|
1849
|
+
message="Bar chart baselines include zero (no truncated-axis lie factor)",
|
|
1850
|
+
details={},
|
|
1851
|
+
)
|
|
1852
|
+
|
|
1853
|
+
|
|
1854
|
+
def _check_chartjunk_hints(
|
|
1855
|
+
fig: Figure,
|
|
1856
|
+
panel_map: dict[int, str],
|
|
1857
|
+
) -> CheckResult:
|
|
1858
|
+
"""Tufte data-ink guard: warn on boxed legends, heavy grids, or spaghetti crowding."""
|
|
1859
|
+
boxed_legends: list[dict[str, Any]] = []
|
|
1860
|
+
heavy_grids: list[dict[str, Any]] = []
|
|
1861
|
+
spaghetti_axes: list[dict[str, Any]] = []
|
|
1862
|
+
|
|
1863
|
+
for ax in fig.axes:
|
|
1864
|
+
if not ax.get_visible() or getattr(ax, "_colorbar", None) is not None:
|
|
1865
|
+
continue
|
|
1866
|
+
panel = _artist_panel(ax, panel_map)
|
|
1867
|
+
|
|
1868
|
+
# 1. Boxed legend frame (allow borderless pure-white readability halos over images)
|
|
1869
|
+
leg = ax.get_legend()
|
|
1870
|
+
if leg is not None and leg.get_visible() and leg.get_frame_on():
|
|
1871
|
+
frame = leg.get_frame()
|
|
1872
|
+
ec = frame.get_edgecolor()
|
|
1873
|
+
fc = frame.get_facecolor()
|
|
1874
|
+
lw = float(frame.get_linewidth())
|
|
1875
|
+
has_visible_border = (
|
|
1876
|
+
lw > 0
|
|
1877
|
+
and _has_visible_rgba(ec)
|
|
1878
|
+
and min(to_rgb(ec)) < 0.94
|
|
1879
|
+
)
|
|
1880
|
+
has_tinted_fill = (
|
|
1881
|
+
_has_visible_rgba(fc)
|
|
1882
|
+
and float(to_rgba(fc)[3]) > 0.15
|
|
1883
|
+
and min(to_rgb(fc)) < 0.94
|
|
1884
|
+
)
|
|
1885
|
+
if has_visible_border or has_tinted_fill:
|
|
1886
|
+
boxed_legends.append({"panel": panel})
|
|
1887
|
+
|
|
1888
|
+
# 2. Heavy dark gridlines (ignore white heatmap cell dividers!)
|
|
1889
|
+
for axis in (ax.xaxis, ax.yaxis):
|
|
1890
|
+
for gl in axis.get_gridlines():
|
|
1891
|
+
if not gl.get_visible():
|
|
1892
|
+
continue
|
|
1893
|
+
alpha = gl.get_alpha()
|
|
1894
|
+
if alpha is not None and alpha <= 0:
|
|
1895
|
+
continue
|
|
1896
|
+
lw = float(gl.get_linewidth())
|
|
1897
|
+
if lw <= 0.65:
|
|
1898
|
+
continue
|
|
1899
|
+
try:
|
|
1900
|
+
rgb = to_rgb(gl.get_color())
|
|
1901
|
+
except (TypeError, ValueError):
|
|
1902
|
+
continue
|
|
1903
|
+
# Skip crisp white cell dividers drawn by style_heatmap()
|
|
1904
|
+
if min(rgb) > 0.94:
|
|
1905
|
+
continue
|
|
1906
|
+
heavy_grids.append({"panel": panel, "linewidth_pt": round(lw, 2)})
|
|
1907
|
+
break
|
|
1908
|
+
|
|
1909
|
+
# 3. Spaghetti crowding: >= 6 distinct labeled data series on a single axes
|
|
1910
|
+
labeled_series: set[str] = set()
|
|
1911
|
+
for line in ax.get_lines():
|
|
1912
|
+
if not line.get_visible():
|
|
1913
|
+
continue
|
|
1914
|
+
ls = _normalize_linestyle(line.get_linestyle())
|
|
1915
|
+
if ls in {"none", "", " "}:
|
|
1916
|
+
continue
|
|
1917
|
+
lbl = str(line.get_label() or "").strip()
|
|
1918
|
+
if lbl and not lbl.startswith("_"):
|
|
1919
|
+
labeled_series.add(lbl)
|
|
1920
|
+
if len(labeled_series) >= 6:
|
|
1921
|
+
spaghetti_axes.append({"panel": panel, "series_count": len(labeled_series)})
|
|
1922
|
+
|
|
1923
|
+
if boxed_legends or heavy_grids or spaghetti_axes:
|
|
1924
|
+
parts: list[str] = []
|
|
1925
|
+
hints: list[str] = []
|
|
1926
|
+
elements: list[str] = []
|
|
1927
|
+
located: list[tuple[str, str | None]] = []
|
|
1928
|
+
|
|
1929
|
+
if boxed_legends:
|
|
1930
|
+
parts.append(f"{len(boxed_legends)} boxed legend frame(s)")
|
|
1931
|
+
hints.append("Remove legend boxes (frameon=False) or use mint.direct_labels(ax).")
|
|
1932
|
+
for b in boxed_legends[:4]:
|
|
1933
|
+
el = f"boxed legend ({b['panel'] or 'axes'})"
|
|
1934
|
+
elements.append(el)
|
|
1935
|
+
located.append((el, b["panel"]))
|
|
1936
|
+
|
|
1937
|
+
if heavy_grids:
|
|
1938
|
+
parts.append(f"{len(heavy_grids)} heavy gridline axes (> 0.65 pt)")
|
|
1939
|
+
hints.append("Use mint.subtle_grid(ax, lw=0.45) instead of heavy dark gridlines.")
|
|
1940
|
+
for g in heavy_grids[:4]:
|
|
1941
|
+
el = f"heavy grid ({g['linewidth_pt']} pt)"
|
|
1942
|
+
elements.append(el)
|
|
1943
|
+
located.append((el, g["panel"]))
|
|
1944
|
+
|
|
1945
|
+
if spaghetti_axes:
|
|
1946
|
+
parts.append(
|
|
1947
|
+
f"{len(spaghetti_axes)} crowded panel(s) with >=6 labeled curves"
|
|
1948
|
+
)
|
|
1949
|
+
hints.append(
|
|
1950
|
+
"Split crowded spaghetti lines into shared-axis small multiples with mint.ghost_context(...)."
|
|
1951
|
+
)
|
|
1952
|
+
for s in spaghetti_axes[:4]:
|
|
1953
|
+
el = f"{s['series_count']} curves ({s['panel'] or 'axes'})"
|
|
1954
|
+
elements.append(el)
|
|
1955
|
+
located.append((el, s["panel"]))
|
|
1956
|
+
|
|
1957
|
+
all_panels = _distinct_panels(
|
|
1958
|
+
[b["panel"] for b in boxed_legends]
|
|
1959
|
+
+ [g["panel"] for g in heavy_grids]
|
|
1960
|
+
+ [s["panel"] for s in spaghetti_axes]
|
|
1961
|
+
)
|
|
1962
|
+
return CheckResult(
|
|
1963
|
+
rule="chartjunk_hints",
|
|
1964
|
+
status="warn",
|
|
1965
|
+
message=f"Tufte data-ink hint(s): {'; '.join(parts)}",
|
|
1966
|
+
details={
|
|
1967
|
+
"boxed_legends": boxed_legends,
|
|
1968
|
+
"heavy_grids": heavy_grids,
|
|
1969
|
+
"spaghetti_axes": spaghetti_axes,
|
|
1970
|
+
},
|
|
1971
|
+
panel=all_panels[0] if all_panels else None,
|
|
1972
|
+
elements=elements,
|
|
1973
|
+
fix_hint=" ".join(hints),
|
|
1974
|
+
panels=all_panels,
|
|
1975
|
+
element_locations=_locate(located),
|
|
1976
|
+
)
|
|
1977
|
+
|
|
1978
|
+
return CheckResult(
|
|
1979
|
+
rule="chartjunk_hints",
|
|
1980
|
+
status="pass",
|
|
1981
|
+
message="Clean data-ink ratio (no boxed legends, heavy grids, or spaghetti crowding)",
|
|
1982
|
+
details={},
|
|
1983
|
+
)
|
|
1984
|
+
|
|
1985
|
+
|
|
1986
|
+
def _check_text_on_data(
|
|
1987
|
+
fig: Figure,
|
|
1988
|
+
visible_texts: list[_TextRecord],
|
|
1989
|
+
panel_map: dict[int, str],
|
|
1990
|
+
) -> CheckResult:
|
|
1991
|
+
"""Clarity warning: detect in-axes annotations/legends printed over foreground data ink."""
|
|
1992
|
+
candidates: list[_TextRecord] = []
|
|
1993
|
+
for rec in visible_texts:
|
|
1994
|
+
if rec.role not in {"annotation", "legend"}:
|
|
1995
|
+
continue
|
|
1996
|
+
artist = rec.artist
|
|
1997
|
+
ax = getattr(artist, "axes", None)
|
|
1998
|
+
if ax is None or not ax.get_visible():
|
|
1999
|
+
continue
|
|
2000
|
+
if getattr(ax, "_colorbar", None) is not None or ax.images:
|
|
2001
|
+
continue
|
|
2002
|
+
if getattr(artist, "_mintfig_scalebar", False) or getattr(
|
|
2003
|
+
artist, "_mintfig_heatmap_text", False
|
|
2004
|
+
):
|
|
2005
|
+
continue
|
|
2006
|
+
# Skip text explicitly shielded by a background halo / pill patch
|
|
2007
|
+
if artist.get_bbox_patch() is not None:
|
|
2008
|
+
continue
|
|
2009
|
+
# Only inspect text positioned inside the plot data box
|
|
2010
|
+
if not rec.bbox.overlaps(ax.bbox):
|
|
2011
|
+
continue
|
|
2012
|
+
candidates.append(rec)
|
|
2013
|
+
|
|
2014
|
+
if not candidates or fig.canvas is None:
|
|
2015
|
+
return CheckResult(
|
|
2016
|
+
rule="text_on_data",
|
|
2017
|
+
status="pass",
|
|
2018
|
+
message="No in-axes annotations or legends collide with foreground data ink",
|
|
2019
|
+
details={"checked_count": len(candidates)},
|
|
2020
|
+
)
|
|
2021
|
+
|
|
2022
|
+
# Temporarily hide candidate text and legend internals (without hiding the Legend
|
|
2023
|
+
# container itself so constrained_layout geometry never shifts), draw once, copy
|
|
2024
|
+
# the pixel buffer, and restore before inspecting foreground ink.
|
|
2025
|
+
to_hide: list[Any] = [rec.artist for rec in candidates]
|
|
2026
|
+
for leg in list(fig.legends) + [ax.get_legend() for ax in fig.axes]:
|
|
2027
|
+
if leg is not None and leg.get_visible():
|
|
2028
|
+
to_hide.extend(leg.get_texts())
|
|
2029
|
+
to_hide.append(leg.get_title())
|
|
2030
|
+
frame = leg.get_frame()
|
|
2031
|
+
if frame is not None:
|
|
2032
|
+
to_hide.append(frame)
|
|
2033
|
+
handles = getattr(leg, "legend_handles", None) or getattr(leg, "legendHandles", [])
|
|
2034
|
+
for h in handles:
|
|
2035
|
+
if h is not None and hasattr(h, "get_visible") and hasattr(h, "set_visible"):
|
|
2036
|
+
to_hide.append(h)
|
|
2037
|
+
|
|
2038
|
+
seen_hide: set[int] = set()
|
|
2039
|
+
saved_vis: list[tuple[Any, bool]] = []
|
|
2040
|
+
for obj in to_hide:
|
|
2041
|
+
oid = id(obj)
|
|
2042
|
+
if oid not in seen_hide:
|
|
2043
|
+
seen_hide.add(oid)
|
|
2044
|
+
saved_vis.append((obj, bool(obj.get_visible())))
|
|
2045
|
+
|
|
2046
|
+
try:
|
|
2047
|
+
for obj, _ in saved_vis:
|
|
2048
|
+
obj.set_visible(False)
|
|
2049
|
+
fig.canvas.draw()
|
|
2050
|
+
# Copy the buffer before finally() redraws the text back into Agg's live memory.
|
|
2051
|
+
buf = np.asarray(fig.canvas.buffer_rgba())[..., :3].copy()
|
|
2052
|
+
except Exception: # noqa: BLE001
|
|
2053
|
+
return CheckResult(
|
|
2054
|
+
rule="text_on_data",
|
|
2055
|
+
status="pass",
|
|
2056
|
+
message="Skipped pixel text-on-data check on non-Agg canvas",
|
|
2057
|
+
details={},
|
|
2058
|
+
)
|
|
2059
|
+
finally:
|
|
2060
|
+
for obj, vis in saved_vis:
|
|
2061
|
+
obj.set_visible(vis)
|
|
2062
|
+
with contextlib.suppress(Exception):
|
|
2063
|
+
fig.canvas.draw()
|
|
2064
|
+
|
|
2065
|
+
img_h, img_w = buf.shape[:2]
|
|
2066
|
+
sx = img_w / max(float(fig.bbox.width), 1.0)
|
|
2067
|
+
sy = img_h / max(float(fig.bbox.height), 1.0)
|
|
2068
|
+
hits: list[dict[str, Any]] = []
|
|
2069
|
+
for rec in candidates:
|
|
2070
|
+
ax = rec.artist.axes
|
|
2071
|
+
if ax is None:
|
|
2072
|
+
continue
|
|
2073
|
+
# Intersect text bbox with the axes plot area (shrink 1 px to ignore edge touches)
|
|
2074
|
+
ix0 = max(int(np.floor(max(rec.bbox.x0, ax.bbox.x0) * sx)) + 1, 0)
|
|
2075
|
+
ix1 = min(int(np.ceil(min(rec.bbox.x1, ax.bbox.x1) * sx)) - 1, img_w)
|
|
2076
|
+
# Matplotlib display y=0 is bottom; buffer row 0 is top
|
|
2077
|
+
iy0 = max(int(np.floor(img_h - min(rec.bbox.y1, ax.bbox.y1) * sy)) + 1, 0)
|
|
2078
|
+
iy1 = min(int(np.ceil(img_h - max(rec.bbox.y0, ax.bbox.y0) * sy)) - 1, img_h)
|
|
2079
|
+
if ix1 - ix0 < 4 or iy1 - iy0 < 4:
|
|
2080
|
+
continue
|
|
2081
|
+
|
|
2082
|
+
patch = buf[iy0:iy1, ix0:ix1]
|
|
2083
|
+
bg_rgba = to_rgba(ax.get_facecolor())
|
|
2084
|
+
if bg_rgba[3] < 0.5:
|
|
2085
|
+
bg_rgba = to_rgba(fig.get_facecolor())
|
|
2086
|
+
bg_u8 = np.array([round(c * 255) for c in bg_rgba[:3]], dtype=np.int16)
|
|
2087
|
+
if float(np.mean(bg_rgba[:3])) >= 0.5:
|
|
2088
|
+
# Light ground: count saturated foreground data ink (ignore pale ribbons/gridlines >= 185)
|
|
2089
|
+
ink_mask = np.min(patch, axis=2) < 185
|
|
2090
|
+
else:
|
|
2091
|
+
# Dark ground: count foreground data ink contrasting strongly with the dark canvas
|
|
2092
|
+
ink_mask = np.max(np.abs(patch.astype(np.int16) - bg_u8), axis=2) > 70
|
|
2093
|
+
ink_frac = float(np.mean(ink_mask))
|
|
2094
|
+
if ink_frac > 0.22:
|
|
2095
|
+
hits.append(
|
|
2096
|
+
{
|
|
2097
|
+
"text": rec.text,
|
|
2098
|
+
"panel": rec.panel or _artist_panel(ax, panel_map),
|
|
2099
|
+
"ink_fraction": round(ink_frac, 3),
|
|
2100
|
+
}
|
|
2101
|
+
)
|
|
2102
|
+
|
|
2103
|
+
if hits:
|
|
2104
|
+
hits.sort(key=lambda h: h["ink_fraction"], reverse=True)
|
|
2105
|
+
first = hits[0]
|
|
2106
|
+
sample = ", ".join(f"'{h['text']}' ({int(h['ink_fraction'] * 100)}% ink)" for h in hits[:4])
|
|
2107
|
+
elements = [h["text"] for h in hits[:6]]
|
|
2108
|
+
panels = _distinct_panels(h["panel"] for h in hits)
|
|
2109
|
+
where = f" in panel '{first['panel']}'" if first["panel"] else ""
|
|
2110
|
+
return CheckResult(
|
|
2111
|
+
rule="text_on_data",
|
|
2112
|
+
status="warn",
|
|
2113
|
+
message=f"{len(hits)} annotation/legend text(s) overlap foreground data: {sample}",
|
|
2114
|
+
details={"overlaps": hits[:20]},
|
|
2115
|
+
panel=first["panel"],
|
|
2116
|
+
elements=elements,
|
|
2117
|
+
fix_hint=(
|
|
2118
|
+
f"Move '{first['text']}'{where} into open whitespace, use mint.direct_labels(ax), "
|
|
2119
|
+
"or add a subtle white bbox halo."
|
|
2120
|
+
),
|
|
2121
|
+
panels=panels,
|
|
2122
|
+
element_locations=_locate((h["text"], h["panel"]) for h in hits[:6]),
|
|
2123
|
+
)
|
|
2124
|
+
|
|
2125
|
+
return CheckResult(
|
|
2126
|
+
rule="text_on_data",
|
|
2127
|
+
status="pass",
|
|
2128
|
+
message=f"All {len(candidates)} in-axes annotation/legend text(s) sit clear of data ink",
|
|
2129
|
+
details={"checked_count": len(candidates)},
|
|
2130
|
+
)
|
|
2131
|
+
|
|
2132
|
+
|
|
2133
|
+
def _safe_draw_and_collect_texts(
|
|
2134
|
+
fig: Figure,
|
|
2135
|
+
panel_map: dict[int, str],
|
|
2136
|
+
) -> tuple[list[_TextRecord], list[str]]:
|
|
2137
|
+
"""Draw the figure canvas, capture layout-collapse warnings, and collect visible texts.
|
|
2138
|
+
|
|
2139
|
+
On macOS, FreeType can raise ``RuntimeError: failed to load glyph`` for
|
|
2140
|
+
sub-5 pt text rendered with ``Helvetica.ttc``. When that happens, we
|
|
2141
|
+
temporarily substitute ``Arial``/``DejaVu Sans`` for sub-5 pt artists
|
|
2142
|
+
strictly during layout/bbox measurement and immediately restore their
|
|
2143
|
+
original font properties so every check inspects the true artist state.
|
|
2144
|
+
"""
|
|
2145
|
+
if fig.canvas is None:
|
|
2146
|
+
FigureCanvasAgg(fig)
|
|
2147
|
+
|
|
2148
|
+
def _draw_capturing_warnings() -> list[str]:
|
|
2149
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
2150
|
+
warnings.simplefilter("always")
|
|
2151
|
+
fig.canvas.draw()
|
|
2152
|
+
collapse_msgs: list[str] = []
|
|
2153
|
+
for w in caught:
|
|
2154
|
+
msg = str(w.message)
|
|
2155
|
+
low = msg.lower()
|
|
2156
|
+
if any(pat in low for pat in _LAYOUT_COLLAPSE_PATTERNS):
|
|
2157
|
+
collapse_msgs.append(msg)
|
|
2158
|
+
return collapse_msgs
|
|
2159
|
+
|
|
2160
|
+
try:
|
|
2161
|
+
layout_warnings = _draw_capturing_warnings()
|
|
2162
|
+
renderer = fig.canvas.get_renderer()
|
|
2163
|
+
return _iter_visible_texts(fig, renderer, panel_map), layout_warnings
|
|
2164
|
+
except RuntimeError:
|
|
2165
|
+
saved_families: list[tuple[Text, list[str]]] = []
|
|
2166
|
+
for text_artist in fig.findobj(Text):
|
|
2167
|
+
if float(text_artist.get_fontsize()) < 5.0:
|
|
2168
|
+
orig = list(text_artist.get_fontfamily())
|
|
2169
|
+
saved_families.append((text_artist, orig))
|
|
2170
|
+
text_artist.set_fontfamily(["Arial", "DejaVu Sans"])
|
|
2171
|
+
try:
|
|
2172
|
+
layout_warnings = _draw_capturing_warnings()
|
|
2173
|
+
renderer = fig.canvas.get_renderer()
|
|
2174
|
+
return _iter_visible_texts(fig, renderer, panel_map), layout_warnings
|
|
2175
|
+
finally:
|
|
2176
|
+
for text_artist, orig in saved_families:
|
|
2177
|
+
text_artist.set_fontfamily(orig)
|
|
2178
|
+
|
|
2179
|
+
|
|
2180
|
+
def preflight_figure(
|
|
2181
|
+
fig: Figure,
|
|
2182
|
+
journal: str | JournalSpec = "nature",
|
|
2183
|
+
*,
|
|
2184
|
+
strict: bool = False,
|
|
2185
|
+
) -> PreflightReport:
|
|
2186
|
+
"""Run all automated publication-compliance and clarity checks on a Matplotlib Figure."""
|
|
2187
|
+
spec = get_spec(journal)
|
|
2188
|
+
panel_map = _build_axes_panel_map(fig)
|
|
2189
|
+
visible_texts, layout_warnings = _safe_draw_and_collect_texts(fig, panel_map)
|
|
2190
|
+
|
|
2191
|
+
width_mm = in_to_mm(float(fig.get_figwidth()))
|
|
2192
|
+
height_mm = in_to_mm(float(fig.get_figheight()))
|
|
2193
|
+
|
|
2194
|
+
checks = [
|
|
2195
|
+
_check_dimensions(width_mm, height_mm, spec),
|
|
2196
|
+
_check_layout_collapse(fig, layout_warnings, panel_map),
|
|
2197
|
+
_check_font_sizes(visible_texts, spec),
|
|
2198
|
+
_check_font_family(visible_texts, spec),
|
|
2199
|
+
_check_text_overlaps(visible_texts),
|
|
2200
|
+
_check_canvas_clipping(fig, visible_texts),
|
|
2201
|
+
_check_lines_past_axes(fig, panel_map),
|
|
2202
|
+
_check_hairline_strokes(fig, spec, panel_map),
|
|
2203
|
+
_check_colormaps(fig, panel_map),
|
|
2204
|
+
_check_vector_fonts(spec, fig),
|
|
2205
|
+
_check_color_separation(fig, panel_map),
|
|
2206
|
+
_check_clarity_metadata(fig, panel_map),
|
|
2207
|
+
_check_bar_baseline_nonzero(fig, panel_map),
|
|
2208
|
+
_check_chartjunk_hints(fig, panel_map),
|
|
2209
|
+
_check_text_on_data(fig, visible_texts, panel_map),
|
|
2210
|
+
]
|
|
2211
|
+
|
|
2212
|
+
report = PreflightReport(
|
|
2213
|
+
journal=spec.name,
|
|
2214
|
+
checks=checks,
|
|
2215
|
+
width_mm=width_mm,
|
|
2216
|
+
height_mm=height_mm,
|
|
2217
|
+
spec_version=getattr(spec, "spec_version", ""),
|
|
2218
|
+
spec_source_url=getattr(spec, "source_url", ""),
|
|
2219
|
+
)
|
|
2220
|
+
|
|
2221
|
+
if strict and not report.passed:
|
|
2222
|
+
raise ValueError(report.summary())
|
|
2223
|
+
|
|
2224
|
+
return report
|
|
2225
|
+
|
|
2226
|
+
|
|
2227
|
+
def _resolve_pdf_obj(obj: Any) -> Any:
|
|
2228
|
+
"""Safely dereference pypdf IndirectObjects."""
|
|
2229
|
+
if hasattr(obj, "get_object"):
|
|
2230
|
+
return obj.get_object()
|
|
2231
|
+
return obj
|
|
2232
|
+
|
|
2233
|
+
|
|
2234
|
+
def _collect_pdf_fonts(
|
|
2235
|
+
resources: Any,
|
|
2236
|
+
seen: set[int],
|
|
2237
|
+
fonts_out: list[dict[str, str]],
|
|
2238
|
+
) -> None:
|
|
2239
|
+
"""Recursively collect /Font dictionaries from a PDF /Resources dict (including XObjects)."""
|
|
2240
|
+
res = _resolve_pdf_obj(resources)
|
|
2241
|
+
if not isinstance(res, dict):
|
|
2242
|
+
return
|
|
2243
|
+
|
|
2244
|
+
res_id = id(res)
|
|
2245
|
+
if res_id in seen:
|
|
2246
|
+
return
|
|
2247
|
+
seen.add(res_id)
|
|
2248
|
+
|
|
2249
|
+
font_dict = _resolve_pdf_obj(res.get("/Font"))
|
|
2250
|
+
if isinstance(font_dict, dict):
|
|
2251
|
+
for font_key, font_ref in font_dict.items():
|
|
2252
|
+
font_obj = _resolve_pdf_obj(font_ref)
|
|
2253
|
+
if not isinstance(font_obj, dict):
|
|
2254
|
+
continue
|
|
2255
|
+
subtype = str(_resolve_pdf_obj(font_obj.get("/Subtype", "")))
|
|
2256
|
+
basefont = str(_resolve_pdf_obj(font_obj.get("/BaseFont", "")))
|
|
2257
|
+
fonts_out.append(
|
|
2258
|
+
{
|
|
2259
|
+
"key": str(font_key),
|
|
2260
|
+
"subtype": subtype,
|
|
2261
|
+
"basefont": basefont.lstrip("/"),
|
|
2262
|
+
}
|
|
2263
|
+
)
|
|
2264
|
+
|
|
2265
|
+
xobjects = _resolve_pdf_obj(res.get("/XObject"))
|
|
2266
|
+
if isinstance(xobjects, dict):
|
|
2267
|
+
for xobj_ref in xobjects.values():
|
|
2268
|
+
xobj = _resolve_pdf_obj(xobj_ref)
|
|
2269
|
+
if isinstance(xobj, dict) and "/Resources" in xobj:
|
|
2270
|
+
_collect_pdf_fonts(xobj["/Resources"], seen, fonts_out)
|
|
2271
|
+
|
|
2272
|
+
|
|
2273
|
+
def preflight_pdf(
|
|
2274
|
+
path: str | Path,
|
|
2275
|
+
journal: str | JournalSpec = "nature",
|
|
2276
|
+
) -> PreflightReport:
|
|
2277
|
+
"""Inspect an exported PDF directly for physical dimensions, fonts, and file size."""
|
|
2278
|
+
pdf_path = Path(path)
|
|
2279
|
+
if not pdf_path.exists():
|
|
2280
|
+
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
|
|
2281
|
+
|
|
2282
|
+
spec = get_spec(journal)
|
|
2283
|
+
reader = PdfReader(str(pdf_path))
|
|
2284
|
+
if not reader.pages:
|
|
2285
|
+
raise ValueError(f"PDF contains no pages: {pdf_path}")
|
|
2286
|
+
|
|
2287
|
+
first_page = reader.pages[0]
|
|
2288
|
+
mediabox = first_page.mediabox
|
|
2289
|
+
width_pt = float(mediabox.width)
|
|
2290
|
+
height_pt = float(mediabox.height)
|
|
2291
|
+
width_mm = width_pt * MM_PER_INCH / 72.0
|
|
2292
|
+
height_mm = height_pt * MM_PER_INCH / 72.0
|
|
2293
|
+
|
|
2294
|
+
# Collect all fonts across all pages
|
|
2295
|
+
fonts: list[dict[str, str]] = []
|
|
2296
|
+
seen: set[int] = set()
|
|
2297
|
+
for page in reader.pages:
|
|
2298
|
+
if "/Resources" in page:
|
|
2299
|
+
_collect_pdf_fonts(page["/Resources"], seen, fonts)
|
|
2300
|
+
|
|
2301
|
+
# 1. Dimensions check
|
|
2302
|
+
dim_check = _check_dimensions(width_mm, height_mm, spec)
|
|
2303
|
+
|
|
2304
|
+
# 2. Type 3 font check (canonical rule name: vector_fonts)
|
|
2305
|
+
type3_fonts = [f for f in fonts if f["subtype"] == "/Type3"]
|
|
2306
|
+
if type3_fonts:
|
|
2307
|
+
keys = [f["key"] for f in type3_fonts[:6]]
|
|
2308
|
+
type3_check = CheckResult(
|
|
2309
|
+
rule="vector_fonts",
|
|
2310
|
+
status="fail",
|
|
2311
|
+
message=(
|
|
2312
|
+
f"Found {len(type3_fonts)} Type 3 outlined font(s) ({', '.join(keys)}); "
|
|
2313
|
+
"export with pdf.fonttype=42 for editable TrueType fonts"
|
|
2314
|
+
),
|
|
2315
|
+
details={"type3_fonts": type3_fonts, "all_fonts": fonts},
|
|
2316
|
+
panel=None,
|
|
2317
|
+
elements=keys,
|
|
2318
|
+
fix_hint=(
|
|
2319
|
+
"Export via mint.save_figure(...) or set plt.rcParams['pdf.fonttype'] = 42 "
|
|
2320
|
+
"to embed editable TrueType fonts instead of Type 3 outlines."
|
|
2321
|
+
),
|
|
2322
|
+
)
|
|
2323
|
+
else:
|
|
2324
|
+
unique_names = sorted({f["basefont"] or f["subtype"] for f in fonts})
|
|
2325
|
+
names_str = ", ".join(unique_names[:5]) if unique_names else "none"
|
|
2326
|
+
type3_check = CheckResult(
|
|
2327
|
+
rule="vector_fonts",
|
|
2328
|
+
status="pass",
|
|
2329
|
+
message=f"Zero Type 3 fonts; {len(fonts)} editable font ref(s) ({names_str})",
|
|
2330
|
+
details={"all_fonts": fonts},
|
|
2331
|
+
)
|
|
2332
|
+
|
|
2333
|
+
# 3. Serif font name check
|
|
2334
|
+
serif_fonts = [
|
|
2335
|
+
f for f in fonts if f["basefont"] and _is_serif_font_name(f["basefont"])
|
|
2336
|
+
]
|
|
2337
|
+
if serif_fonts:
|
|
2338
|
+
bad = sorted({f["basefont"] for f in serif_fonts})
|
|
2339
|
+
family_check = CheckResult(
|
|
2340
|
+
rule="font_family",
|
|
2341
|
+
status="warn",
|
|
2342
|
+
message=f"Serif font(s) embedded in PDF: {', '.join(bad)} (sans-serif required)",
|
|
2343
|
+
details={"serif_fonts": bad},
|
|
2344
|
+
panel=None,
|
|
2345
|
+
elements=bad[:6],
|
|
2346
|
+
fix_hint=(
|
|
2347
|
+
f"Build the figure inside mint.use({spec.name!r}) or mint.Plate(journal={spec.name!r}) "
|
|
2348
|
+
"so embedded PDF fonts are sans-serif."
|
|
2349
|
+
),
|
|
2350
|
+
)
|
|
2351
|
+
else:
|
|
2352
|
+
unique_clean = sorted(
|
|
2353
|
+
{re.sub(r"^[A-Z]{6}\+", "", f["basefont"]) for f in fonts if f["basefont"]}
|
|
2354
|
+
)
|
|
2355
|
+
names_str = ", ".join(unique_clean[:4]) if unique_clean else "none"
|
|
2356
|
+
family_check = CheckResult(
|
|
2357
|
+
rule="font_family",
|
|
2358
|
+
status="pass",
|
|
2359
|
+
message=f"All embedded PDF fonts are sans-serif ({names_str})",
|
|
2360
|
+
details={"fonts": unique_clean},
|
|
2361
|
+
)
|
|
2362
|
+
|
|
2363
|
+
# 4. File size check
|
|
2364
|
+
size_bytes = pdf_path.stat().st_size
|
|
2365
|
+
size_mb = size_bytes / (1024.0 * 1024.0)
|
|
2366
|
+
if size_mb > 10.0:
|
|
2367
|
+
size_check = CheckResult(
|
|
2368
|
+
rule="file_size",
|
|
2369
|
+
status="warn",
|
|
2370
|
+
message=(
|
|
2371
|
+
f"PDF file size {size_mb:.2f} MB exceeds 10.0 MB recommendation "
|
|
2372
|
+
"(use rasterize_heavy for dense data)"
|
|
2373
|
+
),
|
|
2374
|
+
details={"size_bytes": size_bytes, "size_mb": round(size_mb, 3)},
|
|
2375
|
+
panel=None,
|
|
2376
|
+
elements=[f"{size_mb:.2f} MB"],
|
|
2377
|
+
fix_hint=(
|
|
2378
|
+
"Pass rasterize_above=10_000 to plate.save(...) / mint.save_figure(...) "
|
|
2379
|
+
"to rasterize dense scatter/heatmap layers while keeping text vector."
|
|
2380
|
+
),
|
|
2381
|
+
)
|
|
2382
|
+
else:
|
|
2383
|
+
size_kb = size_bytes / 1024.0
|
|
2384
|
+
size_check = CheckResult(
|
|
2385
|
+
rule="file_size",
|
|
2386
|
+
status="pass",
|
|
2387
|
+
message=f"PDF file size {size_kb:.1f} KB ({size_mb:.2f} MB) <= 10.0 MB",
|
|
2388
|
+
details={"size_bytes": size_bytes, "size_mb": round(size_mb, 3)},
|
|
2389
|
+
)
|
|
2390
|
+
|
|
2391
|
+
return PreflightReport(
|
|
2392
|
+
journal=spec.name,
|
|
2393
|
+
checks=[dim_check, type3_check, family_check, size_check],
|
|
2394
|
+
width_mm=width_mm,
|
|
2395
|
+
height_mm=height_mm,
|
|
2396
|
+
spec_version=getattr(spec, "spec_version", ""),
|
|
2397
|
+
spec_source_url=getattr(spec, "source_url", ""),
|
|
2398
|
+
)
|