WAKESET / Examples /Python /load_planes.py
ZacharyCB99's picture
Add files using upload-large-folder tool
b5241eb verified
"""
Utilities for loading WAKESET plane slices (unstructured CFD data)
and interpolating them onto regular 2D grids.
"""
from __future__ import annotations
import re
import numpy as np
import pandas as pd
from pathlib import Path
from scipy.interpolate import LinearNDInterpolator, NearestNDInterpolator
# --- Configuration ---
DEFAULT_GRID_RES: int = 512
# Aliases to map CSV headers to standard names
_COL_ALIASES = {
"cellnumber": "cell",
"x_coordinate": "x", "y_coordinate": "y", "z_coordinate": "z",
"velocity_magnitude": "velocity_magnitude",
"z_velocity": "vz", "y_velocity": "vy", "x_velocity": "vx",
"total_pressure": "total_pressure",
"static_pressure": "static_pressure"
}
def process_plane_export(
filepath: str,
resolution: int = DEFAULT_GRID_RES,
fill_value: float = np.nan,
precision_round: int = 4
):
"""
Parses unstructured CFD plane exports and interpolates them onto a
regular 2D grid (Image format).
"""
filepath = Path(filepath)
print(f"Processing Plane: {filepath.name}...")
# 1. CSV Loading (Handles variable whitespace)
try:
df = pd.read_csv(
filepath,
sep=',', # Comma separator
skipinitialspace=True, # Handle " , 1.0"
engine='c',
on_bad_lines='warn'
)
except Exception as e:
print(f"Read failed: {e}")
return None
# Normalize columns
df.columns = [_normalize_col(c) for c in df.columns]
# Ensure coordinates exist
if not {'x', 'y', 'z'}.issubset(df.columns):
print(f"Error: Missing coordinate columns. Found: {list(df.columns)}")
return None
# 2. Auto-Detect Plane Orientation
# Look for the axis with the least variance (the flat axis)
coords = df[['x', 'y', 'z']].values.astype(np.float32)
spreads = np.ptp(coords, axis=0) # Peak-to-peak (max - min)
flat_axis_idx = np.argmin(spreads)
axis_names = ['x', 'y', 'z']
flat_axis_name = axis_names[flat_axis_idx]
# Safety Check: Is it actually a plane?
if spreads[flat_axis_idx] > 1e-3:
print(f"Warning: Data does not look planar. Spread in {flat_axis_name} is {spreads[flat_axis_idx]}")
# 3. Define 2D Projection (U, V)
# If Plane is X-constant, we map Y->U, Z->V, etc.
if flat_axis_name == 'x':
u_col, v_col = 'y', 'z'
elif flat_axis_name == 'y':
u_col, v_col = 'x', 'z'
else: # z
u_col, v_col = 'x', 'y'
print(f" -> Orientation: {flat_axis_name}-plane. Projecting {u_col}/{v_col} -> Grid.")
# 4. Generate Target Grid (Regular Image)
u_raw = df[u_col].values
v_raw = df[v_col].values
u_min, u_max = u_raw.min(), u_raw.max()
v_min, v_max = v_raw.min(), v_raw.max()
# Create the meshgrid
grid_u_Lin = np.linspace(u_min, u_max, resolution)
grid_v_Lin = np.linspace(v_min, v_max, resolution)
grid_u, grid_v = np.meshgrid(grid_u_Lin, grid_v_Lin)
# Flatten targets for interpolation logic
target_points = np.column_stack((grid_u.ravel(), grid_v.ravel()))
source_points = np.column_stack((u_raw, v_raw))
# 5. Vectorized Interpolation
# We grab all relevant data channels
channels = [c for c in df.columns if c not in ['x', 'y', 'z', 'cell']]
source_values = df[channels].values
# LinearNDInterpolator builds a Delaunay triangulation once
# and interpolates ALL channels simultaneously.
print(f" -> Interpolating {len(source_points)} points to {resolution}x{resolution} grid...")
interp = LinearNDInterpolator(source_points, source_values, fill_value=fill_value)
interpolated_flat = interp(target_points)
# 6. Fallback for Convex Hull Gaps (Optional)
# LinearND returns NaN for points slightly outside the triangulation (edges).
# We fill these with Nearest Neighbor to avoid jagged edges.
if np.isnan(interpolated_flat).any():
nan_mask = np.isnan(interpolated_flat[:, 0]) # Check first channel
if np.any(nan_mask):
# Only train nearest neighbor on valid points
nn = NearestNDInterpolator(source_points, source_values)
interpolated_flat[nan_mask] = nn(target_points[nan_mask])
# 7. Reshape and Store
plane_data = {
"meta": {
"plane_axis": flat_axis_name,
"plane_value": float(np.median(coords[:, flat_axis_idx])),
"u_axis": u_col,
"v_axis": v_col,
"bounds": [u_min, u_max, v_min, v_max]
}
}
for i, col_name in enumerate(channels):
# Reshape (N*N, ) -> (N, N)
# Note: We flip ud (up/down) usually to match image coordinates if needed,
# but here we keep mathematical coordinates.
plane_data[col_name] = interpolated_flat[:, i].reshape(resolution, resolution)
return plane_data
def _normalize_col(name: str) -> str:
clean = re.sub(r"[^a-z0-9]+", "_", name.lower()).strip("_")
return _COL_ALIASES.get(clean, clean)
if __name__ == "__main__":
# --- Test ---
# Update path to a Plane file (VERTPLN or HORZPLN)
test_file = Path("C:/Users/zacco/Desktop/Files/WAKESET/Test Files/Forward_0100_ms_Angle_00_VERTPLN_ALL")
if not test_file.exists() and test_file.with_suffix(".csv").exists():
test_file = test_file.with_suffix(".csv")
if test_file.exists():
data = process_plane_export(test_file, resolution=512)
if data:
print("Success!")
# Access a variable
grid = data['velocity_magnitude']
print(f"Output Grid Shape: {grid.shape}")
print(f"Axis detected: {data['meta']['plane_axis']}")
# Save
out_path = test_file.with_name(test_file.name + ".npz")
np.savez_compressed(out_path, **data)
print(f"Saved to: {out_path}")
else:
print(f"File not found: {test_file}")