QDpy
Loading...
Searching...
No Matches
centroids.py
Go to the documentation of this file.
1# SPDX-License-Identifier: LGPL-3.0-or-later
2
5
6"""Generate Voronoi sites without fitting k-means."""
7
8from operator import index
9
10import numpy as np
11from scipy.spatial.distance import cdist
12from scipy.stats import qmc
13
14__all__ = ["generate_centroids"]
15
16
17def _blue_noise(count, dimension, candidates, rng):
18 sites = np.empty((count, dimension))
19 sites[0] = rng.random(dimension)
20 for i in range(1, count):
21 pool = rng.random((candidates, dimension))
22 nearest = cdist(pool, sites[:i], metric="sqeuclidean").min(axis=1)
23 sites[i] = pool[np.argmax(nearest)]
24 return sites
25
26
27
34def generate_centroids(count, features_domain, *, method="sobol", seed=0, blue_noise_candidates=32):
35 """Generate sites for ``CVTGrid(centroids=...)`` without changing its default geometry.
36
37 Scramble Sobol and Halton sequences. Any positive count is supported.
38 For Sobol, retain the prefix of the next power-of-two block. Blue noise
39 starts uniformly and repeatedly selects the best-separated candidate
40 from a fresh uniform pool. Separation is measured in normalized
41 coordinates before applying the requested physical bounds.
42 """
43 count, candidates = index(count), index(blue_noise_candidates)
44 bounds = np.asarray(tuple(features_domain), dtype=float)
45 if count <= 0 or candidates <= 0:
46 raise ValueError("Use positive centroid and blue-noise candidate counts.")
47 if bounds.ndim != 2 or bounds.shape[1] != 2 or not bounds.shape[0] or not np.isfinite(bounds).all():
48 raise ValueError("Use nonempty finite feature intervals.")
49 low, high = bounds.T
50 with np.errstate(over="ignore"):
51 span = high - low
52 if not (np.isfinite(span) & (span > 0)).all():
53 raise ValueError("Feature intervals must have a finite, positive span.")
54 if method not in ("sobol", "halton", "blue-noise", "uniform"):
55 raise ValueError("Choose sobol, halton, blue-noise, or uniform.")
56 dimension = len(span)
57 rng = np.random.default_rng(seed)
58 if method == "sobol":
59 points = qmc.Sobol(dimension, seed=rng).random_base2((count - 1).bit_length())[:count]
60 elif method == "halton":
61 points = qmc.Halton(dimension, seed=rng).random(count)
62 elif method == "blue-noise":
63 points = _blue_noise(count, dimension, candidates, rng)
64 else:
65 points = rng.random((count, dimension))
66 scaled = np.clip(low + points * span, low, high)
67 if len(np.unique(scaled, axis=0)) != count:
68 raise ValueError("Site coordinates collapsed to duplicates. Check feature scales and count.")
69 return scaled