comparison env/lib/python3.9/site-packages/networkx/readwrite/leda.py @ 0:4f3585e2f14b draft default tip

"planemo upload commit 60cee0fc7c0cda8592644e1aad72851dec82c959"
author shellac
date Mon, 22 Mar 2021 18:12:50 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:4f3585e2f14b
1 """
2 Read graphs in LEDA format.
3
4 LEDA is a C++ class library for efficient data types and algorithms.
5
6 Format
7 ------
8 See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
9
10 """
11 # Original author: D. Eppstein, UC Irvine, August 12, 2003.
12 # The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
13
14 __all__ = ["read_leda", "parse_leda"]
15
16 import networkx as nx
17 from networkx.exception import NetworkXError
18 from networkx.utils import open_file
19
20
21 @open_file(0, mode="rb")
22 def read_leda(path, encoding="UTF-8"):
23 """Read graph in LEDA format from path.
24
25 Parameters
26 ----------
27 path : file or string
28 File or filename to read. Filenames ending in .gz or .bz2 will be
29 uncompressed.
30
31 Returns
32 -------
33 G : NetworkX graph
34
35 Examples
36 --------
37 G=nx.read_leda('file.leda')
38
39 References
40 ----------
41 .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
42 """
43 lines = (line.decode(encoding) for line in path)
44 G = parse_leda(lines)
45 return G
46
47
48 def parse_leda(lines):
49 """Read graph in LEDA format from string or iterable.
50
51 Parameters
52 ----------
53 lines : string or iterable
54 Data in LEDA format.
55
56 Returns
57 -------
58 G : NetworkX graph
59
60 Examples
61 --------
62 G=nx.parse_leda(string)
63
64 References
65 ----------
66 .. [1] http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
67 """
68 if isinstance(lines, str):
69 lines = iter(lines.split("\n"))
70 lines = iter(
71 [
72 line.rstrip("\n")
73 for line in lines
74 if not (line.startswith("#") or line.startswith("\n") or line == "")
75 ]
76 )
77 for i in range(3):
78 next(lines)
79 # Graph
80 du = int(next(lines)) # -1=directed, -2=undirected
81 if du == -1:
82 G = nx.DiGraph()
83 else:
84 G = nx.Graph()
85
86 # Nodes
87 n = int(next(lines)) # number of nodes
88 node = {}
89 for i in range(1, n + 1): # LEDA counts from 1 to n
90 symbol = next(lines).rstrip().strip("|{}| ")
91 if symbol == "":
92 symbol = str(i) # use int if no label - could be trouble
93 node[i] = symbol
94
95 G.add_nodes_from([s for i, s in node.items()])
96
97 # Edges
98 m = int(next(lines)) # number of edges
99 for i in range(m):
100 try:
101 s, t, reversal, label = next(lines).split()
102 except BaseException as e:
103 raise NetworkXError(f"Too few fields in LEDA.GRAPH edge {i+1}") from e
104 # BEWARE: no handling of reversal edges
105 G.add_edge(node[int(s)], node[int(t)], label=label[2:-2])
106 return G