Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/f2py/cfuncs.py
7757 views
#!/usr/bin/env python31"""23C declarations, CPP macros, and C functions for f2py2e.4Only required declarations/macros/functions will be used.56Copyright 1999,2000 Pearu Peterson all rights reserved,7Pearu Peterson <[email protected]>8Permission to use, modify, and distribute this software is given under the9terms of the NumPy License.1011NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.12$Date: 2005/05/06 11:42:34 $13Pearu Peterson1415"""16import sys17import copy1819from . import __version__2021f2py_version = __version__.version22errmess = sys.stderr.write2324##################### Definitions ##################2526outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [],27'userincludes': [],28'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [],29'commonhooks': []}30needs = {}31includes0 = {'includes0': '/*need_includes0*/'}32includes = {'includes': '/*need_includes*/'}33userincludes = {'userincludes': '/*need_userincludes*/'}34typedefs = {'typedefs': '/*need_typedefs*/'}35typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'}36cppmacros = {'cppmacros': '/*need_cppmacros*/'}37cfuncs = {'cfuncs': '/*need_cfuncs*/'}38callbacks = {'callbacks': '/*need_callbacks*/'}39f90modhooks = {'f90modhooks': '/*need_f90modhooks*/',40'initf90modhooksstatic': '/*initf90modhooksstatic*/',41'initf90modhooksdynamic': '/*initf90modhooksdynamic*/',42}43commonhooks = {'commonhooks': '/*need_commonhooks*/',44'initcommonhooks': '/*need_initcommonhooks*/',45}4647############ Includes ###################4849includes0['math.h'] = '#include <math.h>'50includes0['string.h'] = '#include <string.h>'51includes0['setjmp.h'] = '#include <setjmp.h>'5253includes['Python.h'] = '#include <Python.h>'54needs['arrayobject.h'] = ['Python.h']55includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API56#include "arrayobject.h"'''5758includes['arrayobject.h'] = '#include "fortranobject.h"'59includes['stdarg.h'] = '#include <stdarg.h>'6061############# Type definitions ###############6263typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;'64typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;'65typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;'66typedefs['signed_char'] = 'typedef signed char signed_char;'67typedefs['long_long'] = """\68#ifdef _WIN3269typedef __int64 long_long;70#else71typedef long long long_long;72typedef unsigned long long unsigned_long_long;73#endif74"""75typedefs['unsigned_long_long'] = """\76#ifdef _WIN3277typedef __uint64 long_long;78#else79typedef unsigned long long unsigned_long_long;80#endif81"""82typedefs['long_double'] = """\83#ifndef _LONG_DOUBLE84typedef long double long_double;85#endif86"""87typedefs[88'complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;'89typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;'90typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;'91typedefs['string'] = """typedef char * string;"""929394############### CPP macros ####################95cppmacros['CFUNCSMESS'] = """\96#ifdef DEBUGCFUNCS97#define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess);98#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\99PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\100fprintf(stderr,\"\\n\");101#else102#define CFUNCSMESS(mess)103#define CFUNCSMESSPY(mess,obj)104#endif105"""106cppmacros['F_FUNC'] = """\107#if defined(PREPEND_FORTRAN)108#if defined(NO_APPEND_FORTRAN)109#if defined(UPPERCASE_FORTRAN)110#define F_FUNC(f,F) _##F111#else112#define F_FUNC(f,F) _##f113#endif114#else115#if defined(UPPERCASE_FORTRAN)116#define F_FUNC(f,F) _##F##_117#else118#define F_FUNC(f,F) _##f##_119#endif120#endif121#else122#if defined(NO_APPEND_FORTRAN)123#if defined(UPPERCASE_FORTRAN)124#define F_FUNC(f,F) F125#else126#define F_FUNC(f,F) f127#endif128#else129#if defined(UPPERCASE_FORTRAN)130#define F_FUNC(f,F) F##_131#else132#define F_FUNC(f,F) f##_133#endif134#endif135#endif136#if defined(UNDERSCORE_G77)137#define F_FUNC_US(f,F) F_FUNC(f##_,F##_)138#else139#define F_FUNC_US(f,F) F_FUNC(f,F)140#endif141"""142cppmacros['F_WRAPPEDFUNC'] = """\143#if defined(PREPEND_FORTRAN)144#if defined(NO_APPEND_FORTRAN)145#if defined(UPPERCASE_FORTRAN)146#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F147#else148#define F_WRAPPEDFUNC(f,F) _f2pywrap##f149#endif150#else151#if defined(UPPERCASE_FORTRAN)152#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_153#else154#define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_155#endif156#endif157#else158#if defined(NO_APPEND_FORTRAN)159#if defined(UPPERCASE_FORTRAN)160#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F161#else162#define F_WRAPPEDFUNC(f,F) f2pywrap##f163#endif164#else165#if defined(UPPERCASE_FORTRAN)166#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_167#else168#define F_WRAPPEDFUNC(f,F) f2pywrap##f##_169#endif170#endif171#endif172#if defined(UNDERSCORE_G77)173#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_)174#else175#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F)176#endif177"""178cppmacros['F_MODFUNC'] = """\179#if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */180#if defined(NO_APPEND_FORTRAN)181#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f182#else183#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _184#endif185#endif186187#if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */188#if defined(NO_APPEND_FORTRAN)189#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f190#else191#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _192#endif193#endif194195#if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */196#if defined(NO_APPEND_FORTRAN)197#define F_MODFUNCNAME(m,f) f ## .in. ## m198#else199#define F_MODFUNCNAME(m,f) f ## .in. ## m ## _200#endif201#endif202/*203#if defined(UPPERCASE_FORTRAN)204#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F)205#else206#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f)207#endif208*/209210#define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f))211"""212cppmacros['SWAPUNSAFE'] = """\213#define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\214(size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\215(size_t)(a) = ((size_t)(a) ^ (size_t)(b))216"""217cppmacros['SWAP'] = """\218#define SWAP(a,b,t) {\\219t *c;\\220c = a;\\221a = b;\\222b = c;}223"""224# cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) &225# NPY_ARRAY_C_CONTIGUOUS)'226cppmacros['PRINTPYOBJERR'] = """\227#define PRINTPYOBJERR(obj)\\228fprintf(stderr,\"#modulename#.error is related to \");\\229PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\230fprintf(stderr,\"\\n\");231"""232cppmacros['MINMAX'] = """\233#ifndef max234#define max(a,b) ((a > b) ? (a) : (b))235#endif236#ifndef min237#define min(a,b) ((a < b) ? (a) : (b))238#endif239#ifndef MAX240#define MAX(a,b) ((a > b) ? (a) : (b))241#endif242#ifndef MIN243#define MIN(a,b) ((a < b) ? (a) : (b))244#endif245"""246needs['len..'] = ['f2py_size']247cppmacros['len..'] = """\248#define rank(var) var ## _Rank249#define shape(var,dim) var ## _Dims[dim]250#define old_rank(var) (PyArray_NDIM((PyArrayObject *)(capi_ ## var ## _tmp)))251#define old_shape(var,dim) PyArray_DIM(((PyArrayObject *)(capi_ ## var ## _tmp)),dim)252#define fshape(var,dim) shape(var,rank(var)-dim-1)253#define len(var) shape(var,0)254#define flen(var) fshape(var,0)255#define old_size(var) PyArray_SIZE((PyArrayObject *)(capi_ ## var ## _tmp))256/* #define index(i) capi_i ## i */257#define slen(var) capi_ ## var ## _len258#define size(var, ...) f2py_size((PyArrayObject *)(capi_ ## var ## _tmp), ## __VA_ARGS__, -1)259"""260needs['f2py_size'] = ['stdarg.h']261cfuncs['f2py_size'] = """\262static int f2py_size(PyArrayObject* var, ...)263{264npy_int sz = 0;265npy_int dim;266npy_int rank;267va_list argp;268va_start(argp, var);269dim = va_arg(argp, npy_int);270if (dim==-1)271{272sz = PyArray_SIZE(var);273}274else275{276rank = PyArray_NDIM(var);277if (dim>=1 && dim<=rank)278sz = PyArray_DIM(var, dim-1);279else280fprintf(stderr, \"f2py_size: 2nd argument value=%d fails to satisfy 1<=value<=%d. Result will be 0.\\n\", dim, rank);281}282va_end(argp);283return sz;284}285"""286287cppmacros[288'pyobj_from_char1'] = '#define pyobj_from_char1(v) (PyLong_FromLong(v))'289cppmacros[290'pyobj_from_short1'] = '#define pyobj_from_short1(v) (PyLong_FromLong(v))'291needs['pyobj_from_int1'] = ['signed_char']292cppmacros['pyobj_from_int1'] = '#define pyobj_from_int1(v) (PyLong_FromLong(v))'293cppmacros[294'pyobj_from_long1'] = '#define pyobj_from_long1(v) (PyLong_FromLong(v))'295needs['pyobj_from_long_long1'] = ['long_long']296cppmacros['pyobj_from_long_long1'] = """\297#ifdef HAVE_LONG_LONG298#define pyobj_from_long_long1(v) (PyLong_FromLongLong(v))299#else300#warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long.301#define pyobj_from_long_long1(v) (PyLong_FromLong(v))302#endif303"""304needs['pyobj_from_long_double1'] = ['long_double']305cppmacros[306'pyobj_from_long_double1'] = '#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))'307cppmacros[308'pyobj_from_double1'] = '#define pyobj_from_double1(v) (PyFloat_FromDouble(v))'309cppmacros[310'pyobj_from_float1'] = '#define pyobj_from_float1(v) (PyFloat_FromDouble(v))'311needs['pyobj_from_complex_long_double1'] = ['complex_long_double']312cppmacros[313'pyobj_from_complex_long_double1'] = '#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))'314needs['pyobj_from_complex_double1'] = ['complex_double']315cppmacros[316'pyobj_from_complex_double1'] = '#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))'317needs['pyobj_from_complex_float1'] = ['complex_float']318cppmacros[319'pyobj_from_complex_float1'] = '#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))'320needs['pyobj_from_string1'] = ['string']321cppmacros[322'pyobj_from_string1'] = '#define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))'323needs['pyobj_from_string1size'] = ['string']324cppmacros[325'pyobj_from_string1size'] = '#define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))'326needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']327cppmacros['TRYPYARRAYTEMPLATE'] = """\328/* New SciPy */329#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break;330#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;331#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break;332333#define TRYPYARRAYTEMPLATE(ctype,typecode) \\334PyArrayObject *arr = NULL;\\335if (!obj) return -2;\\336if (!PyArray_Check(obj)) return -1;\\337if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\338if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\339switch (PyArray_TYPE(arr)) {\\340case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\341case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=*v; break;\\342case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=*v; break;\\343case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\344case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\345case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\346case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\347case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=*v; break;\\348case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=*v; break;\\349case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=*v; break;\\350case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\351case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\352case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\353case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\354case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\355case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\356case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\357case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\358default: return -2;\\359};\\360return 1361"""362363needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']364cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """\365#define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;366#define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\367PyArrayObject *arr = NULL;\\368if (!obj) return -2;\\369if (!PyArray_Check(obj)) return -1;\\370if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\371if (PyArray_DESCR(arr)->type==typecode) {\\372*(ctype *)(PyArray_DATA(arr))=(*v).r;\\373*(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\374return 1;\\375}\\376switch (PyArray_TYPE(arr)) {\\377case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r;\\378*(npy_double *)(PyArray_DATA(arr)+sizeof(npy_double))=(*v).i;\\379break;\\380case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r;\\381*(npy_float *)(PyArray_DATA(arr)+sizeof(npy_float))=(*v).i;\\382break;\\383case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r; break;\\384case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=(*v).r; break;\\385case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r; break;\\386case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=(*v).r; break;\\387case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=(*v).r; break;\\388case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=(*v).r; break;\\389case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=(*v).r; break;\\390case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\391case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\392case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\393case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\394case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\395case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\396case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\397case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;\\398*(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;\\399break;\\400case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\401default: return -2;\\402};\\403return -1;404"""405# cppmacros['NUMFROMARROBJ']="""\406# define NUMFROMARROBJ(typenum,ctype) \\407# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\408# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\409# if (arr) {\\410# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\411# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\412# goto capi_fail;\\413# } else {\\414# (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\415# }\\416# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\417# return 1;\\418# }419# """420# XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ421# cppmacros['CNUMFROMARROBJ']="""\422# define CNUMFROMARROBJ(typenum,ctype) \\423# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\424# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\425# if (arr) {\\426# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\427# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\428# goto capi_fail;\\429# } else {\\430# (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\431# }\\432# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\433# return 1;\\434# }435# """436437438needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR']439cppmacros['GETSTRFROMPYTUPLE'] = """\440#define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\441PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\442if (rv_cb_str == NULL)\\443goto capi_fail;\\444if (PyBytes_Check(rv_cb_str)) {\\445str[len-1]='\\0';\\446STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\447} else {\\448PRINTPYOBJERR(rv_cb_str);\\449PyErr_SetString(#modulename#_error,\"string object expected\");\\450goto capi_fail;\\451}\\452}453"""454cppmacros['GETSCALARFROMPYTUPLE'] = """\455#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\456if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\457if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\458goto capi_fail;\\459}460"""461462cppmacros['FAILNULL'] = """\\463#define FAILNULL(p) do { \\464if ((p) == NULL) { \\465PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\466goto capi_fail; \\467} \\468} while (0)469"""470needs['MEMCOPY'] = ['string.h', 'FAILNULL']471cppmacros['MEMCOPY'] = """\472#define MEMCOPY(to,from,n)\\473do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0)474"""475cppmacros['STRINGMALLOC'] = """\476#define STRINGMALLOC(str,len)\\477if ((str = (string)malloc(len+1)) == NULL) {\\478PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\479goto capi_fail;\\480} else {\\481(str)[len] = '\\0';\\482}483"""484cppmacros['STRINGFREE'] = """\485#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0)486"""487needs['STRINGPADN'] = ['string.h']488cppmacros['STRINGPADN'] = """\489/*490STRINGPADN replaces null values with padding values from the right.491492`to` must have size of at least N bytes.493494If the `to[N-1]` has null value, then replace it and all the495preceding, nulls with the given padding.496497STRINGPADN(to, N, PADDING, NULLVALUE) is an inverse operation.498*/499#define STRINGPADN(to, N, NULLVALUE, PADDING) \\500do { \\501int _m = (N); \\502char *_to = (to); \\503for (_m -= 1; _m >= 0 && _to[_m] == NULLVALUE; _m--) { \\504_to[_m] = PADDING; \\505} \\506} while (0)507"""508needs['STRINGCOPYN'] = ['string.h', 'FAILNULL']509cppmacros['STRINGCOPYN'] = """\510/*511STRINGCOPYN copies N bytes.512513`to` and `from` buffers must have sizes of at least N bytes.514*/515#define STRINGCOPYN(to,from,N) \\516do { \\517int _m = (N); \\518char *_to = (to); \\519char *_from = (from); \\520FAILNULL(_to); FAILNULL(_from); \\521(void)strncpy(_to, _from, _m); \\522} while (0)523"""524needs['STRINGCOPY'] = ['string.h', 'FAILNULL']525cppmacros['STRINGCOPY'] = """\526#define STRINGCOPY(to,from)\\527do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0)528"""529cppmacros['CHECKGENERIC'] = """\530#define CHECKGENERIC(check,tcheck,name) \\531if (!(check)) {\\532PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\533/*goto capi_fail;*/\\534} else """535cppmacros['CHECKARRAY'] = """\536#define CHECKARRAY(check,tcheck,name) \\537if (!(check)) {\\538PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\539/*goto capi_fail;*/\\540} else """541cppmacros['CHECKSTRING'] = """\542#define CHECKSTRING(check,tcheck,name,show,var)\\543if (!(check)) {\\544char errstring[256];\\545sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\546PyErr_SetString(#modulename#_error, errstring);\\547/*goto capi_fail;*/\\548} else """549cppmacros['CHECKSCALAR'] = """\550#define CHECKSCALAR(check,tcheck,name,show,var)\\551if (!(check)) {\\552char errstring[256];\\553sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\554PyErr_SetString(#modulename#_error,errstring);\\555/*goto capi_fail;*/\\556} else """557# cppmacros['CHECKDIMS']="""\558# define CHECKDIMS(dims,rank) \\559# for (int i=0;i<(rank);i++)\\560# if (dims[i]<0) {\\561# fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\562# goto capi_fail;\\563# }564# """565cppmacros[566'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))'567cppmacros['OLDPYNUM'] = """\568#ifdef OLDPYNUM569#error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html570#endif571"""572cppmacros["F2PY_THREAD_LOCAL_DECL"] = """\573#ifndef F2PY_THREAD_LOCAL_DECL574#if defined(_MSC_VER)575#define F2PY_THREAD_LOCAL_DECL __declspec(thread)576#elif defined(__MINGW32__) || defined(__MINGW64__)577#define F2PY_THREAD_LOCAL_DECL __thread578#elif defined(__STDC_VERSION__) \\579&& (__STDC_VERSION__ >= 201112L) \\580&& !defined(__STDC_NO_THREADS__) \\581&& (!defined(__GLIBC__) || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 12)) \\582&& !defined(__OpenBSD__)583/* __STDC_NO_THREADS__ was first defined in a maintenance release of glibc 2.12,584see https://lists.gnu.org/archive/html/commit-hurd/2012-07/msg00180.html,585so `!defined(__STDC_NO_THREADS__)` may give false positive for the existence586of `threads.h` when using an older release of glibc 2.12587See gh-19437 for details on OpenBSD */588#include <threads.h>589#define F2PY_THREAD_LOCAL_DECL thread_local590#elif defined(__GNUC__) \\591&& (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4)))592#define F2PY_THREAD_LOCAL_DECL __thread593#endif594#endif595"""596################# C functions ###############597598cfuncs['calcarrindex'] = """\599static int calcarrindex(int *i,PyArrayObject *arr) {600int k,ii = i[0];601for (k=1; k < PyArray_NDIM(arr); k++)602ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */603return ii;604}"""605cfuncs['calcarrindextr'] = """\606static int calcarrindextr(int *i,PyArrayObject *arr) {607int k,ii = i[PyArray_NDIM(arr)-1];608for (k=1; k < PyArray_NDIM(arr); k++)609ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */610return ii;611}"""612cfuncs['forcomb'] = """\613static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;614static int initforcomb(npy_intp *dims,int nd,int tr) {615int k;616if (dims==NULL) return 0;617if (nd<0) return 0;618forcombcache.nd = nd;619forcombcache.d = dims;620forcombcache.tr = tr;621if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;622if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;623for (k=1;k<nd;k++) {624forcombcache.i[k] = forcombcache.i_tr[nd-k-1] = 0;625}626forcombcache.i[0] = forcombcache.i_tr[nd-1] = -1;627return 1;628}629static int *nextforcomb(void) {630int j,*i,*i_tr,k;631int nd=forcombcache.nd;632if ((i=forcombcache.i) == NULL) return NULL;633if ((i_tr=forcombcache.i_tr) == NULL) return NULL;634if (forcombcache.d == NULL) return NULL;635i[0]++;636if (i[0]==forcombcache.d[0]) {637j=1;638while ((j<nd) && (i[j]==forcombcache.d[j]-1)) j++;639if (j==nd) {640free(i);641free(i_tr);642return NULL;643}644for (k=0;k<j;k++) i[k] = i_tr[nd-k-1] = 0;645i[j]++;646i_tr[nd-j-1]++;647} else648i_tr[nd-1]++;649if (forcombcache.tr) return i_tr;650return i;651}"""652needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string']653cfuncs['try_pyarr_from_string'] = """\654/*655try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`.656657If obj is an `ndarray`, it is assumed to be contiguous.658659If the specified len==-1, str must be null-terminated.660*/661static int try_pyarr_from_string(PyObject *obj,662const string str, const int len) {663#ifdef DEBUGCFUNCS664fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n",665(char*)str,len, obj);666#endif667if (PyArray_Check(obj)) {668PyArrayObject *arr = (PyArrayObject *)obj;669assert(ISCONTIGUOUS(arr));670string buf = PyArray_DATA(arr);671npy_intp n = len;672if (n == -1) {673/* Assuming null-terminated str. */674n = strlen(str);675}676if (n > PyArray_NBYTES(arr)) {677n = PyArray_NBYTES(arr);678}679STRINGCOPYN(buf, str, n);680return 1;681}682capi_fail:683PRINTPYOBJERR(obj);684PyErr_SetString(#modulename#_error, \"try_pyarr_from_string failed\");685return 0;686}687"""688needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN']689cfuncs['string_from_pyobj'] = """\690/*691Create a new string buffer `str` of at most length `len` from a692Python string-like object `obj`.693694The string buffer has given size (len) or the size of inistr when len==-1.695696The string buffer is padded with blanks: in Fortran, trailing blanks697are insignificant contrary to C nulls.698*/699static int700string_from_pyobj(string *str, int *len, const string inistr, PyObject *obj,701const char *errmess)702{703PyObject *tmp = NULL;704string buf = NULL;705npy_intp n = -1;706#ifdef DEBUGCFUNCS707fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",708(char*)str, *len, (char *)inistr, obj);709#endif710if (obj == Py_None) {711n = strlen(inistr);712buf = inistr;713}714else if (PyArray_Check(obj)) {715PyArrayObject *arr = (PyArrayObject *)obj;716if (!ISCONTIGUOUS(arr)) {717PyErr_SetString(PyExc_ValueError,718\"array object is non-contiguous.\");719goto capi_fail;720}721n = PyArray_NBYTES(arr);722buf = PyArray_DATA(arr);723n = strnlen(buf, n);724}725else {726if (PyBytes_Check(obj)) {727tmp = obj;728Py_INCREF(tmp);729}730else if (PyUnicode_Check(obj)) {731tmp = PyUnicode_AsASCIIString(obj);732}733else {734PyObject *tmp2;735tmp2 = PyObject_Str(obj);736if (tmp2) {737tmp = PyUnicode_AsASCIIString(tmp2);738Py_DECREF(tmp2);739}740else {741tmp = NULL;742}743}744if (tmp == NULL) goto capi_fail;745n = PyBytes_GET_SIZE(tmp);746buf = PyBytes_AS_STRING(tmp);747}748if (*len == -1) {749/* TODO: change the type of `len` so that we can remove this */750if (n > NPY_MAX_INT) {751PyErr_SetString(PyExc_OverflowError,752"object too large for a 32-bit int");753goto capi_fail;754}755*len = n;756}757else if (*len < n) {758/* discard the last (len-n) bytes of input buf */759n = *len;760}761if (n < 0 || *len < 0 || buf == NULL) {762goto capi_fail;763}764STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1)765if (n < *len) {766/*767Pad fixed-width string with nulls. The caller will replace768nulls with blanks when the corresponding argument is not769intent(c).770*/771memset(*str + n, '\\0', *len - n);772}773STRINGCOPYN(*str, buf, n);774Py_XDECREF(tmp);775return 1;776capi_fail:777Py_XDECREF(tmp);778{779PyObject* err = PyErr_Occurred();780if (err == NULL) {781err = #modulename#_error;782}783PyErr_SetString(err, errmess);784}785return 0;786}787"""788789needs['char_from_pyobj'] = ['int_from_pyobj']790cfuncs['char_from_pyobj'] = """\791static int792char_from_pyobj(char* v, PyObject *obj, const char *errmess) {793int i = 0;794if (int_from_pyobj(&i, obj, errmess)) {795*v = (char)i;796return 1;797}798return 0;799}800"""801802803needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char']804cfuncs['signed_char_from_pyobj'] = """\805static int806signed_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) {807int i = 0;808if (int_from_pyobj(&i, obj, errmess)) {809*v = (signed_char)i;810return 1;811}812return 0;813}814"""815816817needs['short_from_pyobj'] = ['int_from_pyobj']818cfuncs['short_from_pyobj'] = """\819static int820short_from_pyobj(short* v, PyObject *obj, const char *errmess) {821int i = 0;822if (int_from_pyobj(&i, obj, errmess)) {823*v = (short)i;824return 1;825}826return 0;827}828"""829830831cfuncs['int_from_pyobj'] = """\832static int833int_from_pyobj(int* v, PyObject *obj, const char *errmess)834{835PyObject* tmp = NULL;836837if (PyLong_Check(obj)) {838*v = Npy__PyLong_AsInt(obj);839return !(*v == -1 && PyErr_Occurred());840}841842tmp = PyNumber_Long(obj);843if (tmp) {844*v = Npy__PyLong_AsInt(tmp);845Py_DECREF(tmp);846return !(*v == -1 && PyErr_Occurred());847}848849if (PyComplex_Check(obj)) {850PyErr_Clear();851tmp = PyObject_GetAttrString(obj,\"real\");852}853else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {854/*pass*/;855}856else if (PySequence_Check(obj)) {857PyErr_Clear();858tmp = PySequence_GetItem(obj, 0);859}860861if (tmp) {862if (int_from_pyobj(v, tmp, errmess)) {863Py_DECREF(tmp);864return 1;865}866Py_DECREF(tmp);867}868869{870PyObject* err = PyErr_Occurred();871if (err == NULL) {872err = #modulename#_error;873}874PyErr_SetString(err, errmess);875}876return 0;877}878"""879880881cfuncs['long_from_pyobj'] = """\882static int883long_from_pyobj(long* v, PyObject *obj, const char *errmess) {884PyObject* tmp = NULL;885886if (PyLong_Check(obj)) {887*v = PyLong_AsLong(obj);888return !(*v == -1 && PyErr_Occurred());889}890891tmp = PyNumber_Long(obj);892if (tmp) {893*v = PyLong_AsLong(tmp);894Py_DECREF(tmp);895return !(*v == -1 && PyErr_Occurred());896}897898if (PyComplex_Check(obj)) {899PyErr_Clear();900tmp = PyObject_GetAttrString(obj,\"real\");901}902else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {903/*pass*/;904}905else if (PySequence_Check(obj)) {906PyErr_Clear();907tmp = PySequence_GetItem(obj, 0);908}909910if (tmp) {911if (long_from_pyobj(v, tmp, errmess)) {912Py_DECREF(tmp);913return 1;914}915Py_DECREF(tmp);916}917{918PyObject* err = PyErr_Occurred();919if (err == NULL) {920err = #modulename#_error;921}922PyErr_SetString(err, errmess);923}924return 0;925}926"""927928929needs['long_long_from_pyobj'] = ['long_long']930cfuncs['long_long_from_pyobj'] = """\931static int932long_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess)933{934PyObject* tmp = NULL;935936if (PyLong_Check(obj)) {937*v = PyLong_AsLongLong(obj);938return !(*v == -1 && PyErr_Occurred());939}940941tmp = PyNumber_Long(obj);942if (tmp) {943*v = PyLong_AsLongLong(tmp);944Py_DECREF(tmp);945return !(*v == -1 && PyErr_Occurred());946}947948if (PyComplex_Check(obj)) {949PyErr_Clear();950tmp = PyObject_GetAttrString(obj,\"real\");951}952else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {953/*pass*/;954}955else if (PySequence_Check(obj)) {956PyErr_Clear();957tmp = PySequence_GetItem(obj, 0);958}959960if (tmp) {961if (long_long_from_pyobj(v, tmp, errmess)) {962Py_DECREF(tmp);963return 1;964}965Py_DECREF(tmp);966}967{968PyObject* err = PyErr_Occurred();969if (err == NULL) {970err = #modulename#_error;971}972PyErr_SetString(err,errmess);973}974return 0;975}976"""977978979needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double']980cfuncs['long_double_from_pyobj'] = """\981static int982long_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess)983{984double d=0;985if (PyArray_CheckScalar(obj)){986if PyArray_IsScalar(obj, LongDouble) {987PyArray_ScalarAsCtype(obj, v);988return 1;989}990else if (PyArray_Check(obj) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {991(*v) = *((npy_longdouble *)PyArray_DATA(obj));992return 1;993}994}995if (double_from_pyobj(&d, obj, errmess)) {996*v = (long_double)d;997return 1;998}999return 0;1000}1001"""100210031004cfuncs['double_from_pyobj'] = """\1005static int1006double_from_pyobj(double* v, PyObject *obj, const char *errmess)1007{1008PyObject* tmp = NULL;1009if (PyFloat_Check(obj)) {1010*v = PyFloat_AsDouble(obj);1011return !(*v == -1.0 && PyErr_Occurred());1012}10131014tmp = PyNumber_Float(obj);1015if (tmp) {1016*v = PyFloat_AsDouble(tmp);1017Py_DECREF(tmp);1018return !(*v == -1.0 && PyErr_Occurred());1019}10201021if (PyComplex_Check(obj)) {1022PyErr_Clear();1023tmp = PyObject_GetAttrString(obj,\"real\");1024}1025else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {1026/*pass*/;1027}1028else if (PySequence_Check(obj)) {1029PyErr_Clear();1030tmp = PySequence_GetItem(obj, 0);1031}10321033if (tmp) {1034if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}1035Py_DECREF(tmp);1036}1037{1038PyObject* err = PyErr_Occurred();1039if (err==NULL) err = #modulename#_error;1040PyErr_SetString(err,errmess);1041}1042return 0;1043}1044"""104510461047needs['float_from_pyobj'] = ['double_from_pyobj']1048cfuncs['float_from_pyobj'] = """\1049static int1050float_from_pyobj(float* v, PyObject *obj, const char *errmess)1051{1052double d=0.0;1053if (double_from_pyobj(&d,obj,errmess)) {1054*v = (float)d;1055return 1;1056}1057return 0;1058}1059"""106010611062needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double',1063'complex_double_from_pyobj']1064cfuncs['complex_long_double_from_pyobj'] = """\1065static int1066complex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess)1067{1068complex_double cd = {0.0,0.0};1069if (PyArray_CheckScalar(obj)){1070if PyArray_IsScalar(obj, CLongDouble) {1071PyArray_ScalarAsCtype(obj, v);1072return 1;1073}1074else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {1075(*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real;1076(*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag;1077return 1;1078}1079}1080if (complex_double_from_pyobj(&cd,obj,errmess)) {1081(*v).r = (long_double)cd.r;1082(*v).i = (long_double)cd.i;1083return 1;1084}1085return 0;1086}1087"""108810891090needs['complex_double_from_pyobj'] = ['complex_double']1091cfuncs['complex_double_from_pyobj'] = """\1092static int1093complex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) {1094Py_complex c;1095if (PyComplex_Check(obj)) {1096c = PyComplex_AsCComplex(obj);1097(*v).r = c.real;1098(*v).i = c.imag;1099return 1;1100}1101if (PyArray_IsScalar(obj, ComplexFloating)) {1102if (PyArray_IsScalar(obj, CFloat)) {1103npy_cfloat new;1104PyArray_ScalarAsCtype(obj, &new);1105(*v).r = (double)new.real;1106(*v).i = (double)new.imag;1107}1108else if (PyArray_IsScalar(obj, CLongDouble)) {1109npy_clongdouble new;1110PyArray_ScalarAsCtype(obj, &new);1111(*v).r = (double)new.real;1112(*v).i = (double)new.imag;1113}1114else { /* if (PyArray_IsScalar(obj, CDouble)) */1115PyArray_ScalarAsCtype(obj, v);1116}1117return 1;1118}1119if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */1120PyObject *arr;1121if (PyArray_Check(obj)) {1122arr = PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE);1123}1124else {1125arr = PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE));1126}1127if (arr == NULL) {1128return 0;1129}1130(*v).r = ((npy_cdouble *)PyArray_DATA(arr))->real;1131(*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag;1132Py_DECREF(arr);1133return 1;1134}1135/* Python does not provide PyNumber_Complex function :-( */1136(*v).i = 0.0;1137if (PyFloat_Check(obj)) {1138(*v).r = PyFloat_AsDouble(obj);1139return !((*v).r == -1.0 && PyErr_Occurred());1140}1141if (PyLong_Check(obj)) {1142(*v).r = PyLong_AsDouble(obj);1143return !((*v).r == -1.0 && PyErr_Occurred());1144}1145if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) {1146PyObject *tmp = PySequence_GetItem(obj,0);1147if (tmp) {1148if (complex_double_from_pyobj(v,tmp,errmess)) {1149Py_DECREF(tmp);1150return 1;1151}1152Py_DECREF(tmp);1153}1154}1155{1156PyObject* err = PyErr_Occurred();1157if (err==NULL)1158err = PyExc_TypeError;1159PyErr_SetString(err,errmess);1160}1161return 0;1162}1163"""116411651166needs['complex_float_from_pyobj'] = [1167'complex_float', 'complex_double_from_pyobj']1168cfuncs['complex_float_from_pyobj'] = """\1169static int1170complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess)1171{1172complex_double cd={0.0,0.0};1173if (complex_double_from_pyobj(&cd,obj,errmess)) {1174(*v).r = (float)cd.r;1175(*v).i = (float)cd.i;1176return 1;1177}1178return 0;1179}1180"""118111821183needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE']1184cfuncs[1185'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n'1186needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char']1187cfuncs[1188'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n'1189needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char']1190cfuncs[1191'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n'1192needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE']1193cfuncs[1194'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n'1195needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE']1196cfuncs[1197'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n'1198needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE']1199cfuncs[1200'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n'1201needs['try_pyarr_from_long_long'] = [1202'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long']1203cfuncs[1204'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n'1205needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE']1206cfuncs[1207'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n'1208needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE']1209cfuncs[1210'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n'1211needs['try_pyarr_from_complex_float'] = [1212'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float']1213cfuncs[1214'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n'1215needs['try_pyarr_from_complex_double'] = [1216'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double']1217cfuncs[1218'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n'121912201221needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX']1222# create the list of arguments to be used when calling back to python1223cfuncs['create_cb_arglist'] = """\1224static int1225create_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs,1226const int nofoptargs, int *nofargs, PyTupleObject **args,1227const char *errmess)1228{1229PyObject *tmp = NULL;1230PyObject *tmp_fun = NULL;1231Py_ssize_t tot, opt, ext, siz, i, di = 0;1232CFUNCSMESS(\"create_cb_arglist\\n\");1233tot=opt=ext=siz=0;1234/* Get the total number of arguments */1235if (PyFunction_Check(fun)) {1236tmp_fun = fun;1237Py_INCREF(tmp_fun);1238}1239else {1240di = 1;1241if (PyObject_HasAttrString(fun,\"im_func\")) {1242tmp_fun = PyObject_GetAttrString(fun,\"im_func\");1243}1244else if (PyObject_HasAttrString(fun,\"__call__\")) {1245tmp = PyObject_GetAttrString(fun,\"__call__\");1246if (PyObject_HasAttrString(tmp,\"im_func\"))1247tmp_fun = PyObject_GetAttrString(tmp,\"im_func\");1248else {1249tmp_fun = fun; /* built-in function */1250Py_INCREF(tmp_fun);1251tot = maxnofargs;1252if (PyCFunction_Check(fun)) {1253/* In case the function has a co_argcount (like on PyPy) */1254di = 0;1255}1256if (xa != NULL)1257tot += PyTuple_Size((PyObject *)xa);1258}1259Py_XDECREF(tmp);1260}1261else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) {1262tot = maxnofargs;1263if (xa != NULL)1264tot += PyTuple_Size((PyObject *)xa);1265tmp_fun = fun;1266Py_INCREF(tmp_fun);1267}1268else if (F2PyCapsule_Check(fun)) {1269tot = maxnofargs;1270if (xa != NULL)1271ext = PyTuple_Size((PyObject *)xa);1272if(ext>0) {1273fprintf(stderr,\"extra arguments tuple cannot be used with CObject call-back\\n\");1274goto capi_fail;1275}1276tmp_fun = fun;1277Py_INCREF(tmp_fun);1278}1279}12801281if (tmp_fun == NULL) {1282fprintf(stderr,1283\"Call-back argument must be function|instance|instance.__call__|f2py-function \"1284\"but got %s.\\n\",1285((fun == NULL) ? \"NULL\" : Py_TYPE(fun)->tp_name));1286goto capi_fail;1287}12881289if (PyObject_HasAttrString(tmp_fun,\"__code__\")) {1290if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) {1291PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\");1292Py_DECREF(tmp);1293if (tmp_argcount == NULL) {1294goto capi_fail;1295}1296tot = PyLong_AsSsize_t(tmp_argcount) - di;1297Py_DECREF(tmp_argcount);1298}1299}1300/* Get the number of optional arguments */1301if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) {1302if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\")))1303opt = PyTuple_Size(tmp);1304Py_XDECREF(tmp);1305}1306/* Get the number of extra arguments */1307if (xa != NULL)1308ext = PyTuple_Size((PyObject *)xa);1309/* Calculate the size of call-backs argument list */1310siz = MIN(maxnofargs+ext,tot);1311*nofargs = MAX(0,siz-ext);13121313#ifdef DEBUGCFUNCS1314fprintf(stderr,1315\"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),\"1316\"tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n\",1317maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs);1318#endif13191320if (siz < tot-opt) {1321fprintf(stderr,1322\"create_cb_arglist: Failed to build argument list \"1323\"(siz) with enough arguments (tot-opt) required by \"1324\"user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n\",1325siz, tot, opt);1326goto capi_fail;1327}13281329/* Initialize argument list */1330*args = (PyTupleObject *)PyTuple_New(siz);1331for (i=0;i<*nofargs;i++) {1332Py_INCREF(Py_None);1333PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None);1334}1335if (xa != NULL)1336for (i=(*nofargs);i<siz;i++) {1337tmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs));1338Py_INCREF(tmp);1339PyTuple_SET_ITEM(*args,i,tmp);1340}1341CFUNCSMESS(\"create_cb_arglist-end\\n\");1342Py_DECREF(tmp_fun);1343return 1;13441345capi_fail:1346if (PyErr_Occurred() == NULL)1347PyErr_SetString(#modulename#_error, errmess);1348Py_XDECREF(tmp_fun);1349return 0;1350}1351"""135213531354def buildcfuncs():1355from .capi_maps import c2capi_map1356for k in c2capi_map.keys():1357m = 'pyarr_from_p_%s1' % k1358cppmacros[1359m] = '#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))' % (m, c2capi_map[k])1360k = 'string'1361m = 'pyarr_from_p_%s1' % k1362# NPY_CHAR compatibility, NPY_STRING with itemsize 11363cppmacros[1364m] = '#define %s(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))' % (m)136513661367############ Auxiliary functions for sorting needs ###################13681369def append_needs(need, flag=1):1370# This function modifies the contents of the global `outneeds` dict.1371if isinstance(need, list):1372for n in need:1373append_needs(n, flag)1374elif isinstance(need, str):1375if not need:1376return1377if need in includes0:1378n = 'includes0'1379elif need in includes:1380n = 'includes'1381elif need in typedefs:1382n = 'typedefs'1383elif need in typedefs_generated:1384n = 'typedefs_generated'1385elif need in cppmacros:1386n = 'cppmacros'1387elif need in cfuncs:1388n = 'cfuncs'1389elif need in callbacks:1390n = 'callbacks'1391elif need in f90modhooks:1392n = 'f90modhooks'1393elif need in commonhooks:1394n = 'commonhooks'1395else:1396errmess('append_needs: unknown need %s\n' % (repr(need)))1397return1398if need in outneeds[n]:1399return1400if flag:1401tmp = {}1402if need in needs:1403for nn in needs[need]:1404t = append_needs(nn, 0)1405if isinstance(t, dict):1406for nnn in t.keys():1407if nnn in tmp:1408tmp[nnn] = tmp[nnn] + t[nnn]1409else:1410tmp[nnn] = t[nnn]1411for nn in tmp.keys():1412for nnn in tmp[nn]:1413if nnn not in outneeds[nn]:1414outneeds[nn] = [nnn] + outneeds[nn]1415outneeds[n].append(need)1416else:1417tmp = {}1418if need in needs:1419for nn in needs[need]:1420t = append_needs(nn, flag)1421if isinstance(t, dict):1422for nnn in t.keys():1423if nnn in tmp:1424tmp[nnn] = t[nnn] + tmp[nnn]1425else:1426tmp[nnn] = t[nnn]1427if n not in tmp:1428tmp[n] = []1429tmp[n].append(need)1430return tmp1431else:1432errmess('append_needs: expected list or string but got :%s\n' %1433(repr(need)))143414351436def get_needs():1437# This function modifies the contents of the global `outneeds` dict.1438res = {}1439for n in outneeds.keys():1440out = []1441saveout = copy.copy(outneeds[n])1442while len(outneeds[n]) > 0:1443if outneeds[n][0] not in needs:1444out.append(outneeds[n][0])1445del outneeds[n][0]1446else:1447flag = 01448for k in outneeds[n][1:]:1449if k in needs[outneeds[n][0]]:1450flag = 11451break1452if flag:1453outneeds[n] = outneeds[n][1:] + [outneeds[n][0]]1454else:1455out.append(outneeds[n][0])1456del outneeds[n][0]1457if saveout and (0 not in map(lambda x, y: x == y, saveout, outneeds[n])) \1458and outneeds[n] != []:1459print(n, saveout)1460errmess(1461'get_needs: no progress in sorting needs, probably circular dependence, skipping.\n')1462out = out + saveout1463break1464saveout = copy.copy(outneeds[n])1465if out == []:1466out = [n]1467res[n] = out1468return res146914701471