本文整理汇总了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
示例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
示例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
示例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)
示例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)
示例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
示例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)
示例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
示例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
示例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
示例11: cdist
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import spatial [as 别名]
def cdist(A, B, **kwargs):
return scipy.spatial.distance.cdist(A, B, **kwargs)
示例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
示例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
示例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)
示例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