Add streakline post-processing and exp control-matrix batch runners (vorticity + streakline)
This commit is contained in:
1 parent
50b2b6a7ca
commit
4758eb3215
30 files changed
+4128
-4600
No files matched your search
@@ -4,5 +4,6 @@ Common utilities and preprocessing functions.
|
||||
"""
|
||||
|
||||
from . import preprocess
|
||||
from . import streakline
|
||||
|
||||
__all__ = ['preprocess']
|
||||
__all__ = ["preprocess", "streakline"]
|
||||
@@ -0,0 +1,778 @@
|
||||
# CelerisLab/common/streakline.py
|
||||
"""Streakline utilities for online/offline particle-based flow visualization.
|
||||
|
||||
Responsibilities:
|
||||
- Build dense release seeds (point/line/strip).
|
||||
- Integrate particles with RK4 and space-time interpolated velocity fields.
|
||||
- Support both online (in-memory frames from Simulation) and offline playback.
|
||||
- Render density-like streakline images or accumulated path trails.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, List, Optional, Sequence, Tuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
CylinderSpec = Tuple[Tuple[float, float], float]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FlowFrame:
|
||||
"""One sampled velocity frame."""
|
||||
|
||||
step: int
|
||||
ux: np.ndarray
|
||||
uy: np.ndarray
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReleaseConfig:
|
||||
"""Release strategy configuration for dense streakline seeding."""
|
||||
|
||||
mode: str = "strip" # point | line | strip
|
||||
line_span: float = 12.0
|
||||
line_count: int = 5
|
||||
downstream_count: int = 4
|
||||
downstream_spacing: float = 3.0
|
||||
inject_per_seed: int = 2
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class IntegratorConfig:
|
||||
"""Particle integration and filtering settings."""
|
||||
|
||||
alpha_t: float = 0.2
|
||||
alpha_x: float = 0.4
|
||||
age_decay_steps: float = 20000.0
|
||||
max_particle_age: Optional[float] = None
|
||||
diffusion_coeff: float = 0.0
|
||||
random_seed: int = 1234
|
||||
num_threads: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ParticleTrailSet:
|
||||
"""Growing polylines per particle (pathline history — not physical streakline)."""
|
||||
|
||||
trails: List[np.ndarray] = field(default_factory=list)
|
||||
active: List[bool] = field(default_factory=list)
|
||||
|
||||
def inject(self, points: np.ndarray) -> None:
|
||||
pts = np.asarray(points, dtype=np.float64)
|
||||
if pts.ndim != 2 or pts.shape[1] != 2:
|
||||
raise ValueError("points must be [N,2].")
|
||||
for p in pts:
|
||||
self.trails.append(np.asarray([[p[0], p[1]]], dtype=np.float64))
|
||||
self.active.append(True)
|
||||
|
||||
def keep_indices(self, survived_mask: np.ndarray) -> None:
|
||||
"""Deactivate trails whose particle did not survive the last advance."""
|
||||
mask = np.asarray(survived_mask, dtype=bool).ravel()
|
||||
j = 0
|
||||
for i, is_active in enumerate(self.active):
|
||||
if not is_active:
|
||||
continue
|
||||
if j >= mask.size:
|
||||
break
|
||||
if not bool(mask[j]):
|
||||
self.active[i] = False
|
||||
j += 1
|
||||
|
||||
def keep_mask(self, survived_mask: np.ndarray) -> None:
|
||||
"""Alias for keep_indices (boolean mask over active particles)."""
|
||||
self.keep_indices(survived_mask)
|
||||
|
||||
def append_positions(self, particles: np.ndarray) -> None:
|
||||
pts = np.asarray(particles, dtype=np.float64)
|
||||
j = 0
|
||||
for i, is_active in enumerate(self.active):
|
||||
if not is_active:
|
||||
continue
|
||||
if j >= pts.shape[0]:
|
||||
break
|
||||
self.trails[i] = np.vstack([self.trails[i], pts[j]])
|
||||
j += 1
|
||||
|
||||
|
||||
def configure_compute_threads(num_threads: int = 0) -> int:
|
||||
"""Set BLAS/OpenMP thread env vars for host-side numpy work."""
|
||||
if num_threads <= 0:
|
||||
num_threads = min(32, os.cpu_count() or 4)
|
||||
for var in (
|
||||
"OMP_NUM_THREADS",
|
||||
"OPENBLAS_NUM_THREADS",
|
||||
"MKL_NUM_THREADS",
|
||||
"NUMEXPR_NUM_THREADS",
|
||||
"VECLIB_MAXIMUM_THREADS",
|
||||
):
|
||||
os.environ[var] = str(int(num_threads))
|
||||
return int(num_threads)
|
||||
|
||||
|
||||
def cylinders_from_triangle_layout(layout: dict) -> List[CylinderSpec]:
|
||||
"""Build cylinder list from triangle-layout dict used in experiment notebook."""
|
||||
radius = float(layout["radius_lb"])
|
||||
return [
|
||||
((float(layout["x_apex"]), float(layout["y_center"])), radius),
|
||||
((float(layout["x_rear"]), float(layout["y_lower"])), radius),
|
||||
((float(layout["x_rear"]), float(layout["y_upper"])), radius),
|
||||
]
|
||||
|
||||
|
||||
def estimate_sampling_plan(
|
||||
*,
|
||||
st_ref: float,
|
||||
diameter: float,
|
||||
u_ref: float,
|
||||
snapshots_per_period: float = 24.0,
|
||||
periods: int = 5,
|
||||
) -> dict:
|
||||
"""Estimate save interval and snapshot count from nominal shedding scale."""
|
||||
period_steps = float(diameter) / (float(st_ref) * float(u_ref))
|
||||
save_every = int(max(20, round(period_steps / snapshots_per_period / 10.0) * 10))
|
||||
n_snapshots = int(max(20, round(float(periods) * float(snapshots_per_period))))
|
||||
return {
|
||||
"st_ref": float(st_ref),
|
||||
"period_steps_est": float(period_steps),
|
||||
"snapshots_per_period_target": float(snapshots_per_period),
|
||||
"save_every_recommended": int(save_every),
|
||||
"snapshot_count_recommended": int(n_snapshots),
|
||||
}
|
||||
|
||||
|
||||
def build_release_points(
|
||||
base_points: np.ndarray,
|
||||
release_cfg: ReleaseConfig,
|
||||
) -> np.ndarray:
|
||||
"""Expand base release points to dense points by line/strip policy."""
|
||||
pts = np.asarray(base_points, dtype=np.float64)
|
||||
if pts.ndim != 2 or pts.shape[1] != 2:
|
||||
raise ValueError("base_points must be [N,2].")
|
||||
mode = str(release_cfg.mode).lower()
|
||||
if mode not in ("point", "line", "strip"):
|
||||
raise ValueError("release mode must be point|line|strip.")
|
||||
|
||||
line_count = max(1, int(release_cfg.line_count))
|
||||
ds_count = max(1, int(release_cfg.downstream_count))
|
||||
line_offsets = np.linspace(
|
||||
-0.5 * float(release_cfg.line_span),
|
||||
0.5 * float(release_cfg.line_span),
|
||||
line_count,
|
||||
)
|
||||
ds_offsets = np.arange(ds_count, dtype=np.float64) * float(release_cfg.downstream_spacing)
|
||||
|
||||
out: list[list[float]] = []
|
||||
for x0, y0 in pts:
|
||||
line_iter = [0.0] if mode == "point" else line_offsets
|
||||
ds_iter = [0.0] if mode in ("point", "line") else ds_offsets
|
||||
for dy in line_iter:
|
||||
for dx in ds_iter:
|
||||
out.append([float(x0 + dx), float(y0 + dy)])
|
||||
return np.asarray(out, dtype=np.float64)
|
||||
|
||||
|
||||
def _bilinear_sample(field: np.ndarray, x: np.ndarray, y: np.ndarray) -> np.ndarray:
|
||||
ny, nx = field.shape
|
||||
x0 = np.floor(x).astype(np.int64)
|
||||
y0 = np.floor(y).astype(np.int64)
|
||||
x1 = x0 + 1
|
||||
y1 = y0 + 1
|
||||
inside = (x0 >= 0) & (x1 < nx) & (y0 >= 0) & (y1 < ny)
|
||||
out = np.full_like(x, np.nan, dtype=np.float64)
|
||||
if not np.any(inside):
|
||||
return out
|
||||
|
||||
xi = x[inside] - x0[inside]
|
||||
yi = y[inside] - y0[inside]
|
||||
f00 = field[y0[inside], x0[inside]]
|
||||
f10 = field[y0[inside], x1[inside]]
|
||||
f01 = field[y1[inside], x0[inside]]
|
||||
f11 = field[y1[inside], x1[inside]]
|
||||
out[inside] = (
|
||||
(1.0 - xi) * (1.0 - yi) * f00
|
||||
+ xi * (1.0 - yi) * f10
|
||||
+ (1.0 - xi) * yi * f01
|
||||
+ xi * yi * f11
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def _velocity_at(pos: np.ndarray, theta: float, f0: FlowFrame, f1: FlowFrame) -> np.ndarray:
|
||||
x = pos[:, 0]
|
||||
y = pos[:, 1]
|
||||
vx0 = _bilinear_sample(f0.ux, x, y)
|
||||
vy0 = _bilinear_sample(f0.uy, x, y)
|
||||
vx1 = _bilinear_sample(f1.ux, x, y)
|
||||
vy1 = _bilinear_sample(f1.uy, x, y)
|
||||
vx = (1.0 - theta) * vx0 + theta * vx1
|
||||
vy = (1.0 - theta) * vy0 + theta * vy1
|
||||
return np.stack([vx, vy], axis=1)
|
||||
|
||||
|
||||
def _particles_valid_mask(
|
||||
p_new: np.ndarray,
|
||||
*,
|
||||
nx: int,
|
||||
ny: int,
|
||||
solid_center: Optional[Tuple[float, float]] = None,
|
||||
solid_radius: Optional[float] = None,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
) -> np.ndarray:
|
||||
valid = np.all(np.isfinite(p_new), axis=1)
|
||||
valid &= (p_new[:, 0] >= 0.0) & (p_new[:, 0] <= nx - 1)
|
||||
valid &= (p_new[:, 1] >= 0.0) & (p_new[:, 1] <= ny - 1)
|
||||
|
||||
specs: List[CylinderSpec] = []
|
||||
if cylinders:
|
||||
specs.extend(cylinders)
|
||||
elif solid_center is not None and solid_radius is not None:
|
||||
specs.append((solid_center, float(solid_radius)))
|
||||
|
||||
for (cx, cy), radius in specs:
|
||||
dx = p_new[:, 0] - float(cx)
|
||||
dy = p_new[:, 1] - float(cy)
|
||||
valid &= (dx * dx + dy * dy) > (float(radius) * float(radius))
|
||||
return valid
|
||||
|
||||
|
||||
def _inject_particles(
|
||||
particles: np.ndarray,
|
||||
ages: np.ndarray,
|
||||
release_points: np.ndarray,
|
||||
*,
|
||||
inject_per_seed: int,
|
||||
) -> Tuple[np.ndarray, np.ndarray]:
|
||||
new_pts = np.repeat(release_points, max(1, int(inject_per_seed)), axis=0)
|
||||
if particles.size == 0:
|
||||
return new_pts.copy(), np.zeros((new_pts.shape[0],), dtype=np.float64)
|
||||
return (
|
||||
np.vstack([particles, new_pts]),
|
||||
np.concatenate([ages, np.zeros((new_pts.shape[0],), dtype=np.float64)]),
|
||||
)
|
||||
|
||||
|
||||
def advance_particles_between_frames(
|
||||
particles: np.ndarray,
|
||||
ages: np.ndarray,
|
||||
frame0: FlowFrame,
|
||||
frame1: FlowFrame,
|
||||
*,
|
||||
nx: int,
|
||||
ny: int,
|
||||
cfg: IntegratorConfig,
|
||||
solid_center: Optional[Tuple[float, float]] = None,
|
||||
solid_radius: Optional[float] = None,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
rng: Optional[np.random.Generator] = None,
|
||||
) -> Tuple[np.ndarray, np.ndarray, dict, np.ndarray]:
|
||||
"""Advance particles from frame0.step to frame1.step with RK4.
|
||||
|
||||
Returns:
|
||||
particles, ages, diagnostics, survived_mask (bool, length = input count).
|
||||
"""
|
||||
if particles.size == 0:
|
||||
return particles, ages, {"n_substeps": 0, "max_speed": 0.0}, np.zeros((0,), dtype=bool)
|
||||
|
||||
dt_save = float(frame1.step - frame0.step)
|
||||
max_speed = float(
|
||||
max(
|
||||
np.nanmax(np.sqrt(frame0.ux * frame0.ux + frame0.uy * frame0.uy)),
|
||||
np.nanmax(np.sqrt(frame1.ux * frame1.ux + frame1.uy * frame1.uy)),
|
||||
)
|
||||
)
|
||||
umax = max(max_speed, 1e-8)
|
||||
dt_trace = min(float(cfg.alpha_t) * dt_save, float(cfg.alpha_x) / umax)
|
||||
n_sub = max(1, int(math.ceil(dt_save / dt_trace)))
|
||||
dt_sub = dt_save / float(n_sub)
|
||||
|
||||
p = np.asarray(particles, dtype=np.float64)
|
||||
a = np.asarray(ages, dtype=np.float64)
|
||||
track = np.ones((p.shape[0],), dtype=bool)
|
||||
local_rng = rng or np.random.default_rng(int(cfg.random_seed))
|
||||
diffusion = float(cfg.diffusion_coeff)
|
||||
|
||||
for sub_idx in range(n_sub):
|
||||
if p.size == 0:
|
||||
break
|
||||
theta = float(sub_idx) / float(n_sub)
|
||||
k1 = _velocity_at(p, theta, frame0, frame1)
|
||||
k2 = _velocity_at(p + 0.5 * dt_sub * k1, min(1.0, theta + 0.5 / n_sub), frame0, frame1)
|
||||
k3 = _velocity_at(p + 0.5 * dt_sub * k2, min(1.0, theta + 0.5 / n_sub), frame0, frame1)
|
||||
k4 = _velocity_at(p + dt_sub * k3, min(1.0, theta + 1.0 / n_sub), frame0, frame1)
|
||||
p_new = p + (k1 + 2.0 * k2 + 2.0 * k3 + k4) * (dt_sub / 6.0)
|
||||
|
||||
if diffusion > 0.0:
|
||||
sigma = math.sqrt(max(0.0, 2.0 * diffusion * dt_sub))
|
||||
p_new += local_rng.normal(0.0, sigma, size=p_new.shape)
|
||||
|
||||
valid = _particles_valid_mask(
|
||||
p_new,
|
||||
nx=nx,
|
||||
ny=ny,
|
||||
solid_center=solid_center,
|
||||
solid_radius=solid_radius,
|
||||
cylinders=cylinders,
|
||||
)
|
||||
track[track] = valid
|
||||
p = p_new[valid]
|
||||
a = a[valid] + dt_sub
|
||||
if cfg.max_particle_age is not None:
|
||||
age_keep = a <= float(cfg.max_particle_age)
|
||||
track[track] = age_keep
|
||||
p = p[age_keep]
|
||||
a = a[age_keep]
|
||||
|
||||
survived_mask = track
|
||||
return p, a, {"dt_trace": float(dt_sub), "n_substeps": int(n_sub), "max_speed": float(max_speed)}, survived_mask
|
||||
|
||||
|
||||
def run_streakline_offline(
|
||||
frames: Sequence[FlowFrame],
|
||||
*,
|
||||
nx: int,
|
||||
ny: int,
|
||||
release_points: np.ndarray,
|
||||
release_cfg: ReleaseConfig,
|
||||
integrator_cfg: IntegratorConfig,
|
||||
solid_center: Optional[Tuple[float, float]] = None,
|
||||
solid_radius: Optional[float] = None,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
) -> Tuple[np.ndarray, np.ndarray, dict]:
|
||||
"""Reconstruct streakline from pre-collected velocity frames."""
|
||||
if len(frames) < 2:
|
||||
raise ValueError("At least two frames are required.")
|
||||
pts = build_release_points(release_points, release_cfg)
|
||||
particles = np.zeros((0, 2), dtype=np.float64)
|
||||
ages = np.zeros((0,), dtype=np.float64)
|
||||
rng = np.random.default_rng(int(integrator_cfg.random_seed))
|
||||
max_speed = 0.0
|
||||
last_step = int(frames[0].step)
|
||||
total_substeps = 0
|
||||
|
||||
for i in range(len(frames) - 1):
|
||||
particles, ages = _inject_particles(
|
||||
particles,
|
||||
ages,
|
||||
pts,
|
||||
inject_per_seed=release_cfg.inject_per_seed,
|
||||
)
|
||||
particles, ages, diag, _ = advance_particles_between_frames(
|
||||
particles,
|
||||
ages,
|
||||
frames[i],
|
||||
frames[i + 1],
|
||||
nx=nx,
|
||||
ny=ny,
|
||||
cfg=integrator_cfg,
|
||||
solid_center=solid_center,
|
||||
solid_radius=solid_radius,
|
||||
cylinders=cylinders,
|
||||
rng=rng,
|
||||
)
|
||||
max_speed = max(max_speed, float(diag["max_speed"]))
|
||||
total_substeps += int(diag["n_substeps"])
|
||||
last_step = int(frames[i + 1].step)
|
||||
|
||||
return particles, ages, {
|
||||
"frames_used": int(len(frames)),
|
||||
"last_step": int(last_step),
|
||||
"n_particles_alive": int(particles.shape[0]),
|
||||
"max_speed_seen": float(max_speed),
|
||||
"total_substeps": int(total_substeps),
|
||||
}
|
||||
|
||||
|
||||
def run_streakline_online(
|
||||
sim: Any,
|
||||
*,
|
||||
start_step: int,
|
||||
sample_every: int,
|
||||
n_samples: int,
|
||||
release_points: np.ndarray,
|
||||
release_cfg: ReleaseConfig,
|
||||
integrator_cfg: IntegratorConfig,
|
||||
solid_center: Optional[Tuple[float, float]] = None,
|
||||
solid_radius: Optional[float] = None,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
) -> Tuple[np.ndarray, np.ndarray, dict]:
|
||||
"""Compute streakline online from a running Simulation without disk snapshots."""
|
||||
if sample_every < 1 or n_samples < 2:
|
||||
raise ValueError("sample_every must be >=1 and n_samples must be >=2.")
|
||||
if not getattr(sim, "_initialized", False):
|
||||
raise RuntimeError("Simulation must be initialized before online streakline run.")
|
||||
|
||||
nx = int(sim.lbm_cfg.nx)
|
||||
ny = int(sim.lbm_cfg.ny)
|
||||
frames: list[FlowFrame] = []
|
||||
target_last = int(start_step + sample_every * (n_samples - 1))
|
||||
|
||||
while int(sim.stepper.step_count) < target_last:
|
||||
sim.step(1)
|
||||
step = int(sim.stepper.step_count)
|
||||
if step < int(start_step):
|
||||
continue
|
||||
if (step - int(start_step)) % int(sample_every) != 0:
|
||||
continue
|
||||
macro = sim.get_macroscopic()
|
||||
frames.append(
|
||||
FlowFrame(
|
||||
step=step,
|
||||
ux=np.asarray(macro["ux"], dtype=np.float64),
|
||||
uy=np.asarray(macro["uy"], dtype=np.float64),
|
||||
)
|
||||
)
|
||||
if len(frames) >= int(n_samples):
|
||||
break
|
||||
|
||||
if len(frames) < 2:
|
||||
raise RuntimeError("Online run did not collect enough frames.")
|
||||
|
||||
particles, ages, diag = run_streakline_offline(
|
||||
frames,
|
||||
nx=nx,
|
||||
ny=ny,
|
||||
release_points=release_points,
|
||||
release_cfg=release_cfg,
|
||||
integrator_cfg=integrator_cfg,
|
||||
solid_center=solid_center,
|
||||
solid_radius=solid_radius,
|
||||
cylinders=cylinders,
|
||||
)
|
||||
diag["mode"] = "online"
|
||||
diag["sample_every"] = int(sample_every)
|
||||
diag["start_step"] = int(start_step)
|
||||
return particles, ages, diag
|
||||
|
||||
|
||||
def compute_vorticity(ux: np.ndarray, uy: np.ndarray) -> np.ndarray:
|
||||
"""Central-difference vorticity ω = ∂uy/∂x − ∂ux/∂y on interior cells."""
|
||||
ux_arr = np.asarray(ux, dtype=np.float64)
|
||||
uy_arr = np.asarray(uy, dtype=np.float64)
|
||||
vort = np.zeros_like(ux_arr, dtype=np.float64)
|
||||
dudy = 0.5 * (ux_arr[2:, 1:-1] - ux_arr[:-2, 1:-1])
|
||||
dvdx = 0.5 * (uy_arr[1:-1, 2:] - uy_arr[1:-1, :-2])
|
||||
vort[1:-1, 1:-1] = dvdx - dudy
|
||||
return vort
|
||||
|
||||
|
||||
def render_vorticity_field(
|
||||
vort: np.ndarray,
|
||||
*,
|
||||
nx: int,
|
||||
ny: int,
|
||||
out_path: str,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
vmin: Optional[float] = None,
|
||||
vmax: Optional[float] = None,
|
||||
percentile: float = 99.0,
|
||||
minimal_axes: bool = True,
|
||||
) -> dict:
|
||||
"""Render vorticity with white at zero, green negative, purple positive."""
|
||||
try:
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.colors import LinearSegmentedColormap, TwoSlopeNorm
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("render_vorticity_field requires matplotlib.") from exc
|
||||
|
||||
field = np.asarray(vort, dtype=np.float64)
|
||||
vmax_field = float(np.nanmax(np.abs(field)))
|
||||
abs_pct = float(np.nanpercentile(np.abs(field), percentile))
|
||||
# Freestream dominates |ω|; do not let a near-zero percentile wash out wake structure.
|
||||
abs_max = max(abs_pct, 0.35 * vmax_field, 1e-6)
|
||||
if vmin is None:
|
||||
vmin = -abs_max
|
||||
if vmax is None:
|
||||
vmax = abs_max
|
||||
if vmin >= 0.0 or vmax <= 0.0:
|
||||
raise ValueError(f"vmin/vmax must bracket zero: vmin={vmin}, vmax={vmax}")
|
||||
|
||||
cmap = LinearSegmentedColormap.from_list(
|
||||
"vort_green_white_purple",
|
||||
["#1a9850", "#f7f7f7", "#762a83"],
|
||||
N=256,
|
||||
)
|
||||
norm = TwoSlopeNorm(vmin=float(vmin), vcenter=0.0, vmax=float(vmax))
|
||||
|
||||
rgba = cmap(norm(field))
|
||||
if cylinders:
|
||||
yy, xx = np.mgrid[0:ny, 0:nx]
|
||||
for (cx, cy), radius in cylinders:
|
||||
mask = (xx - float(cx)) ** 2 + (yy - float(cy)) ** 2 <= float(radius) ** 2
|
||||
rgba[mask] = (0.0, 0.0, 0.0, 1.0)
|
||||
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
fig = plt.figure(figsize=(nx / 100.0, ny / 100.0), dpi=100)
|
||||
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
||||
ax.imshow(rgba, origin="lower", interpolation="nearest", aspect="auto")
|
||||
if minimal_axes:
|
||||
ax.axis("off")
|
||||
fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0)
|
||||
plt.close(fig)
|
||||
|
||||
return {
|
||||
"image_path": out_path,
|
||||
"vmin": float(vmin),
|
||||
"vmax": float(vmax),
|
||||
"vort_min": float(np.nanmin(field)),
|
||||
"vort_max": float(np.nanmax(field)),
|
||||
}
|
||||
|
||||
|
||||
def gaussian_blur2d(img: np.ndarray, sigma: float = 1.0) -> np.ndarray:
|
||||
"""Separable Gaussian blur helper."""
|
||||
if float(sigma) <= 0.0:
|
||||
return np.asarray(img, dtype=np.float64)
|
||||
radius = max(1, int(math.ceil(3.0 * float(sigma))))
|
||||
x = np.arange(-radius, radius + 1, dtype=np.float64)
|
||||
k = np.exp(-(x**2) / (2.0 * sigma * sigma))
|
||||
k /= np.sum(k)
|
||||
arr = np.asarray(img, dtype=np.float64)
|
||||
arr = np.apply_along_axis(lambda m: np.convolve(m, k, mode="same"), 1, arr)
|
||||
arr = np.apply_along_axis(lambda m: np.convolve(m, k, mode="same"), 0, arr)
|
||||
return arr
|
||||
|
||||
|
||||
def _rasterize_segment(
|
||||
intensity: np.ndarray,
|
||||
x0: float,
|
||||
y0: float,
|
||||
x1: float,
|
||||
y1: float,
|
||||
weight: float,
|
||||
) -> None:
|
||||
"""Stamp one segment into a scalar intensity map (for white-bg red compose)."""
|
||||
ny, nx = intensity.shape
|
||||
n = int(max(abs(x1 - x0), abs(y1 - y0), 1.0)) + 1
|
||||
xs = np.linspace(x0, x1, n)
|
||||
ys = np.linspace(y0, y1, n)
|
||||
xi = np.clip(np.rint(xs).astype(np.int64), 0, nx - 1)
|
||||
yi = np.clip(np.rint(ys).astype(np.int64), 0, ny - 1)
|
||||
w = float(max(0.0, min(1.0, weight)))
|
||||
np.add.at(intensity, (yi, xi), w)
|
||||
|
||||
|
||||
def _draw_trail(
|
||||
intensity: np.ndarray,
|
||||
trail: np.ndarray,
|
||||
*,
|
||||
fade_along_trail: bool,
|
||||
) -> None:
|
||||
if trail.shape[0] < 2:
|
||||
return
|
||||
nseg = trail.shape[0] - 1
|
||||
for i in range(nseg):
|
||||
if fade_along_trail:
|
||||
t = float(i + 1) / float(nseg)
|
||||
weight = 0.15 + 0.85 * t
|
||||
else:
|
||||
weight = 1.0
|
||||
_rasterize_segment(
|
||||
intensity,
|
||||
float(trail[i, 0]),
|
||||
float(trail[i, 1]),
|
||||
float(trail[i + 1, 0]),
|
||||
float(trail[i + 1, 1]),
|
||||
weight,
|
||||
)
|
||||
|
||||
|
||||
def _draw_cylinders(rgb: np.ndarray, cylinders: Sequence[CylinderSpec]) -> None:
|
||||
ny, nx = rgb.shape[0], rgb.shape[1]
|
||||
yy, xx = np.mgrid[0:ny, 0:nx]
|
||||
for (cx, cy), radius in cylinders:
|
||||
mask = (xx - float(cx)) ** 2 + (yy - float(cy)) ** 2 <= float(radius) ** 2
|
||||
rgb[mask] = 0.0
|
||||
|
||||
|
||||
def render_snapshot_trails(
|
||||
trail_set: ParticleTrailSet,
|
||||
*,
|
||||
nx: int,
|
||||
ny: int,
|
||||
out_path: str,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
blur_sigma: float = 0.0,
|
||||
fade_along_trail: bool = True,
|
||||
num_threads: int = 0,
|
||||
background_color: Tuple[float, float, float] = (1.0, 1.0, 1.0),
|
||||
streak_color: Tuple[float, float, float] = (1.0, 0.0, 0.0),
|
||||
) -> dict:
|
||||
"""Render accumulated path trails (pathline collage — debug only, not streakline)."""
|
||||
n_threads = configure_compute_threads(num_threads)
|
||||
intensity = np.zeros((ny, nx), dtype=np.float64)
|
||||
|
||||
trails = trail_set.trails
|
||||
if not trails:
|
||||
density_max = 0.0
|
||||
else:
|
||||
chunk = max(1, (len(trails) + n_threads - 1) // n_threads)
|
||||
|
||||
def _worker(batch: List[np.ndarray]) -> np.ndarray:
|
||||
local = np.zeros((ny, nx), dtype=np.float64)
|
||||
for tr in batch:
|
||||
_draw_trail(local, tr, fade_along_trail=fade_along_trail)
|
||||
return local
|
||||
|
||||
batches = [trails[i : i + chunk] for i in range(0, len(trails), chunk)]
|
||||
if len(batches) == 1:
|
||||
intensity = _worker(batches[0])
|
||||
else:
|
||||
with ThreadPoolExecutor(max_workers=n_threads) as pool:
|
||||
parts = list(pool.map(_worker, batches))
|
||||
for part in parts:
|
||||
intensity = np.maximum(intensity, part)
|
||||
|
||||
if np.any(intensity > 0):
|
||||
vmax = float(np.percentile(intensity[intensity > 0], 99.0))
|
||||
intensity = np.clip(intensity / max(vmax, 1e-12), 0.0, 1.0)
|
||||
density_max = float(np.max(intensity))
|
||||
|
||||
rgb = np.ones((ny, nx, 3), dtype=np.float64)
|
||||
rgb[:, :, 0] = background_color[0]
|
||||
rgb[:, :, 1] = background_color[1] * (1.0 - intensity) + streak_color[1] * intensity
|
||||
rgb[:, :, 2] = background_color[2] * (1.0 - intensity) + streak_color[2] * intensity
|
||||
if streak_color[0] < 0.999:
|
||||
rgb[:, :, 0] = background_color[0] * (1.0 - intensity) + streak_color[0] * intensity
|
||||
|
||||
if cylinders:
|
||||
_draw_cylinders(rgb, cylinders)
|
||||
|
||||
if float(blur_sigma) > 0.0:
|
||||
for c in range(3):
|
||||
rgb[:, :, c] = gaussian_blur2d(rgb[:, :, c], sigma=float(blur_sigma))
|
||||
|
||||
rgb = np.clip(rgb, 0.0, 1.0)
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
try:
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig = plt.figure(figsize=(nx / 100.0, ny / 100.0), dpi=100)
|
||||
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
||||
ax.axis("off")
|
||||
ax.imshow(rgb, origin="lower", interpolation="nearest", aspect="auto")
|
||||
fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0)
|
||||
plt.close(fig)
|
||||
except ImportError:
|
||||
from PIL import Image
|
||||
|
||||
Image.fromarray((np.clip(rgb, 0.0, 1.0) * 255.0).astype(np.uint8)).save(out_path)
|
||||
|
||||
return {
|
||||
"image_path": out_path,
|
||||
"trail_count": int(len(trails)),
|
||||
"density_max": density_max,
|
||||
"num_threads": int(n_threads),
|
||||
}
|
||||
|
||||
|
||||
def render_streakline_density(
|
||||
positions: np.ndarray,
|
||||
ages: np.ndarray,
|
||||
*,
|
||||
nx: int,
|
||||
ny: int,
|
||||
out_path: str,
|
||||
release_points: Optional[np.ndarray] = None,
|
||||
solid_center: Optional[Tuple[float, float]] = None,
|
||||
solid_radius: Optional[float] = None,
|
||||
cylinders: Optional[Sequence[CylinderSpec]] = None,
|
||||
age_decay_steps: float = 20000.0,
|
||||
blur_sigma: float = 1.2,
|
||||
title: str = "Streakline",
|
||||
minimal_axes: bool = False,
|
||||
background_color: Tuple[float, float, float] = (0.0, 0.0, 0.0),
|
||||
streak_color: Tuple[float, float, float] = (1.0, 0.5, 0.0),
|
||||
show_release_points: bool = True,
|
||||
) -> dict:
|
||||
"""Render streakline as current particle positions (density cloud at observation time)."""
|
||||
try:
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.colors import LinearSegmentedColormap
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("render_streakline_density requires matplotlib.") from exc
|
||||
|
||||
if positions.size == 0:
|
||||
density = np.zeros((ny, nx), dtype=np.float64)
|
||||
else:
|
||||
w = np.exp(-np.asarray(ages, dtype=np.float64) / max(1.0, float(age_decay_steps)))
|
||||
y_idx = np.clip(np.floor(positions[:, 1]).astype(np.int64), 0, ny - 1)
|
||||
x_idx = np.clip(np.floor(positions[:, 0]).astype(np.int64), 0, nx - 1)
|
||||
density = np.zeros((ny, nx), dtype=np.float64)
|
||||
np.add.at(density, (y_idx, x_idx), w)
|
||||
density = gaussian_blur2d(density, sigma=float(blur_sigma))
|
||||
|
||||
if minimal_axes:
|
||||
rgb = np.ones((ny, nx, 3), dtype=np.float64)
|
||||
rgb[:, :, 0] = background_color[0]
|
||||
rgb[:, :, 1] = background_color[1]
|
||||
rgb[:, :, 2] = background_color[2]
|
||||
if np.any(density > 0):
|
||||
vmax = float(np.percentile(density[density > 0], 99.0))
|
||||
alpha = np.clip(density / max(vmax, 1e-12), 0.0, 1.0)
|
||||
for c, val in enumerate(streak_color):
|
||||
rgb[:, :, c] = np.clip(rgb[:, :, c] * (1.0 - alpha) + val * alpha, 0.0, 1.0)
|
||||
specs = list(cylinders or [])
|
||||
if solid_center is not None and solid_radius is not None:
|
||||
specs.append((solid_center, float(solid_radius)))
|
||||
if specs:
|
||||
_draw_cylinders(rgb, specs)
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
fig = plt.figure(figsize=(nx / 100.0, ny / 100.0), dpi=100)
|
||||
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
|
||||
ax.axis("off")
|
||||
ax.imshow(rgb, origin="lower", interpolation="nearest", aspect="auto")
|
||||
fig.savefig(out_path, dpi=100, bbox_inches="tight", pad_inches=0)
|
||||
plt.close(fig)
|
||||
return {
|
||||
"image_path": out_path,
|
||||
"n_particles": int(positions.shape[0]) if positions.ndim == 2 else 0,
|
||||
"density_max": float(np.max(density)) if density.size else 0.0,
|
||||
}
|
||||
|
||||
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
||||
fig, ax = plt.subplots(figsize=(12, 5))
|
||||
vmax = np.percentile(density[density > 0], 99.0) if np.any(density > 0) else 1.0
|
||||
cmap = LinearSegmentedColormap.from_list("streak", [(0.0, 0.0, 0.0), streak_color])
|
||||
ax.imshow(
|
||||
density,
|
||||
origin="lower",
|
||||
cmap=cmap,
|
||||
extent=(0, nx - 1, 0, ny - 1),
|
||||
vmin=0.0,
|
||||
vmax=max(vmax, 1e-12),
|
||||
aspect="equal",
|
||||
)
|
||||
if solid_center is not None and solid_radius is not None:
|
||||
circ = plt.Circle(solid_center, radius=solid_radius, fill=False, color="cyan", linewidth=1.4)
|
||||
ax.add_patch(circ)
|
||||
if show_release_points and release_points is not None and np.asarray(release_points).size:
|
||||
rp = np.asarray(release_points)
|
||||
ax.scatter(rp[:, 0], rp[:, 1], c="white", s=10, marker="x")
|
||||
ax.set_title(title)
|
||||
ax.set_xlabel("x (lattice)")
|
||||
ax.set_ylabel("y (lattice)")
|
||||
ax.set_xlim(0, nx - 1)
|
||||
ax.set_ylim(0, ny - 1)
|
||||
fig.tight_layout()
|
||||
fig.savefig(out_path, dpi=170, bbox_inches="tight")
|
||||
plt.close(fig)
|
||||
|
||||
return {
|
||||
"image_path": out_path,
|
||||
"n_particles": int(positions.shape[0]) if positions.ndim == 2 else 0,
|
||||
"density_max": float(np.max(density)) if density.size else 0.0,
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
"_doc": "Three rotating cylinders in confined channel (triangle layout, free-slip walls).",
|
||||
"grid": {
|
||||
"lattice_model": "D2Q9",
|
||||
"nx": 6000,
|
||||
"ny": 1200,
|
||||
"nx": 3000,
|
||||
"ny": 300,
|
||||
"nz": 1
|
||||
},
|
||||
"physics": {
|
||||
@@ -27,7 +27,9 @@
|
||||
},
|
||||
"inlet": {
|
||||
"profile": "uniform",
|
||||
"trt_neq_damp": 0.5
|
||||
"scheme": "regularized",
|
||||
"trt_neq_damp": 0.5,
|
||||
"regularized_neq_damp": 0.5
|
||||
},
|
||||
"outlet": {
|
||||
"mode": "neq_extrap",
|
||||
|
||||
@@ -69,6 +69,12 @@ class LBMField:
|
||||
|
||||
# Snapshot
|
||||
self._ddf_snap: np.ndarray | None = None
|
||||
self._host_ddf_step: int | None = None
|
||||
|
||||
# Cached lattice constants mirrored from CUDA __constant__ memory.
|
||||
self._cached_w: np.ndarray | None = None
|
||||
self._cached_vectors_2d: tuple[np.ndarray, np.ndarray] | None = None
|
||||
self._cached_vectors_3d: tuple[np.ndarray, np.ndarray, np.ndarray] | None = None
|
||||
|
||||
# Host mirror of runtime parameters so partial updates preserve state.
|
||||
self._runtime_params = {
|
||||
@@ -82,6 +88,16 @@ class LBMField:
|
||||
# Upload d_params immediately
|
||||
self._upload_params()
|
||||
|
||||
def invalidate_host_ddf_cache(self) -> None:
|
||||
"""Mark host DDF mirror as stale after GPU-side updates."""
|
||||
self._host_ddf_step = None
|
||||
|
||||
def invalidate_module_constant_cache(self) -> None:
|
||||
"""Drop cached __constant__ mirrors after module replacement."""
|
||||
self._cached_w = None
|
||||
self._cached_vectors_2d = None
|
||||
self._cached_vectors_3d = None
|
||||
|
||||
def build_channel_flags(self) -> np.ndarray:
|
||||
"""Return a fresh host flag array for the base channel domain.
|
||||
|
||||
@@ -123,9 +139,15 @@ class LBMField:
|
||||
return self.sensors.count
|
||||
|
||||
# -- DDF download with precision decode ----------------------------------
|
||||
def download_ddf(self):
|
||||
def download_ddf(self, *, step_id: int | None = None, force: bool = False):
|
||||
"""Copy DDF from GPU to host self.ddf (float32), decoding FP16S if needed.
|
||||
If DDF shifting is enabled, un-shifts by adding back lattice weights."""
|
||||
# Fast path for repeated host queries within one solver step.
|
||||
# Callers pass step_id from LBMStepper; force=True bypasses cache
|
||||
# for snapshot-style semantics.
|
||||
if not force and step_id is not None and self._host_ddf_step == int(step_id):
|
||||
return
|
||||
|
||||
if self.store_bytes == 2:
|
||||
buf = np.empty(self.n * self.nq, dtype=self.store_dtype)
|
||||
cuda.memcpy_dtoh(buf, self.ddf_gpu)
|
||||
@@ -143,13 +165,17 @@ class LBMField:
|
||||
ddf_2d = self.ddf.reshape(self.nq, -1)
|
||||
for i in range(self.nq):
|
||||
ddf_2d[i] += w[i]
|
||||
self._host_ddf_step = int(step_id) if step_id is not None else None
|
||||
|
||||
def _read_lattice_weights(self):
|
||||
"""Read d_w[] from CUDA __constant__ memory (single source of truth in descriptors.cuh)."""
|
||||
if self._cached_w is not None:
|
||||
return self._cached_w
|
||||
ptr, size = self.module.get_global("d_w")
|
||||
w = np.empty(self.nq, dtype=np.float32)
|
||||
cuda.memcpy_dtoh(w, ptr)
|
||||
return w
|
||||
self._cached_w = w
|
||||
return self._cached_w
|
||||
|
||||
# -- d_params upload -----------------------------------------------------
|
||||
def _upload_params(self):
|
||||
@@ -209,6 +235,7 @@ class LBMField:
|
||||
else:
|
||||
cuda.memcpy_htod(self.ddf_gpu, self.ddf)
|
||||
cuda.memcpy_htod(self.temp_gpu, self.ddf)
|
||||
self.invalidate_host_ddf_cache()
|
||||
|
||||
# The canonical download_ddf is defined above in the class body.
|
||||
|
||||
@@ -223,6 +250,11 @@ class LBMField:
|
||||
# -- Read lattice descriptors from CUDA module ---------------------------
|
||||
def _read_lattice_vectors(self):
|
||||
"""Read d_cx, d_cy [, d_cz] from CUDA __constant__ memory."""
|
||||
if self.cfg.is_d2q9 and self._cached_vectors_2d is not None:
|
||||
return self._cached_vectors_2d
|
||||
if self.cfg.is_d3q19 and self._cached_vectors_3d is not None:
|
||||
return self._cached_vectors_3d
|
||||
|
||||
nq = self.nq
|
||||
cx = np.empty(nq, dtype=np.int32)
|
||||
cy = np.empty(nq, dtype=np.int32)
|
||||
@@ -234,13 +266,17 @@ class LBMField:
|
||||
cz = np.empty(nq, dtype=np.int32)
|
||||
ptr_cz, _ = self.module.get_global("d_cz")
|
||||
cuda.memcpy_dtoh(cz, ptr_cz)
|
||||
return cx, cy, cz
|
||||
return cx, cy
|
||||
self._cached_vectors_3d = (cx, cy, cz)
|
||||
return self._cached_vectors_3d
|
||||
self._cached_vectors_2d = (cx, cy)
|
||||
return self._cached_vectors_2d
|
||||
|
||||
# -- Macroscopic field extraction ----------------------------------------
|
||||
def get_macroscopic(self):
|
||||
def get_macroscopic(self, *, step_id: int | None = None):
|
||||
"""Download DDF and compute rho, ux, uy [, uz] on host."""
|
||||
self.download_ddf()
|
||||
# Reuse the DDF host mirror when step_id is unchanged to avoid
|
||||
# duplicate DTOH in repeated diagnostics of the same timestep.
|
||||
self.download_ddf(step_id=step_id)
|
||||
nq = self.nq
|
||||
|
||||
if self.cfg.is_d2q9:
|
||||
@@ -266,7 +302,7 @@ class LBMField:
|
||||
|
||||
# -- Snapshots -----------------------------------------------------------
|
||||
def snapshot(self):
|
||||
self.download_ddf()
|
||||
self.download_ddf(force=True)
|
||||
self._ddf_snap = self.ddf.copy()
|
||||
|
||||
def restore(self):
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
#define NT 256
|
||||
#define MULT_GPU 0
|
||||
|
||||
#define NX 401
|
||||
#define NY 201
|
||||
#define NX 3000
|
||||
#define NY 300
|
||||
#define NZ 1
|
||||
|
||||
// ---- Lattice model (single source of truth) ----
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
#define OUTLET_MODE 0
|
||||
#define OUTLET_BLEND_ALPHA 0.700f
|
||||
#define OUTLET_BACKFLOW_CLAMP 1
|
||||
#define Y_WALL_BC 0
|
||||
#define Y_WALL_BC 1
|
||||
|
||||
#define OMEGA_COLLISION_MIN 0.01f
|
||||
#define OMEGA_COLLISION_MAX 1.960f
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
#ifndef CELERIS_CONFIG_OBJECTS_H
|
||||
#define CELERIS_CONFIG_OBJECTS_H
|
||||
|
||||
#define N_OBJS 0
|
||||
#define N_OBJS 3
|
||||
|
||||
#endif
|
||||
@@ -4,9 +4,9 @@
|
||||
#define CELERIS_CONFIG_PHYSICS_H
|
||||
|
||||
#define LBtype float
|
||||
#define VIS 0.0090000000
|
||||
#define VIS 0.0040000000
|
||||
#define RHO 1.0
|
||||
#define U0 0.03
|
||||
#define U0 0.04
|
||||
|
||||
#define PI 3.141592653589793238
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ class LBMStepper:
|
||||
_gpu_bytes = f.n * f.nq * f.store_bytes
|
||||
cuda.memcpy_dtod(f.temp_gpu, f.ddf_gpu, _gpu_bytes)
|
||||
cuda.memcpy_dtoh(f.flag, f.flag_gpu)
|
||||
f.download_ddf()
|
||||
f.download_ddf(step_id=self._step_count, force=True)
|
||||
|
||||
def step(
|
||||
self,
|
||||
@@ -88,6 +88,9 @@ class LBMStepper:
|
||||
|
||||
self._launch_sensor(obs_gpu, **launch_kw)
|
||||
self._step_count += 1
|
||||
if n > 0:
|
||||
# Any completed GPU step invalidates host DDF mirror.
|
||||
f.invalidate_host_ddf_cache()
|
||||
|
||||
def _launch_curved(self, action_gpu, obs_gpu, **launch_kw):
|
||||
f = self.field
|
||||
|
||||
@@ -125,6 +125,7 @@ class Simulation:
|
||||
self._module = compiler.load_module(self._ptx_path)
|
||||
# Reconnect field and stepper to new module
|
||||
self.field.module = self._module
|
||||
self.field.invalidate_module_constant_cache()
|
||||
self.field._upload_params()
|
||||
_prev_step_count = self.stepper._step_count
|
||||
self.stepper = LBMStepper(
|
||||
@@ -194,10 +195,10 @@ class Simulation:
|
||||
# -- Data access ---------------------------------------------------------
|
||||
def get_macroscopic(self) -> Dict[str, np.ndarray]:
|
||||
"""Download DDF and return rho, ux, uy [, uz]."""
|
||||
return self.field.get_macroscopic()
|
||||
return self.field.get_macroscopic(step_id=self.stepper.step_count)
|
||||
|
||||
def get_ddf(self) -> np.ndarray:
|
||||
self.field.download_ddf()
|
||||
self.field.download_ddf(step_id=self.stepper.step_count)
|
||||
return self.field.ddf.copy()
|
||||
|
||||
def get_flags(self) -> np.ndarray:
|
||||
|
||||
Reference in new issue
Block a user