當前位置: 首頁>>代碼示例>>Python>>正文


Python scipy.spatial方法代碼示例

本文整理匯總了Python中scipy.spatial方法的典型用法代碼示例。如果您正苦於以下問題:Python scipy.spatial方法的具體用法?Python scipy.spatial怎麽用?Python scipy.spatial使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在scipy的用法示例。


在下文中一共展示了scipy.spatial方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_extend_hull

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
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:
            # 設置初值 以獲得兩個解
            if simplex[1] == 0:
                continue
            pairs = [True, False]
            for pair in pairs:
                # print(pair)
                extend_point = self.equations(points[simplex], pair)
                # 在邊界內的點排除
                if extend_point and not self.point_in_path(extend_point):
                    ext_points.append([extend_point[0], extend_point[1], self.zvalues[simplex[0]]])
        return ext_points 
開發者ID:flashlxy,項目名稱:PyMICAPS,代碼行數:23,代碼來源:PolygonEx.py

示例2: project_to_sphere

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def project_to_sphere(points, center, radius):
    """
    Projects the elements of points onto the sphere defined
    by center and radius.

    Parameters
    ----------
    points : array of floats of shape (npoints, ndim)
             consisting of the points in a space of dimension ndim
    center : array of floats of shape (ndim,)
            the center of the sphere to project on
    radius : float
            the radius of the sphere to project on

    returns: array of floats of shape (npoints, ndim)
            the points projected onto the sphere
    """

    lengths = scipy.spatial.distance.cdist(points, np.array([center]))
    return (points - center) / lengths * radius + center 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:22,代碼來源:_spherical_voronoi.py

示例3: distance_compare_unit

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def distance_compare_unit(data):
        host = data[0]
        host_words = host['gt'].split(" ")
        host_mean = host['mean']
        host_mean = host_mean / LA.norm(host_mean)

        guest = data[1:]
        num_guest = len(guest)
        bag = []
        for idx, g in enumerate(guest):
            g_mean = g['mean']
            g_words = g['gt'].split(" ")
            # jaccard = comp_jaccard_distance(g_words, host_words)
            cos_distance = -1 * (scipy.spatial.distance.cosine(g_mean, host_mean) - 1)
            bag.append([0, cos_distance])
        return bag 
開發者ID:jiacheng-xu,項目名稱:vmf_vae_nlp,代碼行數:18,代碼來源:analyze_samples.py

示例4: _in_hull

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def _in_hull(p, hull):
  ''' 
  Tests if points in `p` are in the convex hull made up by `hull`
  '''
  dim = p.shape[1]
  # if there are not enough points in `hull` to form a simplex then 
  # return False for each point in `p`.
  if hull.shape[0] <= dim:
    return np.zeros(p.shape[0], dtype=bool)
  
  if dim >= 2:
    hull = scipy.spatial.Delaunay(hull)
    return hull.find_simplex(p)>=0
  else:
    # one dimensional points
    min = np.min(hull)
    max = np.max(hull)
    return (p[:, 0] >= min) & (p[:, 0] <= max) 
開發者ID:treverhines,項目名稱:RBF,代碼行數:20,代碼來源:interpolate.py

示例5: _compute_gram_matrix

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def _compute_gram_matrix(X, kernel_type, params):
    """
    """
    if kernel_type == 'rbf':
        if 'gamma' in params:
            gamma = params['gamma']
        else:
            gamma = 1.0 / X.shape[1]

        pairwise_dist = scipy.spatial.distance.pdist(X, metric='sqeuclidean')
        pairwise_dist = scipy.spatial.distance.squareform(pairwise_dist)
        gram_matrix = np.exp( - gamma * pairwise_dist )

        np.fill_diagonal(gram_matrix, 1)
    else:
        pass

    return(gram_matrix) 
開發者ID:vmirly,項目名稱:pyclust,代碼行數:20,代碼來源:_kernel_kmeans.py

示例6: dHdxy

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def dHdxy(self):
        """
        Calculate the spatial derivative of water depth in each direction
        (xi and eta).

        Parameters
        ----------
        None

        Returns
        -------
        dHdxi : ndarray,
          Slope in x-direction
        dHdeta : ndarray,
          Slope in eta-direction
        """
        dHdxi = np.zeros(self.h.shape)
        dHdeta = np.zeros(self.h.shape)
        dHdxi[:, :-1] = -np.diff(self.h, axis=1) * self.pm[:, 1:]
        dHdxi[:, -1] = dHdxi[:, -2]
        dHdeta[:-1, :] = -np.diff(self.h, axis=0) * self.pn[1:, :]
        dHdeta[-1, :] = dHdeta[-2, :]

        return dHdxi, dHdeta 
開發者ID:powellb,項目名稱:seapy,代碼行數:26,代碼來源:grid.py

