예제 #1
0
def detach_and_rebuild(root, node_to_detach):
    
    node_to_detach.parent = None
    if len(node_to_detach.children) > 0:
        for pre, fill, node in tree.RenderTree(root):
            if node != node_to_detach and len(node.children) < 2:
                node_to_detach.children[0].parent = node
                break
        if len(node_to_detach.children) > 0:
            for pre, fill, node in tree.RenderTree(root):
                if node != node_to_detach and len(node.children) < 2:
                    node_to_detach.children[0].parent = node
                    break
    
    node_to_detach.parent = None

    print("pre balance \n\n")

    for pre, fill, node in tree.RenderTree(root):
            print(pre, node.name, node.data)

    balance_tree(root)

    print("pos balance \n\n")

    for pre, fill, node in tree.RenderTree(root):
            print(pre, node.name, node.data)
 def minimax(self, gameTree, maxFirst=True, show=False):
     """ Function to recursively calculate the minimaxed value of an 
     anytree.Node object based on it's descendants. The leaves are expected 
     to have keyword argument "value" which is the parameter to be
     minimaxed.
     maxFirst=True by default, means the root node will be maximised across
     minimised children (and alternate each layer in the tree). 
     maxFirst = False will instead minimise across maximised children
     (and alternate each layer in the tree).
     """
     if type(gameTree) is not at.Node:
         raise TypeError("argument not an anytree.Node object")
     if show:
         print("Input Tree:")
         print(at.RenderTree(gameTree))
     if maxFirst:
         self._maximin(gameTree)
         if show:
             print("Minimaxed Tree:")
             print(at.RenderTree(gameTree))
         return gameTree
     else:
         self._minimax(gameTree)
         if show:
             print("Minimaxed Tree:")
             print(at.RenderTree(gameTree))
         return gameTree
예제 #3
0
def test_render_str():
    """Render string cast."""
    root = anytree.Node("root")
    s0 = anytree.Node("sub0", parent=root)
    anytree.Node("sub0B", parent=s0)
    anytree.Node("sub0A", parent=s0)
    anytree.Node("sub1", parent=root)
    r = anytree.RenderTree(root)

    expected = u"\n".join([
        u"Node('/root')",
        u"├── Node('/root/sub0')",
        u"│   ├── Node('/root/sub0/sub0B')",
        u"│   └── Node('/root/sub0/sub0A')",
        u"└── Node('/root/sub1')",
    ])
    eq_str(str(r), expected)

    r = anytree.RenderTree(
        root, childiter=lambda nodes: [n for n in nodes if len(n.name) < 5])

    expected = u"\n".join([
        u"Node('/root')",
        u"├── Node('/root/sub0')",
        u"└── Node('/root/sub1')",
    ])
    eq_str(str(r), expected)
예제 #4
0
def test_by_attr():
    """by attr."""
    root = anytree.Node("root", lines=["root"])
    s0 = anytree.Node("sub0", parent=root, lines=["su", "b0"])
    anytree.Node("sub0B", parent=s0, lines=["sub", "0B"])
    anytree.Node("sub0A", parent=s0)
    anytree.Node("sub1", parent=root, lines=["sub1"])
    eq_(anytree.RenderTree(root).by_attr(),
        u"root\n├── sub0\n│   ├── sub0B\n│   └── sub0A\n└── sub1")
    eq_(anytree.RenderTree(root).by_attr("lines"),
        u"root\n├── su\n│   b0\n│   ├── sub\n│   │   0B\n│   └── \n└── sub1")
예제 #5
0
    def print(self, ascii_=False, call_log=False):
        def _format_node(node):
            return str(node.name) + (' (X) ' if node.id_ in call_log else '')

        style = anytree.render.AsciiStyle(
        ) if ascii_ else anytree.render.ContStyle()

        if not call_log:
            print(anytree.RenderTree(self, style=style).by_attr())
        else:
            print(anytree.RenderTree(self, style=style).by_attr(_format_node))
