ufunc API#
Constants#
UFUNC_{THING}_{ERR}
Macros#
- NPY_LOOP_BEGIN_THREADS#
Used in universal function code to only release the Python GIL ifloop->obj is not true (i.e. this is not an OBJECT arrayloop). Requires use of
NPY_BEGIN_THREADS_DEFin variabledeclaration area.
- NPY_LOOP_END_THREADS#
Used in universal function code to re-acquire the Python GIL if itwas released (because loop->obj was not true).
Types#
- typePyUFuncGenericFunction#
Pointers to functions that actually implement the underlying(element-by-element) function\(N\) times with the followingsignature:
- voidloopfunc(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*data)#
- Parameters:
args – An array of pointers to the actual data for the input and outputarrays. The input arguments are given first followed by the outputarguments.
dimensions – A pointer to the size of the dimension over which this function islooping.
steps – A pointer to the number of bytes to jump to get to thenext element in this dimension for each of the input andoutput arguments.
data –
Arbitrary data (extra arguments, function names,etc. )that can be stored with the ufunc and will be passed inwhen it is called. May be
NULL.Changed in version 1.23.0:Accepts
NULLdata in addition to array ofNULLvalues.
This is an example of a func specialized for addition of doublesreturning doubles.
staticvoiddouble_add(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*extra){npy_intpi;npy_intpis1=steps[0],is2=steps[1];npy_intpos=steps[2],n=dimensions[0];char*i1=args[0],*i2=args[1],*op=args[2];for(i=0;i<n;i++){*((double*)op)=*((double*)i1)+*((double*)i2);i1+=is1;i2+=is2;op+=os;}}
- voidloopfunc(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*data)#
Functions#
- PyObject*PyUFunc_FromFuncAndData(PyUFuncGenericFunction*func,void*const*data,constchar*types,intntypes,intnin,intnout,intidentity,constchar*name,constchar*doc,intunused)#
Create a new broadcasting universal function from required variables.Each ufunc builds around the notion of an element-by-elementoperation. Each ufunc object contains pointers to 1-d loopsimplementing the basic functionality for each supported type.
Note
Thefunc,data,types,name, anddoc arguments are notcopied by
PyUFunc_FromFuncAndData. The caller must ensurethat the memory used by these arrays is not freed as long as theufunc object is alive.- Parameters:
func – Must point to an array containingntypes
PyUFuncGenericFunctionelements.data – Should be
NULLor a pointer to an array of sizentypes.This array may contain arbitrary extra-data to be passed tothe corresponding loop function in the func array, includingNULL.types –
Length
(nin+nout)*ntypesarray ofcharencoding thenumpy.dtype.num(built-in only) that the correspondingfunction in thefuncarray accepts. For instance, for a comparisonufunc with threentypes, twoninand onenout, where thefirst function acceptsnumpy.int32and the secondnumpy.int64, with both returningnumpy.bool_,typeswouldbe(char[]){5,5,0,7,7,0}sinceNPY_INT32is 5,NPY_INT64is 7, andNPY_BOOLis 0.The bit-width names can also be used (e.g.
NPY_INT32,NPY_COMPLEX128) if desired.Type casting rules will be used at runtime to find the first
funccallable by the input/output provided.ntypes – How many different data-type-specific functions the ufunc has implemented.
nin – The number of inputs to this operation.
nout – The number of outputs
identity – Either
PyUFunc_One,PyUFunc_Zero,PyUFunc_MinusOne, orPyUFunc_None.This specifies what should be returned whenan empty array is passed to the reduce method of the ufunc.The special valuePyUFunc_IdentityValuemay only be used withthePyUFunc_FromFuncAndDataAndSignatureAndIdentitymethod, toallow an arbitrary python object to be used as the identity.name – The name for the ufunc as a
NULLterminated string. Specifyinga name of ‘add’ or ‘multiply’ enables a special behavior forinteger-typed reductions when no dtype is given. If the input type is aninteger (or boolean) data type smaller than the size of thenumpy.int_data type, it will be internally upcast to thenumpy.int_(ornumpy.uint) data type.doc – Allows passing in a documentation string to be stored with theufunc. The documentation string should not contain the nameof the function or the calling signature as that will bedynamically determined from the object and available whenaccessing the__doc__ attribute of the ufunc.
unused – Unused and present for backwards compatibility of the C-API.
- PyObject*PyUFunc_FromFuncAndDataAndSignature(PyUFuncGenericFunction*func,void*const*data,constchar*types,intntypes,intnin,intnout,intidentity,constchar*name,constchar*doc,intunused,constchar*signature)#
This function is very similar to PyUFunc_FromFuncAndData above, but hasan extrasignature argument, to define ageneralized universal functions.Similarly to how ufuncs are built around an element-by-element operation,gufuncs are around subarray-by-subarray operations, thesignature defining the subarrays to operate on.
- Parameters:
signature – The signature for the new gufunc. Setting it to NULL is equivalentto calling PyUFunc_FromFuncAndData. A copy of the string is made,so the passed in buffer can be freed.
- PyObject*PyUFunc_FromFuncAndDataAndSignatureAndIdentity(PyUFuncGenericFunction*func,void**data,char*types,intntypes,intnin,intnout,intidentity,char*name,char*doc,intunused,char*signature,PyObject*identity_value)#
This function is very similar to
PyUFunc_FromFuncAndDataAndSignatureabove,but has an extraidentity_value argument, to define an arbitrary identityfor the ufunc whenidentityis passed asPyUFunc_IdentityValue.- Parameters:
identity_value – The identity for the new gufunc. Must be passed as
NULLunless theidentityargument isPyUFunc_IdentityValue. Setting it to NULLis equivalent to calling PyUFunc_FromFuncAndDataAndSignature.
- intPyUFunc_RegisterLoopForType(PyUFuncObject*ufunc,intusertype,PyUFuncGenericFunctionfunction,int*arg_types,void*data)#
This function allows the user to register a 1-d loop with analready- created ufunc to be used whenever the ufunc is calledwith any of its input arguments as the user-defineddata-type. This is needed in order to make ufuncs work withbuilt-in data-types. The data-type must have been previouslyregistered with the numpy system. The loop is passed in asfunction. This loop can take arbitrary data which should bepassed in asdata. The data-types the loop requires are passedin asarg_types which must be a pointer to memory at least aslarge as ufunc->nargs.
- intPyUFunc_RegisterLoopForDescr(PyUFuncObject*ufunc,PyArray_Descr*userdtype,PyUFuncGenericFunctionfunction,PyArray_Descr**arg_dtypes,void*data)#
This function behaves like PyUFunc_RegisterLoopForType above, exceptthat it allows the user to register a 1-d loop using PyArray_Descrobjects instead of dtype type num values. This allows a 1-d loop to beregistered for structured array data-dtypes and custom data-typesinstead of scalar data-types.
- intPyUFunc_ReplaceLoopBySignature(PyUFuncObject*ufunc,PyUFuncGenericFunctionnewfunc,int*signature,PyUFuncGenericFunction*oldfunc)#
Replace a 1-d loop matching the givensignature in thealready-createdufunc with the new 1-d loop newfunc. Return theold 1-d loop function inoldfunc. Return 0 on success and -1 onfailure. This function works only with built-in types (use
PyUFunc_RegisterLoopForTypefor user-defined types). Asignature is an array of data-type numbers indicating the inputsfollowed by the outputs assumed by the 1-d loop.
- voidPyUFunc_clearfperr()#
Clear the IEEE error flags.
Generic functions#
At the core of every ufunc is a collection of type-specific functionsthat defines the basic functionality for each of the supported types.These functions must evaluate the underlying function\(N\geq1\)times. Extra-data may be passed in that may be used during thecalculation. This feature allows some general functions to be used asthese basic looping functions. The general function has all the codeneeded to point variables to the right place and set up a functioncall. The general function assumes that the actual function to call ispassed in as the extra data and calls it with the correct values. Allof these functions are suitable for placing directly in the array offunctions stored in the functions member of the PyUFuncObjectstructure.
- voidPyUFunc_e_e_As_d_d(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*func)#
Type specific, core 1-d functions for ufuncs where eachcalculation is obtained by calling a function taking one inputargument and returning one output. This function is passed in
func. The letters correspond to dtypechar’s of the supporteddata types (e- half,f- float,d- double,g- long double,F- cfloat,D- cdouble,G- clongdouble). The argumentfunc must support the samesignature. The _As_X_X variants assume ndarray’s of one data typebut cast the values to use an underlying function that takes adifferent data type. Thus,PyUFunc_f_f_As_d_dusesndarrays of data typeNPY_FLOATbut calls out to aC-function that takes double and returns double.
- voidPyUFunc_ee_e_As_dd_d(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*func)#
Type specific, core 1-d functions for ufuncs where eachcalculation is obtained by calling a function taking two inputarguments and returning one output. The underlying function tocall is passed in asfunc. The letters correspond todtypechar’s of the specific data type supported by thegeneral-purpose function. The argument
funcmust support thecorresponding signature. The_As_XX_Xvariants assume ndarraysof one data type but cast the values at each iteration of the loopto use the underlying function that takes a different data type.
- voidPyUFunc_OO_O(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*func)#
One-input, one-output, and two-input, one-output core 1-d functionsfor the
NPY_OBJECTdata type. These functions handle referencecount issues and return early on error. The actual function to call isfunc and it must accept calls with the signature(PyObject*)(PyObject*)forPyUFunc_O_Oor(PyObject*)(PyObject*,PyObject*)forPyUFunc_OO_O.
- voidPyUFunc_O_O_method(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*func)#
This general purpose 1-d core function assumes thatfunc is a stringrepresenting a method of the input object. For eachiteration of the loop, the Python object is extracted from the arrayand itsfunc method is called returning the result to the output array.
- voidPyUFunc_OO_O_method(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*func)#
This general purpose 1-d core function assumes thatfunc is astring representing a method of the input object that takes oneargument. The first argument inargs is the method whose function iscalled, the second argument inargs is the argument passed to thefunction. The output of the function is stored in the third entryofargs.
- voidPyUFunc_On_Om(char**args,npy_intpconst*dimensions,npy_intpconst*steps,void*func)#
This is the 1-d core function used by the dynamic ufuncs createdby umath.frompyfunc(function, nin, nout). In this casefunc is apointer to a
PyUFunc_PyFuncDatastructure which has definition- typePyUFunc_PyFuncData#
typedefstruct{intnin;intnout;PyObject*callable;}PyUFunc_PyFuncData;
At each iteration of the loop, thenin input objects are extractedfrom their object arrays and placed into an argument tuple, the Pythoncallable is called with the input arguments, and the noutoutputs are placed into their object arrays.
- typePyUFunc_PyFuncData#
Importing the API#
- PY_UFUNC_UNIQUE_SYMBOL#
- NO_IMPORT_UFUNC#
- intPyUFunc_ImportUFuncAPI(void)#
Ensures that the UFunc C-API is imported and usable. It returns
0on success and-1with an error set if NumPy couldn’t be imported.While preferable to call it once at module initialization, this functionis very light-weight if called multiple times.New in version 2.0:This function mainly checks for
PyUFunc_API==NULLso it can bemanually backported if desired.
- import_ufunc(void)#
These are the constants and functions for accessing the ufuncC-API from extension modules in precisely the same way as thearray C-API can be accessed. The
import_ufunc() function mustalways be called (in the initialization subroutine of theextension module). If your extension module is in one file thenthat is all that is required. The other two constants are usefulif your extension module makes use of multiple files. In thatcase, definePY_UFUNC_UNIQUE_SYMBOLto something unique toyour code and then in source files that do not contain the moduleinitialization function but still need access to the UFUNC API,definePY_UFUNC_UNIQUE_SYMBOLto the same name used previouslyand also defineNO_IMPORT_UFUNC.The C-API is actually an array of function pointers. This array iscreated (and pointed to by a global variable) by import_ufunc. Theglobal variable is either statically defined or allowed to be seenby other files depending on the state of
PY_UFUNC_UNIQUE_SYMBOLandNO_IMPORT_UFUNC.