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

Python networkx.parse_gml函数代码示例

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

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



在下文中一共展示了parse_gml函数的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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: test_label_kwarg

    def test_label_kwarg(self):
        G = nx.parse_gml(self.simple_data, label='id')
        assert_equals(sorted(G.nodes), [1, 2, 3])
        labels = [G.nodes[n]['label'] for n in sorted(G.nodes)]
        assert_equals(labels, ['Node 1', 'Node 2', 'Node 3'])

        G = nx.parse_gml(self.simple_data, label=None)
        assert_equals(sorted(G.nodes), [1, 2, 3])
        labels = [G.nodes[n]['label'] for n in sorted(G.nodes)]
        assert_equals(labels, ['Node 1', 'Node 2', 'Node 3'])
开发者ID:networkx,项目名称:networkx,代码行数:10,代码来源:test_gml.py


示例3: main

def main():
    global G
    slave_ip = "172.31.13.227"
    slave_port = 8200
    slave = servernode(slave_ip,slave_port)
    slave.register_function(updateMin)
    slave.start()
    

    master_ip = "172.31.13.224"
    master_port = 8100
    url = "http://{}:{}".format(master_ip, master_port)
    master = xmlrpclib.ServerProxy(url,verbose =True)
    try:
        strGraph = master.getWholeGraph()
        G = nx.parse_gml(strGraph)
        print "Made it"
        x = master.getGraph()

        while (x != None):
            print "in While"
            minTour(G,x)    
            print "First subgraph complete"
            x = master.getGraph
        slave.stop_server()
    except KeyboardInterrupt:
        print "Blah"
        slave.stop_server()
开发者ID:rgentryIII,项目名称:FinalProject,代码行数:28,代码来源:slave.py


示例4: 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


示例5: test_read_gml

 def test_read_gml(self):
     (fd, fname) = tempfile.mkstemp()
     fh = open(fname, 'w')
     fh.write(self.simple_data)
     fh.close()
     Gin = nx.read_gml(fname, label='label')
     G = nx.parse_gml(self.simple_data, label='label')
     assert_equals(sorted(G.nodes(data=True)), sorted(Gin.nodes(data=True)))
     assert_equals(sorted(G.edges(data=True)), sorted(Gin.edges(data=True)))
     os.close(fd)
     os.unlink(fname)
开发者ID:jklaise,项目名称:networkx,代码行数:11,代码来源:test_gml.py


示例6: test_parse_gml

 def test_parse_gml(self):
     G=networkx.parse_gml(self.simple_data)
     assert_equals(sorted(G.nodes()),\
                       ['Node 1', 'Node 2', 'Node 3'])
     assert_equals( [e for e in sorted(G.edges(data=True))],\
                        [('Node 1', 'Node 2', 
                          {'color': {'line': 'blue', 'thickness': 3},
                           'label': 'Edge from node 1 to node 2'}), 
                         ('Node 2', 'Node 3', 
                          {'label': 'Edge from node 2 to node 3'}), 
                         ('Node 3', 'Node 1', {'label': 'Edge from node 3 to node 1'})])
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:11,代码来源:test_gml.py


示例7: 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


示例8: test_read_gml

    def test_read_gml(self):
        import os, tempfile

        (fd, fname) = tempfile.mkstemp()
        fh = open(fname, "w")
        fh.write(self.simple_data)
        fh.close()
        Gin = networkx.read_gml(fname, relabel=True)
        G = networkx.parse_gml(self.simple_data, relabel=True)
        assert_equals(sorted(G.nodes(data=True)), sorted(Gin.nodes(data=True)))
        assert_equals(sorted(G.edges(data=True)), sorted(Gin.edges(data=True)))
        os.close(fd)
        os.unlink(fname)
开发者ID:ciarancourtney,项目名称:cloudify-trial,代码行数:13,代码来源:test_gml.py


示例9: _parse_networkmodel

def _parse_networkmodel(path):
    network_slices = dict()

    zf = zipfile.ZipFile(path, 'r')

    for file in [f for f in zf.namelist() if f.endswith(".gml")]:
        m = re.search('(?!\-)(\d+)\.gml', file)
        file_number = m.group(1)
        log.debug("Parsing GML file %s:  file number %s", file, file_number)

        gml = zf.read(file)
        slice = nx.parse_gml(gml)
        #log.debug("slice nodes: %s", '|'.join(sorted(slice.nodes())))
        network_slices[int(file_number)] = slice

    return network_slices
