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

feat: Add __binsparse__ protocol. #764

Draft
wants to merge 14 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ jobs:
pip install -e '.[tests]'
- name: Run tests
run: ci/test_backends.sh
- uses: codecov/codecov-action@v5
- uses: codecov/codecov-action@2e6e9c5a74ec004831b6d17edfb76c53a54d4d55
if: always()
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./**/coverage*.xml
files: "\"./**/coverage*.xml\""

examples:
runs-on: ubuntu-latest
Expand Down
3 changes: 2 additions & 1 deletion sparse/numba_backend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@
where,
)
from ._dok import DOK
from ._io import load_npz, save_npz
from ._io import from_binsparse, load_npz, save_npz
from ._umath import elemwise
from ._utils import random

Expand Down Expand Up @@ -226,6 +226,7 @@
"float64",
"floor",
"floor_divide",
"from_binsparse",
"full",
"full_like",
"greater",
Expand Down
2 changes: 1 addition & 1 deletion sparse/numba_backend/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def _check_device(func):
def wrapped(*args, **kwargs):
device = kwargs.get("device")
if device not in {"cpu", None}:
raise ValueError("Device must be `'cpu'` or `None`.")
raise BufferError("Device must be `'cpu'` or `None`.")
return func(*args, **kwargs)

return wrapped
Expand Down
68 changes: 35 additions & 33 deletions sparse/numba_backend/_compressed/compressed.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from .._coo.core import COO
from .._sparse_array import SparseArray
from .._utils import (
_zero_of_dtype,
can_store,
check_compressed_axes,
check_fill_value,
Expand Down Expand Up @@ -175,13 +174,9 @@
if self.data.ndim != 1:
raise ValueError("data must be a scalar or 1-dimensional.")

self.shape = shape

if fill_value is None:
fill_value = _zero_of_dtype(self.data.dtype)
SparseArray.__init__(self, shape=shape, fill_value=fill_value)

self._compressed_axes = tuple(compressed_axes) if isinstance(compressed_axes, Iterable) else None
self.fill_value = self.data.dtype.type(fill_value)

if prune:
self._prune()
Expand Down Expand Up @@ -259,32 +254,6 @@
"""
return self.data.shape[0]

@property
def format(self):
"""
The storage format of this array.

Returns
-------
str
The storage format of this array.

See Also
-------
[`scipy.sparse.dok_matrix.format`][] : The Scipy equivalent property.

Examples
-------
>>> import sparse
>>> s = sparse.random((5, 5), density=0.2, format="dok")
>>> s.format
'dok'
>>> t = sparse.random((5, 5), density=0.2, format="coo")
>>> t.format
'coo'
"""
return "gcxs"

@property
def nbytes(self):
"""
Expand Down Expand Up @@ -443,7 +412,7 @@
fill_value=self.fill_value,
)
uncompressed = uncompress_dimension(self.indptr)
coords = np.vstack((uncompressed, self.indices))
coords = np.stack((uncompressed, self.indices))
order = np.argsort(self._axis_order)
return (
COO(
Expand Down Expand Up @@ -844,6 +813,15 @@
def isnan(self):
return self.tocoo().isnan().asformat("gcxs", compressed_axes=self.compressed_axes)

# `GCXS` is a reshaped/transposed `CSR`, but it can't (usually)
# be expressed in the `binsparse` 0.1 language.
# We are missing index maps.
def __binsparse__(self) -> dict:
return super().__binsparse__()

Check warning on line 820 in sparse/numba_backend/_compressed/compressed.py

View check run for this annotation

Codecov / codecov/patch

sparse/numba_backend/_compressed/compressed.py#L820

Added line #L820 was not covered by tests

def __binsparse_descriptor__(self) -> dict[str, np.ndarray]:
return super().__binsparse_descriptor__()

Check warning on line 823 in sparse/numba_backend/_compressed/compressed.py

View check run for this annotation

Codecov / codecov/patch

sparse/numba_backend/_compressed/compressed.py#L823

Added line #L823 was not covered by tests


class _Compressed2d(GCXS):
class_compressed_axes: tuple[int]
Expand Down Expand Up @@ -883,6 +861,30 @@
coo = COO.from_numpy(x, fill_value=fill_value, idx_dtype=idx_dtype)
return cls.from_coo(coo, cls.class_compressed_axes, idx_dtype)

def __binsparse_descriptor__(self) -> dict:
from sparse._version import __version__

data_dt = str(self.data.dtype)
if np.issubdtype(data_dt, np.complexfloating):
data_dt = f"complex[float{self.data.dtype.itemsize * 4}]"

Check warning on line 869 in sparse/numba_backend/_compressed/compressed.py

View check run for this annotation

Codecov / codecov/patch

sparse/numba_backend/_compressed/compressed.py#L869

Added line #L869 was not covered by tests
return {
"binsparse": {
"version": "0.1",
"format": self.format.upper(),
"shape": list(self.shape),
"number_of_stored_values": self.nnz,
"data_types": {
"pointers_to_1": str(self.indices.dtype),
"indices_1": str(self.indptr.dtype),
"values": data_dt,
},
},
"original_source": f"`sparse`, version {__version__}",
}

def __binsparse__(self) -> dict[str, np.ndarray]:
return {"pointers_to_1": self.indptr, "indices_1": self.indices, "values": self.data}


class CSR(_Compressed2d):
"""
Expand Down
63 changes: 40 additions & 23 deletions sparse/numba_backend/_coo/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,29 +601,6 @@
"""
return self.coords.shape[1]

@property
def format(self):
"""
The storage format of this array.
Returns
-------
str
The storage format of this array.
See Also
--------
[`scipy.sparse.dok_matrix.format`][] : The Scipy equivalent property.
Examples
-------
>>> import sparse
>>> s = sparse.random((5, 5), density=0.2, format="dok")
>>> s.format
'dok'
>>> t = sparse.random((5, 5), density=0.2, format="coo")
>>> t.format
'coo'
"""
return "coo"

@property
def nbytes(self):
"""
Expand Down Expand Up @@ -1538,6 +1515,46 @@
prune=True,
)

def __binsparse_descriptor__(self) -> dict:
from sparse._version import __version__

data_dt = str(self.data.dtype)
if np.issubdtype(data_dt, np.complexfloating):
data_dt = f"complex[float{self.data.dtype.itemsize * 4}]"

Check warning on line 1523 in sparse/numba_backend/_coo/core.py

View check run for this annotation

Codecov / codecov/patch

sparse/numba_backend/_coo/core.py#L1523

Added line #L1523 was not covered by tests
return {
"binsparse": {
"version": "0.1",
"format": {
"custom": {
"level": {
"level_desc": "sparse",
"rank": self.ndim,
"level": {
"level_desc": "element",
},
}
}
}
if self.ndim != 2
else "COOR",
"shape": list(self.shape),
"number_of_stored_values": self.nnz,
"data_types": {
"pointers_to_1": "uint64",
"indices_1": str(self.coords.dtype),
"values": data_dt,
},
},
"original_source": f"`sparse`, version {__version__}",
}

def __binsparse__(self) -> dict[str, np.ndarray]:
return {
"pointers_to_1": np.array([0, self.nnz], dtype=np.uint64),
"indices_1": self.coords,
"values": self.data,
}


def as_coo(x, shape=None, fill_value=None, idx_dtype=None):
"""
Expand Down
26 changes: 3 additions & 23 deletions sparse/numba_backend/_dok.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,29 +272,6 @@
"""
return len(self.data)

@property
def format(self):
"""
The storage format of this array.
Returns
-------
str
The storage format of this array.
See Also
-------
[`scipy.sparse.dok_matrix.format`][] : The Scipy equivalent property.
Examples
-------
>>> import sparse
>>> s = sparse.random((5, 5), density=0.2, format="dok")
>>> s.format
'dok'
>>> t = sparse.random((5, 5), density=0.2, format="coo")
>>> t.format
'coo'
"""
return "dok"

@property
def nbytes(self):
"""
Expand Down Expand Up @@ -549,6 +526,9 @@

return DOK.from_coo(self.to_coo().reshape(shape))

def __binsparse__(self) -> tuple[dict, list[np.ndarray]]:
raise TypeError("`DOK` doesn't support the `__binsparse__` protocol.")

Check warning on line 530 in sparse/numba_backend/_dok.py

View check run for this annotation

Codecov / codecov/patch

sparse/numba_backend/_dok.py#L530

Added line #L530 was not covered by tests


def to_slice(k):
"""Convert integer indices to one-element slices for consistency"""
Expand Down
Loading
Loading