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.
99 km, jm, im, _ = nodes.shape
100 cells = (km - 1, jm - 1, im - 1)
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 "
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)
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.
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)
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
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`.
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
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`.
181 kind = filter_spec.get(
"type",
"none")
182 kx, ky, kz = continuum_symbols
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)
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}.")
196def fourier_resample(values, target_cells_kji, lengths_xyz, source_first_xyz, target_first_xyz,
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
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]`.
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)
222 coeff = numpy.fft.fftn(out, axes=(0, 1, 2))
223 out = numpy.fft.ifftn(coeff * transfer[...,
None], axes=(0, 1, 2)).real
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.
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.
_resample_axis(values, storage_axis, target_count, length, shift)
Move one periodic axis of an array of samples to another uniform resolution.