DM_spatial_knn.py
1 ## @package python.demo.DM_spatial_knn
2 #
3 # example script showing how to fill a kdtree and
4 # perform a kNN query
5 #
6 
7 import sys, math
8 import random
9 from opals import pyDM
10 
11 
12 # create empty kdtree object
13 kdtree = pyDM.PointIndexLeaf(pyDM.IndexType.kdtree,2,True) # index type, dimension, thread safety
14 # The dimension is relevant for the knn queries. If the dimension is 2d, than the nn-query is done
15 # based on 2d distance. For selection based on 3d distances, create kdtree with dimension 3
16 
17 
18 # create 100 points with random coordinate ranges between -50 and 50
19 coord_range = [-50, 50]
20 for i in range(100):
21  x = random.uniform(coord_range[0], coord_range[1])
22  y = random.uniform(coord_range[0], coord_range[1])
23  z = random.uniform(coord_range[0], coord_range[1])
24  kdtree.addPoint( pyDM.Point(x,y,z) )
25 
26 limit = kdtree.getLimit()
27 
28 # output some tree statistics
29 print("kdtree contains", kdtree.sizePoint(), "points")
30 print("2D-limit (%.3f," % limit.xmin, "%.3f) -" % limit.ymin, "(%.3f," % limit.xmax,
31  "%.3f)" % limit.ymax)
32 
33 # set parameters for nn selection
34 nnCount = 10 # find 10 neighbours
35 searchPt = pyDM.Point((limit.xmin+limit.xmax)/2.,(limit.ymin+limit.ymax)/2., 0.) # search at the center of the limit window
36 maxSearchDist = -1 # use -1 for no distance limit
37 searchMode = pyDM.SelectionMode.nearest
38 
39 # perform actual knn query
40 pts = kdtree.searchPoint(nnCount,searchPt,maxSearchDist,searchMode)
41 
42 # output found neighours
43 print(len(pts), "neighbours found")
44 print("Output neighbours...")
45 
46 for i, pt in enumerate(pts):
47  dist = math.sqrt( (searchPt.x-pt.x)**2 + (searchPt.y-pt.y)**2 )
48  print("%3d. Point (%8.3f, %8.3f, %8.3f) dist=%5.3f " % ((i+1), pt.x, pt.y, pt.z, dist) )