adjlist.py 8.1 KB

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