Python scipy 模块,spatial() 实例源码

我们从Python开源项目中,提取了以下11个代码示例,用于说明如何使用scipy.spatial()

项目:MicapsDataDraw    作者:flashlxy    | 项目源码 | 文件源码
def get_extend_hull(self):
        ext_points = []
        # ?????numpy??
        points = np.array([self.lons, self.lats]).T
        if len(points) < 3:
            return ext_points
        # ???????????
        hull = scipy.spatial.ConvexHull(points)

        for simplex in hull.simplices:
            # ???? ??????
            pairs = [True, False]
            for pair in pairs:
                extend_point = self.equations(points[simplex], pair)
                # ????????
                if not self.point_in_path(extend_point):
                    ext_points.append([extend_point[0], extend_point[1], self.zvalues[simplex[0]]])
        return ext_points
项目:wradlib    作者:wradlib    | 项目源码 | 文件源码
def _krig_matrix(self, src, drift):
        """Sets up the kriging system for a configuration of source points.
        """
        # the basic covariance matrix
        var_matrix = self.cov_func(scipy.spatial.distance_matrix(src, src))
        # the extended matrix, initialized to ones
        edk_matrix = np.ones((len(src) + 2, len(src) + 2))

        # adding entries for the first lagrange multiplier for the ordinary
        # kriging part
        edk_matrix[:-2, :-2] = var_matrix
        edk_matrix[-2, -2] = 0.

        # adding entries for the second lagrange multiplier for the  edk part
        edk_matrix[:-2, -1] = drift
        edk_matrix[-1, :-2] = drift
        edk_matrix[-2:, -1] = 0.
        edk_matrix[-1, -2:] = 0.

        return edk_matrix
项目:SERT    作者:cvangysel    | 项目源码 | 文件源码
def query(self, centroids):
        if self.entity_neighbors is not None:
            distances, indices = self.entity_neighbors.kneighbors(centroids)

            return distances, indices
        else:
            pairwise_distances = scipy.spatial.distance.cdist(
                centroids, self.entity_representations,
                metric=self.entity_representation_distance)

            distances = np.sort(pairwise_distances, axis=1)
            indices = pairwise_distances.argsort(axis=1)\
                .argsort(axis=1).argsort(axis=1)

            return distances, indices
项目:DeepFold    作者:largelymfs    | 项目源码 | 文件源码
def get_distance_matrix(pdb_path):
    parser = PDBParser()
    structure = parser.get_structure('structure', pdb_path).get_list()[0]
    residue_positions = get_residue_positions(structure)
    pdb_dist_mat = scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(residue_positions, 'euclidean'))
    pdb_dist_mat[numpy.isnan(pdb_dist_mat)] = float('inf')
    return pdb_dist_mat
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def spatial(self):
        if self._spatial is None:
            try:
                import scipy.spatial as spatial
            except ImportError:
                spatial = NotAModule(self._name)
            self._spatial = spatial
        return self._spatial
项目:wradlib    作者:wradlib    | 项目源码 | 文件源码
def _krig_matrix(self, src):
        """Sets up the kriging system for a configuration of source points.
        """
        var_matrix = self.cov_func(scipy.spatial.distance_matrix(src, src))

        ok_matrix = np.ones((len(src) + 1, len(src) + 1))

        ok_matrix[:-1, :-1] = var_matrix
        ok_matrix[-1, -1] = 0.

        return ok_matrix
项目:diffusion-maps    作者:jmbr    | 项目源码 | 文件源码
def compute_kdtree(points: np.array, kdtree_options: Optional[Dict]) \
            -> None:
        """Compute kd-tree from points.

        """
        if kdtree_options is None:
            kdtree_options = dict()

        return scipy.spatial.cKDTree(points, **kdtree_options)
项目:diffusion-maps    作者:jmbr    | 项目源码 | 文件源码
def __init__(self, points: np.array, epsilon: float,
                 cut_off: Optional[float] = None,
                 num_eigenpairs: Optional[int] = default.num_eigenpairs,
                 normalize_kernel: Optional[bool] = True,
                 renormalization: Optional[float] = default.renormalization,
                 kdtree_options: Optional[Dict] = None,
                 use_cuda: Optional[bool] = default.use_cuda) -> None:
        self.points = points
        self.epsilon = epsilon

        if cut_off is not None:
            import warnings
            warnings.warn('A cut off was specified for dense diffusion maps.')

        distance_matrix_squared = scipy.spatial.distance.pdist(points, metric='sqeuclidean')  # noqa
        kernel_matrix = np.exp(-distance_matrix_squared / (2.0 * epsilon))
        kernel_matrix = scipy.spatial.distance.squareform(kernel_matrix)
        if normalize_kernel is True:
            kernel_matrix = self.normalize_kernel_matrix(kernel_matrix,
                                                         renormalization)
        self.kernel_matrix = kernel_matrix
        self.renormalization = renormalization if normalize_kernel else None

        if use_cuda is True:
            import warnings
            warnings.warn('Dense diffusion maps are not implemented on the '
                          'GPU. Using the CPU instead.')

        ew, ev = self.solve_eigenproblem(self.kernel_matrix, num_eigenpairs,
                                         use_cuda=False)
        if np.linalg.norm(ew.imag > 1e2 * sys.float_info.epsilon, np.inf):
            raise ValueError('Eigenvalues have non-negligible imaginary part')
        self.eigenvalues = ew.real
        self.eigenvectors = ev.real
