• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python networkx.to_pydot函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkx.to_pydot函数的典型用法代码示例。如果您正苦于以下问题:Python to_pydot函数的具体用法?Python to_pydot怎么用?Python to_pydot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: parse_tree

 def parse_tree(self, string, explicit=False, display=False):
     '''
     Returns graph representation of the equation tree of string,
     as a networkx graph. 
     If explicit is True, then '-x' -> '0-x'
     '''
     stack, indices = self.parse(string)
     tree = EquationTreeParser._create_tree(stack, indices)
    
     if explicit:
         idx = -1
         for node, data in tree.nodes(data=True):
             if data['label'] == '-' and len(tree[node]) == 1:
                 nbr = tree[node].keys()[0]
                 tree.remove_edge(node, nbr)
                 tree.add_node(idx, label='0')
                 tree.add_edge(node, idx, label='left')
                 tree.add_edge(node, nbr, label='right')
                 idx -= 1
     
     if display:
         _, image_path = tempfile.mkstemp()
         pydot_graph = nx.to_pydot(tree)
         pydot_graph.write_png(image_path)
         cv2.imshow('equation tree', cv2.imread(image_path))
         cv2.waitKey()
         cv2.destroyAllWindows()
         
     return tree
开发者ID:allenai,项目名称:EquationTree,代码行数:29,代码来源:equation_tree_parser.py


示例2: build_graph

 def build_graph(self, G):
     G.add_edge("A", "B")
     G.add_edge("A", "C")
     G.add_edge("B", "C")
     G.add_edge("A", "D")
     G.add_node("E")
     return G, nx.to_pydot(G)
开发者ID:rutsky,项目名称:networkx,代码行数:7,代码来源:test_pydot.py


示例3: neato_from_networkx

def neato_from_networkx( g, min_node_size = 0.5, max_node_size = 2.0, min_edge_width = 1.0, max_edge_width = 5.0, legend_attribute=None, label_nodes_directly = False ) :
    d = nx.to_pydot( g )
    d.set_overlap(False)
    # normalize node size
    nodewidths = array( [float(n.get_width()) for n in d.get_nodes()] )
    # done this way in case input has all the same size to avoid divide by zero
    node_range = (nodewidths.max() - nodewidths.min())/(max_node_size - min_node_size)
    for n in d.get_nodes() :
        n.set_width( min_node_size + (float(n.get_width()) - nodewidths.min()) / node_range )
        n.set_fixedsize( "true" )
        n.set_shape('circle')
    # normalize edge width
    edge_widths = array( [float(e.get_penwidth()) for e in d.get_edges()] )
    edge_width_range = (edge_widths.max() - edge_widths.min())/(max_edge_width - min_edge_width)
    for e in d.get_edges() :
        e.set_penwidth( min_edge_width + (float(e.get_penwidth()) - edge_widths.min() )/edge_width_range )
    # if the legend attribute is set, create a legend node
    if label_nodes_directly :
        if legend_attribute == None :
            legend_attribute = 'labelval'
        for n in d.get_nodes() :
            n.set_label( n.get_attributes()[legend_attribute] )
    else : 
        legend = pydot.Node( "legend" )
        nodelist = [n.get_label()+": "+n.get_attributes()[legend_attribute] for n in d.get_nodes()]
        nodelist.sort( lambda a,b : cmp( int( a.split(':')[0] ), int (b.split(':')[0] ) ))
        
        legend.set_label(  "\l".join([x for x in nodelist])+"\l" )
        legend.set_shape("box")
        d.add_node(legend)
    return d
开发者ID:vputz,项目名称:marion-biblio,代码行数:31,代码来源:wos_cooccurrence_graph.py


示例4: visualize_mcts_tree

