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