test_convert_numpy.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import pytest
  2. np = pytest.importorskip("numpy")
  3. npt = pytest.importorskip("numpy.testing")
  4. import networkx as nx
  5. from networkx.generators.classic import barbell_graph, cycle_graph, path_graph
  6. from networkx.utils import graphs_equal
  7. class TestConvertNumpyArray:
  8. def setup_method(self):
  9. self.G1 = barbell_graph(10, 3)
  10. self.G2 = cycle_graph(10, create_using=nx.DiGraph)
  11. self.G3 = self.create_weighted(nx.Graph())
  12. self.G4 = self.create_weighted(nx.DiGraph())
  13. def create_weighted(self, G):
  14. g = cycle_graph(4)
  15. G.add_nodes_from(g)
  16. G.add_weighted_edges_from((u, v, 10 + u) for u, v in g.edges())
  17. return G
  18. def assert_equal(self, G1, G2):
  19. assert sorted(G1.nodes()) == sorted(G2.nodes())
  20. assert sorted(G1.edges()) == sorted(G2.edges())
  21. def identity_conversion(self, G, A, create_using):
  22. assert A.sum() > 0
  23. GG = nx.from_numpy_array(A, create_using=create_using)
  24. self.assert_equal(G, GG)
  25. GW = nx.to_networkx_graph(A, create_using=create_using)
  26. self.assert_equal(G, GW)
  27. GI = nx.empty_graph(0, create_using).__class__(A)
  28. self.assert_equal(G, GI)
  29. def test_shape(self):
  30. "Conversion from non-square array."
  31. A = np.array([[1, 2, 3], [4, 5, 6]])
  32. pytest.raises(nx.NetworkXError, nx.from_numpy_array, A)
  33. def test_identity_graph_array(self):
  34. "Conversion from graph to array to graph."
  35. A = nx.to_numpy_array(self.G1)
  36. self.identity_conversion(self.G1, A, nx.Graph())
  37. def test_identity_digraph_array(self):
  38. """Conversion from digraph to array to digraph."""
  39. A = nx.to_numpy_array(self.G2)
  40. self.identity_conversion(self.G2, A, nx.DiGraph())
  41. def test_identity_weighted_graph_array(self):
  42. """Conversion from weighted graph to array to weighted graph."""
  43. A = nx.to_numpy_array(self.G3)
  44. self.identity_conversion(self.G3, A, nx.Graph())
  45. def test_identity_weighted_digraph_array(self):
  46. """Conversion from weighted digraph to array to weighted digraph."""
  47. A = nx.to_numpy_array(self.G4)
  48. self.identity_conversion(self.G4, A, nx.DiGraph())
  49. def test_nodelist(self):
  50. """Conversion from graph to array to graph with nodelist."""
  51. P4 = path_graph(4)
  52. P3 = path_graph(3)
  53. nodelist = list(P3)
  54. A = nx.to_numpy_array(P4, nodelist=nodelist)
  55. GA = nx.Graph(A)
  56. self.assert_equal(GA, P3)
  57. # Make nodelist ambiguous by containing duplicates.
  58. nodelist += [nodelist[0]]
  59. pytest.raises(nx.NetworkXError, nx.to_numpy_array, P3, nodelist=nodelist)
  60. # Make nodelist invalid by including non-existent nodes
  61. nodelist = [-1, 0, 1]
  62. with pytest.raises(
  63. nx.NetworkXError,
  64. match=f"Nodes {nodelist - P3.nodes} in nodelist is not in G",
  65. ):
  66. nx.to_numpy_array(P3, nodelist=nodelist)
  67. def test_weight_keyword(self):
  68. WP4 = nx.Graph()
  69. WP4.add_edges_from((n, n + 1, {"weight": 0.5, "other": 0.3}) for n in range(3))
  70. P4 = path_graph(4)
  71. A = nx.to_numpy_array(P4)
  72. np.testing.assert_equal(A, nx.to_numpy_array(WP4, weight=None))
  73. np.testing.assert_equal(0.5 * A, nx.to_numpy_array(WP4))
  74. np.testing.assert_equal(0.3 * A, nx.to_numpy_array(WP4, weight="other"))
  75. def test_from_numpy_array_type(self):
  76. A = np.array([[1]])
  77. G = nx.from_numpy_array(A)
  78. assert type(G[0][0]["weight"]) == int
  79. A = np.array([[1]]).astype(float)
  80. G = nx.from_numpy_array(A)
  81. assert type(G[0][0]["weight"]) == float
  82. A = np.array([[1]]).astype(str)
  83. G = nx.from_numpy_array(A)
  84. assert type(G[0][0]["weight"]) == str
  85. A = np.array([[1]]).astype(bool)
  86. G = nx.from_numpy_array(A)
  87. assert type(G[0][0]["weight"]) == bool
  88. A = np.array([[1]]).astype(complex)
  89. G = nx.from_numpy_array(A)
  90. assert type(G[0][0]["weight"]) == complex
  91. A = np.array([[1]]).astype(object)
  92. pytest.raises(TypeError, nx.from_numpy_array, A)
  93. A = np.array([[[1, 1, 1], [1, 1, 1]], [[1, 1, 1], [1, 1, 1]]])
  94. with pytest.raises(
  95. nx.NetworkXError, match=f"Input array must be 2D, not {A.ndim}"
  96. ):
  97. g = nx.from_numpy_array(A)
  98. def test_from_numpy_array_dtype(self):
  99. dt = [("weight", float), ("cost", int)]
  100. A = np.array([[(1.0, 2)]], dtype=dt)
  101. G = nx.from_numpy_array(A)
  102. assert type(G[0][0]["weight"]) == float
  103. assert type(G[0][0]["cost"]) == int
  104. assert G[0][0]["cost"] == 2
  105. assert G[0][0]["weight"] == 1.0
  106. def test_from_numpy_array_parallel_edges(self):
  107. """Tests that the :func:`networkx.from_numpy_array` function
  108. interprets integer weights as the number of parallel edges when
  109. creating a multigraph.
  110. """
  111. A = np.array([[1, 1], [1, 2]])
  112. # First, with a simple graph, each integer entry in the adjacency
  113. # matrix is interpreted as the weight of a single edge in the graph.
  114. expected = nx.DiGraph()
  115. edges = [(0, 0), (0, 1), (1, 0)]
  116. expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
  117. expected.add_edge(1, 1, weight=2)
  118. actual = nx.from_numpy_array(A, parallel_edges=True, create_using=nx.DiGraph)
  119. assert graphs_equal(actual, expected)
  120. actual = nx.from_numpy_array(A, parallel_edges=False, create_using=nx.DiGraph)
  121. assert graphs_equal(actual, expected)
  122. # Now each integer entry in the adjacency matrix is interpreted as the
  123. # number of parallel edges in the graph if the appropriate keyword
  124. # argument is specified.
  125. edges = [(0, 0), (0, 1), (1, 0), (1, 1), (1, 1)]
  126. expected = nx.MultiDiGraph()
  127. expected.add_weighted_edges_from([(u, v, 1) for (u, v) in edges])
  128. actual = nx.from_numpy_array(
  129. A, parallel_edges=True, create_using=nx.MultiDiGraph
  130. )
  131. assert graphs_equal(actual, expected)
  132. expected = nx.MultiDiGraph()
  133. expected.add_edges_from(set(edges), weight=1)
  134. # The sole self-loop (edge 0) on vertex 1 should have weight 2.
  135. expected[1][1][0]["weight"] = 2
  136. actual = nx.from_numpy_array(
  137. A, parallel_edges=False, create_using=nx.MultiDiGraph
  138. )
  139. assert graphs_equal(actual, expected)
  140. def test_symmetric(self):
  141. """Tests that a symmetric array has edges added only once to an
  142. undirected multigraph when using :func:`networkx.from_numpy_array`.
  143. """
  144. A = np.array([[0, 1], [1, 0]])
  145. G = nx.from_numpy_array(A, create_using=nx.MultiGraph)
  146. expected = nx.MultiGraph()
  147. expected.add_edge(0, 1, weight=1)
  148. assert graphs_equal(G, expected)
  149. def test_dtype_int_graph(self):
  150. """Test that setting dtype int actually gives an integer array.
  151. For more information, see GitHub pull request #1363.
  152. """
  153. G = nx.complete_graph(3)
  154. A = nx.to_numpy_array(G, dtype=int)
  155. assert A.dtype == int
  156. def test_dtype_int_multigraph(self):
  157. """Test that setting dtype int actually gives an integer array.
  158. For more information, see GitHub pull request #1363.
  159. """
  160. G = nx.MultiGraph(nx.complete_graph(3))
  161. A = nx.to_numpy_array(G, dtype=int)
  162. assert A.dtype == int
  163. @pytest.fixture
  164. def multigraph_test_graph():
  165. G = nx.MultiGraph()
  166. G.add_edge(1, 2, weight=7)
  167. G.add_edge(1, 2, weight=70)
  168. return G
  169. @pytest.mark.parametrize(("operator", "expected"), ((sum, 77), (min, 7), (max, 70)))
  170. def test_numpy_multigraph(multigraph_test_graph, operator, expected):
  171. A = nx.to_numpy_array(multigraph_test_graph, multigraph_weight=operator)
  172. assert A[1, 0] == expected
  173. def test_to_numpy_array_multigraph_nodelist(multigraph_test_graph):
  174. G = multigraph_test_graph
  175. G.add_edge(0, 1, weight=3)
  176. A = nx.to_numpy_array(G, nodelist=[1, 2])
  177. assert A.shape == (2, 2)
  178. assert A[1, 0] == 77
  179. @pytest.mark.parametrize(
  180. "G, expected",
  181. [
  182. (nx.Graph(), np.array([[0, 1 + 2j], [1 + 2j, 0]], dtype=complex)),
  183. (nx.DiGraph(), np.array([[0, 1 + 2j], [0, 0]], dtype=complex)),
  184. ],
  185. )
  186. def test_to_numpy_array_complex_weights(G, expected):
  187. G.add_edge(0, 1, weight=1 + 2j)
  188. A = nx.to_numpy_array(G, dtype=complex)
  189. npt.assert_array_equal(A, expected)
  190. def test_to_numpy_array_arbitrary_weights():
  191. G = nx.DiGraph()
  192. w = 922337203685477580102 # Out of range for int64
  193. G.add_edge(0, 1, weight=922337203685477580102) # val not representable by int64
  194. A = nx.to_numpy_array(G, dtype=object)
  195. expected = np.array([[0, w], [0, 0]], dtype=object)
  196. npt.assert_array_equal(A, expected)
  197. # Undirected
  198. A = nx.to_numpy_array(G.to_undirected(), dtype=object)
  199. expected = np.array([[0, w], [w, 0]], dtype=object)
  200. npt.assert_array_equal(A, expected)
  201. @pytest.mark.parametrize(
  202. "func, expected",
  203. ((min, -1), (max, 10), (sum, 11), (np.mean, 11 / 3), (np.median, 2)),
  204. )
  205. def test_to_numpy_array_multiweight_reduction(func, expected):
  206. """Test various functions for reducing multiedge weights."""
  207. G = nx.MultiDiGraph()
  208. weights = [-1, 2, 10.0]
  209. for w in weights:
  210. G.add_edge(0, 1, weight=w)
  211. A = nx.to_numpy_array(G, multigraph_weight=func, dtype=float)
  212. assert np.allclose(A, [[0, expected], [0, 0]])
  213. # Undirected case
  214. A = nx.to_numpy_array(G.to_undirected(), multigraph_weight=func, dtype=float)
  215. assert np.allclose(A, [[0, expected], [expected, 0]])
  216. @pytest.mark.parametrize(
  217. ("G, expected"),
  218. [
  219. (nx.Graph(), [[(0, 0), (10, 5)], [(10, 5), (0, 0)]]),
  220. (nx.DiGraph(), [[(0, 0), (10, 5)], [(0, 0), (0, 0)]]),
  221. ],
  222. )
  223. def test_to_numpy_array_structured_dtype_attrs_from_fields(G, expected):
  224. """When `dtype` is structured (i.e. has names) and `weight` is None, use
  225. the named fields of the dtype to look up edge attributes."""
  226. G.add_edge(0, 1, weight=10, cost=5.0)
  227. dtype = np.dtype([("weight", int), ("cost", int)])
  228. A = nx.to_numpy_array(G, dtype=dtype, weight=None)
  229. expected = np.asarray(expected, dtype=dtype)
  230. npt.assert_array_equal(A, expected)
  231. def test_to_numpy_array_structured_dtype_single_attr_default():
  232. G = nx.path_graph(3)
  233. dtype = np.dtype([("weight", float)]) # A single named field
  234. A = nx.to_numpy_array(G, dtype=dtype, weight=None)
  235. expected = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=float)
  236. npt.assert_array_equal(A["weight"], expected)
  237. @pytest.mark.parametrize(
  238. ("field_name", "expected_attr_val"),
  239. [
  240. ("weight", 1),
  241. ("cost", 3),
  242. ],
  243. )
  244. def test_to_numpy_array_structured_dtype_single_attr(field_name, expected_attr_val):
  245. G = nx.Graph()
  246. G.add_edge(0, 1, cost=3)
  247. dtype = np.dtype([(field_name, float)])
  248. A = nx.to_numpy_array(G, dtype=dtype, weight=None)
  249. expected = np.array([[0, expected_attr_val], [expected_attr_val, 0]], dtype=float)
  250. npt.assert_array_equal(A[field_name], expected)
  251. @pytest.mark.parametrize("graph_type", (nx.Graph, nx.DiGraph))
  252. @pytest.mark.parametrize(
  253. "edge",
  254. [
  255. (0, 1), # No edge attributes
  256. (0, 1, {"weight": 10}), # One edge attr
  257. (0, 1, {"weight": 5, "flow": -4}), # Multiple but not all edge attrs
  258. (0, 1, {"weight": 2.0, "cost": 10, "flow": -45}), # All attrs
  259. ],
  260. )
  261. def test_to_numpy_array_structured_dtype_multiple_fields(graph_type, edge):
  262. G = graph_type([edge])
  263. dtype = np.dtype([("weight", float), ("cost", float), ("flow", float)])
  264. A = nx.to_numpy_array(G, dtype=dtype, weight=None)
  265. for attr in dtype.names:
  266. expected = nx.to_numpy_array(G, dtype=float, weight=attr)
  267. npt.assert_array_equal(A[attr], expected)
  268. @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
  269. def test_to_numpy_array_structured_dtype_scalar_nonedge(G):
  270. G.add_edge(0, 1, weight=10)
  271. dtype = np.dtype([("weight", float), ("cost", float)])
  272. A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=np.nan)
  273. for attr in dtype.names:
  274. expected = nx.to_numpy_array(G, dtype=float, weight=attr, nonedge=np.nan)
  275. npt.assert_array_equal(A[attr], expected)
  276. @pytest.mark.parametrize("G", (nx.Graph(), nx.DiGraph()))
  277. def test_to_numpy_array_structured_dtype_nonedge_ary(G):
  278. """Similar to the scalar case, except has a different non-edge value for
  279. each named field."""
  280. G.add_edge(0, 1, weight=10)
  281. dtype = np.dtype([("weight", float), ("cost", float)])
  282. nonedges = np.array([(0, np.inf)], dtype=dtype)
  283. A = nx.to_numpy_array(G, dtype=dtype, weight=None, nonedge=nonedges)
  284. for attr in dtype.names:
  285. nonedge = nonedges[attr]
  286. expected = nx.to_numpy_array(G, dtype=float, weight=attr, nonedge=nonedge)
  287. npt.assert_array_equal(A[attr], expected)
  288. def test_to_numpy_array_structured_dtype_with_weight_raises():
  289. """Using both a structured dtype (with named fields) and specifying a `weight`
  290. parameter is ambiguous."""
  291. G = nx.path_graph(3)
  292. dtype = np.dtype([("weight", int), ("cost", int)])
  293. exception_msg = "Specifying `weight` not supported for structured dtypes"
  294. with pytest.raises(ValueError, match=exception_msg):
  295. nx.to_numpy_array(G, dtype=dtype) # Default is weight="weight"
  296. with pytest.raises(ValueError, match=exception_msg):
  297. nx.to_numpy_array(G, dtype=dtype, weight="cost")
  298. @pytest.mark.parametrize("graph_type", (nx.MultiGraph, nx.MultiDiGraph))
  299. def test_to_numpy_array_structured_multigraph_raises(graph_type):
  300. G = nx.path_graph(3, create_using=graph_type)
  301. dtype = np.dtype([("weight", int), ("cost", int)])
  302. with pytest.raises(nx.NetworkXError, match="Structured arrays are not supported"):
  303. nx.to_numpy_array(G, dtype=dtype, weight=None)