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


Python spatial.KDTree方法代碼示例

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


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

示例1: generate_icp_results

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def generate_icp_results(self, gt_pose):
		from icp import icp_test
		from scipy.spatial import KDTree
		M_given = self.templates[self.template_idx,:,:]

		S_given = helper.apply_transformation(M_given.reshape((1,-1,3)), gt_pose)[0]
		# S_given = S_given + np.random.normal(0,1,S_given.shape)						# Noisy Data

		M_given = M_given[0:self.NUM_POINT,:]				# template data
		S_given = S_given[0:self.NUM_POINT,:]				# source data

		tree_M = KDTree(M_given)
		tree_M_sampled = KDTree(M_given[0:100,:])

		final_pose, model_data, sensor_data, predicted_data, title, _, _ = icp_test(S_given[0:100,:], M_given, tree_M, M_given[0:100,:], tree_M_sampled, S_given, gt_pose.reshape((1,6)), self.MAX_LOOPS, self.ftol)		
		self.find_errors(gt_pose, final_pose)
		helper.display_three_clouds(model_data, sensor_data, predicted_data, title) 
開發者ID:vinits5,項目名稱:pointnet-registration-framework,代碼行數:19,代碼來源:helper_analysis.py

示例2: bench_build

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def bench_build(self):
        print()
        print('        Constructing kd-tree')
        print('=====================================')
        print(' dim | # points |  KDTree  | cKDTree ')

        for (m, n, repeat) in [(3,10000,3), (8,10000,3), (16,10000,3)]:
            print('%4s | %7s ' % (m, n), end=' ')
            sys.stdout.flush()

            data = np.concatenate((np.random.randn(n//2,m),
                                   np.random.randn(n-n//2,m)+np.ones(m)))

            print('| %6.3fs ' % (measure('T1 = KDTree(data)', repeat) / repeat), end=' ')
            sys.stdout.flush()
            print('| %6.3fs' % (measure('T2 = cKDTree(data)', repeat) / repeat), end=' ')
            sys.stdout.flush()
            print('') 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:20,代碼來源:bench_ckdtree.py

示例3: setUp

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def setUp(self):
        self.data = np.array([[0,0,0],
                              [0,0,1],
                              [0,1,0],
                              [0,1,1],
                              [1,0,0],
                              [1,0,1],
                              [1,1,0],
                              [1,1,1]])
        self.kdtree = KDTree(self.data)
        self.n = self.kdtree.n
        self.m = self.kdtree.m
        np.random.seed(1234)
        self.x = np.random.randn(3)
        self.d = 0.5
        self.k = 4 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:18,代碼來源:test_kdtree.py

示例4: test_onetree_query

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def test_onetree_query():
    np.random.seed(0)
    n = 50
    k = 4
    points = np.random.randn(n,k)
    T = KDTree(points)
    yield check_onetree_query, T, 0.1

    points = np.random.randn(3*n,k)
    points[:n] *= 0.001
    points[n:2*n] += 2
    T = KDTree(points)
    yield check_onetree_query, T, 0.1
    yield check_onetree_query, T, 0.001
    yield check_onetree_query, T, 0.00001
    yield check_onetree_query, T, 1e-6 
開發者ID:ktraunmueller,項目名稱:Computable,代碼行數:18,代碼來源:test_kdtree.py

示例5: exact_full_marker_data

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def exact_full_marker_data(csv_path, marker_pkl):
    all_data_arr = np.genfromtxt(csv_path, delimiter=",", skip_header=1)
    marker_jdcs_collection = cPickle.load(open(marker_pkl[0], "rb"))
    tmp_list = list()
    for jdc in marker_jdcs_collection:
        tmp_list.extend(jdc)
    marker_pcd_arr = np.array(tmp_list)

    tree = spatial.KDTree(all_data_arr[:, :3])
    marker_full_data_ls = []
    for i in xrange(marker_pcd_arr.shape[0]):
        ret = tree.query(marker_pcd_arr[i])
        marker_full_data_ls.append(all_data_arr[ret[1]])

    marker_full_data_arr = np.array(marker_full_data_ls)
    return marker_full_data_arr


# get the Hessian normal form of 3D plane 
開發者ID:mfxox,項目名稱:ILCC,代碼行數:21,代碼來源:pcd_corners_est.py

示例6: build_index

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def build_index(self):

        midpoints = []

        self.index = {}

        for ct, fset in enumerate(self.sets.values()):
            mp = []
            for vr in self.explanatory_variables:
                mp.append(fset.sets[vr.name].centroid)
            midpoints.append(mp)
            self.index[ct] = fset.name

        import sys
        sys.setrecursionlimit(100000)

        self.kdtree = KDTree(midpoints)

        sys.setrecursionlimit(1000) 
開發者ID:PYFTS,項目名稱:pyFTS,代碼行數:21,代碼來源:partitioner.py

示例7: build_index

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def build_index(self):
        points = []

        fset = self.sets[self.ordered_sets[0]]
        points.append([fset.sets[1].lower, fset.sets[1].centroid, fset.sets[1].upper])

        for ct, key in enumerate(self.ordered_sets[1:-1]):
            fset = self.sets[key]
            points.append([fset.lower, fset.centroid, fset.upper])

        fset = self.sets[self.ordered_sets[-1]]
        points.append([fset.sets[1].lower, fset.sets[1].centroid, fset.sets[1].upper])

        import sys
        sys.setrecursionlimit(100000)

        self.kdtree = KDTree(points)

        sys.setrecursionlimit(1000) 
開發者ID:PYFTS,項目名稱:pyFTS,代碼行數:21,代碼來源:partitioner.py

示例8: build_index

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def build_index(self):
        points = []

        #self.index = {}

        for ct, key in enumerate(self.ordered_sets):
            fset = self.sets[key]
            points.append([fset.lower, fset.centroid, fset.upper])
            #self.index[ct] = fset.name

        import sys
        sys.setrecursionlimit(100000)

        self.kdtree = KDTree(points)

        sys.setrecursionlimit(1000) 
開發者ID:PYFTS,項目名稱:pyFTS,代碼行數:18,代碼來源:partitioner.py

示例9: triangulatePolygon

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def triangulatePolygon(poly, hole=None):
    # Triangulate poly with hole
    cdt = CDT(poly.points)
    if hole:
        cdt.add_hole(hole)
    triangles = cdt.triangulate()

    # Frustratingly, CDT sometimes returns points that are not
    # EXACTLY the same as the input points, so we use a KDTree
    valid_points = [shapes.Point(p.x, p.y) for p in poly.points]
    if hole:
        valid_points += [shapes.Point(p.x, p.y) for p in hole]
    tree = sp.KDTree(toNumpy(valid_points))

    def convert(t):
        def findClosest(point):
            idx = tree.query(toNumpy([point]))[1]
            return valid_points[idx]
        A = findClosest(shapes.Point(t.a.x, t.a.y))
        B = findClosest(shapes.Point(t.b.x, t.b.y))
        C = findClosest(shapes.Point(t.c.x, t.c.y))
        return shapes.Triangle(A, B, C)
    return map(convert, triangles) 
開發者ID:crm416,項目名稱:point-location,代碼行數:25,代碼來源:spatial.py

示例10: __init__

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def __init__(self, primaryData):
        self.id = str(uuid.uuid4())

        self.griddedCount = 0
        self.griddedMatched = 0

        self.insituCount = len(primaryData)
        self.insituMatches = 0

        self.primary = primaryData
        for r in self.primary:
            r["matches"] = []

        self.data = []
        for s in primaryData:
            u = utm.from_latlon(s["y"], s["x"])
            v = (u[0], u[1], 0.0)
            self.data.append(v)

        if len(self.data) > 0:
            self.tree = spatial.KDTree(self.data)
        else:
            self.tree = None 
開發者ID:apache,項目名稱:incubator-sdap-nexus,代碼行數:25,代碼來源:MatchupQuery.py

示例11: _friends_leaveoneout_radius

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def _friends_leaveoneout_radius(points, ftype):
    """Internal method used to compute the radius (half-side-length) for each
    ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using
    leave-one-out (LOO) cross-validation."""

    # Construct KDTree to enable quick nearest-neighbor lookup for
    # our resampled objects.
    kdtree = spatial.KDTree(points)

    if ftype == 'balls':
        # Compute radius to two nearest neighbors (self + neighbor).
        dists, ids = kdtree.query(points, k=2, eps=0, p=2)
    elif ftype == 'cubes':
        # Compute half-side-length to two nearest neighbors (self + neighbor).
        dists, ids = kdtree.query(points, k=2, eps=0, p=np.inf)

    dist = dists[:, 1]  # distances to LOO nearest neighbor

    return dist 
開發者ID:joshspeagle,項目名稱:dynesty,代碼行數:21,代碼來源:bounding.py

示例12: __init__

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def __init__(self, p0, p1):
        """ p0.shape == (N, 3)
            p1.shape == (N, 3)
        """
        self.p0 = p0
        self.p1 = p1
        leafsize = 1000
        self.nearest = KDTree(self.p0, leafsize=leafsize)
        self.g_series = None 
開發者ID:vinits5,項目名稱:pointnet-registration-framework,代碼行數:11,代碼來源:icp.py

示例13: closest_building_distance_median

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def closest_building_distance_median( point_ref, tree, df_closest_d, radius_search ):
	""" 
	Dispersion metric at point_ref
	Computes the median of the closest distance to another building for each building within a radius search
	Uses the input KDTree to accelerate calculations

	Parameters
	----------
	point_ref : shapely.Point
		calculate index at input point
	tree : scipy.spatial.KDTree
		KDTree of buildings centroid
	df : pandas.DataFrame 
		data frame of buildings with closest distance calculation
	radius_search : float
		circle radius to consider the dispersion calculation at a local point

	Returns
	----------
	float
		value of dispersion at input point
	"""
	# Query buildings within radius search
	indices = tree.query_ball_point( point_ref, radius_search )
	# No dispersion value
	if (len(indices) == 0): return np.NaN
	# Calculate median of closest distance values. If no information is available, NaN is set
	return df_closest_d.loc[ indices ].median() 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:30,代碼來源:dispersion.py

示例14: closest_building_distance_average

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def closest_building_distance_average( point_ref, tree, df_closest_d, radius_search ):
	""" 
	Dispersion metric at point_ref
	Computes the mean of the closest distance to another building for each building within a radius search
	Uses the input KDTree to accelerate calculations

	Parameters
	----------
	point_ref : shapely.Point
		calculate index at input point
	tree : scipy.spatial.KDTree
		KDTree of buildings centroid
	df : pandas.DataFrame 
		data frame of buildings with closest distance calculation
	radius_search : int
		circle radius to consider the dispersion calculation at a local point

	Returns
	----------
	float
		value of dispersion at input point
	"""
	# Query buildings within radius search
	indices = tree.query_ball_point( point_ref, radius_search )
	# No dispersion value
	if (len(indices) == 0): return np.NaN
	# Calculate mean of closest distance values. If no information is available, NaN is set
	return df_closest_d.loc[ indices ].mean()


##############################################################
### Dispersion indices calculation
############################################################## 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:35,代碼來源:dispersion.py

示例15: _apply_polygon_closest_distance_neighbor

# 需要導入模塊: from scipy import spatial [as 別名]
# 或者: from scipy.spatial import KDTree [as 別名]
def _apply_polygon_closest_distance_neighbor(df_osm_built, K_nearest = 50):
	""" 
	Computes for each polygon, the distance to the (approximated) nearest neighboring polygon
	Approximation is done using distance between centroids to K nearest neighboring polygons, then evaluating the real polygon distance
	A column `closest_d` is added in the data frame

	Parameters
	----------
	df_osm_built: geopandas.GeoDataFrame
		data frame containing the building's geometries
	K_nearest: int
		number of neighboring polygons to evaluate

	Returns
	----------

	"""
	def get_closest_indices(tree, x, K_nearest):
		# Query the closest buidings considering their centroid
		return tree.query( x.centroid.coords[0] , k=K_nearest+1)[1][1:]
	def compute_closest_distance(x, buildings):
		# Minimum distance of all distances between reference building 'x' and the other buildings
		return (buildings.apply(lambda b: x.distance(b) ) ).min()

	# Use all elements to get the exact closest neighbor?
	if ( (K_nearest == -1) or (K_nearest >= len(df_osm_built)) ): K_nearest = len(df_osm_built)-1

	# Get separate list for coordinates
	coords_data = [ geom.centroid.coords[0] for geom in df_osm_built.geometry ]
	# Create KD Tree using polygon's centroid
	tree = spatial.KDTree( coords_data )

	# Get the closest buildings indices
	df_osm_built['closest_buildings'] = df_osm_built.geometry.apply(lambda x: get_closest_indices(tree, x, K_nearest) )
	# Compute the minimum real distance for the closest buildings
	df_osm_built['closest_d'] = df_osm_built.apply(lambda x: compute_closest_distance(x.geometry,df_osm_built.geometry.loc[x.closest_buildings]), axis=1 )
	# Drop unnecessary column
	df_osm_built.drop('closest_buildings', axis=1, inplace=True) 
開發者ID:lgervasoni,項目名稱:urbansprawl,代碼行數:40,代碼來源:dispersion.py


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