WAKESET / Examples /Python /load_visualizations.py
ZacharyCB99's picture
Add files using upload-large-folder tool
b5241eb verified
"""
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
# Configuration
DEFAULT_CMAP = 'jet' # Classic CFD look. Options: 'viridis', 'plasma', 'turbo'
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.
"""
# 1. Load Data if path provided
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]
# 2. Extract Metadata for Axes (if available)
# The load_planes.py script saves a 'meta' dictionary
meta = data_dict.get('meta', {})
if isinstance(meta, np.ndarray): meta = meta.item() # Handle wrapped npz dicts
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) # [min_u, max_u, min_v, max_v]
# 3. Plot
fig, ax = plt.subplots(figsize=FIG_SIZE_PLANE)
# Use 'extent' to map array pixels to physical coordinates
im = ax.imshow(
grid,
origin='lower',
cmap=DEFAULT_CMAP,
aspect='auto',
extent=bounds if bounds is not None else None
)
# Decoration
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).
"""
# 1. Load Data
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
# Default to center slices if not provided
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
# 2. Setup Plot
fig, axes = plt.subplots(1, 3, figsize=FIG_SIZE_VOL)
# Calculate global min/max for consistent coloring across slices
# We ignore 0.0 or NaN if they represent masked geometry
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()
# 3. Slice and Plot
# --- Slice X (Side View) ---
# Fix X, show Y vs Z
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 (Top/Bottom View) ---
# Fix Y, show X vs Z
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 (Front/Back View) ---
# Fix Z, show X vs Y
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")
# 4. Decoration
# Add a single colorbar for the whole figure
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)
# plt.tight_layout() # Sometimes interferes with global colorbar
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}")
# Allow loading .npz files directly
return np.load(p, allow_pickle=True)
return data
if __name__ == "__main__":
# --- Example Usage ---
# 1. Try to find a Plane file (.npz)
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)")
# 2. Try to find a Volume file (.npz)
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)")