Skip to content

Commit

Permalink
Merge pull request #598 from pfebrer/sparse_fixes
Browse files Browse the repository at this point in the history
maint: Adapt to breaking changes in scipy.sparse.isspmatrix
  • Loading branch information
zerothi authored Jul 13, 2023
2 parents 1ef16ed + 3b6a434 commit 708e494
Show file tree
Hide file tree
Showing 8 changed files with 28 additions and 27 deletions.
4 changes: 2 additions & 2 deletions src/sisl/io/tbtrans/tbt.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
ndarray = np.ndarray

# The sparse matrix for the orbital/bond currents
from scipy.sparse import SparseEfficiencyWarning, csr_matrix, isspmatrix_csr
from scipy.sparse import SparseEfficiencyWarning, csr_matrix, issparse

import sisl._array as _a
from sisl import Atoms, Geometry, constant
Expand Down Expand Up @@ -1158,7 +1158,7 @@ def map_col(c):
map_col = o2a

# Lets do array notation for speeding up the computations
if not isspmatrix_csr(Dij):
if not (issparse(Dij) and Dij.format == 'csr'):
Dij = Dij.tocsr()

# Check for the simple case of 1-orbital systems
Expand Down
4 changes: 2 additions & 2 deletions src/sisl/physics/electron.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
sort,
zeros,
)
from scipy.sparse import csr_matrix, hstack, identity, isspmatrix
from scipy.sparse import csr_matrix, hstack, identity, issparse

import sisl._array as _a
from sisl import Geometry, Grid, Lattice, constant, units
Expand Down Expand Up @@ -374,7 +374,7 @@ def tosize(diag, idx):

cop = oplist(tosize(d, idx) for d in cop)

elif isspmatrix(M):
elif issparse(M):

# create the new list
cop0 = M.multiply(0.).real
Expand Down
4 changes: 2 additions & 2 deletions src/sisl/physics/sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import sisl.linalg as lin
from sisl._internal import set_module
from sisl.messages import warn
from sisl.sparse import isspmatrix
from sisl.sparse import issparse
from sisl.sparse_geometry import SparseOrbital

from ._matrix_ddk import matrix_ddk, matrix_ddk_nc, matrix_ddk_nc_diag, matrix_ddk_so
Expand Down Expand Up @@ -148,7 +148,7 @@ def fromsp(cls, geometry, P, S=None, **kwargs):
a new sparse matrix that holds the passed geometry and the elements of `P` and optionally being non-orthogonal if `S` is not none
"""
# Ensure list of csr format (to get dimensions)
if isspmatrix(P):
if issparse(P):
P = [P]
if isinstance(P, tuple):
P = list(P)
Expand Down
4 changes: 2 additions & 2 deletions src/sisl/physics/tests/test_hamiltonian.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import numpy as np
import pytest
from scipy.linalg import block_diag
from scipy.sparse import SparseEfficiencyWarning, isspmatrix
from scipy.sparse import SparseEfficiencyWarning, issparse

from sisl import (
Atom,
Expand Down Expand Up @@ -1240,7 +1240,7 @@ def test_coop_sp_vs_np(self, setup):
for k in ([0] *3, [0.2] * 3):
es = HS.eigenstate(k)
COOP_sp = es.COOP(E, 'lorentzian')
assert isspmatrix(COOP_sp[0])
assert issparse(COOP_sp[0])

es = HS.eigenstate(k, format='array')
COOP_np = es.COOP(E, 'lorentzian')
Expand Down
31 changes: 16 additions & 15 deletions src/sisl/sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
isspmatrix_csc,
isspmatrix_csr,
isspmatrix_lil,
issparse,
spmatrix,
)

Expand Down Expand Up @@ -139,7 +140,7 @@ def __init__(self, arg1, dim=1, dtype=None, nnzpr=20, nnz=None,
# for the insert row is increased at least by this number
self._ns = 10

if isspmatrix(arg1):
if issparse(arg1):
# This is a sparse matrix
# The data-type is infered from the
# input sparse matrix.
Expand Down Expand Up @@ -1387,8 +1388,8 @@ def copy(self, dims=None, dtype=None):
# The default sizes are not passed
# Hence we *must* copy the arrays
# directly
copyto(new.ptr, self.ptr, casting='no')
copyto(new.ncol, self.ncol, casting='no')
copyto(new.ptr, self.ptr, casting='same_kind')
copyto(new.ncol, self.ncol, casting='same_kind')
new.col = self.col.copy()
new._nnz = self.nnz

Expand Down Expand Up @@ -2050,7 +2051,7 @@ def ispmatrix(matrix, map_row=None, map_col=None):
#it = np.nditer([geom.o2a(tmp.row), geom.o2a(tmp.col % geom.no), tmp.data],
# flags=['buffered'], op_flags=['readonly'])

if isspmatrix_csr(matrix):
if issparse(matrix) and matrix.format == "csr":
for r in range(matrix.shape[0]):
rr = map_row(r)
if rows[rr]: continue
Expand All @@ -2062,7 +2063,7 @@ def ispmatrix(matrix, map_row=None, map_col=None):
cols[c] = True
yield rr, c

elif isspmatrix_lil(matrix):
elif issparse(matrix) and matrix.format == "lil":
for r in range(matrix.shape[0]):
rr = map_row(r)
if rows[rr]: continue
Expand All @@ -2075,10 +2076,10 @@ def ispmatrix(matrix, map_row=None, map_col=None):
cols[c] = True
yield rr, c

elif isspmatrix_coo(matrix):
elif issparse(matrix) and matrix.format == "coo":
raise ValueError("mapping and unique returns are not implemented for COO matrix")

elif isspmatrix_csc(matrix):
elif issparse(matrix) and matrix.format == "csc":
raise ValueError("mapping and unique returns are not implemented for CSC matrix")

elif isinstance(matrix, SparseCSR):
Expand Down Expand Up @@ -2113,20 +2114,20 @@ def _ispmatrix_all(matrix):
int, int
the row, column indices of the non-zero elements
"""
if isspmatrix_csr(matrix):
if issparse(matrix) and matrix.format == "csr":
for r in range(matrix.shape[0]):
for ind in range(matrix.indptr[r], matrix.indptr[r+1]):
yield r, matrix.indices[ind]

elif isspmatrix_lil(matrix):
elif issparse(matrix) and matrix.format == "lil":
for r in range(matrix.shape[0]):
for c in matrix.rows[r]:
yield r, c

elif isspmatrix_coo(matrix):
elif issparse(matrix) and matrix.format == "coo":
yield from zip(matrix.row, matrix.col)

elif isspmatrix_csc(matrix):
elif issparse(matrix) and matrix.format == "csc":
for c in range(matrix.shape[1]):
for ind in range(matrix.indptr[c], matrix.indptr[c+1]):
yield matrix.indices[ind], c
Expand Down Expand Up @@ -2171,22 +2172,22 @@ def ispmatrixd(matrix, map_row=None, map_col=None):
#it = np.nditer([geom.o2a(tmp.row), geom.o2a(tmp.col % geom.no), tmp.data],
# flags=['buffered'], op_flags=['readonly'])

if isspmatrix_csr(matrix):
if issparse(matrix) and matrix.format == "csr":
for r in range(matrix.shape[0]):
rr = map_row(r)
for ind in range(matrix.indptr[r], matrix.indptr[r+1]):
yield rr, map_col(matrix.indices[ind]), matrix.data[ind]

elif isspmatrix_lil(matrix):
elif issparse(matrix) and matrix.format == "lil":
for r in range(matrix.shape[0]):
rr = map_row(r)
for c, m in zip(map_col(matrix.rows[r]), matrix.data[r]):
yield rr, c, m

elif isspmatrix_coo(matrix):
elif issparse(matrix) and matrix.format == "coo":
yield from zip(map_row(matrix.row), map_col(matrix.col), matrix.data)

elif isspmatrix_csc(matrix):
elif issparse(matrix) and matrix.format == "csc":
for c in range(matrix.shape[1]):
cc = map_col(c)
for ind in range(matrix.indptr[c], matrix.indptr[c+1]):
Expand Down
4 changes: 2 additions & 2 deletions src/sisl/sparse_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
from .geometry import Geometry
from .messages import SislError, SislWarning, progressbar, warn
from .orbital import Orbital
from .sparse import SparseCSR, _ncol_to_indptr, isspmatrix
from .sparse import SparseCSR, _ncol_to_indptr, issparse
from .utils.ranges import list2str

__all__ = ['SparseAtom', 'SparseOrbital']
Expand Down Expand Up @@ -1078,7 +1078,7 @@ def fromsp(cls, geometry, P, **kwargs):
a new sparse matrix that holds the passed geometry and the elements of `P`
"""
# Ensure list of * format (to get dimensions)
if isspmatrix(P):
if issparse(P):
P = [P]
if isinstance(P, tuple):
P = list(P)
Expand Down
2 changes: 1 addition & 1 deletion src/sisl/tests/test_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1357,10 +1357,10 @@ def test_sparse_column_out_of_bounds(j):
with pytest.raises(IndexError):
S[0, j] = 1


def test_fromsp_csr():
csr1 = sc.sparse.random(10, 100, 0.01, random_state=24812)
csr2 = sc.sparse.random(10, 100, 0.02, random_state=24813)

csr = SparseCSR.fromsp(csr1, csr2)
csr_1 = csr.tocsr(0)
csr_2 = csr.tocsr(1)
Expand Down
2 changes: 1 addition & 1 deletion src/sisl_toolbox/btd/_btd.py
Original file line number Diff line number Diff line change
Expand Up @@ -918,7 +918,7 @@ def _matrix_to_btd(self, M):
BI = BM.block_indexer
c = self.btd_cum0
nb = len(BI)
if ssp.isspmatrix(M):
if ssp.issparse(M):
for jb in range(nb):
for ib in range(max(0, jb-1), min(jb+2, nb)):
BI[ib, jb] = M[c[ib]:c[ib+1], c[jb]:c[jb+1]].toarray()
Expand Down

0 comments on commit 708e494

Please sign in to comment.