Package networkx :: Package readwrite :: Module graphml
[hide private]
[frames] | no frames]

Source Code for Module networkx.readwrite.graphml

  1  """ 
  2  Read graphs in GraphML format. 
  3  http://graphml.graphdrawing.org/ 
  4   
  5  """ 
  6  # Original author: D. Eppstein, UC Irvine, August 12, 2003. 
  7  # The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain. 
  8  __author__ = """Aric Hagberg (hagberg@lanl.gov)""" 
  9  __date__ = """""" 
 10  __credits__ = """""" 
 11  __revision__ = "" 
 12  #    Copyright (C) 2004-2007 by  
 13  #    Aric Hagberg <hagberg@lanl.gov> 
 14  #    Dan Schult <dschult@colgate.edu> 
 15  #    Pieter Swart <swart@lanl.gov> 
 16  #    Distributed under the terms of the GNU Lesser General Public License 
 17  #    http://www.gnu.org/copyleft/lesser.html 
 18   
 19  import networkx 
 20  from networkx.exception import NetworkXException, NetworkXError 
 21  from networkx.utils import _get_fh 
 22           
23 -def read_graphml(path):
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
30 -def parse_graphml(lines):
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 # no mixed graphs in NetworkX 61 # handle mixed graphs by adding two directed 62 # edges for an undirected edge in a directed graph 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
84 -def _test_suite():
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 # directory of networkx package (relative to this) 98 nxbase=sys.path[0]+os.sep+os.pardir 99 sys.path.insert(0,nxbase) # prepend to search path 100 unittest.TextTestRunner().run(_test_suite()) 101