示例7: calc_dist_mat

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def calc_dist_mat(subject, bipolar=False, snap=False):
    from scipy.spatial import distance

    pos_fname = 'electrodes{}_{}positions.npz'.format('_bipolar' if bipolar else '', 'snap_' if snap else '')
    pos_fname = op.join(MMVT_DIR, subject, 'electrodes', pos_fname)
    output_fname = 'electrodes{}_{}dists.npy'.format('_bipolar' if bipolar else '', 'snap_' if snap else '')
    output_fname = op.join(MMVT_DIR, subject, 'electrodes', output_fname)

    if not op.isfile(pos_fname):
        return False
    d = np.load(pos_fname)
    pos = d['pos']
    x = np.zeros((len(pos), len(pos)))
    for i in range(len(pos)):
        for j in range(len(pos)):
            x[i,j] = np.linalg.norm(pos[i]- pos[j]) # np.sqrt((pos[i]- pos[j])**2)
            # assert(x[i,j]==np.linalg.norm(pos[i]- pos[j]))
    # x = distance.cdist(pos, pos, 'euclidean')
    np.save(output_fname, x)
    return op.isfile(output_fname) 
開發者ID:pelednoam,項目名稱:mmvt,代碼行數:22,代碼來源:electrodes.py

示例8: distance_from_goal

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def distance_from_goal(self, goal: np.ndarray, state: dict) -> float:
        """
        Given a state, check its distance from the goal

        :param goal: a numpy array representing the goal
        :param state: a dict representing the state
        :return: the distance from the goal
        """
        state_value = self.goal_from_state(state)

        # calculate distance
        if self.distance_metric == self.DistanceMetric.Cosine:
            dist = scipy.spatial.distance.cosine(goal, state_value)
        elif self.distance_metric == self.DistanceMetric.Euclidean:
            dist = scipy.spatial.distance.euclidean(goal, state_value)
        elif self.distance_metric == self.DistanceMetric.Manhattan:
            dist = scipy.spatial.distance.cityblock(goal, state_value)
        elif callable(self.distance_metric):
            dist = self.distance_metric(goal, state_value)
        else:
            raise ValueError("The given distance metric for the goal is not valid.")

        return dist 
開發者ID:NervanaSystems,項目名稱:coach,代碼行數:25,代碼來源:spaces.py

示例9: spatial_hashes

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def spatial_hashes(coordinates, sigma_bins):
        import scipy, scipy.spatial
        try:              from scipy.spatial import cKDTree as shash
        except Exception: from scipy.spatial import KDTree  as shash
        return tuple([shash(coordinates[ii]) for ii in sigma_bins])
    # Methods 
開發者ID:noahbenson,項目名稱:neuropythy,代碼行數:8,代碼來源:cmag.py

示例10: spatial_hash

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def spatial_hash(coordinates):
        import scipy, scipy.spatial
        try:              from scipy.spatial import cKDTree as shash
        except Exception: from scipy.spatial import KDTree  as shash
        return shash(coordinates)
    # Static helper function 
開發者ID:noahbenson,項目名稱:neuropythy,代碼行數:8,代碼來源:cmag.py

示例11: cdist

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def cdist(A, B, **kwargs):
    return scipy.spatial.distance.cdist(A, B, **kwargs) 
開發者ID:msu-coinlab,項目名稱:pymoo,代碼行數:4,代碼來源:misc.py

示例12: _distance_mahalanobis

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def _distance_mahalanobis(X=None):
    cov = X.cov().values
    cov = scipy.linalg.inv(cov)

    col_means = X.mean().values

    dist = np.full(len(X), np.nan)
    for i in range(len(X)):
        dist[i] = scipy.spatial.distance.mahalanobis(X.iloc[i, :].values, col_means, cov) ** 2
    return dist 
開發者ID:neuropsychology,項目名稱:NeuroKit,代碼行數:12,代碼來源:distance.py

示例13: _find_closest_surface_pos

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def _find_closest_surface_pos(pos, mesh, surface_tags):
    nodes_in_surface = _get_nodes_in_surface(mesh, surface_tags)
    if len(nodes_in_surface) == 0:
        raise ValueError('Surface with tags: {0} not found'.format(surface_tags))
    kd_tree = scipy.spatial.cKDTree(mesh.nodes[nodes_in_surface])
    _, center_idx = kd_tree.query(pos)
    #center_idx = np.argmin(np.linalg.norm(mesh.nodes[nodes_in_surface] - pos))
    pos = mesh.nodes.node_coord[nodes_in_surface - 1][center_idx]
    return pos 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:11,代碼來源:electrode_placement.py

示例14: _calc_kdtree

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def _calc_kdtree(triangles, nodes):
    tr_baricenters = _triangle_baricenters(triangles, nodes)
    return scipy.spatial.cKDTree(tr_baricenters) 
開發者ID:simnibs,項目名稱:simnibs,代碼行數:5,代碼來源:electrode_placement.py

示例15: in_hull

# 需要導入模塊: import scipy [as 別名]
# 或者: from scipy import spatial [as 別名]
def in_hull(p, hull):
    """
    :param p: (N, K) test points
    :param hull: (M, K) M corners of a box
    :return (N) bool
    """
    try:
        if not isinstance(hull, Delaunay):
            hull = Delaunay(hull)
        flag = hull.find_simplex(p) >= 0
    except scipy.spatial.qhull.QhullError:
        print('Warning: not a hull %s' % str(hull))
        flag = np.zeros(p.shape[0], dtype=np.bool)

    return flag 
開發者ID:sshaoshuai,項目名稱:PointRCNN,代碼行數:17,代碼來源:kitti_utils.py


注:本文中的scipy.spatial方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。