[Pyrex] Subclassing Numeric arrays
David M. Cooke
cookedm at physics.mcmaster.ca
Wed May 11 18:11:42 CEST 2005
khinsen at cea.fr writes:
> On May 9, 2005, at 11:46, George Sakkis wrote:
>
>> array and delegates all calls to it. Unfortunately this was a
>> bottleneck
>> for my real-time requirements, so I coded MyVector in Pyrex from
>> scratch
>> (I need only a small fraction of the whole Numeric functionality).
>> Although it's almost four time faster now, I have to convert
>> explicitly to
>> Numeric arrays whenever a real array is expected. This is inelegant
>> apart
>
> I did the same in the same situation - but it's not that much effort:
>
> cdef class vector:
>
> cdef double xv, yv, zv
>
> property array:
> def __get__(self):
> return Numeric.array([self.xv, self.yv, self.zv])
>
> That's three lines for the conversion, and since it's called rarely in
> my case, performance doesn't matter either.
If you make that a method named __array__, Numeric will call it
automatically when it wants an array:
cdef class vector:
cdef double xv, y
def __array__(self):
return Numeric.array([self.xv, self.yv, self.zv])
If you use it as above (creating a list, looking up the array function
the Numeric module, etc.), it'd probably be faster to not provide it,
and let Numeric use the sequence protocol instead (this is a gut
feeling, and should be measured, of course). Using Numeric's C API
(PyArray_FromDims) to build the array inside of the __array__ method
would be the fastest.
Starting with 24.0, Numeric supports the array interface protocol
documented at http://numeric.scipy.org/array_interface.html . This is
the fastest way for larger arrays.
> BTW, I can confirm that Numeric arrays cannot be subclassed. The code
> was written for Python 1.4. Numarray provides subclassable arrays, but
> it has performance problems of its own for small arrays.
>
> BTW, my Pyrex class for vectors is part of the ScientificPython
> distribution:
> http://dirac.cnrs-orleans.fr/ScientificPython/
I've also got a Pyrex vector class at
http://arbutus.mcmaster.ca/dmc/software/vector3.html
It does 2- and 3-dimensional vectors, and it's fast.
--
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca
More information about the Pyrex
mailing list