Source code for qdpy.containers.centroids
# SPDX-License-Identifier: LGPL-3.0-or-later
## @file
# @brief Seeded point generators for nearest-centroid archives.
# @see https://doi.org/10.1145/3583133.3590726
"""Generate Voronoi sites without fitting k-means."""
from operator import index
import numpy as np
from scipy.spatial.distance import cdist
from scipy.stats import qmc
__all__ = ["generate_centroids"]
def _blue_noise(count, dimension, candidates, rng):
sites = np.empty((count, dimension))
sites[0] = rng.random(dimension)
for i in range(1, count):
pool = rng.random((candidates, dimension))
nearest = cdist(pool, sites[:i], metric="sqeuclidean").min(axis=1)
sites[i] = pool[np.argmax(nearest)]
return sites
## @brief Generate sites for CVTGrid using unit-cube point sampling.
# @param count Number of distinct sites.
# @param features_domain Finite increasing intervals, one per dimension.
# @param method Site generator, "sobol", "halton", "blue-noise", or "uniform".
# @param seed Seed for the private NumPy generator.
# @param blue_noise_candidates Pool size for each best-candidate step.
# @return A float64 site matrix scaled into the requested feature domain.
[docs]
def generate_centroids(count, features_domain, *, method="sobol", seed=0, blue_noise_candidates=32):
"""Generate sites for ``CVTGrid(centroids=...)`` without changing its default geometry.
Scramble Sobol and Halton sequences. Any positive count is supported.
For Sobol, retain the prefix of the next power-of-two block. Blue noise
starts uniformly and repeatedly selects the best-separated candidate
from a fresh uniform pool. Separation is measured in normalized
coordinates before applying the requested physical bounds.
"""
count, candidates = index(count), index(blue_noise_candidates)
bounds = np.asarray(tuple(features_domain), dtype=float)
if count <= 0 or candidates <= 0:
raise ValueError("Use positive centroid and blue-noise candidate counts.")
if bounds.ndim != 2 or bounds.shape[1] != 2 or not bounds.shape[0] or not np.isfinite(bounds).all():
raise ValueError("Use nonempty finite feature intervals.")
low, high = bounds.T
with np.errstate(over="ignore"):
span = high - low
if not (np.isfinite(span) & (span > 0)).all():
raise ValueError("Feature intervals must have a finite, positive span.")
if method not in ("sobol", "halton", "blue-noise", "uniform"):
raise ValueError("Choose sobol, halton, blue-noise, or uniform.")
dimension = len(span)
rng = np.random.default_rng(seed)
if method == "sobol":
points = qmc.Sobol(dimension, seed=rng).random_base2((count - 1).bit_length())[:count]
elif method == "halton":
points = qmc.Halton(dimension, seed=rng).random(count)
elif method == "blue-noise":
points = _blue_noise(count, dimension, candidates, rng)
else:
points = rng.random((count, dimension))
scaled = np.clip(low + points * span, low, high)
if len(np.unique(scaled, axis=0)) != count:
raise ValueError("Site coordinates collapsed to duplicates. Check feature scales and count.")
return scaled