Merged pull request #12 from bhy/T423.
[cython.git] / Cython / Includes / numpy.pxd
1 # NumPy static imports for Cython
2 #
3 # If any of the PyArray_* functions are called, import_array must be
4 # called first.
5 #
6 # This also defines backwards-compatability buffer acquisition
7 # code for use in Python 2.x (or Python <= 2.5 when NumPy starts
8 # implementing PEP-3118 directly).
9 #
10 # Because of laziness, the format string of the buffer is statically
11 # allocated. Increase the size if this is not enough, or submit a
12 # patch to do this properly.
13 #
14 # Author: Dag Sverre Seljebotn
15 #
16
17 DEF _buffer_format_string_len = 255
18
19 cimport cpython.buffer as pybuf
20 from cpython.ref cimport Py_INCREF, Py_XDECREF
21 from cpython.object cimport PyObject
22 cimport libc.stdlib as stdlib
23 cimport libc.stdio as stdio
24
25 cdef extern from "Python.h":
26     ctypedef int Py_intptr_t
27
28 cdef extern from "numpy/arrayobject.h":
29     ctypedef Py_intptr_t npy_intp
30     ctypedef size_t npy_uintp
31
32     cdef enum NPY_TYPES:
33         NPY_BOOL
34         NPY_BYTE
35         NPY_UBYTE
36         NPY_SHORT
37         NPY_USHORT
38         NPY_INT
39         NPY_UINT
40         NPY_LONG
41         NPY_ULONG
42         NPY_LONGLONG
43         NPY_ULONGLONG
44         NPY_FLOAT
45         NPY_DOUBLE
46         NPY_LONGDOUBLE
47         NPY_CFLOAT
48         NPY_CDOUBLE
49         NPY_CLONGDOUBLE
50         NPY_OBJECT
51         NPY_STRING
52         NPY_UNICODE
53         NPY_VOID
54         NPY_NTYPES
55         NPY_NOTYPE
56
57         NPY_INT8
58         NPY_INT16
59         NPY_INT32
60         NPY_INT64
61         NPY_INT128
62         NPY_INT256
63         NPY_UINT8
64         NPY_UINT16
65         NPY_UINT32
66         NPY_UINT64
67         NPY_UINT128
68         NPY_UINT256
69         NPY_FLOAT16
70         NPY_FLOAT32
71         NPY_FLOAT64
72         NPY_FLOAT80
73         NPY_FLOAT96
74         NPY_FLOAT128
75         NPY_FLOAT256
76         NPY_COMPLEX32
77         NPY_COMPLEX64
78         NPY_COMPLEX128
79         NPY_COMPLEX160
80         NPY_COMPLEX192
81         NPY_COMPLEX256
82         NPY_COMPLEX512
83
84     enum NPY_ORDER:
85         NPY_ANYORDER
86         NPY_CORDER
87         NPY_FORTRANORDER
88
89     enum NPY_CLIPMODE:
90         NPY_CLIP
91         NPY_WRAP
92         NPY_RAISE
93
94     enum NPY_SCALARKIND:
95         NPY_NOSCALAR,
96         NPY_BOOL_SCALAR,
97         NPY_INTPOS_SCALAR,
98         NPY_INTNEG_SCALAR,
99         NPY_FLOAT_SCALAR,
100         NPY_COMPLEX_SCALAR,
101         NPY_OBJECT_SCALAR
102
103
104     enum NPY_SORTKIND:
105         NPY_QUICKSORT
106         NPY_HEAPSORT
107         NPY_MERGESORT
108
109     cdef enum requirements:
110         NPY_C_CONTIGUOUS
111         NPY_F_CONTIGUOUS
112         NPY_CONTIGUOUS
113         NPY_FORTRAN
114         NPY_OWNDATA
115         NPY_FORCECAST
116         NPY_ENSURECOPY
117         NPY_ENSUREARRAY
118         NPY_ELEMENTSTRIDES
119         NPY_ALIGNED
120         NPY_NOTSWAPPED
121         NPY_WRITEABLE
122         NPY_UPDATEIFCOPY
123         NPY_ARR_HAS_DESCR
124
125         NPY_BEHAVED
126         NPY_BEHAVED_NS
127         NPY_CARRAY
128         NPY_CARRAY_RO
129         NPY_FARRAY
130         NPY_FARRAY_RO
131         NPY_DEFAULT
132
133         NPY_IN_ARRAY
134         NPY_OUT_ARRAY
135         NPY_INOUT_ARRAY
136         NPY_IN_FARRAY
137         NPY_OUT_FARRAY
138         NPY_INOUT_FARRAY
139
140         NPY_UPDATE_ALL
141
142     cdef enum:
143         NPY_MAXDIMS
144
145     npy_intp NPY_MAX_ELSIZE
146
147     ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *,  void *)
148
149     ctypedef class numpy.dtype [object PyArray_Descr]:
150         # Use PyDataType_* macros when possible, however there are no macros
151         # for accessing some of the fields, so some are defined. Please
152         # ask on cython-dev if you need more.
153         cdef int type_num
154         cdef int itemsize "elsize"
155         cdef char byteorder
156         cdef object fields
157         cdef tuple names
158
159     ctypedef extern class numpy.flatiter [object PyArrayIterObject]:
160         # Use through macros
161         pass
162
163     ctypedef extern class numpy.broadcast [object PyArrayMultiIterObject]:
164         # Use through macros
165         pass
166
167     ctypedef struct PyArrayObject:
168         # For use in situations where ndarray can't replace PyArrayObject*,
169         # like PyArrayObject**.
170         pass
171
172     ctypedef class numpy.ndarray [object PyArrayObject]:
173         cdef __cythonbufferdefaults__ = {"mode": "strided"}
174
175         cdef:
176             # Only taking a few of the most commonly used and stable fields.
177             # One should use PyArray_* macros instead to access the C fields.
178             char *data
179             int ndim "nd"
180             npy_intp *shape "dimensions"
181             npy_intp *strides
182             dtype descr
183             PyObject* base
184
185         # Note: This syntax (function definition in pxd files) is an
186         # experimental exception made for __getbuffer__ and __releasebuffer__
187         # -- the details of this may change.
188         def __getbuffer__(ndarray self, Py_buffer* info, int flags):
189             # This implementation of getbuffer is geared towards Cython
190             # requirements, and does not yet fullfill the PEP.
191             # In particular strided access is always provided regardless
192             # of flags
193
194             if info == NULL: return
195
196             cdef int copy_shape, i, ndim
197             cdef int endian_detector = 1
198             cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
199
200             ndim = PyArray_NDIM(self)
201
202             if sizeof(npy_intp) != sizeof(Py_ssize_t):
203                 copy_shape = 1
204             else:
205                 copy_shape = 0
206
207             if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
208                 and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)):
209                 raise ValueError(u"ndarray is not C contiguous")
210
211             if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
212                 and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)):
213                 raise ValueError(u"ndarray is not Fortran contiguous")
214
215             info.buf = PyArray_DATA(self)
216             info.ndim = ndim
217             if copy_shape:
218                 # Allocate new buffer for strides and shape info. This is allocated
219                 # as one block, strides first.
220                 info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * ndim * 2)
221                 info.shape = info.strides + ndim
222                 for i in range(ndim):
223                     info.strides[i] = PyArray_STRIDES(self)[i]
224                     info.shape[i] = PyArray_DIMS(self)[i]
225             else:
226                 info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
227                 info.shape = <Py_ssize_t*>PyArray_DIMS(self)
228             info.suboffsets = NULL
229             info.itemsize = PyArray_ITEMSIZE(self)
230             info.readonly = not PyArray_ISWRITEABLE(self)
231
232             cdef int t
233             cdef char* f = NULL
234             cdef dtype descr = self.descr
235             cdef list stack
236             cdef int offset
237
238             cdef bint hasfields = PyDataType_HASFIELDS(descr)
239
240             if not hasfields and not copy_shape:
241                 # do not call releasebuffer
242                 info.obj = None
243             else:
244                 # need to call releasebuffer
245                 info.obj = self
246
247             if not hasfields:
248                 t = descr.type_num
249                 if ((descr.byteorder == '>' and little_endian) or
250                     (descr.byteorder == '<' and not little_endian)):
251                     raise ValueError(u"Non-native byte order not supported")
252                 if   t == NPY_BYTE:        f = "b"
253                 elif t == NPY_UBYTE:       f = "B"
254                 elif t == NPY_SHORT:       f = "h"
255                 elif t == NPY_USHORT:      f = "H"
256                 elif t == NPY_INT:         f = "i"
257                 elif t == NPY_UINT:        f = "I"
258                 elif t == NPY_LONG:        f = "l"
259                 elif t == NPY_ULONG:       f = "L"
260                 elif t == NPY_LONGLONG:    f = "q"
261                 elif t == NPY_ULONGLONG:   f = "Q"
262                 elif t == NPY_FLOAT:       f = "f"
263                 elif t == NPY_DOUBLE:      f = "d"
264                 elif t == NPY_LONGDOUBLE:  f = "g"
265                 elif t == NPY_CFLOAT:      f = "Zf"
266                 elif t == NPY_CDOUBLE:     f = "Zd"
267                 elif t == NPY_CLONGDOUBLE: f = "Zg"
268                 elif t == NPY_OBJECT:      f = "O"
269                 else:
270                     raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
271                 info.format = f
272                 return
273             else:
274                 info.format = <char*>stdlib.malloc(_buffer_format_string_len)
275                 info.format[0] = '^' # Native data types, manual alignment
276                 offset = 0
277                 f = _util_dtypestring(descr, info.format + 1,
278                                       info.format + _buffer_format_string_len,
279                                       &offset)
280                 f[0] = 0 # Terminate format string
281
282         def __releasebuffer__(ndarray self, Py_buffer* info):
283             if PyArray_HASFIELDS(self):
284                 stdlib.free(info.format)
285             if sizeof(npy_intp) != sizeof(Py_ssize_t):
286                 stdlib.free(info.strides)
287                 # info.shape was stored after info.strides in the same block
288
289
290     ctypedef signed char      npy_bool
291
292     ctypedef signed char      npy_byte
293     ctypedef signed short     npy_short
294     ctypedef signed int       npy_int
295     ctypedef signed long      npy_long
296     ctypedef signed long long npy_longlong
297
298     ctypedef unsigned char      npy_ubyte
299     ctypedef unsigned short     npy_ushort
300     ctypedef unsigned int       npy_uint
301     ctypedef unsigned long      npy_ulong
302     ctypedef unsigned long long npy_ulonglong
303
304     ctypedef float        npy_float
305     ctypedef double       npy_double
306     ctypedef long double  npy_longdouble
307
308     ctypedef signed char        npy_int8
309     ctypedef signed short       npy_int16
310     ctypedef signed int         npy_int32
311     ctypedef signed long long   npy_int64
312     ctypedef signed long long   npy_int96
313     ctypedef signed long long   npy_int128
314
315     ctypedef unsigned char      npy_uint8
316     ctypedef unsigned short     npy_uint16
317     ctypedef unsigned int       npy_uint32
318     ctypedef unsigned long long npy_uint64
319     ctypedef unsigned long long npy_uint96
320     ctypedef unsigned long long npy_uint128
321
322     ctypedef float        npy_float32
323     ctypedef double       npy_float64
324     ctypedef long double  npy_float80
325     ctypedef long double  npy_float96
326     ctypedef long double  npy_float128
327
328     ctypedef struct npy_cfloat:
329         double real
330         double imag
331
332     ctypedef struct npy_cdouble:
333         double real
334         double imag
335
336     ctypedef struct npy_clongdouble:
337         double real
338         double imag
339
340     ctypedef struct npy_complex64:
341         double real
342         double imag
343
344     ctypedef struct npy_complex128:
345         double real
346         double imag
347
348     ctypedef struct npy_complex160:
349         double real
350         double imag
351
352     ctypedef struct npy_complex192:
353         double real
354         double imag
355
356     ctypedef struct npy_complex256:
357         double real
358         double imag
359
360     ctypedef struct PyArray_Dims:
361         npy_intp *ptr
362         int len
363
364     void import_array()
365
366     #
367     # Macros from ndarrayobject.h
368     #
369     bint PyArray_CHKFLAGS(ndarray m, int flags)
370     bint PyArray_ISCONTIGUOUS(ndarray m)
371     bint PyArray_ISWRITEABLE(ndarray m)
372     bint PyArray_ISALIGNED(ndarray m)
373
374     int PyArray_NDIM(ndarray)
375     bint PyArray_ISONESEGMENT(ndarray)
376     bint PyArray_ISFORTRAN(ndarray)
377     int PyArray_FORTRANIF(ndarray)
378
379     void* PyArray_DATA(ndarray)
380     char* PyArray_BYTES(ndarray)
381     npy_intp* PyArray_DIMS(ndarray)
382     npy_intp* PyArray_STRIDES(ndarray)
383     npy_intp PyArray_DIM(ndarray, size_t)
384     npy_intp PyArray_STRIDE(ndarray, size_t)
385
386     # object PyArray_BASE(ndarray) wrong refcount semantics
387     # dtype PyArray_DESCR(ndarray) wrong refcount semantics
388     int PyArray_FLAGS(ndarray)
389     npy_intp PyArray_ITEMSIZE(ndarray)
390     int PyArray_TYPE(ndarray arr)
391
392     object PyArray_GETITEM(ndarray arr, void *itemptr)
393     int PyArray_SETITEM(ndarray arr, void *itemptr, object obj)
394
395     bint PyTypeNum_ISBOOL(int)
396     bint PyTypeNum_ISUNSIGNED(int)
397     bint PyTypeNum_ISSIGNED(int)
398     bint PyTypeNum_ISINTEGER(int)
399     bint PyTypeNum_ISFLOAT(int)
400     bint PyTypeNum_ISNUMBER(int)
401     bint PyTypeNum_ISSTRING(int)
402     bint PyTypeNum_ISCOMPLEX(int)
403     bint PyTypeNum_ISPYTHON(int)
404     bint PyTypeNum_ISFLEXIBLE(int)
405     bint PyTypeNum_ISUSERDEF(int)
406     bint PyTypeNum_ISEXTENDED(int)
407     bint PyTypeNum_ISOBJECT(int)
408
409     bint PyDataType_ISBOOL(dtype)
410     bint PyDataType_ISUNSIGNED(dtype)
411     bint PyDataType_ISSIGNED(dtype)
412     bint PyDataType_ISINTEGER(dtype)
413     bint PyDataType_ISFLOAT(dtype)
414     bint PyDataType_ISNUMBER(dtype)
415     bint PyDataType_ISSTRING(dtype)
416     bint PyDataType_ISCOMPLEX(dtype)
417     bint PyDataType_ISPYTHON(dtype)
418     bint PyDataType_ISFLEXIBLE(dtype)
419     bint PyDataType_ISUSERDEF(dtype)
420     bint PyDataType_ISEXTENDED(dtype)
421     bint PyDataType_ISOBJECT(dtype)
422     bint PyDataType_HASFIELDS(dtype)
423
424     bint PyArray_ISBOOL(ndarray)
425     bint PyArray_ISUNSIGNED(ndarray)
426     bint PyArray_ISSIGNED(ndarray)
427     bint PyArray_ISINTEGER(ndarray)
428     bint PyArray_ISFLOAT(ndarray)
429     bint PyArray_ISNUMBER(ndarray)
430     bint PyArray_ISSTRING(ndarray)
431     bint PyArray_ISCOMPLEX(ndarray)
432     bint PyArray_ISPYTHON(ndarray)
433     bint PyArray_ISFLEXIBLE(ndarray)
434     bint PyArray_ISUSERDEF(ndarray)
435     bint PyArray_ISEXTENDED(ndarray)
436     bint PyArray_ISOBJECT(ndarray)
437     bint PyArray_HASFIELDS(ndarray)
438
439     bint PyArray_ISVARIABLE(ndarray)
440
441     bint PyArray_SAFEALIGNEDCOPY(ndarray)
442     bint PyArray_ISNBO(ndarray)
443     bint PyArray_IsNativeByteOrder(ndarray)
444     bint PyArray_ISNOTSWAPPED(ndarray)
445     bint PyArray_ISBYTESWAPPED(ndarray)
446
447     bint PyArray_FLAGSWAP(ndarray, int)
448
449     bint PyArray_ISCARRAY(ndarray)
450     bint PyArray_ISCARRAY_RO(ndarray)
451     bint PyArray_ISFARRAY(ndarray)
452     bint PyArray_ISFARRAY_RO(ndarray)
453     bint PyArray_ISBEHAVED(ndarray)
454     bint PyArray_ISBEHAVED_RO(ndarray)
455
456
457     bint PyDataType_ISNOTSWAPPED(dtype)
458     bint PyDataType_ISBYTESWAPPED(dtype)
459
460     bint PyArray_DescrCheck(object)
461
462     bint PyArray_Check(object)
463     bint PyArray_CheckExact(object)
464
465     # Cannot be supported due to out arg:
466     # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
467     # bint PyArray_HasArrayInterface(op, out)
468
469
470     bint PyArray_IsZeroDim(object)
471     # Cannot be supported due to ## ## in macro:
472     # bint PyArray_IsScalar(object, verbatim work)
473     bint PyArray_CheckScalar(object)
474     bint PyArray_IsPythonNumber(object)
475     bint PyArray_IsPythonScalar(object)
476     bint PyArray_IsAnyScalar(object)
477     bint PyArray_CheckAnyScalar(object)
478     ndarray PyArray_GETCONTIGUOUS(ndarray)
479     bint PyArray_SAMESHAPE(ndarray, ndarray)
480     npy_intp PyArray_SIZE(ndarray)
481     npy_intp PyArray_NBYTES(ndarray)
482
483     object PyArray_FROM_O(object)
484     object PyArray_FROM_OF(object m, int flags)
485     bint PyArray_FROM_OT(object m, int type)
486     bint PyArray_FROM_OTF(object m, int type, int flags)
487     object PyArray_FROMANY(object m, int type, int min, int max, int flags)
488     object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
489     object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
490     void PyArray_FILLWBYTE(object, int val)
491     npy_intp PyArray_REFCOUNT(object)
492     object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
493     unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
494     bint PyArray_EquivByteorders(int b1, int b2)
495     object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
496     object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
497     #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
498     object PyArray_ToScalar(void* data, ndarray arr)
499
500     void* PyArray_GETPTR1(ndarray m, npy_intp i)
501     void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j)
502     void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k)
503     void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l)
504
505     void PyArray_XDECREF_ERR(ndarray)
506     # Cannot be supported due to out arg
507     # void PyArray_DESCR_REPLACE(descr)
508
509
510     object PyArray_Copy(ndarray)
511     object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
512     object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
513     object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
514
515     object PyArray_Cast(ndarray mp, int type_num)
516     object PyArray_Take(ndarray ap, object items, int axis)
517     object PyArray_Put(ndarray ap, object items, object values)
518
519     void PyArray_ITER_RESET(flatiter it) nogil
520     void PyArray_ITER_NEXT(flatiter it) nogil
521     void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
522     void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
523     void* PyArray_ITER_DATA(flatiter it) nogil
524     bint PyArray_ITER_NOTDONE(flatiter it) nogil
525
526     void PyArray_MultiIter_RESET(broadcast multi) nogil
527     void PyArray_MultiIter_NEXT(broadcast multi) nogil
528     void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
529     void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
530     void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
531     void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
532     bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
533
534     # Functions from __multiarray_api.h
535
536     # Functions taking dtype and returning object/ndarray are disabled
537     # for now as they steal dtype references. I'm conservative and disable
538     # more than is probably needed until it can be checked further.
539     int PyArray_SetNumericOps        (object)
540     object PyArray_GetNumericOps ()
541     int PyArray_INCREF (ndarray)
542     int PyArray_XDECREF (ndarray)
543     void PyArray_SetStringFunction (object, int)
544     dtype PyArray_DescrFromType (int)
545     object PyArray_TypeObjectFromType (int)
546     char * PyArray_Zero (ndarray)
547     char * PyArray_One (ndarray)
548     #object PyArray_CastToType (ndarray, dtype, int)
549     int PyArray_CastTo (ndarray, ndarray)
550     int PyArray_CastAnyTo (ndarray, ndarray)
551     int PyArray_CanCastSafely (int, int)
552     npy_bool PyArray_CanCastTo (dtype, dtype)
553     int PyArray_ObjectType (object, int)
554     dtype PyArray_DescrFromObject (object, dtype)
555     #ndarray* PyArray_ConvertToCommonType (object, int *)
556     dtype PyArray_DescrFromScalar (object)
557     dtype PyArray_DescrFromTypeObject (object)
558     npy_intp PyArray_Size (object)
559     #object PyArray_Scalar (void *, dtype, object)
560     #object PyArray_FromScalar (object, dtype)
561     void PyArray_ScalarAsCtype (object, void *)
562     #int PyArray_CastScalarToCtype (object, void *, dtype)
563     #int PyArray_CastScalarDirect (object, dtype, void *, int)
564     object PyArray_ScalarFromObject (object)
565     #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
566     object PyArray_FromDims (int, int *, int)
567     #object PyArray_FromDimsAndDataAndDescr (int, int *, dtype, char *)
568     #object PyArray_FromAny (object, dtype, int, int, int, object)
569     object PyArray_EnsureArray (object)
570     object PyArray_EnsureAnyArray (object)
571     #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
572     #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
573     #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
574     #object PyArray_FromIter (object, dtype, npy_intp)
575     object PyArray_Return (ndarray)
576     #object PyArray_GetField (ndarray, dtype, int)
577     #int PyArray_SetField (ndarray, dtype, int, object)
578     object PyArray_Byteswap (ndarray, npy_bool)
579     object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
580     int PyArray_MoveInto (ndarray, ndarray)
581     int PyArray_CopyInto (ndarray, ndarray)
582     int PyArray_CopyAnyInto (ndarray, ndarray)
583     int PyArray_CopyObject (ndarray, object)
584     object PyArray_NewCopy (ndarray, NPY_ORDER)
585     object PyArray_ToList (ndarray)
586     object PyArray_ToString (ndarray, NPY_ORDER)
587     int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *)
588     int PyArray_Dump (object, object, int)
589     object PyArray_Dumps (object, int)
590     int PyArray_ValidType (int)
591     void PyArray_UpdateFlags (ndarray, int)
592     object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
593     #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
594     #dtype PyArray_DescrNew (dtype)
595     dtype PyArray_DescrNewFromType (int)
596     double PyArray_GetPriority (object, double)
597     object PyArray_IterNew (object)
598     object PyArray_MultiIterNew (int, ...)
599
600     int PyArray_PyIntAsInt (object)
601     npy_intp PyArray_PyIntAsIntp (object)
602     int PyArray_Broadcast (broadcast)
603     void PyArray_FillObjectArray (ndarray, object)
604     int PyArray_FillWithScalar (ndarray, object)
605     npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
606     dtype PyArray_DescrNewByteorder (dtype, char)
607     object PyArray_IterAllButAxis (object, int *)
608     #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
609     #object PyArray_FromArray (ndarray, dtype, int)
610     object PyArray_FromInterface (object)
611     object PyArray_FromStructInterface (object)
612     #object PyArray_FromArrayAttr (object, dtype, object)
613     #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
614     int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
615     object PyArray_NewFlagsObject (object)
616     npy_bool PyArray_CanCastScalar (type, type)
617     #int PyArray_CompareUCS4 (npy_ucs4 *, npy_ucs4 *, register size_t)
618     int PyArray_RemoveSmallest (broadcast)
619     int PyArray_ElementStrides (object)
620     void PyArray_Item_INCREF (char *, dtype)
621     void PyArray_Item_XDECREF (char *, dtype)
622     object PyArray_FieldNames (object)
623     object PyArray_Transpose (ndarray, PyArray_Dims *)
624     object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
625     object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
626     object PyArray_PutMask (ndarray, object, object)
627     object PyArray_Repeat (ndarray, object, int)
628     object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
629     int PyArray_Sort (ndarray, int, NPY_SORTKIND)
630     object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
631     object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE)
632     object PyArray_ArgMax (ndarray, int, ndarray)
633     object PyArray_ArgMin (ndarray, int, ndarray)
634     object PyArray_Reshape (ndarray, object)
635     object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
636     object PyArray_Squeeze (ndarray)
637     #object PyArray_View (ndarray, dtype, type)
638     object PyArray_SwapAxes (ndarray, int, int)
639     object PyArray_Max (ndarray, int, ndarray)
640     object PyArray_Min (ndarray, int, ndarray)
641     object PyArray_Ptp (ndarray, int, ndarray)
642     object PyArray_Mean (ndarray, int, int, ndarray)
643     object PyArray_Trace (ndarray, int, int, int, int, ndarray)
644     object PyArray_Diagonal (ndarray, int, int, int)
645     object PyArray_Clip (ndarray, object, object, ndarray)
646     object PyArray_Conjugate (ndarray, ndarray)
647     object PyArray_Nonzero (ndarray)
648     object PyArray_Std (ndarray, int, int, ndarray, int)
649     object PyArray_Sum (ndarray, int, int, ndarray)
650     object PyArray_CumSum (ndarray, int, int, ndarray)
651     object PyArray_Prod (ndarray, int, int, ndarray)
652     object PyArray_CumProd (ndarray, int, int, ndarray)
653     object PyArray_All (ndarray, int, ndarray)
654     object PyArray_Any (ndarray, int, ndarray)
655     object PyArray_Compress (ndarray, object, int, ndarray)
656     object PyArray_Flatten (ndarray, NPY_ORDER)
657     object PyArray_Ravel (ndarray, NPY_ORDER)
658     npy_intp PyArray_MultiplyList (npy_intp *, int)
659     int PyArray_MultiplyIntList (int *, int)
660     void * PyArray_GetPtr (ndarray, npy_intp*)
661     int PyArray_CompareLists (npy_intp *, npy_intp *, int)
662     #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
663     #int PyArray_As1D (object*, char **, int *, int)
664     #int PyArray_As2D (object*, char ***, int *, int *, int)
665     int PyArray_Free (object, void *)
666     #int PyArray_Converter (object, object*)
667     int PyArray_IntpFromSequence (object, npy_intp *, int)
668     object PyArray_Concatenate (object, int)
669     object PyArray_InnerProduct (object, object)
670     object PyArray_MatrixProduct (object, object)
671     object PyArray_CopyAndTranspose (object)
672     object PyArray_Correlate (object, object, int)
673     int PyArray_TypestrConvert (int, int)
674     #int PyArray_DescrConverter (object, dtype*)
675     #int PyArray_DescrConverter2 (object, dtype*)
676     int PyArray_IntpConverter (object, PyArray_Dims *)
677     #int PyArray_BufferConverter (object, chunk)
678     int PyArray_AxisConverter (object, int *)
679     int PyArray_BoolConverter (object, npy_bool *)
680     int PyArray_ByteorderConverter (object, char *)
681     int PyArray_OrderConverter (object, NPY_ORDER *)
682     unsigned char PyArray_EquivTypes (dtype, dtype)
683     #object PyArray_Zeros (int, npy_intp *, dtype, int)
684     #object PyArray_Empty (int, npy_intp *, dtype, int)
685     object PyArray_Where (object, object, object)
686     object PyArray_Arange (double, double, double, int)
687     #object PyArray_ArangeObj (object, object, object, dtype)
688     int PyArray_SortkindConverter (object, NPY_SORTKIND *)
689     object PyArray_LexSort (object, int)
690     object PyArray_Round (ndarray, int, ndarray)
691     unsigned char PyArray_EquivTypenums (int, int)
692     int PyArray_RegisterDataType (dtype)
693     int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *)
694     int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND)
695     #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
696     object PyArray_IntTupleFromIntp (int, npy_intp *)
697     int PyArray_TypeNumFromName (char *)
698     int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *)
699     #int PyArray_OutputConverter (object, ndarray*)
700     object PyArray_BroadcastToShape (object, npy_intp *, int)
701     void _PyArray_SigintHandler (int)
702     void* _PyArray_GetSigintBuf ()
703     #int PyArray_DescrAlignConverter (object, dtype*)
704     #int PyArray_DescrAlignConverter2 (object, dtype*)
705     int PyArray_SearchsideConverter (object, void *)
706     object PyArray_CheckAxis (ndarray, int *, int)
707     npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
708     int PyArray_CompareString (char *, char *, size_t)
709
710
711 # Typedefs that matches the runtime dtype objects in
712 # the numpy module.
713
714 # The ones that are commented out needs an IFDEF function
715 # in Cython to enable them only on the right systems.
716
717 ctypedef npy_int8       int8_t
718 ctypedef npy_int16      int16_t
719 ctypedef npy_int32      int32_t
720 ctypedef npy_int64      int64_t
721 #ctypedef npy_int96      int96_t
722 #ctypedef npy_int128     int128_t
723
724 ctypedef npy_uint8      uint8_t
725 ctypedef npy_uint16     uint16_t
726 ctypedef npy_uint32     uint32_t
727 ctypedef npy_uint64     uint64_t
728 #ctypedef npy_uint96     uint96_t
729 #ctypedef npy_uint128    uint128_t
730
731 ctypedef npy_float32    float32_t
732 ctypedef npy_float64    float64_t
733 #ctypedef npy_float80    float80_t
734 #ctypedef npy_float128   float128_t
735
736 ctypedef float complex  complex64_t
737 ctypedef double complex complex128_t
738
739 # The int types are mapped a bit surprising --
740 # numpy.int corresponds to 'l' and numpy.long to 'q'
741 ctypedef npy_long       int_t
742 ctypedef npy_longlong   long_t
743 ctypedef npy_longlong   longlong_t
744
745 ctypedef npy_ulong      uint_t
746 ctypedef npy_ulonglong  ulong_t
747 ctypedef npy_ulonglong  ulonglong_t
748
749 ctypedef npy_intp       intp_t
750 ctypedef npy_uintp      uintp_t
751
752 ctypedef npy_double     float_t
753 ctypedef npy_double     double_t
754 ctypedef npy_longdouble longdouble_t
755
756 ctypedef npy_cfloat      cfloat_t
757 ctypedef npy_cdouble     cdouble_t
758 ctypedef npy_clongdouble clongdouble_t
759
760 ctypedef npy_cdouble     complex_t
761
762 cdef inline object PyArray_MultiIterNew1(a):
763     return PyArray_MultiIterNew(1, <void*>a)
764
765 cdef inline object PyArray_MultiIterNew2(a, b):
766     return PyArray_MultiIterNew(2, <void*>a, <void*>b)
767
768 cdef inline object PyArray_MultiIterNew3(a, b, c):
769     return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
770
771 cdef inline object PyArray_MultiIterNew4(a, b, c, d):
772     return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
773
774 cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
775     return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
776
777 cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL:
778     # Recursive utility function used in __getbuffer__ to get format
779     # string. The new location in the format string is returned.
780
781     cdef dtype child
782     cdef int delta_offset
783     cdef tuple i
784     cdef int endian_detector = 1
785     cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
786     cdef tuple fields
787
788     for childname in descr.names:
789         fields = descr.fields[childname]
790         child, new_offset = fields
791
792         if (end - f) - (new_offset - offset[0]) < 15:
793             raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
794
795         if ((child.byteorder == '>' and little_endian) or
796             (child.byteorder == '<' and not little_endian)):
797             raise ValueError(u"Non-native byte order not supported")
798             # One could encode it in the format string and have Cython
799             # complain instead, BUT: < and > in format strings also imply
800             # standardized sizes for datatypes, and we rely on native in
801             # order to avoid reencoding data types based on their size.
802             #
803             # A proper PEP 3118 exporter for other clients than Cython
804             # must deal properly with this!
805
806         # Output padding bytes
807         while offset[0] < new_offset:
808             f[0] = 120 # "x"; pad byte
809             f += 1
810             offset[0] += 1
811
812         offset[0] += child.itemsize
813
814         if not PyDataType_HASFIELDS(child):
815             t = child.type_num
816             if end - f < 5:
817                 raise RuntimeError(u"Format string allocated too short.")
818
819             # Until ticket #99 is fixed, use integers to avoid warnings
820             if   t == NPY_BYTE:        f[0] =  98 #"b"
821             elif t == NPY_UBYTE:       f[0] =  66 #"B"
822             elif t == NPY_SHORT:       f[0] = 104 #"h"
823             elif t == NPY_USHORT:      f[0] =  72 #"H"
824             elif t == NPY_INT:         f[0] = 105 #"i"
825             elif t == NPY_UINT:        f[0] =  73 #"I"
826             elif t == NPY_LONG:        f[0] = 108 #"l"
827             elif t == NPY_ULONG:       f[0] = 76  #"L"
828             elif t == NPY_LONGLONG:    f[0] = 113 #"q"
829             elif t == NPY_ULONGLONG:   f[0] = 81  #"Q"
830             elif t == NPY_FLOAT:       f[0] = 102 #"f"
831             elif t == NPY_DOUBLE:      f[0] = 100 #"d"
832             elif t == NPY_LONGDOUBLE:  f[0] = 103 #"g"
833             elif t == NPY_CFLOAT:      f[0] = 90; f[1] = 102; f += 1 # Zf
834             elif t == NPY_CDOUBLE:     f[0] = 90; f[1] = 100; f += 1 # Zd
835             elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
836             elif t == NPY_OBJECT:      f[0] = 79 #"O"
837             else:
838                 raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
839             f += 1
840         else:
841             # Cython ignores struct boundary information ("T{...}"),
842             # so don't output it
843             f = _util_dtypestring(child, f, end, offset)
844     return f
845
846
847 #
848 # ufunc API
849 #
850
851 cdef extern from "numpy/ufuncobject.h":
852
853     ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
854
855     ctypedef extern class numpy.ufunc [object PyUFuncObject]:
856         cdef:
857             int nin, nout, nargs
858             int identity
859             PyUFuncGenericFunction *functions
860             void **data
861             int ntypes
862             int check_return
863             char *name, *types
864             char *doc
865             void *ptr
866             PyObject *obj
867             PyObject *userloops
868
869     cdef enum:
870         PyUFunc_Zero
871         PyUFunc_One
872         PyUFunc_None
873         UFUNC_ERR_IGNORE
874         UFUNC_ERR_WARN
875         UFUNC_ERR_RAISE
876         UFUNC_ERR_CALL
877         UFUNC_ERR_PRINT
878         UFUNC_ERR_LOG
879         UFUNC_MASK_DIVIDEBYZERO
880         UFUNC_MASK_OVERFLOW
881         UFUNC_MASK_UNDERFLOW
882         UFUNC_MASK_INVALID
883         UFUNC_SHIFT_DIVIDEBYZERO
884         UFUNC_SHIFT_OVERFLOW
885         UFUNC_SHIFT_UNDERFLOW
886         UFUNC_SHIFT_INVALID
887         UFUNC_FPE_DIVIDEBYZERO
888         UFUNC_FPE_OVERFLOW
889         UFUNC_FPE_UNDERFLOW
890         UFUNC_FPE_INVALID
891         UFUNC_ERR_DEFAULT
892         UFUNC_ERR_DEFAULT2
893
894     object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
895           void **, char *, int, int, int, int, char *, char *, int)
896     int PyUFunc_RegisterLoopForType(ufunc, int,
897                                     PyUFuncGenericFunction, int *, void *)
898     int PyUFunc_GenericFunction \
899         (ufunc, PyObject *, PyObject *, PyArrayObject **)
900     void PyUFunc_f_f_As_d_d \
901          (char **, npy_intp *, npy_intp *, void *)
902     void PyUFunc_d_d \
903          (char **, npy_intp *, npy_intp *, void *)
904     void PyUFunc_f_f \
905          (char **, npy_intp *, npy_intp *, void *)
906     void PyUFunc_g_g \
907          (char **, npy_intp *, npy_intp *, void *)
908     void PyUFunc_F_F_As_D_D \
909          (char **, npy_intp *, npy_intp *, void *)
910     void PyUFunc_F_F \
911          (char **, npy_intp *, npy_intp *, void *)
912     void PyUFunc_D_D \
913          (char **, npy_intp *, npy_intp *, void *)
914     void PyUFunc_G_G \
915          (char **, npy_intp *, npy_intp *, void *)
916     void PyUFunc_O_O \
917          (char **, npy_intp *, npy_intp *, void *)
918     void PyUFunc_ff_f_As_dd_d \
919          (char **, npy_intp *, npy_intp *, void *)
920     void PyUFunc_ff_f \
921          (char **, npy_intp *, npy_intp *, void *)
922     void PyUFunc_dd_d \
923          (char **, npy_intp *, npy_intp *, void *)
924     void PyUFunc_gg_g \
925          (char **, npy_intp *, npy_intp *, void *)
926     void PyUFunc_FF_F_As_DD_D \
927          (char **, npy_intp *, npy_intp *, void *)
928     void PyUFunc_DD_D \
929          (char **, npy_intp *, npy_intp *, void *)
930     void PyUFunc_FF_F \
931          (char **, npy_intp *, npy_intp *, void *)
932     void PyUFunc_GG_G \
933          (char **, npy_intp *, npy_intp *, void *)
934     void PyUFunc_OO_O \
935          (char **, npy_intp *, npy_intp *, void *)
936     void PyUFunc_O_O_method \
937          (char **, npy_intp *, npy_intp *, void *)
938     void PyUFunc_OO_O_method \
939          (char **, npy_intp *, npy_intp *, void *)
940     void PyUFunc_On_Om \
941          (char **, npy_intp *, npy_intp *, void *)
942     int PyUFunc_GetPyValues \
943         (char *, int *, int *, PyObject **)
944     int PyUFunc_checkfperr \
945            (int, PyObject *, int *)
946     void PyUFunc_clearfperr()
947     int PyUFunc_getfperr()
948     int PyUFunc_handlefperr \
949         (int, PyObject *, int, int *)
950     int PyUFunc_ReplaceLoopBySignature \
951         (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
952     object PyUFunc_FromFuncAndDataAndSignature \
953              (PyUFuncGenericFunction *, void **, char *, int, int, int,
954               int, char *, char *, int, char *)
955
956     void import_ufunc()
957
958
959 cdef inline void set_array_base(ndarray arr, object base):
960      cdef PyObject* baseptr
961      if base is None:
962          baseptr = NULL
963      else:
964          Py_INCREF(base) # important to do this before decref below!
965          baseptr = <PyObject*>base
966      Py_XDECREF(arr.base)
967      arr.base = baseptr
968
969 cdef inline object get_array_base(ndarray arr):
970     if arr.base is NULL:
971         return None
972     else:
973         return <object>arr.base