当前位置: 首页>>代码示例>>Python>>正文


Python spatial.Voronoi方法代码示例

本文整理汇总了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]) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:25,代码来源:test_qhull.py

示例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) 
开发者ID:bhargavvader,项目名称:pycobra,代码行数:26,代码来源:plot_voronoi_clustering.py

示例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) 
开发者ID:romerogroup,项目名称:pyprocar,代码行数:22,代码来源:scriptFermi3D.py

示例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) 
开发者ID:romerogroup,项目名称:pyprocar,代码行数:27,代码来源:brillouin_zone.py

示例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) 
开发者ID:landlab,项目名称:landlab,代码行数:27,代码来源:test_voronoi_to_graph.py

示例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
# ============================================================================== 
开发者ID:compas-dev,项目名称:compas,代码行数:26,代码来源:triangulation_numpy.py

示例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) 
开发者ID:brianbeauregard,项目名称:Python-world-gen,代码行数:16,代码来源:src_mapgenmain.py

示例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 
开发者ID:wolverton-research-group,项目名称:qmpy,代码行数:36,代码来源:nearest_neighbors.py

示例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 
开发者ID:pyiron,项目名称:pyiron,代码行数:29,代码来源:atoms.py

示例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 
开发者ID:martinfleis,项目名称:momepy,代码行数:12,代码来源:elements.py

示例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 
开发者ID:martinfleis,项目名称:momepy,代码行数:37,代码来源:elements.py

示例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 
开发者ID:fitodic,项目名称:centerline,代码行数:10,代码来源:geometry.py

示例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) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:5,代码来源:test_qhull.py

示例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) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:5,代码来源:test_qhull.py

示例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) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:42,代码来源:test_qhull.py


注:本文中的scipy.spatial.Voronoi方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。