项目:pyomo    作者:Pyomo    | 项目源码 | 文件源码
def generate_delaunay(variables, num=10, **kwds):
    """
    Generate a Delaunay triangulation of the D-dimensional
    bounded variable domain given a list of D variables.

    Requires numpy and scipy.

    Args:
        variables: A list of variables, each having a finite
            upper and lower bound.
        num (int): The number of grid points to generate for
            each variable (default=10).
        **kwds: All additional keywords are passed to the
          scipy.spatial.Delaunay constructor.

    Returns:
        A scipy.spatial.Delaunay object.
    """
    if not (numpy_available and scipy_available):             #pragma:nocover
        raise ImportError(
            "numpy and scipy are required")
    linegrids = []
    for v in variables:
        if v.has_lb() and v.has_ub():
            linegrids.append(numpy.linspace(v.lb, v.ub, num))
        else:
            raise ValueError(
                "Variable %s does not have a "
                "finite lower and upper bound.")
    # generates a meshgrid and then flattens and transposes
    # the meshgrid into an (npoints, D) shaped array of
    # coordinates
    points = numpy.vstack(numpy.meshgrid(*linegrids)).\
             reshape(len(variables),-1).T
    return scipy.spatial.Delaunay(points, **kwds)
项目:roboschool    作者:openai    | 项目源码 | 文件源码
def test_triangulation(fn, extents):
    tr = Triangulation()

    color_change_grid_search(tr, *extents, 250,250*4//5)
    grid_result = tr.p.copy()

    retry = 10
    nothing_added = False
    while 1:
        tr.p_array = np.array( tr.p )
        print("points:", tr.p_array.shape)
        tr.dela = scipy.spatial.Delaunay(tr.p_array)
        if retry==0: break
        if nothing_added: break
        retry -= 1
        nothing_added = True
        for r in tr.dela.simplices:
            centerx = 1.0/3*( tr.p[r[0]][0] + tr.p[r[1]][0] + tr.p[r[2]][0] )
            centery = 1.0/3*( tr.p[r[0]][1] + tr.p[r[1]][1] + tr.p[r[2]][1] )
            centercolor = color(centerx, centery)
            for p in [0,1,2]:
                worst = 0.02
                fix_x, fix_y = None, None
                for i in [5,0,1,2,3,4,6,7,8,9]:  # start from middle
                    middle = i==5
                    p1share = (i+0.5)/10   # 0.05 0.15 .. 0.95
                    px = p1share*tr.p[r[p]][0] + (1-p1share)*tr.p[r[p-1]][0]
                    py = p1share*tr.p[r[p]][1] + (1-p1share)*tr.p[r[p-1]][1]
                    pcolor = color(px, py)
                    if pcolor==centercolor: continue
                    nx, ny = find_color_change(px,py,pcolor, centerx,centery,centercolor)
                    dist = np.sqrt( np.square(px-nx) + np.square(py-ny) )
                    if worst < dist:
                        worst = dist
                        fix_x, fix_y = nx, ny
                    else:
                        if middle: break  # optimization
                if fix_x != None:
                    tr.p.append( [fix_x, fix_y] )
                    nothing_added = False

    obj = Obj(fn)
    obj.v_idx = []
    for v in tr.p:
        obj.v_idx.append( obj.push_v( [v[0],v[1],0] ) )
        obj.push_vn( [0,0,1] )
        obj.push_vt( [v[0]*0.2+0.25, v[1]*0.2+0.25] )
    for material_index,material in enumerate(tr.material_palette):
        obj.out.write("\n\nusemtl %s\n" % material)
        obj.out.write("o %s\n" % material)
        for r in tr.dela.simplices:
            rx = 1.0/3*( tr.p[r[0]][0] + tr.p[r[1]][0] + tr.p[r[2]][0] )
            ry = 1.0/3*( tr.p[r[0]][1] + tr.p[r[1]][1] + tr.p[r[2]][1] )
            c = color(rx, ry)
            if c!=material_index: continue
            obj.out.write("f %i/%i/%i %i/%i/%i %i/%i/%i\n" % tuple( [obj.v_idx[r[0]]]*3 + [obj.v_idx[r[1]]]*3 + [obj.v_idx[r[2]]]*3 ))
    obj.out.close()
项目:icing    作者:slipguru    | 项目源码 | 文件源码
def dm_dense_intra_padding(l1, dist_function, condensed=False):
    """Compute in a parallel way a distance matrix for a 1-d array.

    Parameters
    ----------
    l1, l2 : array_like
        1-dimensional arrays. Compute the distance matrix for each couple of
        elements of l1.
    dist_function : function
        Function to use for the distance computation.

    Returns
    -------
    dist_matrix : array_like
        Symmetric NxN distance matrix for each input_array element.
    """
    def _internal(l1, n, idx, nprocs, shared_arr, dist_function):
        for i in xrange(idx, n, nprocs):
            if i % 2 == 0:
                progressbar(i, n)
            # shared_arr[i, i:] = [dist_function(l1[i], el2) for el2 in l2]
            for j in xrange(i + 1, n):
                shared_arr[idx, j] = dist_function(l1[i], l1[j])
                # if shared_arr[idx, j] == 0:
                # print l1[i].junction, '\n', l1[j].junction, '\n----------'

    n = len(l1)
    nprocs = min(mp.cpu_count(), n)
    shared_array = np.frombuffer(mp.Array('d', n*n).get_obj()).reshape((n, n))
    procs = []
    try:
        for idx in xrange(nprocs):
            p = mp.Process(target=_internal,
                           args=(l1, n, idx, nprocs, shared_array,
                                 dist_function))
            p.start()
            procs.append(p)

        for p in procs:
            p.join()
    except (KeyboardInterrupt, SystemExit):
        term_processes(procs, 'Exit signal received\n')
    except BaseException as msg:
        term_processes(procs, 'ERROR: %s\n' % msg)

    progressbar(n, n)
    dist_matrix = shared_array + shared_array.T
    if condensed:
        dist_matrix = scipy.spatial.distance.squareform(dist_matrix)
    return dist_matrix