def visualize_mcts_tree(mcts, depth, filename):
    """
    Creates a small subgraph for visualization with a
    number of levels equal to 2 + depth labelled with the
    MCTS values from mcts and saves it as filename.png
    """
    # Find root of the MCTS tree
    mcts_root = nx.topological_sort(mcts.digraph)[0]
    # root = GameState()
    subgraph = nx.DiGraph()

    # Don't include the empty board (the root) in the graphs
    # for first_move in mcts.digraph.successors(root):
    print(mcts_root)
    print(type(mcts_root))
    for first_move in mcts.digraph.successors(mcts_root):
        add_edges(mcts.digraph, subgraph, first_move, depth)

    dot_graph = nx.to_pydot(subgraph)
    for node in dot_graph.get_nodes():
        attr = node.get_attributes()
        try:
            node.set_label('{}{}/{}\n{:.2f}'.format(attr['state'],
                                                   int(attr['w']),
                                                   int(attr['n']),
                                                   float(attr['uct'])))
        except KeyError:
            pass

    dot_graph.set_graph_defaults(fontname='Courier')
    dot_graph.set_rankdir('LR')
    dot_graph.write_png('{}.png'.format(filename))
开发者ID:boruil,项目名称:Math381-Project2,代码行数:32,代码来源:visualization.py


示例5: pydot_checks

    def pydot_checks(self, G):
        G.add_edge('A','B')
        G.add_edge('A','C')
        G.add_edge('B','C')
        G.add_edge('A','D')
        G.add_node('E')
        P = nx.to_pydot(G)
        G2 = G.__class__(nx.from_pydot(P))
        assert_graphs_equal(G, G2)

        fname = tempfile.mktemp()
        assert_true( P.write_raw(fname) )

        Pin = pydotplus.graph_from_dot_file(fname)

        n1 = sorted([p.get_name() for p in P.get_node_list()])
        n2 = sorted([p.get_name() for p in Pin.get_node_list()])
        assert_true( n1 == n2 )

        e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()]
        e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]
        assert_true( sorted(e1)==sorted(e2) )

        Hin = nx.drawing.nx_pydot.read_dot(fname)
        Hin = G.__class__(Hin)
        assert_graphs_equal(G, Hin)
开发者ID:argriffing,项目名称:networkx,代码行数:26,代码来源:test_pydot.py


示例6: dump

    def dump(self, output=False):
        """Prints out network and returns networkx graph

        Prints the devices, links, and flows associated with the network, and
        returns a pydot object with the network graph.

        Parameters
        ----------
        output : boolean, optional
            Specifies whether to print the network information (the default is
            False).

        Returns
        -------
        pydot
            pydot object containing the network graph
        """

        # Print network information if output is True
        if output:
            print "Devices:\n"
            for device_id in self.devices:
                print self.devices[device_id]
            print "Links:\n"
            for link_id in self.links:
                print self.links[link_id]
            print "Flows:\n"
            for flow_id in self.flows:
                print self.flows[flow_id]

        # Convert the graph to a pydot object and return
        return nx.to_pydot(self.g)
开发者ID:BLQ-Software,项目名称:black-widow,代码行数:32,代码来源:network.py


示例7: get_dot

def get_dot(G_orig):
    """Change labels and colors to be presented with graphviz"""
    G = G_orig.copy()
    cluster_networks.relabel_graph(G)
    tr = {}
    for node in G.nodes_iter():
        tr[node] = '"{}"'.format(node)
    nx.relabel_nodes(G, tr, copy=False)
    for node in G.nodes_iter():
        label = str(node)
        if len(label) > MAX_LABEL:
            label = u'{}..."'.format(label[:MAX_LABEL])
        G.node[node]['label'] = label
    for node in cluster_networks.get_leaf_nodes(G):
        G.node[node]['color'] = "blue"
    for node in cluster_networks.hybrid_nodes(G):
        G.node[node]['color'] = "#7BFF74"  # light green
        G.node[node]['style'] = 'filled'
    for node in cluster_networks.get_root_nodes(G):
        G.node[node]['color'] = "orange"
    for node in cluster_networks.problematic_treechild_nodes(G):
        G.node[node]['color'] = "#FF77EB"  # light pink
        G.node[node]['style'] = 'filled'
    for u, v in cluster_networks.removable_edges(G):
        G.edge[u][v]['color'] = "red"
    for root in cluster_networks.get_root_nodes(G):
        G.node[root]['label'] = '"R"'
    dot = nx.to_pydot(G).to_string()
    return dot.strip()
