Yatoom / foronoi

An implementation of Fortune's algorithm for Voronoi diagrams in Python.
MIT License
51 stars 11 forks source link

Iteratively creating voronoi with global variable #24

Open madorjan2 opened 2 years ago

madorjan2 commented 2 years ago

Hey,

Great library, saved me a lot of headache trying to implement Lloyd's algorithm. While implementing it, I ran into a quite severe issue though. While I iterate through the relaxation, I create a new Voronoi object every step, and if I use a global variable as the bounding region parameter, I inherit points from the edge from my previous iteration. So if I use a global variable at initialization, after the 1st iteration I get an increased number of vertices in my Voronoi sites.

As an example, see the code below:

from foronoi import Voronoi, Polygon, Visualizer, VoronoiObserver
import numpy as np

DIM_X = 10
DIM_Y = 10
N_of_P = 5
BBOX = Polygon([(0,0), (DIM_X,0), (0,DIM_Y), (DIM_X, DIM_Y)])
ITERATION = 10

def initialize_voronoi(n):
    rng = np.random.default_rng()
    numbers = rng.choice(DIM_X*DIM_Y, size=n, replace=False)
    points = []
    for number in numbers:
        y = number//DIM_X
        x = number%DIM_X
        points.append((x,y))
    return points

def create_foronoi(points):
    v = Voronoi(BBOX)
    v.create_diagram(points=points)
    return v

for i in range(ITERATION):
    points = initialize_voronoi(N_of_P)
    vor = create_foronoi(points)
    acc = 0
    for site in vor.sites:
        acc += len(site.vertices())
    print(f"{i}.: {acc}")
    Visualizer(vor, canvas_offset=1)\
        .plot_sites(show_labels=True)\
        .plot_edges(show_labels=True)\
        .plot_vertices()\
        .plot_border_to_site()\
        .show()

If at line 21 you change Voronoi(BBOX) to Voronoi(Polygon([(0,0), (DIM_X,0), (0,DIM_Y), (DIM_X, DIM_Y)])) it works perfectly.