예제 #6
0
def render_tree(opts, tree):
    """Render tree in ASCII and graphviz"""
    with codecs.open(
            f"{opts.output_dir}/{constants.FEATURE_IMPORTANCE_HIERARCHY}.txt",
            "w",
            encoding="utf8") as txt_file:
        for pre, _, node in anytree.RenderTree(tree):
            txt_file.write("%s%s: %s (%s: %s)\n" %
                           (pre, node.name, node.description.title(),
                            opts.effect_name, str(node.effect_size)))
    graph_options = [
    ]  # Example: graph_options = ["dpi=300.0;", "style=filled;", "bgcolor=yellow;"]
    exporter = DotExporter(tree,
                           options=graph_options,
                           nodeattrfunc=lambda node: nodeattrfunc(opts, node))
    exporter.to_dotfile(
        f"{opts.output_dir}/{constants.FEATURE_IMPORTANCE_HIERARCHY}.dot")
    try:
        output_filename = f"{opts.output_dir}/{constants.FEATURE_IMPORTANCE_HIERARCHY}.png"
        exporter.to_picture(output_filename)
        print(f"Feature importance visualization: {output_filename}")
    except FileNotFoundError:
        print(
            "Feature importance visualization: error during tree rendering. Is Graphviz installed on your system?"
        )
예제 #7
0
 def show(self):
     for pre, fill, node in anytree.RenderTree(self._root):
         if node.is_leaf:
             print("%s|%s*****%s" % (pre, node.name, 0))
         else:
             print("%s|%s*****%s" %
                   (pre, node.name, node.name.get_middle_border()))
예제 #8
0
 def show_tasks(self):
     for pre, fill, task in anytree.RenderTree(self.task_tree):
         if task.name == 'ProjectFlow':
             L.info(pre + task.name)
         else:
             L.info(pre + task.name + ', running: ' + str(task.run) +
                    ', overwriting: ' + str(task.skip_existing))
예제 #9
0
 def _to_csv(self, node, with_header=False):
     '''print the tree to csv'''
     rend = anytree.RenderTree(node, childiter=self._sort_tree)
     if with_header:
         Logger.out(self.CSV_HEADER)
     for _, _, node in rend:
         self._node_to_csv(node)
예제 #10
0
def render(tree):
    """
    Renders a given tree structure in console.
    """
    for pre, _, node in t.RenderTree(tree):
        print("%s%s (%s)" %
              (pre, node.name, node.id if hasattr(node, 'id') else ''))
예제 #11
0
    def get_gate_hierarchy(self, output='ascii', **kwargs):
        """
        Retrieve the hierarchy of gates in the gating strategy in several formats, including text,
        dictionary, or JSON. If output == 'json', extra keyword arguments are passed to json.dumps

        :param output: Determines format of hierarchy returned, either 'ascii',
            'dict', or 'JSON' (default is 'ascii')
        :return: gate hierarchy as a text string or a dictionary
        """
        if output == 'ascii':
            tree = anytree.RenderTree(self._gate_tree,
                                      style=anytree.render.ContRoundStyle())
            lines = []

            for row in tree:
                lines.append("%s%s" % (row.pre, row.node.name))

            return "\n".join(lines)
        elif output == 'json':
            dict_exporter = anytree.exporter.DictExporter(
                attriter=lambda attrs: [(k, v) for k, v in attrs
                                        if k != 'gate'])

            gs_dict = dict_exporter.export(self._gate_tree)
            gs_json = json.dumps(gs_dict, **kwargs)

            return gs_json
        elif output == 'dict':
            exporter = anytree.exporter.DictExporter()
            gs_dict = exporter.export(self._gate_tree)

            return gs_dict
        else:
            raise ValueError(
                "'output' must be either 'ascii', 'json', or 'dict'")
예제 #12
0
    def print_population_tree(self,
                              image: bool = False,
                              path: str or None = None):
        """
        Print population tree to stdout or save as an image if 'image' is True.

        Parameters
        ----------
        image: bool (default=False)
            Save tree as a png image
        path: str (optional)
            File path for image, ignored if 'image' is False.
            Defaults to working directory.

        Returns
        -------
        None
        """
        root = self.tree['root']
        if image:
            from anytree.exporter import DotExporter
            path = path or f'{os.getcwd()}/{self.id}_population_tree.png'
            DotExporter(root).to_picture(path)
        for pre, fill, node in anytree.RenderTree(root):
            print('%s%s' % (pre, node.name))
예제 #13
0
 def __str__(self):
     """
     Print the complete tree beginning at this node.
     """
     if HAVE_ANYTREE:
         return str(anytree.RenderTree(self))
     return self.__class__
