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

Source Code for Module networkx.readwrite.leda

 1  """ 
 2  Read graphs in LEDA format. 
 3  See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html 
 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, is_string_like 
22           
23 -def read_leda(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_leda(fh) 28 return G
29
30 -def parse_leda(lines):
31 """Parse LEDA.GRAPH format from string or iterable. 32 Returns an XGraph or XDiGraph.""" 33 if is_string_like(lines): lines=iter(lines.split('\n')) 34 lines = iter([line.rstrip('\n') for line in lines \ 35 if not (line.startswith('#') or line.startswith('\n') or line=='')]) 36 for i in range(3): 37 lines.next() 38 # Graph 39 du = int(lines.next()) # -1 directed, -2 undirected 40 if du==-1: 41 G = networkx.XDiGraph() 42 else: 43 G = networkx.XGraph() 44 45 # Nodes 46 n =int(lines.next()) # number of vertices 47 node={} 48 for i in range(1,n+1): # LEDA counts from 1 to n 49 symbol=lines.next()[2:-3] # strip out data from |{data}| 50 if symbol=="": symbol=str(i) # use int if no label - could be trouble 51 node[i]=symbol 52 53 G.add_nodes_from([s for i,s in node.items()]) 54 55 # Edges 56 m = int(lines.next()) # number of edges 57 for i in range(m): 58 try: 59 s,t,reversal,label=lines.next().split() 60 except: 61 raise NetworkXError,\ 62 'Too few fields in LEDA.GRAPH edge %d' % (i+1) 63 # BEWARE: no handling of reversal edges 64 G.add_edge(node[int(s)],node[int(t)],label[2:-2]) 65 return G
66 67
68 -def _test_suite():
69 import doctest 70 suite = doctest.DocFileSuite('tests/readwrite/leda.txt', 71 package='networkx') 72 return suite
73 74 if __name__ == "__main__": 75 import os 76 import sys 77 import unittest 78 if sys.version_info[:2] < (2, 4): 79 print "Python version 2.4 or later required for tests (%d.%d detected)." % sys.version_info[:2] 80 sys.exit(-1) 81 # directory of networkx package (relative to this) 82 nxbase=sys.path[0]+os.sep+os.pardir 83 sys.path.insert(0,nxbase) # prepend to search path 84 unittest.TextTestRunner().run(_test_suite()) 85