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/dmd.py ADDED
@@ -0,0 +1,681 @@
1
+ #!/usr/bin/env python3
2
+ """Dynamic Mode Decomposition (DMD) of Experimental velocity-field and Image (Qualitative) data.
3
+
4
+ Input data
5
+ ----------
6
+ A .npz or .mat file holding the velocity components U, V, W (and/or Vmag) and,
7
+ optionally, dim = [nx, ny]. Every component is a matrix X of shape [N, Nt]:
8
+
9
+ N = nx * ny flattened spatial grid (rows)
10
+ Nt number of time instances (columns)
11
+
12
+ so X[:, k] is the field at time instance k flattened into a vector of length N.
13
+ Each field is flattened in C order (row-major, NumPy `field.reshape(-1)`) by
14
+ default; use --order F for MATLAB data (column-major, `U(:)`). `dim` and the order
15
+ are only used to fold the modes back into 2D fields of shape (nx, ny) for the
16
+ mode images. The data is used as is (no mean removal).
17
+
18
+ Algorithm (exact DMD; the hand-written notes, Tu et al. 2014, Brunton & Kutz, PyDMD)
19
+ -------------------------------------------------------------------------------
20
+ 1. X1 = X[:, :-1] X2 = X[:, 1:] (X2 ~ A X1)
21
+ 2. U, S, V = svd(X1) economy SVD, r = min(U.shape[1], rank)
22
+ 3. Atilde = Ur^H X2 Vr Sr^-1 (r x r)
23
+ 4. [W, D] = eig(Atilde) lambda = diag(D)
24
+ 5. omega = log(lambda) / dt (continuous time)
25
+ 6. phi = X2 Vr Sr^-1 W (DMD modes, N x r)
26
+ 7. b = phi \\ X[:, 0] (mode amplitudes)
27
+ 8. X_dmd(t) = phi @ (b * exp(omega * t)) (t may extend beyond the data)
28
+
29
+ Relation to the references: step 6 is the exact DMD of Tu et al. (2014) as in
30
+ Brunton & Kutz and PyDMD (exact=True). Tu et al. multiply the modes by 1/lambda,
31
+ which only rescales each mode (b absorbs it). `--method projected` gives the
32
+ projected modes of Schmid (2010), phi = Ur W. Brunton & Kutz's code computes b
33
+ from the low-rank system, b = (W D)^-1 Sr Vr^H[:, 0]; PyDMD and the notes use the
34
+ least-squares fit of step 7, as done here.
35
+
36
+ Results
37
+ -------
38
+ DMD modes DMD_modes.npy [N, r] and DMD_mode_<i>.png (2D, shape (nx, ny))
39
+ time dynamics DMD_dynamics.npy = b * exp(omega * t), DMD_dynamics.png
40
+ DMD spectra DMD_eigenvalues.png (lambda plane), DMD_omega.png (omega plane),
41
+ DMD_spectrum.png (amplitude vs frequency)
42
+ growth/decay rate Re(omega) [1/s] and frequency Im(omega)/(2 pi) [Hz] in
43
+ DMD_eigenvalues.csv and DMD_spectrum.npz
44
+ reconstruction DMD_reconstructed.npy [N, Nt (+ predicted)] (+ a snapshot figure)
45
+
46
+ Modes are sorted by amplitude |b| * ||phi||, and the arbitrary phase of each
47
+ eigenvector is fixed (largest element real and positive). A steady (background / mean-flow)
48
+ component appears as a mode with omega ~ 0.
49
+
50
+ Sub-commands
51
+ ------------
52
+ save run the DMD and WRITE all results (arrays, CSV, figures, reconstruction)
53
+ preview run the DMD and only DISPLAY figures (nothing is written)
54
+ reconstruct rebuild the data from saved DMD results with all modes, the leading
55
+ modes, a frequency band, or only the background / foreground modes,
56
+ optionally at future times
57
+ """
58
+
59
+ from __future__ import annotations
60
+
61
+ import argparse
62
+ from datetime import date
63
+ from pathlib import Path
64
+ from time import perf_counter
65
+
66
+ import matplotlib.pyplot as plt
67
+ import numpy as np
68
+
69
+ from ._common import COMPONENTS, FONT, __version__, read_component
70
+ from ._common import bar as _bar
71
+ from ._common import check_dim as _check_dim
72
+ from ._common import chunks as _chunks
73
+ from ._common import component_type as _component
74
+ from ._common import order_type as _order
75
+ from ._common import save_figs as _save_figs
76
+ from ._common import unflatten as _unflatten
77
+
78
+ __all__ = ["DMD"]
79
+
80
+
81
+ RANK_TOL = 1e-10
82
+ EIG_TOL = 1e-12
83
+ BLOCK = 1 << 16
84
+
85
+
86
+ def _with_conjugates(lam, idx):
87
+ """Add the complex-conjugate partner of every selected eigenvalue.
88
+
89
+ A real signal needs both members of a conjugate pair; dropping one halves
90
+ the amplitude of that oscillation.
91
+ """
92
+ chosen = set(int(i) for i in idx)
93
+ for j in list(chosen):
94
+ d = np.abs(lam - np.conj(lam[j]))
95
+ k = int(np.argmin(d))
96
+ if d[k] <= 1e-9 * max(1.0, abs(lam[j])):
97
+ chosen.add(k)
98
+ return np.array(sorted(chosen))
99
+
100
+
101
+ def _write_reconstruction(Phi, b, omega, t, out_path, chunk=32, progress=True):
102
+ """Write X_dmd(t) = Re[phi @ (b * exp(omega * t))] as float32 [N, len(t)].
103
+
104
+ Done block-by-block over the time axis, so the result never has to fit in
105
+ memory (it is written to a memory-mapped .npy file).
106
+ """
107
+ out_path = Path(out_path)
108
+ if out_path.suffix != ".npy":
109
+ out_path = out_path.with_name(out_path.name + ".npy")
110
+ out_path.parent.mkdir(parents=True, exist_ok=True)
111
+
112
+ N, n_out = Phi.shape[0], len(t)
113
+ out = np.lib.format.open_memmap(out_path, mode="w+", dtype=np.float32, shape=(N, n_out))
114
+ for lo, hi in _bar(_chunks(n_out, chunk), "Reconstructing", "blk", progress):
115
+ q_modes = (b[:, None] * np.exp(np.outer(omega, t[lo:hi]))).astype(Phi.dtype)
116
+ out[:, lo:hi] = (Phi @ q_modes).real
117
+ out.flush()
118
+ del out
119
+ return out_path
120
+
121
+
122
+ class DMD:
123
+ """Dynamic Mode Decomposition of one velocity component.
124
+
125
+ Args:
126
+ source (str): .npz or .mat file with U, V, W, Vmag, each of shape [N, Nt],
127
+ where N = nx*ny (flattened grid, rows) and Nt = time instances (columns)
128
+ dt (float): Time step between snapshots [s]
129
+ component (str): One of "U", "V", "W", "Vmag"
130
+ rank (int): Truncation rank r = min(U.shape[1], rank); this is also the
131
+ number of DMD modes that are computed, plotted and saved
132
+ method (str): "exact" (phi = X2 Vr Sr^-1 W) or "projected" (phi = Ur W)
133
+ predict (int): Number of extra snapshots to predict beyond the data
134
+ dim (tuple): Grid size (nx, ny), used to draw modes as 2D fields; the
135
+ file's `dim` is used if this is None; without either, modes are
136
+ drawn as 1D profiles
137
+ order (str): How each field was flattened: "C" row-major (default) or
138
+ "F" column-major (MATLAB)
139
+ target_dir (str): Output directory (required when save_results).
140
+ Results go to <target_dir>/<filename>_<YYYYMMDD>/<component>, where
141
+ <filename> is the stem of the input file
142
+ visualize (bool): Display figures interactively
143
+ save_results (bool): Write arrays, CSV, figures and the reconstruction
144
+ dpi (int): Resolution of saved figures
145
+ progress (bool): Show tqdm progress bars
146
+ """
147
+
148
+ def __init__(self,
149
+ source,
150
+ dt,
151
+ component="U",
152
+ rank=50,
153
+ method="exact",
154
+ predict=0,
155
+ dim=None,
156
+ order="C",
157
+ target_dir=None,
158
+ visualize=False,
159
+ save_results=False,
160
+ dpi=300,
161
+ progress=True):
162
+
163
+ if component not in COMPONENTS:
164
+ raise ValueError(f"component must be one of {COMPONENTS}")
165
+ if dt <= 0:
166
+ raise ValueError("dt must be > 0")
167
+ if rank < 1:
168
+ raise ValueError("rank must be >= 1")
169
+ if method not in ("exact", "projected"):
170
+ raise ValueError("method must be 'exact' or 'projected'")
171
+ if predict < 0:
172
+ raise ValueError("predict must be >= 0")
173
+ if order not in ("C", "F"):
174
+ raise ValueError("order must be 'C' or 'F'")
175
+ if dpi < 1:
176
+ raise ValueError("dpi must be >= 1")
177
+ if save_results and target_dir is None:
178
+ raise ValueError("target_dir is required when saving results")
179
+
180
+ self.source = Path(source)
181
+ if not self.source.is_file():
182
+ raise FileNotFoundError(f"Input file not found: {self.source}")
183
+ if self.source.suffix.lower() not in (".npz", ".mat"):
184
+ raise ValueError("Input must be a .npz or .mat file")
185
+
186
+ self.component = component
187
+ self.dt = float(dt)
188
+ self.rank_arg = rank
189
+ self.method = method
190
+ self.predict = predict
191
+ self._dim_arg = _check_dim(dim) if dim is not None else None
192
+ self.order = order
193
+ self.visualize = visualize
194
+ self.save_results = save_results
195
+ self.dpi = dpi
196
+ self.progress = progress
197
+
198
+ self.out_dir = None
199
+ if save_results:
200
+ self.out_dir = (Path(target_dir)
201
+ / f"{self.source.stem}_{date.today():%Y%m%d}" / component)
202
+
203
+ # filled by load_data() / compute()
204
+ self.X = self.dim = self.nt = None
205
+ self.lam = self.omega = self.b = self.phi = None
206
+ self.growth = self.freq = self.amp = None
207
+ self.t = self.dynamics = None
208
+ self.r = None
209
+
210
+ def _pbar(self, iterable, desc, unit="it"):
211
+ return _bar(iterable, desc, unit, self.progress)
212
+
213
+ def load_data(self):
214
+ """Load the selected component as a float64 matrix X of shape [N, Nt].
215
+
216
+ Rows: N = nx*ny flattened grid points; columns: Nt time instances.
217
+ """
218
+ print(f"Loading '{self.component}' from {self.source.name} ...")
219
+ arr, file_dim = read_component(self.source, self.component)
220
+
221
+ arr = np.squeeze(np.asarray(arr))
222
+ if arr.dtype.kind not in "fiu":
223
+ raise ValueError(f"Velocity data must be numeric, got dtype {arr.dtype}")
224
+ if arr.ndim != 2:
225
+ raise ValueError(f"Expected a matrix of shape [N, Nt] with N = nx*ny grid points "
226
+ f"(rows) and Nt time instances (columns), got {arr.shape}")
227
+ N, nt = arr.shape
228
+ if nt < 3:
229
+ raise ValueError(f"At least 3 time instances (columns) are needed, found {nt}")
230
+
231
+ fdim = _check_dim(file_dim) if file_dim is not None else None
232
+ if self._dim_arg is not None:
233
+ self.dim = self._dim_arg
234
+ if fdim is not None and fdim != self.dim:
235
+ print(f"Warning: --dim {list(self.dim)} overrides dim {list(fdim)} in the file.")
236
+ else:
237
+ self.dim = fdim
238
+ if self.dim is not None and self.dim[0] * self.dim[1] != N:
239
+ raise ValueError(f"dim {list(self.dim)} does not match the N = {N} rows of the data "
240
+ f"(shape {arr.shape}); the data must be [N, Nt] with N = nx*ny")
241
+ if self.dim is None:
242
+ print("No grid size (dim) available: modes will be drawn as 1D profiles.")
243
+ if N < nt:
244
+ print(f"Note: the data has fewer rows (N = {N}) than columns (Nt = {nt}); "
245
+ "the input must be [N, Nt] with N = nx*ny grid points and Nt time instances.")
246
+
247
+ X = arr.astype(np.float32)
248
+ if np.isnan(X).any():
249
+ print("Warning: NaNs found in the data; they are replaced by zero.")
250
+ np.nan_to_num(X, copy=False)
251
+ self.nt = nt
252
+ return X
253
+
254
+ def compute(self):
255
+ """Exact DMD following the algorithm in the notes."""
256
+ self.X = self.load_data()
257
+ N, nt, dt = self.X.shape[0], self.nt, self.dt
258
+
259
+ # snapshot pairs
260
+ X1 = self.X[:, :-1]
261
+ X2 = self.X[:, 1:]
262
+
263
+ # Economy SVD and rank truncation, r = min(U.shape[1], rank)
264
+ U, S, Vh = np.linalg.svd(X1, full_matrices=False)
265
+ r = min(U.shape[1], self.rank_arg)
266
+ r = min(r, int(np.count_nonzero(S > RANK_TOL * S[0])))
267
+ if r == 0:
268
+ raise ValueError("The data is all zeros")
269
+ Ur, Sr, Vr = U[:, :r], S[:r], Vh[:r].conj().T
270
+ print(f"DMD of a [{N} x {nt}] matrix, truncation rank r = {r}")
271
+
272
+ # Atilde = Ur^H X2 Vr Sr^-1 and its eigen-decomposition
273
+ Atilde = (Ur.conj().T @ X2 @ Vr) / Sr
274
+ lam, W = np.linalg.eig(Atilde)
275
+ keep = np.abs(lam) > EIG_TOL
276
+ if not keep.all():
277
+ print(f"Dropped {int((~keep).sum())} zero eigenvalue(s).")
278
+ lam, W = lam[keep], W[:, keep]
279
+
280
+ # DMD modes, built block-by-block over the rows
281
+ T = (Vr / Sr) @ W if self.method == "exact" else None
282
+ phi = np.empty((N, len(lam)), dtype=complex)
283
+ for lo, hi in self._pbar(_chunks(N, BLOCK), "Computing DMD modes", "blk"):
284
+ phi[lo:hi] = X2[lo:hi] @ T if T is not None else Ur[lo:hi] @ W
285
+
286
+ # eigenvectors are only defined up to a complex factor: fix the phase of every
287
+ # mode so that its largest element is real and positive (reproducible modes)
288
+ ph = phi[np.argmax(np.abs(phi), axis=0), np.arange(phi.shape[1])]
289
+ phi = phi / (ph / np.abs(ph))
290
+
291
+ # Amplitudes b = phi \ x0 (least squares)
292
+ b = np.linalg.lstsq(phi, self.X[:, 0].astype(complex), rcond=None)[0]
293
+ amp = np.abs(b) * np.linalg.norm(phi, axis=0)
294
+ order = np.argsort(-amp, kind="stable") # most energetic first
295
+ lam, phi, b, amp = lam[order], phi[:, order], b[order], amp[order]
296
+
297
+ self.lam, self.phi, self.b, self.amp = lam, phi, b, amp
298
+ # 5. continuous-time eigenvalues, growth/decay rate and frequency
299
+ self.omega = np.log(lam) / dt
300
+ self.growth = self.omega.real # growth (+) / decay (-) rate [1/s]
301
+ self.freq = self.omega.imag / (2.0 * np.pi) # frequency [Hz]
302
+ self.r = len(lam)
303
+
304
+ # 8. time dynamics b * exp(omega * t); t may extend beyond the data (tf)
305
+ self.t = np.arange(nt + self.predict) * dt
306
+ self.dynamics = b[:, None] * np.exp(np.outer(self.omega, self.t)) # [r, Nt + predict]
307
+
308
+ if self.save_results:
309
+ self.out_dir.mkdir(parents=True, exist_ok=True)
310
+ self._save_results()
311
+
312
+ def _save_results(self):
313
+ out = self.out_dir
314
+ np.save(out / "DMD_modes.npy", self.phi.astype(np.complex64)) # [N, r]
315
+ np.save(out / "DMD_dynamics.npy", self.dynamics.astype(np.complex64)) # [r, Nt + predict]
316
+ period = np.where(self.freq != 0, 1.0 / np.maximum(np.abs(self.freq), 1e-300), np.inf)
317
+ np.savez(out / "DMD_spectrum.npz", lam=self.lam, omega=self.omega,
318
+ growth_rate=self.growth, frequency=self.freq, amplitude=self.amp,
319
+ b=self.b, period=period)
320
+ np.savez(out / "DMD_info.npz",
321
+ dim=np.array(self.dim if self.dim is not None else (0, 0)),
322
+ order=self.order, dt=self.dt, component=self.component, rank=self.r,
323
+ num_snapshots=self.nt, predict=self.predict, method=self.method)
324
+ table = np.column_stack([np.arange(1, self.r + 1), self.amp, self.lam.real,
325
+ self.lam.imag, np.abs(self.lam), self.growth, self.freq,
326
+ period, np.abs(self.b), self.b.real, self.b.imag])
327
+ np.savetxt(out / "DMD_eigenvalues.csv", table, delimiter=",", fmt="%.8g",
328
+ header="mode,amplitude,lambda_re,lambda_im,abs_lambda,growth_rate [1/s],"
329
+ "frequency [Hz],period [s],abs_b,b_re,b_im", comments="")
330
+
331
+ def _path(self, name):
332
+ return None if self.out_dir is None else self.out_dir / name
333
+
334
+ def _label(self, i):
335
+ return f"f = {self.freq[i]:.4g} Hz, growth = {self.growth[i]:.4g} 1/s"
336
+
337
+ def plot_modes(self):
338
+ """Real and imaginary part of every DMD mode, as 2D images of shape (nx, ny)."""
339
+ for i in self._pbar(range(self.r), "Plotting DMD modes", "mode"):
340
+ z = self.phi[:, i]
341
+ if self.dim is None: # no grid size: 1D profile
342
+ fig, ax = plt.subplots(figsize=(9, 6))
343
+ ax.plot(z.real)
344
+ ax.set_xlabel("Spatial index", fontdict=FONT)
345
+ else:
346
+ fields = _unflatten(z.real.reshape(1, -1), self.dim, self.order)
347
+ assert fields.shape[1:] == tuple(self.dim)
348
+ v = float(np.max(np.abs(fields))) or 1.0
349
+ fig = plt.figure(figsize=(8, 6))
350
+ for img in fields:
351
+ im = plt.imshow(img, cmap="jet", vmin=-v, vmax=v, interpolation="bicubic")
352
+ fig.colorbar(im, fraction=0.04)
353
+ plt.title(f"{self._label(i)}")
354
+ plt.axis("off")
355
+ fig.tight_layout()
356
+ _save_figs(fig, self._path(f"DMD_mode_{i + 1}.png"), self.dpi, self.visualize)
357
+
358
+ def plot_dynamics(self):
359
+ """Time dynamics b*exp(omega*t) of all r modes (laid out in a grid)."""
360
+ r = self.r
361
+ ncols = 1 + (r > 6) + (r > 24)
362
+ nrows = -(-r // ncols)
363
+ fig, axes = plt.subplots(nrows, ncols, figsize=(6 * ncols, max(3, 2 * nrows)),
364
+ sharex=True, squeeze=False)
365
+ flat = axes.ravel()
366
+ for i in range(r):
367
+ ax = flat[i]
368
+ ax.plot(self.t, self.dynamics[i].real, color=plt.cm.tab10(i % 10))
369
+ if self.predict > 0:
370
+ ax.axvspan(self.t[self.nt - 1], self.t[-1], color="gray", alpha=0.15)
371
+ ax.set_title(f"Mode {i + 1}: {self._label(i)}", fontsize=9)
372
+ ax.set_xlim(self.t[0], self.t[-1])
373
+ for ax in flat[r:]:
374
+ ax.axis("off")
375
+ fig.supylabel(r"Re[$b\cdot e^{\omega t}$]", **FONT)
376
+ fig.supxlabel("Time [s]", **FONT)
377
+ fig.tight_layout()
378
+ _save_figs(fig, self._path("DMD_dynamics.png"), self.dpi, self.visualize)
379
+
380
+ def plot_spectra(self):
381
+ """DMD spectra: lambda plane, omega plane, amplitude vs frequency."""
382
+ amp_n = self.amp / self.amp.max()
383
+
384
+ # eigenvalues lambda with the unit circle (inside = decaying, outside = growing)
385
+ fig, ax = plt.subplots(figsize=(8, 6))
386
+ th = np.linspace(0, 2 * np.pi, 400)
387
+ ax.plot(np.cos(th), np.sin(th), "k--", lw=1)
388
+ sc = ax.scatter(self.lam.real, self.lam.imag, s=30 + 300 * amp_n,
389
+ c=self.growth, cmap="coolwarm", edgecolors="k")
390
+ fig.colorbar(sc, ax=ax, label="Growth rate [1/s]", fraction=0.046)
391
+ ax.set_aspect("equal")
392
+ ax.set_xlabel(r"Re($\lambda$)", fontdict=FONT)
393
+ ax.set_ylabel(r"Im($\lambda$)", fontdict=FONT)
394
+ ax.set_title("DMD eigenvalues (size ~ amplitude)")
395
+ fig.tight_layout()
396
+ _save_figs(fig, self._path("DMD_eigs.png"), self.dpi, self.visualize)
397
+
398
+ # continuous-time eigenvalues omega = log(lambda)/dt: growth rate vs frequency
399
+ fig, ax = plt.subplots(figsize=(7, 5))
400
+ ax.axvline(0, color="gray", lw=1)
401
+ ax.scatter(self.growth, self.freq, s=30 + 300 * amp_n, c="tab:red", edgecolors="k")
402
+ ax.set_xlabel(r"Growth rate Re($\omega$) [1/s]", fontdict=FONT)
403
+ ax.set_ylabel(r"Frequency Im($\omega$)/2$\pi$ [Hz]", fontdict=FONT)
404
+ ax.set_title(r"DMD eigenvalues in the $\omega$-plane (size ~ amplitude)")
405
+ fig.tight_layout()
406
+ _save_figs(fig, self._path("DMD_omega.png"), self.dpi, self.visualize)
407
+
408
+ # amplitude spectrum
409
+ fig, ax = plt.subplots(figsize=(9, 5))
410
+ ax.vlines(self.freq, 0, self.amp, color="tab:blue")
411
+ ax.plot(self.freq, self.amp, "o", color="tab:blue")
412
+ ax.set_xlabel("Frequency [Hz]", fontdict=FONT)
413
+ ax.set_ylabel(r"Amplitude $|b|\,\|\Phi\|$", fontdict=FONT)
414
+ fig.tight_layout()
415
+ _save_figs(fig, self._path("DMD_spectrum.png"), self.dpi, self.visualize)
416
+
417
+ def _show_reconstructed(self):
418
+ """Middle snapshot: original vs DMD approximation."""
419
+ idx = self.nt // 2
420
+ orig = self.X[:, idx]
421
+ dmd = (self.phi @ self.dynamics[:, idx]).real
422
+ title = (f"Data at {idx + 1}", "DMD approximation")
423
+ if self.dim is None:
424
+ fig, ax = plt.subplots(figsize=(9, 4))
425
+ ax.plot(orig, label=title[0])
426
+ ax.plot(dmd, "--", label=title[1])
427
+ ax.legend()
428
+ ax.set_xlabel("Spatial index", fontdict=FONT)
429
+ else:
430
+ fields = _unflatten(np.stack([orig, dmd]), self.dim, self.order)
431
+ fig, axes = plt.subplots(1, 2, figsize=(10, 5))
432
+ for ax, img, name in zip(axes, fields, title):
433
+ im = ax.imshow(img, cmap="jet")
434
+ fig.colorbar(im, ax=ax, fraction=0.046)
435
+ ax.set_title(name)
436
+ ax.axis("off")
437
+ fig.tight_layout()
438
+ _save_figs(fig, self._path("DMD_reconstructed.png"), self.dpi, self.visualize)
439
+
440
+ def fit(self):
441
+ t0 = perf_counter()
442
+ print(f"\nComputing DMD of {self.component} ... \n")
443
+ self.compute()
444
+
445
+ print(f"\n{self.r} DMD modes ({self.method} DMD), dt = {self.dt:g} s")
446
+ print("\n # freq [Hz] growth [1/s] |lambda| amplitude")
447
+
448
+ for i in range(min(self.r, 10)):
449
+ print(f"{i + 1:4d} {self.freq[i]:11.5g} {self.growth[i]:13.5g} "
450
+ f"{abs(self.lam[i]):10.6f} {self.amp[i]:13.5g}")
451
+ tol = 1e-3 / (self.nt * self.dt) # < 0.1 % amplitude change over the record = neutral
452
+ n_grow = int(np.count_nonzero(self.growth > tol))
453
+ n_decay = int(np.count_nonzero(self.growth < -tol))
454
+ print(f"\n{n_grow} growing, {n_decay} decaying and {self.r - n_grow - n_decay} "
455
+ f"neutral mode(s) (growth rate = Re(omega) > 0 means growing)\n")
456
+
457
+ self.plot_modes()
458
+ self.plot_dynamics()
459
+ self.plot_spectra()
460
+ self._show_reconstructed()
461
+
462
+ if self.save_results: # DMD reconstruction of every time point (and predicted ones)
463
+ path = _write_reconstruction(self.phi, self.b, self.omega, self.t,
464
+ self.out_dir / "DMD_reconstructed.npy",
465
+ progress=self.progress)
466
+ print(f"DMD reconstruction ({self.X.shape[0]} x {len(self.t)}) saved to {path.resolve()}")
467
+
468
+ msg = f"\nCompleted in {(perf_counter() - t0) / 60:.1f} mins"
469
+ if self.out_dir is not None:
470
+ msg += (f" and results saved in {self.out_dir.resolve()}"
471
+ f"\nUse the `reconstruct` sub-command for a subset of modes, a frequency "
472
+ f"band, background/foreground parts or other prediction times.")
473
+ print(msg)
474
+
475
+ @staticmethod
476
+ def reconstruct_from_files(dmd_dir, output=None, top=None, fmin=None, fmax=None,
477
+ part="all", omega_tol=1e-2, predict=0, chunk=32,
478
+ progress=True):
479
+ """Rebuild the data X(t) = Re[ sum_j Phi_j b_j exp(omega_j t) ] from saved results.
480
+
481
+ Args:
482
+ dmd_dir: folder written by `save` (DMD_modes.npy, DMD_spectrum.npz, ...)
483
+ output: output .npy path; default <dmd_dir>/DMD_reconstructed_<nt>modes.npy
484
+ top: use only the `top` most energetic modes
485
+ fmin, fmax: keep only modes with fmin <= |frequency| <= fmax [Hz]
486
+ part: "all", "background" (|omega| < omega_tol, steady modes) or
487
+ "foreground" (the remaining modes)
488
+ omega_tol: threshold on |omega| [1/s] that defines the background modes
489
+ predict: number of snapshots to add beyond the data
490
+ chunk: number of snapshots rebuilt per block
491
+
492
+ Complex-conjugate partners of the selected modes are always included.
493
+ The result has shape [N, Nt + predict], like the input data.
494
+ """
495
+ d = Path(dmd_dir)
496
+ for name in ("DMD_modes.npy", "DMD_spectrum.npz", "DMD_info.npz"):
497
+ if not (d / name).is_file():
498
+ raise FileNotFoundError(f"{name} not found in {d}")
499
+ if chunk < 1:
500
+ raise ValueError("chunk must be >= 1")
501
+ if predict < 0:
502
+ raise ValueError("predict must be >= 0")
503
+ if top is not None and top < 1:
504
+ raise ValueError("top must be >= 1")
505
+ if part not in ("all", "background", "foreground"):
506
+ raise ValueError("part must be 'all', 'background' or 'foreground'")
507
+ if omega_tol <= 0:
508
+ raise ValueError("omega_tol must be > 0")
509
+
510
+ modes = np.load(d / "DMD_modes.npy", mmap_mode="r")
511
+
512
+ with np.load(d / "DMD_spectrum.npz") as z:
513
+ lam, omega, b, freq = z["lam"], z["omega"], z["b"], z["frequency"]
514
+
515
+ with np.load(d / "DMD_info.npz") as z:
516
+ dt, nt = float(z["dt"]), int(z["num_snapshots"])
517
+ N, r = modes.shape
518
+
519
+ sel = np.arange(r)
520
+ if top is not None:
521
+ sel = sel[:top]
522
+ if fmin is not None:
523
+ sel = sel[np.abs(freq[sel]) >= fmin]
524
+ if fmax is not None:
525
+ sel = sel[np.abs(freq[sel]) <= fmax]
526
+ if part == "background":
527
+ sel = sel[np.abs(omega[sel]) < omega_tol]
528
+ elif part == "foreground":
529
+ sel = sel[np.abs(omega[sel]) >= omega_tol]
530
+ if len(sel) == 0:
531
+ raise ValueError("No DMD mode matches the selection")
532
+ sel = _with_conjugates(lam, sel)
533
+ print(f"Using {len(sel)} of {r} DMD modes (|f| = "
534
+ f"{np.abs(freq[sel]).min():.4g} to {np.abs(freq[sel]).max():.4g} Hz)")
535
+
536
+ if output is None:
537
+ tag = f"_{len(sel)}modes" + (f"_pred{predict}" if predict else "")
538
+ output = d / f"DMD_reconstructed{tag}.npy"
539
+ t = np.arange(nt + predict) * dt
540
+ path = _write_reconstruction(np.ascontiguousarray(modes[:, sel]), b[sel], omega[sel],
541
+ t, output, chunk, progress)
542
+ print(f"Reconstruction ({N} x {len(t)}, [N, Nt]) saved to {path.resolve()}")
543
+ return path
544
+
545
+
546
+ EXAMPLES = """examples:
547
+ python dmd.py save -i piv_data.npz -c U -o ./results -t 0.002 -r 20
548
+ python dmd.py save -i piv_data.mat -c W -o ./results -t 0.002 --order F --predict 100
549
+ python dmd.py preview -i piv_data.npz -c V -t 0.002 -r 10 --dim 120 80
550
+ python dmd.py reconstruct -p ./results/piv_data_20261128/U -r 4
551
+ python dmd.py reconstruct -p ./results/piv_data_20261128/U --fmin 4.5 --fmax 5.5 --predict 50
552
+ python dmd.py reconstruct -p ./results/piv_data_20261128/U --part background
553
+ """
554
+
555
+
556
+ def main(argv=None):
557
+ parser = argparse.ArgumentParser(
558
+ prog="dmd.py",
559
+ description="Dynamic Mode Decomposition of Experimental data and Image data [N, Nt]: modes, "
560
+ "dynamics, spectra and growth/decay rates",
561
+ epilog=EXAMPLES,
562
+ formatter_class=argparse.RawDescriptionHelpFormatter,
563
+ )
564
+ parser.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
565
+ sub = parser.add_subparsers(dest="command", required=True,
566
+ metavar="{save,preview,reconstruct}")
567
+
568
+ # options shared by every sub-command
569
+ base = argparse.ArgumentParser(add_help=False)
570
+ base.add_argument("--no-progress", action="store_true", help="Disable tqdm progress bars")
571
+
572
+ # options shared by the analysis sub-commands
573
+ analysis = argparse.ArgumentParser(add_help=False, parents=[base])
574
+ g = analysis.add_argument_group("analysis options")
575
+ g.add_argument("-i", "--input", required=True,
576
+ help="Input data file (.npz or .mat) with U, V, W, Vmag, each of shape "
577
+ "[N, Nt]: N = nx*ny flattened grid points in rows, Nt time instances "
578
+ "in columns")
579
+ g.add_argument("-c", "--component", type=_component, default="U", metavar="{U,V,W,Vmag}",
580
+ help="Velocity component to analyse (default: U)")
581
+ g.add_argument("-t", "--dt", type=float, required=True,
582
+ help="Time step between snapshots [s]")
583
+ g.add_argument("-r", "--rank", type=int, default=50,
584
+ help="Truncation rank, r = min(U.shape[1], rank); also the number of DMD "
585
+ "modes computed, plotted and saved (default: 50)")
586
+ g.add_argument("-m", "--method", choices=("exact", "projected"), default="exact",
587
+ help="exact: phi = X2 Vr Sr^-1 W (default); projected: phi = Ur W")
588
+ g.add_argument("--predict", type=int, default=0,
589
+ help="Number of extra snapshots to predict beyond the data (default: 0)")
590
+ g.add_argument("--dim", type=int, nargs=2, metavar=("NX", "NY"),
591
+ help="Grid size, to draw modes as 2D (nx, ny) images (default: `dim` from "
592
+ "the file; without it modes are drawn as 1D profiles)")
593
+ g.add_argument("--order", type=_order, default="C", metavar="{C,F}",
594
+ help="Order in which each [nx, ny] field was flattened into a column of X: "
595
+ "C = row-major (NumPy, default), F = column-major (MATLAB)")
596
+
597
+ p_save = sub.add_parser("save", parents=[analysis],
598
+ help="run the DMD and save all results to disk",
599
+ description="Run DMD and save arrays, CSV, figures and the DMD "
600
+ "reconstruction.")
601
+ p_save.add_argument("-o", "--output-dir", required=True,
602
+ help="Output directory; results go to "
603
+ "<output-dir>/<input-file-stem>_<YYYYMMDD>/<component>")
604
+ p_save.add_argument("--dpi", type=int, default=300,
605
+ help="Resolution of saved figures (default: 300)")
606
+ p_save.add_argument("--show", action="store_true",
607
+ help="Also display the figures while saving")
608
+
609
+ sub.add_parser("preview", parents=[analysis],
610
+ help="run the DMD and only display figures (nothing saved)",
611
+ description="Run DMD and display figures. No files are written.")
612
+
613
+ p_rc = sub.add_parser("reconstruct", parents=[base],
614
+ help="rebuild the data from saved DMD results",
615
+ description="Reconstruct X(t) = Re[sum phi b exp(omega t)] from the files "
616
+ "written by `save`, optionally with a subset of modes "
617
+ "and/or at future times. Output shape: [N, Nt].")
618
+ p_rc.add_argument("-p", "--dmd-dir", required=True,
619
+ help="Folder written by `save` (contains DMD_modes.npy, ...)")
620
+ p_rc.add_argument("-r", "--top", type=int,
621
+ help="Use only the K most energetic modes (default: all)")
622
+ p_rc.add_argument("--fmin", type=float, help="Keep modes with |frequency| >= FMIN [Hz]")
623
+ p_rc.add_argument("--fmax", type=float, help="Keep modes with |frequency| <= FMAX [Hz]")
624
+ p_rc.add_argument("--part", choices=("all", "background", "foreground"), default="all",
625
+ help="background: steady modes with |omega| < --omega-tol; foreground: "
626
+ "all other modes (default: all)")
627
+ p_rc.add_argument("-tol", "--omega-tol", type=float, default=1e-2,
628
+ help="|omega| threshold [1/s] for the background modes (default: 0.01)")
629
+ p_rc.add_argument("--predict", type=int, default=0,
630
+ help="Number of extra snapshots to predict beyond the data (default: 0)")
631
+ p_rc.add_argument("-o", "--output",
632
+ help="Output .npy filename (default: DMD_reconstructed_<nt>modes.npy in the "
633
+ "DMD folder)")
634
+ p_rc.add_argument("--chunk", type=int, default=32,
635
+ help="Snapshots rebuilt per block (default: 32)")
636
+
637
+ args = parser.parse_args(argv)
638
+ progress = not args.no_progress
639
+
640
+ try:
641
+ if args.command == "reconstruct":
642
+ DMD.reconstruct_from_files(
643
+ args.dmd_dir,
644
+ args.output,
645
+ args.top,
646
+ args.fmin,
647
+ args.fmax,
648
+ args.part,
649
+ args.omega_tol,
650
+ args.predict,
651
+ chunk=args.chunk,
652
+ progress=progress,
653
+ )
654
+ return
655
+
656
+ save = args.command == "save"
657
+ visualize = args.show if save else True
658
+ if not visualize:
659
+ plt.switch_backend("Agg")
660
+
661
+ DMD(
662
+ source=args.input,
663
+ dt=args.dt,
664
+ component=args.component,
665
+ rank=args.rank,
666
+ method=args.method,
667
+ predict=args.predict,
668
+ dim=tuple(args.dim) if args.dim else None,
669
+ order=args.order,
670
+ target_dir=args.output_dir if save else None,
671
+ visualize=visualize,
672
+ save_results=save,
673
+ dpi=args.dpi if save else 300,
674
+ progress=progress,
675
+ ).fit()
676
+ except (FileNotFoundError, ValueError, OSError) as exc:
677
+ parser.exit(1, f"error: {exc}\n")
678
+
679
+
680
+ if __name__ == "__main__":
681
+ main()
modeflow/py.typed ADDED
File without changes