Example #1
0
def create_tree(nodes, edges):
    outTree = Tree()
    for node in nodes:
        outTree.add_node(node)
    for edge in edges:
        outTree.add_edge(edge)
    return outTree
Example #2
0
    def add_node(self, name=None, id=None, flag=0, expanded_icon=None,
                 collapsed_icon=None, selected=False, expanded=False,
                 full_parent_id=()):
        """overridden method (Tree)"""
        Tree.add_node(self, name, id, flag, expanded_icon, collapsed_icon)

        fullParentPath = self.separater.join(full_parent_id)

        if fullParentPath not in self.savedNodesMap.keys():
            self.savedNodesMap[fullParentPath] = []

        savedNode = self._getSavedNode(fullParentPath, name)
        if savedNode is not None:
            self.new_nodes[-1].selected = savedNode.selected
            self.new_nodes[-1].expanded = savedNode.expanded

            return

        savedParentNode = self._getSavedNode(self.separater.join(full_parent_id[0:len(full_parent_id) - 1]), full_parent_id[-1])

        node = Struct()
        node.name = name
        node.expandable = flag
        node.fullPath = self.separater.join(full_parent_id + (id,))
        node.expanded = expanded
        node.selected = savedParentNode.selected

        self.savedNodesMap[fullParentPath].append(node)

        self.new_nodes[-1].selected = node.selected
        self.new_nodes[-1].expanded = node.expanded
Example #3
0
def main():
    tree = Tree()
    tree.add_node_root(96)
    tree.add_node(88, 'Figlio-3')
    tree.add_node(6, 'Figlio-1')
    tree.add_node(100, 'Figlio-2')

    #Test methods
    print('\n########\n')
    print(tree.add_node(None, 'Figlio-2'))
    print(tree.add_node(111, None))
    print('\n########\n')
    print(tree.search_node(6))
    print('\n########\n')
    print(tree.tree_min(96))
    print('\n########\n')
    print(tree.tree_max(96))
    print('\n########\n')
    print(tree.tree_successor(96))
    print(tree.tree_predecessor(88))
    tree.view_tree()
    print('\n########\n')
    tree.delete_node(88)
    print('\n########\n')
    tree.view_tree()
    print('\n#### END ####\n')
    tree.view_tree_info()
Example #4
0
def RRT_general(environment,
                robot,
                start,
                goal,
                rrt_step_size,
                link_step_size,
                sampling,
                maximum_clear_calls=np.inf):
    """
    Motion plan using a Rapidly-exploring Random Tree strategy.

    :param environment: Environment to motion plan in
    :param robot: Robot to plan motion for
    :param start: Starting robot configuration
    :param goal: Goal robot configuration
    :param rrt_step_size: Step size for RRT growth
    :param link_step_size: Step size for LINK computation
    :param sampling: SamplingRegion for RRT growth
    :param maximum_clear_calls: Timeout for query to fail
    :return: final tree, elapsed time
    """

    done = False
    environment.num_clear_calls = 0
    tree = Tree(start, goal)
    robot_next = robot.copy()
    start_time = time()

    while not done and environment.num_clear_calls < maximum_clear_calls:
        q_rand = sampling.random_configuration()
        q_near = tree.closest_node(q_rand)
        new_configuration = q_rand.configuration

        if q_near.dist(q_rand) > rrt_step_size:
            direction = q_rand.configuration - q_near.configuration
            direction /= np.linalg.norm(direction)
            new_configuration = q_near.configuration + rrt_step_size * direction

        robot.move(*q_near.configuration)
        robot_next.move(*new_configuration)
        if environment.link(robot, robot_next, link_step_size):
            new_node = Node(new_configuration, parent=q_near)
            tree.add_node(new_node)

            if new_node.dist(tree.goal) < rrt_step_size:  # TODO: and LINK?
                tree.goal.parent = new_node
                tree.add_node(tree.goal)
                done = True

    return tree, time() - start_time