开发者ID:paurullan,项目名称:phylonets,代码行数:29,代码来源:web.py


示例8: _graph2pydot

def _graph2pydot(graph, wrap=10, tikz=False,
                 rankdir='TB'):
    """Convert (possibly labeled) state graph to dot str.
    
    @type graph: L{LabeledDiGraph}
    
    @rtype: str
    """
    pydot = import_pydot()
    if pydot is None:
        return None
    
    dummy_nx_graph = nx.MultiDiGraph()
    
    _states2dot_str(graph, dummy_nx_graph, wrap=wrap, tikz=tikz,
                    rankdir=rankdir)
    _transitions2dot_str(graph.transitions, dummy_nx_graph, tikz=tikz)
    
    pydot_graph = nx.to_pydot(dummy_nx_graph)
    _place_initial_states(graph, pydot_graph, tikz)
    
    pydot_graph.set_overlap('false')
    #pydot_graph.set_size('"0.25,1"')
    #pydot_graph.set_ratio('"compress"')
    pydot_graph.set_nodesep(0.5)
    pydot_graph.set_ranksep(0.1)
    
    return pydot_graph
开发者ID:iamkaushik5,项目名称:tulip-control-1,代码行数:28,代码来源:graph2dot.py


示例9: build_graph

 def build_graph(self, G):
     G.add_edge('A','B')
     G.add_edge('A','C')
     G.add_edge('B','C')
     G.add_edge('A','D')
     G.add_node('E')
     return G, nx.to_pydot(G)
开发者ID:JaneliaSciComp,项目名称:Neuroptikon,代码行数:7,代码来源:test_pydot.py


示例10: dot_graph

def dot_graph(filename='conversions'):
    # Edges from Convert
    dg = nx.DiGraph()
    for a, b in convert.graph.edges():
        cost = convert.graph.edge[a][b]['cost']
        dg.add_edge(cls_name(a), cls_name(b),
                    cost=cost,
                    penwidth=max(log(1./(cost + 0.06)), 1))


    # Edges from Append
    for a, b in append.funcs:
        if b is not object and a != b:
            dg.add_edge(cls_name(b), cls_name(a), color='blue')


    # Color edges
    for n in convert.graph.nodes() + list(pluck(0, append.funcs)):
        if issubclass(n, tuple(ooc_types)):
            dg.node[cls_name(n)]['color'] = 'red'

    # Convert to pydot
    p = nx.to_pydot(dg)

    p.set_overlap(False)
    p.set_splines(True)

    with open(filename + '.dot', 'w') as f:
        f.write(p.to_string())

    os.system('neato -Tpdf %s.dot -o %s.pdf' % (filename, filename))
    print("Writing graph to %s.pdf" % filename)
    os.system('neato -Tpng %s.dot -o %s.png' % (filename, filename))
    print("Writing graph to %s.png" % filename)
开发者ID:CaptainAL,项目名称:Spyder,代码行数:34,代码来源:dot.py


示例11: drawGraph

 def drawGraph(self, key=None, filename="graph", format="pdf"):
     graph = self.graphs.get(key)
     if( not graph ):
         return
     if( graph.number_of_nodes() > 1 ):
         ag = nx.to_pydot(graph)
         ag.write("%s.%s"%(filename,format),format=format)
开发者ID:Adhra,项目名称:negex,代码行数:7,代码来源:pycontextNX.py


示例12: to_pydot

    def to_pydot(self, detailed=False):
        """Create GraphViz dot string from given AST.

        @type ast: L{ASTNode}
        @rtype: str
        """
        g = ast_to_labeled_graph(self, detailed)
        return nx.to_pydot(g)
开发者ID:iamkaushik5,项目名称:tulip-control-1,代码行数:8,代码来源:transformation.py


