|
|
"""
|
|
|
Utilities for visualizing WAKESET data.
|
|
|
Handles both 2D planar interpolations and 3D volumetric slices.
|
|
|
"""
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
import numpy as np
|
|
|
import matplotlib.pyplot as plt
|
|
|
from pathlib import Path
|
|
|
from typing import Dict, Union, Optional, Tuple
|
|
|
|
|
|
|
|
|
DEFAULT_CMAP = 'jet'
|
|
|
FIG_SIZE_PLANE = (8, 6)
|
|
|
FIG_SIZE_VOL = (15, 5)
|
|
|
|
|
|
def load_visualization_plane(
|
|
|
data: Union[str, Path, Dict],
|
|
|
variable: str = "velocity_magnitude",
|
|
|
title: Optional[str] = None,
|
|
|
save_path: Optional[Union[str, Path]] = None
|
|
|
):
|
|
|
"""
|
|
|
Visualizes a 2D interpolated plane.
|
|
|
"""
|
|
|
|
|
|
data_dict = _ensure_dict(data)
|
|
|
|
|
|
if variable not in data_dict:
|
|
|
raise KeyError(f"Variable '{variable}' not found in data. Available: {list(data_dict.keys())}")
|
|
|
|
|
|
grid = data_dict[variable]
|
|
|
|
|
|
|
|
|
|
|
|
meta = data_dict.get('meta', {})
|
|
|
if isinstance(meta, np.ndarray): meta = meta.item()
|
|
|
|
|
|
u_label = meta.get('u_axis', 'U-Axis')
|
|
|
v_label = meta.get('v_axis', 'V-Axis')
|
|
|
plane_axis = meta.get('plane_axis', 'Plane')
|
|
|
plane_val = meta.get('plane_value', 0.0)
|
|
|
bounds = meta.get('bounds', None)
|
|
|
|
|
|
|
|
|
fig, ax = plt.subplots(figsize=FIG_SIZE_PLANE)
|
|
|
|
|
|
|
|
|
im = ax.imshow(
|
|
|
grid,
|
|
|
origin='lower',
|
|
|
cmap=DEFAULT_CMAP,
|
|
|
aspect='auto',
|
|
|
extent=bounds if bounds is not None else None
|
|
|
)
|
|
|
|
|
|
|
|
|
cbar = plt.colorbar(im, ax=ax)
|
|
|
cbar.set_label(variable.replace('_', ' ').title())
|
|
|
|
|
|
ax.set_xlabel(f"{u_label} (m)")
|
|
|
ax.set_ylabel(f"{v_label} (m)")
|
|
|
|
|
|
safe_title = title or f"{variable} on {plane_axis}-Plane ({plane_val:.2f} m)"
|
|
|
ax.set_title(safe_title)
|
|
|
|
|
|
plt.tight_layout()
|
|
|
|
|
|
if save_path:
|
|
|
plt.savefig(save_path, dpi=150)
|
|
|
print(f"Saved plot to {save_path}")
|
|
|
plt.close()
|
|
|
else:
|
|
|
plt.show()
|
|
|
|
|
|
|
|
|
def load_visualization_volume(
|
|
|
data: Union[str, Path, Dict],
|
|
|
variable: str = "velocity_magnitude",
|
|
|
slice_indices: Optional[Tuple[int, int, int]] = None,
|
|
|
save_path: Optional[Union[str, Path]] = None
|
|
|
):
|
|
|
"""
|
|
|
Visualizes 3 orthogonal slices (X, Y, Z) of a 3D volume.
|
|
|
Defaults to the center (64th index for 128 grids).
|
|
|
"""
|
|
|
|
|
|
data_dict = _ensure_dict(data)
|
|
|
|
|
|
if variable not in data_dict:
|
|
|
raise KeyError(f"Variable '{variable}' not found. Available: {list(data_dict.keys())}")
|
|
|
|
|
|
vol = data_dict[variable]
|
|
|
nx, ny, nz = vol.shape
|
|
|
|
|
|
|
|
|
if slice_indices is None:
|
|
|
idx_x, idx_y, idx_z = nx // 2, ny // 2, nz // 2
|
|
|
else:
|
|
|
idx_x, idx_y, idx_z = slice_indices
|
|
|
|
|
|
|
|
|
fig, axes = plt.subplots(1, 3, figsize=FIG_SIZE_VOL)
|
|
|
|
|
|
|
|
|
|
|
|
valid_mask = (vol != 0) & (~np.isnan(vol))
|
|
|
if np.any(valid_mask):
|
|
|
vmin, vmax = np.percentile(vol[valid_mask], [1, 99])
|
|
|
else:
|
|
|
vmin, vmax = vol.min(), vol.max()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
slice_x = vol[idx_x, :, :]
|
|
|
im1 = axes[0].imshow(slice_x.T, origin='lower', cmap=DEFAULT_CMAP, vmin=vmin, vmax=vmax, aspect='equal')
|
|
|
axes[0].set_title(f"X-Slice (idx={idx_x})")
|
|
|
axes[0].set_xlabel("Y Axis")
|
|
|
axes[0].set_ylabel("Z Axis")
|
|
|
|
|
|
|
|
|
|
|
|
slice_y = vol[:, idx_y, :]
|
|
|
im2 = axes[1].imshow(slice_y.T, origin='lower', cmap=DEFAULT_CMAP, vmin=vmin, vmax=vmax, aspect='equal')
|
|
|
axes[1].set_title(f"Y-Slice (idx={idx_y})")
|
|
|
axes[1].set_xlabel("X Axis")
|
|
|
axes[1].set_ylabel("Z Axis")
|
|
|
|
|
|
|
|
|
|
|
|
slice_z = vol[:, :, idx_z]
|
|
|
im3 = axes[2].imshow(slice_z.T, origin='lower', cmap=DEFAULT_CMAP, vmin=vmin, vmax=vmax, aspect='equal')
|
|
|
axes[2].set_title(f"Z-Slice (idx={idx_z})")
|
|
|
axes[2].set_xlabel("X Axis")
|
|
|
axes[2].set_ylabel("Y Axis")
|
|
|
|
|
|
|
|
|
|
|
|
cbar = fig.colorbar(im3, ax=axes.ravel().tolist(), shrink=0.8)
|
|
|
cbar.set_label(variable.replace('_', ' ').title())
|
|
|
|
|
|
plt.suptitle(f"Volumetric Slices: {variable}", fontsize=14)
|
|
|
|
|
|
|
|
|
if save_path:
|
|
|
plt.savefig(save_path, dpi=150)
|
|
|
print(f"Saved plot to {save_path}")
|
|
|
plt.close()
|
|
|
else:
|
|
|
plt.show()
|
|
|
|
|
|
def _ensure_dict(data: Union[str, Path, Dict]) -> Dict:
|
|
|
"""Helper to load npz file or pass through dictionary."""
|
|
|
if isinstance(data, (str, Path)):
|
|
|
p = Path(data)
|
|
|
if not p.exists():
|
|
|
raise FileNotFoundError(f"File not found: {p}")
|
|
|
|
|
|
return np.load(p, allow_pickle=True)
|
|
|
return data
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
plane_file = Path("Forward_0100_ms_Angle_00_VERTPLN_ALL.npz")
|
|
|
if plane_file.exists():
|
|
|
print("Visualizing Plane...")
|
|
|
load_visualization_plane(plane_file, variable="velocity_magnitude")
|
|
|
else:
|
|
|
print("No plane file found for demo. (Run load_planes.py first)")
|
|
|
|
|
|
|
|
|
vol_file = Path("Forward_0100_ms_Angle_00_CUBE_128.npz")
|
|
|
if vol_file.exists():
|
|
|
print("Visualizing Volume Slices...")
|
|
|
load_visualization_volume(vol_file, variable="velocity_magnitude", slice_indices=(65, 65, 65))
|
|
|
else:
|
|
|
print("No volume file found for demo. (Run load_volumes.py first)") |