#!/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). The FormLabs Nylon 12 White control is also excluded here — it gets its own figure (assets/{standard}_nylon12white_control.png, see 01_composite.py) per user instruction, same rationale as PLA/PETG. Batch M mixes two ASTM D638 specimen types from the same print (5 Type I dogbones, 12 narrow-section Type IV) — the Type IV specimens are excluded from this figure entirely (per user instruction, same treatment as the Nylon 12 White control) rather than averaged in with Batch M's Type I mean: their geometry isn't comparable (different gauge cross-section -> different modulus/strain response), and they get their own raw-curve figure at assets/D638_type_iv.png instead (see 01_composite.py). Each specimen is first trimmed at its own stress peak (loading branch only), then resampled onto a common strain grid via linear interpolation (`np.interp`; strain is monotonically increasing, so this is safe) and averaged pointwise across the group. Trimming at peak matters: past peak the trace is the fracture/softening branch, whose steep drop — once resampled — made the last grid points swing wildly (one specimen already dropping while others still rise), inflating the per-point std into a spurious spike at each band's end. The grid runs from 0 to the *shortest* specimen's peak 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. 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* peak strain in the group, so every point has full sample size) collapses to near-zero width for the whole group. A second figure, assets/{standard}_nylon12white_average.png, applies the same mean +/- 1 SD banding to just the FormLabs Nylon 12 White control (per user instruction) — same method as above, just a single group instead of the full batch comparison, and kept as its own figure rather than joining the main one for the same reason it's excluded from the main figure above. """ import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Patch from _lib import (BATCH_COLORS, FORMLABS_COLOR, MATERIAL_COLORS, NYLON_CONTROLS, OUT_DIR, ROOT, TYPE_LINESTYLES, load_standard, save_figure, style_axes, truncate_at_peak) 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. # The FormLabs reference control gets a contrasting color (see _lib.FORMLABS_COLOR) # so it stands apart from the orange batch family. GROUP_STYLE = {batch: (color, f"Batch {batch}") for batch, color in BATCH_COLORS.items()} GROUP_STYLE["PA12GF_FL"] = (FORMLABS_COLOR, FORMLABS_LABEL) def group_key(row: dict) -> str | None: if row["batch_label"]: if row["astm"].get("type") in TYPE_LINESTYLES: return None # Type IV etc. — excluded, see module docstring return row["batch_label"] if row["material_class"] == "PA12GF_FL": return "PA12GF_FL" return None # PLA/PETG and Nylon 12 White 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). Each specimen is first trimmed at its own stress peak (truncate_at_peak): past peak the trace is the fracture/softening branch, whose steep drop — once resampled onto the common grid — made the last grid points swing wildly (one specimen already dropping while others still rise), inflating the std into a spurious spike at the band's end. Averaging only the loading branch up to peak removes that artifact. The grid is then bounded by the *shortest* peak-strain in the group, so every point in the mean is backed by the full specimen count.""" trimmed = [truncate_at_peak(s["strain"], s["stress_mpa"]) for s in specs] max_strain = min(max(strain) for strain, _ in trimmed) grid = np.linspace(0, max_strain, N_POINTS) curves = np.array([np.interp(grid, strain, stress) for strain, stress in trimmed]) 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 render_bands(groups: dict[str, list[dict]], group_style: dict[str, tuple[str, str]], title: str, out_stem) -> None: """Draw one mean +/- 1 SD band per group, in group_style's order.""" 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.8, alpha=0.95, zorder=4) ax.fill_between(grid, mean - std, mean + std, color=color, alpha=BAND_ALPHA, linewidth=0, zorder=2) # 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, zorder=3) ax.plot(grid, mean - std, color=color, linewidth=0.8, alpha=EDGE_ALPHA, zorder=3) 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)") 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_stem) plt.close(fig) print(f"wrote {out_path.relative_to(ROOT)} ({len(handles)} groups)") def grouped_specs(specs: list[dict], key_fn) -> dict[str, list[dict]]: groups: dict[str, list[dict]] = {} for s in specs: key = key_fn(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) return groups def plot_standard(standard: str) -> None: specs = load_standard(standard) groups = grouped_specs(specs, group_key) title_map = {"D638": "ASTM D638 — tensile batch averages (± 1 SD)", "D790": "ASTM D790 — three-point flex batch averages (± 1 SD)"} render_bands(groups, GROUP_STYLE, title_map.get(standard, standard), OUT_DIR / f"{standard}_batch_averages") def plot_nylon12white_standard(standard: str) -> None: # group_average() trims every specimen at its stress peak, so the D638 Nylon # 12 White break artifact (VERTICAL_BREAK_MATERIALS) is handled there too — # no material-specific pre-trim needed here. specs = load_standard(standard) groups = grouped_specs( specs, lambda row: "NYLON12_WHITE_FL" if row["material_class"] in NYLON_CONTROLS else None) group_style = {"NYLON12_WHITE_FL": (MATERIAL_COLORS["NYLON12_WHITE_FL"], "FormLabs Nylon 12 White")} title_map = {"D638": "ASTM D638 — FormLabs Nylon 12 White average (± 1 SD)", "D790": "ASTM D790 — FormLabs Nylon 12 White average (± 1 SD)"} render_bands(groups, group_style, title_map.get(standard, standard), OUT_DIR / f"{standard}_nylon12white_average") if __name__ == "__main__": plot_standard("D638") plot_standard("D790") plot_nylon12white_standard("D638") plot_nylon12white_standard("D790")