Пример #1
0
def print_node(node):
    node.update_parent()
    root = AnyTreeVisitor().visit(node)

    for pre, fill, node in RenderTree(root):
        print('%s%s' % (pre, node.name))

    # export graphviz files
    exporter = DotExporter(root)
    exporter.to_dotfile('graphviz.dot')
    exporter.to_picture('graphviz.png')
Пример #2
0
 def generate_parse_tree(self, tokens):
     Global.token_stream[:] = tokens
     Global.cursor = 0
     tree_root = Node('program')
     print(Global.code_objs['decl_list'].check(tree_root))
     print(RenderTree(tree_root))
     DotExporter(tree_root).to_picture('../parse_tree.png')
Пример #3
0
    def visualise(self, filename):
        """
        Produces a .png file of the tree (this node and its children) with the
        name filename

        Parameters
        ----------

        filename : str
            filename to output, must end in ".png"

        """

        # check that filename ends in .png.
        if filename[-4:] != ".png":
            raise ValueError("filename should end in .png")

        new_node, counter = self.relabel_tree(self, 0)

        try:
            DotExporter(new_node,
                        nodeattrfunc=lambda node: 'label="{}"'.format(
                            node.label)).to_picture(filename)
        except FileNotFoundError:
            # raise error but only through logger so that test passes
            pybamm.logger.error(
                "Please install graphviz>=2.42.2 to use dot exporter")
Пример #4
0
    def takeTempPolicy(self):
        li = [[0, 0, 1, 0], [0, 2, 1, 0], [1, 2, 1, 0], [1, 3, 1, 0],
              [0, 3, 0, 0], [1, 4, 1, 0], [0, 4, 0, 1]]
        if (len(li) == 0):
            return
        nodes = [
            AnyNode(name="temp", parent=self.root, dim=0, part=0, inheritedN=0)
            for i in range(len(li))
        ]
        parentNode = self.root
        TreeTravDirec = li[0][0]
        #print(TreeTravDirec)
        for i in range(len(li)):
            if (li[i][0] != TreeTravDirec):
                TreeTravDirec = li[i][0]
                parentNode = nodes[i - 1]
            inheritedN = self.g.childNodeN(parentNode.inheritedN)
            nodes[i].name = str(i)
            nodes[i].dim = str(li[i][0])
            nodes[i].val = str(li[i][1])
            nodes[i].parent = parentNode
            nodes[i].inheritedN = inheritedN

            self.takeAction(li[i][0], li[i][1], li[i][3], inheritedN)

        self.g.renderEnv()
        #print(nameNode,"yo")
        #AnyNode(name="sub0B", parent=s0, index=1, partition=9)
        DotExporter(self.root).to_picture("TreeDiag/root.png")
Пример #5
0
def export(tree, filename, ext='json', **kwargs):
  parent = _get_printable_tree(tree)
  if ext == 'json':
    with io.open(f'{filename}.json', mode='w+', encoding='utf-8') as fp:
      JsonExporter(**kwargs).write(parent, fp)
  else:
    DotExporter(parent, **kwargs).to_picture(f'{filename}.{ext}')
def drawExpressionTree(postfix):
    """Draw expression tree in console and output to file"""
    stack = []
    index = 0
    for i in postfix:
        if type(i) is float or i == 'x':
            stack.append(Node(index, parent=None, val=i))
            index += 1
        else:
            if i == 'sqrt':
                child = stack.pop()
                parent = Node(index, parent=None, val=i)
                index += 1
                child.parent = parent
                stack.append(parent)
            elif i == '-' and len(stack) == 1:
                child = stack.pop()
                parent = Node(index, parent=None, val=i)
                index += 1
                child.parent = parent
                stack.append(parent)
            else:
                right = stack.pop()
                left = stack.pop()
                parent = Node(index, parent=None, val=i)
                index += 1
                left.parent = parent
                right.parent = parent
                stack.append(parent)
    root = stack.pop()
    DotExporter(root, graph="graph", nodeattrfunc=nodeattrfunc,
                edgetypefunc=edgetypefunc).to_dotfile("tree.dot")
    # Graphviz: http://www.webgraphviz.com/
    print("\nExpression Tree:")
    print(RenderTree(root, style=DoubleStyle).by_attr(attrname='val'))
