Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subclassing numpy scalar types

I'm trying to subclass numpy.complex64 in order to make use of the way numpy stores the data, (contiguous, alternating real and imaginary part) but use my own __add__, __sub__, ... routines.

My problem is that when I make a numpy.ndarray, setting dtype=mysubclass, I get a numpy.ndarray with dtype='numpy.complex64' in stead, which results in numpy not using my own functions for additions, subtractions and so on.

Example:

import numpy as np
class mysubclass(np.complex64):
    pass

a = mysubclass(1+1j)
A = np.empty(2, dtype=mysubclass)

print type(a)
print repr(A)

Output:

<class '__main__.mysubclass'>
array([ -2.07782988e-20 +4.58546896e-41j,  -2.07782988e-20 +4.58546896e-41j], dtype=complex64)'

Does anyone know how to do this?

Thanks in advance - Soren

like image 605
Soren Avatar asked Dec 05 '12 18:12

Soren


1 Answers

The NumPy type system is only designed to be extended from C, via the PyArray_RegisterDataType function. It may be possible to access this functionality from Python using ctypes but I wouldn't recommend it; better to write an extension in C or Cython, or subclass ndarray as @seberg describes.

There's a simple example dtype in the NumPy source tree: newdtype_example/floatint.c. If you're into Pyrex, reference.pyx in the pytables source may be worth a look.

like image 162
ecatmur Avatar answered Oct 24 '22 01:10

ecatmur