Example #5
0
def run_prims(graph, vertex):
    """
    TODO
    Run Prim's Algorithm to create a minimum spanning tree
    fram a weighted graph structure
    :param graph: populated WeightedGraph object
    :param vertex: vertex existing withing the WeightedGraph object
    :return: Tree Object representing the MSP of the WeightedGraph
    """
    # reset all the traversed flags
    for vertex in graph._vertices:
        vertex.traversed = False
    # setup result tree and add parent node
    t = Tree()
    t.add_node(None, vertex)
    vertex.traversed = True
    connected_edges = graph.get_outgoing_edges(vertex)
    # Greedily go find the next smallest edge until there is no edges left
    while len(connected_edges) > 0:
        #print("-----------")
        #for item in connected_edges:
        #    print(item)
        #    print(item.connectedVertex.traversed)
        smallest_dist = float("inf")
        smallest_edge = None
        # Find the next smallest un-traversed vertex
        for edge in connected_edges:
            if edge.connectedVertex.traversed is False and edge.distance < smallest_dist:
                smallest_dist = edge.distance
                smallest_edge = edge
        connected_edges.remove(smallest_edge)
        smallest_edge.connectedVertex.traversed = True
        # Update the connected edges set to include edges from the newly added vertex
        connected_edges = connected_edges | graph.get_outgoing_edges(
            smallest_edge.connectedVertex)  # set union
        t.add_node(smallest_edge.sourceVertex, smallest_edge.connectedVertex)
        # Remove other edges that end at the next smallest vertex.
        remove_set = set()
        for edge in connected_edges:
            if edge.connectedVertex.traversed is True:
                remove_set.add(edge)
        connected_edges = connected_edges - remove_set  # set difference
    return t
Example #6
0
 def _initialize_tree(self, edges=None, nodes=None):
     # Create Tree object
     tree = Tree()
     # add nodes to the tree
     if nodes:
         tree.add_nodes(nodes)
     else:
         for cluster_id, cluster in self._clustering_results.clusters.items(
         ):
             tree.add_node(cluster.identifier, data=cluster.densities)
         # TODO find clonal cluster and set it as a root
         root = tree.nodes[CLONAL_CLUSTER]
         tree.set_root(root)
     if edges:
         tree.add_edges(edges)
     else:
         # add edges (initially all edges are children of Clonal cluster)
         for identifier, node in tree.nodes.items():
             if identifier != CLONAL_CLUSTER:
                 tree.add_edge(root, node)
     logging.debug('Tree initialized with edges {}'.format(tree.edges))
     return tree
Example #7
0
import sys
from Tree import Tree
from PartialReplication import PartialReplication

if __name__ == "__main__":
    tree = Tree()

    if len(sys.argv) == 2:
        fp = open(sys.argv[1])
        for line in fp:
            line = line.strip()
            if len(line) > 0:
                line_split = line.split(':')
                data = line_split[0]
                if line_split[0] == "Node":
                    tree.add_node(line_split[1], line_split[2])
                elif line_split[0] == "DataItem":
                    tree.add_data(int(line_split[1]), line_split[2], line_split[3])
                elif line_split[0] == "ReplicationLevel":
                    tree.set_replication_level(int(line_split[1]))
        tree.complete()
        pr = PartialReplication(tree)
        pr.generate_broadcast()
    else:
        print "Usage: python main.py <input file>"
Example #8
0
    def _addFromSavedNode(self, savedNode):
        """Adds the node to new_nodes list from the savedNodesMap structure"""
        Tree.add_node(self, savedNode.name, savedNode.name, savedNode.expandable, None, None)

        self.new_nodes[-1].selected = savedNode.selected
        self.new_nodes[-1].expanded = savedNode.expanded