Пример #7
0
def dbgPrintTreeToImage(inputNode, rootFolder=None, subFolder=None):
    """Debug: print tree relation to image
        for single (root) node: print to single relation image file
        for top node list: print each single top node to single relation image file

    Args:
        inputNode (Node/list): if Node, is single (noramlly root) tree node; if list, is tree top node list
        rootFolder (str): output root folder. Default None. If None, use current folder from os.getcwd()
        subFolder (str): output sub folder
    Returns:
    Raises:
    """
    if not rootFolder:
        rootFolder = os.getcwd()

    isTopNodeList = False
    if isinstance(inputNode, list):
        isTopNodeList = True
        topNodeList = inputNode
    else:
        currentNode = inputNode

    if subFolder:
        outputFolder = os.path.join(rootFolder, subFolder)
    else:
        outputFolder = rootFolder

    if isTopNodeList:
        topNodeSubFolder = "topNode"
        outputFolder = os.path.join(outputFolder, topNodeSubFolder)

    createFolder(outputFolder)

    if isTopNodeList:
        for curTopNode in topNodeList:
            curNodeRealtionFile = "TopNode_Relation_%s.png" % (curTopNode.name)
            curNodeRealtionImg = os.path.join(outputFolder,
                                              curNodeRealtionFile)
            # 'output/20210622/current/topNode/RelationTopNode_aaaaaaaa5522.png'
            print("Generating %s" % curNodeRealtionImg)
            DotExporter(curTopNode).to_picture(curNodeRealtionImg)
    else:
        allNodeOutputFilename = "AllNode_Relation.png"
        allNodeOutputFullPath = os.path.join(outputFolder,
                                             allNodeOutputFilename)
        print("Generating %s" % allNodeOutputFullPath)
        DotExporter(currentNode).to_picture(allNodeOutputFullPath)
Пример #8
0
def ipaddress():
    path = os.path.dirname(__file__)
    with open('{}/test_files/ipaddress.py'.format(path), 'r') as f:
        code = f.read()
        parse_tree = Parser().parse(code)
        root = SimplifiedParsedTreeTransformer().visit(parse_tree)
        from anytree.exporter import DotExporter
        DotExporter(root).to_picture("{}/test_files/ipaddress.png".format(path))
Пример #9
0
    def dot(self):
        '''
        Return the BOM tree structure from :py:attr:`BOM.BOM.tree` in DOT graph
        format (Graphiz)

        :rtype: str
        '''
        return '\n'.join([line for line in DotExporter(self)])
Пример #10
0
 def plot_tree(self, file_path):
     # for pre, fill, node in self:
     #    print("%s%s" % (pre, node.name))
     DotExporter(
         self.node,
         edgeattrfunc=lambda p, c: "label=<" + c.label + ">").to_picture(
             "t2.pdf")
     return
Пример #11
0
def show_tree(tree, path=None):
    if (path):
        DotExporter(tree,
                    nodeattrfunc=lambda node: 'label="{}"'.format(node.value)
                    ).to_dotfile(path)
    else:
        for pre, fill, node in RenderTree(tree):
            print("%s%s" % (pre, node.value))
Пример #12
0
def createTree(root):
    DotExporter(
        root,
        graph="graph",
        nodenamefunc=nodenamefunc,
        # nodeattrfunc= lambda node: "shape=box",
        # edgeattrfunc=edgeattrfunc,
        edgetypefunc=edgetypefunc).to_picture("tree.pdf")
Пример #13
0
def test_esc():
    """Test proper escape of quotes."""
    n = Node(r'6"-6\"')
    eq_(tuple(DotExporter(n)), (
        r'digraph tree {',
        r'    "6\"-6\\\"";',
        r'}'
    ))
Пример #14
0
def export_trie(
    trie, img_filename='trie.png', graphviz_filename=None
):
    if not trie.empty():
        words = trie.list_words()
        for i in range(len(words)):
            words[i] = '*' + words[i]

        nodes = {}
        root = None
        count = 0
        for word in words:
            parent_node = None
            parent_node_label = ""
            for i, val in enumerate(word):
                if i not in nodes:
                    nodes[i] = {}
                key = parent_node_label + val
                count += 1
                if key not in nodes[i]:
                    nodes[i][key] = Node(
                        key, parent=parent_node, display_name=val
                    )

                if root is None:
                    root = nodes[i][key]

                parent_node = nodes[i][key]
                parent_node_label += val

        DotExporter(
            nodes[0]["*"],
            nodeattrfunc=lambda node: 'label="{}"'.format(node.display_name)
        ).to_dotfile(
            'trie.graphviz.txt' if graphviz_filename is None
            else graphviz_filename
        )

        DotExporter(
            nodes[0]["*"],
            nodeattrfunc=lambda node: 'label="{}"'.format(node.display_name)
        ).to_picture(img_filename)

        if graphviz_filename is None:
            os.remove('trie.graphviz.txt')
Пример #15
0
def draw_tree(string1, path_des, file):
    from anytree import RenderTree
    importer = JsonImporter()
    root = importer.import_(string1)
    # Render Tree
    print(RenderTree(root, style=ContRoundStyle()))
    # # Render graph tree
    DotExporter(root).to_picture(path_des + file)
    Image(filename=path_des + file)
Пример #16
0
 def run(self):
     # checking if we have * in names
     if self.algorithm_name[-1] == '*':
         path = "./treeImages/" + str(
             self.algorithm_name[0:-1]) + " tree.png"
     else:
         path = "./treeImages/" + str(self.algorithm_name) + " tree.png"
     DotExporter(self.tree).to_picture(path)
     self.signal.emit(path)
Пример #17
0
def draw_activity_tree(root: Node, rules) -> DotExporter:
    fig = DotExporter(
        root,
        options=["rankdir = LR;"],
        nodenamefunc=lambda n: f"{n.name}\ncount={n.count}",
        nodeattrfunc=lambda node: f'penwidth={5 if node.is_activity else 1}')

    st.graphviz_chart(''.join(fig))
    return fig
Пример #18
0
    def process(self, query, region, meta, match_offset, match_length):

        # Turn Mantee stuff into usable structure.
        line = cow_region_to_conc(region, self.has_attributes)

        # Find true tokens via indices (not structs) for separating match from context.
        # Turn everything into nodes already - to be linked into tree in next step.
        indices = [i for i, s in enumerate(line) if not self.rex.match(s[0])]
        nodes        = [Node("0", token = "TOP", relation = "", head = "", linear = 0, meta = dict(zip(query.references, meta))),] + \
                         [Node(make_token_safe(line[x][self.column_index]),
                         token    = line[x][self.column_token],
                         relation = line[x][self.column_relation],
                         head     = line[x][self.column_head],
                         linear   = int(line[x][self.column_index]),
                         **dict(zip([query.attributes[a] for a in self.attribs], [line[x][a] for a in self.attribs])) ) for x in indices]

        # Build tree from top.
        for n in nodes[1:]:
            n.parent = next((x for x in nodes if x.name == n.head), None)

        # If a descendant implements the filter, certain structures can be
        # discarded.
        if not self.filtre(nodes, line):
            return

        # Export as desired. Three independent formats.
        if self.printtrees:
            for pre, _, node in RenderTree(nodes[0]):
                print("%s%s (%s)" % (pre, node.token, node.name))

        if self.savejson:
            self.exporter.write(nodes[0], self.writer)

        if self.saveimage:
            fnam = self.fileprefix + '_' + meta[self.imagemetaid1]
            if self.imagemetaid2:
                fnam = fnam + '_' + meta[self.imagemetaid2]
            if self.saveimage is 'dot':
                DotExporter(nodes[0]).to_dotfile(fnam + '.dot')
            elif self.saveimage is 'png':
                DotExporter(nodes[0],
                            edgeattrfunc=edgeattrfunc,
                            nodenamefunc=nodenamefunc).to_picture(fnam +
                                                                  '.png')
Пример #19
0
def draw_tree_graph(csv_dict, save_directory, query_dict):
    """
    Only utilize it when you want to generate a tree graph.
    :param csv_dict:
    :param save_directory:
    :param query_dict:
    :return:
    """
    from anytree import Node, RenderTree, AsciiStyle, LevelOrderIter
    from anytree.exporter import DotExporter
    tree_path_list = csv_dict["structure_id_path"]
    count_list = csv_dict["number"]
    label_list = csv_dict["label"]
    percentage_list = csv_dict["percentage"]
    node_dict = {}
    root_node = None

    for path_index in range(len(tree_path_list)):
        tree_path = tree_path_list[path_index]
        node_list = [int(item) for item in tree_path.split('/')[1: -1]]
        for i in range(len(node_list)):
            node_id = node_list[i]
            if node_id not in node_dict.keys():
                if node_id in query_dict.keys():
                    node_name = query_dict[node_id]['name']
                else:
                    node_name = str(node_id)

                if i == len(node_list) - 1:
                    node_dict[node_id] = Node(node_name, parent=node_dict[node_list[i - 1]],
                                              count=count_list[path_index],
                                              percentage=percentage_list[path_index])
                else:
                    if i == 0:
                        root_node = Node(node_name, count=0, percentage=.0)
                        node_dict[node_id] = root_node
                    else:
                        node_dict[node_id] = Node(node_name, parent=node_dict[node_list[i - 1]],
                                                  count=0, percentage=.0)
                    if node_id in label_list:
                        Node(node_name + "_other", parent=node_dict[node_id],
                             count=count_list[label_list.index(node_id)],
                             percentage=percentage_list[label_list.index(node_id)])

    node_level_order_list = list(LevelOrderIter(root_node))
    for i in range(len(node_level_order_list) - 1, 0, -1):
        node_level_order_list[i].parent.count += node_level_order_list[i].count
        node_level_order_list[i].parent.percentage += node_level_order_list[i].percentage


    def nodenamefunc(node):
        return '%s, beads number:%2d, beads percentage: %.5f %%' % (node.name, node.count, node.percentage*100.)
    DotExporter(root_node, nodenamefunc=nodenamefunc).to_picture(os.path.join(save_directory, "tree.png"))
    with open(os.path.join(save_directory, 'tree.txt'), 'w') as f:
        for pre, _, node in RenderTree(root_node):
            f.write('%s:%s, beads number:%2d, beads percentage: %.5f %% \n' % (pre, node.name, node.count, node.percentage*100.))
Пример #20
0
def print_inference_tree(root_node):
    """Print inference tree."""
    
    # Import and save
    from anytree.exporter import DotExporter
    DotExporter(root_node).to_picture("results/transformation_tree.png")
    
    # Print
    for pre, fill, node in RenderTree(root_node):
        print("%s%s" % (pre, node.name))
Пример #21
0
def export_semantics_plot(quest: Grammar.tree.Node=None, semantics_indices: dict={}, current_level_index: int=None):

    if not quest:
        quest = quests.spy
        quest.set_indices()
    semantics_indices_copy = copy(semantics_indices)
    semantics = build_anytree(grammar_root=quest, semantics_indices=semantics_indices_copy,
                              current_level_index=current_level_index)

    DotExporter(semantics).to_picture("Results/Trees/semantics.png")
Пример #22
0
def main():
    """Make a full tree from the default targets, and export it in graphviz and JSON form."""
    tree = make_tree()
    DotExporter(tree).to_dotfile('full_tree.dot')

    with open('full_tree.json', 'w') as f:
        exporter = JsonExporter(indent=4, sort_keys=True)
        exporter.write(tree, f)

    print(f'node count: {len(tree.descendants)}')
def list_to_leaves_model(list_tree, tree_name, display=True):
    root = Node(tree_name)
    non_leaves, leaves = build_tree_model(list_tree, nonleaf_list=[], leaf_list=[], p=root)
    if display:
        # for pre, fill, node in RenderTree(root):
            # print("{0}{1}".format(pre, node.name))
        print("tree name:", tree_name)
        print(root)
        DotExporter(root).to_picture(tree_name)
    return non_leaves, leaves
Пример #24
0
    def export_dotfile(self, filename: PathLike = None) -> None:
        """ exports the resources tree as a DOT file to the file specified by `filename`. Defaults to graph.dot in the local directory otherwise """
        if filename is None:
            filename = Path.cwd().joinpath('graph.dot')
        else:
            filename = Path(filename).expanduser().absolute()

        root = self.__find_root_node(self.items[0])
        DotExporter(root,
                    nodenamefunc=self.__format_node_name).to_dotfile(filename)
Пример #25
0
def dot_export_ideal_workload(root: SolverNode, name_appendix=''):
    def label_split(node, child):
        should = str(round(node.split_ratio[node.children.index(child)], 2))
        return 'label="' + should + '"'

    DotExporter(root,
                nodeattrfunc=design_node,
                edgeattrfunc=label_split,
                options=['dpi=300'
                         ]).to_picture(root.name + name_appendix + ".png")
Пример #26
0
def path_differences(model, paths_labels, type_analysis='production'):
    """

    Parameters
    ----------
    model: PySB model
        Model used to do dominant path analysis
    paths_labels: dict
        Dictionary of pathways generated by dominant path analysis
    type_analysis: str
        Type of analysis used in the dominant path analysis.
        It can either be `production` or `consumption`

    Returns
    -------
    A pandas dataframe where the column names and row indices are the labels of the
    pathways and the cells contain the edges that are present in the
    row pathway index but not in the column pathway.
    """
    generate_equations(model)
    importer = DictImporter()
    path_edges = {}

    def find_numbers(dom_r_str):
        n = map(int, re.findall('\d+', dom_r_str))
        return n

    def nodenamefunc(node):
        node_idx = list(find_numbers(node.name))[0]
        node_sp = model.species[node_idx]
        node_name = parse_name(node_sp)
        return node_name

    def edgeattrfunc(node, child):
        return 'dir="back"'

    for keys, values in paths_labels.items():
        root = importer.import_(values)
        dot = DotExporter(root, graph='strict digraph', options=["rankdir=RL;"], nodenamefunc=nodenamefunc,
                          edgeattrfunc=edgeattrfunc)
        data = ''
        for line in dot:
            data += line
        pydot_graph = graph_from_dot_data(data)
        graph = from_pydot(pydot_graph[0])
        if type_analysis == 'production':
            graph = graph.reverse()
        edges = set(graph.edges())
        path_edges[keys] = edges

    path_diff = pd.DataFrame(index=paths_labels.keys(), columns=paths_labels.keys())
    for row in path_diff.columns:
        for col in path_diff.columns:
            path_diff.loc[row, col] = path_edges[row].difference(path_edges[col])
    return path_diff
Пример #27
0
def draw_page_tree(root: Node, max_count: int) -> DotExporter:
    # color is HSV; saturation determines color intensity
    fig = DotExporter(
        root,
        options=["rankdir = LR; node [color=black, style=filled];"],
        nodenamefunc=lambda n: f"{n.name}\ncount={n.count}",
        nodeattrfunc=lambda node: f'fillcolor="0.6 {node.count / max_count} 1"'
    )

    st.graphviz_chart(''.join(fig))
    return fig
Пример #28
0
    def __init__(self, dir='controllers/'):

        importer = JsonImporter()

        with open(dir + 'data.json', 'r') as f:
            data = json.load(f)
            self.root = importer.import_(data)

        self.current_node = self.root

        DotExporter(self.root).to_picture("tree.png")
Пример #29
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")
Пример #30
0
def image(view, filename):
    """
    Export an image representation of a view's dependency tree.

    Requires the 'graphviz' package to be installed.
    """
    with yaspin(
        text="Exporting dependency tree image for view '{}'".format(view),
        color="yellow",
    ):
        DotExporter(view.tree).to_picture(filename)
    click.echo("Image saved to: {}".format(filename))
Пример #31
0
def simple_example():
    a = '''
a = {
    "b": 1,
    "c": 2,
}
    '''
    path = os.path.dirname(__file__)
    parse_tree = Parser().parse(a)
    root = SimplifiedParsedTreeTransformer().visit(parse_tree)
    from anytree.exporter import DotExporter
    DotExporter(root).to_picture("{}/test_files/test_tree.png".format(path))