faNN / visualize.py
JeoaFesketto's picture
Upload visualize.py (lightweight dataset visualiser)
9a2e03b verified
Raw
History Blame Contribute Delete
22.6 kB
#!/usr/bin/env python3
"""Visualiser for the faNN PLAID dataset: ensemble grids of blade loadings.
faNN ships steady 3D RANS solutions of a 14-blade axial fan rotor passage on a
shared ~9.8M-node structured mesh (see the dataset card / README). Because the
structured-block indices ``i, j, k, block_num`` are constant across samples,
per-sample rendering only needs a handful of arrow columns — no full sample
reconstruction, no VTK, no scipy: **numpy + matplotlib + plaid only**.
Two dataset-scale figures (the ones embedded in the dataset card):
* ``skins`` an n x n grid of samples spread over the operating map; each
cell shows the blade skin (pressure side | suction side)
coloured by the isentropic Mach number M_is on a scale shared
across the whole grid, with hub/shroud endwall context lines.
* ``sections`` an n x n grid of blade-to-blade cuts of the blade blocks
(2, 4, 5, 6, 7), in the style of the paper's operating-map
insets: samples picked towards the outside of the (mdot, PR)
map, each at a span drawn from h/H = 0.1 / 0.5 / 0.9, filled
with static pressure (viridis, per-cell scale) under thin
white isolines.
The isentropic Mach follows the authors' post-processing:
``M_is = sqrt(((pt_rel/p)^((g-1)/g) - 1) * 2/(g-1))`` with ``pt_rel`` the
inlet-plane average of ``p + rho*|w|^2/2`` (relative frame; the rotor spins
about -x at ``RotatingVelocityX`` rad/s).
Mesh topology facts used (identical for every sample): block 5 is the blade
O-block, ``i = 0`` is the blade skin, ``j`` runs hub (0) to tip; the domain
inlet is formed by the k-extremes of blocks 10, 11, 13 and 14.
CLI
---
python visualize.py skins --source JeoaFesketto/faNN --out fann_skins.png
python visualize.py sections --source JeoaFesketto/faNN --out fann_sections.png
``--source`` is a local bridge-format folder (loaded with ``*_from_disk``) if
it is an existing directory, otherwise a Hub repo id (``*_from_hub``).
"""
from __future__ import annotations
import argparse
import os
import sys
import numpy as np
BLADE_BLOCK = 5
PASSAGE_BLOCKS = (2, 4, 5, 6, 7) # the "blade blocks" of a b2b cut
# paper-friendly rc (TrueType fonts so PDFs embed correctly in LaTeX)
PAPER_RC = {
"font.size": 10, "axes.labelsize": 11, "axes.titlesize": 11,
"legend.fontsize": 9, "pdf.fonttype": 42, "ps.fonttype": 42,
"svg.fonttype": "none",
}
_VF = "Base_3_3/Zone/VertexFields/"
_GC = "Base_3_3/Zone/GridCoordinates/"
def _plt():
import matplotlib
try:
matplotlib.use("Agg")
except Exception: # noqa: BLE001
pass
import matplotlib.pyplot as plt
plt.rcParams.update(PAPER_RC)
return plt
# ----------------------------------------------------------------------------- #
# loading
# ----------------------------------------------------------------------------- #
class FaNN:
"""Thin handle over a loaded faNN PLAID dataset (bridge format).
Wraps the ``datasets.DatasetDict`` plus the constant-tree sidecar, with
fast accessors that read single arrow columns (memory-mapped) instead of
reconstructing full PLAID samples.
"""
def __init__(self, ds, flat_cst, key_mappings):
self.ds = ds
self.flat_cst = flat_cst
self.km = key_mappings
@classmethod
def load(cls, source: str) -> "FaNN":
"""Load from a local bridge folder (if ``source`` is a dir) else the Hub."""
from plaid.bridges import huggingface_bridge as hb
if os.path.isdir(source):
ds = hb.load_dataset_from_disk(source)
flat_cst, km = hb.load_tree_struct_from_disk(source)
else:
ds = hb.load_dataset_from_hub(source)
flat_cst, km = hb.load_tree_struct_from_hub(source)
return cls(ds, flat_cst, km)
@property
def splits(self):
return list(self.ds.keys())
def ijk(self, split="hf_train"):
"""(4, N) int array [i, j, k, block] from the constant tree."""
cst = self.flat_cst[split]
return np.stack([np.asarray(cst[_VF + n], np.int64)
for n in ("i", "j", "k", "block_num")])
def field(self, split, index, name):
"""One nodal field of one sample straight from its arrow column."""
col = self.ds[split].data.column(_VF + name)
return col[int(index)].values.to_numpy(zero_copy_only=False)
def coords(self, split, index):
"""(x, y, z) nodal coordinates of one sample."""
return tuple(
self.ds[split].data.column(_GC + f"Coordinate{c}")[int(index)]
.values.to_numpy(zero_copy_only=False) for c in "XYZ")
def scalar(self, split: str, name: str) -> np.ndarray:
"""All values of one Global scalar across ``split`` (NaN where withheld).
Constant scalars (inlet totals, gas properties) live in the constant
tree, not the arrow schema — they are broadcast to the split length.
"""
path = f"Global/{name}"
cst = self.flat_cst[split]
if path in cst:
return np.full(len(self.ds[split]),
float(np.ravel(cst[path])[0]))
col = self.ds[split].data.column(path).to_pylist()
out = np.full(len(col), np.nan)
for i, v in enumerate(col):
a = np.ravel(v)
if a.size and a[0] is not None:
out[i] = float(a[0])
return out
def rpm(self, split: str) -> np.ndarray:
return self.scalar(split, "RotatingVelocityX") * 30.0 / np.pi
# ----------------------------------------------------------------------------- #
# isentropic Mach
# ----------------------------------------------------------------------------- #
def inlet_indices(ijk):
"""Node indices of the domain inlet plane (k-extremes of the inlet blocks)."""
sels = []
for b, ext in ((10, "max"), (11, "max"), (13, "min"), (14, "max")):
in_b = ijk[3] == b
k = ijk[2, in_b]
v = k.min() if ext == "min" else k.max()
sels.append(np.nonzero(in_b & (ijk[2] == v))[0])
return np.concatenate(sels)
def mis_at(fann, split, index, idx, inlet_idx, gamma=1.4):
"""Isentropic Mach at the nodes ``idx`` of one sample.
``pt_rel`` (p + rho*|w|^2/2, with w the relative velocity) is averaged over
the inlet plane, then M_is follows from the local static pressure. NaNs
(p > pt_rel near stagnation at the outer radii) are mapped to 0.
"""
p = fann.field(split, index, "Pressure")
ro = fann.field(split, index, "Density")[inlet_idx]
vx = fann.field(split, index, "VelocityX")[inlet_idx]
vy = fann.field(split, index, "VelocityY")[inlet_idx]
vz = fann.field(split, index, "VelocityZ")[inlet_idx]
x, y, z = fann.coords(split, index)
yi, zi = y[inlet_idx], z[inlet_idx]
r = np.maximum(np.hypot(yi, zi), 1e-12)
om = float(fann.scalar(split, "RotatingVelocityX")[index])
v_t = (-zi * vy + yi * vz) / r
v_r = (yi * vy + zi * vz) / r
w2 = vx ** 2 + v_r ** 2 + (v_t + om * r) ** 2
pt_rel = float(np.mean(p[inlet_idx] + 0.5 * ro * w2))
g = gamma
with np.errstate(invalid="ignore"):
mis = np.sqrt(((pt_rel / p[idx]) ** ((g - 1) / g) - 1) * 2 / (g - 1))
return np.nan_to_num(mis, nan=0.0), (x, y, z)
# ----------------------------------------------------------------------------- #
# constant skin / section topology (computed once, reused for every sample)
# ----------------------------------------------------------------------------- #
def _grid_triangles(u, v):
"""Triangles (two per cell) of a structured 2D index grid given per-point
integer coordinates ``u``, ``v`` (holes allowed)."""
u = np.asarray(u, np.int64)
v = np.asarray(v, np.int64)
nu, nv = u.max() + 1, v.max() + 1
grid = np.full((nu, nv), -1, np.int64)
grid[u, v] = np.arange(u.size)
a = grid[:-1, :-1].ravel()
b = grid[1:, :-1].ravel()
c = grid[:-1, 1:].ravel()
d = grid[1:, 1:].ravel()
ok = (a >= 0) & (b >= 0) & (c >= 0)
t1 = np.stack([a[ok], b[ok], c[ok]], 1)
ok2 = (b >= 0) & (d >= 0) & (c >= 0)
t2 = np.stack([b[ok2], d[ok2], c[ok2]], 1)
return np.vstack([t1, t2])
class SkinTopo:
"""Constant topology of the blade skin (block 5, i = 0).
``idx`` are global node indices; the skin is a complete (j, k) structured
grid, triangulated once. Per sample, the leading edge (min x per j) splits
the k-range into the two blade sides; triangles are side-masked by their
first vertex.
"""
def __init__(self, ijk):
sel = (ijk[3] == BLADE_BLOCK) & (ijk[0] == 0)
self.idx = np.nonzero(sel)[0]
self.j = ijk[1, self.idx]
self.k = ijk[2, self.idx]
self.tris = _grid_triangles(self.j, self.k)
self.nj = self.j.max() + 1
# (nj, nk) lookup: position of each (j, k) in the compact skin arrays
self.pos = np.full((self.nj, self.k.max() + 1), -1, np.int64)
self.pos[self.j, self.k] = np.arange(self.idx.size)
# hub / shroud endwall lines around the blade (i = 0 edge of a
# passage flank block at the spanwise extremes, ordered along k)
flank = ijk[3] == 6
j_hi = ijk[1, flank].max()
self.hub_line, self.shroud_line = (
self._line(ijk, flank & (ijk[1] == jv) & (ijk[0] == 0))
for jv in (0, j_hi))
@staticmethod
def _line(ijk, sel):
idx = np.nonzero(sel)[0]
return idx[np.argsort(ijk[2, idx])]
def side_masks(self, x_skin):
"""(pressure-ish, suction-ish) point masks from the per-j LE position.
Which side is which is settled by the caller from the pressure field.
"""
x_grid = x_skin[self.pos] # (nj, nk); pos is complete for the skin
k_le = np.argmin(x_grid, axis=1)
side_a = self.k <= k_le[self.j]
return side_a, ~side_a
def tri_masks(self, side_a):
"""Triangle masks (mask=True hides) for the two sides."""
a_first = side_a[self.tris[:, 0]]
return ~a_first, a_first
class SectionTopo:
"""Constant topology of one blade-to-blade passage cut (fixed j).
Covers the blade blocks (2, 4, 5, 6, 7): the O-block around the blade and
the passage neighbours. Each block's (i, k) grid at one j is complete;
triangulating per block keeps the blade hole and block boundaries exact.
"""
def __init__(self, ijk, j_cut, blocks=PASSAGE_BLOCKS):
sel = np.isin(ijk[3], blocks) & (ijk[1] == j_cut)
self.idx = np.nonzero(sel)[0]
i, k, b = ijk[0, self.idx], ijk[2, self.idx], ijk[3, self.idx]
tris = []
for blk in np.unique(b):
m = b == blk
sub = np.nonzero(m)[0]
tris.append(sub[_grid_triangles(i[m], k[m])])
self.tris = np.vstack(tris)
skin = np.nonzero((b == BLADE_BLOCK) & (i == 0))[0]
self.blade_edge = skin[np.argsort(k[skin])] # skin ring polyline
def span_j_table(ijk, r):
"""(j values, span fraction 0=hub..1=tip) along the blade skin."""
sel = (ijk[3] == BLADE_BLOCK) & (ijk[0] == 0)
j_vals = np.unique(ijk[1, sel])
r_mean = np.array([r[sel][ijk[1, sel] == jv].mean() for jv in j_vals])
span = (r_mean - r_mean.min()) / max(r_mean.max() - r_mean.min(), 1e-30)
return j_vals, span
# ----------------------------------------------------------------------------- #
# sample / geometry selection
# ----------------------------------------------------------------------------- #
def _farthest_point(feats, n, start=None):
"""Greedy farthest-point sampling on rows of ``feats``. Deterministic."""
feats = np.asarray(feats, float)
if start is None:
start = int(np.argmax(np.linalg.norm(feats - feats.mean(0), axis=1)))
chosen = [start]
d = np.linalg.norm(feats - feats[start], axis=1)
while len(chosen) < n:
nxt = int(np.argmax(d))
chosen.append(nxt)
d = np.minimum(d, np.linalg.norm(feats - feats[nxt], axis=1))
return chosen
def pick_spread_samples(fann, n, split="hf_train"):
"""n sample indices spread over the operating map (FPS on rpm, mdot, PR)."""
rpm = fann.rpm(split)
mf = fann.scalar(split, "MassFlow")
pr = fann.scalar(split, "TotalPressureRatioAbsolute")
def norm(a):
return (a - np.nanmin(a)) / max(np.nanmax(a) - np.nanmin(a), 1e-30)
feats = np.stack([norm(rpm), norm(mf), norm(pr)], 1)
chosen = _farthest_point(feats, n, start=int(np.nanargmax(pr)))
# display order: speed first, then pressure ratio
return sorted(chosen, key=lambda i: (round(rpm[i], -2), pr[i]))
def pick_peripheral_samples(fann, n, split="hf_train"):
"""n sample indices towards the outside of the (mdot, PR) operating map.
The normalised map is divided into ``n`` angular sectors around its
centroid and the most distant point of each sector is taken (falling back
to the globally most distant unused points for empty sectors) — extreme
operating points all around the map: near-surge, windmilling, choke.
Returned in angular order (counter-clockwise sweep of the map).
"""
mf = fann.scalar(split, "MassFlow")
pr = fann.scalar(split, "TotalPressureRatioAbsolute")
def norm(a):
return (a - np.nanmin(a)) / max(np.nanmax(a) - np.nanmin(a), 1e-30)
u, v = norm(mf), norm(pr)
ang = np.arctan2(v - v.mean(), u - u.mean())
rad = np.hypot(u - u.mean(), v - v.mean())
sector = np.minimum(((ang + np.pi) / (2 * np.pi) * n).astype(int), n - 1)
chosen = []
for s in range(n):
in_s = np.nonzero(sector == s)[0]
if in_s.size:
chosen.append(int(in_s[np.argmax(rad[in_s])]))
left = np.setdiff1d(np.arange(u.size), chosen)
for i in left[np.argsort(rad[left])[::-1]]:
if len(chosen) >= n:
break
chosen.append(int(i))
return sorted(chosen[:n], key=lambda i: ang[i])
# ----------------------------------------------------------------------------- #
# figure 1: n x n blade-skin M_is grid
# ----------------------------------------------------------------------------- #
def skins_grid(fann, *, n=3, split="hf_train", levels=25, save=None):
"""Grid of n*n samples: blade skin M_is, pressure side | suction side.
Samples are spread over the operating map by farthest-point sampling and
ordered by rotation speed then pressure ratio; the colour scale and the
spatial scale are shared across cells. Grey lines mark the hub and shroud
endwalls around the blade.
"""
from matplotlib.tri import Triangulation
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
plt = _plt()
ijk = fann.ijk(split)
skin = SkinTopo(ijk)
inlet_idx = inlet_indices(ijk)
rows = pick_spread_samples(fann, n * n, split)
rpm = fann.rpm(split)
pr = fann.scalar(split, "TotalPressureRatioAbsolute")
gid = fann.scalar(split, "GeometryNumber")
gamma = fann.scalar(split, "SpecificHeatRatio")
print(f"[skins] computing M_is for {len(rows)} samples ...",
file=sys.stderr)
cells = []
for c, row in enumerate(rows):
mis, (x, y, z) = mis_at(fann, split, row, skin.idx, inlet_idx,
gamma=float(gamma[row]))
r = np.hypot(y, z)
xs = x[skin.idx]
rs = r[skin.idx]
side_a, side_b = skin.side_masks(xs)
p_skin = fann.field(split, row, "Pressure")[skin.idx]
ps_first = p_skin[side_a].mean() >= p_skin[side_b].mean()
ps, ss = (side_a, side_b) if ps_first else (side_b, side_a)
walls = [(x[li], r[li]) for li in (skin.hub_line, skin.shroud_line)]
cells.append((row, xs, rs, mis, ps, walls))
if (c + 1) % 20 == 0:
print(f"[skins] {c + 1}/{len(rows)}", file=sys.stderr)
vmax = float(np.percentile(np.concatenate([c[3] for c in cells]), 99.5))
norm = Normalize(0.0, vmax)
lev = np.linspace(0.0, vmax, levels)
# one spatial scale for every cell so blade sizes stay comparable
xspan = max(c[1].max() - c[1].min() for c in cells)
r_lo = min(min(w[1].min() for w in c[5]) for c in cells)
r_hi = max(max(w[1].max() for w in c[5]) for c in cells)
shift = 1.14 * xspan # suction side offset within the cell
fig, axes = plt.subplots(n, n, figsize=(2.7 * n, 1.7 * n))
for ax, (row, xs, rs, mis, ps, walls) in zip(axes.ravel(), cells):
mis = np.clip(mis, 0.0, vmax)
m_ps, m_ss = skin.tri_masks(ps)
x_mid = 0.5 * (xs.min() + xs.max())
for x0, mask in ((0.0, m_ps), (shift, m_ss)):
tri = Triangulation(xs - x_mid + x0, rs, skin.tris)
tri.set_mask(mask)
ax.tricontourf(tri, mis, levels=lev, cmap="viridis",
extend="max")
for xw, rw in walls: # hub / shroud endwall context lines
ax.plot(xw - x_mid + x0, rw, color="0.45", lw=0.7, zorder=5)
ax.set_title(
f"G{gid[row]:.0f} · {rpm[row] / 1e3:.0f} kRPM · "
f"$\\Pi$={pr[row]:.2f}", fontsize=8.5, pad=2.5)
ax.set_xlim(-0.60 * xspan, shift + 0.60 * xspan)
ax.set_ylim(r_lo - 0.03 * (r_hi - r_lo), r_hi + 0.03 * (r_hi - r_lo))
ax.set_aspect("equal")
ax.set_xticks([])
ax.set_yticks([])
for spine in ax.spines.values():
spine.set_visible(False)
fig.subplots_adjust(left=0.01, right=0.99, top=0.89, bottom=0.15,
wspace=0.07, hspace=0.28)
cax = fig.add_axes([0.30, 0.075, 0.40, 0.016])
cb = fig.colorbar(ScalarMappable(norm=norm, cmap="viridis"), cax=cax,
orientation="horizontal", extend="max")
cb.set_label("$M_{is}$", fontsize=10)
cb.ax.tick_params(labelsize=8)
fig.suptitle(
f"blade-skin isentropic Mach — {n * n} samples "
"(pressure side | suction side)", fontsize=11, y=0.97)
if save:
fig.savefig(save, dpi=200)
plt.close(fig)
return fig
# ----------------------------------------------------------------------------- #
# figure 2: n x n geometry / span section grid
# ----------------------------------------------------------------------------- #
def sections_grid(fann, *, n=3, split="hf_train", levels=25, save=None):
"""Grid of n*n blade-to-blade cuts in the style of the paper's map insets.
Samples are picked towards the outside of the (mdot, PR) operating map —
near-surge, windmilling, choke — each cut at a span drawn from
h/H = 0.1 / 0.5 / 0.9 (blade root / mid span / blade tip, three cells
each). Cells render the blade blocks (2, 4, 5, 6, 7) filled with static
pressure (viridis, per-cell scale) overlaid with thin white isolines, in
a black frame with corner labels — exactly the map-figure inset look.
"""
from matplotlib.tri import Triangulation
plt = _plt()
ijk = fann.ijk(split)
rows = pick_peripheral_samples(fann, n * n, split)
# one span per cell, drawn from root/mid/tip with equal counts
span_of = {0.1: "Blade root", 0.5: "Mid span", 0.9: "Blade tip"}
pool = ([0.1, 0.5, 0.9] * ((n * n + 2) // 3))[:n * n]
spans = list(np.random.default_rng(0).permutation(pool))
x0, y0, z0 = fann.coords(split, rows[0])
j_vals, span_tab = span_j_table(ijk, np.hypot(y0, z0))
j_of = {s: int(j_vals[np.argmin(np.abs(span_tab - s))])
for s in span_of}
topos = {j: SectionTopo(ijk, j) for j in sorted(set(j_of.values()))}
rpm = fann.rpm(split)
pr = fann.scalar(split, "TotalPressureRatioAbsolute")
gid = fann.scalar(split, "GeometryNumber")
print(f"[sections] rendering {n * n} peripheral samples ...",
file=sys.stderr)
fig, axes = plt.subplots(n, n, figsize=(2.75 * n, 2.6 * n))
for ax, row, sp in zip(axes.ravel(), rows, spans):
topo = topos[j_of[sp]]
p = fann.field(split, row, "Pressure")[topo.idx]
x, y, z = fann.coords(split, row)
xs = x[topo.idx]
ys = (np.hypot(y, z) * np.arctan2(z, y))[topo.idx]
lo, hi = np.percentile(p, [0.5, 99.5])
lev = np.linspace(lo, hi, levels)
tri = Triangulation(xs, ys, topo.tris)
ax.tricontourf(tri, p, levels=lev, cmap="viridis", extend="both")
ax.tricontour(tri, p, levels=lev, colors="white", linewidths=0.25)
ax.margins(0.05)
ax.set_aspect("equal")
ax.set_xticks([])
ax.set_yticks([])
for spine in ax.spines.values():
spine.set_linewidth(0.8)
ax.text(0.025, 0.975,
f"G{gid[row]:.0f} · {rpm[row] / 1e3:.0f} kRPM · "
f"$\\Pi$={pr[row]:.2f}",
transform=ax.transAxes, ha="left", va="top", fontsize=8)
ax.text(0.975, 0.025, span_of[sp], transform=ax.transAxes,
ha="right", va="bottom", fontsize=8)
fig.subplots_adjust(left=0.015, right=0.985, top=0.93, bottom=0.02,
wspace=0.08, hspace=0.08)
fig.suptitle(
f"static pressure, blade-to-blade cuts — {n * n} samples at the "
"edge of the operating map", fontsize=11, y=0.975)
if save:
fig.savefig(save, dpi=200)
plt.close(fig)
return fig
# ----------------------------------------------------------------------------- #
# CLI
# ----------------------------------------------------------------------------- #
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
for name, default_out in (("skins", "fann_skins.png"),
("sections", "fann_sections.png")):
p = sub.add_parser(name)
p.add_argument("--source", default="JeoaFesketto/faNN",
help="local bridge folder or Hub repo id "
"(default: %(default)s)")
p.add_argument("-n", type=int, default=3, help="grid side (default 3)")
p.add_argument("--out", default=default_out)
args = ap.parse_args(argv)
fann = FaNN.load(args.source)
print(f"[load] {args.source}: "
f"{ {k: len(fann.ds[k]) for k in fann.splits} }", file=sys.stderr)
if args.cmd == "skins":
skins_grid(fann, n=args.n, save=args.out)
else:
sections_grid(fann, n=args.n, save=args.out)
print(f"[done] wrote {args.out}", file=sys.stderr)
if __name__ == "__main__":
main()