"""Shared helpers for scripts/plots/*.py. House style is ported from the AdditiveLLM2-OA figures (ppak10/AdditiveLLM2-OA, figures/*/*.py): DM Sans typeface, a curated saturated palette anchored on #2D6A9F / #2AAA8A / #D44000 / #8B5CF6 with #F97415 orange reserved for the reference/highlight series, a *framed* (not despined) look with heavy spines and inward ticks, a light dashed grid, and dual PNG@1200 + PDF export. Call `apply_house_style()` once at import (done here), `style_axes(ax)` per Axes, and `save_figure(fig, stem)` to write both formats. """ import json from pathlib import Path import matplotlib import matplotlib.pyplot as plt import matplotlib.colors as mcolors import matplotlib.font_manager as fm matplotlib.use("Agg") ROOT = Path(__file__).parent.parent.parent DATA_DIR = ROOT / "data" OUT_DIR = ROOT / "assets" FONT_DIR = Path(__file__).parent / "fonts" # ── House style ─────────────────────────────────────────────────────────────── # Publication export DPI, matching the AdditiveLLM2 figures. save_figure() # emits both a PNG at this DPI and a vector PDF. EXPORT_DPI = 1200 # Reference categorical palette (AdditiveLLM2 figures/*/*.py). Used verbatim on # the low-series-count figures (PLA/PETG controls, Type IV, Nylon 12 White). REF_BLUE = "#2D6A9F" REF_TEAL = "#2AAA8A" REF_REDORANGE = "#D44000" REF_PURPLE = "#8B5CF6" # The signature accent — reserved for the reference / highlighted series # (here the FormLabs PA12GF benchtop control the SLS batches are compared # against), exactly as #F97415 flags the "Overall"/"best" series in the # AdditiveLLM2 charts. Never assigned to an SLS batch. ACCENT = "#F97415" # Neutral fallback for any control material without a dedicated color. CONTROL_COLOR = "#6B7280" def apply_house_style() -> None: """Register DM Sans and set the AdditiveLLM2 rcParams. Idempotent.""" for ttf in sorted(FONT_DIR.glob("*.ttf")): fm.fontManager.addfont(str(ttf)) plt.rcParams.update({ "font.family": "DM Sans", "axes.linewidth": 1.4, # heavy framed spines "axes.titlesize": 13, "axes.titleweight": "bold", "axes.labelsize": 12, "xtick.labelsize": 10, "ytick.labelsize": 10, "xtick.direction": "in", # inward ticks "ytick.direction": "in", "xtick.major.size": 4, "ytick.major.size": 4, "xtick.major.width": 1.2, "ytick.major.width": 1.2, "legend.fontsize": 10, "legend.frameon": True, "legend.framealpha": 0.95, "legend.edgecolor": "#D1D5DB", "grid.linestyle": "--", "grid.linewidth": 1.0, "grid.alpha": 0.4, "grid.color": "#B0B0B0", "savefig.dpi": EXPORT_DPI, }) def style_axes(ax) -> None: """Apply the framed look to one Axes: light dashed grid behind the data, origin anchored at zero. Spines/ticks come from rcParams.""" ax.grid(True, zorder=0) ax.set_axisbelow(True) ax.set_xlim(left=0) ax.set_ylim(bottom=0) def save_figure(fig, out_stem: Path) -> Path: """Write `out_stem.png` (dpi=EXPORT_DPI) and `out_stem.pdf`, matching the AdditiveLLM2 dual-format export. Returns the PNG path.""" out_stem.parent.mkdir(parents=True, exist_ok=True) png = out_stem.with_suffix(".png") fig.savefig(png, dpi=EXPORT_DPI, bbox_inches="tight", pad_inches=0.15) fig.savefig(out_stem.with_suffix(".pdf"), bbox_inches="tight", pad_inches=0.15) return png apply_house_style() # ── Batch color ramp ────────────────────────────────────────────────────────── # Ordered list of every batch label, in print chronology. J_MB (media-blasted # variant of print J) sits right after J so the two share a neighborhood on the # ramp — encoding their shared print origin — while staying distinct. ORDERED_BATCHES = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "J_MB", "K", "L", "M", "N"] # The 15 batches are chronological, so their color is an *ordered ramp* rather # than an arbitrary categorical cycle: a warm gold→orange→brown sweep built # around the signature #F97415 orange (ACCENT) — the whole batch palette is # "based off that shade of orange" per user instruction. Adjacent batches read # as neighbors — intended, since batch order is time order — and the legend + # curve position disambiguate within a figure. The FormLabs reference series is # deliberately *not* orange (see FORMLABS_COLOR) so it stands apart from the # batches it's benchmarked against. _RAMP = mcolors.LinearSegmentedColormap.from_list( "batch_ramp", ["#F7C948", "#F9931E", ACCENT, "#C7430C", "#6E2206"]) def _build_batch_colors() -> dict[str, str]: n = len(ORDERED_BATCHES) return {batch: mcolors.to_hex(_RAMP(i / (n - 1))) for i, batch in enumerate(ORDERED_BATCHES)} # Kept consistent across figures so e.g. batch C is the same color everywhere. BATCH_COLORS = _build_batch_colors() # The FormLabs PA12GF benchtop reference is drawn in a contrasting blue rather # than the orange batch family, so on the cluster / batch-average figures it # reads clearly as the external benchmark the SLS batches are compared against. FORMLABS_COLOR = REF_BLUE # Non-SLS materials get explicit reference-palette colors (rather than a shared # gray) so they read as intentional on their own figures. MATERIAL_COLORS = { "PA12GF_FL": FORMLABS_COLOR, # FormLabs PA12 GF reference → contrasting blue "NYLON12_WHITE_FL": REF_PURPLE, # FormLabs Nylon 12 White reference "PLA": REF_BLUE, "PETG": REF_TEAL, } MATERIAL_STYLES = {"SLS": "-", "PLA": "--", "PETG": ":"} # Non-default ASTM specimen types get their own linestyle so e.g. Batch M's # Type IV (narrow-section) tensile specimens are visually tagged apart from # its Type I specimens without needing a separate batch letter or color. TYPE_LINESTYLES = {"Type IV": "--"} FILAMENT_CONTROLS = {"PLA", "PETG"} # FormLabs SLS reference-material controls that get their own dedicated # figures instead of joining the main SLS composite/batch-averages plots — # see scripts/plots/01_composite.py's module docstring. NYLON_CONTROLS = {"NYLON12_WHITE_FL"} # D638 (tensile) materials whose raw curve continues past the stress peak as # a near-straight diagonal decline back toward zero — the crosshead keeps # extending after the specimen separates while load reads ~0, and with few # points sampled through the break itself this draws as a misleading # diagonal rather than the near-vertical drop a real break shows (as seen in # the other SLS batches, whose analyzed curves have many points through the # break). Per user instruction, these curves are cut at their stress peak # and given a synthetic vertical drop to zero at that same strain, matching # the other batches' visual convention. D790 rows aren't affected: their # break isn't a full separation the same way, and their curves don't show # this artifact. VERTICAL_BREAK_MATERIALS = {"NYLON12_WHITE_FL"} def vertical_break_at_peak(strain: list[float], stress_mpa: list[float]) -> tuple[list[float], list[float]]: """Cut the curve at its stress peak and append a point at zero stress, same strain, so it plots as a vertical drop — used for the individual raw-curve figure. See VERTICAL_BREAK_MATERIALS.""" if not stress_mpa: return strain, stress_mpa peak_i = max(range(len(stress_mpa)), key=lambda i: stress_mpa[i]) return strain[:peak_i + 1] + [strain[peak_i]], stress_mpa[:peak_i + 1] + [0.0] def truncate_at_peak(strain: list[float], stress_mpa: list[float]) -> tuple[list[float], list[float]]: """Cut the curve at its stress peak with no added point — used for the mean +/- SD average figure, where a synthetic vertical segment would distort the shared strain grid / averaging. See VERTICAL_BREAK_MATERIALS.""" if not stress_mpa: return strain, stress_mpa peak_i = max(range(len(stress_mpa)), key=lambda i: stress_mpa[i]) return strain[:peak_i + 1], stress_mpa[:peak_i + 1] def load_specimen(path: Path) -> dict | None: with path.open() as f: row = json.loads(f.readline()) pairs = [ (s, t) for s, t in zip(row["curves"]["strain"], row["curves"]["stress_pa"]) if s is not None and t is not None ] if not pairs: return None strain, stress_pa = zip(*pairs) return { "row": row, "strain": list(strain), "stress_mpa": [t / 1e6 for t in stress_pa], } def load_standard(standard: str) -> list[dict]: """Load every specimen with a non-empty curve for a config. Callers that need the VERTICAL_BREAK_MATERIALS peak-cut apply it themselves (see vertical_break_at_peak / truncate_at_peak) — the two figures that need it want different treatments (synthetic vertical drop vs. plain cut), so it isn't baked into this loader.""" paths = sorted((DATA_DIR / standard).glob("*.jsonl")) return [s for p in paths if (s := load_specimen(p))] def style_for(row: dict) -> tuple[str, str]: material = row["material_class"] batch = row["batch_label"] if material == "SLS": color = BATCH_COLORS.get(batch, CONTROL_COLOR) linestyle = TYPE_LINESTYLES.get(row["astm"].get("type"), "-") else: color = MATERIAL_COLORS.get(material, CONTROL_COLOR) linestyle = MATERIAL_STYLES.get(material, "-") return color, linestyle