diff --git a/CHANGELOG.md b/CHANGELOG.md index ce2624727..0bd7f406b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ ### Fixed +- `Graph.Weighted_Adjacency()` now sums duplicate entries in sparse + adjacency matrices before creating edges (#903). + - Errors raised while converting a boolean argument to a boolean (e.g. when passing a NumPy array with more than one element) are now propagated correctly instead of being treated as `True` and left pending. diff --git a/src/igraph/sparse_matrix.py b/src/igraph/sparse_matrix.py index 586d0aecf..1b382b1f8 100644 --- a/src/igraph/sparse_matrix.py +++ b/src/igraph/sparse_matrix.py @@ -159,19 +159,16 @@ def _graph_from_weighted_sparse_matrix( corresponding loop edge. When C{"twice"}, the diagonal is assumed to contain I{twice} the weight of the corresponding loop edge. """ - # This function assumes there is scipy and the matrix is a scipy sparse - # matrix. The caller should make sure those conditions are met. - from scipy import sparse - - if not isinstance(matrix, (sparse.coo_matrix, *([sparse.coo_array] if hasattr(sparse, "coo_array") else []))): - matrix = matrix.tocoo() - nvert = max(matrix.shape) if min(matrix.shape) != nvert: raise ValueError("Matrix must be square") - # Shorthand notation - m = matrix + # Multiple stored entries at one coordinate represent a single weight. + # Work on a copy so summing duplicates and dropping zeros leave the input intact. + m = matrix.tocoo(copy=True) + if not getattr(matrix, "has_canonical_format", False): + m.sum_duplicates() + m.eliminate_zeros() mode = _convert_mode_argument(mode) @@ -199,7 +196,7 @@ def _graph_from_weighted_sparse_matrix( pair = (i, j) if i < j else (j, i) nedges[pair] = fun(nedges.get(pair, 0), n) - edges, weights = zip(*nedges.items()) + edges, weights = list(nedges), list(nedges.values()) elif mode == "min": tmp = {(i, j): n for i, j, n in zip(m_row, m_col, m_data)} diff --git a/tests/test_generators.py b/tests/test_generators.py index 09f1dfa52..6026c3fe7 100644 --- a/tests/test_generators.py +++ b/tests/test_generators.py @@ -794,6 +794,40 @@ def testSparseWeightedAdjacency(self, cls): self.assertListEqual(el, [(0, 1), (0, 2), (1, 0), (2, 2), (3, 1)]) self.assertListEqual(g.es["w0"], [1, 2, 2, 1.25, 1]) + @parameterized.expand(["coo_array", "coo_matrix"]) + @unittest.skipIf(sparse is None, "test case depends on SciPy") + def testSparseWeightedAdjacencyDuplicateCoordinates(self, cls): + # The first two entries represent one edge of weight 2. The entries + # for (1, 2) cancel, and the two diagonal entries represent one loop. + values = [1, 1, 2, 5, -5, 1, 3] + rows = [0, 0, 1, 1, 1, 2, 2] + cols = [1, 1, 0, 2, 2, 2, 2] + mat = getattr(sparse, cls)((values, (rows, cols)), shape=(3, 3)) + dense = mat.toarray() + for mode in ("directed", "upper", "lower", "undirected", "max", "min", "plus"): + with self.subTest(mode=mode): + actual = Graph.Weighted_Adjacency(mat, mode=mode) + expected = Graph.Weighted_Adjacency(dense, mode=mode) + self.assertCountEqual( + zip(actual.get_edgelist(), actual.es["weight"]), + zip(expected.get_edgelist(), expected.es["weight"]), + ) + graph = Graph.Weighted_Adjacency(mat, loops="twice") + self.assertEqual(graph.es[graph.get_eid(2, 2)]["weight"], 2) + self.assertEqual(mat.data.tolist(), values) + self.assertEqual(mat.row.tolist(), rows) + self.assertEqual(mat.col.tolist(), cols) + + @unittest.skipIf(sparse is None, "test case depends on SciPy") + def testSparseWeightedAdjacencyCancellingDuplicates(self): + mat = sparse.coo_matrix(([1, -1], ([0, 0], [1, 1])), shape=(2, 2)) + for mode in ("directed", "max", "plus"): + with self.subTest(mode=mode): + graph = Graph.Weighted_Adjacency(mat, mode=mode) + self.assertEqual(graph.vcount(), 2) + self.assertEqual(graph.ecount(), 0) + self.assertEqual(graph.es["weight"], []) + @unittest.skipIf((np is None) or (pd is None), "test case depends on NumPy/Pandas") def testDataFrame(self): edges = pd.DataFrame(