Python networkx 模块,write_gml() 实例源码

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

项目:taikutsu_blog_works    作者:hokekiyoo    | 项目源码 | 文件源码
def graph_visualize(G, args):
    import networkx as nx
    import numpy as np
    # ???????????????????????????
    pos = nx.spring_layout(G)
    # ?????? ????????????????????
    plt.figure()
    nx.draw_networkx(G, pos, with_labels=False, alpha=0.4,font_size=0.0,node_size=10) 
    plt.savefig(args.directory+"/graph/graph.png")
    nx.write_gml(G, args.directory+"/graph/graph.gml")
    # ??????
    plt.figure() 
    degree_sequence=sorted(nx.degree(G).values(),reverse=True) 
    dmax=max(degree_sequence) 
    dmin =min(degree_sequence)
    kukan=range(0,dmax+2) 
    hist, kukan=np.histogram(degree_sequence,kukan)
    plt.plot(hist,"o-")
    plt.xlabel('degree') 
    plt.ylabel('frequency')
    plt.grid()
    plt.savefig(args.directory+'/graph/degree_hist.png')
项目:PBSuite    作者:dbrowneup    | 项目源码 | 文件源码
def run(self):
        logging.info("Grabbing Filling Metrics")
        self.metricsCollector()
        logging.info("Loading Reference")
        self.loadReference()
        logging.info("Removing Poorly Supported Edges")
        self.cleanGraph()
        logging.info("Outputting new contigs")
        self.outputContigs()
        logging.info("Finished!")
        #g = nx.Graph()
        #for i in self.subGraphs:
            #for n in i.nodes():
                #g.add_node(n)
            #for e in i.edges():
                #g.add_edge(*e)
        #nx.write_gml(g,"output.gml")
项目:PBSuite    作者:dbrowneup    | 项目源码 | 文件源码
def run(self):
        logging.info("Grabbing Filling Metrics")
        self.metricsCollector()
        logging.info("Loading Reference")
        self.loadReference()
        logging.info("Removing Poorly Supported Edges")
        self.cleanGraph()
        logging.info("Outputting new contigs")
        self.outputContigs()
        logging.info("Finished!")
        #g = nx.Graph()
        #for i in self.subGraphs:
            #for n in i.nodes():
                #g.add_node(n)
            #for e in i.edges():
                #g.add_edge(*e)
        #nx.write_gml(g,"output.gml")
项目:gtool    作者:gtoolframework    | 项目源码 | 文件源码
def __output__(self, projectstructure, output=None):

        _graphoutput = super(Directedgraph, self).__output__(projectstructure)

        if output is None:
            raise ValueError('output file be specified for Multipgraph output')
        else:
            networkx.write_gml(_graphoutput, output)
            return True  # TODO inconsistent return json object vs true
项目:taikutsu_blog_works    作者:hokekiyoo    | 项目源码 | 文件源码
def visualize(G, savename, savegml):
    pos = nx.spring_layout(G) # ???????????????????????????
    nx.draw(G, pos, with_labels=True,alpha=0.3,font_size=0.0,node_size=10) # ?????? ????????????????????
    plt.savefig(savename+".png")
    plt.show()
    if savegml:
        nx.write_gml(G,savename+".gml")
项目:maple    作者:Zhengzi    | 项目源码 | 文件源码
def merge_node(path,new_path):
    g = nx.read_gml(path)
    nodes = [n for n,d in g.out_degree().items() if d==1]
    for node in nodes:
        if not node in g.nodes():
            continue

        if g.in_degree(node) != 1:
            continue    
        p = g.successors(node)
        #print p
        #dict = g.in_degree(p)
        #print dict[p]
        #print g.in_degree(p)[p[0]]
        if g.in_degree(p)[p[0]] == 1:
            text1 = g.node[node]["text"]
            text1 = remove_last_jump(text1)
            text2 = g.node[p[0]]["text"]

            #print text1
            #print text2

            new_text = text1 + ',' + text2
            #print new_text

            nns = g.successors(p[0])
            g.node[node]["text"] = new_text

            for n in nns:
                g.add_edge(node, n)
            g.remove_node(p[0])
    nx.write_gml(g, new_path)
    return nx.number_of_nodes(g)
