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/spod.py ADDED
@@ -0,0 +1,766 @@
1
+ """Spectral Proper Orthogonal Decomposition (SPOD) of time-resolved data.
2
+
3
+ Implements the SPOD-Welch algorithm of Schmidt & Colonius, "Guide to Spectral Proper
4
+ Orthogonal Decomposition", AIAA Journal 58(3), 2020 (equation numbers below refer to
5
+ that paper).
6
+
7
+ Input data
8
+ ----------
9
+ A .npz or .mat file holding the velocity components U, V, W (and/or Vmag) of a
10
+ time-resolved PIV measurement and, optionally, dim = [nx, ny]. Every component is a
11
+ matrix Q of shape [N, Nt]:
12
+
13
+ N = nx * ny flattened grid points (rows), the M degrees of freedom of the paper
14
+ Nt number of equally spaced time snapshots (columns), dt apart
15
+
16
+ so Q[:, k] is the field at snapshot k flattened in C order (row-major) by default, or
17
+ in F order (column-major, MATLAB U(:)) with --order F. `dim` and the order are only
18
+ used to fold the modes back into 2D (nx, ny) images.
19
+
20
+ Algorithm (Sec. III)
21
+ ----------------------------
22
+ 1. q' = q - mean_t(q) the data must be centred (fluctuations)
23
+ 2. Welch segmentation N_blk = floor((Nt - N_ovlp)/(N_FFT - N_ovlp))
24
+ block k holds snapshots [k (N_FFT - N_ovlp), k (N_FFT - N_ovlp) + N_FFT)
25
+ 3. window Hamming w(j) = 0.54 - 0.46 cos(2 pi j/(N_FFT-1))
26
+ correction a_w = N_FFT / sum(w)
27
+ 4. DFT in time of every block q^(k)(f_m) = (a_w / N_FFT) sum_j w_j q_j e^(-i2 pi jm/N_FFT)
28
+ f_m = m f_s / N_FFT, m = 0..N_FFT/2 (real data: only f >= 0), df = 1/(N_FFT dt)
29
+ 5. for every frequency: data matrix Q^ = [q^(1) ... q^(N_blk)] (N x N_blk)
30
+ sample CSD C^ = Q^ Q^H / (N_blk - 1)
31
+ (Welch's PSD divides by N_blk instead; --ddof 0 selects that, the eigenvalues are
32
+ then smaller by the factor (N_blk - 1)/N_blk, which matters for few blocks)
33
+ method of snapshots, since N >> N_blk:
34
+ (1/(N_blk-1)) Q^H W Q^ Psi = Psi Lambda, Phi = Q^ Psi
35
+ modes are scaled so that Phi^H W Phi = I
36
+ 6. 99 % confidence bounds of the eigenvalues (chi-squared, 2 N_blk dof)
37
+
38
+ Results (every figure is a separate file):
39
+ SPOD_spectrum.png energy lambda_k(f) of every mode, PSD (their sum), confidence bounds
40
+ SPOD_low_rank.png low-rank measure lambda_1/sum(lambda)
41
+ SPOD_mode<k>_f<f>Hz.png real part of mode k at frequency f, a 2D (nx, ny) image
42
+ SPOD_modes.npy, SPOD_spectrum.npz/.csv, SPOD_mean.npy, SPOD_info.npz
43
+
44
+ Sub-commands
45
+ ------------
46
+ save run the SPOD and WRITE all results (arrays, CSV, figures)
47
+ preview run the SPOD and only DISPLAY figures (nothing is written)
48
+ replot redraw the modes of a saved SPOD at chosen frequencies
49
+ """
50
+
51
+ from __future__ import annotations
52
+
53
+ import argparse
54
+ import shutil
55
+ import tempfile
56
+ from datetime import date
57
+ from pathlib import Path
58
+ from time import perf_counter
59
+
60
+ import matplotlib.pyplot as plt
61
+ import numpy as np
62
+ import scipy.fft as sfft
63
+ from scipy.signal import find_peaks
64
+ from scipy.signal import windows as swin
65
+ from scipy.stats import chi2
66
+
67
+ from ._common import COMPONENTS, FONT, __version__, read_component
68
+ from ._common import bar as _bar
69
+ from ._common import check_dim as _check_dim
70
+ from ._common import component_type as _component
71
+ from ._common import order_type as _order
72
+ from ._common import save_figs as _save_figs
73
+ from ._common import unflatten as _unflatten
74
+
75
+ __all__ = ["SpectralPOD", "SPOD"]
76
+
77
+ WINDOWS = ("hamming", "hann", "rect")
78
+
79
+
80
+ def _make_window(name, nfft):
81
+ """Window of Eq. (29) (symmetric, denominator N_FFT - 1) and its correction factors."""
82
+ if name == "hamming":
83
+ w = swin.hamming(nfft, sym=True) # 0.54 - 0.46 cos(2 pi j/(N_FFT-1))
84
+ elif name == "hann":
85
+ w = swin.hann(nfft, sym=True)
86
+ elif name == "rect":
87
+ w = np.ones(nfft)
88
+ else:
89
+ raise ValueError(f"window must be one of {WINDOWS}")
90
+ a_amp = nfft / w.sum()
91
+ a_energy = np.sqrt(nfft / np.sum(w ** 2)) # energy-preserving alternative
92
+ return w, a_amp, a_energy
93
+
94
+
95
+ def _auto_nfft(nt):
96
+ """Largest power of two <= Nt/16 (>= 8): many blocks, power of 2 for the FFT."""
97
+ n = 8
98
+ while 2 * n <= nt // 16:
99
+ n *= 2
100
+ return min(n, nt)
101
+
102
+
103
+ def _select_peaks(freq, lam1, n_peaks=3):
104
+ """Indices of the strongest peaks of the leading-mode spectrum (f > 0).
105
+
106
+ A peak must stand out by a factor of ~3 (prominence 0.5 in log10) above its
107
+ surroundings, which skips the small ripples of a broadband spectrum.
108
+ """
109
+ if len(freq) < 2:
110
+ return [0]
111
+ body = np.maximum(lam1[1:], 1e-300)
112
+ pk, _ = find_peaks(np.log10(body), prominence=0.5)
113
+ if len(pk) == 0:
114
+ pk = np.array([int(np.argmax(body))])
115
+ pk = pk[np.argsort(-body[pk])][:n_peaks] + 1
116
+ return sorted(int(i) for i in pk)
117
+
118
+
119
+ class SpectralPOD:
120
+ """Spectral POD of one velocity component with Welch's method.
121
+
122
+ Args:
123
+ source (str): .npz or .mat file with U, V, W, Vmag, each [N, Nt] (N = nx*ny rows,
124
+ Nt snapshots as columns)
125
+ dt (float): Time step between snapshots [s]
126
+ component (str): One of "U", "V", "W", "Vmag"
127
+ nfft (int): Snapshots per block N_FFT (default: largest power of two <= Nt/16)
128
+ novlp (int): Overlapping snapshots N_ovlp (default: N_FFT/2, i.e. 50 %)
129
+ window (str): "hamming" (default), "hann" or "rect"
130
+ correction (str): "amplitude" a_w = N_FFT/sum(w) (paper, Eq. 30) or "energy"
131
+ a_w = sqrt(N_FFT/sum(w^2)), which makes the eigenvalues sum to the variance
132
+ num_modes (int): Number of modes per frequency that are stored and plotted
133
+ confidence (float): Confidence level of the eigenvalue bounds, e.g. 0.99
134
+ ddof (int): CSD normalisation 1/(N_blk - ddof): 1 is Eq. (21) of the paper (default),
135
+ 0 is the 1/N_blk of Welch's PSD estimate
136
+ dx, dy (float): Grid spacing; the weight of every point is the cell area dx*dy
137
+ (weighted 2-norm, Sec. III.B). 1 x 1 gives the plain variance norm W = I
138
+ weights (str): Optional .npy file with the cell areas, [N] or [nx, ny]; overrides dx, dy
139
+ dim (tuple): Grid size (nx, ny); the file's `dim` is used if this is None
140
+ order (str): Flatten order of each field: "C" row-major (default) or "F" (MATLAB)
141
+ plot_freqs (list): Frequencies [Hz] whose modes are drawn (default: spectral peaks)
142
+ memory_limit (float): If the Fourier realizations exceed this size [GB] they are
143
+ kept on disk and read back frequency by frequency (Sec. III.C.4)
144
+ target_dir (str): Output directory (required when save_results). Results go to
145
+ <target_dir>/<filename>_<YYYYMMDD>/<component>, <filename> = stem of the input
146
+ visualize (bool): Display figures interactively
147
+ save_results (bool): Write arrays, CSV and figures
148
+ dpi (int): Resolution of saved figures
149
+ progress (bool): Show tqdm progress bars
150
+ """
151
+
152
+ def __init__(self,
153
+ source,
154
+ dt,
155
+ component="U",
156
+ nfft=None,
157
+ novlp=None,
158
+ window="hamming",
159
+ correction="amplitude",
160
+ num_modes=4,
161
+ confidence=0.99,
162
+ ddof=1,
163
+ dx=1.0,
164
+ dy=1.0,
165
+ weights=None,
166
+ dim=None,
167
+ order="C",
168
+ plot_freqs=None,
169
+ memory_limit=4.0,
170
+ target_dir=None,
171
+ visualize=False,
172
+ save_results=False,
173
+ dpi=300,
174
+ progress=True):
175
+
176
+ if component not in COMPONENTS:
177
+ raise ValueError(f"component must be one of {COMPONENTS}")
178
+ if dt <= 0:
179
+ raise ValueError("dt must be > 0")
180
+ if nfft is not None and nfft < 2:
181
+ raise ValueError("nfft must be >= 2")
182
+ if novlp is not None and novlp < 0:
183
+ raise ValueError("novlp must be >= 0")
184
+ if window not in WINDOWS:
185
+ raise ValueError(f"window must be one of {WINDOWS}")
186
+ if correction not in ("amplitude", "energy"):
187
+ raise ValueError("correction must be 'amplitude' or 'energy'")
188
+ if num_modes < 1:
189
+ raise ValueError("num_modes must be >= 1")
190
+ if not 0.0 < confidence < 1.0:
191
+ raise ValueError("confidence must be between 0 and 1")
192
+ if ddof not in (0, 1):
193
+ raise ValueError("ddof must be 0 or 1")
194
+ if dx <= 0 or dy <= 0:
195
+ raise ValueError("dx and dy must be > 0")
196
+ if order not in ("C", "F"):
197
+ raise ValueError("order must be 'C' or 'F'")
198
+ if memory_limit <= 0:
199
+ raise ValueError("memory_limit must be > 0")
200
+ if dpi < 1:
201
+ raise ValueError("dpi must be >= 1")
202
+ if save_results and target_dir is None:
203
+ raise ValueError("target_dir is required when saving results")
204
+
205
+ self.source = Path(source)
206
+ if not self.source.is_file():
207
+ raise FileNotFoundError(f"Input file not found: {self.source}")
208
+
209
+ if self.source.suffix.lower() not in (".npz", ".mat"):
210
+ raise ValueError("Input must be a .npz or .mat file")
211
+
212
+ self.weights_path = Path(weights) if weights is not None else None
213
+ if self.weights_path is not None and not self.weights_path.is_file():
214
+ raise FileNotFoundError(f"Weights file not found: {self.weights_path}")
215
+
216
+ self.component = component
217
+ self.dt = dt
218
+ self.nfft_arg = nfft
219
+ self.novlp_arg = novlp
220
+ self.window_name = window
221
+ self.correction = correction
222
+ self.num_modes = num_modes
223
+ self.confidence = confidence
224
+ self.ddof = ddof
225
+ self.dx = dx
226
+ self.dy = dy
227
+ self._dim_arg = _check_dim(dim) if dim is not None else None
228
+ self.order = order
229
+ self.plot_freqs = None if plot_freqs is None else [float(f) for f in plot_freqs]
230
+ self.memory_limit = float(memory_limit)
231
+ self.visualize = visualize
232
+ self.save_results = save_results
233
+ self.dpi = dpi
234
+ self.progress = progress
235
+
236
+ self.out_dir = None
237
+ if save_results:
238
+ self.out_dir = Path(target_dir) / f"{self.source.stem}_{date.today():%Y%m%d}/{component}"
239
+
240
+ # filled by compute()
241
+ self.dim = self.n_points = self.nt = None
242
+ self.nfft = self.novlp = self.nblk = self.nf = None
243
+ self.freq = self.window = self.a_w = self.weights = self.mean = None
244
+ self.lam = self.lam_lo = self.lam_hi = self.modes = None
245
+ self.parseval = None
246
+
247
+ def _pbar(self, iterable, desc, unit="it"):
248
+ return _bar(iterable, desc, unit, self.progress)
249
+
250
+ def load_data(self):
251
+ """Load the selected component as a float32 matrix of shape [N, Nt]."""
252
+ print(f"Loading '{self.component}' from {self.source.name} ...")
253
+ arr, file_dim = read_component(self.source, self.component)
254
+
255
+ arr = np.squeeze(np.asarray(arr))
256
+ if arr.dtype.kind not in "fiu":
257
+ raise ValueError(f"Velocity data must be numeric, got dtype {arr.dtype}")
258
+ if arr.ndim != 2:
259
+ raise ValueError(f"Expected a matrix of shape [N, Nt] with N = nx*ny grid points "
260
+ f"(rows) and Nt time snapshots (columns), got {arr.shape}")
261
+ N, nt = arr.shape
262
+
263
+ fdim = _check_dim(file_dim) if file_dim is not None else None
264
+ if self._dim_arg is not None:
265
+ self.dim = self._dim_arg
266
+ if fdim is not None and fdim != self.dim:
267
+ print(f"Warning: --dim {list(self.dim)} overrides dim {list(fdim)} in the file.")
268
+ else:
269
+ self.dim = fdim
270
+ if self.dim is not None and self.dim[0] * self.dim[1] != N:
271
+ raise ValueError(f"dim {list(self.dim)} does not match the N = {N} rows of the data "
272
+ f"(shape {arr.shape}); the data must be [N, Nt] with N = nx*ny")
273
+ if self.dim is None:
274
+ print("No grid size (dim) available: modes will be drawn as 1D profiles.")
275
+
276
+ if self.dim is None and N < nt:
277
+ print(f"Note: the input must be [N, Nt] with N = nx*ny grid points in rows and Nt time "
278
+ f"snapshots in columns; here N = {N} and Nt = {nt}.")
279
+ self.n_points = N
280
+ self.nt = nt
281
+ return np.asarray(arr, dtype=np.float32)
282
+
283
+ def _make_weights(self, n_points):
284
+ """Weight of every grid point (cell area): the diagonal of W in Sec. III.B."""
285
+ if self.weights_path is None:
286
+ return np.full(n_points, self.dx * self.dy)
287
+
288
+ w = np.load(self.weights_path)
289
+ if w.ndim == 2:
290
+ if self.dim is None or w.shape != tuple(self.dim):
291
+ raise ValueError(f"A 2D weights file must have shape (nx, ny) = {self.dim}, "
292
+ f"got {w.shape}")
293
+ w = w.reshape(-1, order=self.order)
294
+ if w.ndim != 1 or w.size != n_points:
295
+ raise ValueError(f"Weights must have {n_points} values, got shape {w.shape}")
296
+ w = w.astype(np.float64)
297
+ if not (np.all(np.isfinite(w)) and np.all(w > 0)):
298
+ raise ValueError("Weights must be positive and finite")
299
+ return w
300
+
301
+ def _resolve_parameters(self, nt):
302
+ """Welch parameters N_FFT, N_ovlp and the number of blocks, Eq. (28)."""
303
+ nfft = self.nfft_arg if self.nfft_arg is not None else _auto_nfft(nt)
304
+ if nfft > nt:
305
+ raise ValueError(f"nfft = {nfft} is larger than the number of snapshots Nt = {nt}")
306
+
307
+ novlp = self.novlp_arg if self.novlp_arg is not None else nfft // 2
308
+ if novlp >= nfft:
309
+ raise ValueError(f"novlp = {novlp} must be smaller than nfft = {nfft}")
310
+
311
+ nblk = (nt - novlp) // (nfft - novlp)
312
+ if nblk < 2:
313
+ raise ValueError(f"Only {nblk} block(s) with nfft = {nfft}, novlp = {novlp} and "
314
+ f"Nt = {nt}; at least 2 are needed. Use a smaller nfft.")
315
+
316
+ self.nfft = nfft
317
+ self.novlp = novlp
318
+ self.nblk = nblk
319
+ self.nf = nfft // 2 + 1
320
+ self.freq = sfft.rfftfreq(nfft, d=self.dt)
321
+
322
+ def compute(self):
323
+ """SPOD-Welch: blocks -> windowed DFT -> CSD by the method of snapshots, per frequency."""
324
+ arr = self.load_data()
325
+ M, nt = arr.shape
326
+ self._resolve_parameters(nt)
327
+ self.weights = w = self._make_weights(M)
328
+ nfft, novlp, nblk, nf = self.nfft, self.novlp, self.nblk, self.nf
329
+ nm = min(self.num_modes, nblk)
330
+
331
+ # window and its correction factor
332
+ win, a_amp, a_energy = _make_window(self.window_name, nfft)
333
+ self.window = win
334
+ self.a_w = a_amp if self.correction == "amplitude" else a_energy
335
+ print(f"\nWelch parameters: Nt = {nt}, N_FFT = {nfft}, N_ovlp = {novlp} "
336
+ f"({100 * novlp / nfft:.0f} %), Number of blocks = {nblk}")
337
+ print(f"fs = {1 / self.dt:.6g} Hz, f_max = {0.5 / self.dt:.6g} Hz, "
338
+ f"T_block = {nfft * self.dt:.6g} s, df = {1 / (nfft * self.dt):.6g} Hz, "
339
+ f"{nf} frequencies")
340
+ print(f"window = {self.window_name}, a_w = {self.a_w:.4f} ({self.correction} correction), "
341
+ f"{M} grid points, {nm} modes kept per frequency\n")
342
+
343
+ # Center the data (fluctuations); time-major copy so that blocks are contiguous
344
+ has_nan = bool(np.isnan(arr).any())
345
+ if has_nan:
346
+ print("Warning: NaNs found in the data; they are set to zero after mean removal.")
347
+ with np.errstate(all="ignore"):
348
+ mean = np.nan_to_num(np.nanmean(arr, axis=1, dtype=np.float64))
349
+ else:
350
+ mean = arr.mean(axis=1, dtype=np.float32)
351
+ self.mean = mean
352
+ Q = np.ascontiguousarray(arr.T) # (Nt, N)
353
+ del arr
354
+ Q -= self.mean
355
+ if has_nan:
356
+ np.nan_to_num(Q, copy=False)
357
+
358
+ # total variance <q, q> = mean_t q^T W q, used as a Parseval check
359
+ var = 0.0
360
+ for lo in range(0, nt, 64):
361
+ var += float(((Q[lo:lo + 64].astype(np.float64) ** 2) @ w).sum())
362
+ var /= nt
363
+
364
+ # Welch blocks and their windowed Fourier transforms
365
+ size_gb = nblk * nf * M * 8 / 1e9
366
+ tmp = None
367
+ if size_gb > self.memory_limit:
368
+ tmp = Path(tempfile.mkdtemp(prefix="spod_"))
369
+ print(f"Fourier realizations need {size_gb:.2f} GB (> {self.memory_limit:g} GB): "
370
+ f"storing them on disk ({tmp}) and reading them frequency by frequency.")
371
+ Qhat = np.lib.format.open_memmap(tmp / "Qhat.npy", mode="w+",
372
+ dtype=np.complex64, shape=(nblk, nf, M))
373
+ else:
374
+ Qhat = np.empty((nblk, nf, M), dtype=np.complex64)
375
+ try:
376
+ step = nfft - novlp
377
+ win = win.astype(np.float32)[:, None]
378
+ scale = self.a_w / nfft
379
+ for k in self._pbar(range(nblk), "Fourier transform of blocks", "blk"):
380
+ blk = Q[k * step:k * step + nfft] * win # (N_FFT, N)
381
+ Qhat[k] = (sfft.rfft(blk, axis=0) * scale).astype(np.complex64)
382
+ del Q
383
+
384
+ # compute SPOD one frequency at a time
385
+ fold = np.ones(nf) # real data: negative frequencies are
386
+ fold[1:] = 2.0 # folded onto the positive ones
387
+ if nfft % 2 == 0:
388
+ fold[-1] = 1.0 # Nyquist bin is not doubled
389
+ lam = np.zeros((nf, nblk))
390
+ modes = np.zeros((nf, M, nm), dtype=np.complex64)
391
+ w = w.astype(np.float32)
392
+ dn = nblk - self.ddof
393
+ for j in self._pbar(range(nf), "SPOD, one frequency at a time", "freq"):
394
+ A = np.asarray(Qhat[:, j, :]) # (N_blk, N), rows = q^(k)
395
+ K = ((A.conj() * w) @ A.T) / dn # Q^H W Q^ / (N_blk - ddof)
396
+ ev, psi = np.linalg.eigh(K.astype(np.complex128)) # Hermitian eigenproblem
397
+ ev = np.clip(ev[::-1], 0.0, None)
398
+ psi = psi[:, ::-1]
399
+ lam[j] = ev * fold[j]
400
+ good = ev[:nm] > 1e-14 * max(ev[0], np.finfo(float).tiny)
401
+ phi = psi[:, :nm].T.astype(np.complex64) @ A # (nm, N): Phi = Q^ Psi
402
+ norm = np.sqrt(dn * np.where(good, ev[:nm], 1.0))
403
+ phi = phi / norm[:, None].astype(np.float32) # Phi^H W Phi = I
404
+ phi[~good] = 0.0
405
+ # eigenvectors are defined up to a phase: largest element real and positive
406
+ kmax = np.argmax(np.abs(phi), axis=1)
407
+ ph = phi[np.arange(nm), kmax]
408
+ ph = np.where(np.abs(ph) > 0, ph / np.maximum(np.abs(ph), 1e-30), 1.0)
409
+ modes[j] = (phi / ph[:, None]).T
410
+ finally:
411
+ if tmp is not None:
412
+ del Qhat
413
+ shutil.rmtree(tmp, ignore_errors=True)
414
+
415
+ self.lam, self.modes = lam, modes
416
+
417
+ # confidence bounds of the eigenvalues
418
+ alpha = 1.0 - self.confidence
419
+ dof = 2 * nblk
420
+ self.lam_lo = dof * lam / chi2.ppf(1.0 - alpha / 2.0, dof)
421
+ self.lam_hi = dof * lam / chi2.ppf(alpha / 2.0, dof)
422
+ self.parseval = float(lam.sum() / var) if var > 0 else np.nan
423
+ print(f"\nSum of all eigenvalues / total variance = {self.parseval:.3f} "
424
+ f"(1 would be an exact Parseval balance; with the amplitude correction a_w the "
425
+ f"expected value is the window's noise bandwidth: "
426
+ f"{nfft * np.sum(win ** 2) / np.sum(win) ** 2:.3f})")
427
+
428
+ if self.save_results:
429
+ self.out_dir.mkdir(parents=True, exist_ok=True)
430
+ self._save_results()
431
+
432
+ def _save_results(self):
433
+ out, nm = self.out_dir, self.modes.shape[2]
434
+ np.save(out / "SPOD_modes.npy", self.modes) # (n_freq, N, n_modes)
435
+ np.save(out / "SPOD_mean.npy", self.mean) # (N,)
436
+ np.savez(out / "SPOD_spectrum.npz", frequency=self.freq, eigenvalues=self.lam,
437
+ eigenvalues_lower=self.lam_lo, eigenvalues_upper=self.lam_hi,
438
+ weights=self.weights)
439
+ np.savez(out / "SPOD_info.npz",
440
+ dim=np.array(self.dim if self.dim is not None else (0, 0)),
441
+ order=self.order, dt=self.dt, component=self.component, nfft=self.nfft,
442
+ novlp=self.novlp, nblk=self.nblk, window=self.window_name,
443
+ correction=self.correction, a_w=self.a_w, confidence=self.confidence,
444
+ ddof=self.ddof,
445
+ num_snapshots=self.nt, num_points=self.n_points, num_modes=nm)
446
+
447
+ total = self.lam.sum(axis=1)
448
+ table = np.column_stack([self.freq, self.lam[:, :nm], total, self.lam_lo[:, 0],
449
+ self.lam_hi[:, 0], self.lam[:, 0] / np.maximum(total, 1e-300)])
450
+ head = ("frequency_Hz," + ",".join(f"lambda_{i + 1}" for i in range(nm))
451
+ + ",lambda_total,lambda_1_lower,lambda_1_upper,lambda_1_over_total")
452
+ np.savetxt(out / "SPOD_spectrum.csv", table, delimiter=",", fmt="%.8g", header=head, comments="")
453
+
454
+ def _path(self, name):
455
+ return None if self.out_dir is None else self.out_dir / name
456
+
457
+ def _mode_frequencies(self):
458
+ """Indices of the frequency bins whose modes are drawn."""
459
+ if self.plot_freqs:
460
+ return sorted({int(np.argmin(np.abs(self.freq - f))) for f in self.plot_freqs})
461
+ return _select_peaks(self.freq, self.lam[:, 0])
462
+
463
+ def plot_spectrum(self, marks):
464
+ """SPOD energy spectrum and, as a separate figure, the low-rank measure."""
465
+ f, lam = self.freq[1:], self.lam[1:]
466
+ nm = self.lam.shape[1]
467
+ total = lam.sum(axis=1)
468
+
469
+ # SPOD_spectrum.png: energy of every mode, confidence bounds of mode 1, PSD
470
+ fig, ax = plt.subplots(figsize=(9, 6))
471
+ for i in range(1, nm):
472
+ ax.loglog(f, np.maximum(lam[:, i], 1e-300), color="0.7", lw=0.8)
473
+ ax.fill_between(f, np.maximum(self.lam_lo[1:, 0], 1e-300),
474
+ np.maximum(self.lam_hi[1:, 0], 1e-300), color="tab:blue", alpha=0.25,
475
+ label=f"{100 * self.confidence:g} % confidence (mode 1)")
476
+ ax.loglog(f, np.maximum(lam[:, 0], 1e-300), color="tab:blue", lw=1.8, label="mode 1")
477
+ ax.loglog(f, np.maximum(total, 1e-300), color="tab:red", lw=1.2, label="PSD (sum of modes)")
478
+ for j in marks:
479
+ ax.axvline(self.freq[j], color="k", ls=":", lw=0.8)
480
+ ax.set_xlabel("Frequency [Hz]", fontdict=FONT)
481
+ ax.set_ylabel("SPOD mode energy", fontdict=FONT)
482
+ ax.set_title(f"SPOD spectrum (N_FFT = {self.nfft}, N_blk = {self.nblk})")
483
+ ax.legend()
484
+ fig.tight_layout()
485
+ _save_figs(fig, self._path("SPOD_spectrum.png"), self.dpi, self.visualize)
486
+
487
+ # SPOD_low_rank.png: lambda_1 / sum(lambda), the low-rank measure, with the peak
488
+ # frequencies and the sampling frequency f_s and its Nyquist limit f_max = f_s/2
489
+ fs, fmax = 1.0 / self.dt, 0.5 / self.dt
490
+ ratio = lam[:, 0] / np.maximum(total, 1e-300)
491
+
492
+ fig, ax = plt.subplots(figsize=(9, 6))
493
+ ax.semilogx(f, ratio, color="tab:green")
494
+ for j in marks:
495
+ ax.axvline(self.freq[j], color="k", ls=":", lw=0.9)
496
+ ax.plot(self.freq[j], self.lam[j, 0] / max(self.lam[j].sum(), 1e-300), "o", color="k", ms=4)
497
+ ax.annotate(f"{self.freq[j]:.4g} Hz", xy=(self.freq[j], 0.4),
498
+ xycoords=("data", "axes fraction"), xytext=(-3, -4),
499
+ textcoords="offset points", rotation=90, ha="right", va="top",
500
+ fontsize=9)
501
+ for fx, name in ((fmax, r"$f_{max}$"), (fs, r"$f_s$")): # Nyquist and sampling frequency
502
+ ax.axvline(fx, color="tab:red", ls="--", lw=1.0)
503
+ ax.annotate(f"{name} = {fx:.4g} Hz", xy=(fx, 0.1), xycoords=("data", "axes fraction"),
504
+ xytext=(-3, 6), textcoords="offset points", rotation=90, ha="right",
505
+ va="bottom", fontsize=9, color="tab:red")
506
+ ax.set_xlim(f[0] / 1.15, fs * 1.25)
507
+ ax.set_ylim(0, 1.02)
508
+ ax.set_xlabel("Frequency [Hz]", fontdict=FONT)
509
+ ax.set_ylabel(r"$\lambda_1/\sum\lambda$", fontdict=FONT)
510
+ fig.tight_layout()
511
+ _save_figs(fig, self._path("SPOD_low_rank.png"), self.dpi, self.visualize)
512
+
513
+ def plot_modes(self, marks):
514
+ """Real part of every stored mode at the chosen frequencies, one figure per mode."""
515
+ nm = self.modes.shape[2]
516
+ jobs = [(j, k) for j in marks for k in range(nm)]
517
+ for j, k in self._pbar(jobs, "Plotting SPOD modes", "mode"):
518
+ _draw_mode(self.modes[j][:, k], self.dim,self.order,
519
+ self._path(f"SPOD_mode{k + 1}_f{self.freq[j]:.4g}Hz.png"),
520
+ self.dpi, self.visualize)
521
+
522
+ def fit(self):
523
+ t0 = perf_counter()
524
+ print(f"\nSpectral POD of {self.component} ... \n")
525
+
526
+ self.compute()
527
+ freqs = self._mode_frequencies()
528
+ print("\nStrongest peaks / selected frequencies of the leading mode:")
529
+ print(" f [Hz] lambda_1 lambda_2 lambda_1/sum")
530
+ for j in freqs:
531
+ tot = self.lam[j].sum()
532
+ l2 = self.lam[j, 1] if self.lam.shape[1] > 1 else 0.0
533
+ print(f"{self.freq[j]:9.5g} {self.lam[j, 0]:12.5g} {l2:11.5g} "
534
+ f"{self.lam[j, 0] / max(tot, 1e-300):12.3f}\n")
535
+
536
+ self.plot_spectrum(freqs)
537
+ self.plot_modes(freqs)
538
+ msg = f"\nCompleted in {(perf_counter() - t0) / 60:.1f} mins"
539
+ if self.out_dir is not None:
540
+ msg += (f" and results saved in {self.out_dir.resolve()}"
541
+ f"\nUse the `replot` sub-command to draw the modes at other frequencies.")
542
+ print(msg)
543
+
544
+ @staticmethod
545
+ def replot(spod_dir, freqs=None, num_modes=None, output_dir=None, visualize=False, dpi=300, progress=True):
546
+ """Draw the modes of a saved SPOD at the bins nearest to `freqs` [Hz].
547
+
548
+ Without `freqs` the strongest peaks of the leading-mode spectrum are used.
549
+ """
550
+ d = Path(spod_dir)
551
+ for name in ("SPOD_modes.npy", "SPOD_spectrum.npz", "SPOD_info.npz"):
552
+ if not (d / name).is_file():
553
+ raise FileNotFoundError(f"{name} not found in {d}")
554
+
555
+ if num_modes is not None and num_modes < 1:
556
+ raise ValueError("num_modes must be >= 1")
557
+ modes = np.load(d / "SPOD_modes.npy", mmap_mode="r")
558
+
559
+ with np.load(d / "SPOD_spectrum.npz") as spec:
560
+ freq, lam = spec["frequency"], spec["eigenvalues"]
561
+
562
+ with np.load(d / "SPOD_info.npz") as info:
563
+ dim = tuple(int(v) for v in info["dim"])
564
+ order, _component = str(info["order"]), str(info["component"])
565
+ dim = None if min(dim) < 1 else dim
566
+
567
+ if freqs:
568
+ marks = sorted({int(np.argmin(np.abs(freq - f))) for f in freqs})
569
+ else:
570
+ marks = _select_peaks(freq, lam[:, 0])
571
+ nm = modes.shape[2] if num_modes is None else min(num_modes, modes.shape[2])
572
+
573
+ if output_dir is not None:
574
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
575
+
576
+ jobs = [(j, k) for j in marks for k in range(nm)]
577
+ for j, k in _bar(jobs, "Plotting SPOD modes", "mode", progress):
578
+ phi = np.asarray(modes[j][:, k])
579
+ if output_dir is None:
580
+ out = None
581
+ else:
582
+ stem = f"SPOD_mode{k + 1}_f_{freq[j]:.4g}Hz"
583
+ output_path = Path(output_dir)
584
+ out = output_path / f"{stem}.png"
585
+ # Preserve the full complex mode, not just the real part shown in the plot.
586
+ mode = phi if dim is None else _unflatten(phi[None, :], dim, order)[0]
587
+ np.save(output_path / f"{stem}.npy", mode)
588
+ _draw_mode(phi, dim, order, out, dpi, visualize)
589
+
590
+
591
+ SPOD = SpectralPOD
592
+
593
+
594
+ def _draw_mode(phi, dim, order, path, dpi, visualize):
595
+ """One figure: real part of one mode phi ([N] vector) at frequency f, as a (nx, ny) image."""
596
+ fig, ax = plt.subplots(figsize=(5, 4))
597
+ if dim is None:
598
+ ax.plot(phi.real)
599
+ ax.set_xlabel("Spatial index")
600
+ else:
601
+ field = _unflatten(phi.real[None, :], dim, order)[0]
602
+ assert field.shape == tuple(dim)
603
+ v = float(np.max(np.abs(field))) or 1.0
604
+ im = ax.imshow(field, cmap="jet", vmin=-v, vmax=v, interpolation="bicubic")
605
+ fig.colorbar(im, ax=ax, fraction=0.04)
606
+ ax.axis("off")
607
+ fig.tight_layout()
608
+ _save_figs(fig, path, dpi, visualize)
609
+
610
+
611
+ EXAMPLES = """examples:
612
+ python spod.py save -i data.npz -c U -o ./results -t 0.001 --nfft 256
613
+ python spod.py save -i data.mat -c V -o ./results -t 0.001 --order F --dx 0.002 --dy 0.002
614
+ python spod.py preview -i data.npz -c U -t 0.001 --nfft 256 --novlp 128 --window hann
615
+ python spod.py replot -p ./results/data_20261129/U --freqs 1.59 0.238 -m 2
616
+ python spod.py replot -p ./results/data_20261129/U --freqs 1.59 0.238 -m 2 -o /modes_selected
617
+ """
618
+
619
+
620
+ def main(argv=None):
621
+ parser = argparse.ArgumentParser(
622
+ prog="spod.py",
623
+ description="Spectral POD (SPOD, Welch's method) of time-resolved data [N, Nt]: "
624
+ "energy spectrum and modes",
625
+ epilog=EXAMPLES,
626
+ formatter_class=argparse.RawDescriptionHelpFormatter,
627
+ )
628
+ parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
629
+ sub = parser.add_subparsers(dest="command", required=True, metavar="{save,preview,replot}")
630
+
631
+ base = argparse.ArgumentParser(add_help=False)
632
+ base.add_argument("--no-progress", action="store_true", help="Disable tqdm progress bars")
633
+
634
+ analysis = argparse.ArgumentParser(add_help=False, parents=[base])
635
+
636
+ g = analysis.add_argument_group("data")
637
+ g.add_argument("-i", "--input", required=True,
638
+ help="Input data file (.npz or .mat) with U, V, W, Vmag, each of shape [N, Nt]: "
639
+ "N = nx*ny flattened grid points in rows, Nt time snapshots in columns")
640
+ g.add_argument("-c", "--component", type=_component, default="U", metavar="{U,V,W,Vmag}",
641
+ help="Velocity component to analyse (default: U)")
642
+ g.add_argument("-t", "--dt", type=float, required=True,
643
+ help="Time step between snapshots [s]; the sampling frequency is 1/dt")
644
+ g.add_argument("--dim", type=int, nargs=2, metavar=("NX", "NY"),
645
+ help="Grid size, to draw modes as 2D (nx, ny) images (default: `dim` from "
646
+ "the file; without it modes are drawn as 1D profiles)")
647
+ g.add_argument("--order", type=_order, default="C", metavar="{C,F}",
648
+ help="Order in which each [nx, ny] field was flattened into a column: "
649
+ "C = row-major (NumPy, default), F = column-major (MATLAB)")
650
+
651
+ s = analysis.add_argument_group("spectral estimation (Welch's method)")
652
+ s.add_argument("--nfft", type=int,
653
+ help="Snapshots per block, N_FFT; sets df = 1/(N_FFT dt). A power of 2 is "
654
+ "advisable (default: largest power of 2 <= Nt/16)")
655
+ s.add_argument("--novlp", type=int,
656
+ help="Overlapping snapshots between blocks, N_ovlp (default: N_FFT/2 = 50 %%)")
657
+ s.add_argument("-win", "--window", choices=WINDOWS, default="hamming",
658
+ help="Window applied to every block (default: hamming, Eq. 29), `hann`, or `rect`")
659
+ s.add_argument("--window-correction", dest="correction", choices=("amplitude", "energy"),
660
+ default="amplitude", type=str,
661
+ help="amplitude: a_w = N_FFT/sum(w) (Eq. 30, default); energy: "
662
+ "a_w = sqrt(N_FFT/sum(w^2)), so that the eigenvalues sum to the variance")
663
+ s.add_argument("--ddof", type=int, choices=(0, 1), default=1,
664
+ help="CSD normalisation 1/(N_blk - ddof): 1 = Eq. (21) of the paper (default), "
665
+ "0 = 1/N_blk as in Welch's PSD")
666
+ s.add_argument("--confidence", type=float, default=0.99,
667
+ help="Confidence level of the eigenvalue bounds, Eq. (31) (default: 0.99)")
668
+
669
+ n = analysis.add_argument_group("norm (weight matrix W) and output")
670
+ n.add_argument("--dx", type=float, default=1.0, help="Grid spacing in x (default: 1)")
671
+ n.add_argument("--dy", type=float, default=1.0,
672
+ help="Grid spacing in y; the weight of each point is the cell area dx*dy "
673
+ "(default 1 x 1: plain variance norm W = I)")
674
+ n.add_argument("--weights",
675
+ help=".npy file with the cell area of every grid point, [N] or [nx, ny] "
676
+ "(non-uniform grids); overrides --dx/--dy")
677
+ n.add_argument("-m", "--num-modes", type=int, default=5,
678
+ help="Number of modes per frequency that are stored and plotted (default: 4)")
679
+ n.add_argument("--plot-freqs", type=float, nargs="+", metavar="F",
680
+ help="Frequencies [Hz] whose modes are drawn (default: the strongest "
681
+ "peaks of the leading-mode spectrum)")
682
+ n.add_argument("--memory-limit", type=float, default=4.0,
683
+ help="Fourier realizations larger than this [GB] are kept on disk and read "
684
+ "back frequency by frequency (default: 4)")
685
+
686
+ p_save = sub.add_parser("save", parents=[analysis], help="run the SPOD and save all results",
687
+ description="Run SPOD and save arrays, CSV and figures.")
688
+ p_save.add_argument("-o", "--output-dir", required=True,
689
+ help="Output directory; results go to "
690
+ "<output-dir>/<input-file-stem>_<YYYYMMDD>/<component>")
691
+ p_save.add_argument("--dpi", type=int, default=300,
692
+ help="Resolution of saved figures (default: 300)")
693
+ p_save.add_argument("--show", action="store_true",
694
+ help="Also display the figures while saving")
695
+
696
+ sub.add_parser("preview", parents=[analysis],
697
+ help="run the SPOD and only display figures (nothing saved)",
698
+ description="Run SPOD and display figures. No files are written.")
699
+
700
+ p_re = sub.add_parser("replot", parents=[base],
701
+ help="redraw the modes of a saved SPOD at chosen frequencies",
702
+ description="Draw the modes stored by `save` at the frequency bins "
703
+ "nearest to the requested frequencies.")
704
+ p_re.add_argument("-p", "--mode-dir", required=True,
705
+ help="Folder written by `save` (contains SPOD_modes.npy, ...)")
706
+ p_re.add_argument("-fr", "--freqs", type=float, nargs="+", metavar="F",
707
+ help="Frequencies [Hz] (default: the strongest spectral peaks)")
708
+ p_re.add_argument("-m", "--num-modes", type=int, help="Number of modes to draw")
709
+ p_re.add_argument("-o", "--output-dir", help="Save figures here (otherwise display only)")
710
+ p_re.add_argument("--dpi", type=int, default=300)
711
+ p_re.add_argument("--show", action="store_true", help="Display figures even when saving")
712
+
713
+ args = parser.parse_args(argv)
714
+ progress = not args.no_progress
715
+
716
+ try:
717
+ if args.command == "replot":
718
+ visualize = args.show or args.output_dir is None
719
+ if not visualize:
720
+ plt.switch_backend("Agg")
721
+ SpectralPOD.replot(
722
+ args.mode_dir,
723
+ args.freqs,
724
+ args.num_modes,
725
+ args.output_dir,
726
+ visualize,
727
+ args.dpi,
728
+ progress
729
+ )
730
+ return
731
+
732
+ save = args.command == "save"
733
+ visualize = args.show if save else True
734
+ if not visualize:
735
+ plt.switch_backend("Agg")
736
+
737
+ SpectralPOD(
738
+ source=args.input,
739
+ dt=args.dt,
740
+ component=args.component,
741
+ nfft=args.nfft,
742
+ novlp=args.novlp,
743
+ window=args.window,
744
+ correction=args.correction,
745
+ num_modes=args.num_modes,
746
+ confidence=args.confidence,
747
+ ddof=args.ddof,
748
+ dx=args.dx,
749
+ dy=args.dy,
750
+ weights=args.weights,
751
+ dim=tuple(args.dim) if args.dim else None,
752
+ order=args.order,
753
+ plot_freqs=args.plot_freqs,
754
+ memory_limit=args.memory_limit,
755
+ target_dir=args.output_dir if save else None,
756
+ visualize=visualize,
757
+ save_results=save,
758
+ dpi=args.dpi if save else 300,
759
+ progress=progress,
760
+ ).fit()
761
+ except (FileNotFoundError, ValueError, OSError) as exc:
762
+ parser.exit(1, f"error: {exc}\n")
763
+
764
+
765
+ if __name__ == "__main__":
766
+ main()