Movatterモバイル変換


[0]ホーム

URL:


SciPy

UFunc API

Constants

UFUNC_ERR_{HANDLER}

{HANDLER} can beIGNORE,WARN,RAISE, orCALL

UFUNC_{THING}_{ERR}

{THING} can beMASK,SHIFT, orFPE, and{ERR} canbeDIVIDEBYZERO,OVERFLOW,UNDERFLOW, andINVALID.

PyUFunc_{VALUE}

{VALUE} can beOne (1),Zero (0), orNone (-1)

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 ofNPY_BEGIN_THREADS_DEF in 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).

UFUNC_CHECK_ERROR(loop)

A macro used internally to check for errors and goto fail iffound. This macro requires a fail label in the current codeblock. Theloop variable must have at least members (obj,errormask, and errorobj). Ifloop ->obj is nonzero, thenPyErr_Occurred () is called (meaning the GIL must be held). Ifloop ->obj is zero, then ifloop ->errormask is nonzero,PyUFunc_checkfperr is called with argumentsloop ->errormaskandloop ->errobj. If the result of this check of the IEEEfloating point registers is true then the code redirects to thefail label which must be defined.

UFUNC_CHECK_STATUS(ret)

Deprecated: use npy_clear_floatstatus from npy_math.h instead.

A macro that expands to platform-dependent code. Theretvariable can be any integer. TheUFUNC_FPE_{ERR} bits areset inret according to the status of the corresponding errorflags of the floating point processor.

Functions

PyObject*PyUFunc_FromFuncAndData(PyUFuncGenericFunction* func, void** data, char* types, int ntypes, int nin, int nout, int identity, char* name, char* doc, int unused)

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 byPyUFunc_FromFuncAndData. The caller must ensurethat the memory used by these arrays is not freed as long as theufunc object is alive.

Parameters:
  • func – Must to an array of lengthntypes containingPyUFuncGenericFunction items. These items are pointers tofunctions that actually implement the underlying(element-by-element) functionN times.
  • data – Should beNULL or a pointer to an array of sizentypes. This array may contain arbitrary extra-data to be passed tothe corresponding 1-d loop function in the func array.
  • types

    Length(nin+nout)*ntypes array ofchar encoding thePyArray_Descr.type_num (built-in only) that the correspondingfunction in thefunc array accepts. For instance, for a comparisonufunc with threentypes, twonin and onenout, where thefirst function acceptsnpy_int32 and the the secondnpy_int64, with both returningnpy_bool,types wouldbe(char[]){5,5,0,7,7,0} sinceNPY_INT32 is 5,NPY_INT64 is 7, andNPY_BOOL is 0 (on the python side, theseare exposed viadtype.num, i.e., for the example here,dtype(np.int32).num,dtype(np.int64).num, anddtype(np.bool_).num, resp.).

    casting-rules will be used at runtime to find the firstfunc callable 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
  • name – The name for the ufunc. Specifying a name of ‘add’ or‘multiply’ enables a special behavior for integer-typedreductions when no dtype is given. If the input type is aninteger (or boolean) data type smaller than the size of theint_data type, it will be internally upcast to theint_ (or 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** data, char* types, int ntypes, int nin, int nout, int identity, char* name, char* doc, int unused, char *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.
intPyUFunc_RegisterLoopForType(PyUFuncObject* ufunc, int usertype, PyUFuncGenericFunction function, 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, PyUFuncGenericFunction function,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, PyUFuncGenericFunction newfunc, 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 (usePyUFunc_RegisterLoopForType for user-defined types). Asignature is an array of data-type numbers indicating the inputsfollowed by the outputs assumed by the 1-d loop.

intPyUFunc_GenericFunction(PyUFuncObject* self,PyObject* args,PyObject* kwds,PyArrayObject** mps)

A generic ufunc call. The ufunc is passed in asself, the argumentsto the ufunc asargs andkwds. Themps argument is an array ofPyArrayObject pointers whose values are discarded and whichreceive the converted input arguments as well as the ufunc outputswhen success is returned. The user is responsible for managing thisarray and receives a new reference for each array inmps. The totalnumber of arrays inmps is given byself ->nin +self ->nout.

Returns 0 on success, -1 on error.

intPyUFunc_checkfperr(int errmask,PyObject* errobj)

A simple interface to the IEEE error-flag checking support. Theerrmask argument is a mask ofUFUNC_MASK_{ERR} bitmasksindicating which errors to check for (and how to check forthem). Theerrobj must be a Python tuple with two elements: astring containing the name which will be used in any communicationof error and either a callable Python object (call-back function)orPy_None. The callable object will only be used ifUFUNC_ERR_CALL is set as the desired error checkingmethod. This routine manages the GIL and is safe to call evenafter releasing the GIL. If an error in the IEEE-compatiblehardware is determined a -1 is returned, otherwise a 0 isreturned.

voidPyUFunc_clearfperr()

Clear the IEEE error flags.

voidPyUFunc_GetPyValues(char* name, int* bufsize, int* errmask,PyObject** errobj)

Get the Python values used for ufunc processing from thethread-local storage area unless the defaults have been set inwhich case the name lookup is bypassed. The name is placed as astring in the first element of*errobj. The second element isthe looked-up function to call on error callback. The value of thelooked-up buffer-size to use is passed intobufsize, and thevalue of the error mask is placed intoerrmask.

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 functionN\geq1times. 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_f_f_As_d_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_d_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_f_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_g_g(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_F_F_As_D_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_F_F(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_D_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_G_G(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_e_e(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_e_e_As_f_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_e_e_As_d_d(char** args, npy_intp* dimensions, npy_intp* 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 infunc. 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_d usesndarrays of data typeNPY_FLOAT but calls out to aC-function that takes double and returns double.

voidPyUFunc_ff_f_As_dd_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_ff_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_dd_d(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_gg_g(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_FF_F_As_DD_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_DD_D(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_FF_F(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_GG_G(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_ee_e(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_ee_e_As_ff_f(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_ee_e_As_dd_d(char** args, npy_intp* dimensions, npy_intp* 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 argumentfunc must support thecorresponding signature. The_As_XX_X variants 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_O_O(char** args, npy_intp* dimensions, npy_intp* steps, void* func)
voidPyUFunc_OO_O(char** args, npy_intp* dimensions, npy_intp* steps, void* func)

One-input, one-output, and two-input, one-output core 1-d functionsfor theNPY_OBJECT data 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_O or(PyObject*)(PyObject*,PyObject*) forPyUFunc_OO_O.

voidPyUFunc_O_O_method(char** args, npy_intp* dimensions, npy_intp* 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_intp* dimensions, npy_intp* 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_intp* dimensions, npy_intp* 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 aPyUFunc_PyFuncData structure which has definition

PyUFunc_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.

Importing the API

PY_UFUNC_UNIQUE_SYMBOL
NO_IMPORT_UFUNC
voidimport_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. Theimport_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_SYMBOL to 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_SYMBOL to 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 ofPY_UFUNC_UNIQUE_SYMBOL andNO_IMPORT_UFUNC.

Table Of Contents

Previous topic

Array Iterator API

Next topic

Generalized Universal Function API

Quick search

  • © Copyright 2008-2018, The SciPy community.
  • Last updated on Jul 24, 2018.
  • Created usingSphinx 1.6.6.

[8]ページ先頭

©2009-2025 Movatter.jp