Python graphviz 模块,Digraph() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用graphviz.Digraph()

项目:Lyra    作者:caterinaurban    | 项目源码 | 文件源码
def render(self, data, label=None, filename="Graph", directory="graphs", view=True):
        """Graphviz rendering."""

        # create the Graphviz graph
        graph_attr = self.graph_attr.copy()
        if label is not None:
            graph_attr['label'] = self._escape_label(label)
        graph = gv.Digraph(graph_attr=graph_attr, node_attr=self.node_attr, edge_attr=self.edge_attr)

        # draw nodes and edges of the Graphviz graph
        self._graph = graph
        self._rendered = set()
        self._render(data)
        self._graph = None
        self._rendered = None

        # display the Graphviz graph
        graph.format = "pdf"
        graph.render(f"{filename}.gv", directory, view, cleanup=True)
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def draw_cfg(cfg, output_filename = 'output'):
    """Draw CFG and output as pdf."""
    graph = Digraph(format='pdf')

    for node in cfg.nodes:
        stripped_label = node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, '')

        if 'Exit' in stripped_label:
            graph.node(stripped_label, 'Exit', shape='none')
        elif 'Entry' in stripped_label:
            graph.node(stripped_label, 'Entry', shape='none')
        else:
            graph.node(stripped_label, stripped_label)

        for ingoing_node in node.ingoing:
            graph.edge(ingoing_node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, ''), stripped_label)

    graph = apply_styles(graph, cfg_styles)
    graph.render(filename = output_filename)
项目:PSyclone    作者:stfc    | 项目源码 | 文件源码
def dag(self, file_name='dag', file_format='svg'):
        '''Create a dag of this node and its children'''
        try:
            import graphviz as gv
        except ImportError:
            # todo: add a warning to a log file here
            # silently return if graphviz bindings are not installed
            return
        try:
            graph = gv.Digraph(format=file_format)
        except ValueError:
            raise GenerationError(
                "unsupported graphviz file format '{0}' provided".
                format(file_format))
        self.dag_gen(graph)
        graph.render(filename=file_name)
项目:tfgraphviz    作者:akimach    | 项目源码 | 文件源码
def tf_digraph(name=None, name_scope=None, style=True):
    """
    Return graphviz.dot.Digraph with TensorBoard-like style.
    @param  name
    @param  name_scope
    @param  style
    @return graphviz.dot.Digraph object
    """
    digraph = gv.Digraph(name=name)
    if name_scope:
        digraph.graph_attr['label'] = name_scope
    if style is False: return digraph

    if name_scope:
        digraph.graph_attr.update(name_scope_graph_pref)
    else:
        digraph.graph_attr.update(non_name_scope_graph_pref)
    digraph.graph_attr.update(graph_pref)
    digraph.node_attr.update(node_pref)
    digraph.edge_attr.update(edge_pref)
    return digraph
项目:tfgraphviz    作者:akimach    | 项目源码 | 文件源码
def add_edges(digraph, node_inpt_table, node_inpt_shape_table):
    """
    Add TensorFlow graph's edges to graphviz.dot.Digraph.
    @param  dirgraph
    @param  node_inpt_table
    @param  node_inpt_shape_table
    @return  graphviz.dot.Digraph
    """
    for node, node_inputs in node_inpt_table.items():
        if re.match(r"\^", node): continue
        for ni in node_inputs:
            if ni == node: continue
            if re.match(r"\^", ni): continue
            if not ni in node_inpt_shape_table:
                digraph.edge(ni, node)
            else:
                shape = node_inpt_shape_table[ni]
                digraph.edge(ni, node, label=edge_label(shape))
    return digraph
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def draw_cfg(cfg, output_filename = 'output'):
    """Draw CFG and output as pdf."""
    graph = Digraph(format='pdf')

    for node in cfg.nodes:
        stripped_label = node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, '')

        if 'Exit' in stripped_label:
            graph.node(stripped_label, 'Exit', shape='none')
        elif 'Entry' in stripped_label:
            graph.node(stripped_label, 'Entry', shape='none')
        else:
            graph.node(stripped_label, stripped_label)

        for ingoing_node in node.ingoing:
            graph.edge(ingoing_node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, ''), stripped_label)

    graph = apply_styles(graph, cfg_styles)
    graph.render(filename = output_filename)
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        super(ExVizPass, self).__init__()
        self.show_axes = kwargs.pop('show_axes', True)
        self.show_all_metadata = kwargs.pop('show_all_metadata', True)
        self.subgraph_attr = kwargs.pop('subgraph_attr', None)
        self.exops_with_nodes = set()
        self.exops_without_nodes = set()
        self.filename = kwargs.pop('filename', 'Digraph')
        self.view = kwargs.pop('view', True)
        self.cleanup = kwargs.pop('cleanup', True)
        self.show_tensors = kwargs.pop('show_tensors', False)
        output_directory = kwargs.pop('output_directory', '.')

        if self.view:
            if output_directory is None:
                output_directory = tempfile.mkdtemp()
        self.output_directory = output_directory
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def begin_pass(self, filename=None, **kwargs):
        super(ExVizPass, self).begin_pass(**kwargs)
        try:
            import graphviz
        except ImportError:
            raise ImportError("You tried to use the ShowGraph transformer pass but did "
                              "not have the python graphviz library installed")
        if filename is None:
            filename = self.filename
        self.exops_with_nodes = set()
        self.exops_without_nodes = set()
        self.tensors_with_nodes = set()
        self.tensors_without_nodes = set()

        # Get all ops from this set
        self.graph = graphviz.Digraph(name=filename,
                                      # node_attr={'shape': 'box', 'style': 'rounded'},
                                      graph_attr={'nodesep': '.5',
                                                  'ranksep': '.5'})
项目:vnet.pytorch    作者:mattmacy    | 项目源码 | 文件源码
def save(fname, creator):
    dot = Digraph(comment='LRP',
                node_attr={'style': 'filled', 'shape': 'box'})
    #, 'fillcolor': 'lightblue'})

    seen = set()

    def add_nodes(var):
        if var not in seen:
            if isinstance(var, Variable):
                dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
            else:
                dot.node(str(id(var)), type(var).__name__)
            seen.add(var)
            if hasattr(var, 'previous_functions'):
                for u in var.previous_functions:
                    dot.edge(str(id(u[0])), str(id(var)))
                    add_nodes(u[0])

    add_nodes(creator)
    dot.save(fname)
项目:densenet.pytorch    作者:bamos    | 项目源码 | 文件源码
def save(fname, creator):
    dot = Digraph(comment='LRP',
                node_attr={'style': 'filled', 'shape': 'box'})
    #, 'fillcolor': 'lightblue'})

    seen = set()

    def add_nodes(var):
        if var not in seen:
            if isinstance(var, Variable):
                dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
            else:
                dot.node(str(id(var)), type(var).__name__)
            seen.add(var)
            if hasattr(var, 'previous_functions'):
                for u in var.previous_functions:
                    dot.edge(str(id(u[0])), str(id(var)))
                    add_nodes(u[0])

    add_nodes(creator)
    dot.save(fname)
项目:caproto    作者:NSLS-II    | 项目源码 | 文件源码
def create_transition_graph(d, role, format_):
    graph = gv.Digraph(format=format_)
    for node in d:
        node_name = to_node_name(node)
        graph.node(node_name, label=node_name)

    self_transitions = defaultdict(lambda: [])

    for source, transitions in d.items():
        source_name = to_node_name(source)
        for received, dest in transitions.items():
            dest_name = to_node_name(dest)
            received_name = to_node_name(received)
            if source_name == dest_name:
                self_transitions[source_name].append(received_name)
                continue

            graph.edge(source_name, dest_name,
                       label=received_name)

    for node_name, received_list in self_transitions.items():
        graph.edge(node_name, node_name, label=' / '.join(received_list))
    return graph
项目:crc-diagram    作者:IuryAlves    | 项目源码 | 文件源码
def __init__(self, crc_cards, format='png', graph_data=None):
        self.format = format
        self.crc_cards = crc_cards
        self.graph_data = {'shape': 'record'}
        self._edges = []  # keep track of the edges

        if graph_data is not None:
            self.graph_data.update(graph_data)

        self.graph = Digraph(
            comment='CRC Diagram',
            node_attr=self.graph_data,
            format=self.format
        )

        self._init()
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def dependency_parsing():
    dom = xml.dom.minidom.parse("nlp.txt.xml")
    dpnds = dom.getElementsByTagName('dependencies')
    dot = Digraph(format='png')
    idgov, iddep, lblgov, lbldep = '', '', '', ''
    for dpnd in dpnds:
        if dpnd.getAttribute('type') == "collapsed-dependencies":
            deps = dpnd.getElementsByTagName('dep')
            for dep in deps:
                governors = dep.getElementsByTagName('governor')
                dependents = dep.getElementsByTagName('dependent')
                for governor, dependent in zip(governors, dependents):
                    idgov = governor.getAttribute('idx')
                    lblgov = governor.firstChild.data
                    iddep = dependent.getAttribute('idx')
                    lbldep = dependent.firstChild.data
                    dot.node(str(iddep), lbldep)
                    dot.node(str(idgov), lblgov)
                    dot.edge(str(idgov), str(iddep))
            dot.render('png-knock57', cleanup=True)
            exit()
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def dependency_parsing():
    dom = xml.dom.minidom.parse("nlp.txt.xml")
    dpnds = dom.getElementsByTagName('dependencies')
    dot = Digraph(format='png')
    idgov, iddep, lblgov, lbldep = '', '', '', ''
    for dpnd in dpnds:
        if dpnd.getAttribute('type') == "collapsed-dependencies":
            deps = dpnd.getElementsByTagName('dep')
            for dep in deps:
                governors = dep.getElementsByTagName('governor')
                dependents = dep.getElementsByTagName('dependent')
                for governor, dependent in zip(governors, dependents):
                    idgov = governor.getAttribute('idx')
                    lblgov = governor.firstChild.data
                    iddep = dependent.getAttribute('idx')
                    lbldep = dependent.firstChild.data
                    dot.node(str(iddep), lbldep)
                    dot.node(str(idgov), lblgov)
                    dot.edge(str(iddep), str(idgov))
            dot.render('png-knock57', cleanup=True)
            exit()
项目:reddit-crawler    作者:cdated    | 项目源码 | 文件源码
def generate_graph(related_subs, subscribers, nsfw_subs, censored, full, min_subscribers, outfile):
    """ Make a graphviz graph by adding edges for each sub and related subs """

    g = Digraph('G', filename=outfile)

    edges_added = 0
    for key in related_subs:
        for sub in related_subs[key]:
            if not sub or not sub in subscribers:
                continue

            # In nsfw_subs and censored is mutually exclusive
            if ((sub in nsfw_subs) != (censored)) or full:
                subscriber_cnt = subscribers[sub]

                # Filter: only include edge if sub has # subscribers
                if subscriber_cnt >= min_subscribers:
                    g.edge(key, sub, weight=calculate_edge_weight(subscriber_cnt))
                    print("Edge count: " + str(edges_added))
                    edges_added += 1

    g.save()
项目:openmaptiles-tools    作者:openmaptiles    | 项目源码 | 文件源码
def generate_mapping_subgraph(table):
    subgraph = Digraph(table.name, node_attr={
        'width:': '20',
        'fixed_size': 'shape'
    })

    subgraph.node(table.name, shape='box')

    for osm_key, osm_values in table.mapping:
        node_name = 'key_' + normalize_graphviz_labels(osm_key)
        subgraph.node(node_name, label=osm_key, shape='box')

        subgraph.edge(node_name, table.name,
                      label=values_label(osm_values))

    return subgraph
项目:tetre    作者:aoldoni    | 项目源码 | 文件源码
def sentence_to_graph_recursive(self, token, parent_id, e):
        """Recursive function on each node as to generates the sentence dependency tree image.

        Args:
            token: The string token raw text.
            parent_id: The id of the parent node this token is a child of in the dependency tree.
            e: The graphical object (graphviz.Digraph).
        """
        if len(list(token.children)) == 0:
            return

        current_global_id = {}

        for child in token.children:
            self.current_token_id += 1
            current_global_id[str(self.current_token_id)] = child

        for child_id, child in current_global_id.items():
            self.sentence_to_graph_add_node(e, child_id, child.orth_)
            e.edge(str(parent_id), child_id, label=child.dep_)

        for child_id, child in current_global_id.items():
            self.sentence_to_graph_recursive(child, child_id, e)
项目:tetre    作者:aoldoni    | 项目源码 | 文件源码
def gen_group_image(self, token, depth=1):
        """Generates the images based on the node that represents this group.

        Args:
            token: The Treenode node.
            depth: integer 1 by default, as we are only interested in the first level.

        Returns:
            A string with the image path.
        """
        e = Digraph(self.argv.tetre_word, format=GroupImageNameGenerator.file_extension)
        e.attr('node', shape='box')

        current_id = self.current_token_id
        e.node(str(current_id), token.pos_)

        self.group_to_graph_recursive_with_depth(token, current_id, e, depth)

        name_generator = GroupImageNameGenerator(self.base_image_name, self.argv.tetre_word, str(self.current_group_id))
        e.render(name_generator.get_render_path())

        self.current_group_id += 1

        return name_generator.get_base_path_with_extension()
项目:pygraph    作者:EntilZha    | 项目源码 | 文件源码
def main(engine, undirected, format, name, dot, file, edges, no_vertex_labels):
    if undirected:
        graph = graphviz.Graph(engine=engine, format=format)
    else:
        graph = graphviz.Digraph(engine=engine, format=format)
    if name:
        graph.body.append(r'label = "{0}"'.format(name))
    edges = seq(edges).map(split_edge)

    if no_vertex_labels:
        edges.map(lambda e: (e.left, e.right)).flatten().distinct()\
            .filter_not(lambda n: n is None).for_each(lambda n: graph.node(n, label=''))
    else:
        edges.map(lambda e: (e.left, e.right)).flatten().distinct() \
            .filter_not(lambda n: n is None).for_each(lambda n: graph.node(n))

    edges.filter(lambda e: e.right is not None) \
        .for_each(lambda e: graph.edge(e.left, e.right, label=e.label))
    filepath, filename = path.split(file)
    filepath = filepath if filepath != '' else None
    graph.render(filename=filename, directory=filepath, cleanup=not dot)
项目:simple-markov    作者:Mandragorian    | 项目源码 | 文件源码
def to_dot(self, return_graph=False):
        """
        Creates a DOT format representation of this chain, where states
        are represented as labelled nodes and transitions as directed arcs
        labelled by their probabilities. If return_graph is set to True,
        the graphviz.Digraph object that contains the representation is
        returned instead.

        :param return_graph: a boolean indicating if the underlying Digraph
         object should be returned instead of the string representation
        :returns: a representation of the chain in DOT format
        """
        graph = gv.Digraph(format='svg')
        for st in self.states.values():
            st.populate_graph(graph)

        return graph if return_graph else graph.source
项目:seqmod    作者:emanjavacas    | 项目源码 | 文件源码
def _make_dot(var):
    node_attr = dict(style='filled',
                     shape='box',
                     align='left',
                     fontsize='12',
                     ranksep='0.1',
                     height='0.2')
    dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
    seen = set()

    def add_nodes(var):
        if var not in seen:
            if isinstance(var, Variable):
                value = '(' + (', ').join(['%d' % v for v in var.size()]) + ')'
                dot.node(str(id(var)), str(value), fillcolor='lightblue')
            else:
                dot.node(str(id(var)), str(type(var).__name__))
            seen.add(var)
            if hasattr(var, 'previous_functions'):
                for u in var.previous_functions:
                    dot.edge(str(id(u[0])), str(id(var)))
                    add_nodes(u[0])
    add_nodes(var.creator)
    return dot
项目:thinkgraph    作者:ryanfreckleton    | 项目源码 | 文件源码
def create_graph(semantic_graph):
    splines = 'spline'
    if semantic_graph.loop_edges or semantic_graph.and_loop_edges:
        splines = 'ortho'
    g = graphviz.Digraph(
            graph_attr={'rankdir':'BT', 'splines':splines},
            node_attr={
            'shape':'rectangle', 'style':'rounded,filled', 'fillcolor':'#FFFFCC'
            }
    )
    for identifier, label, cls in semantic_graph.nodes:
        g.node(identifier, label=label, **attrs[cls])
    g.edges(semantic_graph.edges)
    for e in semantic_graph.and_edges:
        g.edge(*e, dir="none")
    for e in semantic_graph.loop_edges:
        g.edge(*e, constraint="false")
    for e in semantic_graph.and_loop_edges:
        g.edge(*e, dir="none", constraint="false")
    for a, b in semantic_graph.conflicts:
        subgraph = graphviz.Digraph('cluster', graph_attr={'rank':'same', 'color':'none'})
        subgraph.edge(a, b, style="tapered", dir="both", arrowhead="none",
                  arrowtail="none", constraint="false", color="red", penwidth="7")
        g.subgraph(subgraph)
    return g
项目:pytorch_resnet    作者:taokong    | 项目源码 | 文件源码
def save(fname, creator):
    dot = Digraph(comment='LRP',
                node_attr={'style': 'filled', 'shape': 'box'})
    #, 'fillcolor': 'lightblue'})

    seen = set()

    def add_nodes(var):
        if var not in seen:
            if isinstance(var, Variable):
                dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
            else:
                dot.node(str(id(var)), type(var).__name__)
            seen.add(var)
            if hasattr(var, 'previous_functions'):
                for u in var.previous_functions:
                    dot.edge(str(id(u[0])), str(id(var)))
                    add_nodes(u[0])

    add_nodes(creator)
    dot.save(fname)
项目:userline    作者:THIBER-ORG    | 项目源码 | 文件源码
def __init__(self,output,cache_data):
        # TODO: Store this relations in a redis-like cache
        self.cache = Cache(cache_data)
        self.cache.create_cache(self.DEST_RELS)
        self.cache.create_cache(self.DOM_RELS)
        self.cache.create_cache(self.SRC_RELS)
        self.cache.create_cache(self.SRCDST_RELS)
        self.cache.create_cache(self.SRCLOGIN_RELS)
        self.cache.create_cache(self.SESSIONS_RELS)
        self.cache.create_cache(self.FROM_SESSIONS)
        self.cache.create_cache(self.USER_LIST)
        self.cache.create_cache(self.DOM_LIST)
        self.cache.create_cache(self.SRV_LIST)
        self.cache.create_cache(self.SRVDOM_RELS)
        self.output = output
        self.graph = gv.Digraph()
项目:kolla    作者:sieve-microservices    | 项目源码 | 文件源码
def save_dependency(self, to_file):
        try:
            import graphviz
        except ImportError:
            LOG.error('"graphviz" is required for save dependency')
            raise
        dot = graphviz.Digraph(comment='Docker Images Dependency')
        dot.body.extend(['rankdir=LR'])
        for image in self.images:
            if image.status not in [STATUS_MATCHED]:
                continue
            dot.node(image.name)
            if image.parent is not None:
                dot.edge(image.parent.name, image.name)

        with open(to_file, 'w') as f:
            f.write(dot.source)
项目:matchpy    作者:HPAC    | 项目源码 | 文件源码
def _as_graph(self, finals: Optional[List[str]]) -> Digraph:  # pragma: no cover
        if Digraph is None:
            raise ImportError('The graphviz package is required to draw the graph.')
        graph = Digraph()
        if finals is None:
            patterns = [
                '{}: {} with {}'.format(
                    self._colored_pattern(i), html.escape(str(p.expression)), self._format_constraint_set(c)
                ) for i, (p, l, c) in enumerate(self.patterns)
            ]
            graph.node('patterns', '<<b>Patterns:</b><br/>\n{}>'.format('<br/>\n'.join(patterns)), {'shape': 'box'})

        self._make_graph_nodes(graph, finals)
        if finals is None:
            constraints = [
                '{}: {} for {}'.format(self._colored_constraint(i), html.escape(str(c)), self._format_pattern_set(p))
                for i, (c, p) in enumerate(self.constraints)
            ]
            graph.node(
                'constraints', '<<b>Constraints:</b><br/>\n{}>'.format('<br/>\n'.join(constraints)), {'shape': 'box'}
            )
        self._make_graph_edges(graph)
        return graph
项目:matchpy    作者:HPAC    | 项目源码 | 文件源码
def _make_graph_edges(self, graph: Digraph) -> None:  # pragma: no cover
        for state in self.states:
            for _, transitions in state.transitions.items():
                for transition in transitions:
                    t_label = '<'
                    if transition.variable_name:
                        t_label += '{}: '.format(self._colored_variable(transition.variable_name))
                    t_label += '&epsilon;' if transition.label is _EPS else html.escape(str(transition.label))
                    if is_operation(transition.label):
                        t_label += '('
                    t_label += '<br/>{}'.format(self._format_pattern_set(transition.patterns))
                    if transition.check_constraints is not None:
                        t_label += '<br/>{}'.format(self._format_constraint_set(transition.check_constraints))
                    if transition.subst is not None:
                        t_label += '<br/>{}'.format(html.escape(str(transition.subst)))
                    t_label += '>'

                    start = 'n{!s}'.format(state.number)
                    if state.matcher and len(state.matcher.automaton.states) > 1:
                        start += '-end'
                    end = 'n{!s}'.format(transition.target.number)
                    graph.edge(start, end, t_label)
项目:pyprom    作者:harrywang    | 项目源码 | 文件源码
def build_petrinet(tl, yl, ti, to, output_file):
    pn = gv.Digraph(format='png')
    pn.attr(rankdir='LR')  # left to righ layout - default is top down
    pn.node('start')
    pn.node('end')

    for elem in yl:
        for i in elem[0]:
            pn.edge(i, str(elem))
            pn.node(i, shape='box')
            pn.node(str(elem), shape='circle')
        for i in elem[1]:
            pn.edge(str(elem), i)
            pn.node(i, shape='box')
    for i in ti:
        pn.edge('start', i)
    for o in to:
        pn.edge(o, 'end')
    pn.render(output_file)
项目:DSOD-Pytorch-Implementation    作者:Ellinier    | 项目源码 | 文件源码
def save(fname, creator):
    dot = Digraph(comment='LRP', node_attr={'style': 'filled', 'shape': 'box'})
    seen = set()

    def add_nodes(var):
        if var not in seen:
            if isinstance(var, Variable):
                dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
            else:
                dot.node(str(id(var)), type(var).__name__)
            seen.add(var)
            if hasattr(var, 'previous_functions'):
                for u in var.previous_functions:
                    dot.edge(str(id(u[0])), str(id(var)))
                    add_nodes(u[0])

    add_nodes(creator)
    dot.save(fname)
项目:vivarium    作者:ihmeuw    | 项目源码 | 文件源码
def to_dot(self):
        """Produces a ball and stick graph of this state machine.

        Returns
        -------
        `graphviz.Digraph`
            A ball and stick visualization of this state machine.
        """
        from graphviz import Digraph
        dot = Digraph(format='png')
        for state in self.states:
            if isinstance(state, TransientState):
                dot.node(state.name(), style='dashed')
            else:
                dot.node(state.name())
            for transition in state.transition_set:
                dot.edge(state.name(), transition.output.name(), transition.label())
        return dot
项目:speccer    作者:bensimner    | 项目源码 | 文件源码
def __init__(self, graphviz=False):
        self.graphviz = graphviz
        self.graphviz_digraph = gv.Digraph(format='svg', comment='Generation Instances') if graphviz else None
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def draw_lattice(node, output_filename = 'output.dot'):
    """Draw CFG and output as pdf."""
    graph = Digraph(format='pdf')

    l = list()
    draw_node(l, graph, node)

    graph = apply_styles(graph, styles)
    graph.render(filename = output_filename)
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def draw_lattice(cfg, output_filename='output'):
    """Draw CFG and output as pdf."""
    graph = Digraph(format='pdf')

    ll = [s.label for s in cfg.nodes if isinstance(s, AssignmentNode)]
    root = make_lattice(ll,len(ll)-1)
    l = list()
    draw_node(l, graph, root)

    graph = apply_styles(graph, lattice_styles)
    graph.render(filename = output_filename+'.dot')

    add_anchor(output_filename)
    run_dot(output_filename)
项目:pyt    作者:SW10IoT    | 项目源码 | 文件源码
def draw_lattice_from_labels(labels, output_filename):
    graph = Digraph(format='pdf')

    root = make_lattice(labels, len(labels)-1)
    l = list()
    draw_node(l, graph, root)

    graph = apply_styles(graph, lattice_styles)
    graph.render(filename = output_filename+'.dot')

    add_anchor(output_filename)
    run_dot(output_filename)
项目:kolla-kubernetes-personal    作者:rthallisey    | 项目源码 | 文件源码
def save_dependency(self, to_file):
        dot = graphviz.Digraph(comment='Docker Images Dependency')
        dot.body.extend(['rankdir=LR'])
        for image in self.images:
            if image['status'] not in ['matched']:
                continue
            dot.node(image['name'])
            if image['parent'] is not None:
                dot.edge(image['parent']['name'], image['name'])

        with open(to_file, 'w') as f:
            f.write(dot.source)
项目:kolla-kubernetes-personal    作者:rthallisey    | 项目源码 | 文件源码
def save_dependency(self, to_file):
        dot = graphviz.Digraph(comment='Docker Images Dependency')
        dot.body.extend(['rankdir=LR'])
        for image in self.images:
            if image['status'] not in ['matched']:
                continue
            dot.node(image['name'])
            if image['parent'] is not None:
                dot.edge(image['parent']['name'], image['name'])

        with open(to_file, 'w') as f:
            f.write(dot.source)
项目:tfgraphviz    作者:akimach    | 项目源码 | 文件源码
def add_nodes(node_table, name=None, name_scope=None, style=True):
    """
    Add TensorFlow graph's nodes to graphviz.dot.Digraph.
    @param  node_table
    @param  name
    @param  name_scope
    @param  style
    @return graphviz.dot.Digraph object
    """
    global CLUSTER_INDEX
    if name:
        digraph = tf_digraph(name=name, name_scope=name_scope, style=style)
    else:
        digraph = tf_digraph(name=str(uuid.uuid4().get_hex().upper()[0:6]), name_scope=name_scope, style=style)
    graphs = []
    for key, value in node_table.items():
        if len(value) > 0:
            sg = add_nodes(value, name='cluster_%i' % CLUSTER_INDEX, name_scope=key.split('/')[-1], style=style)
            sg.node(key, key.split('/')[-1])
            CLUSTER_INDEX += 1
            graphs.append(sg)
        else:
            digraph.node(key, key.split('/')[-1])
    for tg in graphs:
        digraph.subgraph(tg)
    return digraph
项目:tfgraphviz    作者:akimach    | 项目源码 | 文件源码
def board(tfgraph, depth=1, name='G', style=True):
    """
    Return graphviz.dot.Digraph object with TensorFlow's Graphs.
    @param  depth
    @param  name
    @param  style
    @return  graphviz.dot.Digraph
    """
    global CLUSTER_INDEX
    CLUSTER_INDEX = 0
    _node_table = node_table(tfgraph, depth=depth)
    _node_inpt_table, _node_inpt_shape_table = node_input_table(tfgraph, depth=depth)
    digraph = add_nodes(_node_table, name=name, style=style)
    digraph = add_edges(digraph, _node_inpt_table, _node_inpt_shape_table)
    return digraph
项目:PyTorchDemystified    作者:hhsecond    | 项目源码 | 文件源码
def save_visualization(name, format='jpg'):
    g = graphviz.Digraph(format=format)
    def sizestr(var):
        size = [int(i) for i in list(var.size())]
        return str(size)
    # add variable nodes
    for vid, var in vars.items():
        if isinstance(var, nn.Parameter):
            g.node(str(vid), label=sizestr(var), shape='ellipse', style='filled', fillcolor='red')
        elif isinstance(var, Variable):
            g.node(str(vid), label=sizestr(var), shape='ellipse', style='filled', fillcolor='lightblue')
        else:
            assert False, var.__class__
    # add creator nodes
    for cid in func_trace:
        creator = funcs[cid]
        g.node(str(cid), label=str(creator.__class__.__name__), shape='rectangle', style='filled', fillcolor='orange')
    # add edges between creator and inputs
    for cid in func_trace:
        for iid in func_trace[cid]:
            g.edge(str(iid), str(cid))
    # add edges between outputs and creators
    for oid in var_trace:
        for cid in var_trace[oid]:
            g.edge(str(cid), str(oid))
    g.render(name)
项目:neat_py    作者:NathanZabriskie    | 项目源码 | 文件源码
def output_graph(self, outdir, outfile, numInSpecies=None):
        self.init_network()
        g1 = gv.Digraph(format='png')

        g1.attr('node', shape='doublecircle')
        for in_node in self.inputs:
            g1.attr('node', color='green')
            g1.node(self.get_node_name(in_node))
        for out_node in self.outputs:
            g1.attr('node', color='blue')
            g1.node(self.get_node_name(out_node))

        g1.attr('node', shape='circle', color='black')
        for node_id in self.nodes:
            if node_id in self.inputs or node_id in self.outputs:
                continue
            g1.node(self.get_node_name(node_id))

        for conn in (self.connections[x] for x in self.connections):
            if not conn.is_enabled:
                g1.attr('edge', style='dashed', arrowhead='empty')
            if conn.is_recurrent:
                if not self.allow_recurrent:
                    continue
                g1.attr('edge', color='red')
            g1.edge(self.get_node_name(conn.from_node),
                    self.get_node_name(conn.to_node),
                    label='{:.4f}'.format(conn.weight))
            g1.attr('edge', color='black', arrowhead='normal', style='solid')

        if numInSpecies:
            label = ('label = "Fitness = {:.2f}, '
                     'Species Size = {}"').format(self.fitness,
                                                  numInSpecies)
        else:
            label = 'label = "Fitness = {:.2f}"'.format(self.fitness)
        g1.body.append(label)
        g1.render(filename=outfile,
                  directory=outdir,
                  cleanup=True)
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def draw_lattice(cfg, output_filename='output'):
    """Draw CFG and output as pdf."""
    graph = Digraph(format='pdf')

    ll = [s.label for s in cfg.nodes if isinstance(s, AssignmentNode)]
    root = make_lattice(ll,len(ll)-1)
    l = list()
    draw_node(l, graph, root)

    graph = apply_styles(graph, lattice_styles)
    graph.render(filename = output_filename+'.dot')

    add_anchor(output_filename)
    run_dot(output_filename)
项目:pyt    作者:python-security    | 项目源码 | 文件源码
def draw_lattice_from_labels(labels, output_filename):
    graph = Digraph(format='pdf')

    root = make_lattice(labels, len(labels)-1)
    l = list()
    draw_node(l, graph, root)

    graph = apply_styles(graph, lattice_styles)
    graph.render(filename = output_filename+'.dot')

    add_anchor(output_filename)
    run_dot(output_filename)
项目:bifrost    作者:ledatelescope    | 项目源码 | 文件源码
def dot_graph(self, parent_graph=None):
        from graphviz import Digraph

        #graph_attr = {'label': self._name}
        graph_attr = {}
        if parent_graph is None:
            g = Digraph('cluster_' + self._name, graph_attr=graph_attr)
        else:
            g = parent_graph.subgraph('cluster_' + self._name,
                                      label=self._name)
        for child in self._children:
            if isinstance(child, Block):
                block = child
                label = block.name.split('/', 1)[1]
                block_colors = defaultdict(lambda: 'white')
                block_colors['CopyBlock'] = 'lightsteelblue'
                block_type = block.__class__.__name__
                fillcolor = block_colors[block_type]
                g.node(block.name,
                       #label='%s: %s' % (block.type,block.name),
                       label=label,
                       shape='box',
                       style='filled',
                       fillcolor=fillcolor)
                for oring in block.orings:
                    space_colors = {
                        'system':    'orange',
                        'cuda':      'limegreen',
                        'cuda_host': 'deepskyblue'
                    }
                    g.node(oring.name,
                           shape='ellipse',
                           style='filled',
                           fillcolor=space_colors[oring.space])
                    g.edge(block.name, oring.name)
                for iring in block.irings:
                    g.edge(iring.name, block.name)
            else:
                #child.dot_graph(g)
                g.subgraph(child.dot_graph())
        return g
项目:pytorch-caffe-darknet-convert    作者:marvis    | 项目源码 | 文件源码
def tf_to_dot(g):
    dot = Digraph()
    for n in g.node:
        dot.node(n.name, label=n.name)

        for i in n.input:
            dot.edge(i, n.name)
    return dot
项目:AntScheduler    作者:mcalus3    | 项目源码 | 文件源码
def draw_graph(nodes_list):
    """Draws the graph image using Graphviz library"""

    graph = graphviz.Digraph(name='ProcessGraph', format='svg')
    graph.body.extend(['rankdir=LR'])
    graph.attr('node', style='bold')
    for node in nodes_list:
        graph.node(name=node.name, color=X11_colors[node.type])
        for successor in node.successor_list:
            graph.edge(node.name, successor.name, label=str(successor.time_value))

    try:
        graph.render(directory=render_dir)
    except RuntimeError:
        logger.warning("Can't render graphs. Check if Graphviz path is valid")
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def sent2graph(sentence):
    dot = Digraph(format='png')
    for chunk in sentence:
        if chunk.dst != -1:
            dot.node(str(chunk.id), chunk.join_surface())
            dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
            dot.edge(str(chunk.id), str(chunk.dst))
    dot.render('knock44')
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def sent2graph(sentence):
    dot = Digraph(format='png')
    for chunk in sentence:
        if chunk.dst != -1:
            dot.node(str(chunk.id), chunk.join_surface())
            dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
            dot.edge(str(chunk.id), str(chunk.dst))
    dot.render('knock44')
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def sent2graph(sentence):
    dot = Digraph(format='png')
    for chunk in sentence:
        if chunk.dst != -1:
            dot.node(str(chunk.id), chunk.join_surface())
            dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
            dot.edge(str(chunk.id), str(chunk.dst))
    dot.render('knock44', cleanup=True)
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def endElement(self, name):
        self.pop_tag()
        if name == 'dependencies':
            self.is_representative = False
            fname = '{}/{}'.format(dirname, self.sent_id)
            self.graph.render(fname, cleanup=True)
            self.graph = Digraph(format='svg')
项目:100knock2016    作者:tmu-nlp    | 项目源码 | 文件源码
def sent2graph(sentence):
    dot = Digraph(format='png')
    for chunk in sentence:
        if chunk.dst != -1:
            dot.node(str(chunk.id), chunk.join_surface())
            dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
            dot.edge(str(chunk.id), str(chunk.dst))
    dot.render('knock44', cleanup=True)