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 ADDED
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/python3
2
+
3
+ """pymodeflow - modal decompositions of time-resolved experimental/image data
4
+
5
+ Two command line tools and Python classes share one data convention
6
+ (``[N, Nt]`` matrices, ``N = nx*ny``, stored in ``.npz``/``.mat`` files):
7
+
8
+ * :class:`~modeflow.snap_pod.SnapshotPOD` (``snap-pod``): snapshot POD by the method
9
+ of snapshots - spatial modes, time coefficients, energy and PSD of the coefficients.
10
+ * :class:`~modeflow.spod.SpectralPOD` (``spod``): spectral POD with Welch's method
11
+ (Schmidt & Colonius, AIAA J. 2020) - SPOD modes and the SPOD energy spectrum.
12
+
13
+ Please cite the software and the methods it implements, see ``CITATION.cff``.
14
+ """
15
+
16
+ from ._common import __version__
17
+
18
+ __all__ = ["SnapshotPOD", "SpectralPOD", "SPOD", "DMD", "synthetic_piv", "__version__"]
19
+
20
+ # Submodules are imported lazily so that ``python -m modeflow.snap_pod`` starts cleanly
21
+ # and ``import modeflow`` stays fast.
22
+ _LAZY = {
23
+ "SnapshotPOD": "snap_pod",
24
+ "SpectralPOD": "spod",
25
+ "DMD": "dmd",
26
+ "SPOD": "spod",
27
+ "synthetic_piv": "synthetic",
28
+ }
29
+
30
+
31
+ def __getattr__(name):
32
+ if name in _LAZY:
33
+ from importlib import import_module
34
+
35
+ return getattr(import_module(f".{_LAZY[name]}", __name__), name)
36
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
modeflow/__main__.py ADDED
@@ -0,0 +1,11 @@
1
+ """``python -m pymodeflow`` prints the available tools."""
2
+
3
+ from ._common import __version__
4
+
5
+ print(f"""pymodeflow {__version__}
6
+
7
+ snap-pod snapshotPOD (also: python3 -m modeflow.snap_pod)
8
+ spod spectralPOD (also: python3 -m modeflow.spod)
9
+ dmd DMD (also: python3 -m modeflow.dmd)
10
+
11
+ Run `snap-pod --help` or `spod --help`. Documentation: see README.md.""")
modeflow/_common.py ADDED
@@ -0,0 +1,157 @@
1
+ """Helpers shared by :mod:`pymodeflow.snap_pod` and :mod:`pymodeflow.spod`.
2
+
3
+ Data convention (both tools): every velocity component is an array of shape
4
+ ``[N, Nt]`` with ``N = nx * ny`` flattened grid points in rows and ``Nt`` time
5
+ snapshots in columns, stored in a ``.npz`` or ``.mat`` file together with
6
+ ``dim = [nx, ny]``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ from pathlib import Path
13
+
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ from tqdm import tqdm
17
+
18
+ try: # written by setuptools-scm at build time
19
+ from ._version import __version__
20
+ except ImportError: # running from a source tree that was never built / installed
21
+ try:
22
+ from importlib.metadata import version as _metadata_version
23
+
24
+ __version__ = _metadata_version("pymodeflow")
25
+ except Exception: # pragma: no cover
26
+ __version__ = "0+unknown"
27
+
28
+
29
+ COMPONENTS = ("U", "V", "W", "Vmag")
30
+ FONT = {"family": "serif", "fontsize": 13, "color": "navy"}
31
+
32
+
33
+ def chunks(total, size):
34
+ """Return (start, stop) index pairs covering ``range(total)``."""
35
+ return [(a, min(a + size, total)) for a in range(0, total, size)]
36
+
37
+
38
+ def bar(iterable, desc, unit="it", progress=True):
39
+ """``tqdm`` progress bar that can be switched off."""
40
+ return tqdm(iterable, desc=desc, unit=unit, disable=not progress)
41
+
42
+
43
+ def find_key(names, wanted):
44
+ """Return the name in ``names`` matching ``wanted`` (exact first, then case-insensitive)."""
45
+ if wanted in names:
46
+ return wanted
47
+ for n in names:
48
+ if n.lower() == wanted.lower():
49
+ return n
50
+ return None
51
+
52
+
53
+ def missing_component(comp, names, filename):
54
+ """Build a clear error for a velocity component that is not in the data file."""
55
+ present = [n for n in names if n.lower() in {c.lower() for c in COMPONENTS}]
56
+ msg = (f"Component '{comp}' is not in {filename}. "
57
+ f"Components in the file: {present if present else list(names)}.")
58
+ if comp == "W":
59
+ msg += " (W is only present in 3-component data.)"
60
+ return ValueError(msg)
61
+
62
+
63
+ def check_dim(dim):
64
+ """Validate a grid size and return it as a tuple of two ints ``(nx, ny)``."""
65
+ d = tuple(int(round(float(v))) for v in np.ravel(dim))
66
+ if len(d) != 2 or min(d) < 1:
67
+ raise ValueError(f"`dim` must be [nx, ny] with positive values, got {list(d)}")
68
+ return d
69
+
70
+
71
+ def unflatten(rows, dim, order):
72
+ """Fold flattened fields ``(k, N)`` back into ``k`` 2D fields ``(k, nx, ny)``.
73
+
74
+ Every returned field ``fields[i]`` has shape ``(nx, ny)``.
75
+
76
+ order="C": each field was flattened row-major (NumPy ``field.reshape(-1)``)
77
+ order="F": each field was flattened column-major (MATLAB ``U(:)``)
78
+ """
79
+ nx, ny = dim
80
+ rows = np.asarray(rows)
81
+ k = rows.shape[0]
82
+ if order == "C":
83
+ return rows.reshape(k, nx, ny)
84
+ if order == "F":
85
+ return rows.reshape(k, ny, nx).transpose(0, 2, 1)
86
+ raise ValueError("order must be 'C' or 'F'")
87
+
88
+
89
+ def save_figs(fig, path, dpi, visualize):
90
+ """Save (optional), display (optional) and always close the figure."""
91
+ if path is not None:
92
+ fig.savefig(path, dpi=dpi, bbox_inches="tight")
93
+ if visualize:
94
+ plt.show(block=False)
95
+ plt.pause(2)
96
+ plt.close(fig)
97
+
98
+
99
+ def read_mat(path, comp):
100
+ """Return ``(array, dim)`` from a .mat file (v5/v7 via SciPy, v7.3 via h5py)."""
101
+ path = Path(path)
102
+ try:
103
+ from scipy.io import loadmat, whosmat
104
+
105
+ names = [n for n, _, _ in whosmat(path)]
106
+ ckey, dkey = find_key(names, comp), find_key(names, "dim")
107
+ if ckey is None:
108
+ raise missing_component(comp, names, path.name)
109
+ want = [ckey] + ([dkey] if dkey else [])
110
+ d = loadmat(path, variable_names=want, squeeze_me=True)
111
+ return d[ckey], (d[dkey] if dkey else None)
112
+ except NotImplementedError: # MATLAB v7.3 files are HDF5
113
+ try:
114
+ import h5py
115
+ except ImportError as exc:
116
+ raise ValueError(f"{path.name} is a MATLAB v7.3 file; "
117
+ "install h5py (pip install 'pivmodes[mat73]') to read it") from exc
118
+ with h5py.File(path, "r") as f:
119
+ names = [k for k in f.keys() if not k.startswith("#")]
120
+ ckey, dkey = find_key(names, comp), find_key(names, "dim")
121
+ if ckey is None:
122
+ raise missing_component(comp, names, path.name)
123
+ arr = np.array(f[ckey]).T # HDF5 stores MATLAB axes reversed
124
+ dim = np.array(f[dkey]).T if dkey else None
125
+ return arr, dim
126
+
127
+
128
+ def read_component(path, comp):
129
+ """Read one velocity component (and ``dim`` if present) from a .npz or .mat file.
130
+
131
+ Variable names are matched without regard to letter case. Returns
132
+ ``(array, dim_or_None)``; the array is returned as stored.
133
+ """
134
+ path = Path(path)
135
+ if path.suffix.lower() == ".npz":
136
+ with np.load(path, allow_pickle=False) as d:
137
+ keys = list(d.files)
138
+ ckey, dkey = find_key(keys, comp), find_key(keys, "dim")
139
+ if ckey is None:
140
+ raise missing_component(comp, keys, path.name)
141
+ return d[ckey], (d[dkey] if dkey else None)
142
+ return read_mat(path, comp)
143
+
144
+
145
+ def component_type(text):
146
+ """argparse type: case-insensitive component name -> canonical U, V, W or Vmag."""
147
+ for c in COMPONENTS:
148
+ if text.lower() == c.lower():
149
+ return c
150
+ raise argparse.ArgumentTypeError(f"choose from {', '.join(COMPONENTS)}")
151
+
152
+
153
+ def order_type(text):
154
+ """argparse type: flatten order, ``C`` or ``F`` (case-insensitive)."""
155
+ if text.upper() not in ("C", "F"):
156
+ raise argparse.ArgumentTypeError("choose C or F")
157
+ return text.upper()
modeflow/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.2'
22
+ __version_tuple__ = version_tuple = (0, 1, 2)
23
+
24
+ __commit_id__ = commit_id = None