Agentic-SLS-ASTM / scripts /plots /02_batch_averages.py
ppak10's picture
Data update (#6)
5a9a305
Raw
History Blame Contribute Delete
5.63 kB
#!/usr/bin/env python3
"""Render per-batch mean stress-strain curves with +/- 1 SD error *channels*
(shaded bands) for our SLS Nylon 12 GF prints plus the FormLabs PA12GF
benchtop control, one figure per standard.
Groups plotted: every SLS batch (rows with a non-null batch_label) and the
FormLabs PA12GF_FL control, since it's the same nominal material (Nylon 12
GF) printed on different hardware and is the reference point the SLS batches
are being compared against. PLA/PETG filament controls are still excluded —
different material entirely, and they already have their own figure
(assets/D638_controls.png).
Each specimen's analyzed stress-strain curve is resampled onto a common
strain grid via linear interpolation (`np.interp`; strain is monotonically
increasing in every specimen, so this is safe), then averaged pointwise
across the group. The grid runs from 0 to the *shortest* specimen's max
strain in that group, so every point in the mean curve is backed by the same
number of specimens — n doesn't quietly shrink as strain increases past where
some specimens have already broken.
The shaded band is +/- 1 sample standard deviation across specimens at each
strain value (ddof=1). This is specimen-to-specimen variability (print
placement, powder packing, sintering, etc.), which dominates over
DAQ/instrument noise here — that's the source of scatter worth showing, so a
per-point stddev across replicates is more informative than propagating
instrument measurement uncertainty through the curve.
With this many groups, overlapping fills of the same low alpha turn to mud
where two bands cover the same region, so each band's own upper/lower edge is
also traced with a thin, more opaque line in the group's color — that gives
every band a visible boundary to follow even where fills stack.
A specimen with a degenerate curve (too few points to be a real stress-strain
trace, e.g. D790 E6 at 3 points vs. ~2000 for its batch-mates) is excluded
from its group's average — otherwise the shared strain grid (bounded by the
*shortest* max strain in the group, so every point has full sample size)
collapses to near-zero width for the whole group.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from _lib import BATCH_COLORS, CONTROL_COLOR, OUT_DIR, ROOT, load_standard
N_POINTS = 100
BAND_ALPHA = 0.12
EDGE_ALPHA = 0.75
MIN_CURVE_POINTS = 20 # below this a curve is degenerate, not just short
FORMLABS_LABEL = "FormLabs PA12GF"
# Ordered group -> (color, legend label). SLS batches first, FormLabs last.
GROUP_STYLE = {batch: (color, f"Batch {batch}") for batch, color in BATCH_COLORS.items()}
GROUP_STYLE["PA12GF_FL"] = (CONTROL_COLOR, FORMLABS_LABEL)
def group_key(row: dict) -> str | None:
if row["batch_label"]:
return row["batch_label"]
if row["material_class"] == "PA12GF_FL":
return "PA12GF_FL"
return None # PLA/PETG controls — excluded, see module docstring
def group_average(specs: list[dict]) -> tuple[np.ndarray, np.ndarray, np.ndarray, int]:
"""specs: per-specimen {"strain": [...], "stress_mpa": [...]}.
Returns (strain_grid, mean_stress, std_stress, n_specimens)."""
max_strain = min(max(s["strain"]) for s in specs)
grid = np.linspace(0, max_strain, N_POINTS)
curves = np.array([np.interp(grid, s["strain"], s["stress_mpa"]) for s in specs])
n = len(specs)
std = curves.std(axis=0, ddof=1) if n > 1 else np.zeros_like(grid)
return grid, curves.mean(axis=0), std, n
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
if len(s["strain"]) < MIN_CURVE_POINTS:
print(f" skipping {s['row']['specimen_id']} (group {key}): "
f"degenerate curve, only {len(s['strain'])} points")
continue
groups.setdefault(key, []).append(s)
fig, ax = plt.subplots(figsize=(9, 6))
handles = []
for key, (color, label) in GROUP_STYLE.items():
group = groups.get(key)
if not group:
continue
grid, mean, std, n = group_average(group)
ax.plot(grid, mean, color=color, linewidth=1.6, alpha=0.95)
ax.fill_between(grid, mean - std, mean + std, color=color, alpha=BAND_ALPHA,
linewidth=0)
# Trace each band's own edges so overlapping fills don't turn to mud.
ax.plot(grid, mean + std, color=color, linewidth=0.8, alpha=EDGE_ALPHA)
ax.plot(grid, mean - std, color=color, linewidth=0.8, alpha=EDGE_ALPHA)
handles.append(Patch(facecolor=color, edgecolor=color, alpha=0.6,
label=f"{label} (n={n})"))
ax.set_xlabel("Strain (mm/mm)")
ax.set_ylabel("Stress (MPa)")
title_map = {"D638": "ASTM D638 — tensile batch averages (± 1 SD)",
"D790": "ASTM D790 — three-point flex batch averages (± 1 SD)"}
ax.set_title(title_map.get(standard, standard))
ax.grid(True, alpha=0.3)
ax.set_xlim(left=0)
ax.set_ylim(bottom=0)
ax.legend(handles=handles, loc="upper left", bbox_to_anchor=(1.02, 1.0),
borderaxespad=0, fontsize=9, framealpha=0.9)
OUT_DIR.mkdir(parents=True, exist_ok=True)
out_path = OUT_DIR / f"{standard}_batch_averages.png"
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"wrote {out_path.relative_to(ROOT)} ({len(handles)} groups)")
if __name__ == "__main__":
plot_standard("D638")
plot_standard("D790")