当前位置: 首页>>代码示例>>Python>>正文


Python pygraphviz.AGraph方法代码示例

本文整理汇总了Python中pygraphviz.AGraph方法的典型用法代码示例。如果您正苦于以下问题:Python pygraphviz.AGraph方法的具体用法?Python pygraphviz.AGraph怎么用?Python pygraphviz.AGraph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pygraphviz的用法示例。


在下文中一共展示了pygraphviz.AGraph方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: visualize

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def visualize(graph, output_path="a.png"):
    """visualize(graph, **kwargs) -> None
        Graph/Merger graph -> the graph/Merger that will be visualized
        string output_path-> the output path of the image
    """

    if isinstance(graph, Merger): graph = Merger.G
    G = pgv.AGraph(directed=graph.directed)

    G.add_nodes_from([i for i in xrange(1, len(graph.edges))])
    for edge in graph.iterate_edges():
        G.add_edge(edge.start, edge.end, label=edge.weight)
        
    G.node_attr['shape'] = 'egg'
    G.node_attr['width'] = '0.25'
    G.node_attr['height'] = '0.25'
    G.edge_attr['arrowhead'] = 'open'

    G.layout(prog='dot')
    G.draw(output_path) 
开发者ID:luogu-dev,项目名称:cyaron,代码行数:22,代码来源:visual.py

示例2: dependencies

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def dependencies(self, deps_dict):
        """Generate graph file with depenndencies map tree
        """
        try:
            import pygraphviz as pgv
        except ImportError:
            if self.image == "ascii" and not os.path.isfile("/usr/bin/graph-easy"):
                print("Require 'grap_easy': Install with 'slpkg -s sbo graph-easy'")
            else:
                print("Require 'pygraphviz: Install with 'slpkg -s sbo pygraphviz'")
            raise SystemExit()
        if self.image != "ascii":
            self.check_file()
        try:
            G = pgv.AGraph(deps_dict)
            G.layout(prog="fdp")
            if self.image == "ascii":
                G.write(f"{self.image}.dot")
                self.graph_easy()
            G.draw(self.image)
        except IOError:
            raise SystemExit()
        if os.path.isfile(self.image):
            print(f"Graph image file '{self.image}' created")
        raise SystemExit() 
开发者ID:dslackw,项目名称:slpkg,代码行数:27,代码来源:graph.py

示例3: draw_network

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def draw_network(g, path, backbone=False):
    graph = pgv.AGraph(directed=True, strict=True, fontname='Helvetica', arrowtype='open')
    if g is None:
        add_node(graph, 0, 0)
        graph.layout(prog='dot')
        graph.draw(path)
        return
    for idx in range(g.vcount()):
        add_node(graph, idx, g.vs[idx]['type'])
    for idx in range(g.vcount()):
        for node in g.get_adjlist(igraph.IN)[idx]:
            if node == idx-1 and backbone:
                graph.add_edge(node, idx, weight=1)
            else:
                graph.add_edge(node, idx, weight=0)
    graph.layout(prog='dot')
    graph.draw(path) 
开发者ID:muhanzhang,项目名称:D-VAE,代码行数:19,代码来源:util.py

示例4: plot_similarity_graph

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def plot_similarity_graph(self, show_edges=False):
        '''(trial) visualize similarity using GraphViz'''
        g = pygraphviz.AGraph(directed=False, overlap='scale', splines=True)
        g.node_attr['shape'] = 'plaintext'
        g.node_attr['fontsize'] = '12'
        if show_edges:
            g.edge_attr['color'] = 'lightgrey'
            g.edge_attr['fontcolor'] = 'grey'
            g.edge_attr['fontsize'] = '8'
        else:
            g.edge_attr['style'] = 'invis'
        for crawl1 in sorted(self.similarity['url']):
            for crawl2 in sorted(self.similarity['url'][crawl1]):
                similarity = self.similarity['url'][crawl1][crawl2]
                distance = 1.0 - similarity
                g.add_edge(MonthlyCrawl.short_name(crawl1),
                           MonthlyCrawl.short_name(crawl2),
                           len=(distance),
                           label='{0:.2f}'.format(distance))
        g.write(os.path.join(PLOTDIR, 'crawlsimilarity_url.dot'))
        g.draw(os.path.join(PLOTDIR, 'crawlsimilarity_url.svg'), prog='fdp') 
开发者ID:commoncrawl,项目名称:cc-crawl-statistics,代码行数:23,代码来源:overlap.py

示例5: graphviz

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def graphviz(elem, doc):
    if type(elem) == CodeBlock and 'graphviz' in elem.classes:
        code = elem.text
        caption = "caption"
        G = pygraphviz.AGraph(string=code)
        G.layout()
        filename = sha1(code)
        filetype = {'html': 'png', 'latex': 'pdf'}.get(doc.format, 'png')
        alt = Str(caption)
        src = imagedir + '/' + filename + '.' + filetype
        if not os.path.isfile(src):
            try:
                os.mkdir(imagedir)
                sys.stderr.write('Created directory ' + imagedir + '\n')
            except OSError:
                pass
            G.draw(src)
            sys.stderr.write('Created image ' + src + '\n')
        return Para(Image(alt, url=source, title='')) 
开发者ID:sergiocorreia,项目名称:panflute,代码行数:21,代码来源:graphviz.py

示例6: __init__

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def __init__(self, stmts=None, graph_properties=None,
                 node_properties=None, edge_properties=None):
        if stmts is None:
            self.statements = []
        else:
            self.statements = stmts
        self.graph_properties = default_graph_properties
        self.node_properties = default_node_properties
        self.edge_properties = default_edge_properties
        if graph_properties:
            for k, v in graph_properties.items():
                self.graph_properties[k] = v
        if node_properties:
            for k, v in node_properties.items():
                self.node_properties[k] = v
        if edge_properties:
            for k, v in edge_properties.items():
                self.edge_properties[k] = v
        self.graph = pygraphviz.AGraph(**self.graph_properties)
        self.existing_nodes = []
        self.existing_edges = []
        self._complex_nodes = [] 
开发者ID:sorgerlab,项目名称:indra,代码行数:24,代码来源:assembler.py

示例7: draw_network

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def draw_network(dag, path):
    makedirs(os.path.dirname(path))
    graph = pgv.AGraph(directed=True, strict=True,
                       fontname='Helvetica', arrowtype='open') # not work?

    checked_ids = [-2, -1, 0]

    if -1 in dag:
        add_node(graph, -1, 'x[t]')
    if -2 in dag:
        add_node(graph, -2, 'h[t-1]')

    add_node(graph, 0, dag[-1][0].name)

    for idx in dag:
        for node in dag[idx]:
            if node.id not in checked_ids:
                add_node(graph, node.id, node.name)
                checked_ids.append(node.id)
            graph.add_edge(idx, node.id)

    graph.layout(prog='dot')
    graph.draw(path) 
开发者ID:carpedm20,项目名称:ENAS-pytorch,代码行数:25,代码来源:utils.py

示例8: assert_is_dot_format

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def assert_is_dot_format(dot):
    """ Checks that the dot is usable by graphviz. """

    # We launch a process calling graphviz to render the dot. If the exit code is not 0 we assume that the syntax
    # wasn't good
    def run_graph(dot):
        """ Runs graphviz to see if the syntax is good. """
        graph = AGraph()
        graph = graph.from_string(dot)
        extension = 'png'
        graph.draw(path='output.png', prog='dot', format=extension)
        sys.exit(0)

    p = Process(target=run_graph, args=(dot,))
    p.start()
    p.join()
    assert p.exitcode == 0 
开发者ID:Alexis-benoist,项目名称:eralchemy,代码行数:19,代码来源:test_intermediary_to_dot.py

示例9: render

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def render(self, filename='graph.png'):
        """Render the graph to a PNG file using pygraphviz.

        filename: name of the output file.

        To use this method, pygraphviz has to be installed.
        """
        try:
            import pygraphviz as pgv
            agv = pgv.AGraph(directed=True, strict=False)
            for u in self.edges:
                for v in self.edges[u]:
                    agv.add_edge(u, v)
            agv.layout('dot')
            agv.draw(filename)
            print('Rendered graph to "{0}"'.format(filename))
        except ImportError as e:
            print('Unable to import pygraphviz - not rendering')
            print(e) 
开发者ID:eliben,项目名称:code-for-blog,代码行数:21,代码来源:traversals.py

示例10: _get_edges_and_nodes

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def _get_edges_and_nodes(self, raw_lines):
        """Transform a raw GraphViz file into Node and Edge objects.  Note
        that at this point the nodes and edges are not linked into a graph
        they are simply two lists of items."""

        tempf = tempfile.NamedTemporaryFile(delete=False)
        tempf.write(raw_lines)
        tempf.close()
        G = pgv.AGraph(tempf.name)

        all_edges = []
        all_nodes = []

        for node in G.nodes():
            if (util.remove_nix_hash(node.name) not
                in [n.name for n in all_nodes]):
                all_nodes.append(Node(node.name))

        for edge in G.edges():
            all_edges.append(Edge(edge[0], edge[1]))

        return all_nodes, all_edges 
开发者ID:craigmbooth,项目名称:nix-visualize,代码行数:24,代码来源:visualize_tree.py

示例11: get_graph

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def get_graph(self, title=None):
        """ Generate a DOT graph with pygraphviz, returns an AGraph object
        Args:
            title (string): Optional title for the graph.
        """
        if not pgv:  # pragma: no cover
            raise Exception('AGraph diagram requires pygraphviz')

        if title is False:
            title = ''

        fsm_graph = pgv.AGraph(label=title, compound=True, **self.machine_attributes)
        fsm_graph.node_attr.update(self.style_attributes['node']['default'])
        fsm_graph.edge_attr.update(self.style_attributes['edge']['default'])

        # For each state, draw a circle
        self._add_nodes(self.machine.states, fsm_graph)
        self._add_edges(self.machine.events.copy(), fsm_graph)

        setattr(fsm_graph, 'style_attributes', self.style_attributes)

        return fsm_graph 
开发者ID:haynieresearch,项目名称:jarvis,代码行数:24,代码来源:diagrams.py

示例12: generate

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def generate(self, title=None):
        """ Generate a DOT graph with pygraphviz, returns an AGraph object """
        if not pgv:  # pragma: no cover
            raise Exception('AGraph diagram requires pygraphviz')

        title = '' if not title else title

        self.fsm_graph = pgv.AGraph(label=title, **self.machine.machine_attributes)
        self.fsm_graph.node_attr.update(self.machine.style_attributes['node']['default'])
        self.fsm_graph.edge_attr.update(self.machine.style_attributes['edge']['default'])
        states, transitions = self._get_elements()
        self._add_nodes(states, self.fsm_graph)
        self._add_edges(transitions, self.fsm_graph)
        setattr(self.fsm_graph, 'style_attributes', self.machine.style_attributes)

        return self.fsm_graph 
开发者ID:pytransitions,项目名称:transitions,代码行数:18,代码来源:diagrams_pygraphviz.py

示例13: master_spec_graph

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def master_spec_graph(master_spec):
  """Constructs a master spec graph.

  Args:
    master_spec: MasterSpec proto.

  Raises:
    TypeError, if master_spec is not the right type. N.B. that this may be
    raised if you import proto classes in non-standard ways (e.g. dynamically).

  Returns:
    SVG graph contents as a string.
  """
  if not isinstance(master_spec, spec_pb2.MasterSpec):
    raise TypeError("master_spec_graph() expects a MasterSpec input.")

  graph = pygraphviz.AGraph(directed=True)

  graph.node_attr.update(
      shape="box",
      style="filled",
      fillcolor="white",
      fontname="roboto, helvetica, arial",
      fontsize=11)
  graph.edge_attr.update(fontname="roboto, helvetica, arial", fontsize=11)

  for component in master_spec.component:
    graph.add_node(component.name, label=_component_contents(component))

  for component in master_spec.component:
    for linked_feature in component.linked_feature:
      graph.add_edge(
          linked_feature.source_component,
          component.name,
          label=_linked_feature_label(linked_feature))

  with warnings.catch_warnings():
    # Fontconfig spews some warnings, suppress them for now. (Especially because
    # they can clutter IPython notebooks).
    warnings.simplefilter("ignore")
    return graph.draw(format="svg", prog="dot") 
开发者ID:ringringyi,项目名称:DOTA_models,代码行数:43,代码来源:render_spec_with_graphviz.py

示例14: draw_img

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def draw_img(self, img_name='Trie.png'):
        """
        画出trie树
        :param img_name:
        :return:
        """
        if self.root is None:
            return

        tree = pgv.AGraph('graph foo {}', strict=False, directed=False)

        # root
        nid = 0
        color = 'black'
        tree.add_node(nid, color=color, label='None')

        q = Queue()
        q.put((self.root, nid))
        while not q.empty():
            n, pid = q.get()
            for c in n.children:
                nid += 1
                q.put((c, nid))
                color = 'red' if c.is_ending_char is True else 'black'
                tree.add_node(nid, color=color, label=c.data)
                tree.add_edge(pid, nid)

        tree.graph_attr['epsilon'] = '0.01'
        tree.layout('dot')
        tree.draw(OUTPUT_PATH + img_name)
        return True 
开发者ID:wangzheng0822,项目名称:algo,代码行数:33,代码来源:trie_.py

示例15: draw_img

# 需要导入模块: import pygraphviz [as 别名]
# 或者: from pygraphviz import AGraph [as 别名]
def draw_img(self, img_name='Red_Black_Tree.png'):
        """
        画图
        用pygraphviz画出节点和箭头
        箭头的红色和黑色分别代表左和右
        :param img_name:
        :return:
        """
        if self.root is None:
            return

        tree = pgv.AGraph(directed=True, strict=True)

        q = Queue()
        q.put(self.root)

        while not q.empty():
            n = q.get()
            if n != self.black_leaf:  # 黑色叶子的连线由各个节点自己画
                tree.add_node(n.val, color=n.color)
                #  画父节点箭头
                # if n.parent is not None:
                #     tree.add_edge(n.val, n.parent.val)

                for c in [n.left, n.right]:
                    q.put(c)
                    color = 'red' if c == n.left else 'black'
                    if c != self.black_leaf:
                        tree.add_edge(n.val, c.val, color=color)
                    else:
                        tree.add_edge(n.val, 'None', color=color)

        tree.graph_attr['epsilon'] = '0.01'
        tree.layout('dot')
        tree.draw(OUTPUT_PATH + img_name)
        return True 
开发者ID:wangzheng0822,项目名称:algo,代码行数:38,代码来源:red_black_tree.py


注:本文中的pygraphviz.AGraph方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。