示例13: graph

 def graph(self, out_file=None):
     if out_file is None:
         doc_dir = self.config["dir"].get("doc")
         out_file = os.path.join(doc_dir, "pipeline_viz.png")
     if file_exists(out_file):
         return out_file
     pd = nx.to_pydot(self.dag)
     pd.write_png(out_file, prog="dot")
开发者ID:jnhutchinson,项目名称:bipy,代码行数:8,代码来源:__init__.py


示例14: plotGraph

 def plotGraph(self):
     cntxt = self.context["disease"]
     g = cntxt.getDocumentGraph()
     ag = nx.to_pydot(g, strict=True)
     gfile = os.path.join(self.save_dir,
                          "report_%s_unc%s_%s_critical.pdf"%(self.proc_category,
                                                             self.allow_uncertainty,
                                                       self.currentCase))
     ag.write(gfile,format="pdf")
开发者ID:DBMI,项目名称:NLP,代码行数:9,代码来源:criticalFinderGraph.py


示例15: write_networkx_to_dot

def write_networkx_to_dot(dg, filename='mydask'):
    import os
    p = nx.to_pydot(dg)
    p.set_rankdir('BT')
    with open(filename + '.dot', 'w') as f:
        f.write(p.to_string())

    os.system('dot -Tpdf %s.dot -o %s.pdf' % (filename, filename))
    os.system('dot -Tpng %s.dot -o %s.png' % (filename, filename))
    print("Writing graph to %s.pdf" % filename)
开发者ID:kastnerkyle,项目名称:dask,代码行数:10,代码来源:dot.py


示例16: write_dot

def write_dot(G, path):
    # requires graphviz, pygraphviz, pydot
    g = nx.to_pydot(G)
    for n in g.get_nodes():
        n.set_label(G.node_labels[int(n.get_name())])
    for e in g.get_edges():
        key = (int(e.get_destination()), int(e.get_source()))
        s = '\\n'.join(list(str(x) for x in G.edge_labels[key]))
        e.set_label(s)
    g.write_dot(path)
开发者ID:ryanraaum,项目名称:oldowan.mitotype,代码行数:10,代码来源:network.py


示例17: compare_graph_network

    def compare_graph_network(self, goldnet, filename, topn=None):
      import networkx as nx
      #import Image as im
      import matplotlib as plt
      import pylab as P
      import pydot
      G = nx.DiGraph()

      net = self
      if topn != None:
        net = self.copy()
        net.set_top_edges_percent(topn)

      # Add all of the nodes
      for gene in net.network.keys():
        G.add_node(gene)

      Gp = nx.to_pydot(G)

      if goldnet == []:
        for gene1 in net.network.keys():
            for gene2 in net.network.keys():
                if net.network[gene1][gene2] != 0:
                    Gp.add_edge(pydot.Edge(gene1, gene2, style="bold"))
      else:
          for gene1 in net.network.keys():
            for gene2 in net.network.keys():
              # Figure out of node is correct, apply color/style based on that
              # If true positive, bold line
              if net.network[gene1][gene2] != 0 and goldnet.network[gene1][gene2] != 0:
                # thick line
                Gp.add_edge(pydot.Edge(gene1, gene2, style="bold"))

              # If false positive, dashed line
              elif net.network[gene1][gene2] != 0 and goldnet.network[gene1][gene2] == 0:
                Gp.add_edge(pydot.Edge(gene1, gene2, style="dashed"))

              # If false negative, dotted line
              elif net.network[gene1][gene2] == 0 and goldnet.network[gene1][gene2] != 0:
                Gp.add_edge(pydot.Edge(gene1, gene2, style="dotted"))

      # now output your graph to a file and display it
      outstem = filename
      dot = pydot.Dot(Gp)
      Gp.set_size('18!')
      Gp.set_rankdir('RL')
      Gp.set_page('20')
      Gp.set_ranksep(0.5)
      Gp.set_nodesep(0.25)
      #Gp.write_pdf(outstem + '_dot.pdf', prog='dot')  # writes Gp to png file #use
      #Gp.write_pdf(outstem + '_neato.pdf', prog='neato')  # writes Gp to png file #use
      #Gp.write_pdf(outstem + '_fdp.pdf', prog='fdp')  # writes Gp to png file #use
      #Gp.write_pdf(outstem + '_twopi.pdf', prog='twopi')  # writes Gp to png file #use
      Gp.write_pdf(outstem + '_circo.pdf', prog='circo')  # writes Gp to png file #use