开发者ID:mmadsen,项目名称:seriationct,代码行数:16,代码来源:seriationct-sample-assemblages.py


示例10: test_parse_gml

    def test_parse_gml(self):
        G = networkx.parse_gml(self.simple_data, relabel=True)
        assert_equals(sorted(G.nodes()), ["Node 1", "Node 2", "Node 3"])
        assert_equals(
            [e for e in sorted(G.edges())], [("Node 1", "Node 2"), ("Node 2", "Node 3"), ("Node 3", "Node 1")]
        )

        assert_equals(
            [e for e in sorted(G.edges(data=True))],
            [
                (
                    "Node 1",
                    "Node 2",
                    {"color": {"line": "blue", "thickness": 3}, "label": "Edge from node 1 to node 2"},
                ),
                ("Node 2", "Node 3", {"label": "Edge from node 2 to node 3"}),
                ("Node 3", "Node 1", {"label": "Edge from node 3 to node 1"}),
            ],
        )
开发者ID:ciarancourtney,项目名称:cloudify-trial,代码行数:19,代码来源:test_gml.py


示例11: parse_gml_and_normalize_floats

def parse_gml_and_normalize_floats(slice_lines):
    """
    Read a slice GML line by line, looking for scientific notation
    and when found, normalize it using the Decimal library.
    Then pass the lines of text to networkx parse_gml to
    parse it.  This is a drop-in replacement for read_gml()
    """
    exp_regex = compile(r"(\d+(\.\d+)?)[Ee](\+|-)(\d+)")

    input_lines = []


    for line in slice_lines:
        result = exp_regex.search(line)
        if result is not None:
            matched_value = result.group(0)
            replacement = str(remove_exponent(Decimal(float(matched_value))))
            line = line.replace(matched_value, replacement)
            #log.debug("Replacing %s with %s", matched_value, replacement)

        input_lines.append(line)

    return nx.parse_gml(input_lines)
开发者ID:mmadsen,项目名称:seriationct,代码行数:23,代码来源:networkmodel_annotation.py


示例12: test_parse_gml_cytoscape_bug

    def test_parse_gml_cytoscape_bug(self):
        # example from issue #321, originally #324 in trac
        cytoscape_example = """
Creator "Cytoscape"
Version 1.0
graph   [
    node    [
        root_index  -3
        id  -3
        graphics    [
            x   -96.0
            y   -67.0
            w   40.0
            h   40.0
            fill    "#ff9999"
            type    "ellipse"
            outline "#666666"
            outline_width   1.5
        ]
        label   "node2"
    ]
    node    [
        root_index  -2
        id  -2
        graphics    [
            x   63.0
            y   37.0
            w   40.0
            h   40.0
            fill    "#ff9999"
            type    "ellipse"
            outline "#666666"
            outline_width   1.5
        ]
        label   "node1"
    ]
    node    [
        root_index  -1
        id  -1
        graphics    [
            x   -31.0
            y   -17.0
            w   40.0
            h   40.0
            fill    "#ff9999"
            type    "ellipse"
            outline "#666666"
            outline_width   1.5
        ]
        label   "node0"
    ]
    edge    [
        root_index  -2
        target  -2
        source  -1
        graphics    [
            width   1.5
            fill    "#0000ff"
            type    "line"
            Line    [
            ]
            source_arrow    0
            target_arrow    3
        ]
        label   "DirectedEdge"
    ]
    edge    [
        root_index  -1
        target  -1
        source  -3
        graphics    [
            width   1.5
            fill    "#0000ff"
            type    "line"
            Line    [
            ]
            source_arrow    0
            target_arrow    3
        ]
        label   "DirectedEdge"
    ]
]
"""
        nx.parse_gml(cytoscape_example)
开发者ID:jklaise,项目名称:networkx,代码行数:84,代码来源:test_gml.py


