Skip to content

Instantly share code, notes, and snippets.

@tupui
Last active August 9, 2021 05:40
Show Gist options
  • Save tupui/3800794516775aaa3d0a45da60ede337 to your computer and use it in GitHub Desktop.
Save tupui/3800794516775aaa3d0a45da60ede337 to your computer and use it in GitHub Desktop.
Centroidal Voronoi Tessellation to generate sample: Lloyd's algorithm
"""Centroidal Voronoi Tessellation to generate sample: Lloyd's algorithm.
Based on the implementation of Stéfan van der Walt
https://github.com/stefanv/lloyd
which is:
Copyright (c) 2021-04-21 Stéfan van der Walt https://github.com/stefanv/lloyd
MIT License
---------------------------
MIT License
Copyright (c) 2021 Pamphile Tupui ROY
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import functools
import numpy as np
from scipy import spatial
from scipy.stats import qmc
from scipy import optimize
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rng = np.random.default_rng()
def _decay(n_iters):
"""Exponential decay.
Fit an exponential to be 2 at 0 and 1 at `n_iters`.
The decay is used for relaxation.
"""
res = optimize.root_scalar(lambda x: np.exp(-n_iters/x) + 1 - 1.1,
bracket=[1, n_iters])
return (np.exp(-x / res.root) + 0.9 for x in range(n_iters))
def _points_contain_duplicates(points):
"""Check whether `points` contains duplicates."""
vals, count = np.unique(points, return_counts=True)
return np.any(vals[count > 1])
def _jitter_points(points, scalar=.000000001):
"""Randomly jitter points until they are unique.
If the points are not unique, the number of regions in our
tessellation will be less than the number of input points.
"""
while _points_contain_duplicates(points):
offset = rng.uniform(-scalar, scalar, size=(len(points), points.shape[1]))
points = points + offset
return points
def lloyd_centroidal_voronoi_tessellation(points):
"""Centroidal Voronoi Tessellation.
Perturb a sample of points using Lloyd's algorithm.
"""
points = _jitter_points(points)
centroids = np.empty_like(points)
# Add exterior corners before tesselation
d = centroids.shape[1]
arrays = np.tile([0, 1], (d, 1))
hypercube_corners = np.stack(np.meshgrid(*arrays), axis=-1).reshape(-1, d)
n_hypercube_corners = len(hypercube_corners)
points = np.concatenate((points, hypercube_corners))
voronoi = spatial.Voronoi(points)
decay_ = next(decay)
for ii, idx in enumerate(voronoi.point_region[:-n_hypercube_corners]):
# the region is a series of indices into self.voronoi.vertices
# remove point at infinity, designated by index -1
region = [i for i in voronoi.regions[idx] if i != -1]
# enclose the polygon
region = region + [region[0]]
# get the vertices for this region
verts = voronoi.vertices[region]
is_valid = _within_hypercube(verts)
verts = verts[is_valid]
#verts = np.clip(verts, 0, 1)
centroid = _centroid(verts)
centroids[ii] = points[ii] + (centroid - points[ii]) * decay_
centroids[ii] = centroid
is_valid = _within_hypercube(centroids)
points = points[:-n_hypercube_corners]
points[is_valid] = centroids[is_valid]
# points = np.clip(centroids, 0, 1)
return points
def _centroid(polygon):
"""Centroid in n-D is the mean for uniformly distributed nodes of a geometry."""
return np.mean(polygon, axis=0)
def _within_hypercube(points):
return np.all(np.logical_and(points >= 0, points <= 1), axis=1)
n_iters = 1000
decay = _decay(n_iters)
points = qmc.Sobol(d=2, scramble=True).random(128)
points_lloyd = points.copy()
for _ in range(n_iters):
points_lloyd = lloyd_centroidal_voronoi_tessellation(points_lloyd)
sns.pairplot(pd.DataFrame(points_lloyd), corner=True, diag_kws={"bins": 8})
plt.show()
@tupui
Copy link
Author

tupui commented Aug 2, 2021

Here is a 2D example starting with Sobol' points.

sobol_voronoi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment