Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: sparse: Generalize coo_array to support 1d shapes #18530

Merged
merged 20 commits into from Dec 23, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 19 additions & 5 deletions scipy/sparse/_base.py
Expand Up @@ -67,7 +67,15 @@ class _spbase:

__array_priority__ = 10.1
_format = 'und' # undefined
ndim = 2

@property
def ndim(self) -> int:
return len(self._shape)

@property
def _shape_as_2d(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name is OK for now, but needs to be changed if we ever support any other dimensionality than 1 and 2.

s = self._shape
return (1, s[-1]) if len(s) == 1 else s

@property
def _bsr_container(self):
Expand Down Expand Up @@ -355,9 +363,11 @@ def imag(self):
def __repr__(self):
_, format_name = _formats[self.format]
sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
return f"<%dx%d sparse {sparse_cls} of type '%s'\n" \
"\twith %d stored elements in %s format>" % \
(self.shape + (self.dtype.type, self.nnz, format_name))
shape_str = 'x'.join(str(x) for x in self.shape)
perimosocordiae marked this conversation as resolved.
Show resolved Hide resolved
return (
f"<{shape_str} sparse {sparse_cls} of type '{self.dtype.type}'\n"
f"\twith {self.nnz} stored elements in {format_name} format>"
)

def __str__(self):
maxprint = self._getmaxprint()
Expand Down Expand Up @@ -568,7 +578,11 @@ def _mul_dispatch(self, other):
# This method has to be different from `__matmul__` because it is also
# called by sparse matrix classes.

M, N = self.shape
# Currently matrix multiplication is only supported
# for 2D arrays. Hence we unpacked and use only the
# two last axes' lengths.
N = self.shape[-1]
M = self.shape[-2] if self.ndim > 1 else 1
perimosocordiae marked this conversation as resolved.
Show resolved Hide resolved

if other.__class__ is np.ndarray:
# Fast path for the most common case
Expand Down
2 changes: 1 addition & 1 deletion scipy/sparse/_construct.py
Expand Up @@ -931,7 +931,7 @@ def block_diag(mats, format=None, dtype=None):
c_idx = 0
for a in mats:
if isinstance(a, (list, numbers.Number)):
a = coo_array(a)
a = coo_array(np.atleast_2d(a))
nrows, ncols = a.shape
if issparse(a):
a = a.tocoo()
Expand Down