File size: 8,452 Bytes
5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b 5a9a305 386cb7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | #!/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'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.
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, CONTROL_COLOR, NYLON_CONTROLS, OUT_DIR, ROOT, TYPE_LINESTYLES,
VERTICAL_BREAK_MATERIALS, load_standard, 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.
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"]:
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)."""
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 render_bands(groups: dict[str, list[dict]], group_style: dict[str, tuple[str, str]],
title: str, out_path) -> 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.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)")
ax.set_title(title)
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)
fig.savefig(out_path, dpi=150, bbox_inches="tight")
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.png")
def plot_nylon12white_standard(standard: str) -> None:
specs = load_standard(standard)
if standard == "D638":
# Cut at the stress peak (no synthetic point — see truncate_at_peak's
# docstring for why the averaged figure gets a plain cut instead of
# the raw-curve figure's vertical drop).
for s in specs:
if s["row"]["material_class"] in VERTICAL_BREAK_MATERIALS:
s["strain"], s["stress_mpa"] = truncate_at_peak(s["strain"], s["stress_mpa"])
groups = grouped_specs(
specs, lambda row: "NYLON12_WHITE_FL" if row["material_class"] in NYLON_CONTROLS else None)
group_style = {"NYLON12_WHITE_FL": (CONTROL_COLOR, "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.png")
if __name__ == "__main__":
plot_standard("D638")
plot_standard("D790")
plot_nylon12white_standard("D638")
plot_nylon12white_standard("D790")
|