Download scripts/plots/05_layout_maps.py from ppak10/Agentic-SLS-ASTM: direct link, hf CLI and curl.
- Browser
- Download file 8.81 kB
-
https://huggingface.co/datasets/ppak10/Agentic-SLS-ASTM/resolve/main/scripts/plots/05_layout_maps.py
- Command line
-
hf download hf://datasets/ppak10/Agentic-SLS-ASTM/scripts/plots/05_layout_maps.py
-
curl -L -o 05_layout_maps.py https://huggingface.co/datasets/ppak10/Agentic-SLS-ASTM/resolve/main/scripts/plots/05_layout_maps.py
8.81 kB
| #!/usr/bin/env python3 | |
| """Build-plate modulus maps for the stacked Type IV prints (Batches Q-U). | |
| One figure per batch, two panels: the D638 Type IV specimens as they sat on | |
| the build plate, lower stack (samples 1-7, first ~70 layers) beside upper | |
| stack (samples 8-14, printed directly above in the same XY slots). Each | |
| specimen outline is a real cross-section of its numbered STL taken just | |
| below the top face, so the engraved "A n"/"B n" grip identifiers render as | |
| unfilled engravings — the same marks used to identify the physical parts. | |
| Fill color encodes the tensile chord modulus (0.05-0.25% strain, ISO | |
| 527-style), computed from each specimen's stress-strain curve at plot time: | |
| the Q-U exports are curve-only, so the dataset deliberately carries no | |
| TestWorks modulus scalar for them (see CLAUDE.md), and the chord method | |
| reproduces TestWorks moduli within ~5% on batches that have both. | |
| The color scale is normalized PER MATERIAL FAMILY (PA11 Onyx: Q+R; PA12 | |
| White/GF blend: S+T+U) so batches of the same powder compare directly | |
| without a cross-material scale washing out either family's contrast — the | |
| colorbar range on each figure states its family's span. Specimens with no | |
| curve draw with the layout intact: broken-after-print specimens (Batch Q's | |
| specimen 7) as gray hatched outlines; never-printed specimens (Batch S's | |
| upper stack — its build was soft-canceled as that level began) as faint | |
| dashed outlines. Axes bounds are exactly the 161x161 mm plate, so | |
| part-to-edge padding reads true. | |
| Geometry inputs live in source/objects/: the 14 numbered STLs and | |
| d638_type4_stacked_layout.json (per-part firmware MeshPrintTransform | |
| matrices + provenance for every print of this template job — all share the | |
| same XY placement; see the JSON's description for the Z-scale nuance). | |
| Transform convention is row-major V*M applied to the mesh recentered on its | |
| bounds center (firmware convention). | |
| Outputs: assets/batches/D638_{Q,R,S,T,U}_layout.png/.pdf | |
| """ | |
| import json | |
| import numpy as np | |
| import trimesh | |
| import matplotlib.pyplot as plt | |
| import matplotlib.colors as mcolors | |
| from matplotlib.cm import ScalarMappable | |
| from matplotlib.patches import PathPatch | |
| from matplotlib.path import Path as MplPath | |
| from _lib import DATA_DIR, OUT_DIR, ROOT, load_specimen, save_figure | |
| OBJECTS_DIR = ROOT / "source" / "objects" | |
| LAYOUT = json.loads((OBJECTS_DIR / "d638_type4_stacked_layout.json").read_text()) | |
| # material families share a color normalization; batch order inside a family | |
| # only affects figure generation order | |
| FAMILIES = [ | |
| ("PA11 Onyx", ["Q", "R"]), | |
| ("PA12 White/GF blend", ["S", "T", "U"]), | |
| ] | |
| # samples that were never printed (build canceled before their stack) — drawn | |
| # as faint dashed outlines, distinct from broken-after-print (gray hatch) | |
| UNPRINTED = {"S": set(range(8, 15))} | |
| # Slice this far below each part's top face — deep enough to cut through the | |
| # engraved identifiers (so they render as holes), shallower than the engrave | |
| # depth everywhere else. | |
| SLICE_BELOW_TOP_MM = 0.3 | |
| POWDER_BG = "#EFE7DD" | |
| BROKEN_FC, BROKEN_HATCH = "#C9C2B8", "///" | |
| UNPRINTED_EDGE = "#B9B1A4" | |
| # Sequential fill ramp: the batch color ramp's gold->deep-brown sweep (see | |
| # _lib.ORDERED_BATCHES notes), reused here as a continuous modulus scale so | |
| # the layout maps stay in the house palette. | |
| MODULUS_RAMP = mcolors.LinearSegmentedColormap.from_list( | |
| "modulus_ramp", ["#F7C948", "#F9931E", "#F97415", "#C7430C", "#6E2206"]) | |
| def chord_modulus_mpa(spec: dict) -> float | None: | |
| """Tensile chord modulus between 0.05% and 0.25% strain (ISO 527 window), | |
| linearly interpolated on the analyzed stress-strain curve.""" | |
| pairs = sorted(zip(spec["strain"], spec["stress_mpa"])) | |
| strain = [p[0] for p in pairs] | |
| stress = [p[1] for p in pairs] | |
| def at(x: float) -> float | None: | |
| for i in range(1, len(strain)): | |
| if strain[i] >= x: | |
| s0, s1, t0, t1 = strain[i - 1], strain[i], stress[i - 1], stress[i] | |
| return t0 + (t1 - t0) * (x - s0) / (s1 - s0) | |
| return None | |
| lo, hi = at(0.0005), at(0.0025) | |
| if lo is None or hi is None: | |
| return None | |
| return (hi - lo) / 0.002 | |
| def top_slice_polys(stl_path) -> list[tuple[np.ndarray, list[np.ndarray]]]: | |
| """Cross-section polygons (exterior, holes) just below the mesh top face, | |
| in mesh coordinates recentered on the bounds center — the frame the | |
| firmware transform expects.""" | |
| mesh = trimesh.load(stl_path) | |
| z_top = mesh.bounds[1][2] | |
| section = mesh.section(plane_origin=[0, 0, z_top - SLICE_BELOW_TOP_MM], | |
| plane_normal=[0, 0, 1]) | |
| planar, to_3d = section.to_2D() | |
| center = (mesh.bounds[0] + mesh.bounds[1]) / 2.0 | |
| def back(coords) -> np.ndarray: | |
| pts = np.array([[x, y, 0.0, 1.0] for x, y in coords]) @ to_3d.T | |
| return pts[:, :2] - center[:2] | |
| return [(back(p.exterior.coords), [back(h.coords) for h in p.interiors]) | |
| for p in planar.polygons_full] | |
| def to_plate(pts2d: np.ndarray, transform: list) -> np.ndarray: | |
| """Recentered mesh XY -> plate XY via the row-major V*M firmware matrix.""" | |
| pts = np.hstack([pts2d, np.zeros((len(pts2d), 1)), np.ones((len(pts2d), 1))]) | |
| return (pts @ np.array(transform))[:, :2] | |
| def specimen_patch(sample: int, transform: list, facecolor, hatch, | |
| edgecolor="black", linestyle="solid") -> PathPatch: | |
| verts: list[tuple[float, float]] = [] | |
| codes: list[int] = [] | |
| stl = OBJECTS_DIR / "d638_type_4_numbered" / f"d638_type4_{sample}.STL" | |
| for exterior, holes in top_slice_polys(stl): | |
| for ring in [exterior, *holes]: | |
| ring_pts = [tuple(p) for p in to_plate(ring, transform)] | |
| verts += ring_pts | |
| codes += [MplPath.MOVETO] + [MplPath.LINETO] * (len(ring_pts) - 2) + [MplPath.CLOSEPOLY] | |
| return PathPatch(MplPath(verts, codes), facecolor=facecolor, hatch=hatch, | |
| edgecolor=edgecolor, linewidth=0.6, linestyle=linestyle, zorder=2) | |
| def main() -> None: | |
| transforms = {p["sample"]: p["transform"] for p in LAYOUT["parts"]} | |
| plate_x, plate_y = LAYOUT["plate_mm"]["x"], LAYOUT["plate_mm"]["y"] | |
| for family, batches in FAMILIES: | |
| run_family(family, batches, transforms, plate_x, plate_y) | |
| def run_family(family: str, batches: list[str], transforms: dict, | |
| plate_x: float, plate_y: float) -> None: | |
| moduli: dict[tuple[str, int], float] = {} | |
| for batch in batches: | |
| for path in sorted((DATA_DIR / "D638").glob(f"{batch}*.jsonl")): | |
| spec = load_specimen(path) | |
| if spec is None: | |
| continue | |
| sample = int(path.stem.removeprefix(batch)) | |
| mod = chord_modulus_mpa(spec) | |
| if mod is not None: | |
| moduli[(batch, sample)] = mod | |
| # One normalization across the family, so its batch figures share a color | |
| # scale and compare directly. | |
| norm = mcolors.Normalize(vmin=min(moduli.values()), vmax=max(moduli.values())) | |
| for batch in batches: | |
| fig, axes = plt.subplots(1, 2, figsize=(11.5, 5.6), layout="constrained") | |
| for ax, (lo, hi, label) in zip(axes, [(1, 7, "Samples 1–7 (lower stack)"), | |
| (8, 14, "Samples 8–14 (upper stack)")]): | |
| ax.set_facecolor(POWDER_BG) | |
| for sample in range(lo, hi + 1): | |
| mod = moduli.get((batch, sample)) | |
| if mod is not None: | |
| patch = specimen_patch(sample, transforms[sample], | |
| MODULUS_RAMP(norm(mod)), None) | |
| elif sample in UNPRINTED.get(batch, set()): | |
| patch = specimen_patch(sample, transforms[sample], "none", None, | |
| edgecolor=UNPRINTED_EDGE, linestyle=(0, (4, 3))) | |
| else: | |
| patch = specimen_patch(sample, transforms[sample], BROKEN_FC, BROKEN_HATCH) | |
| ax.add_patch(patch) | |
| ax.set_xlim(0, plate_x) | |
| ax.set_ylim(0, plate_y) | |
| ax.set_aspect("equal") | |
| title = label | |
| if lo == 8 and batch in UNPRINTED: | |
| title += " — not printed" | |
| ax.set_title(title) | |
| ax.set_xlabel("X [mm]") | |
| ax.set_ylabel("Y [mm]") | |
| fig.colorbar(ScalarMappable(norm=norm, cmap=MODULUS_RAMP), ax=axes, | |
| shrink=0.8, label="Tensile chord modulus [MPa]") | |
| fig.suptitle(f"Batch {batch} — {family}, tensile modulus by build-plate position") | |
| png = save_figure(fig, OUT_DIR / "batches" / f"D638_{batch}_layout") | |
| plt.close(fig) | |
| print(f"wrote {png.relative_to(ROOT)} " | |
| f"({sum(1 for (b, _) in moduli if b == batch)} specimens colored)") | |
| if __name__ == "__main__": | |
| main() | |