From bc9d407603898da66fabd616f60540506f5bdce7 Mon Sep 17 00:00:00 2001 From: Michael Lamparski Date: Mon, 21 Jan 2019 11:30:40 -0500 Subject: [PATCH] BUG: tighten condition for bsr eliminate_zeros fast path (#9690) * BUG: tighten condition for bsr eliminate_zeros fast path * move test as requested by CJ --- scipy/sparse/bsr.py | 7 ++++--- scipy/sparse/tests/test_base.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/scipy/sparse/bsr.py b/scipy/sparse/bsr.py index 8e4a85138c2d..4d53d37824fa 100644 --- a/scipy/sparse/bsr.py +++ b/scipy/sparse/bsr.py @@ -542,6 +542,10 @@ def transpose(self, axes=None, copy=False): def eliminate_zeros(self): """Remove zero elements in-place.""" + + if not self.nnz: + return # nothing to do + R,C = self.blocksize M,N = self.shape @@ -549,9 +553,6 @@ def eliminate_zeros(self): nonzero_blocks = mask.nonzero()[0] - if len(nonzero_blocks) == 0: - return # nothing to do - self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks] # modifies self.indptr and self.indices *in place* diff --git a/scipy/sparse/tests/test_base.py b/scipy/sparse/tests/test_base.py index fcc693dc74f5..b0e2d5b6205a 100644 --- a/scipy/sparse/tests/test_base.py +++ b/scipy/sparse/tests/test_base.py @@ -4239,6 +4239,30 @@ def test_eliminate_zeros(self): assert_array_equal(asp.nnz, 3*4) assert_array_equal(asp.todense(),bsp.todense()) + # github issue #9687 + def test_eliminate_zeros_all_zero(self): + np.random.seed(0) + m = bsr_matrix(np.random.random((12, 12)), blocksize=(2, 3)) + + # eliminate some blocks, but not all + m.data[m.data <= 0.9] = 0 + m.eliminate_zeros() + assert_equal(m.nnz, 66) + assert_array_equal(m.data.shape, (11, 2, 3)) + + # eliminate all remaining blocks + m.data[m.data <= 1.0] = 0 + m.eliminate_zeros() + assert_equal(m.nnz, 0) + assert_array_equal(m.data.shape, (0, 2, 3)) + assert_array_equal(m.todense(), np.zeros((12,12))) + + # test fast path + m.eliminate_zeros() + assert_equal(m.nnz, 0) + assert_array_equal(m.data.shape, (0, 2, 3)) + assert_array_equal(m.todense(), np.zeros((12,12))) + def test_bsr_matvec(self): A = bsr_matrix(arange(2*3*4*5).reshape(2*4,3*5), blocksize=(4,5)) x = arange(A.shape[1]).reshape(-1,1)