def test_nearest_neighbour_big(self): # creating tree - 36 s # finding nn - 0.3 ms # nth element - 1.37 ms # sort - 1.2 ms random.seed(42) points = [(random.randint(-100000, 100000), random.randint(-100000, 100000), random.randint(-100000, 100000)) for _ in range(25000)] point = (random.randint(-100000, 100000), random.randint(-100000, 100000), random.randint(-100000, 100000)) closest = (-10000000, -10000000, -10000000) for p in points: if distance(point, p) < distance(point, closest): closest = p start = timeit.default_timer() tree = KdTree(points) print('Creating tree', timeit.default_timer() - start) start = timeit.default_timer() nearest = tree.nearest_neighbour(point, 100) print('Searching NN', timeit.default_timer() - start) self.assertTupleEqual(nearest[0].point, closest)
def test_nearest_neighbour_random(self): for seed in range(1, 10): random.seed(seed) points = [self.random_point(100) for _ in range(100)] point = self.random_point(100) closest = sorted(points, key=lambda x: distance(point, x)) tree = KdTree(points) self.assertTupleEqual( tree.nearest_neighbour(point, 1)[0].point, closest[0]) nearest = tree.nearest_neighbour(point, 10) for n, c in zip(nearest, closest): self.assertTupleEqual(n.point, c)
def test_init(self): tree = KdTree([(1, 2)]) self.assertTupleEqual(tree.root.point, (1, 2)) self.assertIsNone(tree.root.left_child) self.assertIsNone(tree.root.right_child) tree = KdTree([(1, 2), (2, 1)]) self.assertTupleEqual(tree.root.point, (2, 1)) self.assertTupleEqual(tree.root.left_child.point, (1, 2)) self.assertIsNone(tree.root.right_child) tree = KdTree([(1, ), (2, ), (3, )]) self.assertTupleEqual(tree.root.point, (2, )) self.assertTupleEqual(tree.root.left_child.point, (1, )) self.assertTupleEqual(tree.root.right_child.point, (3, ))
def _build_tree(self): # build tree self._log.info(u"Building kd-tree...") self.tree = KdTree(point_list=openOff(self._model_var.get()).get_vertices()) self._log.info(u"Building kd-tree done.") # create vertex visualization self._log.info(u"Building kd-tree vizualization...") GLTargetDistantLight( pos = (0.3, -0.5, 1) ) mat = GLMaterial( diffuse = (1, 0, 0) ) vertices = list(self.tree.iter_vertices()) t_vertices, t_faces = self._generate_trimesh_params(vertices) TriMesh(verts=t_vertices, faces=t_faces, material=mat) #, dynamics=False, static=True) #for vertex in list(tree.iter_vertices()): #Box(pos=vertex, lx=0.05, ly=0.05, lz=0.05, dynamics=False, static=True, material=mat) #Sphere() # create bbox visualization pass self._log.info(u"Building kd-tree vizualization done.")
def _build_tree(self): # build tree self._log.info(u"Building kd-tree...") self.tree = KdTree( point_list=openOff(self._model_var.get()).get_vertices()) self._log.info(u"Building kd-tree done.") # create vertex visualization self._log.info(u"Building kd-tree vizualization...") GLTargetDistantLight(pos=(0.3, -0.5, 1)) mat = GLMaterial(diffuse=(1, 0, 0)) vertices = list(self.tree.iter_vertices()) t_vertices, t_faces = self._generate_trimesh_params(vertices) TriMesh(verts=t_vertices, faces=t_faces, material=mat) #, dynamics=False, static=True) #for vertex in list(tree.iter_vertices()): #Box(pos=vertex, lx=0.05, ly=0.05, lz=0.05, dynamics=False, static=True, material=mat) #Sphere() # create bbox visualization pass self._log.info(u"Building kd-tree vizualization done.")
milestones = [] milestones.append(np.array([5, 5])) for coord in coordinates: circle = Circle(coord, robot.b / 2) if len(m.get_intersecting_rects(circle)) == 0: milestones.append(coord) milestones.append(np.array([70, 15])) milestones.append(np.array([90, 50])) milestones.append(np.array([30, 95])) milestones.append(np.array([5, 50])) milestones = np.array(milestones) # Generate kd-tree tree = KdTree(milestones) tree.init_build() # Create connection/adjacency matrix for nodes # Also remove invalid connections connections = np.zeros((tree.nodes.shape[0], tree.nodes.shape[0]), dtype=int) for milestone in milestones: best = tree.get_nn(milestone, 5) for b in best: line_l = Line(best[0].val - robot.b / 2, b.val - robot.b / 2) line_r = Line(best[0].val + robot.b / 2, b.val + robot.b / 2) if m.intersects_line(line_l) or m.intersects_line(line_r): continue
class KdTreeOptionFrame(Frame): def __init__(self, master=None): Frame.__init__(self, master, borderwidth=1, relief=GROOVE) self._log = logging.getLogger('KdTreeOptions') self._model_var = StringVar() self._model_var.set("data/cow.off") self._tree_min_depth_var = IntVar() self._tree_min_depth_var.set(0) self._tree_max_depth_var = IntVar() self._tree_max_depth_var.set(5) self._label = Label(self, text="KD-Tree Options", width=30) self._label.grid(row=0, sticky=E+W) self._entry_model = Entry(self, textvariable=self._model_var) self._entry_model.grid(row=1, sticky=E+W) self._button_build = Button(self, text="Build KD-Tree", command=self._build_tree) self._button_build.grid(row=2, sticky=E+W) self._scale_tree_min_depth = Scale(self, label="Minimum tree depth", variable=self._tree_min_depth_var, from_=0, to=10, orient=HORIZONTAL) self._scale_tree_min_depth.grid(row=3, sticky=E+W) self._scale_tree_max_depth = Scale(self, label="Maximum tree depth", variable=self._tree_max_depth_var, from_=0, to=10, orient=HORIZONTAL) self._scale_tree_max_depth.grid(row=4, sticky=E+W) self._button_show = Button(self, text="Show KD-Tree boxes", command=self._build_tree_visualization) self._button_show.grid(row=5, sticky=E+W) self._tree_boxes = [] def _build_tree(self): # build tree self._log.info(u"Building kd-tree...") self.tree = KdTree(point_list=openOff(self._model_var.get()).get_vertices()) self._log.info(u"Building kd-tree done.") # create vertex visualization self._log.info(u"Building kd-tree vizualization...") GLTargetDistantLight( pos = (0.3, -0.5, 1) ) mat = GLMaterial( diffuse = (1, 0, 0) ) vertices = list(self.tree.iter_vertices()) t_vertices, t_faces = self._generate_trimesh_params(vertices) TriMesh(verts=t_vertices, faces=t_faces, material=mat) #, dynamics=False, static=True) #for vertex in list(tree.iter_vertices()): #Box(pos=vertex, lx=0.05, ly=0.05, lz=0.05, dynamics=False, static=True, material=mat) #Sphere() # create bbox visualization pass self._log.info(u"Building kd-tree vizualization done.") def _build_tree_visualization(self): min_depth = self._tree_min_depth_var.get() max_depth = self._tree_max_depth_var.get() mat = GLMaterial( diffuse = (0, 1, 0, 0.1), blend_factors = (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ) if hasattr(self, 'tree'): self._log.info(u"Building kd-tree bounding box visualization...") stack = [(self.tree.root, 0), ] while stack: node, level = stack.pop() if level >= min_depth and level <= max_depth: bbox = node.get_bbox() bounds = bbox.getBounds() self._tree_boxes.append(Box(pos=bbox.center(), lx=bounds[0][0] - bounds[1][0], ly=bounds[0][1] - bounds[1][1], lz=bounds[0][2] - bounds[1][2], material=mat)) if level < max_depth: if node.left_child: stack.append((node.left_child, level+1)) if node.right_child: stack.append((node.right_child, level+1)) self._log.info(u"Building kd-tree bounding box visualization done.") else: self._log.error(u"No kd-tree found. Please build the tree first.") def _generate_trimesh_params(self, vertices): result_vertices = [] result_faces = [] for n, vertex in enumerate(vertices): n = n * 4 result_vertices.append(vertex) result_vertices.append(vertex+(0.1, 0 , 0 )) result_vertices.append(vertex+(0 , 0.1, 0 )) result_vertices.append(vertex+(0 , 0 , 0.1)) result_faces.append((n , n+1, n+2)) result_faces.append((n , n+1, n+3)) result_faces.append((n , n+2, n+3)) result_faces.append((n+1, n+2, n+3)) return (result_vertices, result_faces)
def test_nearest_neighbour(self): tree = KdTree([(1, )]) nearest = tree.nearest_neighbour((-3, ), 1) self.assertTupleEqual(nearest[0].point, (1, )) tree = KdTree([(1, 3), (2, 4)]) nearest = tree.nearest_neighbour((0, 2), 1) self.assertTupleEqual(nearest[0].point, (1, 3)) nearest = tree.nearest_neighbour((3, 5), 1) self.assertTupleEqual(nearest[0].point, (2, 4)) tree = KdTree([(1, 3, 3), (4, 8, 7), (2, -1, 2), (3, 4, 1)]) nearest = tree.nearest_neighbour((1, 2, 0), 1) self.assertTupleEqual(nearest[0].point, (3, 4, 1)) tree = KdTree([(-1, 1), (0, -2), (1, -2)]) nearest = tree.nearest_neighbour((1, 2), 1) self.assertTupleEqual(nearest[0].point, (-1, 1))
nearest = [node.data for node in nodes] distances = [position.distance(system) for system in nearest] return render_template('closest.html', position=position, rows=zip(nearest, distances)) else: return render_template('closest.html') def load_systems(filename): logging.info('Reading systems data') systems = [] coords = [] with open(filename, 'r') as file: systems_json = json.load(file) systems = [ System(row['name'], sectors=sectors) for row in systems_json ] coords = [system.coordinates for system in systems] logging.info('Number of systems read: %d', len(systems)) return systems, coords logging.basicConfig(level=logging.INFO) sectors = Sectors() systems, coordinates = load_systems('resources/systemsWithoutCoordinates.json') logging.info('Creating tree') kd_tree = KdTree(coordinates, systems) logging.info('Tree created')
def render(): pygame.display.flip() def handel_events(self, click_callback): for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == pygame.MOUSEBUTTONDOWN: click_callback(event.pos[0] // self.scale, event.pos[1] // self.scale) if __name__ == '__main__': renderer = Renderer(100, 100, 5) tree = KdTree(AaBb(2, Vec(2, 0, 0), Vec(2, 100, 100)), 2) def draw_callback(values, box: AaBb): for item in values: renderer.draw_box(item.top_left, item.down_right, 0x0000ff) renderer.draw_box(box.top_left, box.down_right) while True: renderer.cls() ray_point = Vec(2, random.randint(0, 50), random.randint(0, 100)) ray_direct = Vec(2, 100 - ray_point[0], random.randint(0, 100) - ray_point[1]) renderer.draw_line(ray_point[0], ray_point[1], ray_point[0] + ray_direct[0], ray_point[1] + ray_direct[1], 0xff0000)
class KdTreeOptionFrame(Frame): def __init__(self, master=None): Frame.__init__(self, master, borderwidth=1, relief=GROOVE) self._log = logging.getLogger('KdTreeOptions') self._model_var = StringVar() self._model_var.set("data/cow.off") self._tree_min_depth_var = IntVar() self._tree_min_depth_var.set(0) self._tree_max_depth_var = IntVar() self._tree_max_depth_var.set(5) self._label = Label(self, text="KD-Tree Options", width=30) self._label.grid(row=0, sticky=E + W) self._entry_model = Entry(self, textvariable=self._model_var) self._entry_model.grid(row=1, sticky=E + W) self._button_build = Button(self, text="Build KD-Tree", command=self._build_tree) self._button_build.grid(row=2, sticky=E + W) self._scale_tree_min_depth = Scale(self, label="Minimum tree depth", variable=self._tree_min_depth_var, from_=0, to=10, orient=HORIZONTAL) self._scale_tree_min_depth.grid(row=3, sticky=E + W) self._scale_tree_max_depth = Scale(self, label="Maximum tree depth", variable=self._tree_max_depth_var, from_=0, to=10, orient=HORIZONTAL) self._scale_tree_max_depth.grid(row=4, sticky=E + W) self._button_show = Button(self, text="Show KD-Tree boxes", command=self._build_tree_visualization) self._button_show.grid(row=5, sticky=E + W) self._tree_boxes = [] def _build_tree(self): # build tree self._log.info(u"Building kd-tree...") self.tree = KdTree( point_list=openOff(self._model_var.get()).get_vertices()) self._log.info(u"Building kd-tree done.") # create vertex visualization self._log.info(u"Building kd-tree vizualization...") GLTargetDistantLight(pos=(0.3, -0.5, 1)) mat = GLMaterial(diffuse=(1, 0, 0)) vertices = list(self.tree.iter_vertices()) t_vertices, t_faces = self._generate_trimesh_params(vertices) TriMesh(verts=t_vertices, faces=t_faces, material=mat) #, dynamics=False, static=True) #for vertex in list(tree.iter_vertices()): #Box(pos=vertex, lx=0.05, ly=0.05, lz=0.05, dynamics=False, static=True, material=mat) #Sphere() # create bbox visualization pass self._log.info(u"Building kd-tree vizualization done.") def _build_tree_visualization(self): min_depth = self._tree_min_depth_var.get() max_depth = self._tree_max_depth_var.get() mat = GLMaterial(diffuse=(0, 1, 0, 0.1), blend_factors=(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)) if hasattr(self, 'tree'): self._log.info(u"Building kd-tree bounding box visualization...") stack = [ (self.tree.root, 0), ] while stack: node, level = stack.pop() if level >= min_depth and level <= max_depth: bbox = node.get_bbox() bounds = bbox.getBounds() self._tree_boxes.append( Box(pos=bbox.center(), lx=bounds[0][0] - bounds[1][0], ly=bounds[0][1] - bounds[1][1], lz=bounds[0][2] - bounds[1][2], material=mat)) if level < max_depth: if node.left_child: stack.append((node.left_child, level + 1)) if node.right_child: stack.append((node.right_child, level + 1)) self._log.info( u"Building kd-tree bounding box visualization done.") else: self._log.error(u"No kd-tree found. Please build the tree first.") def _generate_trimesh_params(self, vertices): result_vertices = [] result_faces = [] for n, vertex in enumerate(vertices): n = n * 4 result_vertices.append(vertex) result_vertices.append(vertex + (0.1, 0, 0)) result_vertices.append(vertex + (0, 0.1, 0)) result_vertices.append(vertex + (0, 0, 0.1)) result_faces.append((n, n + 1, n + 2)) result_faces.append((n, n + 1, n + 3)) result_faces.append((n, n + 2, n + 3)) result_faces.append((n + 1, n + 2, n + 3)) return (result_vertices, result_faces)