def test_createAndLableTree(self): ''' Create new tree with new ids starting from 0''' print "---------- test createAndLabelTree 1--------" no1dN = [] points = numpy.array([[0.0, 0.0], [0.0, 1.0], [ 1.0, 0.0], [1.0, 1.0]]) util.splitN(points, 0, 0, 6, no1dN) tree1 = kdtree.createNewTree(no1dN) label=0 for n in kdtree.level_order(tree1): self.assertIsNotNone(kdtree.getNode(tree1, label), "1: node with label: "+ str(label) + " not found in tree") label+=1 kdtree.visualize(tree1) print "---------- test createAndLabelTree 2--------" no2dN = [] points = numpy.array([[0.0, 0.01], [0.0, 1.0], [ 1.0, 0.0], [1.0, 1.0]]) util.splitN(points, 0, 0, 6, no2dN) tree2 = kdtree.createNewTree(no2dN) kdtree.visualize(tree2) label=0 for n in kdtree.level_order(tree2): self.assertIsNotNone(kdtree.getNode(tree2, label), "2: node with label: "+ str(label) + " not found in tree") label+=1 self.assertNotEqual(tree1, tree2, "trees have to be different")
def test_add_node_and_pickle_tree(self): print "-------------- test_pickle_tree ---------------" nodes = [] netDimension = 3 levels = 3 sequence = ["".join(seq) for seq in itertools.product("01", repeat=netDimension)] points_temp= numpy.array([list(s) for s in sequence]) points = numpy.array([map(float, f) for f in points_temp]) util.splitN(points, 0, 0, levels, nodes) tree = kdtree.createNewTree(nodes) for i in range(10): tree.split2([random.random(), random.random(), random.random()], axis=random.randint(0, netDimension-1)) points_tree = [(d.data, d.axis) for d in kdtree.level_order(tree) if d.data is not None] kdtree.visualize(tree) kdtree.save( tree, "save_tree_test.pkl" ) tree_loaded = kdtree.load("save_tree_test.pkl") points_tree_loaded = [(d.data, d.axis) for d in kdtree.level_order(tree_loaded) if d.data is not None] numpy.testing.assert_array_equal(points_tree, points_tree_loaded, "trees not equal?")
def test_compare_old_to_new_method_to_create_trees(self): """ tree created with old method should be equal to tree created with new method """ nodes = util.generate_sequence_of_points(2, 2) tree1 = kdtree.createNewTree(nodes) kdtree.visualize(tree1) sel_axis = (lambda axis: axis) tree2 = kdtree.createNewTree([[0.5, 0.5]],axis = 0, sel_axis= sel_axis) tree2.split2([0.25, 0.5], axis = 1) tree2.split2([0.75, 0.5], axis = 1) #left tree2.split2([0.25, 0.25], axis = 0, sel_axis = sel_axis) tree2.split2([0.25, 0.75], axis = 0, sel_axis = sel_axis) #right tree2.split2([0.75, 0.25], axis = 0, sel_axis = sel_axis) tree2.split2([0.75, 0.75], axis = 0, sel_axis = sel_axis) kdtree.visualize(tree2) for n in zip(kdtree.level_order(tree1), kdtree.level_order(tree2)): self.assertEqual(n[0].data, n[1].data, "elements not equal") if n[0].data is not None and n[1].data is not None: self.assertEqual(n[0].axis, n[1].axis, "elements not equal")
def test_create_tree_create_new_tree_with_data_from_first(self): nodes = [] netDimension = 2 levels = 3 sequence = ["".join(seq) for seq in itertools.product("01", repeat=netDimension)] points_temp= numpy.array([list(s) for s in sequence]) points = numpy.array([map(float, f) for f in points_temp]) util.splitN(points, 0, 0, levels, nodes) #print "nodes:", nodes tree = kdtree.createNewTree(nodes) # kdtree.visualize(tree) points_tree = [(d.data, d.axis) for d in kdtree.level_order(tree) if d.data is not None] points_tree_copy = list(points_tree) tree1 = kdtree.createNewTree([d[0] for d in points_tree]) # points_tree1 is changed # kdtree.visualize(tree1) points_tree2 = [(d.data, d.axis) for d in kdtree.level_order(tree1) if d.data is not None] numpy.testing.assert_array_equal(points_tree_copy, points_tree2, "trees not equal?")
def test_numberOfActiveStates(self): """only temporary, active property will disapear in future""" highestlevel = 4 numberOfStates= 2**(highestlevel+2)-1 no1dN = [] points = numpy.array([[0.0, 0.0], [0.0, 1.0], [ 1.0, 0.0], [1.0, 1.0]]) util.splitN(points, 0, 0, highestlevel, no1dN) tree = kdtree.createNewTree(no1dN) util.activate(tree, highestlevel+1) activeNodes = len([n for n in kdtree.level_order(tree) if n.active]) print "activeNodes: ", activeNodes, " numberOfStates: ", numberOfStates self.assertEqual(activeNodes, numberOfStates, "not the correct number of nodes active")
def walk(self, paint=False): """does one randomwalk with n_steps. saves the result to the classes list and returns it returns [distance, array([x,y,z])] """ X = zeros(self.dim, dtype=float) tree = kdtree.create([X]) for i in range(self.n_steps): successful = False while True: phi = rnd.random()*2*pi psi = rnd.random()*2*pi # for 2d set psi to 0 dX = array([sin(phi)*cos(psi), cos(phi), sin(phi)*sin(psi)]) * 2 X_new = X+dX #print dX, X_new #check if this new point is within the sphere of other if len(tree.search_nn_dist(X_new, 2*self.steplength)) == 0: X = X_new tree.add(X) tree = tree.rebalance() #print " accepted" break self.result_dist2.append(sum(X**2)) self.result_element.append(X) if paint: """This only makes sense if solving the 2d prob...""" circles = [] for i, p in enumerate(list(kdtree.level_order(tree))): circles.append(Circle(p.data, self.steplength)) fig=pylab.figure() ax=fig.add_subplot(111) colors = 100*pylab.rand(len(circles)) p = PatchCollection(circles, cmap=matplotlib.cm.jet, alpha=0.4) p.set_array(pylab.array(colors)) ax.add_collection(p) pylab.colorbar(p) pylab.show() return sum(X**2), X
def rrtree(lat, threshold): if lat is None or len(lat) == 0: return [] tree = kdtree.create(dimensions=2) distance_threshold = threshold # 8^2 for i,pt in enumerate(lat): t_pt = (float(pt[0]), float(pt[1])) search_result = tree.search_nn(t_pt, dist=euclid) if search_result is None: tree.add(t_pt) else: node, dist = search_result[0], search_result[1] if dist >= distance_threshold: tree.add(t_pt) filtered_points = [(int(pt.data[0]), int(pt.data[1])) for pt in kdtree.level_order(tree)] return filtered_points
def melt(state): steps_completed = state['steps_completed'] geo = state['geo'] points = state['points'] settings = state['settings'] MELT_INTERVAL = settings['MELT_INTERVAL'] MELT_PROBABILITY = settings['MELT_PROBABILITY'] INTERACTIVE_MODE = settings['INTERACTIVE_MODE'] # Melt stems from the bottom. none_count = 0 if len(points) != 0: for node in kdtree.level_order(geo): # Bug fix for empty root. if node.data is None: none_count += 1 assert none_count <= 1 break point_id = node.data.ident point = points[point_id] # Calculate the proper melt amount probabalistically. binom_melt_amount = np.random.binomial(MELT_INTERVAL, MELT_PROBABILITY) # There shouldn't be any stems that should have already been removed. assert points[point_id]['height'] >= 0 # Melt the stem and remove it if its height has decreased past zero. points[point_id]['height'] -= binom_melt_amount if points[point_id]['height'] < 0: geo = geo.remove(point['coord']) if INTERACTIVE_MODE: unvisualize_drop(point['artist']) return { 'points': points, 'geo': geo, 'steps_completed': steps_completed, 'settings': settings }
def public_entry(settings, output_file_name): # Define the initial state. state = { 'points': {}, 'geo': kdtree.create(dimensions=2), 'steps_completed': 0, 'settings': settings } visualize_init(settings) # Run the simulation. state = simulate_step(state, settings['DROP_COUNT']) geo = state['geo'] points = state['points'] # Collect all of the stems for later analysis. none_count = 0 stems = [] for node in kdtree.level_order(geo): # Bug fix for empty root. if node.data is None: none_count += 1 assert none_count <= 1 break assert node is not None point_id = node.data.ident point = points[point_id] stems.append({'coord': point['coord'], 'height': point['height']}) #print('Number of stems: ', len(stems), file=sys.stderr) #print('Number of points: ', len(points), file=sys.stderr) # Output the relevant parts of the state. _state = {'settings': settings, 'stems': stems} with open(output_file_name, 'w') as output_file: output_file.write(json.dumps(_state))
def draw_tree(self): scale_factor = 20 image_big = self.image.resize((self.map.shape[0] * scale_factor, self.map.shape[1] * scale_factor), Image.ANTIALIAS).convert('RGB') draw = ImageDraw.Draw(image_big) for col in range(0, self.map.shape[0]): draw.line([(col * scale_factor, 0), (col * scale_factor, self.map.shape[1] * scale_factor)], (0, 0, 0)) for row in range(0, self.map.shape[1]): draw.line([(0, row * scale_factor), (self.map.shape[0] * scale_factor, row * scale_factor)], (0, 0, 0)) for kdnode in kdtree.level_order(self.nodes_start_tree): node = kdnode.data if node.parent is not None: draw.line([(node[0] * scale_factor, node[1] * scale_factor), (node.parent[0] * scale_factor, node.parent[1] * scale_factor)], (255, 0, 255)) draw.ellipse( [(node[0] * scale_factor - 2, node[1] * scale_factor - 2), (node[0] * scale_factor + 2, node[1] * scale_factor + 2)], fill=(255, 0, 255), outline=(255, 0, 255)) else: draw.ellipse( [(node[0] * scale_factor - 2, node[1] * scale_factor - 2), (node[0] * scale_factor + 2, node[1] * scale_factor + 2)], fill=(0, 255, 0), outline=(0, 255, 0)) for kdnode in kdtree.level_order(self.nodes_goal_tree): node = kdnode.data if node.parent is not None: draw.line([(node[0] * scale_factor, node[1] * scale_factor), (node.parent[0] * scale_factor, node.parent[1] * scale_factor)], (0, 0, 255)) draw.ellipse( [(node[0] * scale_factor - 2, node[1] * scale_factor - 2), (node[0] * scale_factor + 2, node[1] * scale_factor + 2)], fill=(0, 0, 255), outline=(0, 0, 255)) else: draw.ellipse( [(node[0] * scale_factor - 2, node[1] * scale_factor - 2), (node[0] * scale_factor + 2, node[1] * scale_factor + 2)], fill=(0, 255, 255), outline=(0, 255, 255)) for i in range(0, len(self.path_total) - 1): draw.line([(self.path_total[i][0] * scale_factor, self.path_total[i][1] * scale_factor), (self.path_total[i + 1][0] * scale_factor, self.path_total[i + 1][1] * scale_factor)], (255, 0, 0)) for point in self.samples: draw.ellipse( [(point[0] * scale_factor - 1, point[1] * scale_factor - 1), (point[0] * scale_factor + 1, point[1] * scale_factor + 1)], fill=(255, 0, 0), outline=(255, 0, 0)) del draw image_big.save("test.png")
tree = kdtree.create([point1, point2, point3]) # Each (sub)tree is represented by its root node print(tree) # Adds a tuple to the tree tree.add( (5, 4, 3) ) # Removes the previously added point and returns the new root tree = tree.remove( (5, 4, 3) ) # Retrieving the Tree in inorder print(list(tree.inorder())) # Retrieving the Tree in level order print(list(kdtree.level_order(tree))) # Find the nearest node to the location (1, 2, 3) tree.search_nn( (1, 2, 3) ) # Add a point to make the tree more interesting tree.add( (10, 2, 1) ) # Visualize the Tree kdtree.visualize(tree) # Take the right subtree of the root subtree = tree.right # and detatch it tree.right = None
y.append(int(row[1])) points = [] for i in range(len(x)): points.append([x[i],y[i]]) kd_tree = kd.create(points) #kd.visualize(kd_tree) print(len(kd_tree.data)) #print(type(kd_tree)) level_list = list(kd.level_order(kd_tree)) data = [] #for i in range(len(level_list)): # data.append(level_list[i].data) #print(data) #print(type(empty_tree.left)) def plt_tree(kd_tree,min_x,max_x,min_y,max_y,prv_node,branch, depth = 0): current = kd_tree.data left_sub = kd_tree.left right_sub = kd_tree.right if kd_tree.data is None:
def visualize_state(state): global last_fast_draw_artists for artist in last_fast_draw_artists: artist.remove() last_fast_draw_artists = [] points = state['points'] geo = state['geo'] settings = state['settings'] fig = plt.gcf() ax = plt.gca() if settings['PLANE_SHAPE'] == DISK: border = plt.Circle((0, 0), radius=1, fill=False) ax.add_artist(border) last_fast_draw_artists.append(border) elif settings['PLANE_SHAPE'] == SQUARE: border = matplotlib.patches.Rectangle((-1, -1), 2, 2, fill=False) ax.add_patch(border) last_fast_draw_artists.append(border) height_max = None for point_id in points: point = points[point_id] height = point['height'] if height_max is None or height > height_max: height_max = height none_count = 0 for node in kdtree.level_order(geo): # Bug fix for empty root. if node.data is None: none_count += 1 assert none_count <= 1 break assert node is not None point_id = node.data.ident point = points[point_id] coord = point['coord'] height = point['height'] if height < 0.5 * height_max: continue color = (height / (height_max + 1)) drop_artist = plt.Circle((coord[0], coord[1]), radius=settings['DROP_RADIUS'], fill=True, color=(color, 0, 0, 1)) ax.add_artist(drop_artist) last_fast_draw_artists.append(drop_artist) if settings['SHOW_BOUNCE_RADIUS']: bounce_artist_outer = plt.Circle( (coord[0], coord[1]), radius=settings['BOUNCE_DISTANCE'] + settings['DROP_RADIUS'], fill=False, color=(color, 0, 0, 1)) bounce_artist_inner = plt.Circle( (coord[0], coord[1]), radius=settings['BOUNCE_DISTANCE'] - settings['DROP_RADIUS'], fill=False, color=(color, 0, 0, 1)) ax.add_artist(bounce_artist_outer) ax.add_artist(bounce_artist_inner) plt.draw() #plt.savefig("gallery1/{}.png".format(state['steps_completed'])) plt.pause(settings['INTERACTIVE_DELAY'])