PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
periodic_spectral.py
Go to the documentation of this file.
1"""!
2@file periodic_spectral.py
3@brief Fourier machinery for the uniform periodic axes of PICurv's Cartesian grids.
4@details Shared by `ic.gen`, which synthesizes and resamples initial conditions, and
5 `spectra.gen`, which measures spectra; both load it from `picurv_cli/`. Both need the same answer to three
6 questions: which axes may be transformed, what the continuum and PICurv-discrete
7 wavenumbers are, and how a periodic field is moved between resolutions. Arrays are
8 in PICurv storage order, `[k, j, i, component]`; lengths and wavenumbers are in
9 Cartesian `x, y, z` order. Every function imports NumPy through
10 `require_numpy()`, so importing this module never imports NumPy itself; that import,
11 with its retry, is defined here once for the conductor and every generator.
12"""
13
14import re
15import sys
16
17
18def drop_imported_package(package_name: str):
19 """!
20 @brief Remove a failed/partial import package tree from sys.modules.
21 @param[in] package_name Top-level package name.
22 """
23 prefix = package_name + "."
24 for module_name in list(sys.modules):
25 if module_name == package_name or module_name.startswith(prefix):
26 sys.modules.pop(module_name, None)
27
28
29#: A `pythonX.Y` (or `python-X.Y`) component of a site-packages path.
30_SITE_PYTHON_VERSION = re.compile(r"python(?:-)?(\d+)\.(\d+)", re.IGNORECASE)
31
32
34 """!
35 @brief Remove site-package paths for a different Python major/minor version.
36 @details The version is the first `pythonX.Y` anywhere in the path, so a path with an
37 unversioned `python` directory before it, or a two-digit minor version, is read
38 correctly; a site path naming no version is kept.
39 @param[in] paths Candidate sys.path entries.
40 @return Filtered path list.
41 """
42 current = (sys.version_info[0], sys.version_info[1])
43 filtered = []
44 for path in paths:
45 text = str(path)
46 match = _SITE_PYTHON_VERSION.search(text)
47 if match:
48 path_version = (int(match.group(1)), int(match.group(2)))
49 if path_version != current and ("site-packages" in text or "dist-packages" in text):
50 continue
51 filtered.append(path)
52 return filtered
53
54
55_NUMPY_MODULE = None
56
57
59 """!
60 @brief Import NumPy on first use, retrying without other Pythons' site-packages.
61 @details The one implementation the conductor, the shared modules and the generators use.
62 @return Imported NumPy module.
63 """
64 global _NUMPY_MODULE
65 if _NUMPY_MODULE is not None:
66 return _NUMPY_MODULE
67 try:
68 import numpy
69 except Exception as exc:
70 first_error = exc
71 original_path = list(sys.path)
72 try:
74 sys.path = prune_incompatible_python_site_paths(original_path)
75 import numpy
76 except Exception as retry_exc:
77 raise RuntimeError(
78 "NumPy is required for this operation, but no compatible NumPy "
79 "could be imported for this Python interpreter. PICurv ignored "
80 "site-packages paths for other Python versions and retried. "
81 f"First error: {first_error}. Retry error: {retry_exc}"
82 ) from retry_exc
83 finally:
84 sys.path = original_path
85 _NUMPY_MODULE = numpy
86 return _NUMPY_MODULE
87
88
89def validate_spectral_grid(nodes, transform_axes=(0, 1, 2), subject="spectra require"):
90 """!
91 @brief Validate the uniform axis-aligned Cartesian grid an FFT on periodic axes requires.
92 @param[in] nodes PICGRID node-coordinate array shaped `(KM, JM, IM, 3)`.
93 @param[in] transform_axes Cartesian axes that are transformed and so must be uniform;
94 the remaining axes may stretch.
95 @param[in] subject What needs the grid and its verb, opening each error message.
96 @return Cell counts in storage order and physical lengths in Cartesian order.
97 """
98 numpy = require_numpy()
99 km, jm, im, _ = nodes.shape
100 cells = (km - 1, jm - 1, im - 1)
101 if min(cells) < 4:
102 raise ValueError(f"{subject} at least four cells per axis; found {cells}.")
103 axes = (nodes[0, 0, :, 0], nodes[0, :, 0, 1], nodes[:, 0, 0, 2])
104 for axis, (physical_axis, values) in enumerate(zip("xyz", axes)):
105 delta = numpy.diff(values)
106 if not numpy.all(numpy.isfinite(delta)) or not numpy.all(delta > 0) or (
107 axis in transform_axes and not numpy.allclose(delta, delta[0], rtol=1e-10, atol=1e-12)):
108 raise ValueError(f"{subject} uniform positive {physical_axis} spacing on every "
109 "transformed axis.")
110 if not (numpy.allclose(nodes[..., 0], axes[0][None, None, :]) and
111 numpy.allclose(nodes[..., 1], axes[1][None, :, None]) and
112 numpy.allclose(nodes[..., 2], axes[2][:, None, None])):
113 raise ValueError(f"{subject} an axis-aligned Cartesian grid (x->i, y->j, z->k).")
114 return cells, tuple(float(values[-1] - values[0]) for values in axes)
115
116
117def spectral_symbols(cells_kji, lengths_xyz):
118 """!
119 @brief Build continuum and centered-discrete Fourier symbols.
120 @param[in] cells_kji Cell counts in storage order.
121 @param[in] lengths_xyz Physical box lengths in Cartesian order.
122 @return Continuum symbols, centered-discrete symbols, and Cartesian spacings.
123 """
124 numpy = require_numpy()
125 nk, nj, ni = cells_kji
126 lx, ly, lz = lengths_xyz
127 dx, dy, dz = lx / ni, ly / nj, lz / nk
128 kz = 2*numpy.pi*numpy.fft.fftfreq(nk, d=dz)[:, None, None]
129 ky = 2*numpy.pi*numpy.fft.fftfreq(nj, d=dy)[None, :, None]
130 kx = 2*numpy.pi*numpy.fft.fftfreq(ni, d=dx)[None, None, :]
131 discrete = (numpy.sin(kx*dx)/dx, numpy.sin(ky*dy)/dy, numpy.sin(kz*dz)/dz)
132 return (kx, ky, kz), discrete, (dx, dy, dz)
133
134
135#: Filter kernels `fourier_resample` applies, by name.
136RESAMPLE_FILTERS = ("none", "sharp", "gaussian", "box")
137
138
139def _resample_axis(values, storage_axis, target_count, length, shift):
140 """!
141 @brief Move one periodic axis of an array of samples to another uniform resolution.
142 @details The samples are read as a truncated Fourier series, which is re-evaluated at
143 the target points. Modes are kept only where both resolutions represent them
144 unambiguously, |m| < min(N, M)/2, so each Nyquist mode is dropped and the
145 result stays real.
146 @param[in] values Real samples; `storage_axis` is the axis being moved.
147 @param[in] storage_axis Array axis to resample.
148 @param[in] target_count Number of target samples along that axis.
149 @param[in] length Physical period of the axis.
150 @param[in] shift Target first-sample position minus source first-sample position.
151 @return Real samples with `target_count` points along `storage_axis`.
152 """
153 numpy = require_numpy()
154 source_count = values.shape[storage_axis]
155 coeff = numpy.fft.fft(values, axis=storage_axis) / source_count
156 modes = numpy.rint(numpy.fft.fftfreq(source_count) * source_count).astype(int)
157 keep = numpy.abs(modes) < min(source_count, target_count) / 2.0
158 phase = numpy.exp(1j * 2.0 * numpy.pi * modes[keep] * shift / length)
159 shape = [1] * values.ndim
160 shape[storage_axis] = int(keep.sum())
161 kept = numpy.compress(keep, coeff, axis=storage_axis) * phase.reshape(shape)
162 out_shape = list(values.shape)
163 out_shape[storage_axis] = target_count
164 target = numpy.zeros(out_shape, dtype=complex)
165 index = [slice(None)] * values.ndim
166 index[storage_axis] = modes[keep] % target_count
167 target[tuple(index)] = kept
168 return (numpy.fft.ifft(target, axis=storage_axis) * target_count).real
169
170
171def filter_transfer(continuum_symbols, filter_spec):
172 """!
173 @brief Transfer function of a resampling filter on the target grid's wavenumbers.
174 @param[in] continuum_symbols Continuum `(kx, ky, kz)` from `spectral_symbols()`.
175 @param[in] filter_spec Mapping with `type` in `RESAMPLE_FILTERS`; `sharp` takes
176 `cutoff` (a wavenumber), `gaussian` and `box` take `width`
177 (the filter width Delta, a length).
178 @return Broadcastable transfer array, or None for `none`.
179 """
180 numpy = require_numpy()
181 kind = filter_spec.get("type", "none")
182 kx, ky, kz = continuum_symbols
183 if kind == "none":
184 return None
185 if kind == "sharp":
186 return (kx*kx + ky*ky + kz*kz <= float(filter_spec["cutoff"])**2).astype(float)
187 width = float(filter_spec["width"])
188 if kind == "gaussian":
189 return numpy.exp(-(kx*kx + ky*ky + kz*kz) * width * width / 24.0)
190 if kind == "box":
191 return numpy.sinc(kx*width/(2*numpy.pi)) * numpy.sinc(ky*width/(2*numpy.pi)) * \
192 numpy.sinc(kz*width/(2*numpy.pi))
193 raise ValueError(f"filter type must be one of {RESAMPLE_FILTERS}; got {kind!r}.")
194
195
196def fourier_resample(values, target_cells_kji, lengths_xyz, source_first_xyz, target_first_xyz,
197 filter_spec=None):
198 """!
199 @brief Resample a triply periodic vector field onto another uniform grid, optionally filtered.
200 @details Exact for band-limited data: every mode both grids resolve is carried over with
201 its amplitude and phase, then the filter multiplies its transfer function. Each
202 axis is moved separately, so memory stays at one array of the larger size.
203 @param[in] values Real samples `[k, j, i, component]` of the source field.
204 @param[in] target_cells_kji Target sample counts in storage order.
205 @param[in] lengths_xyz Physical periods, shared by source and target, in Cartesian order.
206 @param[in] source_first_xyz Position of the first source sample on each axis, relative
207 to the box origin.
208 @param[in] target_first_xyz Position of the first target sample on each axis.
209 @param[in] filter_spec Optional filter mapping for `filter_transfer()`.
210 @return Real target samples `[k, j, i, component]`.
211 """
212 numpy = require_numpy()
213 out = numpy.asarray(values, dtype=float)
214 for axis in range(3):
215 storage_axis = 2 - axis
216 out = _resample_axis(out, storage_axis, int(target_cells_kji[storage_axis]),
217 float(lengths_xyz[axis]),
218 float(target_first_xyz[axis]) - float(source_first_xyz[axis]))
219 if filter_spec and filter_spec.get("type", "none") != "none":
220 continuum, _discrete, _spacing = spectral_symbols(tuple(target_cells_kji), lengths_xyz)
221 transfer = filter_transfer(continuum, filter_spec)
222 coeff = numpy.fft.fftn(out, axes=(0, 1, 2))
223 out = numpy.fft.ifftn(coeff * transfer[..., None], axes=(0, 1, 2)).real
224 return out
validate_spectral_grid(nodes, transform_axes=(0, 1, 2), subject="spectra require")
Validate the uniform axis-aligned Cartesian grid an FFT on periodic axes requires.
prune_incompatible_python_site_paths(paths)
Remove site-package paths for a different Python major/minor version.
fourier_resample(values, target_cells_kji, lengths_xyz, source_first_xyz, target_first_xyz, filter_spec=None)
Resample a triply periodic vector field onto another uniform grid, optionally filtered.
spectral_symbols(cells_kji, lengths_xyz)
Build continuum and centered-discrete Fourier symbols.
_resample_axis(values, storage_axis, target_count, length, shift)
Move one periodic axis of an array of samples to another uniform resolution.
drop_imported_package(str package_name)
Remove a failed/partial import package tree from sys.modules.
filter_transfer(continuum_symbols, filter_spec)
Transfer function of a resampling filter on the target grid's wavenumbers.
require_numpy()
Import NumPy on first use, retrying without other Pythons' site-packages.
Head of a generic C-style linked list.
Definition variables.h:504