File size: 22,147 Bytes
889d6d3 | 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 | #!/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()
|