示例13: test_exceptions

    def test_exceptions(self):
        assert_raises(ValueError, literal_destringizer, '(')
        assert_raises(ValueError, literal_destringizer, 'frozenset([1, 2, 3])')
        assert_raises(ValueError, literal_destringizer, literal_destringizer)
        assert_raises(ValueError, literal_stringizer, frozenset([1, 2, 3]))
        assert_raises(ValueError, literal_stringizer, literal_stringizer)
        with tempfile.TemporaryFile() as f:
            f.write(codecs.BOM_UTF8 + 'graph[]'.encode('ascii'))
            f.seek(0)
            assert_raises(nx.NetworkXError, nx.read_gml, f)

        def assert_parse_error(gml):
            assert_raises(nx.NetworkXError, nx.parse_gml, gml)

        assert_parse_error(['graph [\n\n', unicode(']')])
        assert_parse_error('')
        assert_parse_error('Creator ""')
        assert_parse_error('0')
        assert_parse_error('graph ]')
        assert_parse_error('graph [ 1 ]')
        assert_parse_error('graph [ 1.E+2 ]')
        assert_parse_error('graph [ "A" ]')
        assert_parse_error('graph [ ] graph ]')
        assert_parse_error('graph [ ] graph [ ]')
        assert_parse_error('graph [ data [1, 2, 3] ]')
        assert_parse_error('graph [ node [ ] ]')
        assert_parse_error('graph [ node [ id 0 ] ]')
        nx.parse_gml('graph [ node [ id "a" ] ]', label='id')
        assert_parse_error(
            'graph [ node [ id 0 label 0 ] node [ id 0 label 1 ] ]')
        assert_parse_error(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 0 ] ]')
        assert_parse_error('graph [ node [ id 0 label 0 ] edge [ ] ]')
        assert_parse_error('graph [ node [ id 0 label 0 ] edge [ source 0 ] ]')
        nx.parse_gml(
            'graph [edge [ source 0 target 0 ] node [ id 0 label 0 ] ]')
        assert_parse_error(
            'graph [ node [ id 0 label 0 ] edge [ source 1 target 0 ] ]')
        assert_parse_error(
            'graph [ node [ id 0 label 0 ] edge [ source 0 target 1 ] ]')
        assert_parse_error(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] '
            'edge [ source 0 target 1 ] edge [ source 1 target 0 ] ]')
        nx.parse_gml(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] '
            'edge [ source 0 target 1 ] edge [ source 1 target 0 ] '
            'directed 1 ]')
        nx.parse_gml(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] '
            'edge [ source 0 target 1 ] edge [ source 0 target 1 ]'
            'multigraph 1 ]')
        nx.parse_gml(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] '
            'edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 ]'
            'multigraph 1 ]')
        assert_parse_error(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] '
            'edge [ source 0 target 1 key 0 ] edge [ source 0 target 1 key 0 ]'
            'multigraph 1 ]')
        nx.parse_gml(
            'graph [ node [ id 0 label 0 ] node [ id 1 label 1 ] '
            'edge [ source 0 target 1 key 0 ] edge [ source 1 target 0 key 0 ]'
            'directed 1 multigraph 1 ]')

        def assert_generate_error(*args, **kwargs):
            assert_raises(nx.NetworkXError,
                          lambda: list(nx.generate_gml(*args, **kwargs)))

        G = nx.Graph()
        G.graph[3] = 3
        assert_generate_error(G)
        G = nx.Graph()
        G.graph['3'] = 3
        assert_generate_error(G)
        G = nx.Graph()
        G.graph['data'] = frozenset([1, 2, 3])
        assert_generate_error(G, stringizer=literal_stringizer)
        G = nx.Graph()
        G.graph['data'] = []
        assert_generate_error(G)
        assert_generate_error(G, stringizer=len)
开发者ID:jklaise,项目名称:networkx,代码行数:81,代码来源:test_gml.py


示例14: test_name

 def test_name(self):
     G = nx.parse_gml('graph [ name "x" node [ id 0 label "x" ] ]')
     assert_equal('x', G.graph['name'])
     G = nx.parse_gml('graph [ node [ id 0 label "x" ] ]')
     assert_equal('', G.name)
     assert_not_in('name', G.graph)
