6"""Generate Voronoi sites without fitting k-means."""
8from operator
import index
11from scipy.spatial.distance
import cdist
12from scipy.stats
import qmc
14__all__ = [
"generate_centroids"]
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)]
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.
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.
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.")
50 with np.errstate(over=
"ignore"):
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.")
57 rng = np.random.default_rng(seed)
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)
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.")