开发者ID:njouba1352,项目名称:Network-Inference-Workspace,代码行数:54,代码来源:Network.py


示例18: show_pydot

def show_pydot(g):
    """
    Display a networkx graph using pydot.
    """
    
    fd = tempfile.NamedTemporaryFile()
    fd.close()
    p = nx.to_pydot(g)
    p.write_jpg(fd.name)
    imdisp(fd.name)
    os.remove(fd.name)
开发者ID:CEPBEP,项目名称:neurokernel,代码行数:11,代码来源:plot.py


示例19: layer_dag_to_svg

def layer_dag_to_svg():
    model = get_model()
    graph = nx.DiGraph()
    for layer in model.layers:
        graph.add_node(layer["name"], layer_attributes=layer)
    for layer in model.layers:
        for inputLayer in layer.get("inputs", []):
            graph.add_edge(model.layers[inputLayer]["name"], layer["name"], label=model.layers[inputLayer]["outputs"])
    pydot_graph = nx.to_pydot(graph)
    pydot_graph.set_rankdir("LR")
    svg = pydot_graph.create_svg(prog="dot")
    return Response(svg, mimetype="image/svg+xml")
开发者ID:scauhua,项目名称:deepViz,代码行数:12,代码来源:views.py


示例20: print_ascii_graph

def print_ascii_graph(model_):
    """
    pip install img2txt.py

    python -c
    """
    from PIL import Image
    from six.moves import StringIO
    #import networkx as netx
    import copy
    model = copy.deepcopy(model_)
    assert model is not model_
    # model.graph.setdefault('graph', {})['size'] = '".4,.4"'
    model.graph.setdefault('graph', {})['size'] = '".3,.3"'
    model.graph.setdefault('graph', {})['height'] = '".3,.3"'
    pydot_graph = netx.to_pydot(model)
    png_str = pydot_graph.create_png(prog='dot')
    sio = StringIO()
    sio.write(png_str)
    sio.seek(0)
    pil_img = Image.open(sio)
    print('pil_img.size = %r' % (pil_img.size,))
    #def print_ascii_image(pil_img):
    #    img2txt = ut.import_module_from_fpath('/home/joncrall/venv/bin/img2txt.py')
    #    import sys
    #    pixel = pil_img.load()
    #    width, height = pil_img.size
    #    bgcolor = None
    #    #fill_string =
    #    img2txt.getANSIbgstring_for_ANSIcolor(img2txt.getANSIcolor_for_rgb(bgcolor))
    #    fill_string = "\x1b[49m"
    #    fill_string += "\x1b[K"          # does not move the cursor
    #    sys.stdout.write(fill_string)
    #    img_ansii_str = img2txt.generate_ANSI_from_pixels(pixel, width, height, bgcolor)
    #    sys.stdout.write(img_ansii_str)
    def print_ascii_image(pil_img):
        #https://gist.github.com/cdiener/10491632
        SC = 1.0
        GCF = 1.0
        WCF = 1.0
        img = pil_img
        S = (int(round(img.size[0] * SC * WCF * 3)), int(round(img.size[1] * SC)))
        img = np.sum( np.asarray( img.resize(S) ), axis=2)
        print('img.shape = %r' % (img.shape,))
        img -= img.min()
        chars = np.asarray(list(' .,:;irsXA253hMHGS#9B&@'))
        img = (1.0 - img / img.max()) ** GCF * (chars.size - 1)
        print( "\n".join( ("".join(r) for r in chars[img.astype(int)]) ) )
    print_ascii_image(pil_img)
    pil_img.close()
    pass
开发者ID:heroinlin,项目名称:ibeis,代码行数:51,代码来源:pgm_viz.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.to_scipy_sparse_matrix函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.to_numpy_matrix函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap