#!/usr/bin/env python3 """Batch-cluster overview — the canonical "all batches at a glance" figure, replacing the old overlaid composite (which, at 76-80 curves, was unreadable spaghetti; see git history / README). Each specimen collapses to a single point at its stress-strain **peak**: x = strain at peak, y = ultimate strength (peak stress). Peak is derived as max(stress) over the saved curve rather than read from the persistent.h5 PeakStress field — TestWorks often fails to detect the peak for D638 tensile and leaves that scalar null (see CLAUDE.md), but the full curve is always saved, so the maximum is robust. Each SLS batch (plus the FormLabs PA12GF benchtop reference) becomes a cluster of its specimens' peak points, wrapped in a translucent convex-hull boundary in the batch color with a legend entry. This carries the headline ultimate-strength number and shows how tightly each batch clusters (strength-vs-ductility), with none of the overlaid-curve clutter. To read the actual stress-strain curves for one batch, see the per-batch detail figures (scripts/plots/04_batch_details.py, assets/batches/{standard}_{batch}.png). Excluded, same as the old composite: PLA/PETG filament controls, the FormLabs Nylon 12 White control, and Batch M's Type IV specimens (different gauge geometry) — all of which have their own dedicated figures. Outputs assets/{standard}_batch_clusters.png (dpi=1200) + .pdf. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Ellipse from matplotlib.colors import to_rgba from _lib import (BATCH_COLORS, FILAMENT_CONTROLS, FORMLABS_COLOR, NYLON_CONTROLS, ORDERED_BATCHES, OUT_DIR, ROOT, TYPE_LINESTYLES, load_standard, save_figure, style_axes) # Cluster boundary size, in standard deviations along each principal axis. 1.0 # draws the ±1 SD spread of each batch's peak points (matching the ±1 SD # convention in 02_batch_averages.py) — some points fall outside by design. N_STD = 1.0 # Group order: SLS batches (print chronology) then the FormLabs reference last. GROUP_ORDER = ORDERED_BATCHES + ["PA12GF_FL"] GROUP_LABELS = {**{b: f"Batch {b}" for b in ORDERED_BATCHES}, "PA12GF_FL": "FormLabs PA12GF"} GROUP_COLORS = {**BATCH_COLORS, "PA12GF_FL": FORMLABS_COLOR} def group_key(row: dict) -> str | None: """Cluster membership: SLS batch label, or the FormLabs PA12GF reference. Everything with its own dedicated figure returns None (excluded).""" 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: return None # Type IV etc. — different geometry, own figure return row["batch_label"] or None def peak_point(spec: dict) -> tuple[float, float]: """(strain_at_peak, ultimate_stress_mpa) from the specimen's saved curve.""" stress = spec["stress_mpa"] peak_i = max(range(len(stress)), key=lambda i: stress[i]) return spec["strain"][peak_i], stress[peak_i] def confidence_ellipse(points: list[tuple[float, float]], ax, color, n_std: float = N_STD): """Draw a covariance-based n_std confidence ellipse for a cluster of points. Requires >=3 points for a non-degenerate covariance; the 1-2 point cases are handled by the caller (segment / bare marker).""" pts = np.asarray(points, dtype=float) cov = np.cov(pts, rowvar=False) vals, vecs = np.linalg.eigh(cov) # ascending eigenvalues, orthonormal vecs order = vals.argsort()[::-1] vals, vecs = vals[order], vecs[:, order] vals = np.clip(vals, 0.0, None) # guard tiny negative from round-off angle = np.degrees(np.arctan2(vecs[1, 0], vecs[0, 0])) width, height = 2 * n_std * np.sqrt(vals) # full axis lengths ax.add_patch(Ellipse( xy=pts.mean(axis=0), width=width, height=height, angle=angle, facecolor=to_rgba(color, 0.15), edgecolor=to_rgba(color, 0.75), linewidth=1.4, zorder=2)) def render(standard: str, groups: dict[str, list[tuple[float, float]]], ylabel: str, title: str) -> None: fig, ax = plt.subplots(figsize=(9, 6)) handles = [] for key in GROUP_ORDER: pts = groups.get(key) if not pts: continue color = GROUP_COLORS[key] xs = [x for x, _ in pts] ys = [y for _, y in pts] # Cluster boundary: ±N_STD confidence ellipse (>=3 pts), a connecting # segment (2 pts), or nothing (1 pt — just the marker). if len(pts) >= 3: confidence_ellipse(pts, ax, color) elif len(pts) == 2: ax.plot(xs, ys, color=color, linewidth=1.4, alpha=0.7, zorder=3) ax.scatter(xs, ys, s=48, color=color, edgecolor="white", linewidth=0.6, zorder=5, alpha=0.95) handles.append(Line2D([0], [0], marker="o", linestyle="none", color=color, markeredgecolor="white", markeredgewidth=0.6, markersize=8, label=f"{GROUP_LABELS[key]} (n={len(pts)})")) ax.set_xlabel("Strain at peak (mm/mm)") ax.set_ylabel(ylabel) ax.set_title(title) style_axes(ax) ax.legend(handles=handles, loc="upper left", bbox_to_anchor=(1.02, 1.0), borderaxespad=0) out_path = save_figure(fig, OUT_DIR / f"{standard}_batch_clusters") plt.close(fig) print(f"wrote {out_path.relative_to(ROOT)} ({len(handles)} clusters)") def plot_standard(standard: str) -> None: specs = load_standard(standard) groups: dict[str, list[tuple[float, float]]] = {} for s in specs: key = group_key(s["row"]) if key is None: continue groups.setdefault(key, []).append(peak_point(s)) ylabel = {"D638": "Ultimate tensile strength (MPa)", "D790": "Ultimate flexural strength (MPa)"}.get(standard, "Ultimate strength (MPa)") title = {"D638": "ASTM D638 — tensile batch clusters (peak point per specimen)", "D790": "ASTM D790 — flexural batch clusters (peak point per specimen)"}.get( standard, standard) render(standard, groups, ylabel, title) if __name__ == "__main__": plot_standard("D638") plot_standard("D790")