def test_get_voronoi_entropy(self): # square grid points = np.array([[[a, b] for a in range(10)] for b in range(10)]) points = np.concatenate(points, axis=0) # import matplotlib.pyplot as plt # plt.scatter(points[:, 0], points[:, 1]) # plt.show() import scipy.spatial as spatial vor = spatial.Voronoi(points=points) ent = ia.get_voronoi_entropy(voronoi=vor) assert (ent == 0) # hex grid def get_hex_grid(grid_size=8, canvas_size=100, margin=5): ys = np.arange(0, canvas_size, grid_size * np.sqrt(3) / 2) ps = [] for yi, y in enumerate(ys): if yi % 2 == 0: # even lines xs = np.arange(0, canvas_size + grid_size, grid_size) for x in xs: ps.append((x, y)) else: # odd lines xs = np.arange(grid_size / 2, canvas_size + grid_size, grid_size) for x in xs: ps.append((x, y)) # print(ps) # remove points on the edge pss = [] for p in ps: if margin <= p[0] <= canvas_size - margin and \ margin <= p[1] <= canvas_size - margin: pss.append(p) pss = np.array(pss) return pss pss = get_hex_grid(canvas_size=100) vor2 = spatial.Voronoi(points=pss) # import matplotlib.pyplot as plt # f, ax = plt.subplots() # ax.plot(pss[:, 0], pss[:, 1], 'o') # ax.plot(vor2.vertices[:, 0], vor2.vertices[:, 1], '*') # ax.set_aspect('equal') # plt.show() ent2 = ia.get_voronoi_entropy(voronoi=vor2) assert (ent2 == 0)
def calculate_polygons(self): """ Convert the raw data into a voronoi plot """ logger.debug("Generating voronoi graph") if len(self.positions) > 2: self.voronoi = spatial.Voronoi(self.positions) else: return # Then generate a list of polygons for finite regions logger.debug("Generating Polygons") self.polygons.clear() for ind, p in enumerate(self.voronoi.point_region): p_vertices = self.voronoi.regions[p] n_vertices = len(p_vertices) buf = bytearray(4 + n_vertices*16) struct.pack_into('>i', buf, 0, n_vertices) for i, point in enumerate(p_vertices): if point == -1: break point = self.voronoi.vertices[point] struct.pack_into('>2d', buf, 4+i*16, point[0], point[1]) else: ds = QtCore.QDataStream(QtCore.QByteArray.fromRawData(buf)) poly = QtGui.QPolygonF() ds >> poly # pylint: disable=pointless-statement self.polygons.append((ind, poly)) logger.debug("Clearing Voronoi") # Clear the voronoi del self.voronoi self.voronoi = None logger.info("Done")
def plot_data(frame): global pos, data_map, time_map # Plot centres of Voronoi cells vor = spatial.Voronoi(pos[frame]) plt_pts.set_xdata(vor.points[:,0]) plt_pts.set_ydata(vor.points[:,1]) # Plot the Voronoi polygons colors = [] polygons = [] for r in range(len(vor.point_region)): region = vor.regions[vor.point_region[r]] if -1 in region: continue # pt = tuple(vor.points[r]) poly = [vor.vertices[i] for i in region] polygons.append(Polygon(poly)) if (data_col >= 0): colors.append(mapper.to_rgba( data_val[frame][index_map[frame][r]])) else: colors.append(mapper.to_rgba(index_map[frame][r])) plt_polygons.set_paths(polygons) plt_polygons.set_facecolor(colors) plt_polygons.set_edgecolor("black") # Plot the time label if (use_label): plt_time_txt.set_text(r"$D_rt = {:.1f}$".format(time_map[frame]*Dr*dt)) return plt_pts, plt_polygons,
def create_hopping_map(self): ## Create hopping map centers = self.L * np.random.rand(self.num, 2) # Compute Voronoi diagram vor = spatial.Voronoi(centers) # Fill map with ids xm, ym = np.meshgrid(np.arange(0, self.L, self.dL), np.arange(0, self.L, self.dL)) m = np.zeros(xm.shape) id = 0 nc = len(vor.regions) for kc in range(nc): v = vor.regions[kc] v = [x for x in v if x != -1] if len(v) > 0: v.append(v[0]) p = np.round(vor.vertices[v] / self.dL) id += 1 # cv2.polylines(m, v, isClosed=True, color=id) rr, cc = draw.polygon(p[:,0], p[:,1], shape=xm.shape) m[rr,cc] = id # Add the hopping map to the internals self.hopping_map = m self.centers = centers self.voronoi_vertices = vor.vertices self.voronoi_regions = vor.regions
def __make_voronoi(self): """ Makes the vornoi image with region pixels values equal to the index for the points array used to build the voronoi. In this class the voro-image is used as data strcuture to determine the points index refering to the voro-regions """ self.__VOR = SS.Voronoi(self.__xypoints)
def draw_voronoi_cells(img, points): """ Draws the voronoi cells for a set of points on an image Parameters ---------- img: input image Any number of channels points: array of N points Shape (N, 2). points[:, 0] contains x coordinates points[:, 1] contains y coordinates Returns ------- ing: annotated image Same shape and type as input image """ voro = sp.Voronoi(points) ridge_vertices = voro.ridge_vertices new_ridge_vertices = [] for ridge in ridge_vertices: if -1 not in ridge: new_ridge_vertices.append(ridge) img = draw_polygons(img, voro.vertices[new_ridge_vertices], color=PINK) return img
def regenerate(self): self.regions = [] self.continents = [] self.seeds = [] self.set_seeds() self.voronoi_diagram = spatial.Voronoi(self.seeds) self.world = self.create_base_map(self.width, self.height, self.min_altitude) self.regions = self.set_world_regions(self.voronoi_diagram) self.regions = self.generate_continents() self.assign_tiles_to_regions() self.update_region_tiles() self.gen_mountain_ranges() self.world = self.apply_simplex_noise() self.world = self.gaussian_smooth() self.set_sea_tiles() self.truncate_tile_heights() self.terrain_filter()
def farthest(pts, xlims, ylims, n): """ Find the 'n' points that lie farthest from the points given in the region bounded by 'xlims' and 'ylims'. 'pts' is an array of points. 'xlims' and 'ylims are tuples storing the maximum and minimum values to consider along the x and y axes.""" # There are a ton of ways to do this, this is a shorter one. # The 'inside' function tests whether or not a point is on # the interior of the given square. ins = lambda pt: inside(pt, xlims, ylims) # Construct the Voronoi diagram. V = st.Voronoi(pts) # Construct the KD Tree. KD = st.cKDTree(pts) # Now we'll construct a list of tuples where the first # entry is the distance from a point to the nearest node # and the second entry is a tuple with the coordinates for the point. # Process the vertices of the Voronoi diagram. Q = [(KD.query(pt)[0], pt) for pt in V.vertices if ins(pt)] # Process the intersections of the edges of the # Voronoi diagram and the edges of the box. Q += [(KD.query(pt)[0], pt) for pt in edge_intersections(V, xlims, ylims)[0]] # Process the corners of the box. Q += [(KD.query(pt)[0], (x, y)) for x in xlims for y in ylims] # Return the 'n' points with farthest distance from the points # used to generate the Voronoi diagram. return np.array([pair[1] for pair in hq.nlargest(n, Q)])
def voronoi_edges(shape: List[int], radius: int, ncells: int, flat_faces: bool = True): r""" Create an image of the edges in a Voronoi tessellation Parameters ---------- shape : array_like The size of the image to generate in [Nx, Ny, Nz] where Ni is the number of voxels in each direction. radius : scalar The radius to which Voronoi edges should be dilated in the final image. ncells : scalar The number of Voronoi cells to include in the tesselation. flat_faces : Boolean Whether the Voronoi edges should lie on the boundary of the image (True), or if edges outside the image should be removed (False). Returns ------- image : ND-array A boolean array with ``True`` values denoting the pore space """ print(78 * '―') print('voronoi_edges: Generating', ncells, ' cells') shape = sp.array(shape) if sp.size(shape) == 1: shape = sp.full((3, ), int(shape)) im = sp.zeros(shape, dtype=bool) base_pts = sp.rand(ncells, 3) * shape if flat_faces: # Reflect base points Nx, Ny, Nz = shape orig_pts = base_pts base_pts = sp.vstack( (base_pts, [-1, 1, 1] * orig_pts + [2.0 * Nx, 0, 0])) base_pts = sp.vstack( (base_pts, [1, -1, 1] * orig_pts + [0, 2.0 * Ny, 0])) base_pts = sp.vstack( (base_pts, [1, 1, -1] * orig_pts + [0, 0, 2.0 * Nz])) base_pts = sp.vstack((base_pts, [-1, 1, 1] * orig_pts)) base_pts = sp.vstack((base_pts, [1, -1, 1] * orig_pts)) base_pts = sp.vstack((base_pts, [1, 1, -1] * orig_pts)) vor = sptl.Voronoi(points=base_pts) vor.vertices = sp.around(vor.vertices) vor.vertices *= (sp.array(im.shape) - 1) / sp.array(im.shape) vor.edges = _get_Voronoi_edges(vor) for row in vor.edges: pts = vor.vertices[row].astype(int) if sp.all(pts >= 0) and sp.all(pts < im.shape): line_pts = line_segment(pts[0], pts[1]) im[line_pts] = True im = spim.distance_transform_edt(~im) > radius return im
def EuclidExample2(ncenters): vec_centers = np.random.randn(3, ncenters) C = np.array([[vec_centers[0][i], vec_centers[1][i], vec_centers[2][i]] for i in range(len(vec_centers[0]))]) bbox = find_bounding_box(C) def unbounded(input_region): return any(x == -1 for x in input_region) ## insert points to remove ## infinite regions minpt, maxpt = bbox extent = find_extent([minpt, maxpt]) smallpt, bigpt = [minpt[i] - extent[i] for i in range(3) ], [maxpt[i] + extent[i] for i in range(3)] # print(boundary) boundary = np.array([ smallpt, [bigpt[0], smallpt[1], smallpt[2]], [smallpt[0], bigpt[1], smallpt[2]], [smallpt[0], smallpt[1], bigpt[2]], [bigpt[0], bigpt[1], smallpt[2]], [smallpt[0], bigpt[1], bigpt[2]], [bigpt[0], smallpt[1], bigpt[2]], bigpt ]) print(boundary) print(C) diagram = sp.Voronoi(np.concatenate((C, boundary))) bounded_regions = [[diagram.vertices[j] for j in region] for region in diagram.regions if region != [] and not unbounded(region)] return bounded_regions # OrderRegions(C,
def DrawVoronoiTesselation(hdf5_file, frame=0): """ wanted structure: np.array([[3, 0], [4.2, 1], [0, 8], ...]) :return: """ x_gfp, y_gfp, x_rfp, y_rfp = GetXandYcoordinatesPerFrame(hdf5_file=hdf5_file, frame=frame) #x_gfp, y_gfp, x_rfp, y_rfp = ConvertXandYcoordinates(x_gfp, y_gfp, x_rfp, y_rfp) # Restructure so that you get a matrix; merge channels as the cell identity is not important in this case: points = [] for x, y in zip(x_gfp + x_rfp, y_gfp + y_rfp): points.append([x, y]) points = np.array(points) vor = sp.Voronoi(points) tri = sp.Delaunay(points) fig = sp.voronoi_plot_2d(vor) fig = sp.delaunay_plot_2d(tri) plt.grid(which='major') plt.show() plt.close() return vor, tri
def update(self, s): posNow = self.pos[s] if self.posExtra is not None and s >= self.t0pred: posNow = np.vstack((posNow, self.posExtra[s-self.t0pred])) posNow = posNow[~np.isnan(posNow)].reshape(-1, 2) vor = spatial.Voronoi(posNow) lines_normal, lines_inf = voronoi_Lines(vor) self.voro_lines.set_segments(lines_normal) return self.voro_lines
def triangulate(self, points, labels): """Triangulate the voronoi diagram for the specified points. """ self._vor = sp.Voronoi(points) self._vertices = self._vor.vertices self._regions, self._fvertices = voronoi_finite_polygons_2d(self._vor) self._polygons = [self._fvertices[reg] for reg in self._regions] self.border_verts = self.calculate_border_verts()
def farthest(pts, xlims, ylims, n): # there are a ton of ways to do this, this is a shorter one ins = lambda pt: inside(pt, xlims, ylims) V = st.Voronoi(pts) KD = st.cKDTree(pts) Q = [(KD.query(pt)[0], pt) for pt in V.vertices if ins(pt)] Q += [(KD.query(pt)[0], pt) for pt in edge_intersections(V, xlims, ylims)[0]] return np.array([pair[1] for pair in hq.nlargest(n, Q)])
def calculate(particles, boundary): # boundary = Polygon(boundary) vor = sp.Voronoi(particles[:, :2]) regions, vertices = voronoi_finite_polygons_2d(vor) inside = find_points_inside(vertices, boundary) vertices = np.float32(vertices) polygons, on_edge = get_polygons(regions, vertices, inside) polygons = intersect_all_polygons(polygons, boundary, on_edge) area, shape_factor = area_and_shapefactor(polygons) # plot_polygons(polygons) return area, shape_factor, on_edge
def get_voronoi_polygons(self, image: np.ndarray): points = self.get_keypoints(image, include_corners=False) voronoi = spatial.Voronoi(points) regions, vertices = self.finitize_voronoi(voronoi) self.constrain_points(image.shape[:2], vertices) max_polygon_points = len(max(regions, key=lambda x: len(x))) polygons = np.full((len(regions), max_polygon_points, 2), -1) for i, region in enumerate(regions): polygon_points = vertices[region] polygons[i][:polygon_points.shape[0]] = polygon_points return polygons
def __init__(self, points): points = _np.asarray(points) if len(points.shape) != 2 or points.shape[1] != 2: raise ValueError("Need array of shape (N,2)") self._v = _spatial.Voronoi(points) self._infinity_directions = dict() centre = _np.mean(self._v.points, axis=0) for ((a, b), (aa, bb)) in zip(self._v.ridge_vertices, self._v.ridge_points): if a == -1: x, y = self.perp_direction(self._v.points, aa, bb, centre) self._infinity_directions[b] = x, y
def voronoi(df, f_index=None, parameters=None, call_num=None): """ Calculate the voronoi network of particle. Notes ----- The voronoi network is explained here: https://en.wikipedia.org/wiki/Voronoi_diagram This function also calculates the associated area of the voronoi cells.To visualise the result you can use "voronoi" in the annotation section. 'voronoi' - The voronoi coordinates that surround a particle 'voronoi_area' - The area of the voronoi cell associated with a particle Args ---- df The dataframe in which all data is stored f_index Integer specifying the frame for which calculations need to be made. parameters Nested dictionary like object (same as .param files or output from general.param_file_creator.py) call_num Usually None but if multiple calls are made modifies method name with get_method_key Returns ------- updated dataframe including new column """ try: params = parameters['postprocess'] method_key = get_method_key('voronoi') if 'voronoi' not in df.columns: df['voronoi'] = np.nan df['voronoi_area'] = np.nan df_frame = df.loc[[f_index]] points = df_frame[['x', 'y']].values vor = sp.Voronoi(points) df_frame['voronoi'] = _get_voronoi_coords(vor) df_frame['voronoi_area'] = _voronoi_props(vor) df.loc[[f_index]] = df_frame return df except Exception as e: raise VoronoiError(e)
def PlotAll(C, A, assign_pairs): assignment = dict(assign_pairs) diagram = sp.Voronoi(C) sp.voronoi_plot_2d(diagram) for i in range(len(C)): plt.plot(C[i][0], C[i][1], 'd', color=colors[i]) for j in range(len(A)): plt.plot(A[j][0], A[j][1], 'x', color=colors[assignment[j]]) axes = plt.gca() axes.set_xlim([-3, 7]) axes.set_ylim([-3, 7]) plt.show(block=False)
def minimum_nsphere(obj): ''' Compute the minimum n- sphere for a mesh or a set of points. Uses the fact that the minimum n- sphere will be centered at one of the vertices of the furthest site voronoi diagram, which is n*log(n) but should be pretty fast due to using the scipy/qhull implementations of convex hulls and voronoi diagrams. Arguments ---------- obj: Trimesh object OR (n,d) float, set of points Returns ---------- center: (d) float, center of n- sphere radius: float, radius of n-sphere ''' # reduce the input points or mesh to the vertices of the convex hull # since we are computing the furthest site voronoi diagram this reduces # the input complexity substantially and returns the same value points = convex.hull_points(obj) # if all of the points are on an n-sphere already the voronoi # method will fail so we check a least squares fit before # bothering to compute the voronoi diagram fit_C, fit_R, fit_E = fit_nsphere(points) radius_fit = ((points - fit_C)**2).sum(axis=1).max()**.5 if fit_E < 1e-3: log.debug('Points were on an n-sphere, returning fit') return fit_C, fit_R # calculate a furthest site voronoi diagram # this will fail if the points are ALL on the surface of # the n-sphere but hopefully the least squares check caught those cases voronoi = spatial.Voronoi(points, furthest_site=True, qhull_options='QbB Pp') # find the maximum radius^2 point for each of the voronoi vertices # this is worst case quite expensive, but we have used quick convex # hull methods to reduce n for this operation # we are doing comparisons on the radius^2 value so as to only do a sqrt once r2 = np.array([((points - v)**2).sum(axis=1).max() for v in voronoi.vertices]) r2_idx = r2.argmin() radius_v = np.sqrt(r2[r2_idx]) center_v = voronoi.vertices[r2_idx] if radius_v > radius_fit: return fit_C, radius_fit return center_v, radius_v
def PlotAll(C, A, assignment, bounded_regions, bbox): diagram = sp.Voronoi(C) # sp.voronoi_plot_2d(diagram) for i in range(len(C)): plt.plot(C[i][0], C[i][1], 'd', color=colors[i]) for j in range(len(A)): plt.plot(A[j][0], A[j][1], 'x', color=colors[assignment[j]]) axes = plt.gca() plot_regions(bounded_regions) # axes.set_xlim([-3,7]) # axes.set_ylim([-3,7]) plt.axis([bbox[0][0], bbox[1][0], bbox[0][1], bbox[1][1]]) plt.show(block=True)
def build_grid(self, n): self.pts = np.random.random((n, 2)) self.improve_pts() self.vor = spl.Voronoi(self.pts) self.regions = [self.vor.regions[i] for i in self.vor.point_region] self.vxs = self.vor.vertices self.nvxs = self.vxs.shape[0] self.build_adjs() self.improve_vxs() self.calc_edges() self.distort_vxs() self.elevation = np.zeros(self.nvxs + 1) self.erodability = np.ones(self.nvxs)
def VoronoiSphere(bm, points, r=2, offset=0.02, num_materials=1): # Calculate 3D Voronoi diagram vor = spatial.Voronoi(points) faces_dict = {} for (idx_p0, idx_p1), ridge_vertices in zip(vor.ridge_points, vor.ridge_vertices): if -1 in ridge_vertices: continue if idx_p0 not in faces_dict: faces_dict[idx_p0] = [] if idx_p1 not in faces_dict: faces_dict[idx_p1] = [] faces_dict[idx_p0].append(ridge_vertices) faces_dict[idx_p1].append(ridge_vertices) for idx_point in faces_dict: region = faces_dict[idx_point] center = Vector(vor.points[idx_point]) if len(region) <= 1: continue # Skip all Voronoi regions outside of radius r skip = False for faces in region: for idx in faces: p = vor.vertices[idx] if np.linalg.norm(p) > r: skip = True break if not skip: vertsDict = {} material_index = np.random.randint(num_materials) for faces in region: verts = [] for idx in faces: p = Vector(vor.vertices[idx]) if idx not in vertsDict: v = center - p v.normalize() vert = bm.verts.new(p + offset * v) verts.append(vert) vertsDict[idx] = vert else: verts.append(vertsDict[idx]) face = bm.faces.new(verts) face.material_index = material_index bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
def __init__(self, n, dims, name=""): """ Initialize the PolygonMap class, with n points Arguments: n -- the number of points """ # init healines to empty array of arrays # fill with n random 2D vectors self.scale = np.max((dims["xmax"], dims["ymax"])) * 1.05 self.name = name self.pts = np.random.random((n, 2)) # use lloyd relaxation to space them better self.pts = PolygonMap.improve_points(self.pts) self.pts *= self.scale self.vor = spatial.Voronoi(self.pts) self.n_regions = len(self.vor.regions) # ok, so each voronoi vertex defines triangle, with the 3 points of the triangle = # the voronoi centers of the neighboring polygons self.delaunay = spatial.Delaunay(self.pts) self.n_triangles = len(self.delaunay.simplices) self.headlines = [[] for i in range(self.n_triangles)] self.topics = np.zeros(self.n_triangles) # use KD tree to provide nearest neighbor lookups for occasional grid based operation self.tree = spatial.KDTree(self.pts) # ridge points are pairs of points that have a polygon edge between them. # create a adjacency dictionary for the point indices # you could also call these adjacency regions tbh # so for each region, we can easily get a list of its neighbors for p0, p1 in self.vor.ridge_points: self.adj_points[p0].append(p1) self.adj_points[p1].append(p0) # do the same for the ridge vertices (the coordinates that define the edges) for v0, v1 in self.vor.ridge_vertices: self.adj_vertices[v0].append(v1) self.adj_vertices[v1].append(v0) # make a list of whether each region is on the edge or not self.edges = np.asarray( [-1 in neighbors for neighbors in self.delaunay.neighbors]) # make a list of each region's elevation. initialize to zero self.elevation = np.zeros(self.n_triangles) self.moisture = np.zeros(self.n_triangles) self.temperature = np.zeros(self.n_triangles) self.shadow = np.zeros(self.n_triangles) self.flux_map = np.zeros(self.n_triangles)
def voronoi_edges(points: Sequence[Pnt]) -> List[dict]: """Find the edges of Voronoi regions for a set of points. Args: points: A list of points. Returns: A list of line shapes. """ vor = spatial.Voronoi(np.array(points)) edges = [[tuple(vor.vertices[i]) for i in edge] for edge in vor.ridge_vertices if -1 not in edge] return [Line(p1=edge[0], p2=edge[1]) for edge in edges]
def pyLEC(points): ''' LEC: Largest Empty Circle between Points in a flat plane also know as Pole of Inaccessibility problem. see: https://en.wikipedia.org/wiki/Largest_empty_sphere The largest empty circle problem is the problem of finding a circle of largest radius in the plane whose interior does not overlap with any given point and whose center is lying in the convex hull of the points. Hint: The LEC is centered at that internal Voronoi vertice with has the largest shortest distance to the polygon of all internal Voronoi vertices. Parameters ---------- points : 2d numpy array with x, y coordinate of the points on the Concave Hull Returns ------- LEC_Radius: scalar LEC_Centroid: (x, y) ''' # Error handling if points.shape[0] < 3: print('less than 3 Points: ') return np.nan, (np.nan, np.nan) # Step 1: get Voronoi vertices (scipy.spatial) vor_Verts = spatial.Voronoi(points).vertices # Step 2: select Voronoi vertices inside the convex hull (mpl) polygon = path.Path(points) selector = polygon.contains_points(vor_Verts) vor_Verts = vor_Verts[ selector] # Verts inside Polygon Verts inside Polygon # Step 3: Get nearest neighbors as well as radius und centroid of LEC tree = spatial.KDTree(points) neighbores = tree.query(vor_Verts) idx = np.argmax(neighbores[0]) LEC_Radius = neighbores[0][idx] LEC_Centroid = vor_Verts[idx] return LEC_Radius, LEC_Centroid
def set_rough_points(self, topic_points, noise_pts): assert "x" in topic_points assert "y" in topic_points assert "topic" in topic_points assert "x" in noise_pts assert "y" in noise_pts assert "topic" in noise_pts noise_pts = noise_pts.fillna(-1) self.rough_points = pd.concat((topic_points, noise_pts), ignore_index=True) self.rough_voronoi = spatial.Voronoi(self.rough_points[["x", "y"]]) self.rough_kdtree = spatial.KDTree(self.rough_points[["x", "y"]]) self.topic_kdtree = spatial.KDTree(topic_points[["x", "y"]]) self.rough_topic_points = topic_points
def __init__(self, points, radius=None, qhull_options=None): """ Compute and analyze the Voronoi diagram and the convex hull for some input points in 2D. Parameter --------- points: list of lists of floats List of point coordiantes. radius: float or None Radius for computing far points of infinite ridges. If None twice the maximum extent of the input points is used. qhull_options: string or None Options to be passed on to QHull. From the manual: Qbb - scale last coordinate to [0,m] for Delaunay triangulations Qc - keep coplanar points with nearest facet Qx - exact pre-merges (skips coplanar and anglomaniacs facets) Qz - add point-at-infinity to Delaunay triangulation QJn - randomly joggle input in range [-n,n] Qs - search all points for the initial simplex Qz - add point-at-infinity to Voronoi diagram QGn - Voronoi vertices if visible from point n, -n if not QVn - Voronoi vertices for input point n, -n if not Default is: "Qbb Qc Qz Qx" for ndim > 4 and "Qbb Qc Qz" otherwise. """ self.vor = sp.Voronoi(points, furthest_site=False, incremental=False, qhull_options=qhull_options) if self.vor.ndim != 2: raise ValueError("Only 2D input points are supported.") self.hull = sp.Delaunay(points, furthest_site=False, incremental=False, qhull_options=qhull_options) self._compute_distances() self._compute_infinite_vertices() self._compute_hull(qhull_options) self.ndim = self.vor.ndim self.npoints = self.vor.npoints self.points = self.vor.points self.vertices = self.vor.vertices self.regions = self.vor.regions self.ridge_points = self.vor.ridge_points self.ridge_vertices = self.vor.ridge_vertices self.min_bound = self.vor.min_bound self.max_bound = self.vor.max_bound self.center = np.mean(self.points, axis=0)
def main(): df = pd.read_csv('data.csv', header=None) lon = df[1] lat = df[2] #points = np.delete(df.values, 0, 1) #print(points) box = (0, 0, 15, 15) area = [[0, 0], [15, 0], [15, 13], [13, 13], [13, 15], [0, 15]] ext = [(0, 0), (15, 0), (15, 13), (13, 13), (13, 15), (0, 15)] int = [(11, 12), (12, 12), (12, 11), (11, 11)] grint = [(1, 14), (1, 12), (3, 12), (3, 14)] area_shape = Polygon(ext, [grint, int]) coords = np.random.randint(1, 12, size=(3, 2)) print(coords) points = [] for point in coords: if area_shape.contains(Point(point)) is True: points.append(point) points = coords #points = [point for point in coords if area_shape.contains(Point(point)) is True] print("points:") print(area_shape) vor = spatial.Voronoi(points) #regions, vertices = voronoi_finite_polygons_2d(vor) poly_shapes, pts, poly_to_pt_assignment = voronoi_regions_from_coords( points, area_shape) print(type(poly_shapes)) print(dir(pts)) print(poly_to_pt_assignment) fig, ax = subplot_for_map() plt.figure(dpi=96, figsize=(20 / 96, 20 / 96)) plot_voronoi_polys_with_points_in_area(ax, area_shape, poly_shapes, points, poly_to_pt_assignment) polygons = []
def improve_pts(self, n=2): print("Improving points") for _ in range(n): vor = spl.Voronoi(self.pts) newpts = [] for idx in range(len(vor.points)): pt = vor.points[idx, :] region = vor.regions[vor.point_region[idx]] if -1 in region: newpts.append(pt) else: vxs = np.asarray([vor.vertices[i, :] for i in region]) vxs[vxs < 0] = 0 vxs[vxs > 1] = 1 newpt = np.mean(vxs, 0) newpts.append(newpt) self.pts = np.asarray(newpts)