test_convert.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import pytest
  2. import networkx as nx
  3. from networkx.convert import (
  4. from_dict_of_dicts,
  5. from_dict_of_lists,
  6. to_dict_of_dicts,
  7. to_dict_of_lists,
  8. to_networkx_graph,
  9. )
  10. from networkx.generators.classic import barbell_graph, cycle_graph
  11. from networkx.utils import edges_equal, graphs_equal, nodes_equal
  12. class TestConvert:
  13. def edgelists_equal(self, e1, e2):
  14. return sorted(sorted(e) for e in e1) == sorted(sorted(e) for e in e2)
  15. def test_simple_graphs(self):
  16. for dest, source in [
  17. (to_dict_of_dicts, from_dict_of_dicts),
  18. (to_dict_of_lists, from_dict_of_lists),
  19. ]:
  20. G = barbell_graph(10, 3)
  21. G.graph = {}
  22. dod = dest(G)
  23. # Dict of [dicts, lists]
  24. GG = source(dod)
  25. assert graphs_equal(G, GG)
  26. GW = to_networkx_graph(dod)
  27. assert graphs_equal(G, GW)
  28. GI = nx.Graph(dod)
  29. assert graphs_equal(G, GI)
  30. # With nodelist keyword
  31. P4 = nx.path_graph(4)
  32. P3 = nx.path_graph(3)
  33. P4.graph = {}
  34. P3.graph = {}
  35. dod = dest(P4, nodelist=[0, 1, 2])
  36. Gdod = nx.Graph(dod)
  37. assert graphs_equal(Gdod, P3)
  38. def test_exceptions(self):
  39. # NX graph
  40. class G:
  41. adj = None
  42. pytest.raises(nx.NetworkXError, to_networkx_graph, G)
  43. # pygraphviz agraph
  44. class G:
  45. is_strict = None
  46. pytest.raises(nx.NetworkXError, to_networkx_graph, G)
  47. # Dict of [dicts, lists]
  48. G = {"a": 0}
  49. pytest.raises(TypeError, to_networkx_graph, G)
  50. # list or generator of edges
  51. class G:
  52. next = None
  53. pytest.raises(nx.NetworkXError, to_networkx_graph, G)
  54. # no match
  55. pytest.raises(nx.NetworkXError, to_networkx_graph, "a")
  56. def test_digraphs(self):
  57. for dest, source in [
  58. (to_dict_of_dicts, from_dict_of_dicts),
  59. (to_dict_of_lists, from_dict_of_lists),
  60. ]:
  61. G = cycle_graph(10)
  62. # Dict of [dicts, lists]
  63. dod = dest(G)
  64. GG = source(dod)
  65. assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
  66. assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
  67. GW = to_networkx_graph(dod)
  68. assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
  69. assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
  70. GI = nx.Graph(dod)
  71. assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
  72. assert edges_equal(sorted(G.edges()), sorted(GI.edges()))
  73. G = cycle_graph(10, create_using=nx.DiGraph)
  74. dod = dest(G)
  75. GG = source(dod, create_using=nx.DiGraph)
  76. assert sorted(G.nodes()) == sorted(GG.nodes())
  77. assert sorted(G.edges()) == sorted(GG.edges())
  78. GW = to_networkx_graph(dod, create_using=nx.DiGraph)
  79. assert sorted(G.nodes()) == sorted(GW.nodes())
  80. assert sorted(G.edges()) == sorted(GW.edges())
  81. GI = nx.DiGraph(dod)
  82. assert sorted(G.nodes()) == sorted(GI.nodes())
  83. assert sorted(G.edges()) == sorted(GI.edges())
  84. def test_graph(self):
  85. g = nx.cycle_graph(10)
  86. G = nx.Graph()
  87. G.add_nodes_from(g)
  88. G.add_weighted_edges_from((u, v, u) for u, v in g.edges())
  89. # Dict of dicts
  90. dod = to_dict_of_dicts(G)
  91. GG = from_dict_of_dicts(dod, create_using=nx.Graph)
  92. assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
  93. assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
  94. GW = to_networkx_graph(dod, create_using=nx.Graph)
  95. assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
  96. assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
  97. GI = nx.Graph(dod)
  98. assert sorted(G.nodes()) == sorted(GI.nodes())
  99. assert sorted(G.edges()) == sorted(GI.edges())
  100. # Dict of lists
  101. dol = to_dict_of_lists(G)
  102. GG = from_dict_of_lists(dol, create_using=nx.Graph)
  103. # dict of lists throws away edge data so set it to none
  104. enone = [(u, v, {}) for (u, v, d) in G.edges(data=True)]
  105. assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
  106. assert edges_equal(enone, sorted(GG.edges(data=True)))
  107. GW = to_networkx_graph(dol, create_using=nx.Graph)
  108. assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
  109. assert edges_equal(enone, sorted(GW.edges(data=True)))
  110. GI = nx.Graph(dol)
  111. assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
  112. assert edges_equal(enone, sorted(GI.edges(data=True)))
  113. def test_with_multiedges_self_loops(self):
  114. G = cycle_graph(10)
  115. XG = nx.Graph()
  116. XG.add_nodes_from(G)
  117. XG.add_weighted_edges_from((u, v, u) for u, v in G.edges())
  118. XGM = nx.MultiGraph()
  119. XGM.add_nodes_from(G)
  120. XGM.add_weighted_edges_from((u, v, u) for u, v in G.edges())
  121. XGM.add_edge(0, 1, weight=2) # multiedge
  122. XGS = nx.Graph()
  123. XGS.add_nodes_from(G)
  124. XGS.add_weighted_edges_from((u, v, u) for u, v in G.edges())
  125. XGS.add_edge(0, 0, weight=100) # self loop
  126. # Dict of dicts
  127. # with self loops, OK
  128. dod = to_dict_of_dicts(XGS)
  129. GG = from_dict_of_dicts(dod, create_using=nx.Graph)
  130. assert nodes_equal(XGS.nodes(), GG.nodes())
  131. assert edges_equal(XGS.edges(), GG.edges())
  132. GW = to_networkx_graph(dod, create_using=nx.Graph)
  133. assert nodes_equal(XGS.nodes(), GW.nodes())
  134. assert edges_equal(XGS.edges(), GW.edges())
  135. GI = nx.Graph(dod)
  136. assert nodes_equal(XGS.nodes(), GI.nodes())
  137. assert edges_equal(XGS.edges(), GI.edges())
  138. # Dict of lists
  139. # with self loops, OK
  140. dol = to_dict_of_lists(XGS)
  141. GG = from_dict_of_lists(dol, create_using=nx.Graph)
  142. # dict of lists throws away edge data so set it to none
  143. enone = [(u, v, {}) for (u, v, d) in XGS.edges(data=True)]
  144. assert nodes_equal(sorted(XGS.nodes()), sorted(GG.nodes()))
  145. assert edges_equal(enone, sorted(GG.edges(data=True)))
  146. GW = to_networkx_graph(dol, create_using=nx.Graph)
  147. assert nodes_equal(sorted(XGS.nodes()), sorted(GW.nodes()))
  148. assert edges_equal(enone, sorted(GW.edges(data=True)))
  149. GI = nx.Graph(dol)
  150. assert nodes_equal(sorted(XGS.nodes()), sorted(GI.nodes()))
  151. assert edges_equal(enone, sorted(GI.edges(data=True)))
  152. # Dict of dicts
  153. # with multiedges, OK
  154. dod = to_dict_of_dicts(XGM)
  155. GG = from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=True)
  156. assert nodes_equal(sorted(XGM.nodes()), sorted(GG.nodes()))
  157. assert edges_equal(sorted(XGM.edges()), sorted(GG.edges()))
  158. GW = to_networkx_graph(dod, create_using=nx.MultiGraph, multigraph_input=True)
  159. assert nodes_equal(sorted(XGM.nodes()), sorted(GW.nodes()))
  160. assert edges_equal(sorted(XGM.edges()), sorted(GW.edges()))
  161. GI = nx.MultiGraph(dod)
  162. assert nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
  163. assert sorted(XGM.edges()) == sorted(GI.edges())
  164. GE = from_dict_of_dicts(dod, create_using=nx.MultiGraph, multigraph_input=False)
  165. assert nodes_equal(sorted(XGM.nodes()), sorted(GE.nodes()))
  166. assert sorted(XGM.edges()) != sorted(GE.edges())
  167. GI = nx.MultiGraph(XGM)
  168. assert nodes_equal(sorted(XGM.nodes()), sorted(GI.nodes()))
  169. assert edges_equal(sorted(XGM.edges()), sorted(GI.edges()))
  170. GM = nx.MultiGraph(G)
  171. assert nodes_equal(sorted(GM.nodes()), sorted(G.nodes()))
  172. assert edges_equal(sorted(GM.edges()), sorted(G.edges()))
  173. # Dict of lists
  174. # with multiedges, OK, but better write as DiGraph else you'll
  175. # get double edges
  176. dol = to_dict_of_lists(G)
  177. GG = from_dict_of_lists(dol, create_using=nx.MultiGraph)
  178. assert nodes_equal(sorted(G.nodes()), sorted(GG.nodes()))
  179. assert edges_equal(sorted(G.edges()), sorted(GG.edges()))
  180. GW = to_networkx_graph(dol, create_using=nx.MultiGraph)
  181. assert nodes_equal(sorted(G.nodes()), sorted(GW.nodes()))
  182. assert edges_equal(sorted(G.edges()), sorted(GW.edges()))
  183. GI = nx.MultiGraph(dol)
  184. assert nodes_equal(sorted(G.nodes()), sorted(GI.nodes()))
  185. assert edges_equal(sorted(G.edges()), sorted(GI.edges()))
  186. def test_edgelists(self):
  187. P = nx.path_graph(4)
  188. e = [(0, 1), (1, 2), (2, 3)]
  189. G = nx.Graph(e)
  190. assert nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
  191. assert edges_equal(sorted(G.edges()), sorted(P.edges()))
  192. assert edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
  193. e = [(0, 1, {}), (1, 2, {}), (2, 3, {})]
  194. G = nx.Graph(e)
  195. assert nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
  196. assert edges_equal(sorted(G.edges()), sorted(P.edges()))
  197. assert edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
  198. e = ((n, n + 1) for n in range(3))
  199. G = nx.Graph(e)
  200. assert nodes_equal(sorted(G.nodes()), sorted(P.nodes()))
  201. assert edges_equal(sorted(G.edges()), sorted(P.edges()))
  202. assert edges_equal(sorted(G.edges(data=True)), sorted(P.edges(data=True)))
  203. def test_directed_to_undirected(self):
  204. edges1 = [(0, 1), (1, 2), (2, 0)]
  205. edges2 = [(0, 1), (1, 2), (0, 2)]
  206. assert self.edgelists_equal(nx.Graph(nx.DiGraph(edges1)).edges(), edges1)
  207. assert self.edgelists_equal(nx.Graph(nx.DiGraph(edges2)).edges(), edges1)
  208. assert self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges1)).edges(), edges1)
  209. assert self.edgelists_equal(nx.MultiGraph(nx.DiGraph(edges2)).edges(), edges1)
  210. assert self.edgelists_equal(
  211. nx.MultiGraph(nx.MultiDiGraph(edges1)).edges(), edges1
  212. )
  213. assert self.edgelists_equal(
  214. nx.MultiGraph(nx.MultiDiGraph(edges2)).edges(), edges1
  215. )
  216. assert self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges1)).edges(), edges1)
  217. assert self.edgelists_equal(nx.Graph(nx.MultiDiGraph(edges2)).edges(), edges1)
  218. def test_attribute_dict_integrity(self):
  219. # we must not replace dict-like graph data structures with dicts
  220. G = nx.Graph()
  221. G.add_nodes_from("abc")
  222. H = to_networkx_graph(G, create_using=nx.Graph)
  223. assert list(H.nodes) == list(G.nodes)
  224. H = nx.DiGraph(G)
  225. assert list(H.nodes) == list(G.nodes)
  226. def test_to_edgelist(self):
  227. G = nx.Graph([(1, 1)])
  228. elist = nx.to_edgelist(G, nodelist=list(G))
  229. assert edges_equal(G.edges(data=True), elist)
  230. def test_custom_node_attr_dict_safekeeping(self):
  231. class custom_dict(dict):
  232. pass
  233. class Custom(nx.Graph):
  234. node_attr_dict_factory = custom_dict
  235. g = nx.Graph()
  236. g.add_node(1, weight=1)
  237. h = Custom(g)
  238. assert isinstance(g._node[1], dict)
  239. assert isinstance(h._node[1], custom_dict)
  240. # this raise exception
  241. # h._node.update((n, dd.copy()) for n, dd in g.nodes.items())
  242. # assert isinstance(h._node[1], custom_dict)
  243. @pytest.mark.parametrize(
  244. "edgelist",
  245. (
  246. # Graph with no edge data
  247. [(0, 1), (1, 2)],
  248. # Graph with edge data
  249. [(0, 1, {"weight": 1.0}), (1, 2, {"weight": 2.0})],
  250. ),
  251. )
  252. def test_to_dict_of_dicts_with_edgedata_param(edgelist):
  253. G = nx.Graph()
  254. G.add_edges_from(edgelist)
  255. # Innermost dict value == edge_data when edge_data != None.
  256. # In the case when G has edge data, it is overwritten
  257. expected = {0: {1: 10}, 1: {0: 10, 2: 10}, 2: {1: 10}}
  258. assert nx.to_dict_of_dicts(G, edge_data=10) == expected
  259. def test_to_dict_of_dicts_with_edgedata_and_nodelist():
  260. G = nx.path_graph(5)
  261. nodelist = [2, 3, 4]
  262. expected = {2: {3: 10}, 3: {2: 10, 4: 10}, 4: {3: 10}}
  263. assert nx.to_dict_of_dicts(G, nodelist=nodelist, edge_data=10) == expected
  264. def test_to_dict_of_dicts_with_edgedata_multigraph():
  265. """Multi edge data overwritten when edge_data != None"""
  266. G = nx.MultiGraph()
  267. G.add_edge(0, 1, key="a")
  268. G.add_edge(0, 1, key="b")
  269. # Multi edge data lost when edge_data is not None
  270. expected = {0: {1: 10}, 1: {0: 10}}
  271. assert nx.to_dict_of_dicts(G, edge_data=10) == expected
  272. def test_to_networkx_graph_non_edgelist():
  273. invalid_edgelist = [1, 2, 3]
  274. with pytest.raises(nx.NetworkXError, match="Input is not a valid edge list"):
  275. nx.to_networkx_graph(invalid_edgelist)