convert.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. """Functions to convert NetworkX graphs to and from other formats.
  2. The preferred way of converting data to a NetworkX graph is through the
  3. graph constructor. The constructor calls the to_networkx_graph() function
  4. which attempts to guess the input type and convert it automatically.
  5. Examples
  6. --------
  7. Create a graph with a single edge from a dictionary of dictionaries
  8. >>> d = {0: {1: 1}} # dict-of-dicts single edge (0,1)
  9. >>> G = nx.Graph(d)
  10. See Also
  11. --------
  12. nx_agraph, nx_pydot
  13. """
  14. import warnings
  15. from collections.abc import Collection, Generator, Iterator
  16. import networkx as nx
  17. __all__ = [
  18. "to_networkx_graph",
  19. "from_dict_of_dicts",
  20. "to_dict_of_dicts",
  21. "from_dict_of_lists",
  22. "to_dict_of_lists",
  23. "from_edgelist",
  24. "to_edgelist",
  25. ]
  26. def to_networkx_graph(data, create_using=None, multigraph_input=False):
  27. """Make a NetworkX graph from a known data structure.
  28. The preferred way to call this is automatically
  29. from the class constructor
  30. >>> d = {0: {1: {"weight": 1}}} # dict-of-dicts single edge (0,1)
  31. >>> G = nx.Graph(d)
  32. instead of the equivalent
  33. >>> G = nx.from_dict_of_dicts(d)
  34. Parameters
  35. ----------
  36. data : object to be converted
  37. Current known types are:
  38. any NetworkX graph
  39. dict-of-dicts
  40. dict-of-lists
  41. container (e.g. set, list, tuple) of edges
  42. iterator (e.g. itertools.chain) that produces edges
  43. generator of edges
  44. Pandas DataFrame (row per edge)
  45. 2D numpy array
  46. scipy sparse array
  47. pygraphviz agraph
  48. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  49. Graph type to create. If graph instance, then cleared before populated.
  50. multigraph_input : bool (default False)
  51. If True and data is a dict_of_dicts,
  52. try to create a multigraph assuming dict_of_dict_of_lists.
  53. If data and create_using are both multigraphs then create
  54. a multigraph from a multigraph.
  55. """
  56. # NX graph
  57. if hasattr(data, "adj"):
  58. try:
  59. result = from_dict_of_dicts(
  60. data.adj,
  61. create_using=create_using,
  62. multigraph_input=data.is_multigraph(),
  63. )
  64. # data.graph should be dict-like
  65. result.graph.update(data.graph)
  66. # data.nodes should be dict-like
  67. # result.add_node_from(data.nodes.items()) possible but
  68. # for custom node_attr_dict_factory which may be hashable
  69. # will be unexpected behavior
  70. for n, dd in data.nodes.items():
  71. result._node[n].update(dd)
  72. return result
  73. except Exception as err:
  74. raise nx.NetworkXError("Input is not a correct NetworkX graph.") from err
  75. # pygraphviz agraph
  76. if hasattr(data, "is_strict"):
  77. try:
  78. return nx.nx_agraph.from_agraph(data, create_using=create_using)
  79. except Exception as err:
  80. raise nx.NetworkXError("Input is not a correct pygraphviz graph.") from err
  81. # dict of dicts/lists
  82. if isinstance(data, dict):
  83. try:
  84. return from_dict_of_dicts(
  85. data, create_using=create_using, multigraph_input=multigraph_input
  86. )
  87. except Exception as err1:
  88. if multigraph_input is True:
  89. raise nx.NetworkXError(
  90. f"converting multigraph_input raised:\n{type(err1)}: {err1}"
  91. )
  92. try:
  93. return from_dict_of_lists(data, create_using=create_using)
  94. except Exception as err2:
  95. raise TypeError("Input is not known type.") from err2
  96. # Pandas DataFrame
  97. try:
  98. import pandas as pd
  99. if isinstance(data, pd.DataFrame):
  100. if data.shape[0] == data.shape[1]:
  101. try:
  102. return nx.from_pandas_adjacency(data, create_using=create_using)
  103. except Exception as err:
  104. msg = "Input is not a correct Pandas DataFrame adjacency matrix."
  105. raise nx.NetworkXError(msg) from err
  106. else:
  107. try:
  108. return nx.from_pandas_edgelist(
  109. data, edge_attr=True, create_using=create_using
  110. )
  111. except Exception as err:
  112. msg = "Input is not a correct Pandas DataFrame edge-list."
  113. raise nx.NetworkXError(msg) from err
  114. except ImportError:
  115. warnings.warn("pandas not found, skipping conversion test.", ImportWarning)
  116. # numpy array
  117. try:
  118. import numpy as np
  119. if isinstance(data, np.ndarray):
  120. try:
  121. return nx.from_numpy_array(data, create_using=create_using)
  122. except Exception as err:
  123. raise nx.NetworkXError(
  124. f"Failed to interpret array as an adjacency matrix."
  125. ) from err
  126. except ImportError:
  127. warnings.warn("numpy not found, skipping conversion test.", ImportWarning)
  128. # scipy sparse array - any format
  129. try:
  130. import scipy
  131. if hasattr(data, "format"):
  132. try:
  133. return nx.from_scipy_sparse_array(data, create_using=create_using)
  134. except Exception as err:
  135. raise nx.NetworkXError(
  136. "Input is not a correct scipy sparse array type."
  137. ) from err
  138. except ImportError:
  139. warnings.warn("scipy not found, skipping conversion test.", ImportWarning)
  140. # Note: most general check - should remain last in order of execution
  141. # Includes containers (e.g. list, set, dict, etc.), generators, and
  142. # iterators (e.g. itertools.chain) of edges
  143. if isinstance(data, (Collection, Generator, Iterator)):
  144. try:
  145. return from_edgelist(data, create_using=create_using)
  146. except Exception as err:
  147. raise nx.NetworkXError("Input is not a valid edge list") from err
  148. raise nx.NetworkXError("Input is not a known data type for conversion.")
  149. def to_dict_of_lists(G, nodelist=None):
  150. """Returns adjacency representation of graph as a dictionary of lists.
  151. Parameters
  152. ----------
  153. G : graph
  154. A NetworkX graph
  155. nodelist : list
  156. Use only nodes specified in nodelist
  157. Notes
  158. -----
  159. Completely ignores edge data for MultiGraph and MultiDiGraph.
  160. """
  161. if nodelist is None:
  162. nodelist = G
  163. d = {}
  164. for n in nodelist:
  165. d[n] = [nbr for nbr in G.neighbors(n) if nbr in nodelist]
  166. return d
  167. def from_dict_of_lists(d, create_using=None):
  168. """Returns a graph from a dictionary of lists.
  169. Parameters
  170. ----------
  171. d : dictionary of lists
  172. A dictionary of lists adjacency representation.
  173. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  174. Graph type to create. If graph instance, then cleared before populated.
  175. Examples
  176. --------
  177. >>> dol = {0: [1]} # single edge (0,1)
  178. >>> G = nx.from_dict_of_lists(dol)
  179. or
  180. >>> G = nx.Graph(dol) # use Graph constructor
  181. """
  182. G = nx.empty_graph(0, create_using)
  183. G.add_nodes_from(d)
  184. if G.is_multigraph() and not G.is_directed():
  185. # a dict_of_lists can't show multiedges. BUT for undirected graphs,
  186. # each edge shows up twice in the dict_of_lists.
  187. # So we need to treat this case separately.
  188. seen = {}
  189. for node, nbrlist in d.items():
  190. for nbr in nbrlist:
  191. if nbr not in seen:
  192. G.add_edge(node, nbr)
  193. seen[node] = 1 # don't allow reverse edge to show up
  194. else:
  195. G.add_edges_from(
  196. ((node, nbr) for node, nbrlist in d.items() for nbr in nbrlist)
  197. )
  198. return G
  199. def to_dict_of_dicts(G, nodelist=None, edge_data=None):
  200. """Returns adjacency representation of graph as a dictionary of dictionaries.
  201. Parameters
  202. ----------
  203. G : graph
  204. A NetworkX graph
  205. nodelist : list
  206. Use only nodes specified in nodelist
  207. edge_data : scalar, optional
  208. If provided, the value of the dictionary will be set to `edge_data` for
  209. all edges. Usual values could be `1` or `True`. If `edge_data` is
  210. `None` (the default), the edgedata in `G` is used, resulting in a
  211. dict-of-dict-of-dicts. If `G` is a MultiGraph, the result will be a
  212. dict-of-dict-of-dict-of-dicts. See Notes for an approach to customize
  213. handling edge data. `edge_data` should *not* be a container.
  214. Returns
  215. -------
  216. dod : dict
  217. A nested dictionary representation of `G`. Note that the level of
  218. nesting depends on the type of `G` and the value of `edge_data`
  219. (see Examples).
  220. See Also
  221. --------
  222. from_dict_of_dicts, to_dict_of_lists
  223. Notes
  224. -----
  225. For a more custom approach to handling edge data, try::
  226. dod = {
  227. n: {
  228. nbr: custom(n, nbr, dd) for nbr, dd in nbrdict.items()
  229. }
  230. for n, nbrdict in G.adj.items()
  231. }
  232. where `custom` returns the desired edge data for each edge between `n` and
  233. `nbr`, given existing edge data `dd`.
  234. Examples
  235. --------
  236. >>> G = nx.path_graph(3)
  237. >>> nx.to_dict_of_dicts(G)
  238. {0: {1: {}}, 1: {0: {}, 2: {}}, 2: {1: {}}}
  239. Edge data is preserved by default (``edge_data=None``), resulting
  240. in dict-of-dict-of-dicts where the innermost dictionary contains the
  241. edge data:
  242. >>> G = nx.Graph()
  243. >>> G.add_edges_from(
  244. ... [
  245. ... (0, 1, {'weight': 1.0}),
  246. ... (1, 2, {'weight': 2.0}),
  247. ... (2, 0, {'weight': 1.0}),
  248. ... ]
  249. ... )
  250. >>> d = nx.to_dict_of_dicts(G)
  251. >>> d # doctest: +SKIP
  252. {0: {1: {'weight': 1.0}, 2: {'weight': 1.0}},
  253. 1: {0: {'weight': 1.0}, 2: {'weight': 2.0}},
  254. 2: {1: {'weight': 2.0}, 0: {'weight': 1.0}}}
  255. >>> d[1][2]['weight']
  256. 2.0
  257. If `edge_data` is not `None`, edge data in the original graph (if any) is
  258. replaced:
  259. >>> d = nx.to_dict_of_dicts(G, edge_data=1)
  260. >>> d
  261. {0: {1: 1, 2: 1}, 1: {0: 1, 2: 1}, 2: {1: 1, 0: 1}}
  262. >>> d[1][2]
  263. 1
  264. This also applies to MultiGraphs: edge data is preserved by default:
  265. >>> G = nx.MultiGraph()
  266. >>> G.add_edge(0, 1, key='a', weight=1.0)
  267. 'a'
  268. >>> G.add_edge(0, 1, key='b', weight=5.0)
  269. 'b'
  270. >>> d = nx.to_dict_of_dicts(G)
  271. >>> d # doctest: +SKIP
  272. {0: {1: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}},
  273. 1: {0: {'a': {'weight': 1.0}, 'b': {'weight': 5.0}}}}
  274. >>> d[0][1]['b']['weight']
  275. 5.0
  276. But multi edge data is lost if `edge_data` is not `None`:
  277. >>> d = nx.to_dict_of_dicts(G, edge_data=10)
  278. >>> d
  279. {0: {1: 10}, 1: {0: 10}}
  280. """
  281. dod = {}
  282. if nodelist is None:
  283. if edge_data is None:
  284. for u, nbrdict in G.adjacency():
  285. dod[u] = nbrdict.copy()
  286. else: # edge_data is not None
  287. for u, nbrdict in G.adjacency():
  288. dod[u] = dod.fromkeys(nbrdict, edge_data)
  289. else: # nodelist is not None
  290. if edge_data is None:
  291. for u in nodelist:
  292. dod[u] = {}
  293. for v, data in ((v, data) for v, data in G[u].items() if v in nodelist):
  294. dod[u][v] = data
  295. else: # nodelist and edge_data are not None
  296. for u in nodelist:
  297. dod[u] = {}
  298. for v in (v for v in G[u] if v in nodelist):
  299. dod[u][v] = edge_data
  300. return dod
  301. def from_dict_of_dicts(d, create_using=None, multigraph_input=False):
  302. """Returns a graph from a dictionary of dictionaries.
  303. Parameters
  304. ----------
  305. d : dictionary of dictionaries
  306. A dictionary of dictionaries adjacency representation.
  307. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  308. Graph type to create. If graph instance, then cleared before populated.
  309. multigraph_input : bool (default False)
  310. When True, the dict `d` is assumed
  311. to be a dict-of-dict-of-dict-of-dict structure keyed by
  312. node to neighbor to edge keys to edge data for multi-edges.
  313. Otherwise this routine assumes dict-of-dict-of-dict keyed by
  314. node to neighbor to edge data.
  315. Examples
  316. --------
  317. >>> dod = {0: {1: {"weight": 1}}} # single edge (0,1)
  318. >>> G = nx.from_dict_of_dicts(dod)
  319. or
  320. >>> G = nx.Graph(dod) # use Graph constructor
  321. """
  322. G = nx.empty_graph(0, create_using)
  323. G.add_nodes_from(d)
  324. # does dict d represent a MultiGraph or MultiDiGraph?
  325. if multigraph_input:
  326. if G.is_directed():
  327. if G.is_multigraph():
  328. G.add_edges_from(
  329. (u, v, key, data)
  330. for u, nbrs in d.items()
  331. for v, datadict in nbrs.items()
  332. for key, data in datadict.items()
  333. )
  334. else:
  335. G.add_edges_from(
  336. (u, v, data)
  337. for u, nbrs in d.items()
  338. for v, datadict in nbrs.items()
  339. for key, data in datadict.items()
  340. )
  341. else: # Undirected
  342. if G.is_multigraph():
  343. seen = set() # don't add both directions of undirected graph
  344. for u, nbrs in d.items():
  345. for v, datadict in nbrs.items():
  346. if (u, v) not in seen:
  347. G.add_edges_from(
  348. (u, v, key, data) for key, data in datadict.items()
  349. )
  350. seen.add((v, u))
  351. else:
  352. seen = set() # don't add both directions of undirected graph
  353. for u, nbrs in d.items():
  354. for v, datadict in nbrs.items():
  355. if (u, v) not in seen:
  356. G.add_edges_from(
  357. (u, v, data) for key, data in datadict.items()
  358. )
  359. seen.add((v, u))
  360. else: # not a multigraph to multigraph transfer
  361. if G.is_multigraph() and not G.is_directed():
  362. # d can have both representations u-v, v-u in dict. Only add one.
  363. # We don't need this check for digraphs since we add both directions,
  364. # or for Graph() since it is done implicitly (parallel edges not allowed)
  365. seen = set()
  366. for u, nbrs in d.items():
  367. for v, data in nbrs.items():
  368. if (u, v) not in seen:
  369. G.add_edge(u, v, key=0)
  370. G[u][v][0].update(data)
  371. seen.add((v, u))
  372. else:
  373. G.add_edges_from(
  374. ((u, v, data) for u, nbrs in d.items() for v, data in nbrs.items())
  375. )
  376. return G
  377. def to_edgelist(G, nodelist=None):
  378. """Returns a list of edges in the graph.
  379. Parameters
  380. ----------
  381. G : graph
  382. A NetworkX graph
  383. nodelist : list
  384. Use only nodes specified in nodelist
  385. """
  386. if nodelist is None:
  387. return G.edges(data=True)
  388. return G.edges(nodelist, data=True)
  389. def from_edgelist(edgelist, create_using=None):
  390. """Returns a graph from a list of edges.
  391. Parameters
  392. ----------
  393. edgelist : list or iterator
  394. Edge tuples
  395. create_using : NetworkX graph constructor, optional (default=nx.Graph)
  396. Graph type to create. If graph instance, then cleared before populated.
  397. Examples
  398. --------
  399. >>> edgelist = [(0, 1)] # single edge (0,1)
  400. >>> G = nx.from_edgelist(edgelist)
  401. or
  402. >>> G = nx.Graph(edgelist) # use Graph constructor
  403. """
  404. G = nx.empty_graph(0, create_using)
  405. G.add_edges_from(edgelist)
  406. return G