| """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" |
|
|
| |
|
|
| |
| |
| EXPORT_DPI = 1200 |
|
|
| |
| |
| REF_BLUE = "#2D6A9F" |
| REF_TEAL = "#2AAA8A" |
| REF_REDORANGE = "#D44000" |
| REF_PURPLE = "#8B5CF6" |
| |
| |
| |
| |
| ACCENT = "#F97415" |
|
|
| |
| 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, |
| "axes.titlesize": 13, |
| "axes.titleweight": "bold", |
| "axes.labelsize": 12, |
| "xtick.labelsize": 10, |
| "ytick.labelsize": 10, |
| "xtick.direction": "in", |
| "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() |
|
|
| |
|
|
| |
| |
| |
| ORDERED_BATCHES = ["A", "B", "C", "D", "E", "F", "G", "H", "I", |
| "J", "J_MB", "K", "L", "M", "N"] |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| _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)} |
|
|
|
|
| |
| BATCH_COLORS = _build_batch_colors() |
|
|
| |
| |
| |
| FORMLABS_COLOR = REF_BLUE |
|
|
| |
| |
| MATERIAL_COLORS = { |
| "PA12GF_FL": FORMLABS_COLOR, |
| "NYLON12_WHITE_FL": REF_PURPLE, |
| "PLA": REF_BLUE, |
| "PETG": REF_TEAL, |
| } |
|
|
| MATERIAL_STYLES = {"SLS": "-", "PLA": "--", "PETG": ":"} |
|
|
| |
| |
| |
| TYPE_LINESTYLES = {"Type IV": "--"} |
|
|
| FILAMENT_CONTROLS = {"PLA", "PETG"} |
|
|
| |
| |
| |
| NYLON_CONTROLS = {"NYLON12_WHITE_FL"} |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| 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 |
|
|