These macros all access thePyArrayObject structure members. The inputargument, arr, can be anyPyObject* that is directly interpretableas aPyArrayObject* (any instance of thePyArray_Type and itssub-types).
PyArray_NDIM(PyArrayObject *arr)¶The number of dimensions in the array.
PyArray_DIMS(PyArrayObject *arr)¶Returns a pointer to the dimensions/shape of the array. Thenumber of elements matches the number of dimensionsof the array.
PyArray_SHAPE(PyArrayObject *arr)¶New in version 1.7.
A synonym for PyArray_DIMS, named to be consistent with the‘shape’ usage within Python.
PyArray_DATA(PyArrayObject *arr)¶PyArray_BYTES(PyArrayObject *arr)¶These two macros are similar and obtain the pointer to thedata-buffer for the array. The first macro can (and should be)assigned to a particular pointer where the second is for genericprocessing. If you have not guaranteed a contiguous and/or alignedarray then be sure you understand how to access the data in thearray to avoid memory and/or alignment problems.
PyArray_STRIDES(PyArrayObject* arr)¶Returns a pointer to the strides of the array. Thenumber of elements matches the number of dimensionsof the array.
PyArray_DIM(PyArrayObject* arr, int n)¶Return the shape in then^{\textrm{th}} dimension.
PyArray_STRIDE(PyArrayObject* arr, int n)¶Return the stride in then^{\textrm{th}} dimension.
PyArray_BASE(PyArrayObject* arr)¶This returns the base object of the array. In most cases, thismeans the object which owns the memory the array is pointing at.
If you are constructing an array using the C API, and specifyingyour own memory, you should use the functionPyArray_SetBaseObjectto set the base to an object which owns the memory.
If the (deprecated)NPY_ARRAY_UPDATEIFCOPY or theNPY_ARRAY_WRITEBACKIFCOPY flags are set, it has a differentmeaning, namely base is the array into which the current array willbe copied upon copy resolution. This overloading of the base propertyfor two functions is likely to change in a future version of NumPy.
PyArray_DESCR(PyArrayObject* arr)¶Returns a borrowed reference to the dtype property of the array.
PyArray_DTYPE(PyArrayObject* arr)¶New in version 1.7.
A synonym for PyArray_DESCR, named to be consistent with the‘dtype’ usage within Python.
PyArray_ENABLEFLAGS(PyArrayObject* arr, int flags)¶New in version 1.7.
Enables the specified array flags. This function does no validation,and assumes that you know what you’re doing.
PyArray_CLEARFLAGS(PyArrayObject* arr, int flags)¶New in version 1.7.
Clears the specified array flags. This function does no validation,and assumes that you know what you’re doing.
PyArray_FLAGS(PyArrayObject* arr)¶PyArray_ITEMSIZE(PyArrayObject* arr)¶Return the itemsize for the elements of this array.
Note that, in the old API that was deprecated in version 1.7, this functionhad the return typeint.
PyArray_TYPE(PyArrayObject* arr)¶Return the (builtin) typenumber for the elements of this array.
PyArray_GETITEM(PyArrayObject* arr, void* itemptr)¶Get a Python object from the ndarray,arr, at the locationpointed to by itemptr. ReturnNULL on failure.
PyArray_SETITEM(PyArrayObject* arr, void* itemptr,PyObject* obj)¶Convert obj and place it in the ndarray,arr, at the placepointed to by itemptr. Return -1 if an error occurs or 0 onsuccess.
PyArray_SIZE(PyArrayObject* arr)¶Returns the total size (in number of elements) of the array.
PyArray_Size(PyArrayObject* obj)¶Returns 0 ifobj is not a sub-class of ndarray. Otherwise,returns the total number of elements in the array. Safer versionofPyArray_SIZE (obj).
PyArray_NBYTES(PyArrayObject* arr)¶Returns the total number of bytes consumed by the array.
These functions and macros provide easy access to elements of thendarray from C. These work for all arrays. You may need to take carewhen accessing the data in the array, however, if it is not in machinebyte-order, misaligned, or not writeable. In other words, be sure torespect the state of the flags unless you know what you are doing, orhave previously guaranteed an array that is writeable, aligned, and inmachine byte-order usingPyArray_FromAny. If you wish to handle alltypes of arrays, the copyswap function for each type is useful forhandling misbehaved arrays. Some platforms (e.g. Solaris) do not likemisaligned data and will crash if you de-reference a misalignedpointer. Other platforms (e.g. x86 Linux) will just work more slowlywith misaligned data.
PyArray_GetPtr(PyArrayObject* aobj, npy_intp* ind)¶Return a pointer to the data of the ndarray,aobj, at theN-dimensional index given by the c-array,ind, (which must beat leastaobj ->nd in size). You may want to typecast thereturned pointer to the data type of the ndarray.
PyArray_GETPTR1(PyArrayObject* obj, npy_intp i)¶PyArray_GETPTR2(PyArrayObject* obj, npy_intp i, npy_intp j)¶PyArray_GETPTR3(PyArrayObject* obj, npy_intp i, npy_intp j, npy_intp k)¶PyArray_GETPTR4(PyArrayObject* obj, npy_intp i, npy_intp j, npy_intp k, npy_intp l)¶Quick, inline access to the element at the given coordinates inthe ndarray,obj, which must have respectively 1, 2, 3, or 4dimensions (this is not checked). The correspondingi,j,k, andl coordinates can be any integer but will beinterpreted asnpy_intp. You may want to typecast thereturned pointer to the data type of the ndarray.
PyArray_NewFromDescr(PyTypeObject* subtype,PyArray_Descr* descr, int nd, npy_intp* dims, npy_intp* strides, void* data, int flags,PyObject* obj)¶This function steals a reference todescr.
This is the main array creation function. Most new arrays arecreated with this flexible function.
The returned object is an object of Python-typesubtype, whichmust be a subtype ofPyArray_Type. The array hasnddimensions, described bydims. The data-type descriptor of thenew array isdescr.
Ifsubtype is of an array subclass instead of the base&PyArray_Type, thenobj is the object to pass tothe__array_finalize__ method of the subclass.
Ifdata isNULL, then new memory will be allocated andflagscan be non-zero to indicate a Fortran-style contiguous array. Ifdata is notNULL, then it is assumed to point to the memoryto be used for the array and theflags argument is used as thenew flags for the array (except the state ofNPY_OWNDATA,NPY_ARRAY_WRITEBACKIFCOPY andNPY_ARRAY_UPDATEIFCOPYflags of the new array will be reset).
In addition, ifdata is non-NULL, thenstrides canalso be provided. Ifstrides isNULL, then the array stridesare computed as C-style contiguous (default) or Fortran-stylecontiguous (flags is nonzero fordata =NULL orflags &NPY_ARRAY_F_CONTIGUOUS is nonzero non-NULLdata). Anyprovideddims andstrides are copied into newly allocateddimension and strides arrays for the new array object.
PyArray_NewLikeArray(PyArrayObject* prototype,NPY_ORDER order,PyArray_Descr* descr, int subok)¶New in version 1.6.
This function steals a reference todescr if it is not NULL.
This array creation routine allows for the convenient creation ofa new array matching an existing array’s shapes and memory layout,possibly changing the layout and/or data type.
Whenorder isNPY_ANYORDER, the result order isNPY_FORTRANORDER ifprototype is a fortran array,NPY_CORDER otherwise. Whenorder isNPY_KEEPORDER, the result order matches that ofprototype, evenwhen the axes ofprototype aren’t in C or Fortran order.
Ifdescr is NULL, the data type ofprototype is used.
Ifsubok is 1, the newly created array will use the sub-type ofprototype to create the new array, otherwise it will create abase-class array.
PyArray_New(PyTypeObject* subtype, int nd, npy_intp* dims, int type_num, npy_intp* strides, void* data, int itemsize, int flags,PyObject* obj)¶This is similar toPyArray_NewFromDescr (…) except youspecify the data-type descriptor withtype_num anditemsize,wheretype_num corresponds to a builtin (or user-defined)type. If the type always has the same number of bytes, thenitemsize is ignored. Otherwise, itemsize specifies the particularsize of this array.
Warning
If data is passed toPyArray_NewFromDescr orPyArray_New,this memory must not be deallocated until the new array isdeleted. If this data came from another Python object, this canbe accomplished usingPy_INCREF on that object and setting thebase member of the new array to point to that object. If stridesare passed in they must be consistent with the dimensions, theitemsize, and the data of the array.
PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)¶Create a new uninitialized array of type,typenum, whose size ineach ofnd dimensions is given by the integer array,dims.This function cannot be used to create a flexible-type array (noitemsize given).
PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)¶Create an array wrapper arounddata pointed to by the givenpointer. The array flags will have a default that the data area iswell-behaved and C-style contiguous. The shape of the array isgiven by thedims c-array of lengthnd. The data-type of thearray is indicated bytypenum.
PyArray_SimpleNewFromDescr(int nd, npy_intp* dims,PyArray_Descr* descr)¶This function steals a reference todescr if it is not NULL.
Create a new array with the provided data-type descriptor,descr, of the shape determined bynd anddims.
PyArray_FILLWBYTE(PyObject* obj, int val)¶Fill the array pointed to byobj —which must be a (subclassof) ndarray—with the contents ofval (evaluated as a byte).This macro calls memset, so obj must be contiguous.
PyArray_Zeros(int nd, npy_intp* dims,PyArray_Descr* dtype, int fortran)¶Construct a newnd -dimensional array with shape given bydimsand data type given bydtype. Iffortran is non-zero, then aFortran-order array is created, otherwise a C-order array iscreated. Fill the memory with zeros (or the 0 object ifdtypecorresponds toNPY_OBJECT ).
PyArray_ZEROS(int nd, npy_intp* dims, int type_num, int fortran)¶Macro form ofPyArray_Zeros which takes a type-number insteadof a data-type object.
PyArray_Empty(int nd, npy_intp* dims,PyArray_Descr* dtype, int fortran)¶Construct a newnd -dimensional array with shape given bydimsand data type given bydtype. Iffortran is non-zero, then aFortran-order array is created, otherwise a C-order array iscreated. The array is uninitialized unless the data typecorresponds toNPY_OBJECT in which case the array isfilled withPy_None.
PyArray_EMPTY(int nd, npy_intp* dims, int typenum, int fortran)¶Macro form ofPyArray_Empty which takes a type-number,typenum, instead of a data-type object.
PyArray_Arange(double start, double stop, double step, int typenum)¶Construct a new 1-dimensional array of data-type,typenum, thatranges fromstart tostop (exclusive) in increments ofstep. Equivalent toarange (start,stop,step, dtype).
PyArray_ArangeObj(PyObject* start,PyObject* stop,PyObject* step,PyArray_Descr* descr)¶Construct a new 1-dimensional array of data-type determined bydescr, that ranges fromstart tostop (exclusive) inincrements ofstep. Equivalent to arange(start,stop,step,typenum ).
PyArray_SetBaseObject(PyArrayObject* arr,PyObject* obj)¶New in version 1.7.
This functionsteals a reference toobj and sets it as thebase property ofarr.
If you construct an array by passing in your own memory buffer asa parameter, you need to set the array’sbase property to ensurethe lifetime of the memory buffer is appropriate.
The return value is 0 on success, -1 on failure.
If the object provided is an array, this function traverses thechain ofbase pointers so that each array points to the ownerof the memory directly. Once the base is set, it may not be changedto another value.
PyArray_FromAny(PyObject* op,PyArray_Descr* dtype, int min_depth, int max_depth, int requirements,PyObject* context)¶This is the main function used to obtain an array from any nestedsequence, or object that exposes the array interface,op. Theparameters allow specification of the requireddtype, theminimum (min_depth) and maximum (max_depth) number ofdimensions acceptable, and otherrequirements for the array. Thisfunctionsteals a reference to the dtype argument, which needsto be aPyArray_Descr structureindicating the desired data-type (including requiredbyteorder). Thedtype argument may beNULL, indicating that anydata-type (and byteorder) is acceptable. UnlessNPY_ARRAY_FORCECAST is present inflags,this call will generate an error if the datatype cannot be safely obtained from the object. If you want to useNULL for thedtype and ensure the array is notswapped thenusePyArray_CheckFromAny. A value of 0 for either of thedepth parameters causes the parameter to be ignored. Any of thefollowing array flags can be added (e.g. using |) to get therequirements argument. If your code can handle general (e.g.strided, byte-swapped, or unaligned arrays) thenrequirementsmay be 0. Also, ifop is not already an array (or does notexpose the array interface), then a new array will be created (andfilled fromop using the sequence protocol). The new array willhaveNPY_ARRAY_DEFAULT as its flags member. Thecontext argumentis passed to the__array__ method ofop and is only used ifthe array is constructed that way. Almost always thisparameter isNULL.
In versions 1.6 and earlier of NumPy, the following flagsdid not have the_ARRAY_ macro namespace in them. That formof the constant names is deprecated in 1.7.
NPY_ARRAY_C_CONTIGUOUS¶Make sure the returned array is C-style contiguous
NPY_ARRAY_F_CONTIGUOUS¶Make sure the returned array is Fortran-style contiguous.
NPY_ARRAY_ALIGNED¶Make sure the returned array is aligned on proper boundaries for itsdata type. An aligned array has the data pointer and every stridesfactor as a multiple of the alignment factor for the data-type-descriptor.
NPY_ARRAY_WRITEABLE¶Make sure the returned array can be written to.
NPY_ARRAY_ENSURECOPY¶Make sure a copy is made ofop. If this flag is notpresent, data is not copied if it can be avoided.
NPY_ARRAY_ENSUREARRAY¶Make sure the result is a base-class ndarray. Bydefault, ifop is an instance of a subclass ofndarray, an instance of that same subclass is returned. Ifthis flag is set, an ndarray object will be returned instead.
NPY_ARRAY_FORCECAST¶Force a cast to the output type even if it cannot be donesafely. Without this flag, a data cast will occur only if itcan be done safely, otherwise an error is raised.
NPY_ARRAY_WRITEBACKIFCOPY¶Ifop is already an array, but does not satisfy therequirements, then a copy is made (which will satisfy therequirements). If this flag is present and a copy (of an objectthat is already an array) must be made, then the correspondingNPY_ARRAY_WRITEBACKIFCOPY flag is set in the returnedcopy andop is made to be read-only. You must be sure to callPyArray_ResolveWritebackIfCopy to copy the contentsback intoop and theop arraywill be made writeable again. Ifop is not writeable to beginwith, or if it is not already an array, then an error is raised.
NPY_ARRAY_UPDATEIFCOPY¶Deprecated. UseNPY_ARRAY_WRITEBACKIFCOPY, which is similar.This flag “automatically” copies the data back when the returnedarray is deallocated, which is not supported in all pythonimplementations.
NPY_ARRAY_BEHAVED¶NPY_ARRAY_CARRAY¶NPY_ARRAY_CARRAY_RO¶NPY_ARRAY_FARRAY¶NPY_ARRAY_FARRAY_RO¶NPY_ARRAY_DEFAULT¶NPY_ARRAY_IN_ARRAY¶NPY_ARRAY_IN_FARRAY¶NPY_OUT_ARRAY¶NPY_ARRAY_C_CONTIGUOUS |NPY_ARRAY_WRITEABLE |NPY_ARRAY_ALIGNED
NPY_ARRAY_OUT_FARRAY¶NPY_ARRAY_F_CONTIGUOUS |NPY_ARRAY_WRITEABLE |NPY_ARRAY_ALIGNED
NPY_ARRAY_INOUT_ARRAY¶NPY_ARRAY_C_CONTIGUOUS |NPY_ARRAY_WRITEABLE |NPY_ARRAY_ALIGNED |NPY_ARRAY_WRITEBACKIFCOPY |NPY_ARRAY_UPDATEIFCOPY
NPY_ARRAY_INOUT_FARRAY¶NPY_ARRAY_F_CONTIGUOUS |NPY_ARRAY_WRITEABLE |NPY_ARRAY_ALIGNED |NPY_ARRAY_WRITEBACKIFCOPY |NPY_ARRAY_UPDATEIFCOPY
PyArray_GetArrayParamsFromObject(PyObject* op,PyArray_Descr* requested_dtype,npy_bool writeable,PyArray_Descr** out_dtype, int* out_ndim, npy_intp* out_dims,PyArrayObject** out_arr,PyObject* context)¶New in version 1.6.
Retrieves the array parameters for viewing/converting an arbitraryPyObject* to a NumPy array. This allows the “innate type and shape”of Python list-of-lists to be discovered withoutactually converting to an array. PyArray_FromAny calls this functionto analyze its input.
In some cases, such as structured arrays and the__array__ interface,a data type needs to be used to make sense of the object. Whenthis is needed, provide a Descr for ‘requested_dtype’, otherwiseprovide NULL. This reference is not stolen. Also, if the requesteddtype doesn’t modify the interpretation of the input, out_dtype willstill get the “innate” dtype of the object, not the dtype passedin ‘requested_dtype’.
If writing to the value in ‘op’ is desired, set the boolean‘writeable’ to 1. This raises an error when ‘op’ is a scalar, listof lists, or other non-writeable ‘op’. This differs from passingNPY_ARRAY_WRITEABLE to PyArray_FromAny, where the writeable array maybe a copy of the input.
When success (0 return value) is returned, either out_arris filled with a non-NULL PyArrayObject andthe rest of the parameters are untouched, or out_arr isfilled with NULL, and the rest of the parameters are filled.
Typical usage:
PyArrayObject *arr = NULL;PyArray_Descr *dtype = NULL;int ndim = 0;npy_intp dims[NPY_MAXDIMS];if (PyArray_GetArrayParamsFromObject(op, NULL, 1, &dtype, &ndim, &dims, &arr, NULL) < 0) { return NULL;}if (arr == NULL) { ... validate/change dtype, validate flags, ndim, etc ... // Could make custom strides here too arr = PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, dims, NULL, fortran ? NPY_ARRAY_F_CONTIGUOUS : 0, NULL); if (arr == NULL) { return NULL; } if (PyArray_CopyObject(arr, op) < 0) { Py_DECREF(arr); return NULL; }}else { ... in this case the other parameters weren't filled, just validate and possibly copy arr itself ...}... use arr ...PyArray_CheckFromAny(PyObject* op,PyArray_Descr* dtype, int min_depth, int max_depth, int requirements,PyObject* context)¶Nearly identical toPyArray_FromAny (…) exceptrequirements can containNPY_ARRAY_NOTSWAPPED (over-riding thespecification indtype) andNPY_ARRAY_ELEMENTSTRIDES whichindicates that the array should be aligned in the sense that thestrides are multiples of the element size.
In versions 1.6 and earlier of NumPy, the following flagsdid not have the _ARRAY_ macro namespace in them. That formof the constant names is deprecated in 1.7.
NPY_ARRAY_NOTSWAPPED¶Make sure the returned array has a data-type descriptor that is inmachine byte-order, over-riding any specification in thedtypeargument. Normally, the byte-order requirement is determined bythedtype argument. If this flag is set and the dtype argumentdoes not indicate a machine byte-order descriptor (or is NULL andthe object is already an array with a data-type descriptor that isnot in machine byte- order), then a new data-type descriptor iscreated and used with its byte-order field set to native.
NPY_ARRAY_BEHAVED_NS¶NPY_ARRAY_ALIGNED |NPY_ARRAY_WRITEABLE |NPY_ARRAY_NOTSWAPPED
NPY_ARRAY_ELEMENTSTRIDES¶Make sure the returned array has strides that are multiples of theelement size.
PyArray_FromArray(PyArrayObject* op,PyArray_Descr* newtype, int requirements)¶Special case ofPyArray_FromAny for whenop is already anarray but it needs to be of a specificnewtype (includingbyte-order) or has certainrequirements.
PyArray_FromStructInterface(PyObject* op)¶Returns an ndarray object from a Python object that exposes the__array_struct__ attribute and follows the array interfaceprotocol. If the object does not contain this attribute then aborrowed reference toPy_NotImplemented is returned.
PyArray_FromInterface(PyObject* op)¶Returns an ndarray object from a Python object that exposes the__array_interface__ attribute following the array interfaceprotocol. If the object does not contain this attribute then aborrowed reference toPy_NotImplemented is returned.
PyArray_FromArrayAttr(PyObject* op,PyArray_Descr* dtype,PyObject* context)¶Return an ndarray object from a Python object that exposes the__array__ method. The__array__ method can take 0, 1, or 2arguments ([dtype, context]) wherecontext is used to passinformation about where the__array__ method is being calledfrom (currently only used in ufuncs).
PyArray_ContiguousFromAny(PyObject* op, int typenum, int min_depth, int max_depth)¶This function returns a (C-style) contiguous and behaved functionarray from any nested sequence or array interface exportingobject,op, of (non-flexible) type given by the enumeratedtypenum, of minimum depthmin_depth, and of maximum depthmax_depth. Equivalent to a call toPyArray_FromAny withrequirements set toNPY_ARRAY_DEFAULT and the type_num member of thetype argument set totypenum.
PyArray_FromObject(PyObject *op, int typenum, int min_depth, int max_depth)¶Return an aligned and in native-byteorder array from any nestedsequence or array-interface exporting object, op, of a type given bythe enumerated typenum. The minimum number of dimensions the array canhave is given by min_depth while the maximum is max_depth. This isequivalent to a call toPyArray_FromAny with requirements set toBEHAVED.
PyArray_EnsureArray(PyObject* op)¶This functionsteals a reference toop and makes sure thatop is a base-class ndarray. It special cases array scalars,but otherwise callsPyArray_FromAny (op, NULL, 0, 0,NPY_ARRAY_ENSUREARRAY, NULL).
PyArray_FromString(char* string, npy_intp slen,PyArray_Descr* dtype, npy_intp num, char* sep)¶Construct a one-dimensional ndarray of a single type from a binaryor (ASCII) textstring of lengthslen. The data-type ofthe array to-be-created is given bydtype. If num is -1, thencopy the entire string and return an appropriately sizedarray, otherwise,num is the number of items tocopy fromthe string. Ifsep is NULL (or “”), then interpret the stringas bytes of binary data, otherwise convert the sub-stringsseparated bysep to items of data-typedtype. Somedata-types may not be readable in text mode and an error will beraised if that occurs. All errors return NULL.
PyArray_FromFile(FILE* fp,PyArray_Descr* dtype, npy_intp num, char* sep)¶Construct a one-dimensional ndarray of a single type from a binaryor text file. The open file pointer isfp, the data-type ofthe array to be created is given bydtype. This must matchthe data in the file. Ifnum is -1, then read until the end ofthe file and return an appropriately sized array, otherwise,num is the number of items to read. Ifsep is NULL (or“”), then read from the file in binary mode, otherwise read fromthe file in text mode withsep providing the itemseparator. Some array types cannot be read in text mode in whichcase an error is raised.
PyArray_FromBuffer(PyObject* buf,PyArray_Descr* dtype, npy_intp count, npy_intp offset)¶Construct a one-dimensional ndarray of a single type from anobject,buf, that exports the (single-segment) buffer protocol(or has an attribute __buffer__ that returns an object thatexports the buffer protocol). A writeable buffer will be triedfirst followed by a read- only buffer. TheNPY_ARRAY_WRITEABLEflag of the returned array will reflect which one wassuccessful. The data is assumed to start atoffset bytes fromthe start of the memory location for the object. The type of thedata in the buffer will be interpreted depending on the data- typedescriptor,dtype. Ifcount is negative then it will bedetermined from the size of the buffer and the requested itemsize,otherwise,count represents how many elements should beconverted from the buffer.
PyArray_CopyInto(PyArrayObject* dest,PyArrayObject* src)¶Copy from the source array,src, into the destination array,dest, performing a data-type conversion if necessary. If anerror occurs return -1 (otherwise 0). The shape ofsrc must bebroadcastable to the shape ofdest. The data areas of destand src must not overlap.
PyArray_MoveInto(PyArrayObject* dest,PyArrayObject* src)¶Move data from the source array,src, into the destinationarray,dest, performing a data-type conversion ifnecessary. If an error occurs return -1 (otherwise 0). The shapeofsrc must be broadcastable to the shape ofdest. Thedata areas of dest and src may overlap.
PyArray_GETCONTIGUOUS(PyObject* op)¶Ifop is already (C-style) contiguous and well-behaved thenjust return a reference, otherwise return a (contiguous andwell-behaved) copy of the array. The parameter op must be a(sub-class of an) ndarray and no checking for that is done.
PyArray_FROM_O(PyObject* obj)¶Convertobj to an ndarray. The argument can be any nestedsequence or object that exports the array interface. This is amacro form ofPyArray_FromAny usingNULL, 0, 0, 0 for theother arguments. Your code must be able to handle any data-typedescriptor and any combination of data-flags to use this macro.
PyArray_FROM_OF(PyObject* obj, int requirements)¶Similar toPyArray_FROM_O except it can take an argumentofrequirements indicating properties the resulting array musthave. Available requirements that can be enforced areNPY_ARRAY_C_CONTIGUOUS,NPY_ARRAY_F_CONTIGUOUS,NPY_ARRAY_ALIGNED,NPY_ARRAY_WRITEABLE,NPY_ARRAY_NOTSWAPPED,NPY_ARRAY_ENSURECOPY,NPY_ARRAY_WRITEBACKIFCOPY,NPY_ARRAY_UPDATEIFCOPY,NPY_ARRAY_FORCECAST, andNPY_ARRAY_ENSUREARRAY. Standard combinations of flags can alsobe used:
PyArray_FROM_OT(PyObject* obj, int typenum)¶Similar toPyArray_FROM_O except it can take an argument oftypenum specifying the type-number the returned array.
PyArray_FROM_OTF(PyObject* obj, int typenum, int requirements)¶Combination ofPyArray_FROM_OF andPyArray_FROM_OTallowing both atypenum and aflags argument to be provided..
PyArray_FROMANY(PyObject* obj, int typenum, int min, int max, int requirements)¶Similar toPyArray_FromAny except the data-type isspecified using a typenumber.PyArray_DescrFromType(typenum) is passed directly toPyArray_FromAny. Thismacro also addsNPY_ARRAY_DEFAULT to requirements ifNPY_ARRAY_ENSURECOPY is passed in as requirements.
PyArray_CheckAxis(PyObject* obj, int* axis, int requirements)¶Encapsulate the functionality of functions and methods that takethe axis= keyword and work properly with None as the axisargument. The input array isobj, while*axis is aconverted integer (so that >=MAXDIMS is the None value), andrequirements gives the needed properties ofobj. Theoutput is a converted version of the input so that requirementsare met and if needed a flattening has occurred. On outputnegative values of*axis are converted and the new value ischecked to ensure consistency with the shape ofobj.
PyArray_Check(op)¶Evaluates true ifop is a Python object whose type is a sub-typeofPyArray_Type.
PyArray_CheckExact(op)¶Evaluates true ifop is a Python object with typePyArray_Type.
PyArray_HasArrayInterface(op, out)¶Ifop implements any part of the array interface, thenoutwill contain a new reference to the newly created ndarray usingthe interface orout will containNULL if an error duringconversion occurs. Otherwise, out will contain a borrowedreference toPy_NotImplemented and no error condition is set.
PyArray_HasArrayInterfaceType(op, type, context, out)¶Ifop implements any part of the array interface, thenoutwill contain a new reference to the newly created ndarray usingthe interface orout will containNULL if an error duringconversion occurs. Otherwise, out will contain a borrowedreference to Py_NotImplemented and no error condition is set.This version allows setting of the type and context in the part ofthe array interface that looks for the__array__ attribute.
PyArray_IsZeroDim(op)¶Evaluates true ifop is an instance of (a subclass of)PyArray_Type and has 0 dimensions.
PyArray_IsScalar(op, cls)¶Evaluates true ifop is an instance ofPy{cls}ArrType_Type.
PyArray_CheckScalar(op)¶Evaluates true ifop is either an array scalar (an instance of asub-type ofPyGenericArr_Type ), or an instance of (asub-class of)PyArray_Type whose dimensionality is 0.
PyArray_IsPythonNumber(op)¶Evaluates true ifop is an instance of a builtin numeric type (int,float, complex, long, bool)
PyArray_IsPythonScalar(op)¶Evaluates true ifop is a builtin Python scalar object (int,float, complex, str, unicode, long, bool).
PyArray_IsAnyScalar(op)¶Evaluates true ifop is either a Python scalar object (seePyArray_IsPythonScalar) or an array scalar (an instance of a sub-type ofPyGenericArr_Type ).
PyArray_CheckAnyScalar(op)¶Evaluates true ifop is a Python scalar object (seePyArray_IsPythonScalar), an array scalar (an instance of asub-type ofPyGenericArr_Type) or an instance of a sub-type ofPyArray_Type whose dimensionality is 0.
For the typenum macros, the argument is an integer representing anenumerated array data type. For the array type checking macros theargument must be aPyObject* that can be directly interpreted as aPyArrayObject*.
PyTypeNum_ISUNSIGNED(num)¶PyDataType_ISUNSIGNED(descr)¶PyArray_ISUNSIGNED(obj)¶Type represents an unsigned integer.
PyTypeNum_ISSIGNED(num)¶PyDataType_ISSIGNED(descr)¶PyArray_ISSIGNED(obj)¶Type represents a signed integer.
PyTypeNum_ISINTEGER(num)¶PyDataType_ISINTEGER(descr)¶PyArray_ISINTEGER(obj)¶Type represents any integer.
PyTypeNum_ISFLOAT(num)¶PyDataType_ISFLOAT(descr)¶PyArray_ISFLOAT(obj)¶Type represents any floating point number.
PyTypeNum_ISCOMPLEX(num)¶PyDataType_ISCOMPLEX(descr)¶PyArray_ISCOMPLEX(obj)¶Type represents any complex floating point number.
PyTypeNum_ISNUMBER(num)¶PyDataType_ISNUMBER(descr)¶PyArray_ISNUMBER(obj)¶Type represents any integer, floating point, or complex floating pointnumber.
PyTypeNum_ISSTRING(num)¶PyDataType_ISSTRING(descr)¶PyArray_ISSTRING(obj)¶Type represents a string data type.
PyTypeNum_ISPYTHON(num)¶PyDataType_ISPYTHON(descr)¶PyArray_ISPYTHON(obj)¶Type represents an enumerated type corresponding to one of thestandard Python scalar (bool, int, float, or complex).
PyTypeNum_ISFLEXIBLE(num)¶PyDataType_ISFLEXIBLE(descr)¶PyArray_ISFLEXIBLE(obj)¶Type represents one of the flexible array types (NPY_STRING,NPY_UNICODE, orNPY_VOID ).
PyDataType_ISUNSIZED(descr):Type has no size information attached, and can be resized. Should only becalled on flexible dtypes. Types that are attached to an array will alwaysbe sized, hence the array form of this macro not existing.
PyTypeNum_ISUSERDEF(num)¶PyDataType_ISUSERDEF(descr)¶PyArray_ISUSERDEF(obj)¶Type represents a user-defined type.
PyTypeNum_ISEXTENDED(num)¶PyDataType_ISEXTENDED(descr)¶PyArray_ISEXTENDED(obj)¶Type is either flexible or user-defined.
PyTypeNum_ISOBJECT(num)¶PyDataType_ISOBJECT(descr)¶PyArray_ISOBJECT(obj)¶Type represents object data type.
PyTypeNum_ISBOOL(num)¶PyDataType_ISBOOL(descr)¶PyArray_ISBOOL(obj)¶Type represents Boolean data type.
PyDataType_HASFIELDS(descr)¶PyArray_HASFIELDS(obj)¶Type has fields associated with it.
PyArray_ISNOTSWAPPED(m)¶Evaluates true if the data area of the ndarraym is in machinebyte-order according to the array’s data-type descriptor.
PyArray_ISBYTESWAPPED(m)¶Evaluates true if the data area of the ndarraym isnot inmachine byte-order according to the array’s data-type descriptor.
PyArray_EquivTypes(PyArray_Descr* type1,PyArray_Descr* type2)¶ReturnNPY_TRUE iftype1 andtype2 actually representequivalent types for this platform (the fortran member of eachtype is ignored). For example, on 32-bit platforms,NPY_LONG andNPY_INT are equivalent. OtherwisereturnNPY_FALSE.
PyArray_EquivArrTypes(PyArrayObject* a1,PyArrayObject * a2)¶ReturnNPY_TRUE ifa1 anda2 are arrays with equivalenttypes for this platform.
PyArray_EquivTypenums(int typenum1, int typenum2)¶Special case ofPyArray_EquivTypes (…) that does not acceptflexible data types but may be easier to call.
PyArray_EquivByteorders({byteorder} b1, {byteorder} b2)¶True if byteorder characters (NPY_LITTLE,NPY_BIG,NPY_NATIVE,NPY_IGNORE ) areeither equal or equivalent as to their specification of a nativebyte order. Thus, on a little-endian machineNPY_LITTLEandNPY_NATIVE are equivalent where they are notequivalent on a big-endian machine.
PyArray_Cast(PyArrayObject* arr, int typenum)¶Mainly for backwards compatibility to the Numeric C-API and forsimple casts to non-flexible types. Return a new array object withthe elements ofarr cast to the data-typetypenum which mustbe one of the enumerated types and not a flexible type.
PyArray_CastToType(PyArrayObject* arr,PyArray_Descr* type, int fortran)¶Return a new array of thetype specified, casting the elementsofarr as appropriate. The fortran argument specifies theordering of the output array.
PyArray_CastTo(PyArrayObject* out,PyArrayObject* in)¶As of 1.6, this function simply callsPyArray_CopyInto,which handles the casting.
Cast the elements of the arrayin into the arrayout. Theoutput array should be writeable, have an integer-multiple of thenumber of elements in the input array (more than one copy can beplaced in out), and have a data type that is one of the builtintypes. Returns 0 on success and -1 if an error occurs.
PyArray_GetCastFunc(PyArray_Descr* from, int totype)¶Return the low-level casting function to cast from the givendescriptor to the builtin type number. If no casting functionexists returnNULL and set an error. Using this functioninstead of direct access tofrom ->f->cast will allow support ofany user-defined casting functions added to a descriptors castingdictionary.
PyArray_CanCastSafely(int fromtype, int totype)¶Returns non-zero if an array of data typefromtype can be castto an array of data typetotype without losing information. Anexception is that 64-bit integers are allowed to be cast to 64-bitfloating point values even though this can lose precision on largeintegers so as not to proliferate the use of long doubles withoutexplicit requests. Flexible array types are not checked accordingto their lengths with this function.
PyArray_CanCastTo(PyArray_Descr* fromtype,PyArray_Descr* totype)¶PyArray_CanCastTypeTo supersedes this function inNumPy 1.6 and later.
Equivalent to PyArray_CanCastTypeTo(fromtype, totype, NPY_SAFE_CASTING).
PyArray_CanCastTypeTo(PyArray_Descr* fromtype,PyArray_Descr* totype,NPY_CASTING casting)¶New in version 1.6.
Returns non-zero if an array of data typefromtype (which caninclude flexible types) can be cast safely to an array of datatypetotype (which can include flexible types) according tothe casting rulecasting. For simple types withNPY_SAFE_CASTING,this is basically a wrapper aroundPyArray_CanCastSafely, butfor flexible types such as strings or unicode, it produces resultstaking into account their sizes. Integer and float types can only be castto a string or unicode type usingNPY_SAFE_CASTING if the stringor unicode type is big enough to hold the max value of the integer/floattype being cast from.
PyArray_CanCastArrayTo(PyArrayObject* arr,PyArray_Descr* totype,NPY_CASTING casting)¶New in version 1.6.
Returns non-zero ifarr can be cast tototype accordingto the casting rule given incasting. Ifarr is an arrayscalar, its value is taken into account, and non-zero is alsoreturned when the value will not overflow or be truncated toan integer when converting to a smaller type.
This is almost the same as the result ofPyArray_CanCastTypeTo(PyArray_MinScalarType(arr), totype, casting),but it also handles a special case arising because the setof uint values is not a subset of the int values for types with thesame number of bits.
PyArray_MinScalarType(PyArrayObject* arr)¶New in version 1.6.
Ifarr is an array, returns its data type descriptor, but ifarr is an array scalar (has 0 dimensions), it finds the data typeof smallest size to which the value may be convertedwithout overflow or truncation to an integer.
This function will not demote complex to float or anything toboolean, but will demote a signed integer to an unsigned integerwhen the scalar value is positive.
PyArray_PromoteTypes(PyArray_Descr* type1,PyArray_Descr* type2)¶New in version 1.6.
Finds the data type of smallest size and kind to whichtype1 andtype2 may be safely converted. This function is symmetric andassociative. A string or unicode result will be the proper size forstoring the max value of the input types converted to a string or unicode.
PyArray_ResultType(npy_intp narrs,PyArrayObject**arrs, npy_intp ndtypes,PyArray_Descr**dtypes)¶New in version 1.6.
This applies type promotion to all the inputs,using the NumPy rules for combining scalars and arrays, todetermine the output type of a set of operands. This is thesame result type that ufuncs produce. The specific algorithmused is as follows.
Categories are determined by first checking which of boolean,integer (int/uint), or floating point (float/complex) the maximumkind of all the arrays and the scalars are.
If there are only scalars or the maximum category of the scalarsis higher than the maximum category of the arrays,the data types are combined withPyArray_PromoteTypesto produce the return value.
Otherwise, PyArray_MinScalarType is called on each array, andthe resulting data types are all combined withPyArray_PromoteTypes to produce the return value.
The set of int values is not a subset of the uint values for typeswith the same number of bits, something not reflected inPyArray_MinScalarType, but handled as a special case inPyArray_ResultType.
PyArray_ObjectType(PyObject* op, int mintype)¶This function is superceded byPyArray_MinScalarType and/orPyArray_ResultType.
This function is useful for determining a common type that two ormore arrays can be converted to. It only works for non-flexiblearray types as no itemsize information is passed. Themintypeargument represents the minimum type acceptable, andoprepresents the object that will be converted to an array. Thereturn value is the enumerated typenumber that represents thedata-type thatop should have.
PyArray_ArrayType(PyObject* op,PyArray_Descr* mintype,PyArray_Descr* outtype)¶This function is superceded byPyArray_ResultType.
This function works similarly toPyArray_ObjectType (…)except it handles flexible arrays. Themintype argument can havean itemsize member and theouttype argument will have anitemsize member at least as big but perhaps bigger depending onthe objectop.
PyArray_ConvertToCommonType(PyObject* op, int* n)¶The functionality this provides is largely superceded by iteratorNpyIter introduced in 1.6, with flagNPY_ITER_COMMON_DTYPE or with the same dtype parameter forall operands.
Convert a sequence of Python objects contained inop to an arrayof ndarrays each having the same data type. The type is selectedbased on the typenumber (larger type number is chosen over asmaller one) ignoring objects that are only scalars. The length ofthe sequence is returned inn, and ann -length array ofPyArrayObject pointers is the return value (orNULL if anerror occurs). The returned array must be freed by the caller ofthis routine (usingPyDataMem_FREE ) and all the array objectsin itDECREF ‘d or a memory-leak will occur. The exampletemplate-code below shows a typically usage:
mps=PyArray_ConvertToCommonType(obj,&n);if(mps==NULL)returnNULL;{code}<beforereturn>for(i=0;i<n;i++)Py_DECREF(mps[i]);PyDataMem_FREE(mps);{return}
PyArray_Zero(PyArrayObject* arr)¶A pointer to newly created memory of sizearr ->itemsize thatholds the representation of 0 for that type. The returned pointer,ret,must be freed usingPyDataMem_FREE (ret) when it isnot needed anymore.
PyArray_One(PyArrayObject* arr)¶A pointer to newly created memory of sizearr ->itemsize thatholds the representation of 1 for that type. The returned pointer,ret,must be freed usingPyDataMem_FREE (ret) when itis not needed anymore.
PyArray_InitArrFuncs(PyArray_ArrFuncs* f)¶Initialize all function pointers and members toNULL.
PyArray_RegisterDataType(PyArray_Descr* dtype)¶Register a data-type as a new user-defined data type forarrays. The type must have most of its entries filled in. This isnot always checked and errors can produce segfaults. Inparticular, the typeobj member of thedtype structure must befilled with a Python type that has a fixed-size element-size thatcorresponds to the elsize member ofdtype. Also thefmember must have the required functions: nonzero, copyswap,copyswapn, getitem, setitem, and cast (some of the cast functionsmay beNULL if no support is desired). To avoid confusion, youshould choose a unique character typecode but this is not enforcedand not relied on internally.
A user-defined type number is returned that uniquely identifiesthe type. A pointer to the new structure can then be obtained fromPyArray_DescrFromType using the returned type number. A -1 isreturned if an error occurs. If thisdtype has already beenregistered (checked only by the address of the pointer), thenreturn the previously-assigned type-number.
PyArray_RegisterCastFunc(PyArray_Descr* descr, int totype, PyArray_VectorUnaryFunc* castfunc)¶Register a low-level casting function,castfunc, to convertfrom the data-type,descr, to the given data-type number,totype. Any old casting function is over-written. A0 isreturned on success or a-1 on failure.
PyArray_RegisterCanCast(PyArray_Descr* descr, int totype,NPY_SCALARKIND scalar)¶Register the data-type number,totype, as castable fromdata-type object,descr, of the givenscalar kind. Usescalar =NPY_NOSCALAR to register that an array of data-typedescr can be cast safely to a data-type whose type_number istotype.
PyArray_INCREF(PyArrayObject* op)¶Used for an array,op, that contains any Python objects. Itincrements the reference count of every object in the arrayaccording to the data-type ofop. A -1 is returned if an erroroccurs, otherwise 0 is returned.
PyArray_Item_INCREF(char* ptr,PyArray_Descr* dtype)¶A function to INCREF all the objects at the locationptraccording to the data-typedtype. Ifptr is the start of astructured type with an object at any offset, then this will (recursively)increment the reference count of all object-like items in thestructured type.
PyArray_XDECREF(PyArrayObject* op)¶Used for an array,op, that contains any Python objects. Itdecrements the reference count of every object in the arrayaccording to the data-type ofop. Normal return value is 0. A-1 is returned if an error occurs.
PyArray_Item_XDECREF(char* ptr,PyArray_Descr* dtype)¶A function to XDECREF all the object-like items at the locationptr as recorded in the data-type,dtype. This worksrecursively so that ifdtype itself has fields with data-typesthat contain object-like items, all the object-like fields will beXDECREF'd.
PyArray_FillObjectArray(PyArrayObject* arr,PyObject* obj)¶Fill a newly created array with a single value obj at alllocations in the structure with object data-types. No checking isperformed butarr must be of data-typeNPY_OBJECT and besingle-segment and uninitialized (no previous objects inposition). UsePyArray_DECREF (arr) if you need todecrement all the items in the object array prior to calling thisfunction.
PyArray_SetUpdateIfCopyBase(PyArrayObject* arr,PyArrayObject* base)¶Precondition:arr is a copy ofbase (though possibly with differentstrides, ordering, etc.) Set the UPDATEIFCOPY flag andarr->base sothat whenarr is destructed, it will copy any changes back tobase.DEPRECATED, usePyArray_SetWritebackIfCopyBase`.
Returns 0 for success, -1 for failure.
PyArray_SetWritebackIfCopyBase(PyArrayObject* arr,PyArrayObject* base)¶Precondition:arr is a copy ofbase (though possibly with differentstrides, ordering, etc.) Sets theNPY_ARRAY_WRITEBACKIFCOPY flagandarr->base, and setbase to READONLY. CallPyArray_ResolveWritebackIfCopy before callingPy_DECREF` in order copy any changes back tobase andreset the READONLY flag.
Returns 0 for success, -1 for failure.
Theflags attribute of thePyArrayObject structure containsimportant information about the memory used by the array (pointed toby the data member) This flag information must be kept accurate orstrange results and even segfaults may result.
There are 6 (binary) flags that describe the memory area used by thedata buffer. These constants are defined inarrayobject.h anddetermine the bit-position of the flag. Python exposes a niceattribute- based interface as well as a dictionary-like interface forgetting (and, if appropriate, setting) these flags.
Memory areas of all kinds can be pointed to by an ndarray, necessitatingthese flags. If you get an arbitraryPyArrayObject in C-code, youneed to be aware of the flags that are set. If you need to guaranteea certain kind of array (likeNPY_ARRAY_C_CONTIGUOUS andNPY_ARRAY_BEHAVED), then pass these requirements into thePyArray_FromAny function.
An ndarray can have a data segment that is not a simple contiguouschunk of well-behaved memory you can manipulate. It may not be alignedwith word boundaries (very important on some platforms). It might haveits data in a different byte-order than the machine recognizes. Itmight not be writeable. It might be in Fortan-contiguous order. Thearray flags are used to indicate what can be said about dataassociated with an array.
In versions 1.6 and earlier of NumPy, the following flagsdid not have the _ARRAY_ macro namespace in them. That formof the constant names is deprecated in 1.7.
NPY_ARRAY_C_CONTIGUOUSThe data area is in C-style contiguous order (last index varies thefastest).
NPY_ARRAY_F_CONTIGUOUSThe data area is in Fortran-style contiguous order (first index variesthe fastest).
Note
Arrays can be both C-style and Fortran-style contiguous simultaneously.This is clear for 1-dimensional arrays, but can also be true for higherdimensional arrays.
Even for contiguous arrays a stride for a given dimensionarr.strides[dim] may bearbitrary ifarr.shape[dim]==1or the array has no elements.It doesnot generally hold thatself.strides[-1]==self.itemsizefor C-style contiguous arrays orself.strides[0]==self.itemsize forFortran-style contiguous arrays is true. The correct way to access theitemsize of an array from the C API isPyArray_ITEMSIZE(arr).
NPY_ARRAY_OWNDATA¶The data area is owned by this array.
NPY_ARRAY_ALIGNEDThe data area and all array elements are aligned appropriately.
NPY_ARRAY_WRITEABLEThe data area can be written to.
Notice that the above 3 flags are defined so that a new, well-behaved array has these flags defined as true.
NPY_ARRAY_WRITEBACKIFCOPYThe data area represents a (well-behaved) copy whose informationshould be transferred back to the original whenPyArray_ResolveWritebackIfCopy is called.
This is a special flag that is set if this array represents a copymade because a user required certain flags inPyArray_FromAny and a copy had to be made of some otherarray (and the user asked for this flag to be set in such asituation). The base attribute then points to the “misbehaved”array (which is set read_only). :c:func`PyArray_ResolveWritebackIfCopy`will copy its contents back to the “misbehaved”array (casting if necessary) and will reset the “misbehaved” arraytoNPY_ARRAY_WRITEABLE. If the “misbehaved” array was notNPY_ARRAY_WRITEABLE to begin with thenPyArray_FromAnywould have returned an error becauseNPY_ARRAY_WRITEBACKIFCOPYwould not have been possible.
NPY_ARRAY_UPDATEIFCOPYA deprecated version ofNPY_ARRAY_WRITEBACKIFCOPY whichdepends upondealloc to trigger the writeback. For backwardscompatibility,PyArray_ResolveWritebackIfCopy is called atdealloc but relyingon that behavior is deprecated and not supported in PyPy.
PyArray_UpdateFlags (obj, flags) will update theobj->flagsforflags which can be any ofNPY_ARRAY_C_CONTIGUOUS,NPY_ARRAY_F_CONTIGUOUS,NPY_ARRAY_ALIGNED, orNPY_ARRAY_WRITEABLE.
NPY_ARRAY_BEHAVEDNPY_ARRAY_CARRAYNPY_ARRAY_CARRAY_RONPY_ARRAY_FARRAYNPY_ARRAY_FARRAY_RONPY_ARRAY_DEFAULTNPY_ARRAY_UPDATE_ALL¶NPY_ARRAY_C_CONTIGUOUS |NPY_ARRAY_F_CONTIGUOUS |NPY_ARRAY_ALIGNED
These constants are used inPyArray_FromAny (and its macro forms) tospecify desired properties of the new array.
NPY_ARRAY_FORCECASTCast to the desired type, even if it can’t be done without losinginformation.
NPY_ARRAY_ENSURECOPYMake sure the resulting array is a copy of the original.
NPY_ARRAY_ENSUREARRAYMake sure the resulting object is an actual ndarray, and not a sub-class.
NPY_ARRAY_NOTSWAPPEDOnly used inPyArray_CheckFromAny to over-ride the byteorderof the data-type object passed in.
NPY_ARRAY_BEHAVED_NSNPY_ARRAY_ALIGNED |NPY_ARRAY_WRITEABLE |NPY_ARRAY_NOTSWAPPED
For all of these macrosarr must be an instance of a (subclass of)PyArray_Type, but no checking is done.
PyArray_CHKFLAGS(arr, flags)¶The first parameter, arr, must be an ndarray or subclass. Theparameter,flags, should be an integer consisting of bitwisecombinations of the possible flags an array can have:NPY_ARRAY_C_CONTIGUOUS,NPY_ARRAY_F_CONTIGUOUS,NPY_ARRAY_OWNDATA,NPY_ARRAY_ALIGNED,NPY_ARRAY_WRITEABLE,NPY_ARRAY_WRITEBACKIFCOPY,NPY_ARRAY_UPDATEIFCOPY.
PyArray_IS_C_CONTIGUOUS(arr)¶Evaluates true ifarr is C-style contiguous.
PyArray_IS_F_CONTIGUOUS(arr)¶Evaluates true ifarr is Fortran-style contiguous.
PyArray_ISFORTRAN(arr)¶Evaluates true ifarr is Fortran-style contiguous andnotC-style contiguous.PyArray_IS_F_CONTIGUOUSis the correct way to test for Fortran-style contiguity.
PyArray_ISWRITEABLE(arr)¶Evaluates true if the data area ofarr can be written to
PyArray_ISALIGNED(arr)¶Evaluates true if the data area ofarr is properly aligned onthe machine.
PyArray_ISBEHAVED(arr)¶Evaluates true if the data area ofarr is aligned and writeableand in machine byte-order according to its descriptor.
PyArray_ISBEHAVED_RO(arr)¶Evaluates true if the data area ofarr is aligned and in machinebyte-order.
PyArray_ISCARRAY(arr)¶Evaluates true if the data area ofarr is C-style contiguous,andPyArray_ISBEHAVED (arr) is true.
PyArray_ISFARRAY(arr)¶Evaluates true if the data area ofarr is Fortran-stylecontiguous andPyArray_ISBEHAVED (arr) is true.
PyArray_ISCARRAY_RO(arr)¶Evaluates true if the data area ofarr is C-style contiguous,aligned, and in machine byte-order.
PyArray_ISFARRAY_RO(arr)¶Evaluates true if the data area ofarr is Fortran-stylecontiguous, aligned, and in machine byte-order.
PyArray_ISONESEGMENT(arr)¶Evaluates true if the data area ofarr consists of a single(C-style or Fortran-style) contiguous segment.
PyArray_UpdateFlags(PyArrayObject* arr, int flagmask)¶TheNPY_ARRAY_C_CONTIGUOUS,NPY_ARRAY_ALIGNED, andNPY_ARRAY_F_CONTIGUOUS array flags can be “calculated” from thearray object itself. This routine updates one or more of theseflags ofarr as specified inflagmask by performing therequired calculation.
Warning
It is important to keep the flags updated (usingPyArray_UpdateFlags can help) whenever a manipulation with anarray is performed that might cause them to change. Latercalculations in NumPy that rely on the state of these flags do notrepeat the calculation to update them.
PyArray_GetField(PyArrayObject* self,PyArray_Descr* dtype, int offset)¶Equivalent tondarray.getfield (self,dtype,offset). Returna new array of the givendtype using the data in the currentarray at a specifiedoffset in bytes. Theoffset plus theitemsize of the new array type must be less thanself->descr->elsize or an error is raised. The same shape and stridesas the original array are used. Therefore, this function has theeffect of returning a field from a structured array. But, it can alsobe used to select specific bytes or groups of bytes from any arraytype.
PyArray_SetField(PyArrayObject* self,PyArray_Descr* dtype, int offset,PyObject* val)¶Equivalent tondarray.setfield (self,val,dtype,offset). Set the field starting atoffset in bytes and of the givendtype toval. Theoffset plusdtype ->elsize must be lessthanself ->descr->elsize or an error is raised. Otherwise, theval argument is converted to an array and copied into the fieldpointed to. If necessary, the elements ofval are repeated tofill the destination array, But, the number of elements in thedestination must be an integer multiple of the number of elementsinval.
PyArray_Byteswap(PyArrayObject* self, Bool inplace)¶Equivalent tondarray.byteswap (self,inplace). Return an arraywhose data area is byteswapped. Ifinplace is non-zero, then dothe byteswap inplace and return a reference to self. Otherwise,create a byteswapped copy and leave self unchanged.
PyArray_NewCopy(PyArrayObject* old,NPY_ORDER order)¶Equivalent tondarray.copy (self,fortran). Make a copy of theold array. The returned array is always aligned and writeablewith data interpreted the same as the old array. Iforder isNPY_CORDER, then a C-style contiguous array is returned. Iforder isNPY_FORTRANORDER, then a Fortran-style contiguousarray is returned. Iforder isNPY_ANYORDER, then the arrayreturned is Fortran-style contiguous only if the old one is;otherwise, it is C-style contiguous.
PyArray_ToList(PyArrayObject* self)¶Equivalent tondarray.tolist (self). Return a nested Python listfromself.
PyArray_ToString(PyArrayObject* self,NPY_ORDER order)¶Equivalent tondarray.tobytes (self,order). Return the bytesof this array in a Python string.
PyArray_ToFile(PyArrayObject* self, FILE* fp, char* sep, char* format)¶Write the contents ofself to the file pointerfp in C-stylecontiguous fashion. Write the data as binary bytes ifsep is thestring “”orNULL. Otherwise, write the contents ofself astext using thesep string as the item separator. Each item willbe printed to the file. If theformat string is notNULL or“”, then it is a Python print statement format string showing howthe items are to be written.
PyArray_Dump(PyObject* self,PyObject* file, int protocol)¶Pickle the object inself to the givenfile (either a stringor a Python file object). Iffile is a Python string it isconsidered to be the name of a file which is then opened in binarymode. The givenprotocol is used (ifprotocol is negative, orthe highest available is used). This is a simple wrapper aroundcPickle.dump(self,file,protocol).
PyArray_Dumps(PyObject* self, int protocol)¶Pickle the object inself to a Python string and return it. Usethe Pickleprotocol provided (or the highest available ifprotocol is negative).
PyArray_FillWithScalar(PyArrayObject* arr,PyObject* obj)¶Fill the array,arr, with the given scalar object,obj. Theobject is first converted to the data type ofarr, and thencopied into every location. A -1 is returned if an error occurs,otherwise 0 is returned.
PyArray_View(PyArrayObject* self,PyArray_Descr* dtype,PyTypeObject *ptype)¶Equivalent tondarray.view (self,dtype). Return a newview of the arrayself as possibly a different data-type,dtype,and different array subclassptype.
Ifdtype isNULL, then the returned array will have the samedata type asself. The new data-type must be consistent with thesize ofself. Either the itemsizes must be identical, orself mustbe single-segment and the total number of bytes must be the same.In the latter case the dimensions of the returned array will bealtered in the last (or first for Fortran-style contiguous arrays)dimension. The data area of the returned array and self is exactlythe same.
PyArray_Newshape(PyArrayObject* self,PyArray_Dims* newshape,NPY_ORDER order)¶Result will be a new array (pointing to the same memory locationasself if possible), but having a shape given bynewshape.If the new shape is not compatible with the strides ofself,then a copy of the array with the new specified shape will bereturned.
PyArray_Reshape(PyArrayObject* self,PyObject* shape)¶Equivalent tondarray.reshape (self,shape) whereshape is asequence. Convertsshape to aPyArray_Dims structure andcallsPyArray_Newshape internally.For back-ward compatibility – Not recommended
PyArray_Squeeze(PyArrayObject* self)¶Equivalent tondarray.squeeze (self). Return a new view ofselfwith all of the dimensions of length 1 removed from the shape.
Warning
matrix objects are always 2-dimensional. Therefore,PyArray_Squeeze has no effect on arrays of matrix sub-class.
PyArray_SwapAxes(PyArrayObject* self, int a1, int a2)¶Equivalent tondarray.swapaxes (self,a1,a2). The returnedarray is a new view of the data inself with the given axes,a1 anda2, swapped.
PyArray_Resize(PyArrayObject* self,PyArray_Dims* newshape, int refcheck,NPY_ORDER fortran)¶Equivalent tondarray.resize (self,newshape, refcheck=refcheck, order= fortran ). This function only works onsingle-segment arrays. It changes the shape ofself inplace andwill reallocate the memory forself ifnewshape has adifferent total number of elements then the old shape. Ifreallocation is necessary, thenself must own its data, haveself ->base==NULL, haveself ->weakrefs==NULL, and(unless refcheck is 0) not be referenced by any other array.The fortran argument can beNPY_ANYORDER,NPY_CORDER,orNPY_FORTRANORDER. It currently has no effect. Eventuallyit could be used to determine how the resize operation should viewthe data when constructing a differently-dimensioned array.Returns None on success and NULL on error.
PyArray_Transpose(PyArrayObject* self,PyArray_Dims* permute)¶Equivalent tondarray.transpose (self,permute). Permute theaxes of the ndarray objectself according to the data structurepermute and return the result. Ifpermute isNULL, thenthe resulting array has its axes reversed. For example ifselfhas shape10\times20\times30, andpermute.ptr is(0,2,1) the shape of the result is10\times30\times20. Ifpermute isNULL, the shape of the result is30\times20\times10.
PyArray_Flatten(PyArrayObject* self,NPY_ORDER order)¶Equivalent tondarray.flatten (self,order). Return a 1-d copyof the array. Iforder isNPY_FORTRANORDER the elements arescanned out in Fortran order (first-dimension varies thefastest). Iforder isNPY_CORDER, the elements ofselfare scanned in C-order (last dimension varies the fastest). IforderNPY_ANYORDER, then the result ofPyArray_ISFORTRAN (self) is used to determine which orderto flatten.
PyArray_Ravel(PyArrayObject* self,NPY_ORDER order)¶Equivalent toself.ravel(order). Same basic functionalityasPyArray_Flatten (self,order) except iforder is 0andself is C-style contiguous, the shape is altered but no copyis performed.
PyArray_TakeFrom(PyArrayObject* self,PyObject* indices, int axis,PyArrayObject* ret,NPY_CLIPMODE clipmode)¶Equivalent tondarray.take (self,indices,axis,ret,clipmode) exceptaxis =None in Python is obtained by settingaxis =NPY_MAXDIMS in C. Extract the items from selfindicated by the integer-valuedindices along the givenaxis.The clipmode argument can beNPY_RAISE,NPY_WRAP, orNPY_CLIP to indicate what to do with out-of-bound indices. Theret argument can specify an output array rather than having onecreated internally.
PyArray_PutTo(PyArrayObject* self,PyObject* values,PyObject* indices,NPY_CLIPMODE clipmode)¶Equivalent toself.put(values,indices,clipmode). Putvalues intoself at the corresponding (flattened)indices. Ifvalues is too small it will be repeated asnecessary.
PyArray_PutMask(PyArrayObject* self,PyObject* values,PyObject* mask)¶Place thevalues inself wherever corresponding positions(using a flattened context) inmask are true. Themask andself arrays must have the same total number of elements. Ifvalues is too small, it will be repeated as necessary.
PyArray_Repeat(PyArrayObject* self,PyObject* op, int axis)¶Equivalent tondarray.repeat (self,op,axis). Copy theelements ofself,op times along the givenaxis. Eitherop is a scalar integer or a sequence of lengthself->dimensions[axis ] indicating how many times to repeat eachitem along the axis.
PyArray_Choose(PyArrayObject* self,PyObject* op,PyArrayObject* ret,NPY_CLIPMODE clipmode)¶Equivalent tondarray.choose (self,op,ret,clipmode).Create a new array by selecting elements from the sequence ofarrays inop based on the integer values inself. The arraysmust all be broadcastable to the same shape and the entries inself should be between 0 and len(op). The output is placedinret unless it isNULL in which case a new output iscreated. Theclipmode argument determines behavior for whenentries inself are not between 0 and len(op).
NPY_RAISE¶raise a ValueError;
NPY_WRAP¶wrap values < 0 by adding len(op) and values >=len(op)by subtracting len(op) until they are in range;
NPY_CLIP¶all values are clipped to the region [0, len(op) ).
PyArray_Sort(PyArrayObject* self, int axis)¶Equivalent tondarray.sort (self,axis). Return an array withthe items ofself sorted alongaxis.
PyArray_ArgSort(PyArrayObject* self, int axis)¶Equivalent tondarray.argsort (self,axis). Return an array ofindices such that selection of these indices along the givenaxis would return a sorted version ofself. Ifself->descr is a data-type with fields defined, thenself->descr->names is used to determine the sort order. Acomparison where the first field is equal will use the secondfield and so on. To alter the sort order of a structured array, createa new data-type with a different order of names and construct aview of the array with that new data-type.
PyArray_LexSort(PyObject* sort_keys, int axis)¶Given a sequence of arrays (sort_keys) of the same shape,return an array of indices (similar toPyArray_ArgSort (…))that would sort the arrays lexicographically. A lexicographic sortspecifies that when two keys are found to be equal, the order isbased on comparison of subsequent keys. A merge sort (which leavesequal entries unmoved) is required to be defined for thetypes. The sort is accomplished by sorting the indices first usingthe firstsort_key and then using the secondsort_key and soforth. This is equivalent to the lexsort(sort_keys,axis)Python command. Because of the way the merge-sort works, be sureto understand the order thesort_keys must be in (reversed fromthe order you would use when comparing two elements).
If these arrays are all collected in a structured array, thenPyArray_Sort (…) can also be used to sort the arraydirectly.
PyArray_SearchSorted(PyArrayObject* self,PyObject* values, NPY_SEARCHSIDE side,PyObject* perm)¶Equivalent tondarray.searchsorted (self,values,side,perm). Assumingself is a 1-d array in ascending order, then theoutput is an array of indices the same shape asvalues such that, ifthe elements invalues were inserted before the indices, the order ofself would be preserved. No checking is done on whether or not self isin ascending order.
Theside argument indicates whether the index returned should be that ofthe first suitable location (ifNPY_SEARCHLEFT) or of the last(ifNPY_SEARCHRIGHT).
Thesorter argument, if notNULL, must be a 1D array of integerindices the same length asself, that sorts it into ascending order.This is typically the result of a call toPyArray_ArgSort (…)Binary search is used to find the required insertion points.
PyArray_Partition(PyArrayObject *self,PyArrayObject * ktharray, int axis, NPY_SELECTKIND which)¶Equivalent tondarray.partition (self,ktharray,axis,kind). Partitions the array so that the values of the element indexed byktharray are in the positions they would be if the array is fully sortedand places all elements smaller than the kth before and all elements equalor greater after the kth element. The ordering of all elements within thepartitions is undefined.Ifself->descr is a data-type with fields defined, thenself->descr->names is used to determine the sort order. A comparison wherethe first field is equal will use the second field and so on. To alter thesort order of a structured array, create a new data-type with a differentorder of names and construct a view of the array with that new data-type.Returns zero on success and -1 on failure.
PyArray_ArgPartition(PyArrayObject *op,PyArrayObject * ktharray, int axis, NPY_SELECTKIND which)¶Equivalent tondarray.argpartition (self,ktharray,axis,kind). Return an array of indices such that selection of these indicesalong the givenaxis would return a partitioned version ofself.
PyArray_Diagonal(PyArrayObject* self, int offset, int axis1, int axis2)¶Equivalent tondarray.diagonal (self,offset,axis1,axis2). Return theoffset diagonals of the 2-d arrays defined byaxis1 andaxis2.
PyArray_CountNonzero(PyArrayObject* self)¶New in version 1.6.
Counts the number of non-zero elements in the array objectself.
PyArray_Nonzero(PyArrayObject* self)¶Equivalent tondarray.nonzero (self). Returns a tuple of indexarrays that select elements ofself that are nonzero. If (nd=PyArray_NDIM (self ))==1, then a single index array isreturned. The index arrays have data typeNPY_INTP. If atuple is returned (nd\neq 1), then its length is nd.
PyArray_Compress(PyArrayObject* self,PyObject* condition, int axis,PyArrayObject* out)¶Equivalent tondarray.compress (self,condition,axis). Return the elements alongaxis corresponding to elements ofcondition that are true.
Tip
Pass inNPY_MAXDIMS for axis in order to achieve the sameeffect that is obtained by passing inaxis =None in Python(treating the array as a 1-d array).
PyArray_ArgMax(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.argmax (self,axis). Return the index ofthe largest element ofself alongaxis.
PyArray_ArgMin(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.argmin (self,axis). Return the index ofthe smallest element ofself alongaxis.
Note
The out argument specifies where to place the result. If out isNULL, then the output array is created, otherwise the output isplaced in out which must be the correct size and type. A newreference to the output array is always returned even when outis not NULL. The caller of the routine has the responsibilitytoDECREF out if not NULL or a memory-leak will occur.
PyArray_Max(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.max (self,axis). Returns the largestelement ofself along the givenaxis. When the result is a singleelement, returns a numpy scalar instead of an ndarray.
PyArray_Min(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.min (self,axis). Return the smallestelement ofself along the givenaxis. When the result is a singleelement, returns a numpy scalar instead of an ndarray.
PyArray_Ptp(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.ptp (self,axis). Return the differencebetween the largest element ofself alongaxis and thesmallest element ofself alongaxis. When the result is a singleelement, returns a numpy scalar instead of an ndarray.
Note
The rtype argument specifies the data-type the reduction shouldtake place over. This is important if the data-type of the arrayis not “large” enough to handle the output. By default, allinteger data-types are made at least as large asNPY_LONGfor the “add” and “multiply” ufuncs (which form the basis formean, sum, cumsum, prod, and cumprod functions).
PyArray_Mean(PyArrayObject* self, int axis, int rtype,PyArrayObject* out)¶Equivalent tondarray.mean (self,axis,rtype). Returns themean of the elements along the givenaxis, using the enumeratedtypertype as the data type to sum in. Default sum behavior isobtained usingNPY_NOTYPE forrtype.
PyArray_Trace(PyArrayObject* self, int offset, int axis1, int axis2, int rtype,PyArrayObject* out)¶Equivalent tondarray.trace (self,offset,axis1,axis2,rtype). Return the sum (usingrtype as the data type ofsummation) over theoffset diagonal elements of the 2-d arraysdefined byaxis1 andaxis2 variables. A positive offsetchooses diagonals above the main diagonal. A negative offsetselects diagonals below the main diagonal.
PyArray_Clip(PyArrayObject* self,PyObject* min,PyObject* max)¶Equivalent tondarray.clip (self,min,max). Clip an array,self, so that values larger thanmax are fixed tomax andvalues less thanmin are fixed tomin.
PyArray_Conjugate(PyArrayObject* self)¶Equivalent tondarray.conjugate (self).Return the complex conjugate ofself. Ifself is not ofcomplex data type, then returnself with a reference.
PyArray_Round(PyArrayObject* self, int decimals,PyArrayObject* out)¶Equivalent tondarray.round (self,decimals,out). Returnsthe array with elements rounded to the nearest decimal place. Thedecimal place is defined as the10^{-\textrm{decimals}}digit so that negativedecimals cause rounding to the nearest 10’s, 100’s, etc. If out isNULL, then the output array is created, otherwise the output is placed inout which must be the correct size and type.
PyArray_Std(PyArrayObject* self, int axis, int rtype,PyArrayObject* out)¶Equivalent tondarray.std (self,axis,rtype). Return thestandard deviation using data alongaxis converted to data typertype.
PyArray_Sum(PyArrayObject* self, int axis, int rtype,PyArrayObject* out)¶Equivalent tondarray.sum (self,axis,rtype). Return 1-dvector sums of elements inself alongaxis. Perform the sumafter converting data to data typertype.
PyArray_CumSum(PyArrayObject* self, int axis, int rtype,PyArrayObject* out)¶Equivalent tondarray.cumsum (self,axis,rtype). Returncumulative 1-d sums of elements inself alongaxis. Performthe sum after converting data to data typertype.
PyArray_Prod(PyArrayObject* self, int axis, int rtype,PyArrayObject* out)¶Equivalent tondarray.prod (self,axis,rtype). Return 1-dproducts of elements inself alongaxis. Perform the productafter converting data to data typertype.
PyArray_CumProd(PyArrayObject* self, int axis, int rtype,PyArrayObject* out)¶Equivalent tondarray.cumprod (self,axis,rtype). Return1-d cumulative products of elements inself alongaxis.Perform the product after converting data to data typertype.
PyArray_All(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.all (self,axis). Return an array withTrue elements for every 1-d sub-array ofself defined byaxis in which all the elements are True.
PyArray_Any(PyArrayObject* self, int axis,PyArrayObject* out)¶Equivalent tondarray.any (self,axis). Return an array withTrue elements for every 1-d sub-array ofself defined byaxisin which any of the elements are True.
PyArray_AsCArray(PyObject** op, void* ptr, npy_intp* dims, int nd, int typenum, int itemsize)¶Sometimes it is useful to access a multidimensional array as aC-style multi-dimensional array so that algorithms can beimplemented using C’s a[i][j][k] syntax. This routine returns apointer,ptr, that simulates this kind of C-style array, for1-, 2-, and 3-d ndarrays.
| Parameters: |
|
|---|
Note
The simulation of a C-style array is not complete for 2-d and 3-darrays. For example, the simulated arrays of pointers cannot be passedto subroutines expecting specific, statically-defined 2-d and 3-darrays. To pass to functions requiring those kind of inputs, you muststatically define the required array and copy data.
PyArray_Free(PyObject* op, void* ptr)¶Must be called with the same objects and memory locations returnedfromPyArray_AsCArray (…). This function cleans up memorythat otherwise would get leaked.
PyArray_Concatenate(PyObject* obj, int axis)¶Join the sequence of objects inobj together alongaxis into asingle array. If the dimensions or types are not compatible anerror is raised.
PyArray_InnerProduct(PyObject* obj1,PyObject* obj2)¶Compute a product-sum over the last dimensions ofobj1 andobj2. Neither array is conjugated.
PyArray_MatrixProduct(PyObject* obj1,PyObject* obj)¶Compute a product-sum over the last dimension ofobj1 and thesecond-to-last dimension ofobj2. For 2-d arrays this is amatrix-product. Neither array is conjugated.
PyArray_MatrixProduct2(PyObject* obj1,PyObject* obj,PyArrayObject* out)¶New in version 1.6.
Same as PyArray_MatrixProduct, but store the result inout. Theoutput array must have the correct shape, type, and beC-contiguous, or an exception is raised.
PyArray_EinsteinSum(char* subscripts, npy_intp nop,PyArrayObject** op_in,PyArray_Descr* dtype,NPY_ORDER order,NPY_CASTING casting,PyArrayObject* out)¶New in version 1.6.
Applies the Einstein summation convention to the array operandsprovided, returning a new array or placing the result inout.The string insubscripts is a comma separated list of indexletters. The number of operands is innop, andop_in is anarray containing those operands. The data type of the output canbe forced withdtype, the output order can be forced withorder(NPY_KEEPORDER is recommended), and whendtype is specified,casting indicates how permissive the data conversion should be.
See theeinsum function for more details.
PyArray_CopyAndTranspose(PyObject * op)¶A specialized copy and transpose function that works only for 2-darrays. The returned array is a transposed copy ofop.
PyArray_Correlate(PyObject* op1,PyObject* op2, int mode)¶Compute the 1-d correlation of the 1-d arraysop1 andop2. The correlation is computed at each output point by multiplyingop1 by a shifted version ofop2 and summing the result. As aresult of the shift, needed values outside of the defined range ofop1 andop2 are interpreted as zero. The mode determines howmany shifts to return: 0 - return only shifts that did not need toassume zero- values; 1 - return an object that is the same size asop1, 2 - return all possible shifts (any overlap at all isaccepted).
Notes
This does not compute the usual correlation: if op2 is larger than op1, thearguments are swapped, and the conjugate is never taken for complex arrays.See PyArray_Correlate2 for the usual signal processing correlation.
PyArray_Correlate2(PyObject* op1,PyObject* op2, int mode)¶Updated version of PyArray_Correlate, which uses the usual definition ofcorrelation for 1d arrays. The correlation is computed at each output pointby multiplyingop1 by a shifted version ofop2 and summing the result.As a result of the shift, needed values outside of the defined range ofop1 andop2 are interpreted as zero. The mode determines how manyshifts to return: 0 - return only shifts that did not need to assume zero-values; 1 - return an object that is the same size asop1, 2 - return allpossible shifts (any overlap at all is accepted).
Notes
Compute z as follows:
z[k]=sum_nop1[n]*conj(op2[n+k])
PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp* dims, npy_intp* newstrides)¶Determine ifnewstrides is a strides array consistent with thememory of annd -dimensional array with shapedims andelement-size,elsize. Thenewstrides array is checked to seeif jumping by the provided number of bytes in each direction willever mean jumping more thannumbytes which is the assumed sizeof the available memory segment. Ifnumbytes is 0, then anequivalentnumbytes is computed assumingnd,dims, andelsize refer to a single-segment array. ReturnNPY_TRUE ifnewstrides is acceptable, otherwise returnNPY_FALSE.
PyArray_MultiplyList(npy_intp* seq, int n)¶PyArray_MultiplyIntList(int* seq, int n)¶Both of these routines multiply ann -length array,seq, ofintegers and return the result. No overflow checking is performed.
PyArray_CompareLists(npy_intp* l1, npy_intp* l2, int n)¶Given twon -length arrays of integers,l1, andl2, return1 if the lists are identical; otherwise, return 0.
New in version 1.7.0.
NpyAuxData¶When working with more complex dtypes which are composed of other dtypes,such as the struct dtype, creating inner loops that manipulate the dtypesrequires carrying along additional data. NumPy supports this ideathrough a structNpyAuxData, mandating a few conventions so thatit is possible to do this.
Defining anNpyAuxData is similar to defining a class in C++,but the object semantics have to be tracked manually since the API is in C.Here’s an example for a function which doubles up an element usingan element copier function as a primitive.:
typedefstruct{NpyAuxDatabase;ElementCopier_Func*func;NpyAuxData*funcdata;}eldoubler_aux_data;voidfree_element_doubler_aux_data(NpyAuxData*data){eldoubler_aux_data*d=(eldoubler_aux_data*)data;/*Freethememoryownedbythisauxdata*/NPY_AUXDATA_FREE(d->funcdata);PyArray_free(d);}NpyAuxData*clone_element_doubler_aux_data(NpyAuxData*data){eldoubler_aux_data*ret=PyArray_malloc(sizeof(eldoubler_aux_data));if(ret==NULL){returnNULL;}/*Rawcopyofalldata*/memcpy(ret,data,sizeof(eldoubler_aux_data));/*Fixuptheownedauxdatasowehaveourowncopy*/ret->funcdata=NPY_AUXDATA_CLONE(ret->funcdata);if(ret->funcdata==NULL){PyArray_free(ret);returnNULL;}return(NpyAuxData*)ret;}NpyAuxData*create_element_doubler_aux_data(ElementCopier_Func*func,NpyAuxData*funcdata){eldoubler_aux_data*ret=PyArray_malloc(sizeof(eldoubler_aux_data));if(ret==NULL){PyErr_NoMemory();returnNULL;}memset(&ret,0,sizeof(eldoubler_aux_data));ret->base->free=&free_element_doubler_aux_data;ret->base->clone=&clone_element_doubler_aux_data;ret->func=func;ret->funcdata=funcdata;return(NpyAuxData*)ret;}
NpyAuxData_FreeFunc¶The function pointer type for NpyAuxData free functions.
NpyAuxData_CloneFunc¶The function pointer type for NpyAuxData clone functions. Thesefunctions should never set the Python exception on error, becausethey may be called from a multi-threaded context.
NPY_AUXDATA_FREE(auxdata)¶A macro which calls the auxdata’s free function appropriately,does nothing if auxdata is NULL.
NPY_AUXDATA_CLONE(auxdata)¶A macro which calls the auxdata’s clone function appropriately,returning a deep copy of the auxiliary data.
As of NumPy 1.6.0, these array iterators are superceded bythe new array iterator,NpyIter.
An array iterator is a simple way to access the elements of anN-dimensional array quickly and efficiently. Section2 provides more description and examples ofthis useful approach to looping over an array.
PyArray_IterNew(PyObject* arr)¶Return an array iterator object from the array,arr. This isequivalent toarr.flat. The array iterator object makesit easy to loop over an N-dimensional non-contiguous array inC-style contiguous fashion.
PyArray_IterAllButAxis(PyObject* arr, int *axis)¶Return an array iterator that will iterate over all axes but theone provided in*axis. The returned iterator cannot be usedwithPyArray_ITER_GOTO1D. This iterator could be used towrite something similar to what ufuncs do wherein the loop overthe largest axis is done by a separate sub-routine. If*axis isnegative then*axis will be set to the axis having the smalleststride and that axis will be used.
PyArray_BroadcastToShape(PyObject* arr, npy_intp *dimensions, int nd)¶Return an array iterator that is broadcast to iterate as an arrayof the shape provided bydimensions andnd.
PyArrayIter_Check(PyObject* op)¶Evaluates true ifop is an array iterator (or instance of asubclass of the array iterator type).
PyArray_ITER_NEXT(PyObject* iterator)¶Incremement the index and the dataptr members of theiterator topoint to the next element of the array. If the array is not(C-style) contiguous, also increment the N-dimensional coordinatesarray.
PyArray_ITER_GOTO(PyObject* iterator, npy_intp* destination)¶Set theiterator index, dataptr, and coordinates members to thelocation in the array indicated by the N-dimensional c-array,destination, which must have size at leastiterator->nd_m1+1.
PyArray_MultiIterNew(int num, ...)¶A simplified interface to broadcasting. This function takes thenumber of arrays to broadcast and thennum extra (PyObject*) arguments. These arguments are converted to arrays and iteratorsare created.PyArray_Broadcast is then called on the resultingmulti-iterator object. The resulting, broadcasted mult-iteratorobject is then returned. A broadcasted operation can then beperformed using a single loop and usingPyArray_MultiIter_NEXT(..)
PyArray_MultiIter_RESET(PyObject* multi)¶Reset all the iterators to the beginning in a multi-iteratorobject,multi.
PyArray_MultiIter_NEXT(PyObject* multi)¶Advance each iterator in a multi-iterator object,multi, to itsnext (broadcasted) element.
PyArray_MultiIter_DATA(PyObject* multi, int i)¶Return the data-pointer of thei^{\textrm{th}} iteratorin a multi-iterator object.
PyArray_MultiIter_NEXTi(PyObject* multi, int i)¶Advance the pointer of only thei^{\textrm{th}} iterator.
PyArray_MultiIter_GOTO(PyObject* multi, npy_intp* destination)¶Advance each iterator in a multi-iterator object,multi, to thegivenN -dimensionaldestination whereN is thenumber of dimensions in the broadcasted array.
PyArray_MultiIter_GOTO1D(PyObject* multi, npy_intp index)¶Advance each iterator in a multi-iterator object,multi, to thecorresponding location of theindex into the flattenedbroadcasted array.
PyArray_MultiIter_NOTDONE(PyObject* multi)¶Evaluates TRUE as long as the multi-iterator has not loopedthrough all of the elements (of the broadcasted result), otherwiseit evaluates FALSE.
PyArray_Broadcast(PyArrayMultiIterObject* mit)¶This function encapsulates the broadcasting rules. Themitcontainer should already contain iterators for all the arrays thatneed to be broadcast. On return, these iterators will be adjustedso that iteration over each simultaneously will accomplish thebroadcasting. A negative number is returned if an error occurs.
PyArray_RemoveSmallest(PyArrayMultiIterObject* mit)¶This function takes a multi-iterator object that has beenpreviously “broadcasted,” finds the dimension with the smallest“sum of strides” in the broadcasted result and adapts all theiterators so as not to iterate over that dimension (by effectivelymaking them of length-1 in that dimension). The correspondingdimension is returned unlessmit ->nd is 0, then -1 isreturned. This function is useful for constructing ufunc-likeroutines that broadcast their inputs correctly and then call astrided 1-d version of the routine as the inner-loop. This 1-dversion is usually optimized for speed and for this reason theloop should be performed over the axis that won’t require largestride jumps.
New in version 1.4.0.
Neighborhood iterators are subclasses of the iterator object, and can be usedto iter over a neighborhood of a point. For example, you may want to iterateover every voxel of a 3d image, and for every such voxel, iterate over anhypercube. Neighborhood iterator automatically handle boundaries, thus makingthis kind of code much easier to write than manual boundaries handling, at thecost of a slight overhead.
PyArray_NeighborhoodIterNew(PyArrayIterObject* iter, npy_intp bounds, int mode,PyArrayObject* fill_value)¶This function creates a new neighborhood iterator from an existingiterator. The neighborhood will be computed relatively to the positioncurrently pointed byiter, the bounds define the shape of theneighborhood iterator, and the mode argument the boundaries handling mode.
Thebounds argument is expected to be a (2 * iter->ao->nd) arrays, suchas the range bound[2*i]->bounds[2*i+1] defines the range where to walk fordimension i (both bounds are included in the walked coordinates). Thebounds should be ordered for each dimension (bounds[2*i] <= bounds[2*i+1]).
The mode should be one of:
If the mode is constant filling (NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING),fill_value should point to an array object which holds the filling value(the first item will be the filling value if the array contains more thanone item). For other cases, fill_value may be NULL.
PyArrayIterObject \*iter;PyArrayNeighborhoodIterObject \*neigh_iter;iter = PyArray_IterNew(x);//For a 3x3 kernelbounds = {-1, 1, -1, 1};neigh_iter = (PyArrayNeighborhoodIterObject*)PyArrayNeighborhoodIter_New( iter, bounds, NPY_NEIGHBORHOOD_ITER_ZERO_PADDING, NULL);for(i = 0; i < iter->size; ++i) { for (j = 0; j < neigh_iter->size; ++j) { // Walk around the item currently pointed by iter->dataptr PyArrayNeighborhoodIter_Next(neigh_iter); } // Move to the next point of iter PyArrayIter_Next(iter); PyArrayNeighborhoodIter_Reset(neigh_iter);}PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject* iter)¶Reset the iterator position to the first point of the neighborhood. Thisshould be called whenever the iter argument given atPyArray_NeighborhoodIterObject is changed (see example)
PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject* iter)¶After this call, iter->dataptr points to the next point of theneighborhood. Calling this function after every point of theneighborhood has been visited is undefined.
PyArray_Return(PyArrayObject* arr)¶This function steals a reference toarr.
This function checks to see ifarr is a 0-dimensional array and,if so, returns the appropriate array scalar. It should be usedwhenever 0-dimensional arrays could be returned to Python.
PyArray_Scalar(void* data,PyArray_Descr* dtype,PyObject* itemsize)¶Return an array scalar object of the given enumeratedtypenumanditemsize bycopying from memory pointed to bydata. Ifswap is nonzero then this function will byteswap the dataif appropriate to the data-type because array scalars are alwaysin correct machine-byte order.
PyArray_ToScalar(void* data,PyArrayObject* arr)¶Return an array scalar object of the type and itemsize indicatedby the array objectarr copied from the memory pointed to bydata and swapping if the data inarr is not in machinebyte-order.
PyArray_FromScalar(PyObject* scalar,PyArray_Descr* outcode)¶Return a 0-dimensional array of type determined byoutcode fromscalar which should be an array-scalar object. Ifoutcode isNULL, then the type is determined fromscalar.
PyArray_ScalarAsCtype(PyObject* scalar, void* ctypeptr)¶Return inctypeptr a pointer to the actual value in an arrayscalar. There is no error checking soscalar must be anarray-scalar object, and ctypeptr must have enough space to holdthe correct type. For flexible-sized types, a pointer to the datais copied into the memory ofctypeptr, for all other types, theactual data is copied into the address pointed to byctypeptr.
PyArray_CastScalarToCtype(PyObject* scalar, void* ctypeptr,PyArray_Descr* outcode)¶Return the data (cast to the data type indicated byoutcode)from the array-scalar,scalar, into the memory pointed to byctypeptr (which must be large enough to handle the incomingmemory).
PyArray_TypeObjectFromType(int type)¶Returns a scalar type-object from a type-number,type. Equivalent toPyArray_DescrFromType (type)->typeobjexcept for reference counting and error-checking. Returns a newreference to the typeobject on success orNULL on failure.
PyArray_ScalarKind(int typenum,PyArrayObject** arr)¶See the functionPyArray_MinScalarType for an alternativemechanism introduced in NumPy 1.6.0.
Return the kind of scalar represented bytypenum and the arrayin*arr (ifarr is notNULL ). The array is assumed to berank-0 and only used iftypenum represents a signed integer. Ifarr is notNULL and the first element is negative thenNPY_INTNEG_SCALAR is returned, otherwiseNPY_INTPOS_SCALAR is returned. The possible return valuesareNPY_{kind}_SCALAR where{kind} can beINTPOS,INTNEG,FLOAT,COMPLEX,BOOL, orOBJECT.NPY_NOSCALAR is also an enumerated valueNPY_SCALARKIND variables can take on.
PyArray_CanCoerceScalar(char thistype, char neededtype,NPY_SCALARKIND scalar)¶See the functionPyArray_ResultType for details ofNumPy type promotion, updated in NumPy 1.6.0.
Implements the rules for scalar coercion. Scalars are onlysilently coerced from thistype to neededtype if this functionreturns nonzero. If scalar isNPY_NOSCALAR, then thisfunction is equivalent toPyArray_CanCastSafely. The rule isthat scalars of the same KIND can be coerced into arrays of thesame KIND. This rule means that high-precision scalars will nevercause low-precision arrays of the same KIND to be upcast.
Warning
Data-type objects must be reference counted so be aware of theaction on the data-type reference of different C-API calls. Thestandard rule is that when a data-type object is returned it is anew reference. Functions that takePyArray_Descr* objects andreturn arrays steal references to the data-type their inputsunless otherwise noted. Therefore, you must own a reference to anydata-type object used as input to such a function.
PyArray_DescrCheck(PyObject* obj)¶Evaluates as true ifobj is a data-type object (PyArray_Descr* ).
PyArray_DescrNew(PyArray_Descr* obj)¶Return a new data-type object copied fromobj (the fieldsreference is just updated so that the new object points to thesame fields dictionary if any).
PyArray_DescrNewFromType(int typenum)¶Create a new data-type object from the built-in (oruser-registered) data-type indicated bytypenum. All builtintypes should not have any of their fields changed. This creates anew copy of thePyArray_Descr structure so that you can fillit in as appropriate. This function is especially needed forflexible data-types which need to have a new elsize member inorder to be meaningful in array construction.
PyArray_DescrNewByteorder(PyArray_Descr* obj, char newendian)¶Create a new data-type object with the byteorder set according tonewendian. All referenced data-type objects (in subdescr andfields members of the data-type object) are also changed(recursively). If a byteorder ofNPY_IGNORE is encountered itis left alone. If newendian isNPY_SWAP, then all byte-ordersare swapped. Other valid newendian values areNPY_NATIVE,NPY_LITTLE, andNPY_BIG which all cause the returneddata-typed descriptor (and all it’sreferenced data-type descriptors) to have the corresponding byte-order.
PyArray_DescrFromObject(PyObject* op,PyArray_Descr* mintype)¶Determine an appropriate data-type object from the objectop(which should be a “nested” sequence object) and the minimumdata-type descriptor mintype (which can beNULL ). Similar inbehavior to array(op).dtype. Don’t confuse this function withPyArray_DescrConverter. This function essentially looks atall the objects in the (nested) sequence and determines thedata-type from the elements it finds.
PyArray_DescrFromScalar(PyObject* scalar)¶Return a data-type object from an array-scalar object. No checkingis done to be sure thatscalar is an array scalar. If nosuitable data-type can be determined, then a data-type ofNPY_OBJECT is returned by default.
PyArray_DescrFromType(int typenum)¶Returns a data-type object corresponding totypenum. Thetypenum can be one of the enumerated types, a character code forone of the enumerated types, or a user-defined type.
PyArray_DescrConverter(PyObject* obj,PyArray_Descr** dtype)¶Convert any compatible Python object,obj, to a data-type objectindtype. A large number of Python objects can be converted todata-type objects. SeeData type objects (dtype) for a completedescription. This version of the converter converts None objectsto aNPY_DEFAULT_TYPE data-type object. This function canbe used with the “O&” character code inPyArg_ParseTupleprocessing.
PyArray_DescrConverter2(PyObject* obj,PyArray_Descr** dtype)¶Convert any compatible Python object,obj, to a data-typeobject indtype. This version of the converter converts Noneobjects so that the returned data-type isNULL. This functioncan also be used with the “O&” character in PyArg_ParseTupleprocessing.
Pyarray_DescrAlignConverter(PyObject* obj,PyArray_Descr** dtype)¶LikePyArray_DescrConverter except it aligns C-struct-likeobjects on word-boundaries as the compiler would.
Pyarray_DescrAlignConverter2(PyObject* obj,PyArray_Descr** dtype)¶LikePyArray_DescrConverter2 except it aligns C-struct-likeobjects on word-boundaries as the compiler would.
PyArray_FieldNames(PyObject* dict)¶Take the fields dictionary,dict, such as the one attached to adata-type object and construct an ordered-list of field names suchas is stored in the names field of thePyArray_Descr object.
PyArg_ParseTuple¶All of these functions can be used inPyArg_ParseTuple (…) withthe “O&” format specifier to automatically convert any Python objectto the required C-object. All of these functions returnNPY_SUCCEED if successful andNPY_FAIL if not. The firstargument to all of these function is a Python object. The secondargument is theaddress of the C-type to convert the Python objectto.
Warning
Be sure to understand what steps you should take to manage thememory when using these conversion functions. These functions canrequire freeing memory, and/or altering the reference counts ofspecific objects based on your use.
PyArray_Converter(PyObject* obj,PyObject** address)¶Convert any Python object to aPyArrayObject. IfPyArray_Check (obj) is TRUE then its reference count isincremented and a reference placed inaddress. Ifobj is notan array, then convert it to an array usingPyArray_FromAny. No matter what is returned, you must DECREF the object returnedby this routine inaddress when you are done with it.
PyArray_OutputConverter(PyObject* obj,PyArrayObject** address)¶This is a default converter for output arrays given tofunctions. Ifobj isPy_None orNULL, then*addresswill beNULL but the call will succeed. IfPyArray_Check (obj) is TRUE then it is returned in*address withoutincrementing its reference count.
PyArray_IntpConverter(PyObject* obj,PyArray_Dims* seq)¶Convert any Python sequence,obj, smaller thanNPY_MAXDIMSto a C-array ofnpy_intp. The Python object could also be asingle number. Theseq variable is a pointer to a structure withmembers ptr and len. On successful return,seq ->ptr contains apointer to memory that must be freed, by callingPyDimMem_FREE,to avoid a memory leak. The restriction on memory size allows thisconverter to be conveniently used for sequences intended to beinterpreted as array shapes.
PyArray_BufferConverter(PyObject* obj,PyArray_Chunk* buf)¶Convert any Python object,obj, with a (single-segment) bufferinterface to a variable with members that detail the object’s useof its chunk of memory. Thebuf variable is a pointer to astructure with base, ptr, len, and flags members. ThePyArray_Chunk structure is binary compatible with thePython’s buffer object (through its len member on 32-bit platformsand its ptr member on 64-bit platforms or in Python 2.5). Onreturn, the base member is set toobj (or its base ifobj isalready a buffer object pointing to another object). If you needto hold on to the memory be sure to INCREF the base member. Thechunk of memory is pointed to bybuf ->ptr member and has lengthbuf ->len. The flags member ofbuf isNPY_BEHAVED_RO withtheNPY_ARRAY_WRITEABLE flag set ifobj has a writeable bufferinterface.
PyArray_AxisConverter(PyObject * obj, int* axis)¶Convert a Python object,obj, representing an axis argument tothe proper value for passing to the functions that take an integeraxis. Specifically, ifobj is None,axis is set toNPY_MAXDIMS which is interpreted correctly by the C-APIfunctions that take axis arguments.
PyArray_BoolConverter(PyObject* obj, Bool* value)¶Convert any Python object,obj, toNPY_TRUE orNPY_FALSE, and place the result invalue.
PyArray_ByteorderConverter(PyObject* obj, char* endian)¶Convert Python strings into the corresponding byte-ordercharacter:‘>’, ‘<’, ‘s’, ‘=’, or ‘|’.
PyArray_SortkindConverter(PyObject* obj,NPY_SORTKIND* sort)¶Convert Python strings into one ofNPY_QUICKSORT (startswith ‘q’ or ‘Q’) ,NPY_HEAPSORT (starts with ‘h’ or ‘H’),orNPY_MERGESORT (starts with ‘m’ or ‘M’).
PyArray_SearchsideConverter(PyObject* obj, NPY_SEARCHSIDE* side)¶Convert Python strings into one ofNPY_SEARCHLEFT (starts with ‘l’or ‘L’), orNPY_SEARCHRIGHT (starts with ‘r’ or ‘R’).
PyArray_OrderConverter(PyObject* obj,NPY_ORDER* order)¶Convert the Python strings ‘C’, ‘F’, ‘A’, and ‘K’ into theNPY_ORDERenumerationNPY_CORDER,NPY_FORTRANORDER,NPY_ANYORDER, andNPY_KEEPORDER.
PyArray_CastingConverter(PyObject* obj,NPY_CASTING* casting)¶Convert the Python strings ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, and‘unsafe’ into theNPY_CASTING enumerationNPY_NO_CASTING,NPY_EQUIV_CASTING,NPY_SAFE_CASTING,NPY_SAME_KIND_CASTING, andNPY_UNSAFE_CASTING.
PyArray_ClipmodeConverter(PyObject* object,NPY_CLIPMODE* val)¶Convert the Python strings ‘clip’, ‘wrap’, and ‘raise’ into theNPY_CLIPMODE enumerationNPY_CLIP,NPY_WRAP,andNPY_RAISE.
PyArray_ConvertClipmodeSequence(PyObject* object,NPY_CLIPMODE* modes, int n)¶Converts either a sequence of clipmodes or a single clipmode intoa C array ofNPY_CLIPMODE values. The number of clipmodesnmust be known before calling this function. This function is providedto help functions allow a different clipmode for each dimension.
PyArray_PyIntAsInt(PyObject* op)¶Convert all kinds of Python objects (including arrays and arrayscalars) to a standard integer. On error, -1 is returned and anexception set. You may find useful the macro:
#define error_converting(x) (((x) == -1) && PyErr_Occurred()PyArray_PyIntAsIntp(PyObject* op)¶Convert all kinds of Python objects (including arrays and arrayscalars) to a (platform-pointer-sized) integer. On error, -1 isreturned and an exception set.
PyArray_IntpFromSequence(PyObject* seq, npy_intp* vals, int maxvals)¶Convert any Python sequence (or single Python number) passed in asseq to (up to)maxvals pointer-sized integers and place themin thevals array. The sequence can be smaller thenmaxvals asthe number of converted objects is returned.
PyArray_TypestrConvert(int itemsize, int gentype)¶Convert typestring characters (withitemsize) to basicenumerated data types. The typestring character corresponding tosigned and unsigned integers, floating point numbers, andcomplex-floating point numbers are recognized and converted. Othervalues of gentype are returned. This function can be used toconvert, for example, the string ‘f4’ toNPY_FLOAT32.
In order to make use of the C-API from another extension module, theimport_array function must be called. If the extension module isself-contained in a single .c file, then that is all that needs to bedone. If, however, the extension module involves multiple files wherethe C-API is needed then some additional steps must be taken.
import_array(void)¶This function must be called in the initialization section of amodule that will make use of the C-API. It imports the modulewhere the function-pointer table is stored and points the correctvariable to it.
PY_ARRAY_UNIQUE_SYMBOL¶NO_IMPORT_ARRAY¶Using these #defines you can use the C-API in multiple files for asingle extension module. In each file you must definePY_ARRAY_UNIQUE_SYMBOL to some name that will hold theC-API (e.g. myextension_ARRAY_API). This must be donebeforeincluding the numpy/arrayobject.h file. In the moduleinitialization routine you callimport_array. In addition,in the files that do not have the module initializationsub_routine defineNO_IMPORT_ARRAY prior to includingnumpy/arrayobject.h.
Suppose I have two files coolmodule.c and coolhelper.c which needto be compiled and linked into a single extension module. Supposecoolmodule.c contains the required initcool module initializationfunction (with the import_array() function called). Then,coolmodule.c would have at the top:
#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API#includenumpy/arrayobject.h
On the other hand, coolhelper.c would contain at the top:
#define NO_IMPORT_ARRAY#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API#includenumpy/arrayobject.h
You can also put the common two last lines into an extension-localheader file as long as you make sure that NO_IMPORT_ARRAY is#defined before #including that file.
Internally, these #defines work as follows:
- If neither is defined, the C-API is declared to be
staticvoid**, so it is only visible within thecompilation unit that #includes numpy/arrayobject.h.- If
PY_ARRAY_UNIQUE_SYMBOLis #defined, butNO_IMPORT_ARRAYis not, the C-API is declared tobevoid**, so that it will also be visible to othercompilation units.- If
NO_IMPORT_ARRAYis #defined, regardless ofwhetherPY_ARRAY_UNIQUE_SYMBOLis, the C-API isdeclared to beexternvoid**, so it is expected tobe defined in another compilation unit.- Whenever
PY_ARRAY_UNIQUE_SYMBOLis #defined, italso changes the name of the variable holding the C-API, whichdefaults toPyArray_API, to whatever the macro is#defined to.
Because python extensions are not used in the same way as usual libraries onmost platforms, some errors cannot be automatically detected at build time oreven runtime. For example, if you build an extension using a function availableonly for numpy >= 1.3.0, and you import the extension later with numpy 1.2, youwill not get an import error (but almost certainly a segmentation fault whencalling the function). That’s why several functions are provided to check fornumpy versions. The macrosNPY_VERSION andNPY_FEATURE_VERSION corresponds to the numpy version used to build theextension, whereas the versions returned by the functionsPyArray_GetNDArrayCVersion and PyArray_GetNDArrayCFeatureVersion corresponds tothe runtime numpy’s version.
The rules for ABI and API compatibilities can be summarized as follows:
- Whenever
NPY_VERSION!= PyArray_GetNDArrayCVersion, theextension has to be recompiled (ABI incompatibility).NPY_VERSION== PyArray_GetNDArrayCVersion andNPY_FEATURE_VERSION<= PyArray_GetNDArrayCFeatureVersion meansbackward compatible changes.
ABI incompatibility is automatically detected in every numpy’s version. APIincompatibility detection was added in numpy 1.4.0. If you want to supportedmany different numpy versions with one extension binary, you have to build yourextension with the lowest NPY_FEATURE_VERSION as possible.
PyArray_GetNDArrayCVersion(void)¶This just returns the valueNPY_VERSION.NPY_VERSIONchanges whenever a backward incompatible change at the ABI level. Becauseit is in the C-API, however, comparing the output of this function from thevalue defined in the current header gives a way to test if the C-API haschanged thus requiring a re-compilation of extension modules that use theC-API. This is automatically checked in the functionimport_array.
PyArray_GetNDArrayCFeatureVersion(void)¶New in version 1.4.0.
This just returns the valueNPY_FEATURE_VERSION.NPY_FEATURE_VERSION changes whenever the API changes (e.g. afunction is added). A changed value does not always require a recompile.
PyArray_SetNumericOps(PyObject* dict)¶NumPy stores an internal table of Python callable objects that areused to implement arithmetic operations for arrays as well ascertain array calculation methods. This function allows the userto replace any or all of these Python objects with their ownversions. The keys of the dictionary,dict, are the namedfunctions to replace and the paired value is the Python callableobject to use. Care should be taken that the function used toreplace an internal array operation does not itself call back tothat internal array operation (unless you have designed thefunction to handle that), or an unchecked infinite recursion canresult (possibly causing program crash). The key names thatrepresent operations that can be replaced are:
add,subtract,multiply,divide,remainder,power,square,reciprocal,ones_like,sqrt,negative,positive,absolute,invert,left_shift,right_shift,bitwise_and,bitwise_xor,bitwise_or,less,less_equal,equal,not_equal,greater,greater_equal,floor_divide,true_divide,logical_or,logical_and,floor,ceil,maximum,minimum,rint.
These functions are included here because they are used at least oncein the array object’s methods. The function returns -1 (withoutsetting a Python Error) if one of the objects being assigned is notcallable.
PyArray_GetNumericOps(void)¶Return a Python dictionary containing the callable Python objectsstored in the internal arithmetic operation table. The keys ofthis dictionary are given in the explanation forPyArray_SetNumericOps.
PyArray_SetStringFunction(PyObject* op, int repr)¶This function allows you to alter the tp_str and tp_repr methodsof the array object to any Python function. Thus you can alterwhat happens for all arrays when str(arr) or repr(arr) is calledfrom Python. The function to be called is passed in asop. Ifrepr is non-zero, then this function will be called in responseto repr(arr), otherwise the function will be called in response tostr(arr). No check on whether or notop is callable isperformed. The callable passed in toop should expect an arrayargument and should return a string to be printed.
PyDataMem_NEW(size_t nbytes)¶PyDataMem_FREE(char* ptr)¶PyDataMem_RENEW(void * ptr, size_t newbytes)¶Macros to allocate, free, and reallocate memory. These macros are usedinternally to create arrays.
PyDimMem_NEW(nd)¶PyDimMem_FREE(npy_intp* ptr)¶PyDimMem_RENEW(npy_intp* ptr, npy_intp newnd)¶Macros to allocate, free, and reallocate dimension and strides memory.
PyArray_malloc(nbytes)¶PyArray_free(ptr)¶PyArray_realloc(ptr, nbytes)¶These macros use different memory allocators, depending on theconstantNPY_USE_PYMEM. The system malloc is used whenNPY_USE_PYMEM is 0, ifNPY_USE_PYMEM is 1, thenthe Python memory allocator is used.
PyArray_ResolveWritebackIfCopy(PyArrayObject* obj)¶Ifobj.flags hasNPY_ARRAY_WRITEBACKIFCOPY or (deprecated)NPY_ARRAY_UPDATEIFCOPY, this function clears the flags,DECREF sobj->base and makes it writeable, and setsobj->base to NULL. It thencopiesobj->data toobj->base->data, and returns the error state ofthe copy operation. This is the opposite ofPyArray_SetWritebackIfCopyBase. Usually this is called onceyou are finished withobj, just beforePy_DECREF(obj). It may be calledmultiple times, or withNULL input. See alsoPyArray_DiscardWritebackIfCopy.
Returns 0 if nothing was done, -1 on error, and 1 if action was taken.
These macros are only meaningful ifNPY_ALLOW_THREADSevaluates True during compilation of the extension module. Otherwise,these macros are equivalent to whitespace. Python uses a single GlobalInterpreter Lock (GIL) for each Python process so that only a singlethread may execute at a time (even on multi-cpu machines). Whencalling out to a compiled function that may take time to compute (anddoes not have side-effects for other threads like updated globalvariables), the GIL should be released so that other Python threadscan run while the time-consuming calculations are performed. This canbe accomplished using two groups of macros. Typically, if one macro ina group is used in a code block, all of them must be used in the samecode block. Currently,NPY_ALLOW_THREADS is defined to thepython-definedWITH_THREADS constant unless the environmentvariableNPY_NOSMP is set in which caseNPY_ALLOW_THREADS is defined to be 0.
This group is used to call code that may take some time but does notuse any Python C-API calls. Thus, the GIL should be released duringits calculation.
NPY_BEGIN_ALLOW_THREADS¶Equivalent to
Py_BEGIN_ALLOW_THREADSexcept it usesNPY_ALLOW_THREADSto determine if the macro ifreplaced with white-space or not.
NPY_END_ALLOW_THREADS¶Equivalent to
Py_END_ALLOW_THREADSexcept it usesNPY_ALLOW_THREADSto determine if the macro ifreplaced with white-space or not.
NPY_BEGIN_THREADS_DEF¶Place in the variable declaration area. This macro sets up thevariable needed for storing the Python state.
NPY_BEGIN_THREADS¶Place right before code that does not need the Pythoninterpreter (no Python C-API calls). This macro saves thePython state and releases the GIL.
NPY_END_THREADS¶Place right after code that does not need the Pythoninterpreter. This macro acquires the GIL and restores thePython state from the saved variable.
NPY_BEGIN_THREADS_DESCR(PyArray_Descr *dtype)¶Useful to release the GIL only ifdtype does not containarbitrary Python objects which may need the Python interpreterduring execution of the loop. Equivalent to
NPY_END_THREADS_DESCR(PyArray_Descr *dtype)¶Useful to regain the GIL in situations where it was releasedusing the BEGIN form of this macro.
NPY_BEGIN_THREADS_THRESHOLDED(int loop_size)¶Useful to release the GIL only ifloop_size exceeds aminimum threshold, currently set to 500. Should be matchedwith a
NPY_END_THREADSto regain the GIL.
This group is used to re-acquire the Python GIL after it has beenreleased. For example, suppose the GIL has been released (using theprevious calls), and then some path in the code (perhaps in adifferent subroutine) requires use of the Python C-API, then thesemacros are useful to acquire the GIL. These macros accomplishessentially a reverse of the previous three (acquire the LOCK savingwhat state it had) and then re-release it with the saved state.
NPY_ALLOW_C_API_DEF¶Place in the variable declaration area to set up the necessaryvariable.
NPY_ALLOW_C_API¶Place before code that needs to call the Python C-API (when it isknown that the GIL has already been released).
NPY_DISABLE_C_API¶Place after code that needs to call the Python C-API (to re-releasethe GIL).
Tip
Never use semicolons after the threading support macros.
NPY_PRIORITY¶Default priority for arrays.
NPY_SUBTYPE_PRIORITY¶Default subtype priority.
NPY_SCALAR_PRIORITY¶Default scalar priority (very small)
PyArray_GetPriority(PyObject* obj, double def)¶Return the__array_priority__ attribute (converted to adouble) ofobj ordef if no attribute of that nameexists. Fast returns that avoid the attribute lookup are providedfor objects of typePyArray_Type.
NPY_BUFSIZE¶Default size of the user-settable internal buffers.
NPY_MIN_BUFSIZE¶Smallest size of user-settable internal buffers.
NPY_MAX_BUFSIZE¶Largest size allowed for the user-settable buffers.
NPY_NUM_FLOATTYPE¶The number of floating-point types
NPY_MAXDIMS¶The maximum number of dimensions allowed in arrays.
NPY_VERSION¶The current version of the ndarray object (check to see if thisvariable is defined to guarantee the numpy/arrayobject.h header isbeing used).
NPY_FALSE¶Defined as 0 for use with Bool.
NPY_TRUE¶Defined as 1 for use with Bool.
NPY_FAIL¶The return value of failed converter functions which are called usingthe “O&” syntax inPyArg_ParseTuple-like functions.
NPY_SUCCEED¶The return value of successful converter functions which are calledusing the “O&” syntax inPyArg_ParseTuple-like functions.
PyArray_SAMESHAPE(a1, a2)¶Evaluates as True if arraysa1 anda2 have the same shape.
PyArray_MAX(a, b)¶Returns the maximum ofa andb. If (a) or (b) areexpressions they are evaluated twice.
PyArray_MIN(a, b)¶Returns the minimum ofa andb. If (a) or (b) areexpressions they are evaluated twice.
PyArray_CLT(a, b)¶PyArray_CGT(a, b)¶PyArray_CLE(a, b)¶PyArray_CGE(a, b)¶PyArray_CEQ(a, b)¶PyArray_CNE(a, b)¶Implements the complex comparisons between two complex numbers(structures with a real and imag member) using NumPy’s definitionof the ordering which is lexicographic: comparing the real partsfirst and then the complex parts if the real parts are equal.
PyArray_DiscardWritebackIfCopy(PyObject* obj)¶Ifobj.flags hasNPY_ARRAY_WRITEBACKIFCOPY or (deprecated)NPY_ARRAY_UPDATEIFCOPY, this function clears the flags,DECREF sobj->base and makes it writeable, and setsobj->base to NULL. Incontrast toPyArray_DiscardWritebackIfCopy it makes no attemptto copy the data fromobj->base This undoesPyArray_SetWritebackIfCopyBase. Usually this is called after anerror when you are finished withobj, just beforePy_DECREF(obj).It may be called multiple times, or withNULL input.
PyArray_XDECREF_ERR(PyObject* obj)¶Deprecated in 1.14, usePyArray_DiscardWritebackIfCopyfollowed byPy_XDECREF
DECREF’s an array object which may have the (deprecated)NPY_ARRAY_UPDATEIFCOPY orNPY_ARRAY_WRITEBACKIFCOPYflag set without causing the contents to be copied back into theoriginal array. Resets theNPY_ARRAY_WRITEABLE flag on the baseobject. This is useful for recovering from an error condition whenwriteback semantics are used, but will lead to wrong results.
NPY_SORTKIND¶A special variable-type which can take on the valuesNPY_{KIND}where{KIND} is
QUICKSORT,HEAPSORT,MERGESORT
NPY_NSORTS¶Defined to be the number of sorts.
NPY_SCALARKIND¶A special variable type indicating the number of “kinds” ofscalars distinguished in determining scalar-coercion rules. Thisvariable can take on the valuesNPY_{KIND} where{KIND} can be
NOSCALAR,BOOL_SCALAR,INTPOS_SCALAR,INTNEG_SCALAR,FLOAT_SCALAR,COMPLEX_SCALAR,OBJECT_SCALAR
NPY_NSCALARKINDS¶Defined to be the number of scalar kinds(not includingNPY_NOSCALAR).
NPY_ORDER¶An enumeration type indicating the element order that an array should beinterpreted in. When a brand new array is created, generallyonlyNPY_CORDER andNPY_FORTRANORDER are used, whereaswhen one or more inputs are provided, the order can be based on them.
NPY_ANYORDER¶Fortran order if all the inputs are Fortran, C otherwise.
NPY_CORDER¶C order.
NPY_FORTRANORDER¶Fortran order.
NPY_KEEPORDER¶An order as close to the order of the inputs as possible, evenif the input is in neither C nor Fortran order.
NPY_CLIPMODE¶A variable type indicating the kind of clipping that should beapplied in certain functions.
NPY_RAISEThe default for most operations, raises an exception if an indexis out of bounds.
NPY_CLIPClips an index to the valid range if it is out of bounds.
NPY_WRAPWraps an index to the valid range if it is out of bounds.
NPY_CASTING¶New in version 1.6.
An enumeration type indicating how permissive data conversions shouldbe. This is used by the iterator added in NumPy 1.6, and is intendedto be used more broadly in a future version.
NPY_NO_CASTING¶Only allow identical types.
NPY_EQUIV_CASTING¶Allow identical and casts involving byte swapping.
NPY_SAFE_CASTING¶Only allow casts which will not cause values to be rounded,truncated, or otherwise changed.
NPY_SAME_KIND_CASTING¶Allow any safe casts, and casts between types of the same kind.For example, float64 -> float32 is permitted with this rule.
NPY_UNSAFE_CASTING¶Allow any cast, no matter what kind of data loss may occur.