adjlist.py 8.8 KB

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