[SciPy-dev] Adding to an array with __radd__()

Robert Cimrman cimrman3 at ntc.zcu.cz
Tue Nov 1 07:07:28 EST 2005


Ed Schofield wrote:
> 
> Robert Cimrman wrote:
> 
>>Travis Oliphant wrote:
>>
>>>I think this is a result of the fact that arrays are now new style
>>>numbers and the fact that array(B) created a perfectly nice object array.
>>>
>>>I've committed a change that makes special cases this case so the
>>>reflected operands will work if they are defined for something that
>>>becomes an object array.
>>
>>Is it possible, in principle, to call always the sparse matrix operator
>>method when it enters an operation with a dense array?
>>(a .. dense array, b sparse -- a + b calls b.__radd__, b + a calls
>>b.__add__)
>>
>>The reason I would support this is, that IMHO the higher level object (a
>>sparse matrix) knows well how to handle the lower level object (a dense
>>array) in numeric operations, but not vice-versa -- there is already a
>>number of sparse matrix formats, so the dense array object definitely
>>cannot understand them all.
> 
> 
> Travis's patch has this effect.  Python calls the left operand's __op__
> method, but a dense array on the left now yields control to the right
> operand's __rop__ if it can't interpret the right operand as a normal
> (non-Object) array.  So the tests that were previously commented in
> test_sparse.py now pass for CSC and CSR matrices.

Cool, Travis obviously works faster than I am able to write e-mails... :-)

> There is one remaining problem with DOK matrices: it never gets this far,
> first raising a ValueError while trying to interpret it as a sequence.  I
> committed a patch for more graceful handling of such objects that claim to
> be sequences but don't allow integer indexing.  I then reverted this,
> thinking we should instead fix dok_matrix so PySequence_Check() doesn't
> return true.  But I'm not sure if this is possible.  It seems that since
> Python 2.2 PySequence_Check() returns true for dictionaries, even though
> they don't allow integer indexing.  Isn't this a blatant violation of the
> sequence protocol?  (cf http://docs.python.org/ref/sequence-types.html)
> Is there any way to override PySequence_Check() to return false for a
> subclassed dict like dok_matrix?  If not I suggest we apply my patch after
> all -- and complain to the Python developers ;)

I have just tested with:

PyObject *isSequence( PyObject *input ) {

   if (PySequence_Check( input )) {
     return( PyBool_FromLong( 1 ) );
   } else {
     return( PyBool_FromLong( 0 ) );
   }
}

print isSequence( [] )
print isSequence( (1,) )
print isSequence( {} )
print isSequence( scipy.sparse.dok_matrix( scipy.array( [[1,2,3]] ) ) )

and got (Python 2.4.2):

True
True
False
True

... so the problem is not in PySequence_Check(). The DOK matrix inherits 
not only from dict, but also from spmatrix. Could this cause such a 
behaviour??

r.




More information about the SciPy-Dev mailing list