本文整理匯總了Python中scipy.spatial.Voronoi方法的典型用法代碼示例。如果您正苦於以下問題:Python spatial.Voronoi方法的具體用法?Python spatial.Voronoi怎麽用?Python spatial.Voronoi使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類scipy.spatial
的用法示例。
在下文中一共展示了spatial.Voronoi方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_ridges
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def test_ridges(self, name):
# Check that the ridges computed by Voronoi indeed separate
# the regions of nearest neighborhood, by comparing the result
# to KDTree.
points = DATASETS[name]
tree = KDTree(points)
vor = qhull.Voronoi(points)
for p, v in vor.ridge_dict.items():
# consider only finite ridges
if not np.all(np.asarray(v) >= 0):
continue
ridge_midpoint = vor.vertices[v].mean(axis=0)
d = 1e-6 * (points[p[0]] - ridge_midpoint)
dist, k = tree.query(ridge_midpoint + d, k=1)
assert_equal(k, p[0])
dist, k = tree.query(ridge_midpoint - d, k=1)
assert_equal(k, p[1])
示例2: plot_cluster_voronoi
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def plot_cluster_voronoi(data, algo):
# passing input space to set up voronoi regions.
points = np.hstack((np.reshape(data[:,0], (len(data[:,0]), 1)), np.reshape(data[:,1], (len(data[:,1]), 1))))
vor = Voronoi(points)
# use helper Voronoi
regions, vertices = voronoi_finite_polygons_2d(vor)
fig, ax = plt.subplots()
plot = ax.scatter([], [])
indice = 0
for region in regions:
ax.plot(data[:,0][indice], data[:,1][indice], 'ko')
polygon = vertices[region]
# if it isn't gradient based we just color red or blue depending on whether that point uses the machine in question
color = algo.labels_[indice]
# we assume only two
if color == 0:
color = 'r'
else:
color = 'b'
ax.fill(*zip(*polygon), alpha=0.4, color=color, label="")
indice += 1
ax.axis('equal')
plt.xlim(vor.min_bound[0] - 0.1, vor.max_bound[0] + 0.1)
plt.ylim(vor.min_bound[1] - 0.1, vor.max_bound[1] + 0.1)
示例3: get_wigner_seitz
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def get_wigner_seitz(recLat):
kpoints = []
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
vec = i * recLat[0] + j * recLat[1] + k * recLat[2]
kpoints.append(vec)
brill = Voronoi(np.array(kpoints))
faces = []
for idict in brill.ridge_dict:
if idict[0] == 13 or idict[1] == 13:
faces.append(brill.ridge_dict[idict])
verts = brill.vertices
poly = []
for ix in range(len(faces)):
temp = []
for iy in range(len(faces[ix])):
temp.append(verts[faces[ix][iy]])
poly.append(np.array(temp))
return np.array(poly)
示例4: wigner_seitz
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def wigner_seitz(self):
"""
Returns
-------
TYPE
Using the Wigner-Seitz Method, this function finds the 1st
Brillouin Zone in terms of vertices and faces
"""
kpoints = []
for i in range(-1, 2):
for j in range(-1, 2):
for k in range(-1, 2):
vec = i * self.reciprocal[0] + j * \
self.reciprocal[1] + k * self.reciprocal[2]
kpoints.append(vec)
brill = Voronoi(np.array(kpoints))
faces = []
for idict in brill.ridge_dict:
if idict[0] == 13 or idict[1] == 13:
faces.append(brill.ridge_dict[idict])
verts = brill.vertices
return np.array(verts), np.array(faces)
示例5: test_voronoi_name_mapping
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def test_voronoi_name_mapping(xy_of_hex):
"""Test scipy Voronoi names are mapped to landlab-style names."""
voronoi = Voronoi(xy_of_hex)
delaunay = Delaunay(xy_of_hex)
graph = VoronoiDelaunay(xy_of_hex)
assert np.all(graph.x_of_node == approx(voronoi.points[:, 0]))
assert np.all(graph.y_of_node == approx(voronoi.points[:, 1]))
assert np.all(graph.x_of_corner == approx(voronoi.vertices[:, 0]))
assert np.all(graph.y_of_corner == approx(voronoi.vertices[:, 1]))
assert np.all(graph.nodes_at_link == voronoi.ridge_points)
assert tuple(graph.n_corners_at_cell) == tuple(
len(region) for region in voronoi.regions
)
for cell, corners in enumerate(graph.corners_at_cell):
assert np.all(corners[: graph.n_corners_at_cell[cell]] == voronoi.regions[cell])
assert np.all(corners[graph.n_corners_at_cell[cell] :] == -1)
assert np.all(graph.corners_at_face == voronoi.ridge_vertices)
assert np.all(graph.nodes_at_face == voronoi.ridge_points)
assert np.all(graph.cell_at_node == voronoi.point_region)
assert np.all(graph.nodes_at_patch == delaunay.simplices)
示例6: voronoi_from_points_numpy
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def voronoi_from_points_numpy(points):
"""Generate a voronoi diagram from a set of points.
Parameters
----------
points : list of list of float
XYZ coordinates of the voronoi sites.
Returns
-------
Examples
--------
>>>
"""
points = asarray(points)
voronoi = Voronoi(points)
return voronoi
# ==============================================================================
# Main
# ==============================================================================
示例7: relaxLloyd
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def relaxLloyd(pts,strength):
for i in range(strength):
vor = Voronoi(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])
newpt = centroidnp(vxs)
newpts.append(newpt)
pts = np.array(newpts)
示例8: _voronoi
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def _voronoi(structure, limit=5, tol=1e-2):
lps = structure.lat_params
limits = np.array([ int(np.ceil(limit/lps[i])) for i in range(3)])
# Create a new cell large enough to find neighbors at least `limit` away.
new_struct = structure.transform(limits+1, in_place=False)
nns = defaultdict(list)
# look for neighbors for each atom in the structure
for i, atom in enumerate(structure.atoms):
atom.neighbors = []
# center on the atom so that its voronoi cell is fully described
new_struct.recenter(atom, middle=True)
tess = Voronoi(new_struct.cartesian_coords)
for j, r in enumerate(tess.ridge_points):
if not i in r: # only ridges involving the specified atom matter
continue
inds = tess.ridge_vertices[j]
verts = tess.vertices[inds]
# check that the area of the facet is large enough
if _get_facet_area(verts) < tol:
continue
# Get the indices of all points which this atom shares a ridge with
ind = [k for k in tess.ridge_points[j] if k != i ][0]
# map the atom index back into the original cell.
atom.neighbors.append(atom)
## nns[atom] = atom.neighbors
## `qmpy.Atom` objects that are not saved are not hashable, and hence
## cannot be used as dictionary keys. Unit tests will fail.
nns[i] = atom.neighbors
return nns
示例9: get_equivalent_voronoi_vertices
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def get_equivalent_voronoi_vertices(
self, return_box=False, minimum_dist=0.1, symprec=1e-5, angle_tolerance=-1.0
):
"""
This function gives the positions of spatially equivalent Voronoi vertices in lists, which
most likely represent interstitial points or vacancies (along with other high symmetry points)
Each list item contains an array of positions which are spacially equivalent.
This function does not work if there are Hs atoms in the box
Args:
return_box: True, if the box containing atoms on the positions of Voronoi vertices
should be returned (which are represented by Hs atoms)
minimum_dist: Minimum distance between two Voronoi vertices to be considered as one
Returns: List of numpy array positions of spacially equivalent Voronoi vertices
"""
_, box_copy = self._get_voronoi_vertices(minimum_dist=minimum_dist)
list_positions = []
sym = box_copy.get_symmetry(symprec=symprec, angle_tolerance=angle_tolerance)
for ind in set(sym["equivalent_atoms"][box_copy.select_index("Hs")]):
list_positions.append(box_copy.positions[sym["equivalent_atoms"] == ind])
if return_box:
return list_positions, box_copy
else:
return list_positions
示例10: _get_centre
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def _get_centre(self, gdf):
"""
Returns centre coords of gdf.
"""
bounds = gdf["geometry"].bounds
centre_x = (bounds["maxx"].max() + bounds["minx"].min()) / 2
centre_y = (bounds["maxy"].max() + bounds["miny"].min()) / 2
return centre_x, centre_y
# densify geometry before Voronoi tesselation
示例11: _regions
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def _regions(self, voronoi_diagram, unique_id, ids, crs):
"""
Generate GeoDataFrame of Voronoi regions from scipy.spatial.Voronoi.
"""
# generate DataFrame of results
regions = pd.DataFrame()
regions[unique_id] = ids # add unique id
regions["region"] = voronoi_diagram.point_region # add region id for each point
# add vertices of each polygon
vertices = []
for region in regions.region:
vertices.append(voronoi_diagram.regions[region])
regions["vertices"] = vertices
# convert vertices to Polygons
polygons = []
for region in tqdm(regions.vertices, desc="Vertices to Polygons"):
if -1 not in region:
polygons.append(Polygon(voronoi_diagram.vertices[region]))
else:
polygons.append(None)
# save polygons as geometry column
regions["geometry"] = polygons
# generate GeoDataFrame
regions_gdf = gpd.GeoDataFrame(regions.dropna(), geometry="geometry")
regions_gdf = regions_gdf.loc[
regions_gdf["geometry"].length < 1000000
] # delete errors
regions_gdf = regions_gdf.loc[
regions_gdf[unique_id] != -1
] # delete hull-based cells
regions_gdf.crs = crs
return regions_gdf
示例12: _get_voronoi_vertices_and_ridges
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def _get_voronoi_vertices_and_ridges(self):
borders = self._get_densified_borders()
voronoi_diagram = Voronoi(borders)
vertices = voronoi_diagram.vertices
ridges = voronoi_diagram.ridge_vertices
return vertices, ridges
示例13: test_issue_8051
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def test_issue_8051(self):
points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2],[2, 0], [2, 1], [2, 2]])
Voronoi(points)
示例14: test_masked_array_fails
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def test_masked_array_fails(self):
masked_array = np.ma.masked_all(1)
assert_raises(ValueError, qhull.Voronoi, masked_array)
示例15: test_simple
# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import Voronoi [as 別名]
def test_simple(self):
# Simple case with known Voronoi diagram
points = [(0, 0), (0, 1), (0, 2),
(1, 0), (1, 1), (1, 2),
(2, 0), (2, 1), (2, 2)]
# qhull v o Fv Qbb Qc Qz < dat
output = """
2
5 10 1
-10.101 -10.101
0.5 0.5
1.5 0.5
0.5 1.5
1.5 1.5
2 0 1
3 3 0 1
2 0 3
3 2 0 1
4 4 3 1 2
3 4 0 3
2 0 2
3 4 0 2
2 0 4
0
12
4 0 3 0 1
4 0 1 0 1
4 1 4 1 3
4 1 2 0 3
4 2 5 0 3
4 3 4 1 2
4 3 6 0 2
4 4 5 3 4
4 4 7 2 4
4 5 8 0 4
4 6 7 0 2
4 7 8 0 4
"""
self._compare_qvoronoi(points, output)