1 """
2 Read graphs in GraphML format.
3 http://graphml.graphdrawing.org/
4
5 """
6
7
8 __author__ = """Aric Hagberg (hagberg@lanl.gov)"""
9 __date__ = """"""
10 __credits__ = """"""
11 __revision__ = ""
12
13
14
15
16
17
18
19 import networkx
20 from networkx.exception import NetworkXException, NetworkXError
21 from networkx.utils import _get_fh
22
24 """Read graph in GraphML format from path.
25 Returns an XGraph or XDiGraph."""
26 fh=_get_fh(path,mode='r')
27 G=parse_graphml(fh)
28 return G
29
31 """Read graph in GraphML format from string.
32 Returns an XGraph or XDiGraph."""
33 context = []
34 G=networkx.XDiGraph()
35 defaultDirected = [True]
36
37 def start_element(name,attrs):
38 context.append(name)
39 if len(context) == 1:
40 if name != 'graphml':
41 raise GraphFormatError, \
42 'Unrecognized outer tag "%s" in GraphML' % name
43 elif len(context) == 2 and name == 'graph':
44 if 'edgedefault' not in attrs:
45 raise GraphFormatError, \
46 'Required attribute edgedefault missing in GraphML'
47 if attrs['edgedefault'] == 'undirected':
48 print "undirected"
49 defaultDirected[0] = False
50 elif len(context) == 3 and context[1] == 'graph' and name == 'node':
51 if 'id' not in attrs:
52 raise GraphFormatError, 'Anonymous node in GraphML'
53 G.add_node(attrs['id'])
54 elif len(context) == 3 and context[1] == 'graph' and name == 'edge':
55 if 'source' not in attrs:
56 raise GraphFormatError, 'Edge without source in GraphML'
57 if 'target' not in attrs:
58 raise GraphFormatError, 'Edge without target in GraphML'
59 G.add_edge(attrs['source'], attrs['target'],attrs.get('id'))
60
61
62
63 if attrs.get('directed')=='false':
64 if defaultDirected[0]:
65 G.add_edge(attrs['target'], attrs['source'],attrs.get('id'))
66
67 def end_element(name):
68 context.pop()
69
70 import xml.parsers.expat
71 p = xml.parsers.expat.ParserCreate()
72 p.StartElementHandler = start_element
73 p.EndElementHandler = end_element
74 for line in lines:
75 p.Parse(line)
76 p.Parse("", 1)
77
78 if defaultDirected[0]:
79 return G
80 else:
81 return G.to_undirected()
82
83
85 import doctest
86 suite = doctest.DocFileSuite('tests/readwrite/graphml.txt',
87 package='networkx')
88 return suite
89
90 if __name__ == "__main__":
91 import os
92 import sys
93 import unittest
94 if sys.version_info[:2] < (2, 4):
95 print "Python version 2.4 or later required for tests (%d.%d detected)." % sys.version_info[:2]
96 sys.exit(-1)
97
98 nxbase=sys.path[0]+os.sep+os.pardir
99 sys.path.insert(0,nxbase)
100 unittest.TextTestRunner().run(_test_suite())
101