Example #9
0
def DRRRT(environment,
          robot,
          start_configuration,
          goal_configuration,
          rrt_step_size,
          link_step_size,
          reeb_graph,
          start_node,
          goal_node,
          region_failure_threshold=np.inf,
          maximum_clear_calls=np.inf):
    """
    Motion plan using a Dynamic Region-biased Rapidly-exploring Random Tree strategy.

    :param environment: Environment to motion plan in
    :param robot: Robot to plan motion for
    :param start_configuration: Starting robot configuration
    :param goal_configuration: Goal robot configuration
    :param rrt_step_size: Step size for RRT growth
    :param link_step_size: Step size for LINK computation
    :param reeb_graph: ReebGraph for RRT growth
    :param start_node: Start node of reeb graph
    :param goal_node: Goal node of reeb graph
    :param region_failure_threshold: Maximum number of failed queries before removing a region
    :param maximum_clear_calls: Timeout for query to fail
    :return: final tree, elapsed time
    """

    # Sampling regions and the graph edges they are traversing
    regions = []
    seen_edges = set()
    targets_hit = set()

    def add_regions_at_node(node):
        for neighbor in reeb_graph.out_neighbors[node]:
            if (node, neighbor) not in seen_edges and (neighbor,
                                                       node) not in seen_edges:
                new_region = DRRRTRegion(node, neighbor, rrt_step_size)
                new_region.advance_region_distance(rrt_step_size)
                regions.append(new_region)
                seen_edges.add((node, neighbor))

        for i in reversed(range(len(regions))):
            if regions[i].target in targets_hit:
                del regions[i]

    done = False
    environment.num_clear_calls = 0
    tree = Tree(start_configuration, goal_configuration)
    add_regions_at_node(start_node)
    robot_next = robot.copy()
    start_time = time()

    while not done and environment.num_clear_calls < maximum_clear_calls:
        region = choice(regions)
        q_rand = region.random_configuration()
        q_near = tree.closest_node(q_rand)
        new_configuration = q_rand.configuration

        if q_near.dist(q_rand) > rrt_step_size:
            direction = q_rand.configuration - q_near.configuration
            direction /= np.linalg.norm(direction)
            new_configuration = q_near.configuration + rrt_step_size * direction

        robot.move(*q_near.configuration)
        robot_next.move(*new_configuration)
        if environment.link(robot, robot_next, link_step_size):
            new_node = Node(new_configuration, parent=q_near)
            tree.add_node(new_node)

            if new_node.dist(tree.goal) < rrt_step_size:  # TODO: and LINK?
                tree.goal.parent = new_node
                tree.add_node(tree.goal)
                done = True

            region.advance_region_beyond(new_node, link_step_size)
            region.failures = 0

            if region.target_hit:
                if region.target is not goal_node:
                    regions.remove(region)
                    add_regions_at_node(region.target)
                    targets_hit.add(region.target)

            # plt.close()
            # for region in regions:
            #     region.region.draw('green')
            # reeb_graph.draw('black')
            # draw_full_tree(environment, robot, start_configuration, goal_configuration, tree, title='')
            # plt.savefig("tree{}.pdf".format(len(tree)))
        else:
            region.failures += 1
            if region.failures > region_failure_threshold:
                regions.remove(region)

    return tree, time() - start_time
Example #10
0
def parse():
  tree = Tree()
  project_home = dirname(sys.path[0])
  # while project_home.split('/')[-1] != 'AdaptiveCAP':
  #   project_home = dirname(project_home)
  # print ('project_home', project_home)

  log_path = os.path.join(project_home, _LOG_FILE)
  print ('log_path', log_path)

  with open(log_path, 'r') as fp:
    lines = fp.readlines()
    print "heyhehheehheheyeyeyeyeyeyyeyeyyyyyyyyy"
  print "file is accessed"
  interested = False
  hello_sent_from = -1  # new parent
  hello_sent_to = -1  # node which will move

  for line in lines:
    # TODO: start at timestamp/ automatically run afterclustering

    if not line:
      continue

    last_part = line.split('-')[-1].strip()
    if last_part == 'Starting Server':
      node_id = line.split('-')[-2].split(':')[-1].strip()

      if node_id in SPANNING_INFO:
        parent = SPANNING_INFO[node_id]['parentId']
      else:
        parent = None
      if parent:
        parent = int(parent)
      node_id = int(node_id)
      tree.add_node(node=node_id, parent=parent)

      sleep(_DELAY)
      draw(tree.data)

      if _PARSE_LOGS_DEBUG:
        print 'Starting Server'
        print ('node_id', node_id)
        print ('parent', parent)
        pp.pprint(tree.data)
        print "\n"

    elif last_part == 'Got Prune':
      node_id = line.split('-')[-2].split(':')[-1].strip()
      tree.prune(node_id)
      sleep(_DELAY)
      draw(tree.data)
      if _PARSE_LOGS_DEBUG:
        print 'Got Prune'
        pp.pprint(tree.data)
        print "\n"

    elif last_part == 'Got Response: interested: 1':
      interested = True
      hello_sent_from = line.split('-')[-2].split(':')[-1].strip()

    elif interested:
      interested = False
      hello_sent_to = line.split(':')[-1].strip()
      new_parent = int(hello_sent_from)
      to_move = int(hello_sent_to)
      tree.prune(node=to_move, new_parent=new_parent)
      sleep(_DELAY)
      draw(tree.data)
      if _PARSE_LOGS_DEBUG:
        print 'Got Response: interested: 1'
        print "moving Node {to_move} to Node {new_parent}".format(
          to_move=to_move, new_parent=new_parent)
        pp.pprint(tree.data)
        print '\n'
Example #11
0
from Tree import Tree

tree = Tree()
tree.add_node(5)
tree.add_node(3)
tree.add_node(4)
tree.add_node(8)
tree.add_node(14)
tree.add_node(5)
tree.add_node(6)
tree.add_node(1)
tree.add_node(2)

tree.print_tree()
print(tree.find_common(2, 4).value)