On Wed, Nov 30, 2011 at 3:01 AM, Per Nielsen <evilper@gmail.com> wrote:
Hi all

I am trying to create a subclass of the sparse matrix class in scipy, to add some extra methods I need. 

I have tried to follow the guide on: http://www.scipy.org/Subclasses but without much luck, the view method does not exist for the sparse matrix class. Below is a script I have created


Hi,

It appears that sparse matrices do not inherit from numpy.ndarray:

In [5]: sparse_mat = csr_matrix( np.ones(3) )
In [7]: isinstance( sparse_mat, np.ndarray )
Out[7]: False

So much of the numpy - specific information on that page at scipy.org is not relevant for a sparse matrix subclass. I would assume subclassing csr_matrix would essentially look more like plain python subclassing. However, playing around with this, I quickly found what appears to be a sparse matrix-specific aspect. The sparse matrix format is based on the name of the class - so if you want this to work you have to name the subclass with the same 3 letters as the desired subclass ("csr" in this case). Here is a minimal example that works - note the fail_matrix doesn't work, and causes an attribute error just because of the name:

from scipy.sparse.csr import csr_matrix

class csr_matrix_alt(csr_matrix):
    def __init__(self, *args, **kwargs):
        csr_matrix.__init__(self, *args, **kwargs)
    def square_spmat(self):
        return self ** 2

class fail_matrix(csr_matrix):
    pass

x = np.array( [[1, 0], [1, 3]] )
xsparse = csr_matrix_alt(x)
xsparse_sq = xsparse.square_spmat()

print xsparse.todense()
print xsparse_sq.todense()

xfail = fail_matrix(x)



Here is the output I get, running from ipython:

In [2]: execfile('spsub_example.py')
[[1 0]
 [1 3]]
[[1 0]
 [4 9]]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<snip>
AttributeError: tofai not found