Spaces:
Running
Running
File size: 8,386 Bytes
b200bda |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
"""
**************
Adjacency List
**************
Read and write NetworkX graphs as adjacency lists.
Adjacency list format is useful for graphs without data associated
with nodes or edges and for nodes that can be meaningfully represented
as strings.
Format
------
The adjacency list format consists of lines with node labels. The
first label in a line is the source node. Further labels in the line
are considered target nodes and are added to the graph along with an edge
between the source node and target node.
The graph with edges a-b, a-c, d-e can be represented as the following
adjacency list (anything following the # in a line is a comment)::
a b c # source target target
d e
"""
__all__ = ["generate_adjlist", "write_adjlist", "parse_adjlist", "read_adjlist"]
import networkx as nx
from networkx.utils import open_file
def generate_adjlist(G, delimiter=" "):
"""Generate a single line of the graph G in adjacency list format.
Parameters
----------
G : NetworkX graph
delimiter : string, optional
Separator for node labels
Returns
-------
lines : string
Lines of data in adjlist format.
Examples
--------
>>> G = nx.lollipop_graph(4, 3)
>>> for line in nx.generate_adjlist(G):
... print(line)
0 1 2 3
1 2 3
2 3
3 4
4 5
5 6
6
See Also
--------
write_adjlist, read_adjlist
Notes
-----
The default `delimiter=" "` will result in unexpected results if node names contain
whitespace characters. To avoid this problem, specify an alternate delimiter when spaces are
valid in node names.
NB: This option is not available for data that isn't user-generated.
"""
directed = G.is_directed()
seen = set()
for s, nbrs in G.adjacency():
line = str(s) + delimiter
for t, data in nbrs.items():
if not directed and t in seen:
continue
if G.is_multigraph():
for d in data.values():
line += str(t) + delimiter
else:
line += str(t) + delimiter
if not directed:
seen.add(s)
yield line[: -len(delimiter)]
@open_file(1, mode="wb")
def write_adjlist(G, path, comments="#", delimiter=" ", encoding="utf-8"):
"""Write graph G in single-line adjacency-list format to path.
Parameters
----------
G : NetworkX graph
path : string or file
Filename or file handle for data output.
Filenames ending in .gz or .bz2 will be compressed.
comments : string, optional
Marker for comment lines
delimiter : string, optional
Separator for node labels
encoding : string, optional
Text encoding.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_adjlist(G, "test.adjlist")
The path can be a filehandle or a string with the name of the file. If a
filehandle is provided, it has to be opened in 'wb' mode.
>>> fh = open("test.adjlist", "wb")
>>> nx.write_adjlist(G, fh)
Notes
-----
The default `delimiter=" "` will result in unexpected results if node names contain
whitespace characters. To avoid this problem, specify an alternate delimiter when spaces are
valid in node names.
NB: This option is not available for data that isn't user-generated.
This format does not store graph, node, or edge data.
See Also
--------
read_adjlist, generate_adjlist
"""
import sys
import time
pargs = comments + " ".join(sys.argv) + "\n"
header = (
pargs
+ comments
+ f" GMT {time.asctime(time.gmtime())}\n"
+ comments
+ f" {G.name}\n"
)
path.write(header.encode(encoding))
for line in generate_adjlist(G, delimiter):
line += "\n"
path.write(line.encode(encoding))
@nx._dispatch(graphs=None)
def parse_adjlist(
lines, comments="#", delimiter=None, create_using=None, nodetype=None
):
"""Parse lines of a graph adjacency list representation.
Parameters
----------
lines : list or iterator of strings
Input data in adjlist format
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
nodetype : Python type, optional
Convert nodes to this type.
comments : string, optional
Marker for comment lines
delimiter : string, optional
Separator for node labels. The default is whitespace.
Returns
-------
G: NetworkX graph
The graph corresponding to the lines in adjacency list format.
Examples
--------
>>> lines = ["1 2 5", "2 3 4", "3 5", "4", "5"]
>>> G = nx.parse_adjlist(lines, nodetype=int)
>>> nodes = [1, 2, 3, 4, 5]
>>> all(node in G for node in nodes)
True
>>> edges = [(1, 2), (1, 5), (2, 3), (2, 4), (3, 5)]
>>> all((u, v) in G.edges() or (v, u) in G.edges() for (u, v) in edges)
True
See Also
--------
read_adjlist
"""
G = nx.empty_graph(0, create_using)
for line in lines:
p = line.find(comments)
if p >= 0:
line = line[:p]
if not len(line):
continue
vlist = line.strip().split(delimiter)
u = vlist.pop(0)
# convert types
if nodetype is not None:
try:
u = nodetype(u)
except BaseException as err:
raise TypeError(
f"Failed to convert node ({u}) to type " f"{nodetype}"
) from err
G.add_node(u)
if nodetype is not None:
try:
vlist = list(map(nodetype, vlist))
except BaseException as err:
raise TypeError(
f"Failed to convert nodes ({','.join(vlist)}) to type {nodetype}"
) from err
G.add_edges_from([(u, v) for v in vlist])
return G
@open_file(0, mode="rb")
@nx._dispatch(graphs=None)
def read_adjlist(
path,
comments="#",
delimiter=None,
create_using=None,
nodetype=None,
encoding="utf-8",
):
"""Read graph in adjacency list format from path.
Parameters
----------
path : string or file
Filename or file handle to read.
Filenames ending in .gz or .bz2 will be uncompressed.
create_using : NetworkX graph constructor, optional (default=nx.Graph)
Graph type to create. If graph instance, then cleared before populated.
nodetype : Python type, optional
Convert nodes to this type.
comments : string, optional
Marker for comment lines
delimiter : string, optional
Separator for node labels. The default is whitespace.
Returns
-------
G: NetworkX graph
The graph corresponding to the lines in adjacency list format.
Examples
--------
>>> G = nx.path_graph(4)
>>> nx.write_adjlist(G, "test.adjlist")
>>> G = nx.read_adjlist("test.adjlist")
The path can be a filehandle or a string with the name of the file. If a
filehandle is provided, it has to be opened in 'rb' mode.
>>> fh = open("test.adjlist", "rb")
>>> G = nx.read_adjlist(fh)
Filenames ending in .gz or .bz2 will be compressed.
>>> nx.write_adjlist(G, "test.adjlist.gz")
>>> G = nx.read_adjlist("test.adjlist.gz")
The optional nodetype is a function to convert node strings to nodetype.
For example
>>> G = nx.read_adjlist("test.adjlist", nodetype=int)
will attempt to convert all nodes to integer type.
Since nodes must be hashable, the function nodetype must return hashable
types (e.g. int, float, str, frozenset - or tuples of those, etc.)
The optional create_using parameter indicates the type of NetworkX graph
created. The default is `nx.Graph`, an undirected graph.
To read the data as a directed graph use
>>> G = nx.read_adjlist("test.adjlist", create_using=nx.DiGraph)
Notes
-----
This format does not store graph or node data.
See Also
--------
write_adjlist
"""
lines = (line.decode(encoding) for line in path)
return parse_adjlist(
lines,
comments=comments,
delimiter=delimiter,
create_using=create_using,
nodetype=nodetype,
)
|