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