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

Python networkx.generate_gml函数代码示例

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

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



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

示例1: test_data_types

 def test_data_types(self):
     data = [True, False, 10 ** 20, -2e33, "'", '"&&&""',
             [{(b'\xfd',): '\x7f', unichr(0x4444): (1, 2)}, (2, "3")]]
     try:
         data.append(unichr(0x14444))  # fails under IronPython
     except ValueError:
         data.append(unichr(0x1444))
     try:
         data.append(literal_eval('{2.3j, 1 - 2.3j, ()}'))  # fails under Python 2.7
     except ValueError:
         data.append([2.3j, 1 - 2.3j, ()])
     G = nx.Graph()
     G.name = data
     G.graph['data'] = data
     G.add_node(0, int=-1, data=dict(data=data))
     G.add_edge(0, 0, float=-2.5, data=data)
     gml = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer))
     G = nx.parse_gml(gml, destringizer=literal_destringizer)
     assert_equal(data, G.name)
     assert_equal({'name': data, unicode('data'): data}, G.graph)
     assert_equal(list(G.nodes(data=True)),
                  [(0, dict(int=-1, data=dict(data=data)))])
     assert_equal(list(G.edges(data=True)), [(0, 0, dict(float=-2.5, data=data))])
     G = nx.Graph()
     G.graph['data'] = 'frozenset([1, 2, 3])'
     G = nx.parse_gml(nx.generate_gml(G), destringizer=literal_eval)
     assert_equal(G.graph['data'], 'frozenset([1, 2, 3])')
开发者ID:jklaise,项目名称:networkx,代码行数:27,代码来源:test_gml.py


示例2: ato_write_gml

def ato_write_gml(graph, fileName, labelGraphics):
    def writeDict(gml, key, label, contents, space, labelGraphics=None):
        gml.write('{1}{0} [\n'.format(key, space))
        for subKey in contents:
            if type(contents[subKey]) in [str]:
                gml.write('{2}\t{0} "{1}"\n'.format(subKey, contents[subKey], space))
            elif type(contents[subKey]) in [int]:
                gml.write('{2}\t{0} {1}\n'.format(subKey, contents[subKey], space))
            elif type(contents[subKey]) in [dict]:
                writeDict(gml, subKey, subKey, contents[subKey], space + '\t')
            if labelGraphics and label in labelGraphics:
                for labelInstance in labelGraphics[label]:
                    writeDict(gml, 'LabelGraphics', 'LabelGraphics', labelInstance, space + '\t')
        gml.write('{0}]\n'.format(space))

    gml = StringIO.StringIO()
    gml.write('graph [\n')
    gml.write('\tdirected 1\n')
    for node in graph.node:

        writeDict(gml, 'node', node, graph.node[node], '\t', labelGraphics)

    flag = False
    for x in nx.generate_gml(graph):
        if 'edge' in x and not flag:
            flag = True
        if flag:
            gml.write(x + '\n')
            

    #gml.write(']\n')
    with open(fileName, 'w') as f:
        f.write(gml.getvalue())
    nx.read_gml(fileName)
开发者ID:jjtapia,项目名称:atomizer,代码行数:34,代码来源:stdgraph.py


示例3: test_graph_types

    def test_graph_types(self):
        for directed in [None, False, True]:
            for multigraph in [None, False, True]:
                gml = 'graph ['
                if directed is not None:
                    gml += ' directed ' + str(int(directed))
                if multigraph is not None:
                    gml += ' multigraph ' + str(int(multigraph))
                gml += ' node [ id 0 label "0" ]'
                gml += ' edge [ source 0 target 0 ]'
                gml += ' ]'
                G = nx.parse_gml(gml)
                assert_equal(bool(directed), G.is_directed())
                assert_equal(bool(multigraph), G.is_multigraph())
                gml = 'graph [\n'
                if directed is True:
                    gml += '  directed 1\n'
                if multigraph is True:
                    gml += '  multigraph 1\n'
                gml += """  node [
    id 0
    label "0"
  ]
  edge [
    source 0
    target 0
"""
                if multigraph:
                    gml += '    key 0\n'
                gml += '  ]\n]'
                assert_equal(gml, '\n'.join(nx.generate_gml(G)))
开发者ID:jklaise,项目名称:networkx,代码行数:31,代码来源:test_gml.py


示例4: generateGraph

    def generateGraph(self, ticket, bnglContents, graphtype):
        print ticket
        pointer = tempfile.mkstemp(suffix='.bngl', text=True)
        with open(pointer[1], 'w') as f:
            f.write(bnglContents)
        try:
            if graphtype in ['regulatory', 'contactmap']:
                consoleCommands.setBngExecutable(bngDistro)
                consoleCommands.generateGraph(pointer[1], graphtype)
                name = pointer[1].split('.')[0].split('/')[-1]
                with open('{0}_{1}.gml'.format(name, graphtype), 'r') as f:
                    graphContent = f.read()

                gml = networkx.read_gml('{0}_{1}.gml'.format(name, graphtype))
                result = gml2cyjson(gml, graphtype=graphtype)
                jsonStr = json.dumps(result, indent=1, separators=(',', ': '))

                result = {'jsonStr': jsonStr, 'gmlStr': graphContent}
                self.addToDict(ticket, result)
                os.remove('{0}_{1}.gml'.format(name, graphtype))
                print 'success', ticket

            elif graphtype in ['sbgn_er']:
                consoleCommands.setBngExecutable(bngDistro)
                consoleCommands.generateGraph(pointer[1], 'contactmap')
                name = pointer[1].split('.')[0].split('/')[-1]
                # with open('{0}_{1}.gml'.format(name,'contactmap'),'r') as f:
                #   graphContent = f.read()
                graphContent = networkx.read_gml(
                    '{0}_{1}.gml'.format(name, 'contactmap'))
                sbgn = libsbgn.createSBNG_ER_gml(graphContent)
                self.addToDict(ticket, sbgn)
                os.remove('{0}_{1}.gml'.format(name, 'contactmap'))
                print 'success', ticket
            elif graphtype in ['std']:
                consoleCommands.setBngExecutable(bngDistro)
                consoleCommands.bngl2xml(pointer[1])
                xmlFileName = pointer[1].split('.')[0] + '.xml'
                xmlFileName = xmlFileName.split(os.sep)[-1]

                graph = stdgraph.generateSTDGML(xmlFileName)
                gmlGraph = networkx.generate_gml(graph)


                #os.remove('{0}.gml'.format(xmlFileName))
                result = gml2cyjson(graph, graphtype=graphtype)
                jsonStr = json.dumps(result, indent=1, separators=(',', ': '))

                result = {'jsonStr': jsonStr, 'gmlStr': ''.join(gmlGraph)}

                #self.addToDict(ticket, ''.join(gmlGraph))
                self.addToDict(ticket, result)
                print 'success', ticket
        except:
            import traceback
            traceback.print_exc()
            self.addToDict(ticket,-5)
            print 'failure',ticket
        finally:
            task.deferLater(reactor, 600,  freeQueue, ticket)
开发者ID:RuleWorld,项目名称:atomizer,代码行数:60,代码来源:twistedServer.py


示例5: main

def main():
    if len(sys.argv) != 3:
        sys.stderr.write('Usage: %s /path/to/flavornet.txt output.gml\n'.format(sys.argv[0]))
        sys.exit(1)

    ingredient2compounds, compound2ingredients = load_data(sys.argv[1])
    graph = generate_graph(ingredient2compounds, compound2ingredients)

    with open(sys.argv[2], 'w') as f:
        for line in nx.generate_gml(graph):
            f.write('{}\n'.format(line))
开发者ID:mrorii,项目名称:foodpairing,代码行数:11,代码来源:generate_gml.py


示例6: test_escape_unescape

    def test_escape_unescape(self):
        gml = """graph [
  name "&"䑄��&unknown;"
]"""
        G = nx.parse_gml(gml)
        assert_equal(
            '&"\x0f' + unichr(0x4444) + '��&unknown;',
            G.name)
        gml = '\n'.join(nx.generate_gml(G))
        assert_equal("""graph [
  name "&"䑄��&unknown;"
]""", gml)
开发者ID:jklaise,项目名称:networkx,代码行数:12,代码来源:test_gml.py


示例7: test_labels_are_strings

    def test_labels_are_strings(self):
        # GML requires labels to be strings (i.e., in quotes)
        answer = """graph [
  node [
    id 0
    label "1203"
  ]
]"""
        G = nx.Graph()
        G.add_node(1203)
        data = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer))
        assert_equal(data, answer)
开发者ID:jklaise,项目名称:networkx,代码行数:12,代码来源:test_gml.py


示例8: exportToGML

def exportToGML(n, e) :
    
    G=nx.Graph()
    
    #for node in n :
        #G.add_node(node[0], frequency=node[1])
        
    G.add_nodes_from(n)
    G.add_edges_from(e)
    print len(G.edges())
    
    graph = nx.generate_gml(G)
    print graph
    
    nx.write_gml(G, dir + output)
开发者ID:herlifeinpixels,项目名称:ExpertiseMapper,代码行数:15,代码来源:association.py


示例9: set_graph_digest

    def set_graph_digest(self):
        """
        Hashes graph structure with ornamentation
        :return:
        """
        g_gml = nx.generate_gml(self.graph)
        #g_string = self.get_gml_str()
        g_string = self.get_graph_str()
        #g_string = 'twas brillig'
        self.g_string = g_string

        g_hash = self.hash_method(g_string)
        self.g_hash = g_hash                # Move these onto nodes attributes?
        self.g_digest = g_hash.hexdigest()     # Move these node attributes?
        return g_hash.hexdigest()
开发者ID:rastapavel,项目名称:csm,代码行数:15,代码来源:cryptostatemachine.py


示例10: download_cmtys

def download_cmtys(request, ds, did, cd, cdname, layer, format):
    fname_requested = format
    format = format.rsplit('.')[-1]

    fname = '%s-%s%s.%s'%(os.path.basename(ds.netfile.name), cdname, layer, format)
    if fname_requested != fname:
        return redirect(download_cmtys, did=did, cdname=cdname, layer=layer,
                        format=fname)

    cmtys = cd.get_results()[layer]

    data = [ ]
    content_type = 'text/plain'
    force_download = False
    if format == 'txt':
        for cname, cnodes in cmtys.iteritems():
            data.append(' '.join(str(x) for x in cnodes))
        data = '\n'.join(data)
    elif format == 'nc':
        for cname, cnodes in cmtys.iteritems():
            for node in cnodes:
                data.append('%s %s'%(node, cname))
        data = '\n'.join(data)
    elif format == 'gexf':
        g = ds.get_networkx()
        for node, cs in cmtys.nodecmtys().iteritems():
            g.node[node]['cmty'] = ' '.join(str(x) for x in cs)
        data = nx.generate_gexf(g)
        data = '\n'.join(data)
    elif format == 'gml':
        g = ds.get_networkx()
        for node, cs in cmtys.nodecmtys().iteritems():
            g.node[node]['cmty'] = ','.join(str(x) for x in cs)
        data = nx.generate_gml(g)
        data = '\n'.join(data)

    response = HttpResponse(content=data, content_type=content_type, )
    # If the data size is too big, force a download instead of viewing as text.
    if force_download or len(data) > 50 * 2**10:
        response['Content-Disposition'] = 'attachment; filename=%s'%fname
    return response
开发者ID:rkdarst,项目名称:jako,代码行数:41,代码来源:views.py


示例11: test_tuplelabels

    def test_tuplelabels(self):
        # https://github.com/networkx/networkx/pull/1048
        # Writing tuple labels to GML failed.
        G = nx.OrderedGraph()
        G.add_edge((0, 1), (1, 0))
        data = '\n'.join(nx.generate_gml(G, stringizer=literal_stringizer))
        answer = """graph [
  node [
    id 0
    label "(0,1)"
  ]
  node [
    id 1
    label "(1,0)"
  ]
  edge [
    source 0
    target 1
  ]
]"""
        assert_equal(data, answer)
开发者ID:jklaise,项目名称:networkx,代码行数:21,代码来源:test_gml.py


示例12: test_bool

    def test_bool(self):
        G=networkx.Graph()
        G.add_node(1,on=True)
        G.add_edge(1,2,on=False)
        data = '\n'.join(list(networkx.generate_gml(G)))
        answer ="""graph [
  node [
    id 0
    label "1"
    on 1
  ]
  node [
    id 1
    label "2"
  ]
  edge [
    source 0
    target 1
    on 0
  ]
]"""
        assert_equal(data,answer)
开发者ID:CallaJun,项目名称:hackprince,代码行数:22,代码来源:test_gml.py


示例13: getWholeGraph

def getWholeGraph():
    str1 = ''.join(nx.generate_gml(G))
    return str1
开发者ID:rgentryIII,项目名称:FinalProject,代码行数:3,代码来源:testMasterNode.py


示例14: save

 def save(self, graph):
     with self.fname.open('w') as fp:
         fp.write('\n'.join(html.unescape(line) for line in nx.generate_gml(graph)))
     return self.fname
开发者ID:clics,项目名称:clics-data,代码行数:4,代码来源:models.py


示例15: normalize

        pass
    else:
        g.add_node(target, **gml.vs[edge.target].attributes())
    g.add_edge(source,target,**edge.attributes())


def normalize(freqA, freqB, weight):
    """
    Normalize edge weights following Dellert's proposal.
    """

    return weight ** 2 / (freqA + freqB - weight)

for nA, nB, data in list(g.edges(data=True)):

    w = data['families']
    fA = occs[g.node[nA]['key']]
    fB = occs[g.node[nB]['key']]

    nw = normalize(fA, fB, w)
    if nw > 0:
        data['normalized_weight'] = nw * 100
    else:
        g.remove_edge(nA, nB)

with open('output/clics_b.gml', 'w') as f:
    for line in nx.generate_gml(g):
        f.write(line+'\n')
#nx.write_gml(g, 'output/clics_b.gml')

开发者ID:clics,项目名称:clics,代码行数:29,代码来源:normalize_weights.py


示例16: write_gml

def write_gml(graph, path):
    
    with open(path, 'w') as f:
        f.write('\n'.join([html.unescape(x) for x in
            nx.generate_gml(graph)]))
    print("wrote data to file")
开发者ID:dighl,项目名称:shijing,代码行数:6,代码来源:C_get_triples.py


示例17: to_gml

def to_gml(net):
    return '\n'.join(nx.generate_gml(net))
开发者ID:epurdy,项目名称:elegans,代码行数:2,代码来源:netx.py


示例18: _graph_or_file

def _graph_or_file(graph, filename):
    if filename:
        util.write_text_file(filename + '.gml', nx.generate_gml(graph))
        return
    return graph
开发者ID:magnusnissel,项目名称:lingpy,代码行数:5,代码来源:graph.py


示例19: debug_print_gml

def debug_print_gml(g):
    for t in nx.generate_gml(g):
        print t
开发者ID:mmadsen,项目名称:seriationct,代码行数:3,代码来源:seriationct-build-clustered-network.py


示例20: assert_generate_error

 def assert_generate_error(*args, **kwargs):
     assert_raises(nx.NetworkXError,
                   lambda: list(nx.generate_gml(*args, **kwargs)))
开发者ID:jklaise,项目名称:networkx,代码行数:3,代码来源:test_gml.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python networkx.get_edge_attributes函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.fruchterman_reingold_layout函数代码示例发布时间: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