项目:bioconda-utils    作者:bioconda    | 项目源码 | 文件源码
def dag(recipe_folder, config, packages="*", format='gml', hide_singletons=False):
    """
    Export the DAG of packages to a graph format file for visualization
    """
    dag, name2recipes = utils.get_dag(utils.get_recipes(recipe_folder, packages), config)
    if hide_singletons:
        for node in nx.nodes(dag):
            if dag.degree(node) == 0:
                dag.remove_node(node)
    if format == 'gml':
        nx.write_gml(dag, sys.stdout.buffer)
    elif format == 'dot':
        write_dot(dag, sys.stdout)
    elif format == 'txt':
        subdags = sorted(map(sorted, nx.connected_components(dag.to_undirected())))
        subdags = sorted(subdags, key=len, reverse=True)
        singletons = []
        for i, s in enumerate(subdags):
            if len(s) == 1:
                singletons += s
                continue
            print("# subdag {0}".format(i))
            subdag = dag.subgraph(s)
            recipes = [
                recipe for package in nx.topological_sort(subdag)
                for recipe in name2recipes[package]]
            print('\n'.join(recipes) + '\n')
        if not hide_singletons:
            print('# singletons')
            recipes = [recipe for package in singletons for recipe in
                       name2recipes[package]]
            print('\n'.join(recipes) + '\n')
项目:maple    作者:Zhengzi    | 项目源码 | 文件源码
def extract_intra_function_cfg(name):
    for seg in Segments():  
        if SegName(seg) == ".text":

            #functions = Functions(seg)     
            #for func_ea in functions:      
            func_ea = here()

            cfg = nx.DiGraph()
            tmp_bbs = []

            #flag FC_PREDS is to get the backward info 
            for bb in FlowChart(get_func(func_ea), flags=FC_PREDS):

                #check if we have already met this bb
                flag = True
                for tmp_bb in tmp_bbs:
                    if tmp_bb.startEA == bb.startEA:
                        bb = tmp_bb
                        flag = False
                if flag:
                    tmp_bbs.append(bb)

                cfg.add_node(bb.startEA)

                preds = bb.preds()
                succs = bb.succs()

                if preds:
                    for preds_block in preds:

                        #check if we have already met this bb
                        flag = True
                        for tmp_bb in tmp_bbs:
                            if tmp_bb.startEA == preds_block.startEA:
                                preds_block = tmp_bb
                                flag = False
                        if flag:
                            tmp_bbs.append(preds_block)

                        cfg.add_edge(preds_block.startEA, bb.startEA)

                if succs:
                    for succs_block in preds:

                        #check if we have already met this bb
                        flag = True
                        for tmp_bb in tmp_bbs:
                            if tmp_bb.startEA == succs_block.startEA:
                                succs_block = tmp_bb
                                flag = False
                        if flag:
                            tmp_bbs.append(succs_block)

                        cfg.add_edge(bb.startEA, succs_block.startEA)
    nx.write_gml(cfg, "C:\\Users\\Xu Zhengzi\\Desktop\\tt\\second.gml")
    return cfg
项目:k-clique-graphs-dense-subgraphs    作者:giannisnik    | 项目源码 | 文件源码
def read_gml(path, relabel=False):
    """Read graph in GML format from path.

    Parameters
    ----------
    path : filename or filehandle
       The filename or filehandle to read from.

    relabel : bool, optional
       If True use the GML node label attribute for node names otherwise use
       the node id.

    Returns
    -------
    G : MultiGraph or MultiDiGraph

    Raises
    ------
    ImportError
        If the pyparsing module is not available.

    See Also
    --------
    write_gml, parse_gml

    Notes
    -----
    Requires pyparsing: http://pyparsing.wikispaces.com/
    The GML specification says that files should be ASCII encoded, with any
    extended ASCII characters (iso8859-1) appearing as HTML character entities.

    References
    ----------
    GML specification:
    http://www.infosun.fim.uni-passau.de/Graphlet/GML/gml-tr.html

    Examples
    --------
    >>> G=nx.path_graph(4)
    >>> nx.write_gml(G,'test.gml')
    >>> H=nx.read_gml('test.gml')
    """
    lines = (unescape(line.decode('ascii')) for line in path)
    G = parse_gml(lines, relabel=relabel)
    return G
