File size: 6,170 Bytes
b5241eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""

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)")