예제 #14
0
def processJSON(title="SML Lec 1_2.txt"):
    """
    Function to process JSON from Azure video indexer
    """
    # OPEN AND LOAD JSON INTO DICTIONARY
    with open(title, "r") as _file:
        new_dic = json.load(_file)
    insights = new_dic["summarizedInsights"]

    # GET ALL DICTIONARY KEYS FOR JSON
    keys = []
    for key, value in insights.items():
        keys.append(key)

    # print(keys)

    # GET ALL KEYWORDS
    keywords = []
    for k in insights["keywords"]:
        keywords.append(k["name"])

    print('Keywords: ', keywords, '\n')

    # GET ALL TOPICS
    topics = []
    for t in insights["topics"]:
        if len(topics) == 0 or topics[-1] != t["name"]:
            topics.append(t["name"])

    print('Topics: ', topics, '\n')

    if '.txt' in title:
        title = title[:-4]
    top = treeify(topics, title)
    print(anytree.RenderTree(top, style=anytree.render.ContStyle()).by_attr())
예제 #15
0
    def _build_group_tree(self, timestamp):
        """Build a tree of all the groups in the organization.

        Args:
            timestamp: String of snapshot timestamp, formatted as
                YYYYMMDDTHHMMSSZ.

        Returns:
            The root node that holds the tree structure of all the groups
                in the organization.
        """
        root = MemberNode(MY_CUSTOMER, MY_CUSTOMER)

        all_groups = self.dao.get_all_groups('groups', timestamp)
        for group in all_groups:
            group_node = MemberNode(group.get('group_id'),
                                    group.get('group_email'), 'group',
                                    'ACTIVE', root)
            group_node = self.get_recursive_members(group_node, timestamp)

        LOGGER.debug(
            anytree.RenderTree(
                root, style=anytree.AsciiStyle()).by_attr('member_email'))

        return root
def printNodeTree(start_node, t_speeds, debug):
    '''
    Print out a right angle tree of the generated state space.
    '''
    for pre, fill, node in tree.RenderTree(start_node):
        print(
            "{pre}ID:{id} Parent:{stateparent} Depth: {depth} Time: {start}\n\
        {pre} RunningT: {task_run}\n\
        {pre} RunningP: {proc_run}\n\
        {pre} End time: {ends}\n\
        {pre} Waitlist: {waitlist}\n\
        {pre} Procs Avail: {proc_avail}\n\
        {pre} Tasks Done: {task_done}\n\
        {pre} Value: {val}\n".format(pre=pre,
                                     id=node.name,
                                     parent=node.parent,
                                     waitlist=node.value[0],
                                     task_run=node.value[1],
                                     proc_run=node.value[2],
                                     task_done=node.value[3],
                                     proc_avail=node.value[4],
                                     start=node.value[5],
                                     depth=node.value[6],
                                     stateparent=node.value[7],
                                     val=states.getValue(
                                         node.value, t_speeds, debug),
                                     ends=node.value[10],
                                     stateid=node.value[9]))
 def updateTerminalNodes(self):
     text = list()
     for pre, fill, node in anytree.RenderTree(self.displayTree):
         if node.is_leaf:
             text.append(' : '.join([node.parent.name, node.name]))
     text = '\n'.join(text)
     self.terminalNodesLabel.setText(text)
예제 #18
0
    def __init__(self,
                 dpt_ip_address=None,
                 dpt_serial_number=None,
                 dpt_key=None,
                 dpt_client_id=None,
                 uid=None,
                 gid=None):
        self.dpt_ip_address = dpt_ip_address
        self.dpt_serial_number = dpt_serial_number
        self.dpt_key = os.path.expanduser(dpt_key)
        self.dpt_client_id = os.path.expanduser(dpt_client_id)
        self.uid = uid
        self.gid = gid
        self.__authenticate__()

        # Create root node
        self.__init_empty_tree()

        # Cache this for the session
        logger.info('Loading initial document list')
        self._load_document_list()
        logger.debug(anytree.RenderTree(self.root))

        self.documents_data = {}
        self.documents_fds = {}
        self.files = {}
        self.fd = 0