项目:k-clique-graphs-dense-subgraphs    作者:giannisnik    | 项目源码 | 文件源码
def pyparse_gml():
    """A pyparsing tokenizer for GML graph format.

    This is not intended to be called directly.

    See Also
    --------
    write_gml, read_gml, parse_gml
    """
    try:
        from pyparsing import \
             Literal, CaselessLiteral, Word, Forward,\
             ZeroOrMore, Group, Dict, Optional, Combine,\
             ParseException, restOfLine, White, alphas, alphanums, nums,\
             OneOrMore,quotedString,removeQuotes,dblQuotedString, Regex
    except ImportError:
        try:
            from matplotlib.pyparsing import \
             Literal, CaselessLiteral, Word, Forward,\
             ZeroOrMore, Group, Dict, Optional, Combine,\
             ParseException, restOfLine, White, alphas, alphanums, nums,\
             OneOrMore,quotedString,removeQuotes,dblQuotedString, Regex
        except:
            raise ImportError('pyparsing not found',
                              'http://pyparsing.wikispaces.com/')

    lbrack = Literal("[").suppress()
    rbrack = Literal("]").suppress()
    pound = ("#")
    comment = pound + Optional( restOfLine )
    integer = Word(nums+'-').setParseAction(lambda s,l,t:[ int(t[0])])
    real = Regex(r"[+-]?\d+\.\d*([eE][+-]?\d+)?").setParseAction(
        lambda s,l,t:[ float(t[0]) ])
    dblQuotedString.setParseAction( removeQuotes )
    key = Word(alphas,alphanums+'_')
    value_atom = (real | integer | Word(alphanums) | dblQuotedString)
    value = Forward()   # to be defined later with << operator
    keyvalue = Group(key+value)
    value << (value_atom | Group( lbrack + ZeroOrMore(keyvalue) + rbrack ))
    node = Group(Literal("node") + lbrack + Group(OneOrMore(keyvalue)) + rbrack)
    edge = Group(Literal("edge") + lbrack + Group(OneOrMore(keyvalue)) + rbrack)

    creator = Group(Literal("Creator")+ Optional( restOfLine ))
    version = Group(Literal("Version")+ Optional( restOfLine ))
    graphkey = Literal("graph").suppress()

    graph = Dict (Optional(creator)+Optional(version)+\
        graphkey + lbrack + ZeroOrMore( (node|edge|keyvalue) ) + rbrack )
    graph.ignore(comment)

    return graph
项目:k-clique-graphs-dense-subgraphs    作者:giannisnik    | 项目源码 | 文件源码
def write_gml(G, path):
    """
    Write the graph G in GML format to the file or file handle path.

    Parameters
    ----------
    path : filename or filehandle
       The filename or filehandle to write.  Filenames ending in
       .gz or .gz2 will be compressed.

    See Also
    --------
    read_gml, parse_gml

    Notes
    -----
    GML specifications indicate that the file should only use
    7bit ASCII text encoding.iso8859-1 (latin-1).

    This implementation does not support all Python data types as GML
    data.  Nodes, node attributes, edge attributes, and graph
    attributes must be either dictionaries or single stings or
    numbers.  If they are not an attempt is made to represent them as
    strings.  For example, a list as edge data
    G[1][2]['somedata']=[1,2,3], will be represented in the GML file
    as::

       edge [
         source 1
         target 2
         somedata "[1, 2, 3]"
       ]


    Examples
    ---------
    >>> G=nx.path_graph(4)
    >>> nx.write_gml(G,"test.gml")

    Filenames ending in .gz or .bz2 will be compressed.

    >>> nx.write_gml(G,"test.gml.gz")
    """
    for line in generate_gml(G):
        line += '\n'
        path.write(line.encode('ascii', 'xmlcharrefreplace'))


# fixture for nose tests