[SciPy-Dev] Indexing sparse matrices

Jason Grout jason-sage at creativetrax.com
Wed Jun 23 10:22:26 EDT 2010


Hi everyone,

This bug in scipy sparse matrices was recently reported in Sage:

----------------------------------------------------------------------
| Sage Version 4.4.2, Release Date: 2010-05-19                       |
| Type notebook() for the GUI, and license() for information.        |
----------------------------------------------------------------------
sage: from scipy import sparse
sage: a = sparse.lil_matrix((10,10))
sage: a[1,2] = 1
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

/Users/grout/sage-4.4.2-test3/local/lib/python2.6/site-packages/numpy/core/<ipython 
console> in <module>()

/Users/grout/sage/local/lib/python2.6/site-packages/scipy/sparse/lil.pyc 
in __setitem__(self, index, x)
     320                     self._insertat3(row, data, j, xx)
     321         else:
--> 322             raise ValueError('invalid index value: %s' % str((i, 
j)))
     323
     324     def _mul_scalar(self, other):

ValueError: invalid index value: (1, 2)


Since the preparser in Sage makes integers instances of the Sage Integer 
class, and the Sage Integer class is not in the specific list of types 
checked by numpy.isscalar, the case falls through the checks in the 
sparse matrix setitem method to the last error-raising case. The problem 
seems to be that scipy checks for a specific list of types (via 
numpy.isscalar), instead of just using the __index__ magic method which 
was designed for this purpose (by Travis Oliphant for numpy! see 
http://docs.python.org/whatsnew/2.5.html#pep-357-the-index-method).

Note that things work fine in numpy:

sage: import numpy
sage: a=numpy.array([[1,2],[3,4]],dtype=int); a
array([[1, 2],
        [3, 4]])
sage: a[1,1]=5
sage: a
array([[1, 2],
        [3, 5]])


Thanks,

Jason





More information about the SciPy-Dev mailing list