예제 #19
0
def render_tree(args, tree):
    """Render tree in ASCII and graphviz"""
    with codecs.open("{0}/{1}.txt".format(args.output_dir, constants.TREE),
                     "w",
                     encoding="utf8") as txt_file:
        for pre, _, node in anytree.RenderTree(tree):
            txt_file.write("%s%s: %s (%s: %s)\n" %
                           (pre, node.name, node.description.title(),
                            args.effect_name, str(node.effect_size)))
    graph_options = [
    ]  # Example: graph_options = ["dpi=300.0;", "style=filled;", "bgcolor=yellow;"]
    DotExporter(tree,
                options=graph_options,
                nodeattrfunc=lambda node: nodeattrfunc(args, node)).to_dotfile(
                    "{0}/{1}.dot".format(args.output_dir, constants.TREE))
    try:
        DotExporter(
            tree,
            options=graph_options,
            nodeattrfunc=lambda node: nodeattrfunc(args, node)).to_picture(
                "{0}/{1}.png".format(args.output_dir, constants.TREE))
    except FileNotFoundError:
        raise FileNotFoundError(
            "Error during tree rendering - is Graphviz installed on your system?\n"
        )
예제 #20
0
    def get_gate_hierarchy(self, output='ascii'):
        """
        Show hierarchy of gates in multiple formats, including text,
        dictionary, or JSON,

        :param output: Determines format of hierarchy returned, either 'text',
            'dict', or 'JSON' (default is 'text')
        :return: either a text string or a dictionary
        """
        root = self._build_hierarchy_tree()

        tree = anytree.RenderTree(root, style=anytree.render.ContRoundStyle())

        if output == 'ascii':
            lines = []

            for row in tree:
                lines.append("%s%s" % (row.pre, row.node.name))

            return "\n".join(lines)
        elif output == 'json':
            exporter = anytree.exporter.JsonExporter()
            gs_json = exporter.export(root)

            return gs_json
        elif output == 'dict':
            exporter = anytree.exporter.DictExporter()
            gs_dict = exporter.export(root)

            return gs_dict
        else:
            raise ValueError(
                "'output' must be either 'ascii', 'json', or 'dict'")
예제 #21
0
def test_by_attr():
    """by attr."""
    root = anytree.Node("root", lines=["root"])
    s0 = anytree.Node("sub0", parent=root, lines=["su", "b0"])
    anytree.Node("sub0B", parent=s0, lines=["sub", "0B"])
    anytree.Node("sub0A", parent=s0)
    anytree.Node("sub1", parent=root, lines=["sub1"])
    eq_(
        anytree.RenderTree(root).by_attr(),
        u"root\n├── sub0\n│   ├── sub0B\n│   └── sub0A\n└── sub1")
    eq_(
        anytree.RenderTree(root).by_attr("lines"),
        u"root\n├── su\n│   b0\n│   ├── sub\n│   │   0B\n│   └── \n└── sub1")
    eq_(
        anytree.RenderTree(root).by_attr(lambda node: ":".join(node.name)),
        u"r:o:o:t\n├── s:u:b:0\n│   ├── s:u:b:0:B\n│   └── s:u:b:0:A\n└── s:u:b:1"
    )
예제 #22
0
def get_max_depth(root):
    max = 0
    maxnode = None
    for pre, fill, node in tree.RenderTree(root):
        if node.depth > max:
            max = node.depth
            maxnode = node
    return max, maxnode
예제 #23
0
def get_min_av(root):
    min = 9999
    av = None
    for pre, fill, node in tree.RenderTree(root):
        if node.depth < min and len(node.children) < 1:
            av = node
            min = node.depth

    return min, av
예제 #24
0
 def render(self):  # pragma: no cover
     """print out a visual representation of the tree (this node and its
     children)
     """
     for pre, _, node in anytree.RenderTree(self):
         if isinstance(node, pybamm.Scalar) and node.name != str(node.value):
             print("{}{} = {}".format(pre, node.name, node.value))
         else:
             print("{}{}".format(pre, node.name))
예제 #25
0
def generate_wcs_diagram(conversation_username: str = None,
                         conversation_password: str = None,
                         version: str = None,
                         workspace: str = None) -> str:
    """ generates a compact, text represation of a WCS instance.
    ex:

    root
    ├── welcome
    ├── 1 (jumps to: 3)
    ├── 2
    │   ├── 2_1
    │   └── 2_2
    ├── 3
    │   ├── 3_1
    │   ├── 3_2
    │   └── 3_3
    └── Anything else

    parameters:
    conversation_username: WCS instance username
    conversation_password: WCS instance password
    version: WCS API version
    workspace: WCS instance workspace

    returns:
    projection: a string representation of the WCS workspace
    """

    export = get_and_backup_workspace(username=conversation_username,
                                      password=conversation_password,
                                      version=version,
                                      workspace=workspace,
                                      export_path=None)

    # build tree roots
    root = anytree.AnyNode(id=None, title=None, desc='root')

    # build our trees
    _build_tree(export['dialog_nodes'], root)

    # for rendering, let's update the desc fields with titles of the jump
    nodes_with_jumps = anytree.search.findall(root,
                                              filter_=_get_nodes_with_jump)

    # update the descriptions
    for node in nodes_with_jumps:
        dest = _get_all_matches(root, node.node['next_step']['dialog_node'])
        if len(dest) == 1:
            node.desc = node.desc + ' (jumps to: {})'.format(dest[0].desc)

    # projected rendering of tree
    projected = anytree.RenderTree(
        root, childiter=_sort_child_nodes).by_attr(attrname='desc')

    return projected
예제 #26
0
 def print_hie(self):
     """
     Print out some info about a SB, in a hierarchical fashion.
     """
     out = ""
     for pre, _, node in at.RenderTree(self):
         # Only the SB name is printed
         treestr = "  {0}{1}\n".format(pre, node.name)
         out += treestr
     return (out)
예제 #27
0
def tree_repr(tree: DataTree) -> str:
    renderer = anytree.RenderTree(tree)
    lines = []
    for pre, _, node in renderer:
        if node.has_data or node.has_attrs:
            node_repr = _single_node_repr(node)

            node_line = f"{pre}{node_repr.splitlines()[0]}"
            lines.append(node_line)
    return "\n".join(lines)
    def _render_ascii(self, starting_node, attr):
        """Render an ascii representation of the tree structure.

        Args:
            starting_node: The starting node to render the ascii.

        Returns:rm 
            attr: String of the attribute to render.
        """
        return anytree.RenderTree(starting_node,
                                  style=anytree.AsciiStyle()).by_attr(attr)
예제 #29
0
파일: algorithm.py 프로젝트: stachuk99/Keny
    def move(self, board, return_move):
        moves = board.get_moves(self.color)

        if self.tree is None:
            self.tree = anytree.Node("root",
                                     children=[],
                                     board=deepcopy(board),
                                     move=None,
                                     wins=0,
                                     simulations=0,
                                     moves_left=moves,
                                     color=not self.color)
        else:
            self.tree = anytree.search.find_by_attr(self.tree,
                                                    name="board",
                                                    value=board,
                                                    maxlevel=3)
            if self.tree is None:
                self.tree = anytree.Node("root",
                                         children=[],
                                         board=deepcopy(board),
                                         move=None,
                                         wins=0,
                                         simulations=0,
                                         moves_left=moves,
                                         color=not self.color)
            else:
                self.tree.parent = None

        start = time.time()
        i = 0
        while time.time() - start < self.simulation_time:
            selected_node = self._selection()
            expansion_node = self._expansion(selected_node)
            result = self._simulation(deepcopy(expansion_node.board),
                                      expansion_node.color)
            self._back_propagation(expansion_node, result, 1)
            i += 1
            if i % 100 == 0:
                print(i)
                for pre, _, node in anytree.RenderTree(self.tree, maxlevel=2):
                    print("%s %s->(%s/%s --> %s%%)" %
                          (pre, node.move, node.wins, node.simulations,
                           node.wins / node.simulations))

        best_node = None
        max_simulations = 0
        for n in self.tree.children:
            if n.simulations > max_simulations:
                best_node = n
                max_simulations = n.simulations
        return_move.append(best_node.move)
        return
예제 #30
0
def export_grammar_plot(quest: Grammar.tree.Node=None):

    if not quest:
        quest = quests.spy
        quest.set_indices()
    grammar = build_anytree(grammar_root=quest)

    if statics.Playground.debug_mode:
        for pre, fill, node in anytree.RenderTree(grammar):
            print("%s%s" % (pre, str(node.name).replace("\n", " ")))

    DotExporter(grammar).to_picture("Results/Trees/grammar.png")