enufft 1.0.0__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.
enufft/__init__.py ADDED
@@ -0,0 +1,77 @@
1
+ """Elastic non-uniform FFT and elastic mode selection."""
2
+
3
+ # Adapted from Elastic Non Uniform FFT by Tridib Banerjee
4
+ # Original research code by Dr T Banerjee
5
+ # Apache 2.0 license terms are provided in LICENSE
6
+
7
+ __version__ = "1.0.0"
8
+
9
+ from .analysis import (
10
+ ENUFFTResult,
11
+ PolygonNUFFTResult,
12
+ dominant_mode_pair,
13
+ enufft_on_polygon,
14
+ mode_values,
15
+ nufft_on_polygon,
16
+ reconstruct_at_points,
17
+ spectrum_amplitudes,
18
+ )
19
+ from .ems import (
20
+ EMSConfig,
21
+ EMSResult,
22
+ SparseModeSelection,
23
+ count_signed_nonzero_modes,
24
+ count_unique_mode_pairs,
25
+ elastic_mode_selection,
26
+ ems_retain_count,
27
+ select_sparse_conjugate_modes,
28
+ )
29
+ from .geometry import (
30
+ AnalysisWindow,
31
+ WindowConfig,
32
+ build_analysis_window,
33
+ points_in_polygon,
34
+ points_to_window_coordinates,
35
+ polygon_area,
36
+ )
37
+ from .nufft import (
38
+ NUFFTConfig,
39
+ build_auxiliary_grid,
40
+ compute_direct_dft_coefficients,
41
+ compute_nufft_coefficients,
42
+ compute_nufft_for_kernels,
43
+ )
44
+ from .synthetic import generate_dem_points, irregular_orography
45
+
46
+ __all__ = [
47
+ "__version__",
48
+ "AnalysisWindow",
49
+ "EMSConfig",
50
+ "EMSResult",
51
+ "ENUFFTResult",
52
+ "NUFFTConfig",
53
+ "PolygonNUFFTResult",
54
+ "SparseModeSelection",
55
+ "WindowConfig",
56
+ "build_analysis_window",
57
+ "build_auxiliary_grid",
58
+ "compute_direct_dft_coefficients",
59
+ "compute_nufft_coefficients",
60
+ "compute_nufft_for_kernels",
61
+ "count_signed_nonzero_modes",
62
+ "count_unique_mode_pairs",
63
+ "dominant_mode_pair",
64
+ "elastic_mode_selection",
65
+ "ems_retain_count",
66
+ "enufft_on_polygon",
67
+ "generate_dem_points",
68
+ "irregular_orography",
69
+ "mode_values",
70
+ "nufft_on_polygon",
71
+ "points_in_polygon",
72
+ "points_to_window_coordinates",
73
+ "polygon_area",
74
+ "reconstruct_at_points",
75
+ "select_sparse_conjugate_modes",
76
+ "spectrum_amplitudes",
77
+ ]
enufft/analysis.py ADDED
@@ -0,0 +1,328 @@
1
+ """High-level polygon NUFFT and ENUFFT workflows."""
2
+
3
+ # Adapted from Elastic Non Uniform FFT by Tridib Banerjee
4
+ # Original research code by Dr T Banerjee
5
+ # Apache 2.0 license terms are provided in LICENSE
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Literal
11
+
12
+ import numpy as np
13
+
14
+ from .ems import EMSConfig, SparseModeSelection, select_sparse_conjugate_modes
15
+ from .geometry import (
16
+ AnalysisWindow,
17
+ WindowConfig,
18
+ build_analysis_window,
19
+ compute_local_voronoi_weights,
20
+ points_to_window_coordinates,
21
+ )
22
+ from .nufft import NUFFTConfig, compute_direct_dft_coefficients, compute_nufft_coefficients
23
+
24
+
25
+ WeightKind = Literal["uniform", "voronoi", None]
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class PolygonNUFFTResult:
30
+ """NUFFT result for a polygon-prescribed square analysis window."""
31
+
32
+ spectrum: np.ndarray
33
+ m_values: np.ndarray
34
+ n_values: np.ndarray
35
+ window: AnalysisWindow
36
+ mask: np.ndarray
37
+ local_points: np.ndarray
38
+ values: np.ndarray
39
+ weights: np.ndarray | None
40
+ config: NUFFTConfig
41
+
42
+ @property
43
+ def sample_count(self) -> int:
44
+ return int(self.values.size)
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class ENUFFTResult:
49
+ """ENUFFT result: raw NUFFT spectrum plus EMS sparse selection."""
50
+
51
+ raw: PolygonNUFFTResult
52
+ selection: SparseModeSelection
53
+
54
+ @property
55
+ def raw_spectrum(self) -> np.ndarray:
56
+ return self.raw.spectrum
57
+
58
+ @property
59
+ def spectrum(self) -> np.ndarray:
60
+ return self.selection.spectrum
61
+
62
+ @property
63
+ def selected_modes(self) -> np.ndarray:
64
+ return self.selection.selected_modes
65
+
66
+ @property
67
+ def mode_pair_count(self) -> int:
68
+ return self.selection.mode_pair_count
69
+
70
+ @property
71
+ def signed_mode_count(self) -> int:
72
+ return self.selection.signed_mode_count
73
+
74
+ @property
75
+ def power_retained(self) -> float:
76
+ return self.selection.power_retained
77
+
78
+ @property
79
+ def window(self) -> AnalysisWindow:
80
+ return self.raw.window
81
+
82
+ @property
83
+ def m_values(self) -> np.ndarray:
84
+ return self.raw.m_values
85
+
86
+ @property
87
+ def n_values(self) -> np.ndarray:
88
+ return self.raw.n_values
89
+
90
+ def reconstruct(self, points=None, sparse: bool = True) -> np.ndarray:
91
+ """Reconstruct the selected or raw spectrum at local or original points."""
92
+
93
+ if points is None:
94
+ local_points = self.raw.local_points
95
+ else:
96
+ local_points = np.asarray(points, dtype=float)
97
+ if local_points.ndim != 2 or local_points.shape[1] != 2:
98
+ raise ValueError("points must have shape (N, 2)")
99
+ spectrum = self.spectrum if sparse else self.raw_spectrum
100
+ return reconstruct_at_points(
101
+ spectrum,
102
+ local_points[:, 0],
103
+ local_points[:, 1],
104
+ self.m_values,
105
+ self.n_values,
106
+ self.window.Lx,
107
+ self.window.Ly,
108
+ )
109
+
110
+
111
+ def mode_values(mode_limit: int) -> np.ndarray:
112
+ """Return signed integer modes from ``-mode_limit`` to ``mode_limit``."""
113
+
114
+ mode_limit = int(mode_limit)
115
+ if mode_limit < 0:
116
+ raise ValueError("mode_limit must be nonnegative")
117
+ return np.arange(-mode_limit, mode_limit + 1, dtype=int)
118
+
119
+
120
+ def _mode_arrays(mode_limit: int, m_values=None, n_values=None) -> tuple[np.ndarray, np.ndarray]:
121
+ if m_values is None:
122
+ m_values = mode_values(mode_limit)
123
+ else:
124
+ m_values = np.asarray(m_values, dtype=int)
125
+ if n_values is None:
126
+ n_values = mode_values(mode_limit)
127
+ else:
128
+ n_values = np.asarray(n_values, dtype=int)
129
+ return m_values, n_values
130
+
131
+
132
+ def _finite_mask(points, values) -> np.ndarray:
133
+ points = np.asarray(points, dtype=float)
134
+ values = np.asarray(values, dtype=float)
135
+ return np.isfinite(points).all(axis=1) & np.isfinite(values)
136
+
137
+
138
+ def nufft_on_polygon(
139
+ points,
140
+ values,
141
+ polygon,
142
+ mode_limit: int,
143
+ window_config: WindowConfig | None = None,
144
+ nufft_config: NUFFTConfig | None = None,
145
+ weight_type: WeightKind = "uniform",
146
+ m_values=None,
147
+ n_values=None,
148
+ direct: bool = False,
149
+ ) -> PolygonNUFFTResult:
150
+ """Compute a coefficient block from samples selected by a polygon window."""
151
+
152
+ points = np.asarray(points, dtype=float)
153
+ values = np.asarray(values, dtype=float)
154
+ if points.ndim != 2 or points.shape[1] != 2:
155
+ raise ValueError("points must have shape (N, 2)")
156
+ if values.ndim != 1 or values.size != points.shape[0]:
157
+ raise ValueError("values must be one-dimensional and match points")
158
+ nufft_config = NUFFTConfig() if nufft_config is None else nufft_config
159
+ nufft_config.validate()
160
+ m_values, n_values = _mode_arrays(mode_limit, m_values, n_values)
161
+
162
+ finite = _finite_mask(points, values)
163
+ mask, window = build_analysis_window(points, polygon, window_config)
164
+ active = mask & finite
165
+ if int(np.sum(active)) < 3:
166
+ raise ValueError("analysis window contains fewer than three finite samples")
167
+ local_x, local_y = points_to_window_coordinates(points[active], window)
168
+ local_points = np.column_stack([local_x, local_y])
169
+ local_values = values[active]
170
+ if weight_type in {None, "uniform"}:
171
+ weights = None
172
+ elif weight_type == "voronoi":
173
+ weights = compute_local_voronoi_weights(
174
+ local_x,
175
+ local_y,
176
+ window.Lx,
177
+ window.Ly,
178
+ window=window,
179
+ )
180
+ else:
181
+ raise ValueError("weight_type must be 'uniform', 'voronoi', or None")
182
+
183
+ if direct:
184
+ spectrum = compute_direct_dft_coefficients(
185
+ local_x,
186
+ local_y,
187
+ local_values,
188
+ m_values,
189
+ n_values,
190
+ window.Lx,
191
+ window.Ly,
192
+ weights,
193
+ )
194
+ else:
195
+ spectrum = compute_nufft_coefficients(
196
+ local_x,
197
+ local_y,
198
+ local_values,
199
+ m_values,
200
+ n_values,
201
+ window.Lx,
202
+ window.Ly,
203
+ nufft_config.oversample,
204
+ nufft_config.kernel_half_width,
205
+ nufft_config.kernel_beta,
206
+ nufft_config.kernel_type,
207
+ weights,
208
+ )
209
+ return PolygonNUFFTResult(
210
+ spectrum=spectrum,
211
+ m_values=m_values,
212
+ n_values=n_values,
213
+ window=window,
214
+ mask=active,
215
+ local_points=local_points,
216
+ values=local_values,
217
+ weights=weights,
218
+ config=nufft_config,
219
+ )
220
+
221
+
222
+ def enufft_on_polygon(
223
+ points,
224
+ values,
225
+ polygon,
226
+ mode_limit: int,
227
+ window_config: WindowConfig | None = None,
228
+ nufft_config: NUFFTConfig | None = None,
229
+ ems_config: EMSConfig | None = None,
230
+ weight_type: WeightKind = "uniform",
231
+ m_values=None,
232
+ n_values=None,
233
+ direct: bool = False,
234
+ ) -> ENUFFTResult:
235
+ """Compute NUFFT coefficients on a polygon-prescribed square and apply EMS."""
236
+
237
+ raw = nufft_on_polygon(
238
+ points,
239
+ values,
240
+ polygon,
241
+ mode_limit,
242
+ window_config=window_config,
243
+ nufft_config=nufft_config,
244
+ weight_type=weight_type,
245
+ m_values=m_values,
246
+ n_values=n_values,
247
+ direct=direct,
248
+ )
249
+ selection = select_sparse_conjugate_modes(
250
+ raw.spectrum,
251
+ raw.m_values,
252
+ raw.n_values,
253
+ config=EMSConfig(k_max=mode_limit) if ems_config is None else ems_config,
254
+ )
255
+ return ENUFFTResult(raw=raw, selection=selection)
256
+
257
+
258
+ def reconstruct_at_points(
259
+ spectrum,
260
+ x_values,
261
+ y_values,
262
+ m_values,
263
+ n_values,
264
+ domain_length_x: float,
265
+ domain_length_y: float,
266
+ ) -> np.ndarray:
267
+ """Evaluate an inverse Fourier series at arbitrary local coordinates."""
268
+
269
+ spectrum = np.asarray(spectrum)
270
+ x_values = np.asarray(x_values, dtype=float)
271
+ y_values = np.asarray(y_values, dtype=float)
272
+ m_values = np.asarray(m_values, dtype=int)
273
+ n_values = np.asarray(n_values, dtype=int)
274
+ if x_values.shape != y_values.shape:
275
+ raise ValueError("x_values and y_values must have the same shape")
276
+ if spectrum.shape != (m_values.size, n_values.size):
277
+ raise ValueError("spectrum shape must be (len(m_values), len(n_values))")
278
+
279
+ field = np.zeros(x_values.size, dtype=complex)
280
+ for m_index, m_mode in enumerate(m_values):
281
+ phase_x = 2.0 * np.pi * int(m_mode) * x_values.ravel() / domain_length_x
282
+ for n_index, n_mode in enumerate(n_values):
283
+ coeff = spectrum[m_index, n_index]
284
+ if np.abs(coeff) <= 1e-15:
285
+ continue
286
+ phase = phase_x + 2.0 * np.pi * int(n_mode) * y_values.ravel() / domain_length_y
287
+ field += coeff * np.exp(1j * phase)
288
+ field = field.reshape(x_values.shape)
289
+ return np.real_if_close(field, tol=1000).real
290
+
291
+
292
+ def spectrum_amplitudes(spectrum) -> np.ndarray:
293
+ """Return coefficient magnitudes sorted from largest to smallest."""
294
+
295
+ return np.sort(np.abs(np.asarray(spectrum)).ravel())[::-1]
296
+
297
+
298
+ def dominant_mode_pair(spectrum, m_values, n_values) -> tuple[int, int, float]:
299
+ """Return the strongest non-DC canonical mode pair and amplitude."""
300
+
301
+ spectrum = np.asarray(spectrum)
302
+ m_values = np.asarray(m_values, dtype=int)
303
+ n_values = np.asarray(n_values, dtype=int)
304
+ best_pair = (0, 0)
305
+ best_amp = 0.0
306
+ m_lookup = {int(value): index for index, value in enumerate(m_values)}
307
+ n_lookup = {int(value): index for index, value in enumerate(n_values)}
308
+ for m_mode in m_values:
309
+ for n_mode in n_values:
310
+ m_mode = int(m_mode)
311
+ n_mode = int(n_mode)
312
+ if m_mode == 0 and n_mode == 0:
313
+ continue
314
+ if m_mode < 0 or (m_mode == 0 and n_mode < 0):
315
+ continue
316
+ amp = float(
317
+ np.sqrt(
318
+ (
319
+ np.abs(spectrum[m_lookup[m_mode], n_lookup[n_mode]]) ** 2
320
+ + np.abs(spectrum[m_lookup[-m_mode], n_lookup[-n_mode]]) ** 2
321
+ )
322
+ / 2.0
323
+ )
324
+ )
325
+ if amp > best_amp:
326
+ best_pair = (m_mode, n_mode)
327
+ best_amp = amp
328
+ return best_pair[0], best_pair[1], best_amp