开发者ID:jklaise,项目名称:networkx,代码行数:6,代码来源:test_gml.py


示例15: print

import matplotlib.pyplot as plt
import networkx as nx

url = "http://www-personal.umich.edu/~mejn/netdata/football.zip"

sock = urllib.urlopen(url)  # open URL
s = io.BytesIO(sock.read())  # read into BytesIO "file"
sock.close()

zf = zipfile.ZipFile(s)  # zipfile object
txt = zf.read('football.txt').decode()  # read info file
gml = zf.read('football.gml').decode()  # read gml data
# throw away bogus first line with # from mejn files
gml = gml.split('\n')[1:]
G = nx.parse_gml(gml)  # parse gml data

print(txt)
# print degree for each team - number of games
for n, d in G.degree():
    print('%s %d' % (n, d))

options = {
    'node_color': 'black',
    'node_size': 50,
    'line_color': 'grey',
    'linewidths': 0,
    'width': 0.1,
}
nx.draw(G, **options)
plt.show()
开发者ID:ProgVal,项目名称:networkx,代码行数:30,代码来源:plot_football.py


示例16: graph

 def graph(self):
     def lines():
         for line in self.fname.open():
             yield line.encode('ascii', 'xmlcharrefreplace').decode('utf-8')
     return nx.parse_gml(''.join(lines()))
开发者ID:clics,项目名称:clics-data,代码行数:5,代码来源:models.py


示例17: get_graph_from_gml

def get_graph_from_gml(file_name, label='label'):
    correct_gml = re.sub(r'\s+\[', ' [', open(file_name).read())
    return networkx.parse_gml(correct_gml, label)
开发者ID:zaktan8,项目名称:GCP,代码行数:3,代码来源:util.py


示例18: HTMLParser

#remove additional route_type infos
string = re.sub(r'\s+route\_type [0-9]+', '', string)
string = re.sub(r'\s+agency None', '', string)
string = re.sub(r'\s+weight None', '', string)

##XML read string by xmlcharrefreplace -> unicode, replace all non-ascii characters
#from HTMLParser import HTMLParser
#parser = HTMLParser()
#string = parser.unescape(string)
#string = string.encode('ascii', 'ignore')

#replace labels by unique id
lbl_counter = count()
string = re.sub(r'label ".+"', lambda x: 'label "a%s"' %next(lbl_counter), string)

G = nx.parse_gml(string)
stream = stdout

stream.write('p tw %s %s\n' %(G.number_of_nodes(), G.number_of_edges()))
G = nx.convert_node_labels_to_integers(G, first_label=1)

text = r'''c
c Graphs generated from publicly available GTFS transit feeds by Johannes K. Fichte
c
c References
c [1] https://en.wikipedia.org/wiki/General_Transit_Feed_Specification or
c [2] https://developers.google.com/transit/gtfs/
c [3] https://github.com/daajoe/transit_graphs/blob/master/transitfeeds-tw.pdf
c [4] https://github.com/daajoe/gtfs2graphs
c
c GTFS feeds extracted using gtfs2graphs [4]
开发者ID:daajoe,项目名称:PACE2016_transit_graphs,代码行数:31,代码来源:gml2pace.py


示例19: open

  
  input_json_filename= sys.argv[1]
  gml_filename= sys.argv[2]
  output_json_filename= sys.argv[3]

  json_object= json.loads(open(input_json_filename, "r").read())
  
  gml_string= open(gml_filename, "r").read()
  gml_string= gml_string.replace("graph\n", "graph \n")
  gml_string= gml_string.replace("node\n", "node \n")
  gml_string= gml_string.replace("edge\n", "edge \n")
  gml_string= re.sub("Creator Gephi\n", "", gml_string)
  gml_string= gml_string.replace("graphics\n", "graphics \n")
  
  open(gml_filename, "w").write(gml_string)
  gml_object= nx.parse_gml(gml_string)
  
  json_object["authors"]= map(int, gml_object.nodes())
  open(output_json_filename, "w").write(json.dumps(json_object, indent= 4))

  
  
    
    
        
    
      
    
  
    
    
开发者ID:Twinklebear,项目名称:dataviscourse-pr-collaboration-networks,代码行数:18,代码来源:json_gml_bridge.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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