"""Shared, deliberately small style layer for the TRACE paper figures.""" from __future__ import annotations import hashlib from itertools import combinations from pathlib import Path from typing import Iterable import matplotlib import numpy as np # Keep the PDF backend as the owning canvas: this avoids a PDFKit/Quick Look # rendering defect seen when a figure created on Agg is later serialized as # PDF. Boundary checks still use an explicit Agg canvas below, and each # generator writes both formats from the same Figure object. matplotlib.use("pdf") import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.text import Text from matplotlib.transforms import Bbox HERE = Path(__file__).resolve().parent # figures/ sits at paper/figures/, so the repository root is two levels up. # Manifest paths are recorded relative to this root. REPO_ROOT = HERE.parents[1] FULL_WIDTH_IN = 7.0 COLUMN_WIDTH_IN = (7.0 - 0.375) / 2.0 TEXT_PT = 7.8 SMALL_TEXT_PT = 7.5 LABEL_PT = 8.2 PANEL_PT = 8.5 INK = "#20252A" MID_GREY = "#6F7880" LIGHT_GREY = "#D8DDE1" PALE_GREY = "#F2F4F5" BLUE = "#2B6F9F" PALE_BLUE = "#DCEAF3" ORANGE = "#C2762B" PALE_ORANGE = "#F4E5D5" WHITE = "#FFFFFF" CONTENT_TRIM_DPI = 300 CONTENT_TRIM_SAFETY_PIXELS = 2 def configure_matplotlib() -> None: """Set print-oriented defaults and embed TrueType fonts in vector output.""" plt.rcParams.update( { "font.family": "DejaVu Sans", "font.size": TEXT_PT, "axes.labelsize": LABEL_PT, "axes.titlesize": PANEL_PT, "xtick.labelsize": SMALL_TEXT_PT, "ytick.labelsize": SMALL_TEXT_PT, "legend.fontsize": SMALL_TEXT_PT, "mathtext.fontset": "dejavusans", "axes.edgecolor": INK, "axes.labelcolor": INK, "axes.linewidth": 0.65, "xtick.color": INK, "ytick.color": INK, "xtick.major.width": 0.55, "ytick.major.width": 0.55, "xtick.major.size": 2.5, "ytick.major.size": 2.5, "text.color": INK, "pdf.fonttype": 42, "ps.fonttype": 42, "svg.fonttype": "path", "svg.hashsalt": "trace-paper-figures", "savefig.facecolor": WHITE, "figure.facecolor": WHITE, } ) def panel_label(ax, label: str) -> None: ax.text( -0.12, 1.01, label, transform=ax.transAxes, fontsize=PANEL_PT, fontweight="bold", va="bottom", ha="left", clip_on=False, ) def remove_spines(ax, names: Iterable[str] = ("top", "right")) -> None: for name in names: ax.spines[name].set_visible(False) def assert_text_floor(fig, floor: float = SMALL_TEXT_PT) -> None: """Fail generation if any visible, non-empty Matplotlib text is too small.""" offenders: list[tuple[str, float]] = [] for item in fig.findobj(match=Text): if not item.get_visible() or not item.get_text().strip(): continue size = float(item.get_fontsize()) if size + 1e-9 < floor: offenders.append((item.get_text(), size)) if offenders: details = ", ".join(f"{text!r}: {size:g} pt" for text, size in offenders) raise ValueError(f"text below {floor:g} pt: {details}") def assert_text_inside_figure(fig, padding_points: float = 1.0) -> None: """Fail if visible text reaches beyond, or too close to, the PDF boundary.""" original_canvas = fig.canvas canvas = FigureCanvasAgg(fig) canvas.draw() renderer = canvas.get_renderer() figure_box = fig.bbox padding_pixels = padding_points * fig.dpi / 72.0 offenders: list[str] = [] for item in fig.findobj(match=Text): if not item.get_visible() or not item.get_text().strip(): continue box = item.get_window_extent(renderer) if ( box.x0 < figure_box.x0 + padding_pixels or box.y0 < figure_box.y0 + padding_pixels or box.x1 > figure_box.x1 - padding_pixels or box.y1 > figure_box.y1 - padding_pixels ): offenders.append(item.get_text()) fig.set_canvas(original_canvas) if offenders: details = ", ".join(repr(text) for text in offenders) raise ValueError( f"text reaches within {padding_points:g} pt of figure boundary: {details}" ) def assert_text_not_overlapping( fig, items: Iterable[Text], padding_points: float = 1.0 ) -> None: """Fail if any supplied text boxes touch after adding a small safety gap.""" original_canvas = fig.canvas canvas = FigureCanvasAgg(fig) canvas.draw() renderer = canvas.get_renderer() padding_pixels = padding_points * fig.dpi / 72.0 boxes = [ (item.get_text(), item.get_window_extent(renderer)) for item in items if item.get_visible() and item.get_text().strip() ] offenders: list[tuple[str, str]] = [] for (left_text, left), (right_text, right) in combinations(boxes, 2): x_gap = max(left.x0, right.x0) - min(left.x1, right.x1) y_gap = max(left.y0, right.y0) - min(left.y1, right.y1) if x_gap < padding_pixels and y_gap < padding_pixels: offenders.append((left_text, right_text)) fig.set_canvas(original_canvas) if offenders: details = ", ".join(f"{left!r} / {right!r}" for left, right in offenders) raise ValueError( f"text boxes overlap or come within {padding_points:g} pt: {details}" ) def content_bbox_inches( fig, *, dpi: int = CONTENT_TRIM_DPI, safety_pixels: int = CONTENT_TRIM_SAFETY_PIXELS, ) -> Bbox: """Return one renderer-independent crop box around all visible ink. Matplotlib's ``bbox_inches="tight"`` still retains an axes-sized white border for diagrams whose axes are intentionally hidden. Measure the painted pixels on one high-resolution Agg reference render instead, then reuse that exact box for PNG, PDF, and SVG. Two reference pixels equal 0.48 pt: enough to protect antialiasing and stroke caps without producing visible layout padding. """ if dpi <= 0: raise ValueError("content-trim dpi must be positive") if safety_pixels < 0: raise ValueError("content-trim safety must be non-negative") original_canvas = fig.canvas original_dpi = fig.dpi try: fig.set_dpi(dpi) canvas = FigureCanvasAgg(fig) canvas.draw() rgba = np.asarray(canvas.buffer_rgba()) painted = (rgba[:, :, 3] > 0) & np.any(rgba[:, :, :3] < 255, axis=2) if not painted.any(): raise ValueError("cannot content-trim a figure with no visible ink") rows, columns = np.nonzero(painted) height, width = painted.shape left = max(0, int(columns.min()) - safety_pixels) right = min(width, int(columns.max()) + 1 + safety_pixels) top = max(0, int(rows.min()) - safety_pixels) bottom = min(height, int(rows.max()) + 1 + safety_pixels) # Raster rows count downward, whereas Matplotlib's inch-coordinate # bounding boxes count upward from the lower-left corner. return Bbox.from_extents( left / dpi, (height - bottom) / dpi, right / dpi, (height - top) / dpi, ) finally: fig.set_dpi(original_dpi) fig.set_canvas(original_canvas) def save_figure(fig, output_path: Path, *, subject: str) -> tuple[Path, Path, Path]: """Write content-trimmed vector PDF/SVG and 300 dpi PNG counterparts.""" assert_text_floor(fig) assert_text_inside_figure(fig) crop_box = content_bbox_inches(fig) pdf_path = output_path.with_suffix(".pdf") png_path = output_path.with_suffix(".png") svg_path = output_path.with_suffix(".svg") pdf_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig( png_path, format="png", dpi=300, bbox_inches=crop_box, pad_inches=0, metadata={"Software": "TRACE tracked figure generator"}, ) fig.savefig( pdf_path, format="pdf", dpi=300, bbox_inches=crop_box, pad_inches=0, metadata={ "Title": "", "Author": "", "Subject": subject, "Keywords": "TRACE; datacenter telemetry; scientific figure", "Creator": "TRACE tracked figure generator", "Producer": "Matplotlib PDF backend", "CreationDate": None, "ModDate": None, }, ) fig.savefig( svg_path, format="svg", dpi=300, bbox_inches=crop_box, pad_inches=0, metadata={ "Date": None, "Creator": "TRACE tracked figure generator", "Description": subject, }, ) plt.close(fig) return pdf_path, png_path, svg_path def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() configure_matplotlib()