#!/usr/bin/env python3 """Per-batch detail figures — one clean stress-strain plot per batch, so the individual specimen curves can actually be read (the "look deeper into one batch" companion to the batch-cluster overview in 03_batch_clusters.py). One figure per SLS batch (plus the FormLabs PA12GF reference) per standard, written to assets/batches/{standard}_{batch}.png (+ .pdf). Within a figure each specimen gets its own color (tab10) and a legend entry keyed by sample_id, so a batch's ~5-10 curves stay individually legible. Excluded (they have their own dedicated figures): PLA/PETG controls, the FormLabs Nylon 12 White control, and Batch M's Type IV specimens. """ import matplotlib.pyplot as plt from _lib import (BATCH_COLORS, BATCH_MATERIAL_LABEL, FILAMENT_CONTROLS, FORMLABS_COLOR, NYLON_CONTROLS, OUT_DIR, ROOT, TYPE_IV_DEDICATED_BATCHES, TYPE_LINESTYLES, load_standard, save_figure, style_axes) BATCHES_DIR = OUT_DIR / "batches" def group_key(row: dict) -> str | None: """Same membership as the cluster overview: SLS batch label or the FormLabs PA12GF reference; everything with its own figure is excluded — except a Type IV batch NOT in TYPE_IV_DEDICATED_BATCHES (e.g. Nylon 11 Batches O/P), which still gets a normal per-batch detail figure here rather than Batch M's combined-figure treatment in 01_controls.py.""" if row["material_class"] == "PA12GF_FL": return "PA12GF_FL" if row["material_class"] in FILAMENT_CONTROLS or row["material_class"] in NYLON_CONTROLS: return None if row["astm"].get("type") in TYPE_LINESTYLES and row["batch_label"] in TYPE_IV_DEDICATED_BATCHES: return None return row["batch_label"] or None def specimen_label(row: dict) -> str: return row.get("sample_id") or row["specimen_id"].split("/")[-1] def specimen_sort_key(spec: dict): """Order by sample_id numeric suffix (C1, C2, …) when present, else by the fully-qualified specimen_id so ordering is at least stable.""" sid = spec["row"].get("sample_id") if sid: digits = "".join(c for c in sid if c.isdigit()) if digits: return (0, int(digits)) return (1, spec["row"]["specimen_id"]) def group_title(standard: str, key: str, n: int) -> str: test = {"D638": "tensile", "D790": "flexural"}.get(standard, "") name = "FormLabs PA12GF" if key == "PA12GF_FL" else f"Batch {key}" material_hint = BATCH_MATERIAL_LABEL.get(key) if material_hint: name += f" ({material_hint})" return f"ASTM {standard} — {name} {test} ({n} specimen{'s' if n != 1 else ''})" def render(standard: str, key: str, specs: list[dict]) -> None: specs = sorted(specs, key=specimen_sort_key) accent_color = FORMLABS_COLOR if key == "PA12GF_FL" else BATCH_COLORS.get(key, FORMLABS_COLOR) fig, ax = plt.subplots(figsize=(8, 5.5)) cmap = plt.get_cmap("tab10") for i, s in enumerate(specs): ax.plot(s["strain"], s["stress_mpa"], color=cmap(i % 10), linewidth=1.6, alpha=0.9, zorder=3, label=specimen_label(s["row"])) ax.set_xlabel("Strain (mm/mm)") ax.set_ylabel("Stress (MPa)") ax.set_title(group_title(standard, key, len(specs)), color=accent_color) style_axes(ax) ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1.0), borderaxespad=0, title="Specimen") out_path = save_figure(fig, BATCHES_DIR / f"{standard}_{key}") plt.close(fig) print(f"wrote {out_path.relative_to(ROOT)} ({len(specs)} curves)") def plot_standard(standard: str) -> None: specs = load_standard(standard) groups: dict[str, list[dict]] = {} for s in specs: key = group_key(s["row"]) if key is None: continue groups.setdefault(key, []).append(s) for key, group in groups.items(): render(standard, key, group) if __name__ == "__main__": plot_standard("D638") plot_standard("D790")