pymodeflow 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- modeflow/__init__.py +36 -0
- modeflow/__main__.py +11 -0
- modeflow/_common.py +157 -0
- modeflow/_version.py +24 -0
- modeflow/dmd.py +681 -0
- modeflow/py.typed +0 -0
- modeflow/snap_pod.py +631 -0
- modeflow/spod.py +766 -0
- modeflow/synthetic.py +88 -0
- pymodeflow-0.1.2.dist-info/METADATA +228 -0
- pymodeflow-0.1.2.dist-info/RECORD +15 -0
- pymodeflow-0.1.2.dist-info/WHEEL +5 -0
- pymodeflow-0.1.2.dist-info/entry_points.txt +4 -0
- pymodeflow-0.1.2.dist-info/licenses/LICENSE +21 -0
- pymodeflow-0.1.2.dist-info/top_level.txt +1 -0
modeflow/snap_pod.py
ADDED
|
@@ -0,0 +1,631 @@
|
|
|
1
|
+
"""Snapshot Proper Orthogonal Decomposition (SnapshotPOD) of velocity-field from
|
|
2
|
+
experiments [PIV, PTV] and schlieren image data or other qualitative experiment data.
|
|
3
|
+
|
|
4
|
+
Uses the method of snapshots: the small nt x nt temporal correlation matrix is
|
|
5
|
+
diagonalized instead of running an SVD on the (grid points x nt) data matrix,
|
|
6
|
+
which is much faster and lighter on memory when grid points >> snapshots.
|
|
7
|
+
|
|
8
|
+
Input: a .npz or .mat file holding the velocity components U, V, W, Vmag and
|
|
9
|
+
`dim` = [nx, ny]. Every component is ALREADY FLATTENED: an array of shape
|
|
10
|
+
[nx*ny, nt] whose columns are the snapshots. The POD works directly on this
|
|
11
|
+
matrix; `dim` is only used to fold modes back to an nx-by-ny field for plots
|
|
12
|
+
(see --order). Pick the component to analyze with -c/--component.
|
|
13
|
+
|
|
14
|
+
Sub-commands
|
|
15
|
+
------------
|
|
16
|
+
save run the analysis and WRITE results (arrays, CSVs, figures)
|
|
17
|
+
preview run the analysis and only DISPLAY figures (nothing is written)
|
|
18
|
+
replot re-draw modes from a previously saved POD_modes.npy
|
|
19
|
+
reconstruct rebuild the data from saved POD_modes.npy + POD_coefficients.npy
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import argparse
|
|
25
|
+
from datetime import date
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from time import perf_counter
|
|
28
|
+
|
|
29
|
+
import matplotlib.pyplot as plt
|
|
30
|
+
import numpy as np
|
|
31
|
+
import scipy.signal as spy
|
|
32
|
+
|
|
33
|
+
from ._common import COMPONENTS, FONT, __version__, read_component
|
|
34
|
+
from ._common import bar as _bar
|
|
35
|
+
from ._common import check_dim as _check_dim
|
|
36
|
+
from ._common import chunks as _chunks
|
|
37
|
+
from ._common import component_type as _component
|
|
38
|
+
from ._common import order_type as _order
|
|
39
|
+
from ._common import save_figs as _save_figs
|
|
40
|
+
from ._common import unflatten as _unflatten
|
|
41
|
+
|
|
42
|
+
__all__ = ["SnapshotPOD"]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
RANK_TOL = 1e-3
|
|
46
|
+
BLOCK = 1 << 16
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _mode_figure(mode, clim):
|
|
50
|
+
if clim is None: # symmetric auto-scaling around zero
|
|
51
|
+
v = float(np.nanmax(np.abs(mode))) or 1.0
|
|
52
|
+
vmin, vmax = -v, v
|
|
53
|
+
else:
|
|
54
|
+
vmin, vmax = clim
|
|
55
|
+
fig, ax = plt.subplots()
|
|
56
|
+
im = ax.imshow(mode, cmap="jet", vmin=vmin, vmax=vmax, interpolation="bicubic")
|
|
57
|
+
fig.colorbar(im, ax=ax)
|
|
58
|
+
ax.axis("off")
|
|
59
|
+
fig.tight_layout()
|
|
60
|
+
return fig
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class SnapshotPOD:
|
|
64
|
+
"""Snapshot POD of one velocity component.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
source (str): .npz or .mat file with U, V, W, Vmag ([nx*ny, nt], already
|
|
68
|
+
flattened, one snapshot per column) and dim = [nx, ny]
|
|
69
|
+
dt (float): Time step between snapshots [s]
|
|
70
|
+
component (str): One of "U", "V", "W", "Vmag"
|
|
71
|
+
num_modes (int): Number of modes to plot
|
|
72
|
+
energy (float): Energy fraction that defines the optimal rank (0-1)
|
|
73
|
+
dim (tuple): Grid size (nx, ny). Needed only when the data file has no `dim`;
|
|
74
|
+
if both are given, this value is used
|
|
75
|
+
order (str): How each [nx, ny] field was flattened, used only to fold
|
|
76
|
+
modes back to 2D for plotting: "F" = column-major (MATLAB), "C" = row-major
|
|
77
|
+
clim (tuple): (vmin, vmax) colour limits; None = auto per mode
|
|
78
|
+
target_dir (str): Output root directory (required when save_results).
|
|
79
|
+
results saved as <target_dir>_<YYYYMMDD>/<component>
|
|
80
|
+
visualize (bool): Display figures interactively
|
|
81
|
+
save_results (bool): Write arrays, CSVs and figures to disk. At least
|
|
82
|
+
the optimal-rank number of modes/coefficients is saved so that the
|
|
83
|
+
data can be rebuilt later with the `reconstruct` sub-command.
|
|
84
|
+
dpi (int): Resolution of saved figures
|
|
85
|
+
progress (bool): Show tqdm progress bars
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(self,
|
|
89
|
+
source,
|
|
90
|
+
dt,
|
|
91
|
+
component="U",
|
|
92
|
+
num_modes=4,
|
|
93
|
+
energy=0.99,
|
|
94
|
+
dim=None,
|
|
95
|
+
order="C",
|
|
96
|
+
clim=None,
|
|
97
|
+
target_dir=None,
|
|
98
|
+
visualize=False,
|
|
99
|
+
save_results=False,
|
|
100
|
+
dpi=300,
|
|
101
|
+
progress=True):
|
|
102
|
+
|
|
103
|
+
if num_modes < 1:
|
|
104
|
+
raise ValueError("num_modes must be >= 1")
|
|
105
|
+
if component not in COMPONENTS:
|
|
106
|
+
raise ValueError(f"component must be one of {COMPONENTS}")
|
|
107
|
+
if order not in ("F", "C"):
|
|
108
|
+
raise ValueError("order must be 'F' or 'C'")
|
|
109
|
+
if dt <= 0:
|
|
110
|
+
raise ValueError("dt must be > 0")
|
|
111
|
+
if not 0.0 < energy < 1.0:
|
|
112
|
+
raise ValueError("energy must be between 0 and 1")
|
|
113
|
+
if dpi < 1:
|
|
114
|
+
raise ValueError("dpi must be >= 1")
|
|
115
|
+
if clim is not None and not clim[0] < clim[1]:
|
|
116
|
+
raise ValueError("clim must be (vmin, vmax) with vmin < vmax")
|
|
117
|
+
|
|
118
|
+
self.source = Path(source)
|
|
119
|
+
if not self.source.is_file():
|
|
120
|
+
raise FileNotFoundError(f"Input file not found: {self.source}")
|
|
121
|
+
if self.source.suffix.lower() not in (".npz", ".mat"):
|
|
122
|
+
raise ValueError("Input must be a .npz or .mat file")
|
|
123
|
+
|
|
124
|
+
self.component = component
|
|
125
|
+
self.order = order
|
|
126
|
+
self._dim_arg = self._check_dim(dim) if dim is not None else None
|
|
127
|
+
self.dt = dt
|
|
128
|
+
self.num_modes = num_modes
|
|
129
|
+
self.energy_target = energy
|
|
130
|
+
self.clim = tuple(clim) if clim is not None else None
|
|
131
|
+
self.visualize = visualize
|
|
132
|
+
self.save_results = save_results
|
|
133
|
+
self.dpi = dpi
|
|
134
|
+
self.progress = progress
|
|
135
|
+
|
|
136
|
+
self.out_dir = None
|
|
137
|
+
if save_results:
|
|
138
|
+
if target_dir is None:
|
|
139
|
+
raise ValueError("target_dir is required when saving results")
|
|
140
|
+
self.out_dir = (Path(target_dir)
|
|
141
|
+
/ f"{self.source.stem}_{date.today():%Y%m%d}/{component}")
|
|
142
|
+
|
|
143
|
+
# filled by load_data() and compute()
|
|
144
|
+
self.nt = self.dim = self.mean = self._X = None
|
|
145
|
+
self.s = self.Vt = self.energy_ratio = None
|
|
146
|
+
self.modes = self.coeffs = None
|
|
147
|
+
self.r = self.m = None
|
|
148
|
+
|
|
149
|
+
_check_dim = staticmethod(_check_dim)
|
|
150
|
+
|
|
151
|
+
def _pbar(self, iterable, desc, unit="it"):
|
|
152
|
+
return _bar(iterable, desc, unit, self.progress)
|
|
153
|
+
|
|
154
|
+
def load_data(self):
|
|
155
|
+
"""Load the selected component as float32 snapshots of shape (nt, nx*ny).
|
|
156
|
+
|
|
157
|
+
The file holds the flattened data as [nx*ny, nt]; it is transposed so that each row is one snapshot.
|
|
158
|
+
Sets self.dim = (nx, ny).
|
|
159
|
+
"""
|
|
160
|
+
print(f"Loading '{self.component}' from {self.source.name} ...")
|
|
161
|
+
arr, dim = read_component(self.source, self.component)
|
|
162
|
+
|
|
163
|
+
file_dim = self._check_dim(dim) if dim is not None else None
|
|
164
|
+
if self._dim_arg is not None:
|
|
165
|
+
dim = self._dim_arg # explicit --dim wins over the file
|
|
166
|
+
if file_dim is not None and file_dim != dim:
|
|
167
|
+
print(f"Warning: --dim {list(dim)} overrides dim {list(file_dim)} stored in the file.")
|
|
168
|
+
elif file_dim is not None:
|
|
169
|
+
dim = file_dim
|
|
170
|
+
else:
|
|
171
|
+
raise ValueError(f"`dim` is not in {self.source.name}; pass it with --dim NX NY")
|
|
172
|
+
|
|
173
|
+
arr = np.squeeze(np.asarray(arr))
|
|
174
|
+
if arr.dtype.kind not in "fiu":
|
|
175
|
+
raise ValueError(f"Velocity data must be numeric, got dtype {arr.dtype}")
|
|
176
|
+
if arr.ndim != 2 or arr.shape[0] != dim[0] * dim[1]:
|
|
177
|
+
raise ValueError(f"Expected an array of shape [nx*ny, nt] = [{dim[0] * dim[1]}, nt] "
|
|
178
|
+
f"for dim={list(dim)}, got {arr.shape}")
|
|
179
|
+
if arr.shape[1] < 2:
|
|
180
|
+
raise ValueError(f"Need at least 2 snapshots, found {arr.shape[1]}")
|
|
181
|
+
|
|
182
|
+
self.dim = dim
|
|
183
|
+
return np.ascontiguousarray(arr.T, dtype=np.float32)
|
|
184
|
+
|
|
185
|
+
def compute(self):
|
|
186
|
+
"""Method of snapshots: eigen-decomposition of the nt x nt correlation matrix."""
|
|
187
|
+
|
|
188
|
+
snaps = self.load_data() # (nt, nx*ny)
|
|
189
|
+
self.nt = snaps.shape[0]
|
|
190
|
+
|
|
191
|
+
# use the NaN-aware mean and treat the fluctuation there as zero so the SVD stays finite.
|
|
192
|
+
has_nan = bool(np.isnan(snaps).any())
|
|
193
|
+
if has_nan:
|
|
194
|
+
print("Warning: NaNs found in the data; they are set to zero after mean removal.")
|
|
195
|
+
with np.errstate(all="ignore"):
|
|
196
|
+
self.mean = np.nan_to_num(np.nanmean(snaps, axis=0))
|
|
197
|
+
else:
|
|
198
|
+
self.mean = snaps.mean(axis=0)
|
|
199
|
+
snaps -= self.mean
|
|
200
|
+
if has_nan:
|
|
201
|
+
np.nan_to_num(snaps, copy=False)
|
|
202
|
+
|
|
203
|
+
self._X = snaps
|
|
204
|
+
n_grid = snaps.shape[1]
|
|
205
|
+
blocks = _chunks(n_grid, BLOCK)
|
|
206
|
+
|
|
207
|
+
# correlation matrix accumulated block-by-block in float64
|
|
208
|
+
C = np.zeros((self.nt, self.nt), dtype=np.float64)
|
|
209
|
+
for a, b in self._pbar(blocks, "Correlation matrix", "blk"):
|
|
210
|
+
blk = self._X[:, a:b]
|
|
211
|
+
C += blk @ blk.T
|
|
212
|
+
|
|
213
|
+
print("Solving Eigen Decomposition ...")
|
|
214
|
+
lam, V = np.linalg.eigh(C)
|
|
215
|
+
lam = np.clip(lam[::-1], 0.0, None)
|
|
216
|
+
V = V[:, ::-1]
|
|
217
|
+
s = np.sqrt(lam)
|
|
218
|
+
|
|
219
|
+
k = int(np.count_nonzero(s > RANK_TOL * s[0]))
|
|
220
|
+
if k == 0:
|
|
221
|
+
raise ValueError("All snapshots are identical; nothing to decompose")
|
|
222
|
+
lam, self.s, self.Vt = lam[:k], s[:k], V[:, :k].T
|
|
223
|
+
self.energy_ratio = np.cumsum(lam) / lam.sum()
|
|
224
|
+
|
|
225
|
+
# smallest rank whose cumulative energy reaches the target
|
|
226
|
+
self.r = min(int(np.searchsorted(self.energy_ratio, self.energy_target)) + 1, k)
|
|
227
|
+
self.m = min(self.num_modes, k)
|
|
228
|
+
|
|
229
|
+
# when saving, keep at least the optimal rank so the data can be rebuilt
|
|
230
|
+
keep = max(self.m, self.r) if self.save_results else self.m
|
|
231
|
+
self.coeffs = self.s[:keep, None] * self.Vt[:keep] # (keep, nt)
|
|
232
|
+
|
|
233
|
+
Vk = self.Vt[:keep].astype(np.float32)
|
|
234
|
+
sk = self.s[:keep, None].astype(np.float32)
|
|
235
|
+
self.modes = np.empty((keep, n_grid), dtype=np.float32) # flattened, (keep, nx*ny)
|
|
236
|
+
for a, b in self._pbar(blocks, "Computing modes", "blk"):
|
|
237
|
+
self.modes[:, a:b] = (Vk @ self._X[:, a:b]) / sk
|
|
238
|
+
|
|
239
|
+
if self.save_results:
|
|
240
|
+
self.out_dir.mkdir(parents=True, exist_ok=True)
|
|
241
|
+
np.save(self.out_dir/"POD_modes.npy", np.ascontiguousarray(self.modes.T)) # (nx*ny, keep)
|
|
242
|
+
np.save(self.out_dir/"POD_coefficients.npy", self.coeffs) # (keep, nt)
|
|
243
|
+
np.save(self.out_dir/"POD_mean.npy", self.mean) # (nx*ny,)
|
|
244
|
+
np.savez(self.out_dir/"POD_info.npz", dim=np.array(self.dim), order=self.order,
|
|
245
|
+
component=self.component, dt=self.dt, optimal_rank=self.r, num_snapshots=self.nt)
|
|
246
|
+
|
|
247
|
+
def _path(self, name):
|
|
248
|
+
return None if self.out_dir is None else self.out_dir/name
|
|
249
|
+
|
|
250
|
+
def plot_energy(self):
|
|
251
|
+
"""Cumulative energy ratio, normalized singular values and the CSV."""
|
|
252
|
+
k = len(self.s)
|
|
253
|
+
x = np.arange(1, k + 1)
|
|
254
|
+
|
|
255
|
+
fig, ax = plt.subplots()
|
|
256
|
+
ax.plot(x, self.energy_ratio, "g.-")
|
|
257
|
+
ax.axvline(self.r, color="gray", linestyle="--")
|
|
258
|
+
ax.set_xlim(left=1)
|
|
259
|
+
ax.set_xlabel("Truncated SVD size, $r$", fontdict=FONT)
|
|
260
|
+
ax.set_ylabel(r"Energy ratio $\epsilon(r)$", fontdict=FONT)
|
|
261
|
+
ax.text(0.95, 0.1, f"Optimal SnapshotPOD rank = {self.r}", transform=ax.transAxes, ha="right", fontdict=FONT)
|
|
262
|
+
fig.tight_layout()
|
|
263
|
+
_save_figs(fig, self._path("energy_ratio.png"), self.dpi, self.visualize)
|
|
264
|
+
|
|
265
|
+
e_norm = 100.0 * self.s / self.s.sum()
|
|
266
|
+
fig, ax = plt.subplots()
|
|
267
|
+
ax.semilogy(x, e_norm, "r.-")
|
|
268
|
+
ax.set_xlim(left=1)
|
|
269
|
+
ax.set_xlabel("SnapshotPOD modes", fontdict=FONT)
|
|
270
|
+
ax.set_ylabel(r"% TKE", fontdict=FONT)
|
|
271
|
+
fig.tight_layout()
|
|
272
|
+
_save_figs(fig, self._path("POD_energies.png"), self.dpi, self.visualize)
|
|
273
|
+
|
|
274
|
+
if self.save_results:
|
|
275
|
+
table = np.column_stack([x, e_norm, self.energy_ratio])
|
|
276
|
+
np.savetxt(self.out_dir / "mode_energies.csv", table, delimiter=",",
|
|
277
|
+
header="modes,s_norm (%),energy_ratio", comments="")
|
|
278
|
+
|
|
279
|
+
def plot_modes(self):
|
|
280
|
+
fields = _unflatten(self.modes[: self.m], self.dim, self.order)
|
|
281
|
+
for i in self._pbar(range(self.m), "Plotting modes", "mode"):
|
|
282
|
+
fig = _mode_figure(fields[i], self.clim)
|
|
283
|
+
_save_figs(fig, self._path(f"mode_{i + 1}.png"), self.dpi, self.visualize)
|
|
284
|
+
|
|
285
|
+
def plot_coefficients(self):
|
|
286
|
+
t = np.arange(self.nt) * self.dt
|
|
287
|
+
fig, axes = plt.subplots(self.m, 1, figsize=(10, max(3, 2 * self.m)),
|
|
288
|
+
sharey=True, squeeze=False)
|
|
289
|
+
for i, ax in enumerate(axes[:, 0]):
|
|
290
|
+
ax.plot(t, self.coeffs[i], color=plt.cm.tab10(i % 10))
|
|
291
|
+
ax.set_title(f"Mode {i + 1}")
|
|
292
|
+
ax.set_xlim(left=0)
|
|
293
|
+
fig.supylabel("SnapshotPOD Coefficients", **FONT)
|
|
294
|
+
fig.supxlabel("Time [s]", **FONT)
|
|
295
|
+
fig.tight_layout()
|
|
296
|
+
_save_figs(fig, self._path("POD_coefficients.png"), self.dpi, self.visualize)
|
|
297
|
+
|
|
298
|
+
def plot_psd(self):
|
|
299
|
+
"""Welch PSD of the plotted coefficients in one call; one figure save."""
|
|
300
|
+
freq, Pxx = spy.welch(self.coeffs[: self.m], fs=1.0 / self.dt, window="hann",
|
|
301
|
+
scaling="spectrum", nperseg=min(256, self.nt), axis=-1)
|
|
302
|
+
fig, axes = plt.subplots(self.m, 1, figsize=(10, max(3, 2 * self.m)), sharey=True, squeeze=False)
|
|
303
|
+
for i, ax in enumerate(axes[:, 0]):
|
|
304
|
+
ax.semilogy(freq, Pxx[i], color=plt.cm.tab10(i % 10))
|
|
305
|
+
ax.set_title(f"Mode {i + 1}")
|
|
306
|
+
ax.set_xlim(left=0)
|
|
307
|
+
if self.save_results:
|
|
308
|
+
np.savetxt(self.out_dir / f"psd_result_mode_{i + 1}.csv",
|
|
309
|
+
np.column_stack([Pxx[i], freq]), delimiter=",",
|
|
310
|
+
header="PSD,freq", comments="")
|
|
311
|
+
fig.supylabel("PSD", **FONT)
|
|
312
|
+
fig.supxlabel("Frequency [Hz]", **FONT)
|
|
313
|
+
fig.tight_layout()
|
|
314
|
+
_save_figs(fig, self._path("PSD.png"), self.dpi, self.visualize)
|
|
315
|
+
|
|
316
|
+
def reconstructed_data(self):
|
|
317
|
+
"""Display snapshot 1 next to its rank-r reconstruction (visual check only)."""
|
|
318
|
+
Vr = self.Vt[: self.r].astype(np.float32)
|
|
319
|
+
|
|
320
|
+
recon = Vr[:, 0] @ (Vr @ self._X) + self.mean
|
|
321
|
+
orig = self._X[0] + self.mean
|
|
322
|
+
pair = _unflatten(np.stack([orig, recon]), self.dim, self.order)
|
|
323
|
+
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
|
|
324
|
+
for ax, img, title in zip(axes, pair, (f"Raw {self.component}", f"{self.r}-mode reconstructed")):
|
|
325
|
+
im = ax.imshow(img, cmap="jet")
|
|
326
|
+
fig.colorbar(im, ax=ax, fraction=0.04)
|
|
327
|
+
ax.set_title(title)
|
|
328
|
+
ax.axis("off")
|
|
329
|
+
fig.tight_layout()
|
|
330
|
+
_save_figs(fig, self._path("reconstructed_snapshot.png"), self.dpi, self.visualize)
|
|
331
|
+
|
|
332
|
+
def fit(self):
|
|
333
|
+
t0 = perf_counter()
|
|
334
|
+
print(f"\nComputing SnapshotPOD of {self.source} ({self.component}) ... It takes some time!\n")
|
|
335
|
+
self.compute()
|
|
336
|
+
|
|
337
|
+
print(f"Loaded {self.nt} snapshots of {self.dim[0] * self.dim[1]} points "
|
|
338
|
+
f"(nx={self.dim[0]}, ny={self.dim[1]}); "
|
|
339
|
+
f"optimal rank for {self.energy_target:.0%} energy: {self.r}")
|
|
340
|
+
self.plot_modes()
|
|
341
|
+
self.plot_coefficients()
|
|
342
|
+
self.plot_energy()
|
|
343
|
+
self.plot_psd()
|
|
344
|
+
self.reconstructed_data() # run for save, preview and --show alike
|
|
345
|
+
|
|
346
|
+
msg = f"\nCompleted in {(perf_counter() - t0) / 60:.1f} mins"
|
|
347
|
+
|
|
348
|
+
if self.out_dir is not None:
|
|
349
|
+
msg += (f" and results saved in {self.out_dir.resolve()}"
|
|
350
|
+
f"\n{len(self.coeffs)} modes saved (optimal rank = {self.r}). "
|
|
351
|
+
f"\nRebuild the data with the `reconstruct` sub-command.")
|
|
352
|
+
print(msg)
|
|
353
|
+
|
|
354
|
+
@staticmethod
|
|
355
|
+
def plot_all_modes(path, output_dir=None, num_modes=None, clim=None,
|
|
356
|
+
visualize=False, dpi=300, progress=True, dim=None, order=None):
|
|
357
|
+
"""Plot modes from a saved POD_modes.npy, shape (nx*ny, K).
|
|
358
|
+
|
|
359
|
+
dim and order are read from POD_info.npz next to the modes file unless
|
|
360
|
+
given explicitly.
|
|
361
|
+
"""
|
|
362
|
+
path = Path(path)
|
|
363
|
+
if not path.is_file():
|
|
364
|
+
raise FileNotFoundError(f"File not found: {path}")
|
|
365
|
+
|
|
366
|
+
modes = np.load(path, mmap_mode="r")
|
|
367
|
+
if modes.ndim != 2:
|
|
368
|
+
raise ValueError(f"Expected a (nx*ny, K) array, got shape {modes.shape}")
|
|
369
|
+
|
|
370
|
+
info = path.with_name("POD_info.npz")
|
|
371
|
+
if (dim is None or order is None) and info.is_file():
|
|
372
|
+
with np.load(info) as d:
|
|
373
|
+
if dim is None:
|
|
374
|
+
dim = tuple(int(v) for v in d["dim"])
|
|
375
|
+
if order is None:
|
|
376
|
+
order = str(d["order"])
|
|
377
|
+
if dim is None:
|
|
378
|
+
raise ValueError("Grid size unknown: POD_info.npz not found next to the modes; pass --dim NX NY")
|
|
379
|
+
|
|
380
|
+
order = order or "C"
|
|
381
|
+
if dim[0] * dim[1] != modes.shape[0]:
|
|
382
|
+
raise ValueError(f"dim {tuple(dim)} does not match {modes.shape[0]} grid points")
|
|
383
|
+
|
|
384
|
+
if output_dir is not None:
|
|
385
|
+
Path(output_dir).mkdir(parents=True, exist_ok=True)
|
|
386
|
+
|
|
387
|
+
k = modes.shape[1] if num_modes is None else min(num_modes, modes.shape[1])
|
|
388
|
+
for n in _bar(range(k), "Plotting modes", "mode", progress):
|
|
389
|
+
field = _unflatten(np.asarray(modes[:, n])[None, :], dim, order)[0]
|
|
390
|
+
fig = _mode_figure(field, clim)
|
|
391
|
+
out = None if output_dir is None else Path(output_dir)/f"mode_{n + 1}.png"
|
|
392
|
+
_save_figs(fig, out, dpi, visualize)
|
|
393
|
+
|
|
394
|
+
@staticmethod
|
|
395
|
+
def reconstruct_from_files(modes_path, coeff_path=None, output=None, mean_path=None,
|
|
396
|
+
use_mean=True, rank=None, chunk=32, progress=True):
|
|
397
|
+
"""Rebuild the data from saved POD files: X ~ mean + modes @ coefficients.
|
|
398
|
+
|
|
399
|
+
Everything stays flattened, so the result has the same layout as the
|
|
400
|
+
input file: [nx*ny, nt], one snapshot per column.
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
modes_path: POD_modes.npy, shape (nx*ny, K)
|
|
404
|
+
coeff_path: POD_coefficients.npy, shape (K, nt); default is the file
|
|
405
|
+
next to modes_path
|
|
406
|
+
output: output .npy path; default <modes dir>/reconstructed_rank<k>.npy
|
|
407
|
+
mean_path: POD_mean.npy, shape (nx*ny,); default is the file next to
|
|
408
|
+
modes_path, if it exists
|
|
409
|
+
use_mean: add the mean back
|
|
410
|
+
rank: number of modes to use (default: all saved modes)
|
|
411
|
+
chunk: number of snapshots rebuilt per block
|
|
412
|
+
progress: Display progress bar for the reconstruction.
|
|
413
|
+
|
|
414
|
+
The result is written block-by-block to disk, so it never has to fit
|
|
415
|
+
in memory.
|
|
416
|
+
"""
|
|
417
|
+
modes_path = Path(modes_path)
|
|
418
|
+
coeff_path = Path(coeff_path) if coeff_path else modes_path.with_name("POD_coefficients.npy")
|
|
419
|
+
for p in (modes_path, coeff_path):
|
|
420
|
+
if not p.is_file():
|
|
421
|
+
raise FileNotFoundError(f"File not found: {p}")
|
|
422
|
+
|
|
423
|
+
modes = np.load(modes_path, mmap_mode="r")
|
|
424
|
+
coeffs = np.load(coeff_path, mmap_mode="r")
|
|
425
|
+
if modes.ndim != 2 or coeffs.ndim != 2:
|
|
426
|
+
raise ValueError(f"Expected modes (nx*ny, K) and coefficients (K, nt); "
|
|
427
|
+
f"got {modes.shape} and {coeffs.shape}")
|
|
428
|
+
P, K = modes.shape
|
|
429
|
+
if coeffs.shape[0] != K:
|
|
430
|
+
raise ValueError(f"Mode count mismatch: {K} modes vs {coeffs.shape[0]} coefficient rows")
|
|
431
|
+
N = coeffs.shape[1]
|
|
432
|
+
|
|
433
|
+
k = K if rank is None else rank
|
|
434
|
+
if k < 1:
|
|
435
|
+
raise ValueError("rank must be >= 1")
|
|
436
|
+
if k > K:
|
|
437
|
+
print(f"Only {K} modes were saved; using rank {K} instead of {k}.")
|
|
438
|
+
k = K
|
|
439
|
+
|
|
440
|
+
M = np.ascontiguousarray(modes[:, :k], dtype=np.float32)
|
|
441
|
+
Cf = np.ascontiguousarray(coeffs[:k], dtype=np.float32)
|
|
442
|
+
|
|
443
|
+
mean = None
|
|
444
|
+
if use_mean:
|
|
445
|
+
mp = Path(mean_path) if mean_path else modes_path.with_name("POD_mean.npy")
|
|
446
|
+
if mp.is_file():
|
|
447
|
+
mean = np.load(mp).astype(np.float32).reshape(-1, 1)
|
|
448
|
+
if mean.shape[0] != P:
|
|
449
|
+
raise ValueError(f"Mean has {mean.shape[0]} points, modes have {P}")
|
|
450
|
+
elif mean_path:
|
|
451
|
+
raise FileNotFoundError(f"File not found: {mp}")
|
|
452
|
+
else:
|
|
453
|
+
print("No POD_mean.npy found next to the modes; reconstructing without the mean.")
|
|
454
|
+
|
|
455
|
+
out_path = Path(output) if output else modes_path.with_name(f"reconstructed_rank{k}.npy")
|
|
456
|
+
if out_path.suffix != ".npy":
|
|
457
|
+
out_path = out_path.with_name(out_path.name + ".npy")
|
|
458
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
459
|
+
|
|
460
|
+
out = np.lib.format.open_memmap(out_path, mode="w+", dtype=np.float32, shape=(P, N))
|
|
461
|
+
for a, b in _bar(_chunks(N, chunk), "Reconstructing", "blk", progress):
|
|
462
|
+
block = M @ Cf[:, a:b] # (nx*ny, snapshots in block)
|
|
463
|
+
if mean is not None:
|
|
464
|
+
block += mean
|
|
465
|
+
out[:, a:b] = block
|
|
466
|
+
out.flush()
|
|
467
|
+
del out
|
|
468
|
+
print(f"Rank-{k} reconstructed with dimension ({P} x {N}, [nx*ny, nt]) saved to {out_path.resolve()}")
|
|
469
|
+
return out_path
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _energy(text):
|
|
473
|
+
v = float(text)
|
|
474
|
+
if not 0.0 < v < 1.0:
|
|
475
|
+
raise argparse.ArgumentTypeError("must be between 0 and 1")
|
|
476
|
+
return v
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
EXAMPLES = """examples:
|
|
480
|
+
python3 snap_pod.py save -i piv_data.npz -c U -o ./results -t 0.002 -m 6
|
|
481
|
+
python3 snap_pod.py save -i piv_data.npz -c U -o ./results -t 0.002 -m 6 --show # display plots while saving
|
|
482
|
+
python3 snap_pod.py save -i piv_data.npz -c V -o ./results -t 0.002 --order C
|
|
483
|
+
python3 snap_pod.py save -i piv_data.npz -c W -o ./results -t 0.002 --dim 120 80 # file without dim
|
|
484
|
+
python3 snap_pod.py preview -i piv_data.npz -c V -t 0.002
|
|
485
|
+
python3 snap_pod.py replot -p ./results/piv_data_20261202/U/POD_modes.npy -m 4 -o ./figures
|
|
486
|
+
python3 snap_pod.py reconstruct -p ./results/piv_data_20261202/U/POD_modes.npy -r 10
|
|
487
|
+
"""
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def main(argv=None):
|
|
491
|
+
parser = argparse.ArgumentParser(
|
|
492
|
+
prog="snap_pod.py",
|
|
493
|
+
description="Snapshot Proper Orthogonal Decomposition (method of snapshots) of velocity field",
|
|
494
|
+
epilog=EXAMPLES,
|
|
495
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
496
|
+
)
|
|
497
|
+
parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
|
|
498
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="{save,preview,replot,reconstruct}")
|
|
499
|
+
|
|
500
|
+
# options shared by every sub-command
|
|
501
|
+
base = argparse.ArgumentParser(add_help=False)
|
|
502
|
+
base.add_argument("--no-progress", action="store_true", help="Disable tqdm progress bars")
|
|
503
|
+
|
|
504
|
+
# options shared by the analysis sub-commands
|
|
505
|
+
analysis = argparse.ArgumentParser(add_help=False, parents=[base])
|
|
506
|
+
g = analysis.add_argument_group("analysis options")
|
|
507
|
+
g.add_argument("-i", "--input", "--input-dir", dest="input", required=True,
|
|
508
|
+
help="Input data file (.npz or .mat) with flattened U, V, W, Vmag "
|
|
509
|
+
"[nx*ny, nt] and dim [nx, ny]")
|
|
510
|
+
g.add_argument("-c", "--component", type=_component, default="U", metavar="{U,V,W,Vmag}",
|
|
511
|
+
help="Velocity component or magnitude to analyse (default: U)")
|
|
512
|
+
g.add_argument("-t", "--dt", type=float, required=True, help="Time step between snapshots [s]")
|
|
513
|
+
g.add_argument("-m", "--num-modes", type=int, default=4, help="Number of modes to plot (default: 4)")
|
|
514
|
+
g.add_argument("-e", "--energy", type=_energy, default=0.99,
|
|
515
|
+
help="Energy fraction defining the optimal rank (default: 0.99)")
|
|
516
|
+
g.add_argument("-d", "--dim", type=int, nargs=2, metavar=("NX", "NY"),
|
|
517
|
+
help="Grid size; needed only if the data file has no `dim` "
|
|
518
|
+
"(overrides the file's dim if both exist)")
|
|
519
|
+
g.add_argument("-ord", "--order", type=_order, default="C", metavar="{C,F}",
|
|
520
|
+
help="How each [nx, ny] field was flattened; only affects how modes are "
|
|
521
|
+
"folded back for plotting, not the POD. F = column-major (MATLAB U(:), "
|
|
522
|
+
"default), C = row-major (NumPy flatten)")
|
|
523
|
+
g.add_argument("-cb", "--cbar-limit", type=float, nargs=2, metavar=("VMIN", "VMAX"),
|
|
524
|
+
help="Colour-bar limits for modes (default: auto, symmetric per mode)")
|
|
525
|
+
|
|
526
|
+
p_save = sub.add_parser("save", parents=[analysis],
|
|
527
|
+
help="run the analysis and save all results to disk",
|
|
528
|
+
description="Run SnapshotPOD and save arrays, CSV files and figures.")
|
|
529
|
+
p_save.add_argument("-o", "--output-dir", required=True,
|
|
530
|
+
help="Output directory; the date is appended to its name and results "
|
|
531
|
+
"go to <output-dir>_<date>/<component> "
|
|
532
|
+
"(e.g. ./run01 -> ./run01_YYYYMMDD/U)")
|
|
533
|
+
p_save.add_argument("--dpi", type=int, default=300, help="Resolution of saved figures (default: 300)")
|
|
534
|
+
p_save.add_argument("--show", action="store_true", help="Also display the figures while saving")
|
|
535
|
+
|
|
536
|
+
sub.add_parser("preview", parents=[analysis],
|
|
537
|
+
help="run the analysis and only display figures (nothing saved)",
|
|
538
|
+
description="Run SnapshotPOD and display figures. No files are written.")
|
|
539
|
+
|
|
540
|
+
p_replot = sub.add_parser("replot", parents=[base],
|
|
541
|
+
help="re-plot modes from a saved POD_modes.npy",
|
|
542
|
+
description="Plot modes from a saved POD_modes.npy (nx*ny, K). The grid "
|
|
543
|
+
"size and flatten order are read from POD_info.npz next to it.")
|
|
544
|
+
p_replot.add_argument("-p", "--path", required=True, help="Path to POD_modes.npy")
|
|
545
|
+
p_replot.add_argument("-m", "--num-modes", type=int, help="Number of modes to plot")
|
|
546
|
+
p_replot.add_argument("-d", "--dim", type=int, nargs=2, metavar=("NX", "NY"),
|
|
547
|
+
help="Grid size (default: read from POD_info.npz)")
|
|
548
|
+
p_replot.add_argument("-ord", "--order", type=_order, default="C", metavar="{C, F}",
|
|
549
|
+
help="Flatten order (default: read from POD_info.npz)")
|
|
550
|
+
p_replot.add_argument("-cb", "--cbar-limit", type=float, nargs=2, metavar=("VMIN", "VMAX"),
|
|
551
|
+
help="Colour-bar limits (default: auto)")
|
|
552
|
+
p_replot.add_argument("-o", "--output-dir", help="Save figures here (otherwise display only)")
|
|
553
|
+
p_replot.add_argument("--dpi", type=int, default=300)
|
|
554
|
+
p_replot.add_argument("--show", action="store_true", help="Display figures even when saving")
|
|
555
|
+
|
|
556
|
+
p_rc = sub.add_parser("reconstruct", parents=[base],
|
|
557
|
+
help="rebuild the data from saved modes and coefficients",
|
|
558
|
+
description="Reconstruct X = mean + modes @ coefficients from the .npy "
|
|
559
|
+
"files written by `save`. The output has the same layout as "
|
|
560
|
+
"the input data: [nx*ny, nt].")
|
|
561
|
+
p_rc.add_argument("-p", "--modes-path", required=True, help="Path to POD_modes.npy")
|
|
562
|
+
p_rc.add_argument("-c", "--coeffs-path",
|
|
563
|
+
help="Path to POD_coefficients.npy (default: next to the modes file)")
|
|
564
|
+
p_rc.add_argument("-mu", "--mean-path", help="Path to POD_mean.npy (default: next to the modes file)")
|
|
565
|
+
p_rc.add_argument("--no-mean", action="store_true", help="Do not add the mean back")
|
|
566
|
+
p_rc.add_argument("-r", "--rank", type=int, help="Number of modes to use (default: all saved modes)")
|
|
567
|
+
p_rc.add_argument("-o", "--output", help="Output .npy file (default: reconstructed_rank<k>.npy "
|
|
568
|
+
"next to the modes file)")
|
|
569
|
+
p_rc.add_argument("-ch", "--chunk", type=int, default=32, help="Snapshots rebuilt per block (default: 32)")
|
|
570
|
+
|
|
571
|
+
args = parser.parse_args(argv)
|
|
572
|
+
progress = not args.no_progress
|
|
573
|
+
|
|
574
|
+
try:
|
|
575
|
+
if args.command == "reconstruct":
|
|
576
|
+
SnapshotPOD.reconstruct_from_files(
|
|
577
|
+
args.modes_path,
|
|
578
|
+
args.coeffs_path,
|
|
579
|
+
args.output,
|
|
580
|
+
args.mean_path,
|
|
581
|
+
use_mean=not args.no_mean,
|
|
582
|
+
rank=args.rank,
|
|
583
|
+
chunk=args.chunk,
|
|
584
|
+
progress=progress,
|
|
585
|
+
)
|
|
586
|
+
return
|
|
587
|
+
|
|
588
|
+
clim = tuple(args.cbar_limit) if args.cbar_limit else None
|
|
589
|
+
if args.command == "replot":
|
|
590
|
+
visualize = args.show or args.output_dir is None
|
|
591
|
+
elif args.command == "save":
|
|
592
|
+
visualize = args.show
|
|
593
|
+
else: # preview
|
|
594
|
+
visualize = True
|
|
595
|
+
if not visualize:
|
|
596
|
+
plt.switch_backend("Agg")
|
|
597
|
+
|
|
598
|
+
if args.command == "replot":
|
|
599
|
+
SnapshotPOD.plot_all_modes(
|
|
600
|
+
args.path,
|
|
601
|
+
args.output_dir,
|
|
602
|
+
args.num_modes,
|
|
603
|
+
clim,
|
|
604
|
+
visualize,
|
|
605
|
+
args.dpi,
|
|
606
|
+
progress,
|
|
607
|
+
dim=tuple(args.dim) if args.dim else None, order=args.order
|
|
608
|
+
)
|
|
609
|
+
else:
|
|
610
|
+
save = args.command == "save"
|
|
611
|
+
SnapshotPOD(
|
|
612
|
+
source=args.input,
|
|
613
|
+
dt=args.dt,
|
|
614
|
+
component=args.component,
|
|
615
|
+
num_modes=args.num_modes,
|
|
616
|
+
energy=args.energy,
|
|
617
|
+
order=args.order,
|
|
618
|
+
dim=tuple(args.dim) if args.dim else None,
|
|
619
|
+
clim=clim,
|
|
620
|
+
target_dir=args.output_dir if save else None,
|
|
621
|
+
visualize=visualize,
|
|
622
|
+
save_results=save,
|
|
623
|
+
dpi=args.dpi if save else 300,
|
|
624
|
+
progress=progress
|
|
625
|
+
).fit()
|
|
626
|
+
except (FileNotFoundError, ValueError, OSError) as exc:
|
|
627
|
+
parser.exit(1, f"error: {exc}\n")
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
if __name__ == "__main__":
|
|
631
|
+
main()
|