qmc-sampler 1.0.0__tar.gz
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.
- qmc_sampler-1.0.0/.gitignore +6 -0
- qmc_sampler-1.0.0/PKG-INFO +99 -0
- qmc_sampler-1.0.0/README.md +88 -0
- qmc_sampler-1.0.0/pyproject.toml +42 -0
- qmc_sampler-1.0.0/src/__init__.py +44 -0
- qmc_sampler-1.0.0/src/qmc_geom.py +329 -0
- qmc_sampler-1.0.0/src/qmc_sampler.py +319 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: qmc-sampler
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: QMC sampling methods based on blue_sampler
|
|
5
|
+
Project-URL: Repository, https://github.com/For-a-few-DPPs-more/hyperuniform-samplers
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: NUFFT,QMC,hyperuniformity,point sampling,quasi-Monte Carlo,wrap-around discrepancy
|
|
8
|
+
Requires-Python: >=3.9
|
|
9
|
+
Requires-Dist: blue-sampler[keops]
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# qmc-sampler
|
|
13
|
+
|
|
14
|
+
**Quasi-Monte Carlo point sampling with spectral exclusion and discrepancy-based criteria.**
|
|
15
|
+
|
|
16
|
+
`qmc-sampler` is a lightweight wrapper around [`blue_sampler`](https://github.com/For-a-few-DPPs-more/hyperuniform-samplers) that provides several sampling methods for generating quasi-Monte Carlo (QMC) point sets.
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
|
|
20
|
+
Install from PyPI:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pip install qmc-sampler
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
For the optional KeOps backend:
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
## Available sampling methods
|
|
30
|
+
|
|
31
|
+
The package provides three sampling methods:
|
|
32
|
+
|
|
33
|
+
- **`sample_l2(N, D, **kwargs)`** — uses a classical isotropic L_2-ball as the spectral exclusion region.
|
|
34
|
+
- **`sample_l1(N, D, **kwargs)`** — uses an L_1-ball, producing an anisotropic spectral exclusion region that can be useful when exploiting low effective dimensionality.
|
|
35
|
+
- **`sample_wd(N, D, **kwargs)`** — uses the wrap-around discrepancy (WD), a criterion designed to further exploit low-effective-dimensionality structure.
|
|
36
|
+
|
|
37
|
+
Here, `N` denotes the number of points and `D` the dimension.
|
|
38
|
+
|
|
39
|
+
## Basic usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from qmc_sampler import sample_l1, sample_l2, sample_wd
|
|
43
|
+
|
|
44
|
+
N = 1000
|
|
45
|
+
D = 2
|
|
46
|
+
|
|
47
|
+
points_l2 = sample_l2(N, D)
|
|
48
|
+
points_l1 = sample_l1(N, D)
|
|
49
|
+
points_wd = sample_wd(N, D)
|
|
50
|
+
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Additional keyword arguments e.g. "chi = 0.4" can be passed to the sampling functions and forwarded to the underlying implementation.
|
|
54
|
+
|
|
55
|
+
## Accelerated L2 sampling with FINUFFT
|
|
56
|
+
|
|
57
|
+
For supported 2D and 3D problems, `blue_sampler` provides an accelerated NUFFT-based implementation that can reduce the computational complexity from approximately O(N^2) to O(N\log N).
|
|
58
|
+
|
|
59
|
+
This backend requires a compatible GPU environment and additional dependencies. Install the appropriate extras supported by your version of `blue_sampler`, for example:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
pip install "blue-sampler[gpu13]"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
To use the accelerated backend, overwright the default `sample_l2` implementation with:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
def sample_l2(N, D, **kwargs):
|
|
69
|
+
from blue_sampler.run.run_nufft import _nufft_pipeline
|
|
70
|
+
|
|
71
|
+
kwargs.setdefault("verbose", 0)
|
|
72
|
+
return _nufft_pipeline(N, D, **kwargs)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
**Note:** This uses a private function from `blue_sampler` (indicated by the leading underscore), so its API may change between versions. The accelerated backend also requires compatible GPU dependencies and is intended for supported 2D and 3D problems.
|
|
76
|
+
|
|
77
|
+
## Plotting utilities
|
|
78
|
+
|
|
79
|
+
The package also exposes plotting functions from `blue_sampler`:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from qmc_sampler import plot, plot_structure_factor
|
|
83
|
+
|
|
84
|
+
plot(...)
|
|
85
|
+
plot_structure_factor(...)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Refer to the upstream documentation for the accepted arguments.
|
|
89
|
+
|
|
90
|
+
## Links
|
|
91
|
+
|
|
92
|
+
- **Source code:** [hyperuniform-samplers on GitHub](https://github.com/For-a-few-DPPs-more/hyperuniform-samplers)
|
|
93
|
+
- **Underlying package:** [blue_sampler on PyPI](https://pypi.org/project/blue-sampler/)
|
|
94
|
+
- **Upstream repository:** [Recursive Gaussian Blue Noise](https://github.com/For-a-few-DPPs-more/Recursive-Gaussian-Blue-Noise)
|
|
95
|
+
- **Documentation:** [blue-sampler.readthedocs.io](https://blue-sampler.readthedocs.io)
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
MIT
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# qmc-sampler
|
|
2
|
+
|
|
3
|
+
**Quasi-Monte Carlo point sampling with spectral exclusion and discrepancy-based criteria.**
|
|
4
|
+
|
|
5
|
+
`qmc-sampler` is a lightweight wrapper around [`blue_sampler`](https://github.com/For-a-few-DPPs-more/hyperuniform-samplers) that provides several sampling methods for generating quasi-Monte Carlo (QMC) point sets.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
Install from PyPI:
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install qmc-sampler
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
For the optional KeOps backend:
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
## Available sampling methods
|
|
19
|
+
|
|
20
|
+
The package provides three sampling methods:
|
|
21
|
+
|
|
22
|
+
- **`sample_l2(N, D, **kwargs)`** — uses a classical isotropic L_2-ball as the spectral exclusion region.
|
|
23
|
+
- **`sample_l1(N, D, **kwargs)`** — uses an L_1-ball, producing an anisotropic spectral exclusion region that can be useful when exploiting low effective dimensionality.
|
|
24
|
+
- **`sample_wd(N, D, **kwargs)`** — uses the wrap-around discrepancy (WD), a criterion designed to further exploit low-effective-dimensionality structure.
|
|
25
|
+
|
|
26
|
+
Here, `N` denotes the number of points and `D` the dimension.
|
|
27
|
+
|
|
28
|
+
## Basic usage
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from qmc_sampler import sample_l1, sample_l2, sample_wd
|
|
32
|
+
|
|
33
|
+
N = 1000
|
|
34
|
+
D = 2
|
|
35
|
+
|
|
36
|
+
points_l2 = sample_l2(N, D)
|
|
37
|
+
points_l1 = sample_l1(N, D)
|
|
38
|
+
points_wd = sample_wd(N, D)
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Additional keyword arguments e.g. "chi = 0.4" can be passed to the sampling functions and forwarded to the underlying implementation.
|
|
43
|
+
|
|
44
|
+
## Accelerated L2 sampling with FINUFFT
|
|
45
|
+
|
|
46
|
+
For supported 2D and 3D problems, `blue_sampler` provides an accelerated NUFFT-based implementation that can reduce the computational complexity from approximately O(N^2) to O(N\log N).
|
|
47
|
+
|
|
48
|
+
This backend requires a compatible GPU environment and additional dependencies. Install the appropriate extras supported by your version of `blue_sampler`, for example:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install "blue-sampler[gpu13]"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
To use the accelerated backend, overwright the default `sample_l2` implementation with:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
def sample_l2(N, D, **kwargs):
|
|
58
|
+
from blue_sampler.run.run_nufft import _nufft_pipeline
|
|
59
|
+
|
|
60
|
+
kwargs.setdefault("verbose", 0)
|
|
61
|
+
return _nufft_pipeline(N, D, **kwargs)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**Note:** This uses a private function from `blue_sampler` (indicated by the leading underscore), so its API may change between versions. The accelerated backend also requires compatible GPU dependencies and is intended for supported 2D and 3D problems.
|
|
65
|
+
|
|
66
|
+
## Plotting utilities
|
|
67
|
+
|
|
68
|
+
The package also exposes plotting functions from `blue_sampler`:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from qmc_sampler import plot, plot_structure_factor
|
|
72
|
+
|
|
73
|
+
plot(...)
|
|
74
|
+
plot_structure_factor(...)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Refer to the upstream documentation for the accepted arguments.
|
|
78
|
+
|
|
79
|
+
## Links
|
|
80
|
+
|
|
81
|
+
- **Source code:** [hyperuniform-samplers on GitHub](https://github.com/For-a-few-DPPs-more/hyperuniform-samplers)
|
|
82
|
+
- **Underlying package:** [blue_sampler on PyPI](https://pypi.org/project/blue-sampler/)
|
|
83
|
+
- **Upstream repository:** [Recursive Gaussian Blue Noise](https://github.com/For-a-few-DPPs-more/Recursive-Gaussian-Blue-Noise)
|
|
84
|
+
- **Documentation:** [blue-sampler.readthedocs.io](https://blue-sampler.readthedocs.io)
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
|
|
2
|
+
[build-system]
|
|
3
|
+
requires = ["hatchling>=1.26"]
|
|
4
|
+
build-backend = "hatchling.build"
|
|
5
|
+
|
|
6
|
+
[project]
|
|
7
|
+
name = "qmc-sampler"
|
|
8
|
+
version = "1.0.0"
|
|
9
|
+
description = "QMC sampling methods based on blue_sampler"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
|
|
14
|
+
keywords = [
|
|
15
|
+
"QMC",
|
|
16
|
+
"quasi-Monte Carlo",
|
|
17
|
+
"point sampling",
|
|
18
|
+
"hyperuniformity",
|
|
19
|
+
"wrap-around discrepancy",
|
|
20
|
+
"NUFFT",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
dependencies = [
|
|
24
|
+
"blue-sampler[keops]",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Repository = "https://github.com/For-a-few-DPPs-more/hyperuniform-samplers"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.build.targets.wheel]
|
|
31
|
+
packages = ["src/qmc_sampler"]
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build]
|
|
34
|
+
exclude = [
|
|
35
|
+
"**/*.ipynb",
|
|
36
|
+
"**/*.jpg",
|
|
37
|
+
"**/*.png",
|
|
38
|
+
"**/__pycache__",
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
line-length = 100
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
MESSAGE = """
|
|
2
|
+
qmc_sampler: lightweight wrapper around the blue_sampler python package for generating QMC
|
|
3
|
+
point set, see https://github.com/For-a-few-DPPs-more/hyperuniform-samplers
|
|
4
|
+
|
|
5
|
+
Available methods:
|
|
6
|
+
- sample_l2: uses a classical isotropic L2-ball as the spectral exclusion region.
|
|
7
|
+
- sample_l1: uses an L1-ball, which is anisotropic and can be useful for QMC
|
|
8
|
+
in settings with low effective dimensionality.
|
|
9
|
+
- sample_wd: uses the wrap-around discrepancy, further exploiting the
|
|
10
|
+
low-effective-dimensionality assumption.
|
|
11
|
+
|
|
12
|
+
For faster L2 sampling in 2D or 3D, a FINUFFT backend with O(N log N) complexity is available (instead of O(N^2)).
|
|
13
|
+
It requires GPU support and additional
|
|
14
|
+
dependencies:
|
|
15
|
+
pip install "blue_sampler[gpu3]"
|
|
16
|
+
|
|
17
|
+
Once installed, you will have to overwright the default sample_l2 implementation with this new version, which will use FINUFFT:
|
|
18
|
+
|
|
19
|
+
def sample_l2(N, D, **kwargs):
|
|
20
|
+
from blue_sampler.run.run_nufft import _nufft_pipeline
|
|
21
|
+
kwargs.setdefault("verbose", 0)
|
|
22
|
+
return _nufft_pipeline(N, D, **kwargs)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
print(MESSAGE)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
from .qmc_sampler import sample_l1, sample_wd
|
|
29
|
+
|
|
30
|
+
def sample_l2(N, D, **kwargs):
|
|
31
|
+
from blue_sampler.run.run_nufft_keops import _nufft_pipeline_keops
|
|
32
|
+
kwargs.setdefault("verbose", 0)
|
|
33
|
+
return _nufft_pipeline_keops(N, D, **kwargs)
|
|
34
|
+
|
|
35
|
+
def plot(*args, **kwargs):
|
|
36
|
+
from blue_sampler import plot as _plot
|
|
37
|
+
return _plot(*args, **kwargs)
|
|
38
|
+
|
|
39
|
+
def plot_structure_factor(*args, **kwargs):
|
|
40
|
+
from blue_sampler import plot_structure_factor as _psf
|
|
41
|
+
return _psf(*args, **kwargs)
|
|
42
|
+
|
|
43
|
+
__all__ = ["sample_l1", "sample_l2", "sample_wd", "plot", "plot_structure_factor"]
|
|
44
|
+
__version__ = "1.0"
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""
|
|
2
|
+
qmc_geom.py
|
|
3
|
+
-----------
|
|
4
|
+
Geometric utilities for Fourier mode selection on the unit torus.
|
|
5
|
+
|
|
6
|
+
Provides:
|
|
7
|
+
- Fourier weights of the SciPy wrap-around discrepancy (WD) kernel
|
|
8
|
+
- exact half-space WD mode selection by signed-permutation orbits
|
|
9
|
+
- classical L1-ball construction
|
|
10
|
+
- unified get_wave_vectors interface
|
|
11
|
+
|
|
12
|
+
The WD weights are the Fourier coefficients of the one-dimensional kernel
|
|
13
|
+
used by scipy.stats.qmc.discrepancy(..., method="WD"):
|
|
14
|
+
|
|
15
|
+
K(t) = 3/2 - |t| + |t|**2, for t in [0, 1],
|
|
16
|
+
|
|
17
|
+
with periodic extension. Its Fourier coefficients are 4/3 at frequency zero
|
|
18
|
+
and 1 / (2*pi**2*m**2) at every nonzero integer frequency.
|
|
19
|
+
|
|
20
|
+
Only one vector from each pair {k, -k} is retained: the first nonzero
|
|
21
|
+
coordinate must be positive.
|
|
22
|
+
|
|
23
|
+
Generating the wd ball, including efficient generation of all the orbitals,
|
|
24
|
+
is tricky and has been AI generated (could'nt do it alone).
|
|
25
|
+
"""
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
from collections import Counter
|
|
29
|
+
from itertools import combinations, count, product
|
|
30
|
+
from math import comb, factorial, log, pi
|
|
31
|
+
from typing import Iterator, List, Optional, Tuple
|
|
32
|
+
import heapq
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
CHI = 0.5
|
|
38
|
+
EPSILON = 1e-12
|
|
39
|
+
INV_TWO_PI_SQUARED = 1.0 / (2.0 * pi * pi)
|
|
40
|
+
ZERO_FREQUENCY_WEIGHT = 4.0 / 3.0
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _n_modes_target(N: int, D: int, chi: float = CHI) -> int:
|
|
44
|
+
return max(0, int(round(chi * D * (N - 1))))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _hatK(m: int) -> float:
|
|
48
|
+
"""One-dimensional Fourier coefficient of the WD kernel."""
|
|
49
|
+
m = abs(int(m))
|
|
50
|
+
if m == 0:
|
|
51
|
+
return ZERO_FREQUENCY_WEIGHT
|
|
52
|
+
return INV_TWO_PI_SQUARED / (m * m)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def wd_weight(K: np.ndarray) -> np.ndarray:
|
|
56
|
+
"""Return product WD Fourier weights for an array of integer vectors."""
|
|
57
|
+
abs_K = np.abs(np.asarray(K, dtype=np.float64))
|
|
58
|
+
factors = np.full(abs_K.shape, ZERO_FREQUENCY_WEIGHT, dtype=np.float64)
|
|
59
|
+
nonzero = abs_K != 0
|
|
60
|
+
factors[nonzero] = INV_TWO_PI_SQUARED / abs_K[nonzero] ** 2
|
|
61
|
+
return factors.prod(axis=1)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _orbit_size(k: Tuple[int, ...], D: int) -> int:
|
|
65
|
+
"""Count half-space modes in the signed-permutation orbit of k."""
|
|
66
|
+
s = len(k)
|
|
67
|
+
if s == 0 or s > D:
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
permutations_count = factorial(s)
|
|
71
|
+
for multiplicity in Counter(k).values():
|
|
72
|
+
permutations_count //= factorial(multiplicity)
|
|
73
|
+
|
|
74
|
+
return comb(D, s) * permutations_count * (1 << (s - 1))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _orbit_weight(k: Tuple[int, ...], D: int) -> float:
|
|
78
|
+
"""Return the common WD Fourier weight of an orbit."""
|
|
79
|
+
s = len(k)
|
|
80
|
+
weight = ZERO_FREQUENCY_WEIGHT ** (D - s)
|
|
81
|
+
for frequency in k:
|
|
82
|
+
weight *= _hatK(frequency)
|
|
83
|
+
return weight
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _log_orbit_weight(k: Tuple[int, ...], D: int) -> float:
|
|
87
|
+
"""Log weight used for stable priority-queue ordering."""
|
|
88
|
+
s = len(k)
|
|
89
|
+
return (
|
|
90
|
+
(D - s) * log(ZERO_FREQUENCY_WEIGHT)
|
|
91
|
+
+ s * log(INV_TWO_PI_SQUARED)
|
|
92
|
+
- 2.0 * sum(log(frequency) for frequency in k)
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _distinct_permutations(values: Tuple[int, ...]) -> Iterator[Tuple[int, ...]]:
|
|
97
|
+
"""Yield distinct permutations without materializing duplicates."""
|
|
98
|
+
counts = Counter(values)
|
|
99
|
+
choices = sorted(counts, reverse=True)
|
|
100
|
+
length = len(values)
|
|
101
|
+
current: List[int] = []
|
|
102
|
+
|
|
103
|
+
def visit() -> Iterator[Tuple[int, ...]]:
|
|
104
|
+
if len(current) == length:
|
|
105
|
+
yield tuple(current)
|
|
106
|
+
return
|
|
107
|
+
for value in choices:
|
|
108
|
+
if counts[value] == 0:
|
|
109
|
+
continue
|
|
110
|
+
counts[value] -= 1
|
|
111
|
+
current.append(value)
|
|
112
|
+
yield from visit()
|
|
113
|
+
current.pop()
|
|
114
|
+
counts[value] += 1
|
|
115
|
+
|
|
116
|
+
yield from visit()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _expand_half_orbit(
|
|
120
|
+
k: Tuple[int, ...],
|
|
121
|
+
D: int,
|
|
122
|
+
limit: Optional[int] = None,
|
|
123
|
+
) -> Iterator[Tuple[int, ...]]:
|
|
124
|
+
"""Yield distinct orbit vectors whose first nonzero entry is positive."""
|
|
125
|
+
s = len(k)
|
|
126
|
+
if s == 0 or s > D or limit == 0:
|
|
127
|
+
return
|
|
128
|
+
|
|
129
|
+
emitted = 0
|
|
130
|
+
for positions in combinations(range(D), s):
|
|
131
|
+
for values in _distinct_permutations(k):
|
|
132
|
+
for tail_signs in product((-1, 1), repeat=s - 1):
|
|
133
|
+
signs = (1,) + tail_signs
|
|
134
|
+
vector = [0] * D
|
|
135
|
+
for position, value, sign in zip(positions, values, signs):
|
|
136
|
+
vector[position] = value * sign
|
|
137
|
+
|
|
138
|
+
yield tuple(vector)
|
|
139
|
+
emitted += 1
|
|
140
|
+
if limit is not None and emitted >= limit:
|
|
141
|
+
return
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def half_wd_ball(
|
|
145
|
+
D: int,
|
|
146
|
+
M: int,
|
|
147
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
148
|
+
"""
|
|
149
|
+
Return the M highest-weight nonzero WD modes in the half-space.
|
|
150
|
+
|
|
151
|
+
Orbit representatives are nonincreasing positive integer tuples. A
|
|
152
|
+
best-first heap explores the infinite set of representatives in exact
|
|
153
|
+
nonincreasing weight order. Unlike a fixed frequency cutoff, this gives
|
|
154
|
+
an exact top-M selection without omitting potentially better modes.
|
|
155
|
+
|
|
156
|
+
"""
|
|
157
|
+
if D < 1:
|
|
158
|
+
raise ValueError("D must be at least 1")
|
|
159
|
+
if M <= 0:
|
|
160
|
+
return np.empty((0, D), dtype=np.int32), np.empty(0, dtype=np.float64)
|
|
161
|
+
|
|
162
|
+
# Heap entries are (-log_weight, tie_breaker, canonical_tuple).
|
|
163
|
+
# Canonical tuples are nonincreasing and contain only positive values.
|
|
164
|
+
queue = []
|
|
165
|
+
serial = count()
|
|
166
|
+
seen = set()
|
|
167
|
+
|
|
168
|
+
for support in range(1, D + 1):
|
|
169
|
+
representative = (1,) * support
|
|
170
|
+
seen.add(representative)
|
|
171
|
+
heapq.heappush(
|
|
172
|
+
queue,
|
|
173
|
+
(-_log_orbit_weight(representative, D), next(serial), representative),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
vectors: List[Tuple[int, ...]] = []
|
|
177
|
+
weights: List[float] = []
|
|
178
|
+
|
|
179
|
+
while len(vectors) < M:
|
|
180
|
+
if not queue:
|
|
181
|
+
raise RuntimeError("Orbit search unexpectedly exhausted.")
|
|
182
|
+
|
|
183
|
+
_, _, representative = heapq.heappop(queue)
|
|
184
|
+
orbit_size = _orbit_size(representative, D)
|
|
185
|
+
remaining = M - len(vectors)
|
|
186
|
+
take = min(orbit_size, remaining)
|
|
187
|
+
orbit_weight = _orbit_weight(representative, D)
|
|
188
|
+
|
|
189
|
+
vectors.extend(_expand_half_orbit(representative, D, limit=take))
|
|
190
|
+
weights.extend([orbit_weight] * take)
|
|
191
|
+
|
|
192
|
+
# If the requested cutoff falls inside this orbit, all its modes have
|
|
193
|
+
# the same weight and every unvisited orbit has no larger weight.
|
|
194
|
+
if take < orbit_size:
|
|
195
|
+
break
|
|
196
|
+
|
|
197
|
+
# Increasing any frequency creates a lower-weight representative.
|
|
198
|
+
# These monotone neighbours enumerate every canonical tuple.
|
|
199
|
+
for index, frequency in enumerate(representative):
|
|
200
|
+
if index > 0 and frequency == representative[index - 1]:
|
|
201
|
+
continue
|
|
202
|
+
|
|
203
|
+
child = list(representative)
|
|
204
|
+
child[index] += 1
|
|
205
|
+
child_tuple = tuple(child)
|
|
206
|
+
if child_tuple not in seen:
|
|
207
|
+
seen.add(child_tuple)
|
|
208
|
+
heapq.heappush(
|
|
209
|
+
queue,
|
|
210
|
+
(
|
|
211
|
+
-_log_orbit_weight(child_tuple, D),
|
|
212
|
+
next(serial),
|
|
213
|
+
child_tuple,
|
|
214
|
+
),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
K = np.asarray(vectors, dtype=np.int32).reshape(M, D)
|
|
218
|
+
r = np.asarray(weights, dtype=np.float64)
|
|
219
|
+
return K, r
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
# ------------------------------------------------------------------
|
|
223
|
+
# L1 helpers (unchanged)
|
|
224
|
+
# ------------------------------------------------------------------
|
|
225
|
+
def _count_l1_ball(D, radius):
|
|
226
|
+
return sum((2 ** j) * comb(D, j) * comb(radius, j)
|
|
227
|
+
for j in range(min(D, radius) + 1))
|
|
228
|
+
|
|
229
|
+
def _full_l1_ball(D, radius):
|
|
230
|
+
if D == 1:
|
|
231
|
+
return np.arange(-radius, radius + 1, dtype=np.int32)[:, None]
|
|
232
|
+
prev = _full_l1_ball(D - 1, radius)
|
|
233
|
+
prev_norm = np.abs(prev.astype(np.int64)).sum(1)
|
|
234
|
+
remaining = radius - prev_norm
|
|
235
|
+
counts = 2 * remaining + 1
|
|
236
|
+
total = int(counts.sum())
|
|
237
|
+
wdts = np.cumsum(counts, dtype=np.int64) - counts
|
|
238
|
+
row_ids = np.repeat(np.arange(len(prev), dtype=np.int64), counts)
|
|
239
|
+
z = np.arange(total, dtype=np.int64) - np.repeat(wdts, counts)
|
|
240
|
+
z -= np.repeat(remaining, counts)
|
|
241
|
+
return np.concatenate([prev[row_ids], z.astype(np.int32)[:, None]], 1)
|
|
242
|
+
|
|
243
|
+
def _half_l1_ball(D, radius):
|
|
244
|
+
if radius <= 0:
|
|
245
|
+
return np.empty((0, D), dtype=np.int32)
|
|
246
|
+
if D == 1:
|
|
247
|
+
return np.arange(1, radius + 1, dtype=np.int32)[:, None]
|
|
248
|
+
prev = _full_l1_ball(D - 1, radius)
|
|
249
|
+
prev_norm = np.abs(prev.astype(np.int64)).sum(1)
|
|
250
|
+
max_z = radius - prev_norm
|
|
251
|
+
counts = max_z
|
|
252
|
+
total = int(counts.sum())
|
|
253
|
+
if total:
|
|
254
|
+
wdts = np.cumsum(counts, dtype=np.int64) - counts
|
|
255
|
+
row_ids = np.repeat(np.arange(len(prev), dtype=np.int64), counts)
|
|
256
|
+
z = np.arange(total, dtype=np.int64) - np.repeat(wdts, counts) + 1
|
|
257
|
+
positive_part = np.concatenate(
|
|
258
|
+
[prev[row_ids], z.astype(np.int32)[:, None]], 1)
|
|
259
|
+
else:
|
|
260
|
+
positive_part = np.empty((0, D), dtype=np.int32)
|
|
261
|
+
previous_half = _half_l1_ball(D - 1, radius)
|
|
262
|
+
zero_part = np.concatenate(
|
|
263
|
+
[previous_half, np.zeros((len(previous_half), 1), dtype=np.int32)], 1)
|
|
264
|
+
return np.concatenate([positive_part, zero_part], 0)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def get_wave_vectors(
|
|
268
|
+
N: int,
|
|
269
|
+
D: int,
|
|
270
|
+
mode: str = "wd",
|
|
271
|
+
chi: float = CHI,
|
|
272
|
+
rng: Optional[np.random.Generator] = None,
|
|
273
|
+
epsilon: float = EPSILON,
|
|
274
|
+
):
|
|
275
|
+
rng = np.random.default_rng() if rng is None else rng
|
|
276
|
+
M_target = _n_modes_target(N, D, chi)
|
|
277
|
+
if M_target == 0:
|
|
278
|
+
empty = np.empty((0, D), dtype=np.int32)
|
|
279
|
+
return empty, np.empty(0, dtype=np.int64), np.empty(0), 0
|
|
280
|
+
if mode == "wd":
|
|
281
|
+
K, r = half_wd_ball(D, M_target)
|
|
282
|
+
weights = r / (r.max() + epsilon)
|
|
283
|
+
elif mode == "l1":
|
|
284
|
+
radius = 1
|
|
285
|
+
while (_count_l1_ball(D, radius) - 1) // 2 < M_target:
|
|
286
|
+
radius *= 2
|
|
287
|
+
low, high = max(1, radius // 2), radius
|
|
288
|
+
while low < high:
|
|
289
|
+
mid = (low + high) // 2
|
|
290
|
+
if (_count_l1_ball(D, mid) - 1) // 2 >= M_target:
|
|
291
|
+
high = mid
|
|
292
|
+
else:
|
|
293
|
+
low = mid + 1
|
|
294
|
+
radius = low
|
|
295
|
+
K = _half_l1_ball(D, radius)
|
|
296
|
+
score = np.abs(K).sum(1)
|
|
297
|
+
order = np.lexsort((rng.random(len(score)), score))[:M_target]
|
|
298
|
+
K = K[order]
|
|
299
|
+
raw = 1.0 / (score[order].astype(np.float64) ** 2 + epsilon)
|
|
300
|
+
weights = raw / raw.max()
|
|
301
|
+
else:
|
|
302
|
+
raise ValueError(f"Unknown mode '{mode}'. Choose 'wd' or 'l1'.")
|
|
303
|
+
K = np.ascontiguousarray(K.astype(np.int32))
|
|
304
|
+
kl1 = np.abs(K).sum(1).astype(np.int64)
|
|
305
|
+
return K, kl1, weights.astype(np.float64), len(K)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _check_orbits(D: int, max_frequency: int = 4) -> bool:
|
|
309
|
+
"""Run small exhaustive checks of orbit counts, signs, and weights."""
|
|
310
|
+
from itertools import combinations_with_replacement
|
|
311
|
+
|
|
312
|
+
for support in range(1, D + 1):
|
|
313
|
+
for ascending in combinations_with_replacement(
|
|
314
|
+
range(1, max_frequency + 1), support
|
|
315
|
+
):
|
|
316
|
+
representative = tuple(reversed(ascending))
|
|
317
|
+
modes = list(_expand_half_orbit(representative, D))
|
|
318
|
+
assert len(modes) == _orbit_size(representative, D)
|
|
319
|
+
assert len(set(modes)) == len(modes)
|
|
320
|
+
|
|
321
|
+
for vector in modes:
|
|
322
|
+
first_nonzero = next(value for value in vector if value != 0)
|
|
323
|
+
assert first_nonzero > 0
|
|
324
|
+
assert np.isclose(
|
|
325
|
+
np.prod([_hatK(value) for value in vector]),
|
|
326
|
+
_orbit_weight(representative, D),
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
return True
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""
|
|
2
|
+
see https://github.com/For-a-few-DPPs-more/Recursive-Gaussian-Blue-Noise/blob/main/src/blue_sampler/run/run_nufft.py:
|
|
3
|
+
same but:
|
|
4
|
+
- L1 ball instead of L2 ball
|
|
5
|
+
- keops backend instead of finufft
|
|
6
|
+
- "wd" mode: gradient descent on the *exact* WD discrepancy (no Fourier
|
|
7
|
+
truncation), warm-started from the L1 (chi=0.5) optimum
|
|
8
|
+
|
|
9
|
+
Common API: every mode provides a `loss_and_grad(points) -> (loss, grad)` and
|
|
10
|
+
`minimize` runs the same adaptive normalised-gradient / bold-driver descent.
|
|
11
|
+
|
|
12
|
+
There is no .prod() over the feature axis in KeOps, hence the products over
|
|
13
|
+
dimensions are written as exp(sum(log(.))).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import time
|
|
19
|
+
from math import pi
|
|
20
|
+
from typing import Callable, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from .qmc_geom import CHI, get_wave_vectors
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ------------------------------------------------------------------
|
|
28
|
+
# Global defaults
|
|
29
|
+
# ------------------------------------------------------------------
|
|
30
|
+
EPSILON = 1e-12
|
|
31
|
+
PRECISION = "float32"
|
|
32
|
+
NITER = 150
|
|
33
|
+
LR = 1.0
|
|
34
|
+
|
|
35
|
+
real_dtype = np.float32 if PRECISION == "float32" else np.float64
|
|
36
|
+
complex_dtype = np.complex64 if PRECISION == "float32" else np.complex128
|
|
37
|
+
two_pi = 2.0 * pi
|
|
38
|
+
|
|
39
|
+
# Max number of elements of one (block, N, D) temporary in the torch fallback
|
|
40
|
+
# (KeOps never materialises it, so it processes all rows at once).
|
|
41
|
+
_TORCH_MAX_ELEMS = 2e7
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
try:
|
|
45
|
+
from pykeops.numpy import LazyTensor
|
|
46
|
+
|
|
47
|
+
HAS_KEOPS = True
|
|
48
|
+
|
|
49
|
+
def to_numpy(x):
|
|
50
|
+
return np.asarray(x)
|
|
51
|
+
|
|
52
|
+
except ImportError:
|
|
53
|
+
import torch
|
|
54
|
+
|
|
55
|
+
HAS_KEOPS = False
|
|
56
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
57
|
+
_torch_dtype = torch.float32 if PRECISION == "float32" else torch.float64
|
|
58
|
+
|
|
59
|
+
def LazyTensor(x):
|
|
60
|
+
return torch.as_tensor(x, dtype=_torch_dtype, device=device)
|
|
61
|
+
|
|
62
|
+
def to_numpy(x):
|
|
63
|
+
if isinstance(x, torch.Tensor):
|
|
64
|
+
return x.detach().cpu().numpy()
|
|
65
|
+
return np.asarray(x)
|
|
66
|
+
|
|
67
|
+
def sum0(x):
|
|
68
|
+
return to_numpy(x.sum(0))
|
|
69
|
+
|
|
70
|
+
def sum1(x):
|
|
71
|
+
return to_numpy(x.sum(1))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
LossAndGrad = Callable[[np.ndarray], Tuple[float, np.ndarray]]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# ------------------------------------------------------------------
|
|
78
|
+
# Wrappers (for convenience)
|
|
79
|
+
# ------------------------------------------------------------------
|
|
80
|
+
def sample_l1(N, D):
|
|
81
|
+
return sample(N, D, "l1", verbose=0, strict = False)
|
|
82
|
+
|
|
83
|
+
def sample_wd(N, D):
|
|
84
|
+
return sample(N, D, "wd", verbose=0, strict = True)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ------------------------------------------------------------------
|
|
88
|
+
# Common optimiser
|
|
89
|
+
# ------------------------------------------------------------------
|
|
90
|
+
def minimize(
|
|
91
|
+
x: np.ndarray,
|
|
92
|
+
loss_and_grad: LossAndGrad,
|
|
93
|
+
n_iter: int = NITER,
|
|
94
|
+
lr: float = LR,
|
|
95
|
+
verbose: int = 1,
|
|
96
|
+
strict: bool = False,
|
|
97
|
+
) -> np.ndarray:
|
|
98
|
+
"""
|
|
99
|
+
Adaptive normalised-gradient descent on the torus (bold-driver step).
|
|
100
|
+
|
|
101
|
+
loss_and_grad(x) must return (float loss, grad array with the shape of x).
|
|
102
|
+
strict=False reproduces the historical behaviour (always move, only the
|
|
103
|
+
step size reacts to a loss increase); strict=True returns to the best
|
|
104
|
+
point seen so far (with a smaller step) when the loss does not decrease.
|
|
105
|
+
"""
|
|
106
|
+
N, D = x.shape
|
|
107
|
+
adaptive = lr * 0.1 * N ** (-1.0 / D)
|
|
108
|
+
prev_loss = np.inf
|
|
109
|
+
x_best = g_best = None
|
|
110
|
+
|
|
111
|
+
t0 = time.time()
|
|
112
|
+
for it in range(n_iter):
|
|
113
|
+
loss, grad = loss_and_grad(x)
|
|
114
|
+
improved = loss < prev_loss
|
|
115
|
+
|
|
116
|
+
if strict and not improved and x_best is not None:
|
|
117
|
+
# reject: go back to the best point with a smaller step
|
|
118
|
+
adaptive *= 0.8
|
|
119
|
+
x, grad = x_best, g_best
|
|
120
|
+
|
|
121
|
+
rms = float(np.sqrt(np.mean(grad * grad) + 1e-30))
|
|
122
|
+
step = (grad / rms) * adaptive
|
|
123
|
+
x_new = np.mod(x - step, 1.0).astype(real_dtype)
|
|
124
|
+
|
|
125
|
+
# bold-driver
|
|
126
|
+
if improved:
|
|
127
|
+
adaptive *= 1.05
|
|
128
|
+
prev_loss = loss
|
|
129
|
+
x_best, g_best = x, grad
|
|
130
|
+
elif not strict:
|
|
131
|
+
adaptive *= 0.8
|
|
132
|
+
# historical behaviour: always move, only the step size adapts
|
|
133
|
+
x = x_new
|
|
134
|
+
|
|
135
|
+
if verbose and (it % 20 == 0 or it == n_iter - 1):
|
|
136
|
+
print(f" iter {it:4d} | loss {loss:.3e}")
|
|
137
|
+
|
|
138
|
+
if verbose:
|
|
139
|
+
print(f"done in {time.time() - t0:.1f}s")
|
|
140
|
+
|
|
141
|
+
return np.asarray(x)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# ------------------------------------------------------------------
|
|
145
|
+
# Loss / gradient factory: truncated Fourier energy on an L1 ball
|
|
146
|
+
# ------------------------------------------------------------------
|
|
147
|
+
def make_l1_loss_and_grad(
|
|
148
|
+
N: int,
|
|
149
|
+
D: int,
|
|
150
|
+
chi: float,
|
|
151
|
+
rng: np.random.Generator,
|
|
152
|
+
target: Optional[np.ndarray] = None,
|
|
153
|
+
):
|
|
154
|
+
K, kl1, w, M = get_wave_vectors(N, D, mode="l1", chi=chi, rng=rng)
|
|
155
|
+
k_coords = np.ascontiguousarray(K.astype(real_dtype))
|
|
156
|
+
norm = float(max(M, 1))
|
|
157
|
+
|
|
158
|
+
# optional target spectrum
|
|
159
|
+
if target is not None:
|
|
160
|
+
tx = LazyTensor(target[:, None, :])
|
|
161
|
+
tk = LazyTensor(k_coords[None, :, :])
|
|
162
|
+
phase = two_pi * (tx * tk).sum(-1)
|
|
163
|
+
tr = np.asarray(sum0(phase.cos())).ravel()
|
|
164
|
+
ti = -np.asarray(sum0(phase.sin())).ravel()
|
|
165
|
+
fk_target = ((tr + 1j * ti) / target.shape[0]).astype(complex_dtype)
|
|
166
|
+
else:
|
|
167
|
+
fk_target = np.zeros(M, dtype=complex_dtype)
|
|
168
|
+
|
|
169
|
+
fk_tr = np.ascontiguousarray(fk_target.real.astype(real_dtype))
|
|
170
|
+
fk_ti = np.ascontiguousarray(fk_target.imag.astype(real_dtype))
|
|
171
|
+
k_j = LazyTensor(k_coords[None, :, :])
|
|
172
|
+
|
|
173
|
+
def fourier_modes(pts):
|
|
174
|
+
xi = LazyTensor(pts[:, None, :])
|
|
175
|
+
phase = two_pi * (xi * k_j).sum(-1)
|
|
176
|
+
fr = np.asarray(sum0(phase.cos())).ravel() / N
|
|
177
|
+
fi = -np.asarray(sum0(phase.sin())).ravel() / N
|
|
178
|
+
return fr.astype(real_dtype), fi.astype(real_dtype)
|
|
179
|
+
|
|
180
|
+
def loss_and_grad(pts):
|
|
181
|
+
fr, fi = fourier_modes(pts)
|
|
182
|
+
dr = fr - fk_tr
|
|
183
|
+
di = fi - fk_ti
|
|
184
|
+
loss = float(np.sum(w * (dr ** 2 + di ** 2)) / norm)
|
|
185
|
+
|
|
186
|
+
pref = 2.0 / norm * (-two_pi) / N
|
|
187
|
+
cr = np.ascontiguousarray((pref * w * dr).astype(real_dtype))
|
|
188
|
+
ci = np.ascontiguousarray((pref * w * di).astype(real_dtype))
|
|
189
|
+
|
|
190
|
+
xi = LazyTensor(pts[:, None, :])
|
|
191
|
+
crj = LazyTensor(cr[None, :, None])
|
|
192
|
+
cij = LazyTensor(ci[None, :, None])
|
|
193
|
+
phase = two_pi * (xi * k_j).sum(-1, keepdim=True)
|
|
194
|
+
scalar = crj * phase.sin() + cij * phase.cos()
|
|
195
|
+
grad = sum1(scalar * k_j)
|
|
196
|
+
return loss, np.asarray(grad).astype(real_dtype)
|
|
197
|
+
|
|
198
|
+
return loss_and_grad, M
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ------------------------------------------------------------------
|
|
202
|
+
# Loss / gradient factory: exact WD discrepancy
|
|
203
|
+
# ------------------------------------------------------------------
|
|
204
|
+
def make_wd_loss_and_grad(N: int, D: int, block: Optional[int] = None):
|
|
205
|
+
"""
|
|
206
|
+
Exact squared wrap-around discrepancy and its gradient.
|
|
207
|
+
|
|
208
|
+
WD^2(x) = -(4/3)^D + 1/N^2 sum_{i,j} P_ij,
|
|
209
|
+
P_ij = prod_d g(x_id - x_jd), g(delta) = 3/2 - |delta| + delta^2.
|
|
210
|
+
|
|
211
|
+
g >= 5/4 > 0, so P_ij = exp( sum_d log g_ijd ): a plain `.sum(-1)` is all
|
|
212
|
+
that is needed (no product over the feature axis).
|
|
213
|
+
|
|
214
|
+
Logarithmic derivative: d log P_ij / d x_id = g'(delta_ijd) / g_ijd with
|
|
215
|
+
g'(delta) = 2 delta - sign(delta) (odd, = 0 on the diagonal i=j), hence
|
|
216
|
+
|
|
217
|
+
dWD^2/dx_id = 2/N^2 * sum_j P_ij * g'(delta_ijd) / g_ijd
|
|
218
|
+
|
|
219
|
+
(the factor 2 comes from the symmetry P_ij = P_ji). Cost O(N^2 D), versus
|
|
220
|
+
O(N^2 D^2) for "product of the other coordinates".
|
|
221
|
+
|
|
222
|
+
The loss is accumulated as sum(P_ij - (4/3)^D), which keeps the row sums
|
|
223
|
+
small and avoids most of the float32 cancellation against (4/3)^D.
|
|
224
|
+
"""
|
|
225
|
+
const = (4.0 / 3.0) ** D
|
|
226
|
+
inv_n2 = 1.0 / float(N) ** 2
|
|
227
|
+
if block is None:
|
|
228
|
+
block = N if HAS_KEOPS else max(1, int(_TORCH_MAX_ELEMS // (N * D)))
|
|
229
|
+
block = min(block, N)
|
|
230
|
+
|
|
231
|
+
def loss_and_grad(pts):
|
|
232
|
+
xj = LazyTensor(pts[None, :, :])
|
|
233
|
+
grad = np.empty((N, D), dtype=real_dtype)
|
|
234
|
+
total = 0.0
|
|
235
|
+
for i0 in range(0, N, block):
|
|
236
|
+
i1 = min(i0 + block, N)
|
|
237
|
+
xi = LazyTensor(pts[i0:i1, None, :])
|
|
238
|
+
|
|
239
|
+
delta = xi - xj # (block, N, D)
|
|
240
|
+
t = delta.abs()
|
|
241
|
+
g = t * t - t + 1.5 # 3/2 - |d| + d^2
|
|
242
|
+
logP = g.log().sum(-1, keepdim=True) # (block, N, 1)
|
|
243
|
+
P = logP.exp()
|
|
244
|
+
|
|
245
|
+
total += float(np.sum(sum1(P - const), dtype=np.float64))
|
|
246
|
+
|
|
247
|
+
dg = 2.0 * delta - delta.sign() # g'(delta)
|
|
248
|
+
grad[i0:i1] = 2.0 * inv_n2 * sum1(P * dg / g)
|
|
249
|
+
|
|
250
|
+
return total * inv_n2, grad
|
|
251
|
+
|
|
252
|
+
return loss_and_grad
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
# ------------------------------------------------------------------
|
|
256
|
+
# Main pipeline
|
|
257
|
+
# ------------------------------------------------------------------
|
|
258
|
+
def sample(
|
|
259
|
+
N,
|
|
260
|
+
D,
|
|
261
|
+
mode,
|
|
262
|
+
chi: float = CHI,
|
|
263
|
+
target: Optional[np.ndarray] = None,
|
|
264
|
+
seed: Optional[int] = None,
|
|
265
|
+
n_iter: int = NITER,
|
|
266
|
+
lr: float = LR,
|
|
267
|
+
verbose: int = 1,
|
|
268
|
+
warmstart: Optional[np.ndarray] = None,
|
|
269
|
+
strict: bool = False,
|
|
270
|
+
block: Optional[int] = None,
|
|
271
|
+
):
|
|
272
|
+
"""
|
|
273
|
+
Generate a low-discrepancy point set on [0,1)^D by optimisation.
|
|
274
|
+
|
|
275
|
+
Parameters
|
|
276
|
+
----------
|
|
277
|
+
N : number of points
|
|
278
|
+
D : dimension
|
|
279
|
+
mode : "l1" -> truncated Fourier energy on a half L1 ball
|
|
280
|
+
"wd" -> exact WD discrepancy, warm-started from "l1"
|
|
281
|
+
(chi=0.5, same n_iter, same seed) unless `warmstart`
|
|
282
|
+
is given
|
|
283
|
+
chi : fraction of degrees of freedom kept as Fourier modes ("l1" only)
|
|
284
|
+
target : optional target point cloud for non-uniform densities ("l1" only)
|
|
285
|
+
seed : random seed
|
|
286
|
+
n_iter : number of gradient steps (for each stage)
|
|
287
|
+
lr : base learning-rate scale
|
|
288
|
+
verbose : print progress
|
|
289
|
+
warmstart: optional warm start for the point cloud, eg a Sobol sequence
|
|
290
|
+
strict : reject steps that do not decrease the loss
|
|
291
|
+
block : rows per block in the "wd" kernel (only matters for torch)
|
|
292
|
+
|
|
293
|
+
Returns
|
|
294
|
+
-------
|
|
295
|
+
x : (N, D) array of points in [0,1)^D
|
|
296
|
+
"""
|
|
297
|
+
if mode not in ("l1", "wd"):
|
|
298
|
+
raise ValueError(f"Unknown mode '{mode}'. Choose 'l1' or 'wd'.")
|
|
299
|
+
if mode == "wd" and target is not None:
|
|
300
|
+
raise ValueError("mode='wd' only supports the uniform measure (target=None).")
|
|
301
|
+
|
|
302
|
+
rng = np.random.default_rng(seed)
|
|
303
|
+
if warmstart is None and mode == "wd":
|
|
304
|
+
warmstart = sample(N, D, "l1", chi=0.5, target=target, seed=seed,
|
|
305
|
+
n_iter=n_iter, lr=lr, verbose=verbose, strict=strict)
|
|
306
|
+
x = rng.uniform(size=(N, D)).astype(real_dtype) if warmstart is None \
|
|
307
|
+
else np.ascontiguousarray(warmstart, dtype=real_dtype)
|
|
308
|
+
|
|
309
|
+
if mode == "l1":
|
|
310
|
+
loss_and_grad, M = make_l1_loss_and_grad(N, D, chi, rng, target)
|
|
311
|
+
if verbose:
|
|
312
|
+
print(f"[keops-l1] N={N} D={D} modes={M} chi={chi:.3f}")
|
|
313
|
+
else:
|
|
314
|
+
loss_and_grad = make_wd_loss_and_grad(N, D, block=block)
|
|
315
|
+
if verbose:
|
|
316
|
+
print(f"[keops-wd] N={N} D={D} exact WD^2")
|
|
317
|
+
|
|
318
|
+
return minimize(x, loss_and_grad, n_iter=n_iter, lr=lr,
|
|
319
|
+
verbose=verbose, strict=strict)
|