ubend-cfd / visualize_sample.py
Jens
Upload visualize_sample.py with huggingface_hub
23e78eb verified
#!/usr/bin/env python3
"""Download N random samples from the U-bend HuggingFace dataset and visualize them.
For each sample, generates individual PNGs:
- <id>_geometry.png : fluid + solid mesh
- <id>_U.png : velocity magnitude
- <id>_p.png : pressure
- <id>_T.png : temperature (fluid + solid)
- <id>_k.png : turbulent kinetic energy
- <id>_nut.png : turbulent viscosity
Additionally, an overview grid (N rows x 6 columns) is saved as `overview.png`.
Usage:
python visualize_sample.py --n 5
"""
import argparse
import os
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from huggingface_hub import hf_hub_download
from safetensors.numpy import load_file
REPO_ID = "JensDe/ubend-cfd"
parser = argparse.ArgumentParser()
parser.add_argument("--n", type=int, default=5, help="Number of random samples")
parser.add_argument("--seed", type=int, default=42, help="Random seed")
parser.add_argument("--out_dir", type=str, default="visualizations", help="Output directory")
args = parser.parse_args()
os.makedirs(args.out_dir, exist_ok=True)
random.seed(args.seed)
sample_ids = random.sample(range(10000), args.n * 3) # buffer for failed downloads
FIELD_SPECS = [
("U", "Velocity magnitude", "viridis", "|U| [m/s]"),
("p", "Pressure", "coolwarm", "p [Pa]"),
("T", "Temperature", "hot", "T [K]"),
("k", "Turbulent kinetic energy", "magma", "k [m²/s²]"),
("nut", "Turbulent viscosity", "plasma", "ν_t [m²/s]"),
]
def render_geometry(ax, x, y, sx, sy):
fluid_field = np.ones_like(x)
solid_field = np.ones_like(sx) * 2
ax.pcolormesh(x, y, fluid_field, cmap="Blues", shading="auto", vmin=0, vmax=3)
ax.pcolormesh(sx, sy, solid_field, cmap="Oranges", shading="auto", vmin=0, vmax=3)
ax.set_aspect("equal")
def render_field(ax, x, y, field, cmap, sx=None, sy=None, sfield=None):
vmin, vmax = field.min(), field.max()
if sfield is not None:
vmin = min(vmin, sfield.min())
vmax = max(vmax, sfield.max())
pcm = ax.pcolormesh(x, y, field, cmap=cmap, shading="auto", vmin=vmin, vmax=vmax)
if sfield is not None:
ax.pcolormesh(sx, sy, sfield, cmap=cmap, shading="auto", vmin=vmin, vmax=vmax)
ax.set_aspect("equal")
return pcm
def get_field(data, name):
if name == "U":
U = data["U"]
return np.sqrt(U[0]**2 + U[1]**2 + U[2]**2)
return data[name]
# Download samples
samples = []
i = 0
while len(samples) < args.n and i < len(sample_ids):
sid = sample_ids[i]
i += 1
try:
print(f"[{len(samples)+1}/{args.n}] Downloading sample {sid}...")
file_path = hf_hub_download(
repo_id=REPO_ID,
filename=f"fields/sample_{sid}.safetensors",
repo_type="dataset",
)
samples.append((sid, load_file(file_path)))
except Exception as e:
print(f" Skipping {sid}: {e.__class__.__name__}")
# Individual PNGs
for sid, data in samples:
x, y = data["coords"][0], data["coords"][1]
sx, sy = data["solid_coords"][0], data["solid_coords"][1]
base = os.path.join(args.out_dir, f"sample_{sid:05d}")
# Geometry
fig, ax = plt.subplots(figsize=(5, 7))
render_geometry(ax, x, y, sx, sy)
ax.set_title(f"Sample {sid} — Geometry")
ax.set_xlabel("x [m]"); ax.set_ylabel("y [m]")
ax.legend(handles=[Patch(facecolor="steelblue", label="Fluid"),
Patch(facecolor="orange", label="Solid")],
loc="upper center", bbox_to_anchor=(0.5, -0.1), ncol=2)
plt.tight_layout()
plt.savefig(f"{base}_geometry.png", dpi=150)
plt.close(fig)
# Fields
for fname, ftitle, cmap, label in FIELD_SPECS:
field = get_field(data, fname)
fig, ax = plt.subplots(figsize=(5, 7))
sfield = data["solid_T"] if fname == "T" else None
pcm = render_field(ax, x, y, field, cmap,
sx=sx if sfield is not None else None,
sy=sy if sfield is not None else None,
sfield=sfield)
plt.colorbar(pcm, ax=ax, label=label, orientation="horizontal", location="bottom", pad=0.08)
ax.set_title(f"Sample {sid}{ftitle}")
ax.set_xlabel("x [m]"); ax.set_ylabel("y [m]")
plt.tight_layout()
plt.savefig(f"{base}_{fname}.png", dpi=150)
plt.close(fig)
# Overview grid: N rows x 6 columns
print(f"\nCreating overview grid...")
ncols = 1 + len(FIELD_SPECS) # geometry + fields
fig, axes = plt.subplots(args.n, ncols, figsize=(3.5 * ncols, 4.5 * args.n))
if args.n == 1:
axes = axes[None, :]
col_titles = ["Geometry"] + [s[1] for s in FIELD_SPECS]
for row, (sid, data) in enumerate(samples):
x, y = data["coords"][0], data["coords"][1]
sx, sy = data["solid_coords"][0], data["solid_coords"][1]
# Geometry
ax = axes[row, 0]
render_geometry(ax, x, y, sx, sy)
ax.set_xticks([]); ax.set_yticks([])
if row == 0:
ax.set_title(col_titles[0])
ax.set_ylabel(f"Sample {sid}", fontsize=10)
# Fields
for col, (fname, _, cmap, _) in enumerate(FIELD_SPECS, start=1):
ax = axes[row, col]
field = get_field(data, fname)
sfield = data["solid_T"] if fname == "T" else None
render_field(ax, x, y, field, cmap,
sx=sx if sfield is not None else None,
sy=sy if sfield is not None else None,
sfield=sfield)
ax.set_xticks([]); ax.set_yticks([])
if row == 0:
ax.set_title(col_titles[col])
plt.tight_layout()
overview_path = os.path.join(args.out_dir, "overview.png")
plt.savefig(overview_path, dpi=150)
plt.close(fig)
print(f"Saved overview to {overview_path}")
print(f"\nDone! {len(samples)} samples visualized in {args.out_dir}/")