structure-factor-v2 2.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.
- structure_factor_v2/__init__.py +40 -0
- structure_factor_v2/backend.py +219 -0
- structure_factor_v2/lattices.py +213 -0
- structure_factor_v2/structure_factor.py +300 -0
- structure_factor_v2/torus.py +86 -0
- structure_factor_v2/viz.py +199 -0
- structure_factor_v2-2.0.0.dist-info/METADATA +206 -0
- structure_factor_v2-2.0.0.dist-info/RECORD +10 -0
- structure_factor_v2-2.0.0.dist-info/WHEEL +4 -0
- structure_factor_v2-2.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
structure_factor_v2: structure factor S(k) of point sets in the unit cube [0, 1)^D, and plots.
|
|
3
|
+
|
|
4
|
+
>>> import structure_factor_v2 as sf
|
|
5
|
+
>>> points = sf.jittered_lattice(10_000, 2) # a hyperuniform test pattern
|
|
6
|
+
>>> kint, S = sf.structure_factor(points) # raw scattering intensity
|
|
7
|
+
>>> sf.plot_structure_factor(points) # log-log plot, radial average
|
|
8
|
+
>>> sf.plot_structure_factor(points, trust_boundary=False) # non-periodic window: Kaiser taper
|
|
9
|
+
>>> sf.plot(points) # scatter plot of the points
|
|
10
|
+
>>> sf.plot_structure_factor(points, backend="keops", precision="float64")
|
|
11
|
+
|
|
12
|
+
Layout
|
|
13
|
+
------
|
|
14
|
+
structure_factor estimation of S(k): scattering intensity, Kaiser taper, radial averages
|
|
15
|
+
viz plot (point sets), plot_structure_factor
|
|
16
|
+
lattices Korobov, jittered and curled lattices (test patterns, warm starts)
|
|
17
|
+
torus integer wave vectors of Z^D (grids, balls, isotropic sampling)
|
|
18
|
+
backend Fourier sums: finufft, cufinufft, keops, torch, numpy, cupy; check_gpu
|
|
19
|
+
|
|
20
|
+
Tunable constants live in `structure_factor_v2.CONFIG` (editable in place).
|
|
21
|
+
"""
|
|
22
|
+
from .backend import BACKENDS, available_backends, check_gpu
|
|
23
|
+
from .lattices import curled_lattice, jittered_lattice, korobov_lattice
|
|
24
|
+
from .structure_factor import (
|
|
25
|
+
CFG as CONFIG,
|
|
26
|
+
auto_beta,
|
|
27
|
+
structure_factor,
|
|
28
|
+
structure_factor_and_average,
|
|
29
|
+
tapered_kmin,
|
|
30
|
+
)
|
|
31
|
+
from .viz import plot, plot_structure_factor
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"structure_factor", "structure_factor_and_average", "tapered_kmin", "auto_beta",
|
|
35
|
+
"plot", "plot_structure_factor",
|
|
36
|
+
"jittered_lattice", "curled_lattice", "korobov_lattice",
|
|
37
|
+
"check_gpu", "available_backends", "BACKENDS", "CONFIG",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
__version__ = "2.0.0"
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Backends of the Fourier sums F(n) = sum_j c_j exp(2i pi n.x_j), for points x (N, D) in
|
|
3
|
+
[0, 1)^D, real weights c (N,) and integer wave vectors n (M, D).
|
|
4
|
+
|
|
5
|
+
backend method dimensions accuracy
|
|
6
|
+
"finufft" type-1 non-uniform FFT, CPU D <= 3 nufft_tolerance
|
|
7
|
+
"cufinufft" type-1 non-uniform FFT, GPU (+ cupy) D <= 3 nufft_tolerance
|
|
8
|
+
"keops" direct sums, pykeops (GPU if available) any exact
|
|
9
|
+
"torch" direct sums, torch (cuda if available) any exact
|
|
10
|
+
"numpy" direct sums, numpy, chunked any exact
|
|
11
|
+
"cupy" direct sums, cupy, chunked any exact
|
|
12
|
+
|
|
13
|
+
"auto" (default): D <= 3 -> cufinufft if it works, else finufft; D >= 4 -> cupy if it works,
|
|
14
|
+
else numpy. device="cpu" restricts "auto" to finufft / numpy. keops and torch are optional
|
|
15
|
+
and only used when asked for. `check_gpu` reports what is usable.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib
|
|
20
|
+
import shutil
|
|
21
|
+
import subprocess
|
|
22
|
+
from functools import lru_cache
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
|
|
26
|
+
BACKENDS = ("finufft", "cufinufft", "keops", "torch", "numpy", "cupy")
|
|
27
|
+
NUFFT_BACKENDS = ("finufft", "cufinufft")
|
|
28
|
+
NUFFT_MAX_DIM = 3
|
|
29
|
+
PRECISIONS = ("float32", "float64")
|
|
30
|
+
AUTO_NUFFT_TOLERANCE = {"float32": 1e-5, "float64": 1e-12}
|
|
31
|
+
CHUNK_ELEMS = 8_000_000 # direct sums: (points x wave vectors) per chunk
|
|
32
|
+
NUFFT_CHUNK = 400_000 # points per 3D NUFFT call
|
|
33
|
+
|
|
34
|
+
_MODULES = {
|
|
35
|
+
"finufft": ("finufft",),
|
|
36
|
+
"cufinufft": ("cufinufft", "cupy"),
|
|
37
|
+
"keops": ("pykeops.numpy",),
|
|
38
|
+
"torch": ("torch",),
|
|
39
|
+
"numpy": ("numpy",),
|
|
40
|
+
"cupy": ("cupy",),
|
|
41
|
+
}
|
|
42
|
+
_PIP = {
|
|
43
|
+
"finufft": "pip install finufft",
|
|
44
|
+
"cufinufft": "pip install cufinufft cupy-cuda12x (or structure-factor-v2[gpu12])",
|
|
45
|
+
"keops": "pip install pykeops",
|
|
46
|
+
"torch": "pip install torch",
|
|
47
|
+
"numpy": "pip install numpy",
|
|
48
|
+
"cupy": "pip install cupy-cuda12x",
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ── Loading and selection ─────────────────────────────────────────────────────
|
|
53
|
+
|
|
54
|
+
@lru_cache(maxsize=None)
|
|
55
|
+
def _try_load(backend: str):
|
|
56
|
+
"""(module, None) if the backend imports and works (tested once), else (None, error)."""
|
|
57
|
+
try:
|
|
58
|
+
mods = [importlib.import_module(m) for m in _MODULES[backend]]
|
|
59
|
+
if backend in ("cufinufft", "cupy"):
|
|
60
|
+
cp = mods[-1]
|
|
61
|
+
if cp.cuda.runtime.getDeviceCount() < 1:
|
|
62
|
+
raise RuntimeError("no CUDA device found")
|
|
63
|
+
if backend == "keops": # pykeops often imports where it cannot compile
|
|
64
|
+
x = np.random.rand(10, 3).astype(np.float32)
|
|
65
|
+
LazyTensor = mods[0].LazyTensor
|
|
66
|
+
((LazyTensor(x[:, None, :]) - LazyTensor(x[None, :, :])) ** 2).sum(-1).sum_reduction(axis=1)
|
|
67
|
+
return mods[0], None
|
|
68
|
+
except Exception as exc: # noqa: BLE001 (any failure means "unusable")
|
|
69
|
+
return None, exc
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _load(backend: str):
|
|
73
|
+
mod, err = _try_load(backend)
|
|
74
|
+
if mod is None:
|
|
75
|
+
raise ImportError(f"structure_factor_v2: backend {backend!r} is not available "
|
|
76
|
+
f"({err}). Install it with `{_PIP[backend]}`.") from None
|
|
77
|
+
return mod
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def is_available(backend: str) -> bool:
|
|
81
|
+
return _try_load(backend)[0] is not None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def available_backends(D: int | None = None) -> list:
|
|
85
|
+
"""Backends that import and work (and, if D is given, that support dimension D)."""
|
|
86
|
+
out = [b for b in BACKENDS if is_available(b)]
|
|
87
|
+
if D is not None and D > NUFFT_MAX_DIM:
|
|
88
|
+
out = [b for b in out if b not in NUFFT_BACKENDS]
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def resolve_backend(backend: str, D: int, device: str = "auto") -> str:
|
|
93
|
+
"""The backend actually used: checks a named one, picks one for "auto"."""
|
|
94
|
+
if backend == "auto":
|
|
95
|
+
gpu = device.lower() in ("auto", "gpu", "cuda")
|
|
96
|
+
if D <= NUFFT_MAX_DIM:
|
|
97
|
+
return "cufinufft" if gpu and is_available("cufinufft") else "finufft"
|
|
98
|
+
return "cupy" if gpu and is_available("cupy") else "numpy"
|
|
99
|
+
if backend not in BACKENDS:
|
|
100
|
+
raise ValueError(f"unknown backend {backend!r}, expected 'auto' or one of {BACKENDS}")
|
|
101
|
+
if backend in NUFFT_BACKENDS and D > NUFFT_MAX_DIM:
|
|
102
|
+
raise ValueError(f"the {backend} backend only supports D <= {NUFFT_MAX_DIM} (got D={D})")
|
|
103
|
+
_load(backend)
|
|
104
|
+
return backend
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def resolve_precision(precision: str) -> str:
|
|
108
|
+
precision = "float64" if precision in ("float64", "double") else precision
|
|
109
|
+
if precision not in PRECISIONS:
|
|
110
|
+
raise ValueError(f"precision must be one of {PRECISIONS}, got {precision!r}")
|
|
111
|
+
return precision
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def resolve_tolerance(nufft_tolerance, precision: str) -> float:
|
|
115
|
+
if isinstance(nufft_tolerance, str):
|
|
116
|
+
if nufft_tolerance != "auto":
|
|
117
|
+
raise ValueError(f"nufft_tolerance must be a positive float or 'auto', got {nufft_tolerance!r}")
|
|
118
|
+
return AUTO_NUFFT_TOLERANCE[precision]
|
|
119
|
+
if not nufft_tolerance > 0:
|
|
120
|
+
raise ValueError(f"nufft_tolerance must be positive, got {nufft_tolerance!r}")
|
|
121
|
+
return float(nufft_tolerance)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _real(precision):
|
|
125
|
+
return np.float64 if precision == "float64" else np.float32
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _complex(precision):
|
|
129
|
+
return np.complex128 if precision == "float64" else np.complex64
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
# ── Fourier sums ──────────────────────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
def nufft_grid_sums(pts, c, n_modes: int, backend: str, precision: str, tol: float) -> np.ndarray:
|
|
135
|
+
"""F on the centred cube of n_modes^D modes (finufft modeord=0 order), flattened, by a
|
|
136
|
+
type-1 NUFFT ("finufft" or "cufinufft"). Returns complex128 (n_modes^D,)."""
|
|
137
|
+
nufft = _load(backend)
|
|
138
|
+
if backend == "cufinufft":
|
|
139
|
+
import cupy as xp
|
|
140
|
+
to_np = xp.asnumpy
|
|
141
|
+
else:
|
|
142
|
+
xp, to_np = np, np.asarray
|
|
143
|
+
N, D = pts.shape
|
|
144
|
+
x = [xp.asarray(np.ascontiguousarray(2.0 * np.pi * pts[:, d], dtype=_real(precision)))
|
|
145
|
+
for d in range(D)]
|
|
146
|
+
cc = xp.asarray(np.ascontiguousarray(c, dtype=_complex(precision)))
|
|
147
|
+
shape = (n_modes,) * D
|
|
148
|
+
fn = getattr(nufft, f"nufft{D}d1")
|
|
149
|
+
if D < 3:
|
|
150
|
+
fk = fn(*x, cc, n_modes if D == 1 else shape, eps=tol, isign=1)
|
|
151
|
+
else:
|
|
152
|
+
fk = xp.zeros(shape, dtype=_complex(precision))
|
|
153
|
+
for s in range(0, N, NUFFT_CHUNK):
|
|
154
|
+
fk += fn(*[a[s:s + NUFFT_CHUNK].copy() for a in x], cc[s:s + NUFFT_CHUNK].copy(),
|
|
155
|
+
shape, eps=tol, isign=1)
|
|
156
|
+
return to_np(fk).ravel().astype(np.complex128)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def direct_sums(pts, c, kint, backend: str, precision: str) -> np.ndarray:
|
|
160
|
+
"""F on the wave vectors kint (M, D) by direct sums ("keops", "torch", "numpy", "cupy").
|
|
161
|
+
Returns complex128 (M,)."""
|
|
162
|
+
real = _real(precision)
|
|
163
|
+
pts = np.ascontiguousarray(pts, dtype=real)
|
|
164
|
+
c = np.ascontiguousarray(c, dtype=real)
|
|
165
|
+
k2pi = np.ascontiguousarray(2.0 * np.pi * np.asarray(kint), dtype=real)
|
|
166
|
+
if backend == "keops":
|
|
167
|
+
LazyTensor = _load("keops").LazyTensor
|
|
168
|
+
phase = (LazyTensor(pts[:, None, :]) * LazyTensor(k2pi[None, :, :])).sum(-1, keepdim=True)
|
|
169
|
+
w = LazyTensor(c.reshape(-1, 1, 1))
|
|
170
|
+
re = np.asarray((w * phase.cos()).sum(0)).ravel()
|
|
171
|
+
im = np.asarray((w * phase.sin()).sum(0)).ravel()
|
|
172
|
+
return re.astype(np.float64) + 1j * im.astype(np.float64)
|
|
173
|
+
|
|
174
|
+
if backend == "torch":
|
|
175
|
+
torch = _load("torch")
|
|
176
|
+
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
177
|
+
dt = getattr(torch, np.dtype(real).name)
|
|
178
|
+
asx = lambda a: torch.as_tensor(a, dtype=dt, device=dev) # noqa: E731
|
|
179
|
+
to_np = lambda a: a.cpu().numpy() # noqa: E731
|
|
180
|
+
cos, sin = torch.cos, torch.sin
|
|
181
|
+
elif backend in ("numpy", "cupy"):
|
|
182
|
+
xp = _load(backend)
|
|
183
|
+
asx = lambda a: xp.asarray(a, dtype=real) # noqa: E731
|
|
184
|
+
to_np = xp.asnumpy if backend == "cupy" else np.asarray
|
|
185
|
+
cos, sin = xp.cos, xp.sin
|
|
186
|
+
else:
|
|
187
|
+
raise ValueError(f"{backend!r} is not a direct-sum backend")
|
|
188
|
+
|
|
189
|
+
kt, ct = asx(k2pi), asx(c)
|
|
190
|
+
M = len(k2pi)
|
|
191
|
+
re, im = asx(np.zeros(M)), asx(np.zeros(M))
|
|
192
|
+
chunk = max(1, CHUNK_ELEMS // max(M, 1))
|
|
193
|
+
for s in range(0, len(pts), chunk):
|
|
194
|
+
phase = asx(pts[s:s + chunk]) @ kt.T # (n, M)
|
|
195
|
+
re += ct[s:s + chunk] @ cos(phase)
|
|
196
|
+
im += ct[s:s + chunk] @ sin(phase)
|
|
197
|
+
return to_np(re).astype(np.float64) + 1j * to_np(im).astype(np.float64)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
# ── Diagnostic ────────────────────────────────────────────────────────────────
|
|
201
|
+
|
|
202
|
+
def check_gpu() -> None:
|
|
203
|
+
"""Print which backends work: the GPU stack (CuPy, cuFINUFFT) and the optional KeOps, torch."""
|
|
204
|
+
print("GPU support diagnostic\n----------------------")
|
|
205
|
+
print("NVIDIA GPU detected." if _nvidia_gpu() else "No NVIDIA GPU detected.")
|
|
206
|
+
for backend in ("cupy", "cufinufft", "keops", "torch"):
|
|
207
|
+
mod, err = _try_load(backend)
|
|
208
|
+
print(f"{backend}: {'OK' if mod is not None else f'unavailable ({err})'}")
|
|
209
|
+
print(f"auto backend: D <= 3 -> {resolve_backend('auto', 2)}, D >= 4 -> {resolve_backend('auto', 4)}")
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _nvidia_gpu() -> bool:
|
|
213
|
+
if shutil.which("nvidia-smi") is None:
|
|
214
|
+
return False
|
|
215
|
+
try:
|
|
216
|
+
out = subprocess.run(["nvidia-smi", "-L"], capture_output=True, text=True, timeout=5)
|
|
217
|
+
return out.returncode == 0 and bool(out.stdout.strip())
|
|
218
|
+
except (subprocess.SubprocessError, OSError):
|
|
219
|
+
return False
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Lattice point sets in [0, 1)^D: cheap, well spread, and a quick reference for the structure
|
|
3
|
+
factor (a jittered lattice is hyperuniform; an unjittered one is a crystal, S = 0 except on
|
|
4
|
+
its Bragg peaks).
|
|
5
|
+
|
|
6
|
+
korobov_lattice rank-1 lattice with the best spectral test among random generators
|
|
7
|
+
jittered_lattice Korobov lattice, randomly shifted, every point uniform in its own cell
|
|
8
|
+
curled_lattice Korobov lattice deformed by a random divergence-free (curl noise) flow
|
|
9
|
+
|
|
10
|
+
>>> import structure_factor_v2 as sf
|
|
11
|
+
>>> x = sf.jittered_lattice(10_000, 2)
|
|
12
|
+
>>> sf.plot_structure_factor(x)
|
|
13
|
+
|
|
14
|
+
Korobov lattice: x_t = t z / N mod 1 with z = (1, a, a^2, ..., a^(D-1)) mod N. The generator a
|
|
15
|
+
maximises the length of the shortest non-zero vector of the dual lattice {h : h.z = 0 mod N},
|
|
16
|
+
estimated by an LLL reduction (O(D^3) per candidate; for D <= 6 its approximation factor is
|
|
17
|
+
<= 2.37, so the first reduced vector is virtually always the shortest).
|
|
18
|
+
Sloan & Joe (1994), Lattice Methods for Multiple Integration.
|
|
19
|
+
|
|
20
|
+
Jittered lattice: each point is moved uniformly in a fundamental cell P of the lattice L (the
|
|
21
|
+
parallelepiped of an LLL-reduced basis, volume 1/N). The translates of P tile the torus, so the
|
|
22
|
+
characteristic function of the jitter vanishes on the dual lattice L* (origin excluded): the
|
|
23
|
+
Bragg peaks disappear and the expected structure factor is exactly S(k) = 1 - |phi_P(k)|^2 ~ k^2.
|
|
24
|
+
(Jittering
|
|
25
|
+
in an axis-aligned cube of side N^(-1/D) instead is not a cell of L: Bragg peaks of height
|
|
26
|
+
~ N |phi_cube(h)|^2 survive at the shortest dual vectors h, near k = 1.)
|
|
27
|
+
|
|
28
|
+
Curled lattice: curl noise jittering (Bærentzen, Frisvad & Martínez 2023, reference below):
|
|
29
|
+
the lattice points are moved along the streamlines of a random divergence-free vector field.
|
|
30
|
+
The flow preserves volume, so the points stay well separated, while the lattice anisotropy
|
|
31
|
+
(Bragg peaks) is smeared out: the result is a blue noise point set. Two departures from the
|
|
32
|
+
original method:
|
|
33
|
+
- the starting lattice is our Korobov lattice instead of a triangular (2D) / cubic (3D) grid.
|
|
34
|
+
The method only needs well spread starting points on a lattice, and a good Korobov lattice
|
|
35
|
+
is close to the densest lattice packing (its generator maximises the shortest dual vector);
|
|
36
|
+
- the field is a sum of random Fourier modes u_m cos(2 pi k_m.x + phase_m) with integer
|
|
37
|
+
wave vectors k_m (|k_m| ~ N^(1/D) / noise_scale) and polarisations u_m orthogonal to k_m,
|
|
38
|
+
instead of the curl of a Perlin / sparse convolution noise. Each mode is exactly
|
|
39
|
+
divergence-free (in 2D it is the curl of a stream function, in 3D of a vector potential),
|
|
40
|
+
in any dimension D, and exactly periodic on the torus: no boundary effect.
|
|
41
|
+
The displacement is one RK4 step along the field (the "direct method" of the paper).
|
|
42
|
+
|
|
43
|
+
Reference
|
|
44
|
+
---------
|
|
45
|
+
J. A. Bærentzen, J. R. Frisvad, and J. Martínez. Curl Noise Jittering. SIGGRAPH Asia 2023
|
|
46
|
+
Conference Papers, article 88, 2023. https://doi.org/10.1145/3610548.3618163
|
|
47
|
+
Code: https://github.com/jonasmb/curlnoisejittering (AGPL-3.0; not used here, the
|
|
48
|
+
implementation below is independent).
|
|
49
|
+
"""
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
from math import gcd
|
|
53
|
+
|
|
54
|
+
import numpy as np
|
|
55
|
+
from numpy.typing import NDArray
|
|
56
|
+
|
|
57
|
+
__all__ = ["korobov_lattice", "jittered_lattice", "curled_lattice"]
|
|
58
|
+
|
|
59
|
+
POINT_CHUNK = 50_000 # curled_lattice: points per evaluation of the field
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def jittered_lattice(N: int, D: int, seed=None, max_candidates: int | None = 100) -> NDArray:
|
|
63
|
+
"""
|
|
64
|
+
A Korobov lattice of N points, randomly translated, each point moved uniformly in its own
|
|
65
|
+
fundamental cell (LLL-reduced parallelepiped, see the module docstring): exactly one point
|
|
66
|
+
per cell, no Bragg peak. seed: int, numpy Generator or None.
|
|
67
|
+
"""
|
|
68
|
+
rng = np.random.default_rng(seed)
|
|
69
|
+
z = _korobov_generator(N, D, rng, max_candidates)
|
|
70
|
+
cell = _reduced_cell(z, N) # (D, D), rows: basis of L
|
|
71
|
+
x = _lattice_points(z, N) + rng.random(D) + rng.random((N, D)) @ cell
|
|
72
|
+
return x % 1.0
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def curled_lattice(N: int, D: int, noise_scale: float = 5.0, dt: float = 1.2, n_modes: int = 256,
|
|
76
|
+
bandwidth: float = 0.3, n_steps: int = 1, seed=None,
|
|
77
|
+
max_candidates: int | None = 100) -> NDArray:
|
|
78
|
+
"""
|
|
79
|
+
A Korobov lattice of N points, randomly shifted, then moved along a random periodic
|
|
80
|
+
divergence-free field (curl noise jittering, see the module docstring). Any D; tuned in
|
|
81
|
+
2D and 3D.
|
|
82
|
+
|
|
83
|
+
noise_scale : wavelength of the field, in lattice spacings N^(-1/D) (larger: smoother flow).
|
|
84
|
+
dt : length of the flow, in lattice spacings (RMS displacement ~ dt spacings).
|
|
85
|
+
Smaller keeps more of the lattice (Bragg peaks come back below ~0.8),
|
|
86
|
+
larger brings the points closer to each other.
|
|
87
|
+
n_modes : number of random Fourier modes of the field.
|
|
88
|
+
bandwidth : relative spread of |k_m| around N^(1/D) / noise_scale.
|
|
89
|
+
n_steps : RK4 steps (1: the paper's direct method; more: closer to the exact flow).
|
|
90
|
+
seed : int, numpy Generator or None.
|
|
91
|
+
"""
|
|
92
|
+
rng = np.random.default_rng(seed)
|
|
93
|
+
z = _korobov_generator(N, D, rng, max_candidates)
|
|
94
|
+
x = (_lattice_points(z, N) + rng.random(D)) % 1.0
|
|
95
|
+
k, u, phase = _solenoidal_modes(N, D, noise_scale, n_modes, bandwidth, rng)
|
|
96
|
+
h = dt * N ** (-1.0 / D) / n_steps
|
|
97
|
+
for s in range(0, N, POINT_CHUNK):
|
|
98
|
+
y = x[s:s + POINT_CHUNK]
|
|
99
|
+
for _ in range(n_steps):
|
|
100
|
+
a = h * _velocity(y, k, u, phase)
|
|
101
|
+
b = h * _velocity(y + a / 2, k, u, phase)
|
|
102
|
+
c = h * _velocity(y + b / 2, k, u, phase)
|
|
103
|
+
d = h * _velocity(y + c, k, u, phase)
|
|
104
|
+
y = y + (a + 2 * b + 2 * c + d) / 6
|
|
105
|
+
x[s:s + POINT_CHUNK] = y
|
|
106
|
+
return x % 1.0
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _solenoidal_modes(N: int, D: int, noise_scale: float, n_modes: int, bandwidth: float, rng):
|
|
110
|
+
"""Integer wave vectors k (M, D), amplitudes u (M, D) with u_m . k_m = 0, phases (M,);
|
|
111
|
+
the field sum_m u_m cos(2 pi k_m.x + phase_m) has unit RMS norm."""
|
|
112
|
+
k0 = N ** (1.0 / D) / noise_scale
|
|
113
|
+
dirs = rng.normal(size=(n_modes, D))
|
|
114
|
+
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
|
|
115
|
+
radii = k0 * np.abs(1.0 + bandwidth * rng.normal(size=(n_modes, 1)))
|
|
116
|
+
k = np.rint(radii * dirs)
|
|
117
|
+
k = k[np.any(k != 0, axis=1)]
|
|
118
|
+
if len(k) == 0:
|
|
119
|
+
raise ValueError(f"noise_scale={noise_scale} is too large for N={N}: no wave vector left")
|
|
120
|
+
u = rng.normal(size=k.shape)
|
|
121
|
+
u -= (u * k).sum(1, keepdims=True) / (k * k).sum(1, keepdims=True) * k # u_m orthogonal to k_m
|
|
122
|
+
u *= np.sqrt(2.0 / len(k)) / np.linalg.norm(u, axis=1, keepdims=True)
|
|
123
|
+
return k, u, rng.uniform(0.0, 2.0 * np.pi, len(k))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _velocity(x, k, u, phase):
|
|
127
|
+
"""sum_m u_m cos(2 pi k_m.x + phase_m), shape of x."""
|
|
128
|
+
return np.cos(2.0 * np.pi * (x @ k.T) + phase) @ u
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ── Korobov lattice ───────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
def korobov_lattice(N: int, D: int, shift: bool = True, seed=None,
|
|
134
|
+
max_candidates: int | None = 100) -> NDArray:
|
|
135
|
+
"""
|
|
136
|
+
N points of a Korobov lattice, generator chosen among max_candidates random ones (all if
|
|
137
|
+
None), with a random toroidal shift if `shift`. seed: int, numpy Generator or None
|
|
138
|
+
(reproducible for a given int).
|
|
139
|
+
"""
|
|
140
|
+
rng = np.random.default_rng(seed)
|
|
141
|
+
points = _lattice_points(_korobov_generator(N, D, rng, max_candidates), N)
|
|
142
|
+
if shift:
|
|
143
|
+
points = (points + rng.random(D)) % 1.0
|
|
144
|
+
return points
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _korobov_generator(N: int, D: int, rng, max_candidates: int | None) -> np.ndarray:
|
|
148
|
+
"""Best generator z among max_candidates random ones (all if None)."""
|
|
149
|
+
candidates = [a for a in range(2, N) if gcd(a, N) == 1]
|
|
150
|
+
if max_candidates is not None and len(candidates) > max_candidates:
|
|
151
|
+
candidates = sorted(rng.choice(candidates, size=max_candidates, replace=False))
|
|
152
|
+
best = max(candidates, key=lambda a: _shortest_dual_vector(_generator(a, N, D), N))
|
|
153
|
+
return _generator(int(best), N, D)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _lattice_points(z: np.ndarray, N: int) -> np.ndarray:
|
|
157
|
+
"""The N points t z / N mod 1."""
|
|
158
|
+
return (np.arange(N, dtype=np.float64)[:, None] * (z.astype(np.float64) / N)) % 1.0
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _reduced_cell(z: np.ndarray, N: int) -> np.ndarray:
|
|
162
|
+
"""LLL-reduced basis (rows) of the primal lattice L = Z z/N + Z^D, covolume 1/N."""
|
|
163
|
+
basis = N * np.eye(len(z), dtype=np.int64) # rows N z/N = z, N e_2, ..., N e_D
|
|
164
|
+
basis[0] = z # (z_0 = 1: generates N L)
|
|
165
|
+
return _lll(basis).astype(np.float64) / N
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _generator(a: int, N: int, D: int) -> np.ndarray:
|
|
169
|
+
"""z = (1, a, a^2, ..., a^(D-1)) mod N."""
|
|
170
|
+
z = np.empty(D, dtype=np.int64)
|
|
171
|
+
z[0] = 1
|
|
172
|
+
for j in range(1, D):
|
|
173
|
+
z[j] = (z[j - 1] * a) % N
|
|
174
|
+
return z
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _shortest_dual_vector(z: np.ndarray, N: int) -> float:
|
|
178
|
+
"""Length of the first LLL-reduced vector of the dual lattice {h : h.z = 0 mod N}."""
|
|
179
|
+
basis = np.eye(len(z), dtype=np.int64) # rows, determinant N
|
|
180
|
+
basis[0, 0] = N
|
|
181
|
+
basis[1:, 0] = (-z[1:]) % N
|
|
182
|
+
return float(np.linalg.norm(_lll(basis)[0]))
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _gram_schmidt(B: np.ndarray):
|
|
186
|
+
D = len(B)
|
|
187
|
+
B_star = np.zeros_like(B)
|
|
188
|
+
mu = np.zeros((D, D))
|
|
189
|
+
for i in range(D):
|
|
190
|
+
B_star[i] = B[i]
|
|
191
|
+
for j in range(i):
|
|
192
|
+
mu[i, j] = B[i] @ B_star[j] / (B_star[j] @ B_star[j])
|
|
193
|
+
B_star[i] -= mu[i, j] * B_star[j]
|
|
194
|
+
return B_star, mu
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _lll(B: np.ndarray, delta: float = 0.99) -> np.ndarray:
|
|
198
|
+
"""LLL reduction of the lattice spanned by the rows of B."""
|
|
199
|
+
B = B.astype(np.float64).copy()
|
|
200
|
+
k = 1
|
|
201
|
+
while k < len(B):
|
|
202
|
+
_, mu = _gram_schmidt(B)
|
|
203
|
+
for j in range(k - 1, -1, -1): # size reduction
|
|
204
|
+
q = round(mu[k, j])
|
|
205
|
+
if q != 0:
|
|
206
|
+
B[k] -= q * B[j]
|
|
207
|
+
B_star, mu = _gram_schmidt(B)
|
|
208
|
+
if B_star[k] @ B_star[k] >= (delta - mu[k, k - 1] ** 2) * (B_star[k - 1] @ B_star[k - 1]):
|
|
209
|
+
k += 1 # Lovasz condition holds
|
|
210
|
+
else:
|
|
211
|
+
B[[k, k - 1]] = B[[k - 1, k]]
|
|
212
|
+
k = max(1, k - 1)
|
|
213
|
+
return np.round(B).astype(np.int64)
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Structure factor estimation.
|
|
3
|
+
|
|
4
|
+
The structure factor is estimated from the scattering intensity.
|
|
5
|
+
Two modes, selected by ``trust_boundary``
|
|
6
|
+
-----------------------------------------
|
|
7
|
+
trust_boundary=True (default, reference)
|
|
8
|
+
The boundary of [0, 1)^D is trusted: plain scattering intensity
|
|
9
|
+
S(n) = |sum_j exp(2i pi n.x_j)|^2 / N on the integer wave vectors of [0, 1)^D.
|
|
10
|
+
Exact for point sets that "self compensate" for boundary effects,
|
|
11
|
+
e.g. because they were sampled with a periodic procedure on the unit torus.
|
|
12
|
+
|
|
13
|
+
trust_boundary=False
|
|
14
|
+
The boundary is not trusted, e.g. because the point set is not periodic
|
|
15
|
+
(which biases the estimate at low k).
|
|
16
|
+
A compensation based on tapering is then applied:
|
|
17
|
+
|
|
18
|
+
1. Truncation: keep only the points of the inner cube [m, 1-m]^D
|
|
19
|
+
2. Tapering: weight each point by a separable Kaiser-Bessel taper
|
|
20
|
+
See https://numpy.org/doc/2.5/reference/generated/numpy.kaiser.html
|
|
21
|
+
3. Debiasing with the estimated density rho = N (points per unit volume)
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
|
|
29
|
+
from .backend import (
|
|
30
|
+
direct_sums,
|
|
31
|
+
nufft_grid_sums,
|
|
32
|
+
resolve_backend,
|
|
33
|
+
resolve_precision,
|
|
34
|
+
resolve_tolerance,
|
|
35
|
+
)
|
|
36
|
+
from .torus import integer_grid, isotropic_wave_vectors
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class StructureFactorConfig:
|
|
41
|
+
margin: float = 0.1
|
|
42
|
+
max_beta: float = 15.0 # Kaiser taper: leakage ~exp(-2 beta) ~ 1e-13
|
|
43
|
+
k_max: float = 2.0 # in units of the inter-particle wave number
|
|
44
|
+
low_mode_fraction: float = 0.25 # D >= 4: share of exhaustive low modes
|
|
45
|
+
radial_bins: dict = field(default_factory=lambda: {1: (10, 50), 2: (5, 25), 3: (2, 6)}) # (width, start) in |n|^2
|
|
46
|
+
smoothing: float = 0.01 # gaussian smoothing width, fraction of the log-k range
|
|
47
|
+
resolution_divisor: int = 10 # D >= 4: wave vectors evaluated = resolution / divisor
|
|
48
|
+
|
|
49
|
+
CFG = StructureFactorConfig()
|
|
50
|
+
|
|
51
|
+
__all__ = ["structure_factor", "structure_factor_and_average", "tapered_kmin", "auto_beta"]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
# ── Kaiser-Bessel taper on [0, 1] ─────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
def _kaiser_norm(beta: float) -> float:
|
|
57
|
+
"""sqrt(int_0^1 I0(beta sqrt(1 - (2x - 1)^2))^2 dx), by Gauss-Legendre quadrature."""
|
|
58
|
+
u, w = np.polynomial.legendre.leggauss(400) # u in [-1, 1], x = (u + 1) / 2
|
|
59
|
+
return float(np.sqrt(0.5 * np.sum(w * np.i0(beta * np.sqrt(1.0 - u ** 2)) ** 2)))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _kaiser_weights(pts: np.ndarray, beta: float) -> np.ndarray:
|
|
63
|
+
"""Separable taper h(x_j) (normalised: int_[0,1]^D h^2 = 1), shape (N,)."""
|
|
64
|
+
u = 2.0 * np.clip(pts, 0.0, 1.0) - 1.0
|
|
65
|
+
w = np.i0(beta * np.sqrt(1.0 - u ** 2)) / _kaiser_norm(beta)
|
|
66
|
+
return np.prod(w, axis=1)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _kaiser_ft(kint: np.ndarray, beta: float) -> np.ndarray:
|
|
70
|
+
"""H(n) = int_[0,1]^D h(x) exp(2i pi n.x) dx, analytic, shape (M,).
|
|
71
|
+
|
|
72
|
+
Uses int_{-1}^{1} I0(beta sqrt(1-u^2)) e^{i w u} du = 2 sinh(sqrt(beta^2 - w^2)) / sqrt(beta^2 - w^2).
|
|
73
|
+
"""
|
|
74
|
+
norm = _kaiser_norm(beta)
|
|
75
|
+
H = np.ones(len(kint), dtype=complex)
|
|
76
|
+
for d in range(kint.shape[1]):
|
|
77
|
+
n = kint[:, d].astype(float)
|
|
78
|
+
r = np.sqrt((beta ** 2 - (np.pi * n) ** 2).astype(complex))
|
|
79
|
+
safe = np.abs(r) > 1e-12
|
|
80
|
+
g = np.ones_like(r) # limit sinh(r)/r -> 1
|
|
81
|
+
g[safe] = np.sinh(r[safe]) / r[safe]
|
|
82
|
+
H *= np.real(g) * np.cos(np.pi * n) / norm # (-1)^n from the shift x -> u
|
|
83
|
+
return H
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def auto_beta(n_points: int, D: int, margin: float) -> float:
|
|
87
|
+
"""Kaiser parameter used when beta=None.
|
|
88
|
+
|
|
89
|
+
The spectral window of the taper spans ~beta/pi modes, while the truncated window
|
|
90
|
+
only holds n_axis = (rho|W|)^(1/D) modes per axis up to the inter-particle scale.
|
|
91
|
+
We take beta = min(15, pi * n_axis / 4): leakage ~1e-13 whenever there are enough
|
|
92
|
+
points (typically D <= 3), otherwise the main lobe is capped at a quarter of the
|
|
93
|
+
useful range and the leakage floor rises to ~exp(-2 beta) (curse of dimension:
|
|
94
|
+
certifying a low bulk S(k) in high D requires a huge number of points).
|
|
95
|
+
"""
|
|
96
|
+
n_axis = (n_points * (1.0 - 2.0 * margin) ** D) ** (1.0 / D)
|
|
97
|
+
return float(min(CFG.max_beta, np.pi * n_axis / 4.0))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def tapered_kmin(n_points: int, D: int, margin: float | None = None, beta: float | None = None) -> float:
|
|
101
|
+
"""Smallest trustworthy normalised wave number (k = 1 <-> |n| = (rho|W|)^(1/D))
|
|
102
|
+
when trust_boundary=False (truncated + tapered estimate)."""
|
|
103
|
+
margin = CFG.margin if margin is None else margin
|
|
104
|
+
if beta is None:
|
|
105
|
+
beta = auto_beta(n_points, D, margin)
|
|
106
|
+
n_exp = n_points * (1.0 - 2.0 * margin) ** D
|
|
107
|
+
return (beta / np.pi + 1.0) / n_exp ** (1.0 / D)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ── Fourier sums F(n) = sum_j c_j exp(2i pi n.x_j) ────────────────────────────
|
|
111
|
+
|
|
112
|
+
def _grid(n_modes: int, D: int) -> np.ndarray:
|
|
113
|
+
"""Wave vectors of a centred cube of n_modes^D modes, in finufft's (modeord=0) order."""
|
|
114
|
+
return integer_grid(np.arange(-(n_modes // 2), n_modes - (n_modes // 2)), D)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# ── Core ──────────────────────────────────────────────────────────────────────
|
|
118
|
+
|
|
119
|
+
def _structure_factor_core(points, resolution, device, precision, trust_boundary,
|
|
120
|
+
margin, beta, backend, nufft_tolerance):
|
|
121
|
+
"""Return (kint, S, n_exp): wave vectors of the analysed window, S, expected count rho|W|."""
|
|
122
|
+
pts = np.asarray(points, dtype=float).reshape(-1, np.asarray(points).shape[-1])
|
|
123
|
+
N, D = pts.shape
|
|
124
|
+
taper = not trust_boundary
|
|
125
|
+
|
|
126
|
+
if taper:
|
|
127
|
+
margin = CFG.margin if margin is None else margin
|
|
128
|
+
side = 1.0 - 2.0 * margin
|
|
129
|
+
if not 0.0 < side <= 1.0:
|
|
130
|
+
raise ValueError("margin must be in [0, 0.5)")
|
|
131
|
+
keep = np.all((pts >= margin) & (pts < 1.0 - margin), axis=1)
|
|
132
|
+
pts = (pts[keep] - margin) / side
|
|
133
|
+
n_exp = N * side ** D # promised density x volume of the window
|
|
134
|
+
if beta is None:
|
|
135
|
+
beta = auto_beta(N, D, margin)
|
|
136
|
+
weights = _kaiser_weights(pts, beta)
|
|
137
|
+
else:
|
|
138
|
+
n_exp = float(N)
|
|
139
|
+
weights = np.ones(len(pts))
|
|
140
|
+
|
|
141
|
+
kunit = float(n_exp ** (1.0 / D))
|
|
142
|
+
kmax = CFG.k_max * kunit
|
|
143
|
+
precision = resolve_precision(precision)
|
|
144
|
+
backend = resolve_backend(backend, D, device)
|
|
145
|
+
|
|
146
|
+
if D <= 3: # every mode of the cube up to kmax
|
|
147
|
+
n_modes = int(np.ceil(kmax)) + 1
|
|
148
|
+
kint = _grid(n_modes, D)
|
|
149
|
+
else: # low modes + isotropic sample of the others
|
|
150
|
+
k_low = max(int((resolution * CFG.low_mode_fraction) ** (1.0 / D)), 1)
|
|
151
|
+
if kmax <= k_low:
|
|
152
|
+
kmax = k_low + 1
|
|
153
|
+
kint = isotropic_wave_vectors(k_low, kmax, D, int(resolution * (1.0 - CFG.low_mode_fraction)))
|
|
154
|
+
|
|
155
|
+
if backend in ("finufft", "cufinufft"):
|
|
156
|
+
F = nufft_grid_sums(pts, weights, n_modes, backend, precision,
|
|
157
|
+
resolve_tolerance(nufft_tolerance, precision))
|
|
158
|
+
else:
|
|
159
|
+
F = direct_sums(pts, weights, kint, backend, precision)
|
|
160
|
+
|
|
161
|
+
if taper:
|
|
162
|
+
F = F - n_exp * _kaiser_ft(kint, beta)
|
|
163
|
+
S = np.abs(F) ** 2 / n_exp
|
|
164
|
+
|
|
165
|
+
isnt0 = ~np.all(kint == 0, axis=1)
|
|
166
|
+
kint, S = kint[isnt0], S[isnt0]
|
|
167
|
+
order = np.argsort((kint ** 2).sum(axis=1), kind="stable")
|
|
168
|
+
return kint[order], S[order], n_exp
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _gaussian_filter1d(x, sigma, truncate=4.0):
|
|
172
|
+
"""Gaussian smoothing of a 1D array using a truncated kernel."""
|
|
173
|
+
radius = int(np.ceil(truncate * sigma))
|
|
174
|
+
if radius == 0:
|
|
175
|
+
return x.copy()
|
|
176
|
+
kernel_x = np.arange(-radius, radius + 1)
|
|
177
|
+
kernel = np.exp(-0.5 * (kernel_x / sigma) ** 2)
|
|
178
|
+
kernel /= kernel.sum()
|
|
179
|
+
xp = np.pad(x, radius, mode="reflect")
|
|
180
|
+
windows = np.lib.stride_tricks.sliding_window_view(xp, 2 * radius + 1)
|
|
181
|
+
return windows @ kernel
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ── Public API ────────────────────────────────────────────────────────────────
|
|
185
|
+
|
|
186
|
+
def structure_factor(
|
|
187
|
+
points: np.ndarray,
|
|
188
|
+
resolution: int = 2000,
|
|
189
|
+
device="auto",
|
|
190
|
+
precision="float32",
|
|
191
|
+
trust_boundary: bool = True,
|
|
192
|
+
margin: float | None = None,
|
|
193
|
+
beta: float | None = None,
|
|
194
|
+
backend: str = "auto",
|
|
195
|
+
nufft_tolerance: float | str = "auto",
|
|
196
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
197
|
+
"""
|
|
198
|
+
Estimate S(k) via scattering intensity.
|
|
199
|
+
|
|
200
|
+
Parameters
|
|
201
|
+
----------
|
|
202
|
+
points : (N, D) array of point coordinates in [0, 1)^D.
|
|
203
|
+
resolution : number of sampled wave vectors (only used when D >= 4).
|
|
204
|
+
device : "auto" | "cpu" | "gpu": for backend="auto" only, "cpu" never picks
|
|
205
|
+
cufinufft / cupy.
|
|
206
|
+
precision : "float32" | "float64". Use float64 to resolve S below ~1e-6.
|
|
207
|
+
trust_boundary : True (default): plain estimate on the whole cube.
|
|
208
|
+
False: truncate to [margin, 1 - margin]^D, Kaiser-taper, debias
|
|
209
|
+
with the promised density (see module docstring).
|
|
210
|
+
margin : width removed on each side (trust_boundary=False only),
|
|
211
|
+
default structure_factor_v2.CONFIG.margin (0.1).
|
|
212
|
+
beta : Kaiser parameter (trust_boundary=False only). Larger -> less
|
|
213
|
+
leakage (~exp(-2 beta)) but coarser resolution (~beta/pi modes).
|
|
214
|
+
None (default) -> auto_beta(N, D, margin).
|
|
215
|
+
backend : "auto" | "finufft" | "cufinufft" | "keops" | "torch" | "numpy" | "cupy"
|
|
216
|
+
(see `structure_factor_v2.backend`). "auto": (cu)finufft for D <= 3,
|
|
217
|
+
direct sums (cupy or numpy) above. (cu)finufft only for D <= 3.
|
|
218
|
+
nufft_tolerance: relative tolerance of (cu)finufft, float or "auto"
|
|
219
|
+
(1e-5 in float32, 1e-12 in float64). Ignored by the direct sums (exact).
|
|
220
|
+
|
|
221
|
+
Returns
|
|
222
|
+
-------
|
|
223
|
+
kint : (M, D) int array of wave vectors of the analysed window (k = 2 pi kint),
|
|
224
|
+
sorted by norm. With trust_boundary=False they refer to the rescaled
|
|
225
|
+
truncated window.
|
|
226
|
+
S : (M,) array.
|
|
227
|
+
|
|
228
|
+
Note
|
|
229
|
+
----
|
|
230
|
+
Points must lie in the unit hypercube [0, 1)^D. This is not checked.
|
|
231
|
+
"""
|
|
232
|
+
kint, S, _ = _structure_factor_core(points, resolution, device, precision,
|
|
233
|
+
trust_boundary, margin, beta, backend, nufft_tolerance)
|
|
234
|
+
return kint, S
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def structure_factor_and_average(
|
|
238
|
+
points,
|
|
239
|
+
resolution: int = 20000,
|
|
240
|
+
min_val: float = 1e-20,
|
|
241
|
+
precision="float32",
|
|
242
|
+
trust_boundary: bool = True,
|
|
243
|
+
margin: float | None = None,
|
|
244
|
+
beta: float | None = None,
|
|
245
|
+
backend: str = "auto",
|
|
246
|
+
nufft_tolerance: float | str = "auto",
|
|
247
|
+
device: str = "auto",
|
|
248
|
+
):
|
|
249
|
+
"""
|
|
250
|
+
Structure factor of a point set, raw and radially averaged, ready to plot.
|
|
251
|
+
|
|
252
|
+
resolution : number of raw values returned (subsampled), and of wave vectors evaluated
|
|
253
|
+
(divided by structure_factor_v2.CONFIG.resolution_divisor) when D >= 4.
|
|
254
|
+
min_val : floor of the returned values (log plots).
|
|
255
|
+
``precision``, ``trust_boundary``, ``margin``, ``beta``, ``backend``, ``nufft_tolerance``
|
|
256
|
+
and ``device`` behave as in ``structure_factor``.
|
|
257
|
+
|
|
258
|
+
Returns
|
|
259
|
+
-------
|
|
260
|
+
kraw, Sraw : normalised wave numbers and raw S values (subsampled for display).
|
|
261
|
+
kgroup, Sgroup : radially averaged then log-k smoothed curve.
|
|
262
|
+
|
|
263
|
+
Wave numbers are normalised so that k = 1 corresponds to |n| = (rho |W|)^(1/D),
|
|
264
|
+
i.e. to the inter-particle distance, in both modes.
|
|
265
|
+
Group averages are taken on raw values (which can be slightly negative after
|
|
266
|
+
debiasing) and clipped to ``min_val`` afterwards.
|
|
267
|
+
"""
|
|
268
|
+
pts = np.asarray(points).reshape(-1, np.asarray(points).shape[-1])
|
|
269
|
+
D = pts.shape[1]
|
|
270
|
+
kint, Sraw, n_exp = _structure_factor_core(pts, resolution // CFG.resolution_divisor, device,
|
|
271
|
+
precision, trust_boundary, margin, beta, backend,
|
|
272
|
+
nufft_tolerance)
|
|
273
|
+
kunit = n_exp ** (1.0 / D)
|
|
274
|
+
k2_ = (kint ** 2).sum(axis=1)
|
|
275
|
+
|
|
276
|
+
if D in CFG.radial_bins:
|
|
277
|
+
groupbin, groupstart = CFG.radial_bins[D]
|
|
278
|
+
mask = k2_ >= groupstart
|
|
279
|
+
k2_[mask] = groupbin * (k2_[mask] // groupbin)
|
|
280
|
+
|
|
281
|
+
kraw = np.sqrt(k2_) / kunit
|
|
282
|
+
k2group_, inverse = np.unique(k2_, return_inverse=True)
|
|
283
|
+
counts = np.bincount(inverse)
|
|
284
|
+
Sgroup = (np.bincount(inverse, weights=Sraw) / counts).clip(min=min_val)
|
|
285
|
+
kgroup = np.sqrt(k2group_) / kunit
|
|
286
|
+
Sraw = Sraw.clip(min=min_val)
|
|
287
|
+
|
|
288
|
+
if len(kraw) >= resolution:
|
|
289
|
+
p = kraw ** (-D)
|
|
290
|
+
p *= resolution / p.sum()
|
|
291
|
+
keep = np.random.random(len(kraw)) < p
|
|
292
|
+
kraw, Sraw = kraw[keep], Sraw[keep]
|
|
293
|
+
|
|
294
|
+
logk = np.log(kgroup)
|
|
295
|
+
logk_u = np.linspace(logk[0], logk[-1], 1000)
|
|
296
|
+
S_u = np.interp(logk_u, logk, Sgroup)
|
|
297
|
+
sigma_pixels = (logk[-1] - logk[0]) * CFG.smoothing / (logk_u[1] - logk_u[0])
|
|
298
|
+
Sgroup = np.interp(logk, logk_u, _gaussian_filter1d(S_u, sigma_pixels, truncate=4.0)).clip(min=min_val)
|
|
299
|
+
Sraw = Sraw.clip(min=Sgroup.min())
|
|
300
|
+
return kraw, Sraw, kgroup, Sgroup
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
The unit torus [0, 1)^D and its dual lattice Z^D.
|
|
3
|
+
|
|
4
|
+
integer_grid, ball, half_ball
|
|
5
|
+
integer points of Z^D: grids, balls, one representative per pair {k, -k}
|
|
6
|
+
isotropic_wave_vectors low modes + isotropically sampled high modes (D >= 4)
|
|
7
|
+
|
|
8
|
+
Balls are given by an integer squared radius r2: ball(r2, D) = {k in Z^D : |k|^2 <= r2}.
|
|
9
|
+
They are built shell by shell (cylinders over the (D-1)-ball), so memory never exceeds the
|
|
10
|
+
size of the output, even for millions of vectors.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# ── Integer points ────────────────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
def integer_grid(axis, D: int) -> np.ndarray:
|
|
20
|
+
"""Cartesian product axis^D, as a (len(axis)^D, D) array in 'ij' order."""
|
|
21
|
+
grids = np.meshgrid(*([np.asarray(axis)] * D), indexing="ij")
|
|
22
|
+
return np.stack([g.ravel() for g in grids], axis=1)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _isqrt(x):
|
|
26
|
+
"""Exact floor(sqrt(x)) of non-negative integers."""
|
|
27
|
+
x = np.asarray(x, dtype=np.int64)
|
|
28
|
+
z = np.floor(np.sqrt(x.astype(np.float64))).astype(np.int64)
|
|
29
|
+
z -= z * z > x
|
|
30
|
+
z += (z + 1) * (z + 1) <= x
|
|
31
|
+
return z
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _cylinders(counts, lo):
|
|
35
|
+
"""Concatenation of the integer ranges [lo[i], lo[i] + counts[i]), int32."""
|
|
36
|
+
starts = np.cumsum(counts) - counts
|
|
37
|
+
z = np.arange(int(counts.sum()), dtype=np.int32)
|
|
38
|
+
z -= np.repeat(starts, counts).astype(np.int32)
|
|
39
|
+
z += np.repeat(np.asarray(lo, dtype=np.int32), counts)
|
|
40
|
+
return z
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def ball(r2: int, D: int) -> np.ndarray:
|
|
44
|
+
"""All k in Z^D with |k|^2 <= r2, int32, in lexicographic order."""
|
|
45
|
+
if D == 1:
|
|
46
|
+
K = int(_isqrt(r2))
|
|
47
|
+
return np.arange(-K, K + 1, dtype=np.int32)[:, None]
|
|
48
|
+
head = ball(r2, D - 1)
|
|
49
|
+
m = _isqrt(r2 - np.sum(head.astype(np.int64) ** 2, axis=1))
|
|
50
|
+
counts = 2 * m + 1
|
|
51
|
+
return np.concatenate([np.repeat(head, counts, axis=0), _cylinders(counts, -m)[:, None]], axis=1)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _half_ball_last_positive(r2: int, D: int) -> np.ndarray:
|
|
55
|
+
"""Half-ball whose representatives have their *last* non-zero coordinate positive."""
|
|
56
|
+
if D == 1:
|
|
57
|
+
return np.arange(1, int(_isqrt(r2)) + 1, dtype=np.int32)[:, None]
|
|
58
|
+
head = ball(r2, D - 1) # last coordinate > 0
|
|
59
|
+
m = _isqrt(r2 - np.sum(head.astype(np.int64) ** 2, axis=1))
|
|
60
|
+
upper = np.concatenate([np.repeat(head, m, axis=0), _cylinders(m, np.ones_like(m))[:, None]], axis=1)
|
|
61
|
+
flat = _half_ball_last_positive(r2, D - 1) # last coordinate = 0
|
|
62
|
+
flat = np.concatenate([flat, np.zeros((len(flat), 1), dtype=np.int32)], axis=1)
|
|
63
|
+
return np.concatenate([upper, flat], axis=0)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def half_ball(r2: int, D: int) -> np.ndarray:
|
|
67
|
+
"""One k per pair {k, -k} with 0 < |k|^2 <= r2 (first non-zero coordinate > 0), int32,
|
|
68
|
+
in lexicographic order."""
|
|
69
|
+
k = _half_ball_last_positive(int(r2), D)
|
|
70
|
+
first = k[np.arange(len(k)), np.argmax(k != 0, axis=1)]
|
|
71
|
+
k = k * np.sign(first)[:, None].astype(np.int32)
|
|
72
|
+
return k[np.lexsort(k.T[::-1])]
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ── Wave vectors ──────────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
def isotropic_wave_vectors(k_low: int, k_max: float, D: int, n_high: int) -> np.ndarray:
|
|
78
|
+
"""Every mode with |k| <= k_low, plus n_high modes drawn isotropically in k_low < |k| < k_max
|
|
79
|
+
(rounded to Z^D, deduplicated, origin removed)."""
|
|
80
|
+
low = half_ball(k_low ** 2, D)
|
|
81
|
+
dirs = np.random.normal(size=(n_high, D))
|
|
82
|
+
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
|
|
83
|
+
radii = np.random.uniform(k_low, k_max, size=(n_high, 1))
|
|
84
|
+
high = np.rint(radii * dirs).astype(int)
|
|
85
|
+
k = np.concatenate([low, high], axis=0)
|
|
86
|
+
return np.unique(k[np.any(k != 0, axis=1)], axis=0)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""plot (point sets) and plot_structure_factor."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
|
|
7
|
+
import matplotlib.pyplot as plt
|
|
8
|
+
import numpy as np
|
|
9
|
+
from numpy.typing import NDArray
|
|
10
|
+
|
|
11
|
+
from .structure_factor import structure_factor_and_average, tapered_kmin
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _show_or_return(fig, axes, return_fig: bool):
|
|
15
|
+
plt.tight_layout()
|
|
16
|
+
if return_fig:
|
|
17
|
+
return fig, axes
|
|
18
|
+
plt.show()
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def plot(
|
|
23
|
+
points: NDArray,
|
|
24
|
+
auto_zoom: bool = False,
|
|
25
|
+
max_points: int = 30_000,
|
|
26
|
+
ax: plt.Axes | None = None,
|
|
27
|
+
return_fig: bool = False,
|
|
28
|
+
figsize: tuple = (8, 8),
|
|
29
|
+
**scatter_kw,
|
|
30
|
+
) -> tuple[plt.Figure, plt.Axes] | None:
|
|
31
|
+
"""
|
|
32
|
+
Scatter plot of a point set (N, D), or (N, K, D) flattened. Only the first 3 coordinates
|
|
33
|
+
are shown (a 3D plot if D >= 3).
|
|
34
|
+
|
|
35
|
+
auto_zoom : show a random sub-box holding about max_points points (large sets stay readable).
|
|
36
|
+
ax : existing axes (with projection="3d" for 3D data). Otherwise a new figure of figsize.
|
|
37
|
+
return_fig : return (fig, ax) instead of calling plt.show().
|
|
38
|
+
**scatter_kw : forwarded to ax.scatter (color, s, alpha...).
|
|
39
|
+
"""
|
|
40
|
+
pts = np.asarray(points).reshape(-1, np.asarray(points).shape[-1])
|
|
41
|
+
D = min(pts.shape[-1], 3)
|
|
42
|
+
pts = pts[:, :D]
|
|
43
|
+
|
|
44
|
+
if auto_zoom and len(pts) > max_points:
|
|
45
|
+
# keep a random sub-box holding ~max_points points
|
|
46
|
+
unit = (pts - pts.min()) / (pts.max() - pts.min())
|
|
47
|
+
zoom = (max_points / len(pts)) ** (1.0 / D)
|
|
48
|
+
lo = (1 - zoom) * np.random.rand(D)
|
|
49
|
+
pts = pts[((lo <= unit) & (unit <= lo + zoom)).all(axis=1)]
|
|
50
|
+
|
|
51
|
+
kw = dict(s=10_000 / len(pts), color="black")
|
|
52
|
+
kw.update(scatter_kw)
|
|
53
|
+
|
|
54
|
+
if ax is None:
|
|
55
|
+
fig = plt.figure(figsize=figsize)
|
|
56
|
+
if D == 2:
|
|
57
|
+
ax = fig.add_subplot(111)
|
|
58
|
+
else:
|
|
59
|
+
ax = fig.add_subplot(111, projection="3d")
|
|
60
|
+
else:
|
|
61
|
+
fig = ax.get_figure()
|
|
62
|
+
|
|
63
|
+
if D == 2:
|
|
64
|
+
ax.scatter(pts[:, 0], pts[:, 1], **kw)
|
|
65
|
+
else:
|
|
66
|
+
ax.scatter(pts[:, 0], pts[:, 1], pts[:, 2], **kw)
|
|
67
|
+
|
|
68
|
+
ax.set_axis_off()
|
|
69
|
+
return _show_or_return(fig, ax, return_fig)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def plot_structure_factor(
|
|
73
|
+
points: NDArray,
|
|
74
|
+
resolution: int = 20_000,
|
|
75
|
+
precision: str = "float32",
|
|
76
|
+
ax: plt.Axes | None = None,
|
|
77
|
+
return_fig: bool = False,
|
|
78
|
+
title: str = None,
|
|
79
|
+
trust_boundary: bool | str = True,
|
|
80
|
+
margin: float | None = None,
|
|
81
|
+
beta: float | None = None,
|
|
82
|
+
backend: str = "auto",
|
|
83
|
+
nufft_tolerance: float | str = "auto",
|
|
84
|
+
device: str = "auto",
|
|
85
|
+
**plot_kw,
|
|
86
|
+
) -> tuple[plt.Figure, plt.Axes] | None:
|
|
87
|
+
"""
|
|
88
|
+
Log-log plot of the radially averaged structure factor S(k) of points in [0, 1)^D.
|
|
89
|
+
|
|
90
|
+
S is estimated by the scattering intensity on the integer wave vectors up to 2 N^(1/D);
|
|
91
|
+
k is normalised so that k = 1 is the inter-particle wave number N^(1/D). Raw values are
|
|
92
|
+
shown in grey, their smoothed radial average as a curve. For an order-alpha hyperuniform
|
|
93
|
+
pattern S(k) ~ k^alpha at small k.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
points : (N, D) array in the unit cube (not checked).
|
|
98
|
+
resolution : number of wave vectors shown. For D >= 4 (no fast transform) only
|
|
99
|
+
resolution / 10 are evaluated: ask for 200_000 to get 20_000.
|
|
100
|
+
precision : "float32", or "float64" (much slower) to resolve S below ~1e-10.
|
|
101
|
+
ax, return_fig : draw on existing axes; return (fig, ax) instead of showing.
|
|
102
|
+
title : default depends on trust_boundary.
|
|
103
|
+
trust_boundary : True, False or "both".
|
|
104
|
+
True: plain estimate, for patterns that are periodic on the unit torus.
|
|
105
|
+
False: for a window cut out of a larger pattern. The points are restricted to
|
|
106
|
+
[m, 1 - m)^D (m = margin) and the estimate is debiased with a Kaiser taper.
|
|
107
|
+
"both": plot both estimates.
|
|
108
|
+
margin : default structure_factor_v2.CONFIG.margin (0.1), trust_boundary=False only.
|
|
109
|
+
beta : Kaiser parameter, trust_boundary=False only. Larger: less leakage (~exp(-2 beta)),
|
|
110
|
+
coarser resolution at small k. None: automatic (`structure_factor.auto_beta`).
|
|
111
|
+
backend, nufft_tolerance, device : Fourier sums, as in `structure_factor`.
|
|
112
|
+
**plot_kw : forwarded to ``ax.loglog`` for the smoothed curve.
|
|
113
|
+
"""
|
|
114
|
+
pts = np.asarray(points).reshape(-1, np.asarray(points).shape[-1])
|
|
115
|
+
N, D = pts.shape
|
|
116
|
+
|
|
117
|
+
if isinstance(trust_boundary, str):
|
|
118
|
+
if trust_boundary != "both":
|
|
119
|
+
raise ValueError("trust_boundary must be True, False or 'both'")
|
|
120
|
+
modes = [True, False]
|
|
121
|
+
both = True
|
|
122
|
+
else:
|
|
123
|
+
modes = [bool(trust_boundary)]
|
|
124
|
+
both = False
|
|
125
|
+
|
|
126
|
+
# --- Axes setup ---
|
|
127
|
+
own_fig = ax is None
|
|
128
|
+
if own_fig:
|
|
129
|
+
fig, ax = plt.subplots(figsize=(7, 5))
|
|
130
|
+
else:
|
|
131
|
+
fig = ax.get_figure()
|
|
132
|
+
|
|
133
|
+
ax.set_axisbelow(True)
|
|
134
|
+
ax.grid(True, which="both", alpha=0.4, zorder=0)
|
|
135
|
+
ax.set_xscale("log")
|
|
136
|
+
ax.set_yscale("log")
|
|
137
|
+
|
|
138
|
+
for trust in modes:
|
|
139
|
+
# --- Compute structure factor and averages ---
|
|
140
|
+
k, S, kgroup, Sgroup = structure_factor_and_average(
|
|
141
|
+
pts, resolution=resolution, precision=precision,
|
|
142
|
+
trust_boundary=trust, margin=margin, beta=beta,
|
|
143
|
+
backend=backend, nufft_tolerance=nufft_tolerance, device=device,
|
|
144
|
+
)
|
|
145
|
+
if not trust:
|
|
146
|
+
# nothing is shown below the resolution limit of the taper
|
|
147
|
+
kmin = tapered_kmin(N, D, margin, beta)
|
|
148
|
+
keep, keep_g = k >= kmin, kgroup >= kmin
|
|
149
|
+
k, S, kgroup, Sgroup = k[keep], S[keep], kgroup[keep_g], Sgroup[keep_g]
|
|
150
|
+
if len(kgroup) < 2:
|
|
151
|
+
warnings.warn("trust_boundary=False: no wave number above the resolution "
|
|
152
|
+
"limit (too few points in the truncated window); curve not drawn.")
|
|
153
|
+
continue
|
|
154
|
+
|
|
155
|
+
# --- Scatter (raw values) ---
|
|
156
|
+
# single mode: neutral grays; 'both': same hue as the smoothed curve,
|
|
157
|
+
# bluish gray (trusted, tab:blue) / orangish gray (tapered, tab:orange)
|
|
158
|
+
if not both:
|
|
159
|
+
c_light, c_dark = "lightgray", "gray"
|
|
160
|
+
elif trust:
|
|
161
|
+
c_light, c_dark = "#b8c4d0", "#6b7f94"
|
|
162
|
+
else:
|
|
163
|
+
c_light, c_dark = "#d8c7b6", "#9c8068"
|
|
164
|
+
Sgroup_interp = np.exp(np.interp(np.log(k), np.log(kgroup), np.log(Sgroup)))
|
|
165
|
+
bigS = S >= 30 * Sgroup_interp
|
|
166
|
+
ax.scatter(k[~bigS], S[~bigS], s=5, color=c_light, alpha=0.6, zorder=2)
|
|
167
|
+
ax.scatter(k[bigS], S[bigS], s=20, color=c_dark, alpha=1.0, zorder=2)
|
|
168
|
+
|
|
169
|
+
# --- Smoothed curve ---
|
|
170
|
+
curve_kw = {"color": "tab:blue", "zorder": 3, "label": None,
|
|
171
|
+
"marker": "o", "markersize": 2, "linewidth": 2}
|
|
172
|
+
curve_kw.update(plot_kw)
|
|
173
|
+
if both:
|
|
174
|
+
curve_kw["label"] = "boundary trusted" if trust else "truncated + taper"
|
|
175
|
+
if not trust:
|
|
176
|
+
curve_kw["color"] = "tab:orange"
|
|
177
|
+
curve_kw["zorder"] = 4
|
|
178
|
+
ax.loglog(kgroup, Sgroup, **curve_kw)
|
|
179
|
+
|
|
180
|
+
if ax.get_legend_handles_labels()[1]:
|
|
181
|
+
ax.legend()
|
|
182
|
+
|
|
183
|
+
# --- Reference lines and axis limits (only when we own the figure) ---
|
|
184
|
+
if own_fig:
|
|
185
|
+
ax.axvline(1, color="green", linewidth=2, alpha=0.2, zorder=1)
|
|
186
|
+
ax.axhline(1, color="green", linewidth=2, alpha=0.2, zorder=1)
|
|
187
|
+
ax.set_xlim(right=2)
|
|
188
|
+
ax.set_ylim(top=2)
|
|
189
|
+
ax.set_xlabel(r"$k$")
|
|
190
|
+
ax.set_ylabel(r"$S(k)$")
|
|
191
|
+
|
|
192
|
+
if both:
|
|
193
|
+
default_title = "Structure factor (log-log): boundary trusted vs truncated + taper"
|
|
194
|
+
elif not modes[0]:
|
|
195
|
+
default_title = "Structure factor (log-log, truncated + Kaiser taper)"
|
|
196
|
+
else:
|
|
197
|
+
default_title = "Structure factor (log-log, scattering intensity)"
|
|
198
|
+
ax.set_title(title or default_title)
|
|
199
|
+
return _show_or_return(fig, ax, return_fig)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: structure-factor-v2
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Structure factor S(k) of point sets in the unit cube: scattering intensity, Kaiser taper, NUFFT, plots
|
|
5
|
+
Project-URL: Repository, https://github.com/adecacqueray/structure-factor-v2
|
|
6
|
+
Project-URL: Issues, https://github.com/adecacqueray/structure-factor-v2/issues
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: Kaiser taper,NUFFT,finufft,hyperuniformity,point process,power spectrum,scattering intensity,structure factor
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
20
|
+
Requires-Python: >=3.9
|
|
21
|
+
Requires-Dist: finufft
|
|
22
|
+
Requires-Dist: matplotlib
|
|
23
|
+
Requires-Dist: numpy
|
|
24
|
+
Provides-Extra: gpu12
|
|
25
|
+
Requires-Dist: cufinufft; extra == 'gpu12'
|
|
26
|
+
Requires-Dist: cupy-cuda12x; extra == 'gpu12'
|
|
27
|
+
Provides-Extra: gpu13
|
|
28
|
+
Requires-Dist: cufinufft; extra == 'gpu13'
|
|
29
|
+
Requires-Dist: cupy-cuda13x; extra == 'gpu13'
|
|
30
|
+
Provides-Extra: keops
|
|
31
|
+
Requires-Dist: pykeops; extra == 'keops'
|
|
32
|
+
Provides-Extra: torch
|
|
33
|
+
Requires-Dist: torch; extra == 'torch'
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# structure-factor-v2
|
|
37
|
+
|
|
38
|
+
[](https://pypi.org/project/structure-factor-v2/)
|
|
39
|
+
[](https://pypi.org/project/structure-factor-v2/)
|
|
40
|
+
[](https://github.com/adecacqueray/structure-factor-v2/blob/main/LICENSE)
|
|
41
|
+
[](https://github.com/adecacqueray/structure-factor-v2)
|
|
42
|
+
|
|
43
|
+
**Structure factor $S(k)$ of point sets in the unit cube $[0, 1)^D$**, estimated by the
|
|
44
|
+
scattering intensity, with fast transforms (finufft / cufinufft) and ready-made log-log plots.
|
|
45
|
+
|
|
46
|
+
The structure factor measures the density fluctuations of a point set in Fourier space
|
|
47
|
+
(it is the power spectrum, up to normalisation). For a hyperuniform (blue-noise) pattern,
|
|
48
|
+
$S(k) \to 0$ as $k \to 0$; for an order-$\alpha$ hyperuniform pattern $S(k) \sim k^\alpha$.
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## Installation
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install structure-factor-v2 # CPU: numpy + finufft
|
|
56
|
+
#pip install structure-factor-v2[gpu12] # GPU: [gpu12] or [gpu13], cupy + cufinufft
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## Quick start
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import structure_factor_v2 as sf
|
|
65
|
+
|
|
66
|
+
x = sf.jittered_lattice(10_000, 2) # (N, D) points in [0, 1)^D, hyperuniform
|
|
67
|
+
|
|
68
|
+
sf.plot(x) # scatter plot
|
|
69
|
+
sf.plot_structure_factor(x) # log-log S(k), raw values + radial average
|
|
70
|
+
|
|
71
|
+
kint, S = sf.structure_factor(x) # raw estimate: integer wave vectors (M, D), S (M,)
|
|
72
|
+
k, S, kgroup, Sgroup = sf.structure_factor_and_average(x) # normalised k, raw + smoothed
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
A jittered lattice (a Korobov lattice, randomly shifted, every point moved uniformly within its
|
|
76
|
+
cell) is a cheap hyperuniform pattern: $S(k) \sim k^2$ at small $k$. Compare with i.i.d. points
|
|
77
|
+
($S \equiv 1$) and with the bare lattice (a crystal: $S = 0$ except on its Bragg peaks):
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import numpy as np
|
|
81
|
+
sf.plot_structure_factor(np.random.rand(10_000, 2)) # Poisson: S = 1
|
|
82
|
+
sf.plot_structure_factor(sf.korobov_lattice(10_000, 2)) # crystal
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
A curled lattice goes further: the Korobov lattice is moved along a random periodic
|
|
86
|
+
divergence-free flow (curl noise jittering, Bærentzen, Frisvad & Martínez, SIGGRAPH Asia
|
|
87
|
+
2023). The flow preserves volume, so the points stay well separated, and the Bragg peaks are
|
|
88
|
+
smeared out: a blue noise point set, with a much lower $S(k)$ at small $k$ than the jittered
|
|
89
|
+
lattice. Any dimension (tuned in 2D and 3D), about 3 s for $10^5$ points.
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
x = sf.curled_lattice(10_000, 2) # noise_scale=5.0, dt=1.2
|
|
93
|
+
sf.plot_structure_factor(x)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Wave numbers returned by `structure_factor_and_average` (and shown by
|
|
97
|
+
`plot_structure_factor`) are normalised so that $k = 1$ is the inter-particle wave
|
|
98
|
+
number $N^{1/D}$.
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## Two estimators: `trust_boundary`
|
|
103
|
+
|
|
104
|
+
| `trust_boundary` | When | Estimator |
|
|
105
|
+
|------------------|-------------------------------------------------------------|-----------|
|
|
106
|
+
| `True` (default) | the points are periodic on the unit torus | $S(n) = \lvert\sum_j e^{2i\pi n \cdot x_j}\rvert^2 / N$ on the integer wave vectors $n$ |
|
|
107
|
+
| `False` | the points are a window cut out of a larger, non-periodic pattern | points restricted to $[m, 1-m)^D$, separable Kaiser–Bessel taper, debiased with the density |
|
|
108
|
+
| `"both"` | (plots only) compare the two | |
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
sf.plot_structure_factor(x, trust_boundary=False) # margin m = 0.1, beta automatic
|
|
112
|
+
sf.plot_structure_factor(x, trust_boundary=False, margin=0.05, beta=10)
|
|
113
|
+
sf.plot_structure_factor(x, trust_boundary="both")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
With the taper, leakage decays like $e^{-2\beta}$ while the resolution at small $k$
|
|
117
|
+
coarsens (about $\beta/\pi$ modes). `beta=None` picks
|
|
118
|
+
$\beta = \min(15, \pi\, n_{\text{axis}} / 4)$, see `sf.auto_beta`; nothing is plotted
|
|
119
|
+
below the resolution limit `sf.tapered_kmin(N, D, margin, beta)`.
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Backends, precision and tolerance
|
|
124
|
+
|
|
125
|
+
Every function takes `backend`, `precision` and `nufft_tolerance`:
|
|
126
|
+
|
|
127
|
+
| `backend` | method | dimensions | accuracy |
|
|
128
|
+
|---------------|------------------------------------------|------------|----------|
|
|
129
|
+
| `"finufft"` | type-1 non-uniform FFT, CPU | D <= 3 | `nufft_tolerance` |
|
|
130
|
+
| `"cufinufft"` | type-1 non-uniform FFT, GPU (+ cupy) | D <= 3 | `nufft_tolerance` |
|
|
131
|
+
| `"keops"` | direct sums, pykeops (GPU if available) | any | exact |
|
|
132
|
+
| `"torch"` | direct sums, torch (cuda if available) | any | exact |
|
|
133
|
+
| `"numpy"` | direct sums, numpy, chunked | any | exact |
|
|
134
|
+
| `"cupy"` | direct sums, cupy, chunked | any | exact |
|
|
135
|
+
|
|
136
|
+
`"auto"` (default): (cu)finufft for D <= 3 (cufinufft when it works), direct sums with cupy or
|
|
137
|
+
numpy above; `device="cpu"` keeps "auto" off the GPU. `keops` and `torch` are optional
|
|
138
|
+
installs, only used when asked for (KeOps counts as working only if it compiles a test
|
|
139
|
+
reduction).
|
|
140
|
+
|
|
141
|
+
| Dimension | Wave vectors |
|
|
142
|
+
|-----------|--------------|
|
|
143
|
+
| $D \le 3$ | every integer mode of the cube up to $2 N^{1/D}$ |
|
|
144
|
+
| $D \ge 4$ | all low modes + isotropically sampled high modes (`resolution`) |
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
sf.plot_structure_factor(x, backend="keops") # exact sums
|
|
148
|
+
sf.plot_structure_factor(x, precision="float64", nufft_tolerance=1e-14)
|
|
149
|
+
sf.available_backends(D=2) # what works here
|
|
150
|
+
sf.check_gpu()
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`nufft_tolerance="auto"` means 1e-5 in float32 and 1e-12 in float64; float32 sets a floor on
|
|
154
|
+
the smallest resolvable S (float64 for S below ~1e-6 at large N).
|
|
155
|
+
|
|
156
|
+
Tunable constants (margin, $k_{\max}$, radial bins, smoothing...) are in `sf.CONFIG`, editable in place:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
sf.CONFIG.k_max = 3.0 # wave numbers up to 3 N^(1/D)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
---
|
|
163
|
+
|
|
164
|
+
## API
|
|
165
|
+
|
|
166
|
+
| Function | Returns |
|
|
167
|
+
|----------|---------|
|
|
168
|
+
| `structure_factor(points, resolution=2000, device="auto", precision="float32", trust_boundary=True, margin=None, beta=None, backend="auto", nufft_tolerance="auto")` | `kint (M, D)`, `S (M,)`, sorted by $\lvert n\rvert$ |
|
|
169
|
+
| `structure_factor_and_average(points, resolution=20000, min_val=1e-20, precision="float32", trust_boundary=True, margin=None, beta=None, backend="auto", nufft_tolerance="auto", device="auto")` | `kraw, Sraw, kgroup, Sgroup` |
|
|
170
|
+
| `plot_structure_factor(points, resolution=20000, precision="float32", ax=None, return_fig=False, title=None, trust_boundary=True, margin=None, beta=None, backend="auto", nufft_tolerance="auto", device="auto", **plot_kw)` | `None`, or `(fig, ax)` |
|
|
171
|
+
| `plot(points, auto_zoom=False, max_points=30000, ax=None, return_fig=False, figsize=(8, 8), **scatter_kw)` | `None`, or `(fig, ax)` |
|
|
172
|
+
| `jittered_lattice(N, D, seed=None, max_candidates=100)`, `korobov_lattice(N, D, shift=True, seed=None, max_candidates=100)` | `(N, D)` test point sets |
|
|
173
|
+
| `curled_lattice(N, D, noise_scale=5.0, dt=1.2, n_modes=256, bandwidth=0.3, n_steps=1, seed=None, max_candidates=100)` | `(N, D)` blue noise point set |
|
|
174
|
+
| `auto_beta(n_points, D, margin)`, `tapered_kmin(n_points, D, margin=None, beta=None)` | Kaiser parameter, smallest trustworthy $k$ |
|
|
175
|
+
| `check_gpu()`, `available_backends(D=None)`, `BACKENDS` | diagnostic, backends that work here |
|
|
176
|
+
|
|
177
|
+
Points must lie in $[0, 1)^D$; this is not checked.
|
|
178
|
+
|
|
179
|
+
---
|
|
180
|
+
|
|
181
|
+
## References
|
|
182
|
+
|
|
183
|
+
- **Korobov lattices**: I. H. Sloan and S. Joe. *Lattice Methods for Multiple Integration.*
|
|
184
|
+
Oxford University Press, 1994.
|
|
185
|
+
- **Curl noise jittering**: J. A. Bærentzen, J. R. Frisvad, and J. Martínez. *Curl Noise
|
|
186
|
+
Jittering.* SIGGRAPH Asia 2023 Conference Papers, article 88, 2023.
|
|
187
|
+
[doi:10.1145/3610548.3618163](https://doi.org/10.1145/3610548.3618163),
|
|
188
|
+
code: [jonasmb/curlnoisejittering](https://github.com/jonasmb/curlnoisejittering).
|
|
189
|
+
`curled_lattice` starts from a Korobov lattice instead of their triangular / cubic grids,
|
|
190
|
+
and uses a random Fourier divergence-free field (exactly periodic, any dimension) instead
|
|
191
|
+
of the curl of a Perlin noise; independent implementation.
|
|
192
|
+
- **finufft / cufinufft**: A. H. Barnett, J. F. Magland, and L. af Klinteberg.
|
|
193
|
+
*A parallel non-uniform fast Fourier transform library based on an "exponential of
|
|
194
|
+
semicircle" kernel.* SIAM J. Sci. Comput. 41(5), C479–C504, 2019.
|
|
195
|
+
See [finufft](https://github.com/flatironinstitute/finufft).
|
|
196
|
+
- **structure-factor**: the original package of the same group,
|
|
197
|
+
[For-a-few-DPPs-more/structure-factor](https://github.com/For-a-few-DPPs-more/structure-factor).
|
|
198
|
+
|
|
199
|
+
Used by [blue-sampler](https://pypi.org/project/blue-sampler/), which re-exports
|
|
200
|
+
`plot`, `plot_structure_factor`, `structure_factor` and `structure_factor_and_average`.
|
|
201
|
+
|
|
202
|
+
---
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT, see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
structure_factor_v2/__init__.py,sha256=WnSnR5FAmz-aTzQDiZTU6sbLKpsCbChJU1G9AxhnMxE,1740
|
|
2
|
+
structure_factor_v2/backend.py,sha256=yUrFsAK3YvfivyUqIFFTU-Ehb3SL-s_VW-Un-xxay5g,9657
|
|
3
|
+
structure_factor_v2/lattices.py,sha256=XABzH9lydxXY0w33J4_0_4ZwhQaAb0ioZbHM8Ucv_F4,10236
|
|
4
|
+
structure_factor_v2/structure_factor.py,sha256=4XeIoPaaDuN6RarYd8Y3GCyvy1yjAcTEeLFmwOtCXHs,13267
|
|
5
|
+
structure_factor_v2/torus.py,sha256=8mrd3EdsVFttofXSRnzXQ0XPCna4G7DAkMtds6I3duI,3892
|
|
6
|
+
structure_factor_v2/viz.py,sha256=hhjUtTTOurs0OZmd-89M3S-8eE-QYPrVvEeguwPSZVs,7631
|
|
7
|
+
structure_factor_v2-2.0.0.dist-info/METADATA,sha256=4vLHwjt8l4yttUYH1D3Gfy9vr0ZKlUqeFsBIBkSp5S4,10359
|
|
8
|
+
structure_factor_v2-2.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
structure_factor_v2-2.0.0.dist-info/licenses/LICENSE,sha256=EKinUlZ-baH6RjzBA9jnNhkQdGmFYjwRe_dUB90G1W0,1069
|
|
10
|
+
structure_factor_v2-2.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 adecacqueray
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|