Skip to content

Commit

Permalink
Merge pull request #464 from hameerabbasi/dok-ctor-scipy
Browse files Browse the repository at this point in the history
Add DOK sparse constructor.
  • Loading branch information
hameerabbasi committed Apr 22, 2021
2 parents 0d50c9d + 7e8e044 commit e036c25
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/generated/sparse.DOK.from_scipy_sparse.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
DOK.from\_scipy\_sparse
=======================

.. currentmodule:: sparse

.. automethod:: DOK.from_scipy_sparse
2 changes: 2 additions & 0 deletions docs/generated/sparse.DOK.rst
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ DOK
DOK.from_coo

DOK.from_numpy

DOK.from_scipy_sparse

DOK.to_coo

Expand Down
32 changes: 32 additions & 0 deletions sparse/_dok.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from collections.abc import Iterable

import numpy as np
import scipy.sparse
from numpy.lib.mixins import NDArrayOperatorsMixin

from ._slicing import normalize_index
Expand Down Expand Up @@ -106,6 +107,11 @@ def __init__(self, shape, data=None, dtype=None, fill_value=None):
self._make_shallow_copy_of(ar)
return

if isinstance(shape, scipy.sparse.spmatrix):
ar = DOK.from_scipy_sparse(shape)
self._make_shallow_copy_of(ar)
return

self.dtype = np.dtype(dtype)

if not data:
Expand All @@ -127,6 +133,32 @@ def __init__(self, shape, data=None, dtype=None, fill_value=None):
else:
raise ValueError("data must be a dict.")

@classmethod
def from_scipy_sparse(cls, x):
"""
Create a :obj:`DOK` array from a :obj:`scipy.sparse.spmatrix`.
Parameters
----------
x : scipy.sparse.spmatrix
The matrix to convert.
Returns
-------
DOK
The equivalent :obj:`DOK` array.
Examples
--------
>>> x = scipy.sparse.rand(6, 3, density=0.2)
>>> s = DOK.from_scipy_sparse(x)
>>> np.array_equal(x.todense(), s.todense())
True
"""
from sparse import COO

return COO.from_scipy_sparse(x).asformat(cls)

@classmethod
def from_coo(cls, x):
"""
Expand Down
9 changes: 9 additions & 0 deletions sparse/tests/test_dok.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,15 @@ def test_convert_to_numpy():
assert_eq(x, s)


def test_convert_from_scipy_sparse():
import scipy.sparse

x = scipy.sparse.rand(6, 3, density=0.2)
s = DOK(x)

assert_eq(x, s)


@pytest.mark.parametrize(
"shape, data",
[
Expand Down

0 comments on commit e036c25

Please sign in to comment.