FLOW-3D-Single-Track / scripts /01_generate_views.py
ppak10's picture
Adds scripts
c128a53
#!/usr/bin/env python3
"""
Generate all views for every unprocessed simulation case.
W (the adaptive crop half-width) is derived directly from the laser spot
radius in the prepin file — no temperature scan needed.
Single pass over source timesteps produces:
• top-down 2D projection (50×50, 1 mm × 1 mm) per field
• adaptive-crop 3D volume (Z×W×W) per field
Outputs written to views/<case>/:
metadata.json simulation parameters + per-field stats
cropped.npz all fields (N, Z, W, W), timestep, power,
velocity, window_cells
<field>/top_down.gif matplotlib 2D animation (1 mm × 1 mm)
<field>/cropped.gif PyVista 3D volume render animation
Cases that already have cropped.npz are skipped automatically.
Use --workers to control parallelism (default: cpu_count // 2).
"""
import argparse
import json
import multiprocessing
import re
import shutil
import zipfile
from pathlib import Path
from typing import NamedTuple
import imageio
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
import pyvista as pv
from tqdm import tqdm
# ── Domain constants (CGS: cm) ────────────────────────────────────────────────
CELL_SIZE_CM = 0.002
TOP_DOWN_HALF = 25 # fixed 1 mm window → 50 cells → ±25
LIQUIDUS_K = 1697.15
T_AMBIENT = 299.15
BUFFER_CELLS = 5
# Ghost cell counts added by FLOW-3D at array boundaries
GHOST_Z = 2
GHOST_Y = 1
GHOST_X = 1
# ── Field configuration ───────────────────────────────────────────────────────
class Field(NamedTuple):
name: str
label: str
cmap: str
project: str # "max" or "sum" along Z for 2-D top-down
vmin_fixed: float | None
vmax_pct: float = 99.9
vmin_pct: float = 0.0
sparse: bool = False # percentile over nonzero cells only
FIELDS = [
Field("temperature", "Temperature (K)", "inferno", "max", T_AMBIENT),
Field("fraction_of_fluid", "Fluid depth (cells)", "Blues", "sum", None, 99.9, 1.0),
Field("liquid_label", "Liquid region", "plasma", "max", 0.0, 100.0),
Field("melt_region", "Melt region", "hot", "max", 0.0, 99.9, 0.0, sparse=True),
Field("pressure", "Pressure (dyne/cm²)", "RdBu_r", "max", None, 99.9, 0.1),
Field("velocity_magnitude", "Velocity magnitude (cm/s)", "viridis", "max", 0.0, 99.9, 0.0, sparse=True),
Field("temperature_gradient", "Temperature gradient (raw)", "magma", "max", 0.0, 99.9, 0.0, sparse=True),
Field("gradient_magnitude", "|∇T| from components (K/cm)", "magma", "max", 0.0, 99.9, 0.0, sparse=True),
]
FIELD_MAP = {f.name: f for f in FIELDS}
# ── Prepin parsing ────────────────────────────────────────────────────────────
def find_prepin(case_dir: Path) -> Path:
matches = list(case_dir.glob("prepin.*"))
if not matches:
raise FileNotFoundError(f"No prepin file in {case_dir}")
return matches[0]
def parse_prepin(text: str) -> dict:
def f(pat): return float(re.search(pat, text).group(1))
power_raw = f(r"powlbm\(1,1\)\s*=\s*([\d.eE+-]+)")
return {
"px1": f(r"px\(1\)\s*=\s*([\d.eE+-]+)"), # cm, mesh X start
"py1": f(r"py\(1\)\s*=\s*([\d.eE+-]+)"), # cm, mesh Y start
"xb0": f(r"xb0lbm\(1\)\s*=\s*([\d.eE+-]+)"), # cm
"yb0": f(r"yb0lbm\(1\)\s*=\s*([\d.eE+-]+)"), # cm
"velocity_cms":f(r"utlbm\(1,1\)\s*=\s*([\d.eE+-]+)"), # cm/s
"spot_radius": f(r"rflbm\(1\)\s*=\s*([\d.eE+-]+)"), # cm
"gauss_radius":f(r"rblbm\(1\)\s*=\s*([\d.eE+-]+)"), # cm
"power_w": round(power_raw / 1e7),
"t_liquidus": f(r"tl1\s*=\s*([\d.eE+-]+)"),
"t_solidus": f(r"ts1\s*=\s*([\d.eE+-]+)"),
"t_finish": f(r"twfin\s*=\s*([\d.eE+-]+)"),
}
def beam_x_index(t: float, pp: dict) -> int:
"""Beam X index relative to the mesh origin (px1)."""
x_abs = pp["xb0"] + pp["velocity_cms"] * t
return round((x_abs - pp["px1"] - CELL_SIZE_CM / 2) / CELL_SIZE_CM)
def domain_from_raw(raw: dict, pp: dict) -> tuple[int, int, int, int]:
"""Return (nz, ny, nx, y_center) from the first npz array and prepin.
FLOW-3D appends ghost cells at the end of each axis:
Z: +2, Y: +1, X: +1
y_center is the beam Y position as a cell index within the mesh.
"""
shape = raw["temperature"].shape # (1, nz+2, ny+1, nx+1)
nz = shape[1] - GHOST_Z
ny = shape[2] - GHOST_Y
nx = shape[3] - GHOST_X
y_center = round((pp["yb0"] - pp["py1"]) / CELL_SIZE_CM)
return nz, ny, nx, y_center
def crop_half_from_prepin(spot_radius_cm: float) -> int:
"""Derive the crop half-width from the laser spot radius.
Uses 4× the spot radius as a conservative bound for the melt pool
half-width in Y, then adds the safety buffer.
"""
return int(np.ceil(spot_radius_cm / CELL_SIZE_CM * 4)) + BUFFER_CELLS
# ── Cropping helpers ──────────────────────────────────────────────────────────
def _crop_params(center: int, half: int, size: int) -> tuple[int, int, int, int]:
"""Compute (lo, hi, pad_left, pad_right) for a centered crop of width 2*half.
Always guarantees (hi - lo) + pad_left + pad_right == 2 * half, even when
the window is partially or fully outside [0, size).
"""
lo = center - half
hi = center + half
pl = max(0, -lo); lo = max(0, lo)
pr = max(0, hi - size); hi = min(size, hi)
lo = min(lo, hi) # clamp when window is past the end
pr = 2 * half - pl - (hi - lo) # ensure exact output width
return lo, hi, pl, pr
def top_down_2d(proj: np.ndarray, beam_x: int, y_center: int) -> np.ndarray:
"""(Y, X) → (TOP_DOWN_HALF*2, TOP_DOWN_HALF*2) fixed 1 mm × 1 mm window."""
# X axis: follow the beam
xlo, xhi, xpl, xpr = _crop_params(beam_x, TOP_DOWN_HALF, proj.shape[1])
w = proj[:, xlo:xhi]
if xpl or xpr:
w = np.pad(w, ((0, 0), (xpl, xpr)), constant_values=0.0)
# Y axis: centered on beam y position
ylo, yhi, ypt, ypb = _crop_params(y_center, TOP_DOWN_HALF, w.shape[0])
w = w[ylo:yhi, :]
if ypt or ypb:
w = np.pad(w, ((ypt, ypb), (0, 0)), constant_values=0.0)
return w
def crop_3d(arr: np.ndarray, beam_x: int, half: int, y_center: int,
pad_val: float = 0.0) -> np.ndarray:
"""(Z, Y, X[, C]) → (Z, W, W[, C]) adaptive square window."""
xlo, xhi, xpl, xpr = _crop_params(beam_x, half, arr.shape[2])
ylo, yhi, ypt, ypb = _crop_params(y_center, half, arr.shape[1])
w = arr[:, ylo:yhi, xlo:xhi]
if xpl or xpr or ypt or ypb:
pad = ((0,0),(ypt,ypb),(xpl,xpr)) if arr.ndim == 3 \
else ((0,0),(ypt,ypb),(xpl,xpr),(0,0))
w = np.pad(w, pad, constant_values=pad_val)
return w
# ── Per-timestep extraction ───────────────────────────────────────────────────
def extract(
raw: dict, beam_x: int, crop_half: int,
nz: int, ny: int, nx: int, y_center: int,
) -> tuple[dict, dict]:
"""Return (top_down, cropped) dicts from one loaded npz.
top_down[field] : (TOP_DOWN_HALF*2, TOP_DOWN_HALF*2)
cropped[field] : (nz, W, W) scalars
cropped['vx_vy_vz'] : (nz, W, W, 3)
cropped['dtdx_dtdy_dtdz']: (nz, W, W, 3)
"""
def slc(k):
return raw[k][0, :nz, :ny, :nx]
def proj(arr, method):
return arr.max(axis=0) if method == "max" else arr.sum(axis=0)
td, cr = {}, {}
for name, method in [
("temperature", "max"),
("fraction_of_fluid", "sum"),
("liquid_label", "max"),
("melt_region", "max"),
("pressure", "max"),
("temperature_gradient", "max"),
]:
arr = slc(name)
pad = T_AMBIENT if name == "temperature" else 0.0
td[name] = top_down_2d(proj(arr, method), beam_x, y_center)
cr[name] = crop_3d(arr, beam_x, crop_half, y_center, pad_val=pad)
vel = slc("vx_vy_vz")
vmag = np.linalg.norm(vel, axis=-1)
td["velocity_magnitude"] = top_down_2d(proj(vmag, "max"), beam_x, y_center)
cr["velocity_magnitude"] = crop_3d(vmag, beam_x, crop_half, y_center)
cr["vx_vy_vz"] = crop_3d(vel, beam_x, crop_half, y_center)
grad = slc("dtdx_dtdy_dtdz")
gmag = np.linalg.norm(grad, axis=-1)
td["gradient_magnitude"] = top_down_2d(proj(gmag, "max"), beam_x, y_center)
cr["gradient_magnitude"] = crop_3d(gmag, beam_x, crop_half, y_center)
cr["dtdx_dtdy_dtdz"] = crop_3d(grad, beam_x, crop_half, y_center)
return td, cr
# ── GIF: top-down (matplotlib) ────────────────────────────────────────────────
def make_top_down_gif(
frames: np.ndarray, field: Field, case_name: str,
out_path: Path, fps: int, max_frames: int,
) -> None:
stride = max(1, len(frames) // max_frames)
gf = frames[::stride]
src = gf[gf > 0] if field.sparse else gf
vmax = float(np.percentile(src if src.size else gf, field.vmax_pct))
vmin = field.vmin_fixed if field.vmin_fixed is not None \
else float(np.percentile(src if src.size else gf, field.vmin_pct))
fig, ax = plt.subplots(figsize=(5, 5))
im = ax.imshow(gf[0], origin="lower", cmap=field.cmap,
vmin=vmin, vmax=vmax, extent=[0, 1, 0, 1])
ax.set_xlabel("X (mm)"); ax.set_ylabel("Y (mm)")
ax.set_title(f"{case_name}\n{field.label}")
plt.colorbar(im, ax=ax, label=field.label)
plt.tight_layout()
def _update(i):
im.set_data(gf[i])
return [im]
anim = animation.FuncAnimation(fig, _update, frames=len(gf),
interval=1000 // fps, blit=True)
anim.save(out_path, writer="pillow", fps=fps)
plt.close()
# ── GIF: cropped 3D volume (PyVista) ─────────────────────────────────────────
def _render_pyvista(vol: np.ndarray, cmap: str, opacity,
vmin: float, vmax: float) -> np.ndarray:
nz, ny, nx = vol.shape
grid = pv.ImageData(dimensions=(nx, ny, nz),
spacing=(CELL_SIZE_CM,) * 3)
grid.point_data["v"] = vol.transpose(2, 1, 0).ravel(order="F")
pl = pv.Plotter(off_screen=True, window_size=[600, 500])
pl.set_background("black")
pl.add_volume(grid, scalars="v", cmap=cmap, opacity=opacity,
clim=[vmin, vmax], show_scalar_bar=False)
pl.camera_position = "iso"
img = pl.screenshot(return_img=True)
pl.close()
return img
def make_cropped_gif(
frames: np.ndarray, field: Field,
out_path: Path, fps: int, max_frames: int,
) -> None:
stride = max(1, len(frames) // max_frames)
gf = frames[::stride]
src = frames[frames > 0] if field.sparse else frames
if src.size == 0:
return
vmax = float(np.percentile(src, field.vmax_pct))
vmin = field.vmin_fixed if field.vmin_fixed is not None \
else float(np.percentile(src, field.vmin_pct))
# For temperature: fade in above liquidus; others: standard sigmoid
if field.name == "temperature":
opacity = [0.0, 0.0, 0.05, 0.3, 0.8, 1.0]
else:
opacity = field.cmap # reuse cmap name as opacity preset string
opacity = "sigmoid"
rendered = [_render_pyvista(f, field.cmap, opacity, vmin, vmax) for f in gf]
imageio.mimsave(str(out_path), rendered, fps=fps, loop=0)
# ── Metadata ──────────────────────────────────────────────────────────────────
def build_metadata(
case_name: str,
pp: dict,
npz_files: list[Path],
W: int,
nz: int, ny: int, nx: int,
crop_data: dict[str, np.ndarray],
timesteps: np.ndarray,
) -> dict:
vel_mps = pp["velocity_cms"] / 100.0
meta: dict = {
"case_id": case_name,
"simulation": {
"power_w": pp["power_w"],
"velocity_mps": vel_mps,
"angle_deg": int(re.search(r"A(\d+)deg", case_name).group(1)),
"finish_time_s": pp["t_finish"],
"n_timesteps": len(timesteps),
"t_start_s": float(timesteps[0]),
"t_end_s": float(timesteps[-1]),
},
"laser": {
"spot_radius_cm": pp["spot_radius"],
"gauss_radius_cm": pp["gauss_radius"],
"beam_start_x_cm": pp["xb0"],
"beam_start_y_cm": pp["yb0"],
},
"material": {
"name": "316L Stainless Steel",
"t_liquidus_k": pp["t_liquidus"],
"t_solidus_k": pp["t_solidus"],
"t_ambient_k": T_AMBIENT,
},
"domain": {
"cell_size_um": CELL_SIZE_CM * 1e4,
"nx": nx, "ny": ny, "nz": nz,
"x_mm": nx * CELL_SIZE_CM * 10,
"y_mm": ny * CELL_SIZE_CM * 10,
"z_mm": nz * CELL_SIZE_CM * 10,
},
"windows": {
"top_down_cells": TOP_DOWN_HALF * 2,
"top_down_mm": TOP_DOWN_HALF * 2 * CELL_SIZE_CM * 10,
"crop_cells": W,
"crop_mm": W * CELL_SIZE_CM * 10,
"crop_z_cells": nz,
"crop_z_mm": nz * CELL_SIZE_CM * 10,
},
"fields": {},
}
for field in FIELDS:
key = field.name
if key not in crop_data:
continue
arr = crop_data[key]
nz_vals = arr[arr != 0] if field.sparse else arr
meta["fields"][key] = {
"shape": list(arr.shape),
"min": float(arr.min()),
"max": float(arr.max()),
"mean": float(np.mean(nz_vals)) if nz_vals.size else 0.0,
"std": float(np.std(nz_vals)) if nz_vals.size else 0.0,
"p99": float(np.percentile(nz_vals, 99)) if nz_vals.size else 0.0,
}
return meta
# ── Per-case worker ───────────────────────────────────────────────────────────
def process_case(args: tuple) -> str:
"""Process one case. Runs in a worker process. Returns case name on completion."""
import os
case_name, root, gif_fps, gif_max_frames = args
# Redirect stderr → /dev/null in this worker to suppress EGL/libEGL/VTK noise.
# Worker processes are isolated, so this doesn't affect the main process.
# Python-level exceptions still propagate back via the pool mechanism.
_devnull = os.open(os.devnull, os.O_WRONLY)
os.dup2(_devnull, 2)
os.close(_devnull)
# Each worker process needs its own OFF_SCREEN flag
pv.OFF_SCREEN = True
try:
import vtk
vtk.vtkObject.GlobalWarningDisplayOff()
except Exception:
pass
case_dir = root / "source" / case_name
npz_dir = case_dir / "flslnk_npz"
out_dir = root / "views" / case_name
out_dir.mkdir(parents=True, exist_ok=True)
# ── unzip flslnk_npz.zip if not already extracted ─────────────────────────
zip_path = case_dir / "flslnk_npz.zip"
unzipped = False
if not npz_dir.exists():
if not zip_path.exists():
raise FileNotFoundError(f"Neither flslnk_npz/ nor flslnk_npz.zip found in {case_dir}")
npz_dir.mkdir()
with zipfile.ZipFile(zip_path) as zf:
zf.extractall(npz_dir)
unzipped = True
pp = parse_prepin(find_prepin(case_dir).read_text())
npz_files = sorted(npz_dir.glob("*.npz"))
crop_half = crop_half_from_prepin(pp["spot_radius"])
W = crop_half * 2
# ── determine domain dimensions from first readable timestep ─────────────
nz = ny = nx = y_center = None
for _f in npz_files:
try:
first_raw = np.load(_f)
nz, ny, nx, y_center = domain_from_raw(first_raw, pp)
break
except (EOFError, Exception):
continue
if nz is None:
raise RuntimeError(f"No readable NPZ files found for {case_name}")
# ── extraction ────────────────────────────────────────────────────────────
td_acc: dict[str, list] = {}
crop_acc: dict[str, list] = {}
timesteps: list[float] = []
n_skipped = 0
for npz_path in tqdm(npz_files, desc=case_name, leave=False, position=1):
try:
raw = np.load(npz_path)
t = float(raw["timestep"][0])
except (EOFError, Exception):
n_skipped += 1
continue
bx = beam_x_index(t, pp)
td, cr = extract(raw, bx, crop_half, nz, ny, nx, y_center)
for k, v in td.items(): td_acc.setdefault(k, []).append(v)
for k, v in cr.items(): crop_acc.setdefault(k, []).append(v)
timesteps.append(t)
if n_skipped:
tqdm.write(f" ! {case_name}: skipped {n_skipped} corrupt NPZ files")
ts = np.array(timesteps, dtype=np.float64)
crop_arrays = {k: np.array(v, dtype=np.float32) for k, v in crop_acc.items()}
# ── cropped.npz ───────────────────────────────────────────────────────────
np.savez_compressed(out_dir / "cropped.npz", **{
"timestep": ts,
"power": np.array([pp["power_w"]], dtype=np.int32),
"velocity": np.array([pp["velocity_cms"] / 100.0], dtype=np.float64),
"window_cells": np.array([W], dtype=np.int32),
**crop_arrays,
})
# ── delete extracted npz folder if we unzipped it ────────────────────────
if unzipped:
shutil.rmtree(npz_dir)
# ── metadata.json ─────────────────────────────────────────────────────────
meta = build_metadata(case_name, pp, npz_files, W, nz, ny, nx, crop_arrays, ts)
with open(out_dir / "metadata.json", "w") as f:
json.dump(meta, f, indent=2)
# ── GIFs ──────────────────────────────────────────────────────────────────
for field in tqdm(FIELDS, desc=f"{case_name} GIFs", leave=False, position=1):
fd = out_dir / field.name
fd.mkdir(exist_ok=True)
make_top_down_gif(
np.array(td_acc[field.name], dtype=np.float32),
field, case_name, fd / "top_down.gif", gif_fps, gif_max_frames,
)
make_cropped_gif(
np.array(crop_acc[field.name], dtype=np.float32),
field, fd / "cropped.gif", gif_fps, gif_max_frames,
)
return case_name
# ── Main ──────────────────────────────────────────────────────────────────────
def main() -> None:
parser = argparse.ArgumentParser(
description="Generate all views for every unprocessed simulation case."
)
parser.add_argument(
"cases", nargs="*",
help="Case folder names under source/ (default: all unprocessed)",
)
parser.add_argument("--gif-fps", type=int, default=20)
parser.add_argument("--gif-max-frames", type=int, default=200)
parser.add_argument(
"--workers", type=int,
default=max(1, multiprocessing.cpu_count() // 2),
help="Parallel worker processes (default: cpu_count // 2)",
)
args = parser.parse_args()
root = Path(__file__).parent.parent
# Resolve case list — explicit args or all source folders with flslnk_npz/
if args.cases:
candidates = [root / "source" / c for c in args.cases]
else:
candidates = sorted((root / "source").iterdir())
# Filter to valid, unprocessed cases
todo = []
for case_dir in candidates:
npz_dir = case_dir / "flslnk_npz"
zip_path = case_dir / "flslnk_npz.zip"
cropped = root / "views" / case_dir.name / "cropped.npz"
if not npz_dir.exists() and not zip_path.exists():
print(f" skip {case_dir.name} — no flslnk_npz/ or flslnk_npz.zip")
continue
if cropped.exists():
print(f" skip {case_dir.name} — already done")
continue
todo.append(case_dir.name)
if not todo:
print("Nothing to do.")
return
print(f"\nProcessing {len(todo)} cases with {args.workers} workers\n")
worker_args = [(c, root, args.gif_fps, args.gif_max_frames) for c in todo]
with multiprocessing.Pool(args.workers) as pool:
for done in tqdm(
pool.imap_unordered(process_case, worker_args),
total=len(todo), desc="Cases", position=0,
):
tqdm.write(f" ✓ {done}")
if __name__ == "__main__":
multiprocessing.set_start_method("spawn", force=True)
main()