Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
wiseplat
GitHub Repository: wiseplat/python-code
Path: blob/master/ invest-robot-contest_TinkoffBotTwitch-main/venv/lib/python3.8/site-packages/numpy/f2py/cfuncs.py
7757 views
1
#!/usr/bin/env python3
2
"""
3
4
C declarations, CPP macros, and C functions for f2py2e.
5
Only required declarations/macros/functions will be used.
6
7
Copyright 1999,2000 Pearu Peterson all rights reserved,
8
Pearu Peterson <[email protected]>
9
Permission to use, modify, and distribute this software is given under the
10
terms of the NumPy License.
11
12
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
13
$Date: 2005/05/06 11:42:34 $
14
Pearu Peterson
15
16
"""
17
import sys
18
import copy
19
20
from . import __version__
21
22
f2py_version = __version__.version
23
errmess = sys.stderr.write
24
25
##################### Definitions ##################
26
27
outneeds = {'includes0': [], 'includes': [], 'typedefs': [], 'typedefs_generated': [],
28
'userincludes': [],
29
'cppmacros': [], 'cfuncs': [], 'callbacks': [], 'f90modhooks': [],
30
'commonhooks': []}
31
needs = {}
32
includes0 = {'includes0': '/*need_includes0*/'}
33
includes = {'includes': '/*need_includes*/'}
34
userincludes = {'userincludes': '/*need_userincludes*/'}
35
typedefs = {'typedefs': '/*need_typedefs*/'}
36
typedefs_generated = {'typedefs_generated': '/*need_typedefs_generated*/'}
37
cppmacros = {'cppmacros': '/*need_cppmacros*/'}
38
cfuncs = {'cfuncs': '/*need_cfuncs*/'}
39
callbacks = {'callbacks': '/*need_callbacks*/'}
40
f90modhooks = {'f90modhooks': '/*need_f90modhooks*/',
41
'initf90modhooksstatic': '/*initf90modhooksstatic*/',
42
'initf90modhooksdynamic': '/*initf90modhooksdynamic*/',
43
}
44
commonhooks = {'commonhooks': '/*need_commonhooks*/',
45
'initcommonhooks': '/*need_initcommonhooks*/',
46
}
47
48
############ Includes ###################
49
50
includes0['math.h'] = '#include <math.h>'
51
includes0['string.h'] = '#include <string.h>'
52
includes0['setjmp.h'] = '#include <setjmp.h>'
53
54
includes['Python.h'] = '#include <Python.h>'
55
needs['arrayobject.h'] = ['Python.h']
56
includes['arrayobject.h'] = '''#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API
57
#include "arrayobject.h"'''
58
59
includes['arrayobject.h'] = '#include "fortranobject.h"'
60
includes['stdarg.h'] = '#include <stdarg.h>'
61
62
############# Type definitions ###############
63
64
typedefs['unsigned_char'] = 'typedef unsigned char unsigned_char;'
65
typedefs['unsigned_short'] = 'typedef unsigned short unsigned_short;'
66
typedefs['unsigned_long'] = 'typedef unsigned long unsigned_long;'
67
typedefs['signed_char'] = 'typedef signed char signed_char;'
68
typedefs['long_long'] = """\
69
#ifdef _WIN32
70
typedef __int64 long_long;
71
#else
72
typedef long long long_long;
73
typedef unsigned long long unsigned_long_long;
74
#endif
75
"""
76
typedefs['unsigned_long_long'] = """\
77
#ifdef _WIN32
78
typedef __uint64 long_long;
79
#else
80
typedef unsigned long long unsigned_long_long;
81
#endif
82
"""
83
typedefs['long_double'] = """\
84
#ifndef _LONG_DOUBLE
85
typedef long double long_double;
86
#endif
87
"""
88
typedefs[
89
'complex_long_double'] = 'typedef struct {long double r,i;} complex_long_double;'
90
typedefs['complex_float'] = 'typedef struct {float r,i;} complex_float;'
91
typedefs['complex_double'] = 'typedef struct {double r,i;} complex_double;'
92
typedefs['string'] = """typedef char * string;"""
93
94
95
############### CPP macros ####################
96
cppmacros['CFUNCSMESS'] = """\
97
#ifdef DEBUGCFUNCS
98
#define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess);
99
#define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\
100
PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
101
fprintf(stderr,\"\\n\");
102
#else
103
#define CFUNCSMESS(mess)
104
#define CFUNCSMESSPY(mess,obj)
105
#endif
106
"""
107
cppmacros['F_FUNC'] = """\
108
#if defined(PREPEND_FORTRAN)
109
#if defined(NO_APPEND_FORTRAN)
110
#if defined(UPPERCASE_FORTRAN)
111
#define F_FUNC(f,F) _##F
112
#else
113
#define F_FUNC(f,F) _##f
114
#endif
115
#else
116
#if defined(UPPERCASE_FORTRAN)
117
#define F_FUNC(f,F) _##F##_
118
#else
119
#define F_FUNC(f,F) _##f##_
120
#endif
121
#endif
122
#else
123
#if defined(NO_APPEND_FORTRAN)
124
#if defined(UPPERCASE_FORTRAN)
125
#define F_FUNC(f,F) F
126
#else
127
#define F_FUNC(f,F) f
128
#endif
129
#else
130
#if defined(UPPERCASE_FORTRAN)
131
#define F_FUNC(f,F) F##_
132
#else
133
#define F_FUNC(f,F) f##_
134
#endif
135
#endif
136
#endif
137
#if defined(UNDERSCORE_G77)
138
#define F_FUNC_US(f,F) F_FUNC(f##_,F##_)
139
#else
140
#define F_FUNC_US(f,F) F_FUNC(f,F)
141
#endif
142
"""
143
cppmacros['F_WRAPPEDFUNC'] = """\
144
#if defined(PREPEND_FORTRAN)
145
#if defined(NO_APPEND_FORTRAN)
146
#if defined(UPPERCASE_FORTRAN)
147
#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F
148
#else
149
#define F_WRAPPEDFUNC(f,F) _f2pywrap##f
150
#endif
151
#else
152
#if defined(UPPERCASE_FORTRAN)
153
#define F_WRAPPEDFUNC(f,F) _F2PYWRAP##F##_
154
#else
155
#define F_WRAPPEDFUNC(f,F) _f2pywrap##f##_
156
#endif
157
#endif
158
#else
159
#if defined(NO_APPEND_FORTRAN)
160
#if defined(UPPERCASE_FORTRAN)
161
#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F
162
#else
163
#define F_WRAPPEDFUNC(f,F) f2pywrap##f
164
#endif
165
#else
166
#if defined(UPPERCASE_FORTRAN)
167
#define F_WRAPPEDFUNC(f,F) F2PYWRAP##F##_
168
#else
169
#define F_WRAPPEDFUNC(f,F) f2pywrap##f##_
170
#endif
171
#endif
172
#endif
173
#if defined(UNDERSCORE_G77)
174
#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f##_,F##_)
175
#else
176
#define F_WRAPPEDFUNC_US(f,F) F_WRAPPEDFUNC(f,F)
177
#endif
178
"""
179
cppmacros['F_MODFUNC'] = """\
180
#if defined(F90MOD2CCONV1) /*E.g. Compaq Fortran */
181
#if defined(NO_APPEND_FORTRAN)
182
#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f
183
#else
184
#define F_MODFUNCNAME(m,f) $ ## m ## $ ## f ## _
185
#endif
186
#endif
187
188
#if defined(F90MOD2CCONV2) /*E.g. IBM XL Fortran, not tested though */
189
#if defined(NO_APPEND_FORTRAN)
190
#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f
191
#else
192
#define F_MODFUNCNAME(m,f) __ ## m ## _MOD_ ## f ## _
193
#endif
194
#endif
195
196
#if defined(F90MOD2CCONV3) /*E.g. MIPSPro Compilers */
197
#if defined(NO_APPEND_FORTRAN)
198
#define F_MODFUNCNAME(m,f) f ## .in. ## m
199
#else
200
#define F_MODFUNCNAME(m,f) f ## .in. ## m ## _
201
#endif
202
#endif
203
/*
204
#if defined(UPPERCASE_FORTRAN)
205
#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(M,F)
206
#else
207
#define F_MODFUNC(m,M,f,F) F_MODFUNCNAME(m,f)
208
#endif
209
*/
210
211
#define F_MODFUNC(m,f) (*(f2pymodstruct##m##.##f))
212
"""
213
cppmacros['SWAPUNSAFE'] = """\
214
#define SWAP(a,b) (size_t)(a) = ((size_t)(a) ^ (size_t)(b));\\
215
(size_t)(b) = ((size_t)(a) ^ (size_t)(b));\\
216
(size_t)(a) = ((size_t)(a) ^ (size_t)(b))
217
"""
218
cppmacros['SWAP'] = """\
219
#define SWAP(a,b,t) {\\
220
t *c;\\
221
c = a;\\
222
a = b;\\
223
b = c;}
224
"""
225
# cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) &
226
# NPY_ARRAY_C_CONTIGUOUS)'
227
cppmacros['PRINTPYOBJERR'] = """\
228
#define PRINTPYOBJERR(obj)\\
229
fprintf(stderr,\"#modulename#.error is related to \");\\
230
PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\
231
fprintf(stderr,\"\\n\");
232
"""
233
cppmacros['MINMAX'] = """\
234
#ifndef max
235
#define max(a,b) ((a > b) ? (a) : (b))
236
#endif
237
#ifndef min
238
#define min(a,b) ((a < b) ? (a) : (b))
239
#endif
240
#ifndef MAX
241
#define MAX(a,b) ((a > b) ? (a) : (b))
242
#endif
243
#ifndef MIN
244
#define MIN(a,b) ((a < b) ? (a) : (b))
245
#endif
246
"""
247
needs['len..'] = ['f2py_size']
248
cppmacros['len..'] = """\
249
#define rank(var) var ## _Rank
250
#define shape(var,dim) var ## _Dims[dim]
251
#define old_rank(var) (PyArray_NDIM((PyArrayObject *)(capi_ ## var ## _tmp)))
252
#define old_shape(var,dim) PyArray_DIM(((PyArrayObject *)(capi_ ## var ## _tmp)),dim)
253
#define fshape(var,dim) shape(var,rank(var)-dim-1)
254
#define len(var) shape(var,0)
255
#define flen(var) fshape(var,0)
256
#define old_size(var) PyArray_SIZE((PyArrayObject *)(capi_ ## var ## _tmp))
257
/* #define index(i) capi_i ## i */
258
#define slen(var) capi_ ## var ## _len
259
#define size(var, ...) f2py_size((PyArrayObject *)(capi_ ## var ## _tmp), ## __VA_ARGS__, -1)
260
"""
261
needs['f2py_size'] = ['stdarg.h']
262
cfuncs['f2py_size'] = """\
263
static int f2py_size(PyArrayObject* var, ...)
264
{
265
npy_int sz = 0;
266
npy_int dim;
267
npy_int rank;
268
va_list argp;
269
va_start(argp, var);
270
dim = va_arg(argp, npy_int);
271
if (dim==-1)
272
{
273
sz = PyArray_SIZE(var);
274
}
275
else
276
{
277
rank = PyArray_NDIM(var);
278
if (dim>=1 && dim<=rank)
279
sz = PyArray_DIM(var, dim-1);
280
else
281
fprintf(stderr, \"f2py_size: 2nd argument value=%d fails to satisfy 1<=value<=%d. Result will be 0.\\n\", dim, rank);
282
}
283
va_end(argp);
284
return sz;
285
}
286
"""
287
288
cppmacros[
289
'pyobj_from_char1'] = '#define pyobj_from_char1(v) (PyLong_FromLong(v))'
290
cppmacros[
291
'pyobj_from_short1'] = '#define pyobj_from_short1(v) (PyLong_FromLong(v))'
292
needs['pyobj_from_int1'] = ['signed_char']
293
cppmacros['pyobj_from_int1'] = '#define pyobj_from_int1(v) (PyLong_FromLong(v))'
294
cppmacros[
295
'pyobj_from_long1'] = '#define pyobj_from_long1(v) (PyLong_FromLong(v))'
296
needs['pyobj_from_long_long1'] = ['long_long']
297
cppmacros['pyobj_from_long_long1'] = """\
298
#ifdef HAVE_LONG_LONG
299
#define pyobj_from_long_long1(v) (PyLong_FromLongLong(v))
300
#else
301
#warning HAVE_LONG_LONG is not available. Redefining pyobj_from_long_long.
302
#define pyobj_from_long_long1(v) (PyLong_FromLong(v))
303
#endif
304
"""
305
needs['pyobj_from_long_double1'] = ['long_double']
306
cppmacros[
307
'pyobj_from_long_double1'] = '#define pyobj_from_long_double1(v) (PyFloat_FromDouble(v))'
308
cppmacros[
309
'pyobj_from_double1'] = '#define pyobj_from_double1(v) (PyFloat_FromDouble(v))'
310
cppmacros[
311
'pyobj_from_float1'] = '#define pyobj_from_float1(v) (PyFloat_FromDouble(v))'
312
needs['pyobj_from_complex_long_double1'] = ['complex_long_double']
313
cppmacros[
314
'pyobj_from_complex_long_double1'] = '#define pyobj_from_complex_long_double1(v) (PyComplex_FromDoubles(v.r,v.i))'
315
needs['pyobj_from_complex_double1'] = ['complex_double']
316
cppmacros[
317
'pyobj_from_complex_double1'] = '#define pyobj_from_complex_double1(v) (PyComplex_FromDoubles(v.r,v.i))'
318
needs['pyobj_from_complex_float1'] = ['complex_float']
319
cppmacros[
320
'pyobj_from_complex_float1'] = '#define pyobj_from_complex_float1(v) (PyComplex_FromDoubles(v.r,v.i))'
321
needs['pyobj_from_string1'] = ['string']
322
cppmacros[
323
'pyobj_from_string1'] = '#define pyobj_from_string1(v) (PyUnicode_FromString((char *)v))'
324
needs['pyobj_from_string1size'] = ['string']
325
cppmacros[
326
'pyobj_from_string1size'] = '#define pyobj_from_string1size(v,len) (PyUnicode_FromStringAndSize((char *)v, len))'
327
needs['TRYPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
328
cppmacros['TRYPYARRAYTEMPLATE'] = """\
329
/* New SciPy */
330
#define TRYPYARRAYTEMPLATECHAR case NPY_STRING: *(char *)(PyArray_DATA(arr))=*v; break;
331
#define TRYPYARRAYTEMPLATELONG case NPY_LONG: *(long *)(PyArray_DATA(arr))=*v; break;
332
#define TRYPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr,PyArray_DATA(arr),pyobj_from_ ## ctype ## 1(*v)); break;
333
334
#define TRYPYARRAYTEMPLATE(ctype,typecode) \\
335
PyArrayObject *arr = NULL;\\
336
if (!obj) return -2;\\
337
if (!PyArray_Check(obj)) return -1;\\
338
if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
339
if (PyArray_DESCR(arr)->type==typecode) {*(ctype *)(PyArray_DATA(arr))=*v; return 1;}\\
340
switch (PyArray_TYPE(arr)) {\\
341
case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\
342
case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=*v; break;\\
343
case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=*v; break;\\
344
case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\
345
case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=*v; break;\\
346
case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=*v; break;\\
347
case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=(*v!=0); break;\\
348
case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=*v; break;\\
349
case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=*v; break;\\
350
case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=*v; break;\\
351
case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=*v; break;\\
352
case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=*v; break;\\
353
case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=*v; break;\\
354
case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=*v; break;\\
355
case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=*v; break;\\
356
case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
357
case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=*v; break;\\
358
case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_ ## ctype ## 1(*v)); break;\\
359
default: return -2;\\
360
};\\
361
return 1
362
"""
363
364
needs['TRYCOMPLEXPYARRAYTEMPLATE'] = ['PRINTPYOBJERR']
365
cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """\
366
#define TRYCOMPLEXPYARRAYTEMPLATEOBJECT case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;
367
#define TRYCOMPLEXPYARRAYTEMPLATE(ctype,typecode)\\
368
PyArrayObject *arr = NULL;\\
369
if (!obj) return -2;\\
370
if (!PyArray_Check(obj)) return -1;\\
371
if (!(arr=(PyArrayObject *)obj)) {fprintf(stderr,\"TRYCOMPLEXPYARRAYTEMPLATE:\");PRINTPYOBJERR(obj);return 0;}\\
372
if (PyArray_DESCR(arr)->type==typecode) {\\
373
*(ctype *)(PyArray_DATA(arr))=(*v).r;\\
374
*(ctype *)(PyArray_DATA(arr)+sizeof(ctype))=(*v).i;\\
375
return 1;\\
376
}\\
377
switch (PyArray_TYPE(arr)) {\\
378
case NPY_CDOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r;\\
379
*(npy_double *)(PyArray_DATA(arr)+sizeof(npy_double))=(*v).i;\\
380
break;\\
381
case NPY_CFLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r;\\
382
*(npy_float *)(PyArray_DATA(arr)+sizeof(npy_float))=(*v).i;\\
383
break;\\
384
case NPY_DOUBLE: *(npy_double *)(PyArray_DATA(arr))=(*v).r; break;\\
385
case NPY_LONG: *(npy_long *)(PyArray_DATA(arr))=(*v).r; break;\\
386
case NPY_FLOAT: *(npy_float *)(PyArray_DATA(arr))=(*v).r; break;\\
387
case NPY_INT: *(npy_int *)(PyArray_DATA(arr))=(*v).r; break;\\
388
case NPY_SHORT: *(npy_short *)(PyArray_DATA(arr))=(*v).r; break;\\
389
case NPY_UBYTE: *(npy_ubyte *)(PyArray_DATA(arr))=(*v).r; break;\\
390
case NPY_BYTE: *(npy_byte *)(PyArray_DATA(arr))=(*v).r; break;\\
391
case NPY_BOOL: *(npy_bool *)(PyArray_DATA(arr))=((*v).r!=0 && (*v).i!=0); break;\\
392
case NPY_USHORT: *(npy_ushort *)(PyArray_DATA(arr))=(*v).r; break;\\
393
case NPY_UINT: *(npy_uint *)(PyArray_DATA(arr))=(*v).r; break;\\
394
case NPY_ULONG: *(npy_ulong *)(PyArray_DATA(arr))=(*v).r; break;\\
395
case NPY_LONGLONG: *(npy_longlong *)(PyArray_DATA(arr))=(*v).r; break;\\
396
case NPY_ULONGLONG: *(npy_ulonglong *)(PyArray_DATA(arr))=(*v).r; break;\\
397
case NPY_LONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r; break;\\
398
case NPY_CLONGDOUBLE: *(npy_longdouble *)(PyArray_DATA(arr))=(*v).r;\\
399
*(npy_longdouble *)(PyArray_DATA(arr)+sizeof(npy_longdouble))=(*v).i;\\
400
break;\\
401
case NPY_OBJECT: PyArray_SETITEM(arr, PyArray_DATA(arr), pyobj_from_complex_ ## ctype ## 1((*v))); break;\\
402
default: return -2;\\
403
};\\
404
return -1;
405
"""
406
# cppmacros['NUMFROMARROBJ']="""\
407
# define NUMFROMARROBJ(typenum,ctype) \\
408
# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
409
# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
410
# if (arr) {\\
411
# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
412
# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
413
# goto capi_fail;\\
414
# } else {\\
415
# (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\
416
# }\\
417
# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
418
# return 1;\\
419
# }
420
# """
421
# XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ
422
# cppmacros['CNUMFROMARROBJ']="""\
423
# define CNUMFROMARROBJ(typenum,ctype) \\
424
# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\
425
# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\
426
# if (arr) {\\
427
# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\
428
# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\
429
# goto capi_fail;\\
430
# } else {\\
431
# (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\
432
# }\\
433
# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\
434
# return 1;\\
435
# }
436
# """
437
438
439
needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR']
440
cppmacros['GETSTRFROMPYTUPLE'] = """\
441
#define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\
442
PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\
443
if (rv_cb_str == NULL)\\
444
goto capi_fail;\\
445
if (PyBytes_Check(rv_cb_str)) {\\
446
str[len-1]='\\0';\\
447
STRINGCOPYN((str),PyBytes_AS_STRING((PyBytesObject*)rv_cb_str),(len));\\
448
} else {\\
449
PRINTPYOBJERR(rv_cb_str);\\
450
PyErr_SetString(#modulename#_error,\"string object expected\");\\
451
goto capi_fail;\\
452
}\\
453
}
454
"""
455
cppmacros['GETSCALARFROMPYTUPLE'] = """\
456
#define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\
457
if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\
458
if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\
459
goto capi_fail;\\
460
}
461
"""
462
463
cppmacros['FAILNULL'] = """\\
464
#define FAILNULL(p) do { \\
465
if ((p) == NULL) { \\
466
PyErr_SetString(PyExc_MemoryError, "NULL pointer found"); \\
467
goto capi_fail; \\
468
} \\
469
} while (0)
470
"""
471
needs['MEMCOPY'] = ['string.h', 'FAILNULL']
472
cppmacros['MEMCOPY'] = """\
473
#define MEMCOPY(to,from,n)\\
474
do { FAILNULL(to); FAILNULL(from); (void)memcpy(to,from,n); } while (0)
475
"""
476
cppmacros['STRINGMALLOC'] = """\
477
#define STRINGMALLOC(str,len)\\
478
if ((str = (string)malloc(len+1)) == NULL) {\\
479
PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\
480
goto capi_fail;\\
481
} else {\\
482
(str)[len] = '\\0';\\
483
}
484
"""
485
cppmacros['STRINGFREE'] = """\
486
#define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0)
487
"""
488
needs['STRINGPADN'] = ['string.h']
489
cppmacros['STRINGPADN'] = """\
490
/*
491
STRINGPADN replaces null values with padding values from the right.
492
493
`to` must have size of at least N bytes.
494
495
If the `to[N-1]` has null value, then replace it and all the
496
preceding, nulls with the given padding.
497
498
STRINGPADN(to, N, PADDING, NULLVALUE) is an inverse operation.
499
*/
500
#define STRINGPADN(to, N, NULLVALUE, PADDING) \\
501
do { \\
502
int _m = (N); \\
503
char *_to = (to); \\
504
for (_m -= 1; _m >= 0 && _to[_m] == NULLVALUE; _m--) { \\
505
_to[_m] = PADDING; \\
506
} \\
507
} while (0)
508
"""
509
needs['STRINGCOPYN'] = ['string.h', 'FAILNULL']
510
cppmacros['STRINGCOPYN'] = """\
511
/*
512
STRINGCOPYN copies N bytes.
513
514
`to` and `from` buffers must have sizes of at least N bytes.
515
*/
516
#define STRINGCOPYN(to,from,N) \\
517
do { \\
518
int _m = (N); \\
519
char *_to = (to); \\
520
char *_from = (from); \\
521
FAILNULL(_to); FAILNULL(_from); \\
522
(void)strncpy(_to, _from, _m); \\
523
} while (0)
524
"""
525
needs['STRINGCOPY'] = ['string.h', 'FAILNULL']
526
cppmacros['STRINGCOPY'] = """\
527
#define STRINGCOPY(to,from)\\
528
do { FAILNULL(to); FAILNULL(from); (void)strcpy(to,from); } while (0)
529
"""
530
cppmacros['CHECKGENERIC'] = """\
531
#define CHECKGENERIC(check,tcheck,name) \\
532
if (!(check)) {\\
533
PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
534
/*goto capi_fail;*/\\
535
} else """
536
cppmacros['CHECKARRAY'] = """\
537
#define CHECKARRAY(check,tcheck,name) \\
538
if (!(check)) {\\
539
PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\
540
/*goto capi_fail;*/\\
541
} else """
542
cppmacros['CHECKSTRING'] = """\
543
#define CHECKSTRING(check,tcheck,name,show,var)\\
544
if (!(check)) {\\
545
char errstring[256];\\
546
sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\
547
PyErr_SetString(#modulename#_error, errstring);\\
548
/*goto capi_fail;*/\\
549
} else """
550
cppmacros['CHECKSCALAR'] = """\
551
#define CHECKSCALAR(check,tcheck,name,show,var)\\
552
if (!(check)) {\\
553
char errstring[256];\\
554
sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\
555
PyErr_SetString(#modulename#_error,errstring);\\
556
/*goto capi_fail;*/\\
557
} else """
558
# cppmacros['CHECKDIMS']="""\
559
# define CHECKDIMS(dims,rank) \\
560
# for (int i=0;i<(rank);i++)\\
561
# if (dims[i]<0) {\\
562
# fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\
563
# goto capi_fail;\\
564
# }
565
# """
566
cppmacros[
567
'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))'
568
cppmacros['OLDPYNUM'] = """\
569
#ifdef OLDPYNUM
570
#error You need to install NumPy version 0.13 or higher. See https://scipy.org/install.html
571
#endif
572
"""
573
cppmacros["F2PY_THREAD_LOCAL_DECL"] = """\
574
#ifndef F2PY_THREAD_LOCAL_DECL
575
#if defined(_MSC_VER)
576
#define F2PY_THREAD_LOCAL_DECL __declspec(thread)
577
#elif defined(__MINGW32__) || defined(__MINGW64__)
578
#define F2PY_THREAD_LOCAL_DECL __thread
579
#elif defined(__STDC_VERSION__) \\
580
&& (__STDC_VERSION__ >= 201112L) \\
581
&& !defined(__STDC_NO_THREADS__) \\
582
&& (!defined(__GLIBC__) || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 12)) \\
583
&& !defined(__OpenBSD__)
584
/* __STDC_NO_THREADS__ was first defined in a maintenance release of glibc 2.12,
585
see https://lists.gnu.org/archive/html/commit-hurd/2012-07/msg00180.html,
586
so `!defined(__STDC_NO_THREADS__)` may give false positive for the existence
587
of `threads.h` when using an older release of glibc 2.12
588
See gh-19437 for details on OpenBSD */
589
#include <threads.h>
590
#define F2PY_THREAD_LOCAL_DECL thread_local
591
#elif defined(__GNUC__) \\
592
&& (__GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 4)))
593
#define F2PY_THREAD_LOCAL_DECL __thread
594
#endif
595
#endif
596
"""
597
################# C functions ###############
598
599
cfuncs['calcarrindex'] = """\
600
static int calcarrindex(int *i,PyArrayObject *arr) {
601
int k,ii = i[0];
602
for (k=1; k < PyArray_NDIM(arr); k++)
603
ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */
604
return ii;
605
}"""
606
cfuncs['calcarrindextr'] = """\
607
static int calcarrindextr(int *i,PyArrayObject *arr) {
608
int k,ii = i[PyArray_NDIM(arr)-1];
609
for (k=1; k < PyArray_NDIM(arr); k++)
610
ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */
611
return ii;
612
}"""
613
cfuncs['forcomb'] = """\
614
static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;
615
static int initforcomb(npy_intp *dims,int nd,int tr) {
616
int k;
617
if (dims==NULL) return 0;
618
if (nd<0) return 0;
619
forcombcache.nd = nd;
620
forcombcache.d = dims;
621
forcombcache.tr = tr;
622
if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
623
if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
624
for (k=1;k<nd;k++) {
625
forcombcache.i[k] = forcombcache.i_tr[nd-k-1] = 0;
626
}
627
forcombcache.i[0] = forcombcache.i_tr[nd-1] = -1;
628
return 1;
629
}
630
static int *nextforcomb(void) {
631
int j,*i,*i_tr,k;
632
int nd=forcombcache.nd;
633
if ((i=forcombcache.i) == NULL) return NULL;
634
if ((i_tr=forcombcache.i_tr) == NULL) return NULL;
635
if (forcombcache.d == NULL) return NULL;
636
i[0]++;
637
if (i[0]==forcombcache.d[0]) {
638
j=1;
639
while ((j<nd) && (i[j]==forcombcache.d[j]-1)) j++;
640
if (j==nd) {
641
free(i);
642
free(i_tr);
643
return NULL;
644
}
645
for (k=0;k<j;k++) i[k] = i_tr[nd-k-1] = 0;
646
i[j]++;
647
i_tr[nd-j-1]++;
648
} else
649
i_tr[nd-1]++;
650
if (forcombcache.tr) return i_tr;
651
return i;
652
}"""
653
needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string']
654
cfuncs['try_pyarr_from_string'] = """\
655
/*
656
try_pyarr_from_string copies str[:len(obj)] to the data of an `ndarray`.
657
658
If obj is an `ndarray`, it is assumed to be contiguous.
659
660
If the specified len==-1, str must be null-terminated.
661
*/
662
static int try_pyarr_from_string(PyObject *obj,
663
const string str, const int len) {
664
#ifdef DEBUGCFUNCS
665
fprintf(stderr, "try_pyarr_from_string(str='%s', len=%d, obj=%p)\\n",
666
(char*)str,len, obj);
667
#endif
668
if (PyArray_Check(obj)) {
669
PyArrayObject *arr = (PyArrayObject *)obj;
670
assert(ISCONTIGUOUS(arr));
671
string buf = PyArray_DATA(arr);
672
npy_intp n = len;
673
if (n == -1) {
674
/* Assuming null-terminated str. */
675
n = strlen(str);
676
}
677
if (n > PyArray_NBYTES(arr)) {
678
n = PyArray_NBYTES(arr);
679
}
680
STRINGCOPYN(buf, str, n);
681
return 1;
682
}
683
capi_fail:
684
PRINTPYOBJERR(obj);
685
PyErr_SetString(#modulename#_error, \"try_pyarr_from_string failed\");
686
return 0;
687
}
688
"""
689
needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN']
690
cfuncs['string_from_pyobj'] = """\
691
/*
692
Create a new string buffer `str` of at most length `len` from a
693
Python string-like object `obj`.
694
695
The string buffer has given size (len) or the size of inistr when len==-1.
696
697
The string buffer is padded with blanks: in Fortran, trailing blanks
698
are insignificant contrary to C nulls.
699
*/
700
static int
701
string_from_pyobj(string *str, int *len, const string inistr, PyObject *obj,
702
const char *errmess)
703
{
704
PyObject *tmp = NULL;
705
string buf = NULL;
706
npy_intp n = -1;
707
#ifdef DEBUGCFUNCS
708
fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",
709
(char*)str, *len, (char *)inistr, obj);
710
#endif
711
if (obj == Py_None) {
712
n = strlen(inistr);
713
buf = inistr;
714
}
715
else if (PyArray_Check(obj)) {
716
PyArrayObject *arr = (PyArrayObject *)obj;
717
if (!ISCONTIGUOUS(arr)) {
718
PyErr_SetString(PyExc_ValueError,
719
\"array object is non-contiguous.\");
720
goto capi_fail;
721
}
722
n = PyArray_NBYTES(arr);
723
buf = PyArray_DATA(arr);
724
n = strnlen(buf, n);
725
}
726
else {
727
if (PyBytes_Check(obj)) {
728
tmp = obj;
729
Py_INCREF(tmp);
730
}
731
else if (PyUnicode_Check(obj)) {
732
tmp = PyUnicode_AsASCIIString(obj);
733
}
734
else {
735
PyObject *tmp2;
736
tmp2 = PyObject_Str(obj);
737
if (tmp2) {
738
tmp = PyUnicode_AsASCIIString(tmp2);
739
Py_DECREF(tmp2);
740
}
741
else {
742
tmp = NULL;
743
}
744
}
745
if (tmp == NULL) goto capi_fail;
746
n = PyBytes_GET_SIZE(tmp);
747
buf = PyBytes_AS_STRING(tmp);
748
}
749
if (*len == -1) {
750
/* TODO: change the type of `len` so that we can remove this */
751
if (n > NPY_MAX_INT) {
752
PyErr_SetString(PyExc_OverflowError,
753
"object too large for a 32-bit int");
754
goto capi_fail;
755
}
756
*len = n;
757
}
758
else if (*len < n) {
759
/* discard the last (len-n) bytes of input buf */
760
n = *len;
761
}
762
if (n < 0 || *len < 0 || buf == NULL) {
763
goto capi_fail;
764
}
765
STRINGMALLOC(*str, *len); // *str is allocated with size (*len + 1)
766
if (n < *len) {
767
/*
768
Pad fixed-width string with nulls. The caller will replace
769
nulls with blanks when the corresponding argument is not
770
intent(c).
771
*/
772
memset(*str + n, '\\0', *len - n);
773
}
774
STRINGCOPYN(*str, buf, n);
775
Py_XDECREF(tmp);
776
return 1;
777
capi_fail:
778
Py_XDECREF(tmp);
779
{
780
PyObject* err = PyErr_Occurred();
781
if (err == NULL) {
782
err = #modulename#_error;
783
}
784
PyErr_SetString(err, errmess);
785
}
786
return 0;
787
}
788
"""
789
790
needs['char_from_pyobj'] = ['int_from_pyobj']
791
cfuncs['char_from_pyobj'] = """\
792
static int
793
char_from_pyobj(char* v, PyObject *obj, const char *errmess) {
794
int i = 0;
795
if (int_from_pyobj(&i, obj, errmess)) {
796
*v = (char)i;
797
return 1;
798
}
799
return 0;
800
}
801
"""
802
803
804
needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char']
805
cfuncs['signed_char_from_pyobj'] = """\
806
static int
807
signed_char_from_pyobj(signed_char* v, PyObject *obj, const char *errmess) {
808
int i = 0;
809
if (int_from_pyobj(&i, obj, errmess)) {
810
*v = (signed_char)i;
811
return 1;
812
}
813
return 0;
814
}
815
"""
816
817
818
needs['short_from_pyobj'] = ['int_from_pyobj']
819
cfuncs['short_from_pyobj'] = """\
820
static int
821
short_from_pyobj(short* v, PyObject *obj, const char *errmess) {
822
int i = 0;
823
if (int_from_pyobj(&i, obj, errmess)) {
824
*v = (short)i;
825
return 1;
826
}
827
return 0;
828
}
829
"""
830
831
832
cfuncs['int_from_pyobj'] = """\
833
static int
834
int_from_pyobj(int* v, PyObject *obj, const char *errmess)
835
{
836
PyObject* tmp = NULL;
837
838
if (PyLong_Check(obj)) {
839
*v = Npy__PyLong_AsInt(obj);
840
return !(*v == -1 && PyErr_Occurred());
841
}
842
843
tmp = PyNumber_Long(obj);
844
if (tmp) {
845
*v = Npy__PyLong_AsInt(tmp);
846
Py_DECREF(tmp);
847
return !(*v == -1 && PyErr_Occurred());
848
}
849
850
if (PyComplex_Check(obj)) {
851
PyErr_Clear();
852
tmp = PyObject_GetAttrString(obj,\"real\");
853
}
854
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
855
/*pass*/;
856
}
857
else if (PySequence_Check(obj)) {
858
PyErr_Clear();
859
tmp = PySequence_GetItem(obj, 0);
860
}
861
862
if (tmp) {
863
if (int_from_pyobj(v, tmp, errmess)) {
864
Py_DECREF(tmp);
865
return 1;
866
}
867
Py_DECREF(tmp);
868
}
869
870
{
871
PyObject* err = PyErr_Occurred();
872
if (err == NULL) {
873
err = #modulename#_error;
874
}
875
PyErr_SetString(err, errmess);
876
}
877
return 0;
878
}
879
"""
880
881
882
cfuncs['long_from_pyobj'] = """\
883
static int
884
long_from_pyobj(long* v, PyObject *obj, const char *errmess) {
885
PyObject* tmp = NULL;
886
887
if (PyLong_Check(obj)) {
888
*v = PyLong_AsLong(obj);
889
return !(*v == -1 && PyErr_Occurred());
890
}
891
892
tmp = PyNumber_Long(obj);
893
if (tmp) {
894
*v = PyLong_AsLong(tmp);
895
Py_DECREF(tmp);
896
return !(*v == -1 && PyErr_Occurred());
897
}
898
899
if (PyComplex_Check(obj)) {
900
PyErr_Clear();
901
tmp = PyObject_GetAttrString(obj,\"real\");
902
}
903
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
904
/*pass*/;
905
}
906
else if (PySequence_Check(obj)) {
907
PyErr_Clear();
908
tmp = PySequence_GetItem(obj, 0);
909
}
910
911
if (tmp) {
912
if (long_from_pyobj(v, tmp, errmess)) {
913
Py_DECREF(tmp);
914
return 1;
915
}
916
Py_DECREF(tmp);
917
}
918
{
919
PyObject* err = PyErr_Occurred();
920
if (err == NULL) {
921
err = #modulename#_error;
922
}
923
PyErr_SetString(err, errmess);
924
}
925
return 0;
926
}
927
"""
928
929
930
needs['long_long_from_pyobj'] = ['long_long']
931
cfuncs['long_long_from_pyobj'] = """\
932
static int
933
long_long_from_pyobj(long_long* v, PyObject *obj, const char *errmess)
934
{
935
PyObject* tmp = NULL;
936
937
if (PyLong_Check(obj)) {
938
*v = PyLong_AsLongLong(obj);
939
return !(*v == -1 && PyErr_Occurred());
940
}
941
942
tmp = PyNumber_Long(obj);
943
if (tmp) {
944
*v = PyLong_AsLongLong(tmp);
945
Py_DECREF(tmp);
946
return !(*v == -1 && PyErr_Occurred());
947
}
948
949
if (PyComplex_Check(obj)) {
950
PyErr_Clear();
951
tmp = PyObject_GetAttrString(obj,\"real\");
952
}
953
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
954
/*pass*/;
955
}
956
else if (PySequence_Check(obj)) {
957
PyErr_Clear();
958
tmp = PySequence_GetItem(obj, 0);
959
}
960
961
if (tmp) {
962
if (long_long_from_pyobj(v, tmp, errmess)) {
963
Py_DECREF(tmp);
964
return 1;
965
}
966
Py_DECREF(tmp);
967
}
968
{
969
PyObject* err = PyErr_Occurred();
970
if (err == NULL) {
971
err = #modulename#_error;
972
}
973
PyErr_SetString(err,errmess);
974
}
975
return 0;
976
}
977
"""
978
979
980
needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double']
981
cfuncs['long_double_from_pyobj'] = """\
982
static int
983
long_double_from_pyobj(long_double* v, PyObject *obj, const char *errmess)
984
{
985
double d=0;
986
if (PyArray_CheckScalar(obj)){
987
if PyArray_IsScalar(obj, LongDouble) {
988
PyArray_ScalarAsCtype(obj, v);
989
return 1;
990
}
991
else if (PyArray_Check(obj) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {
992
(*v) = *((npy_longdouble *)PyArray_DATA(obj));
993
return 1;
994
}
995
}
996
if (double_from_pyobj(&d, obj, errmess)) {
997
*v = (long_double)d;
998
return 1;
999
}
1000
return 0;
1001
}
1002
"""
1003
1004
1005
cfuncs['double_from_pyobj'] = """\
1006
static int
1007
double_from_pyobj(double* v, PyObject *obj, const char *errmess)
1008
{
1009
PyObject* tmp = NULL;
1010
if (PyFloat_Check(obj)) {
1011
*v = PyFloat_AsDouble(obj);
1012
return !(*v == -1.0 && PyErr_Occurred());
1013
}
1014
1015
tmp = PyNumber_Float(obj);
1016
if (tmp) {
1017
*v = PyFloat_AsDouble(tmp);
1018
Py_DECREF(tmp);
1019
return !(*v == -1.0 && PyErr_Occurred());
1020
}
1021
1022
if (PyComplex_Check(obj)) {
1023
PyErr_Clear();
1024
tmp = PyObject_GetAttrString(obj,\"real\");
1025
}
1026
else if (PyBytes_Check(obj) || PyUnicode_Check(obj)) {
1027
/*pass*/;
1028
}
1029
else if (PySequence_Check(obj)) {
1030
PyErr_Clear();
1031
tmp = PySequence_GetItem(obj, 0);
1032
}
1033
1034
if (tmp) {
1035
if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;}
1036
Py_DECREF(tmp);
1037
}
1038
{
1039
PyObject* err = PyErr_Occurred();
1040
if (err==NULL) err = #modulename#_error;
1041
PyErr_SetString(err,errmess);
1042
}
1043
return 0;
1044
}
1045
"""
1046
1047
1048
needs['float_from_pyobj'] = ['double_from_pyobj']
1049
cfuncs['float_from_pyobj'] = """\
1050
static int
1051
float_from_pyobj(float* v, PyObject *obj, const char *errmess)
1052
{
1053
double d=0.0;
1054
if (double_from_pyobj(&d,obj,errmess)) {
1055
*v = (float)d;
1056
return 1;
1057
}
1058
return 0;
1059
}
1060
"""
1061
1062
1063
needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double',
1064
'complex_double_from_pyobj']
1065
cfuncs['complex_long_double_from_pyobj'] = """\
1066
static int
1067
complex_long_double_from_pyobj(complex_long_double* v, PyObject *obj, const char *errmess)
1068
{
1069
complex_double cd = {0.0,0.0};
1070
if (PyArray_CheckScalar(obj)){
1071
if PyArray_IsScalar(obj, CLongDouble) {
1072
PyArray_ScalarAsCtype(obj, v);
1073
return 1;
1074
}
1075
else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {
1076
(*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real;
1077
(*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag;
1078
return 1;
1079
}
1080
}
1081
if (complex_double_from_pyobj(&cd,obj,errmess)) {
1082
(*v).r = (long_double)cd.r;
1083
(*v).i = (long_double)cd.i;
1084
return 1;
1085
}
1086
return 0;
1087
}
1088
"""
1089
1090
1091
needs['complex_double_from_pyobj'] = ['complex_double']
1092
cfuncs['complex_double_from_pyobj'] = """\
1093
static int
1094
complex_double_from_pyobj(complex_double* v, PyObject *obj, const char *errmess) {
1095
Py_complex c;
1096
if (PyComplex_Check(obj)) {
1097
c = PyComplex_AsCComplex(obj);
1098
(*v).r = c.real;
1099
(*v).i = c.imag;
1100
return 1;
1101
}
1102
if (PyArray_IsScalar(obj, ComplexFloating)) {
1103
if (PyArray_IsScalar(obj, CFloat)) {
1104
npy_cfloat new;
1105
PyArray_ScalarAsCtype(obj, &new);
1106
(*v).r = (double)new.real;
1107
(*v).i = (double)new.imag;
1108
}
1109
else if (PyArray_IsScalar(obj, CLongDouble)) {
1110
npy_clongdouble new;
1111
PyArray_ScalarAsCtype(obj, &new);
1112
(*v).r = (double)new.real;
1113
(*v).i = (double)new.imag;
1114
}
1115
else { /* if (PyArray_IsScalar(obj, CDouble)) */
1116
PyArray_ScalarAsCtype(obj, v);
1117
}
1118
return 1;
1119
}
1120
if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */
1121
PyObject *arr;
1122
if (PyArray_Check(obj)) {
1123
arr = PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE);
1124
}
1125
else {
1126
arr = PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE));
1127
}
1128
if (arr == NULL) {
1129
return 0;
1130
}
1131
(*v).r = ((npy_cdouble *)PyArray_DATA(arr))->real;
1132
(*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag;
1133
Py_DECREF(arr);
1134
return 1;
1135
}
1136
/* Python does not provide PyNumber_Complex function :-( */
1137
(*v).i = 0.0;
1138
if (PyFloat_Check(obj)) {
1139
(*v).r = PyFloat_AsDouble(obj);
1140
return !((*v).r == -1.0 && PyErr_Occurred());
1141
}
1142
if (PyLong_Check(obj)) {
1143
(*v).r = PyLong_AsDouble(obj);
1144
return !((*v).r == -1.0 && PyErr_Occurred());
1145
}
1146
if (PySequence_Check(obj) && !(PyBytes_Check(obj) || PyUnicode_Check(obj))) {
1147
PyObject *tmp = PySequence_GetItem(obj,0);
1148
if (tmp) {
1149
if (complex_double_from_pyobj(v,tmp,errmess)) {
1150
Py_DECREF(tmp);
1151
return 1;
1152
}
1153
Py_DECREF(tmp);
1154
}
1155
}
1156
{
1157
PyObject* err = PyErr_Occurred();
1158
if (err==NULL)
1159
err = PyExc_TypeError;
1160
PyErr_SetString(err,errmess);
1161
}
1162
return 0;
1163
}
1164
"""
1165
1166
1167
needs['complex_float_from_pyobj'] = [
1168
'complex_float', 'complex_double_from_pyobj']
1169
cfuncs['complex_float_from_pyobj'] = """\
1170
static int
1171
complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess)
1172
{
1173
complex_double cd={0.0,0.0};
1174
if (complex_double_from_pyobj(&cd,obj,errmess)) {
1175
(*v).r = (float)cd.r;
1176
(*v).i = (float)cd.i;
1177
return 1;
1178
}
1179
return 0;
1180
}
1181
"""
1182
1183
1184
needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE']
1185
cfuncs[
1186
'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n'
1187
needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char']
1188
cfuncs[
1189
'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n'
1190
needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char']
1191
cfuncs[
1192
'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n'
1193
needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE']
1194
cfuncs[
1195
'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n'
1196
needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE']
1197
cfuncs[
1198
'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n'
1199
needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE']
1200
cfuncs[
1201
'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n'
1202
needs['try_pyarr_from_long_long'] = [
1203
'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long']
1204
cfuncs[
1205
'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n'
1206
needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE']
1207
cfuncs[
1208
'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n'
1209
needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE']
1210
cfuncs[
1211
'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n'
1212
needs['try_pyarr_from_complex_float'] = [
1213
'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float']
1214
cfuncs[
1215
'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n'
1216
needs['try_pyarr_from_complex_double'] = [
1217
'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double']
1218
cfuncs[
1219
'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n'
1220
1221
1222
needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX']
1223
# create the list of arguments to be used when calling back to python
1224
cfuncs['create_cb_arglist'] = """\
1225
static int
1226
create_cb_arglist(PyObject* fun, PyTupleObject* xa , const int maxnofargs,
1227
const int nofoptargs, int *nofargs, PyTupleObject **args,
1228
const char *errmess)
1229
{
1230
PyObject *tmp = NULL;
1231
PyObject *tmp_fun = NULL;
1232
Py_ssize_t tot, opt, ext, siz, i, di = 0;
1233
CFUNCSMESS(\"create_cb_arglist\\n\");
1234
tot=opt=ext=siz=0;
1235
/* Get the total number of arguments */
1236
if (PyFunction_Check(fun)) {
1237
tmp_fun = fun;
1238
Py_INCREF(tmp_fun);
1239
}
1240
else {
1241
di = 1;
1242
if (PyObject_HasAttrString(fun,\"im_func\")) {
1243
tmp_fun = PyObject_GetAttrString(fun,\"im_func\");
1244
}
1245
else if (PyObject_HasAttrString(fun,\"__call__\")) {
1246
tmp = PyObject_GetAttrString(fun,\"__call__\");
1247
if (PyObject_HasAttrString(tmp,\"im_func\"))
1248
tmp_fun = PyObject_GetAttrString(tmp,\"im_func\");
1249
else {
1250
tmp_fun = fun; /* built-in function */
1251
Py_INCREF(tmp_fun);
1252
tot = maxnofargs;
1253
if (PyCFunction_Check(fun)) {
1254
/* In case the function has a co_argcount (like on PyPy) */
1255
di = 0;
1256
}
1257
if (xa != NULL)
1258
tot += PyTuple_Size((PyObject *)xa);
1259
}
1260
Py_XDECREF(tmp);
1261
}
1262
else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) {
1263
tot = maxnofargs;
1264
if (xa != NULL)
1265
tot += PyTuple_Size((PyObject *)xa);
1266
tmp_fun = fun;
1267
Py_INCREF(tmp_fun);
1268
}
1269
else if (F2PyCapsule_Check(fun)) {
1270
tot = maxnofargs;
1271
if (xa != NULL)
1272
ext = PyTuple_Size((PyObject *)xa);
1273
if(ext>0) {
1274
fprintf(stderr,\"extra arguments tuple cannot be used with CObject call-back\\n\");
1275
goto capi_fail;
1276
}
1277
tmp_fun = fun;
1278
Py_INCREF(tmp_fun);
1279
}
1280
}
1281
1282
if (tmp_fun == NULL) {
1283
fprintf(stderr,
1284
\"Call-back argument must be function|instance|instance.__call__|f2py-function \"
1285
\"but got %s.\\n\",
1286
((fun == NULL) ? \"NULL\" : Py_TYPE(fun)->tp_name));
1287
goto capi_fail;
1288
}
1289
1290
if (PyObject_HasAttrString(tmp_fun,\"__code__\")) {
1291
if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) {
1292
PyObject *tmp_argcount = PyObject_GetAttrString(tmp,\"co_argcount\");
1293
Py_DECREF(tmp);
1294
if (tmp_argcount == NULL) {
1295
goto capi_fail;
1296
}
1297
tot = PyLong_AsSsize_t(tmp_argcount) - di;
1298
Py_DECREF(tmp_argcount);
1299
}
1300
}
1301
/* Get the number of optional arguments */
1302
if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) {
1303
if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\")))
1304
opt = PyTuple_Size(tmp);
1305
Py_XDECREF(tmp);
1306
}
1307
/* Get the number of extra arguments */
1308
if (xa != NULL)
1309
ext = PyTuple_Size((PyObject *)xa);
1310
/* Calculate the size of call-backs argument list */
1311
siz = MIN(maxnofargs+ext,tot);
1312
*nofargs = MAX(0,siz-ext);
1313
1314
#ifdef DEBUGCFUNCS
1315
fprintf(stderr,
1316
\"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),\"
1317
\"tot,opt,ext,siz,nofargs = %d(-%d), %zd, %zd, %zd, %zd, %d\\n\",
1318
maxnofargs, nofoptargs, tot, opt, ext, siz, *nofargs);
1319
#endif
1320
1321
if (siz < tot-opt) {
1322
fprintf(stderr,
1323
\"create_cb_arglist: Failed to build argument list \"
1324
\"(siz) with enough arguments (tot-opt) required by \"
1325
\"user-supplied function (siz,tot,opt=%zd, %zd, %zd).\\n\",
1326
siz, tot, opt);
1327
goto capi_fail;
1328
}
1329
1330
/* Initialize argument list */
1331
*args = (PyTupleObject *)PyTuple_New(siz);
1332
for (i=0;i<*nofargs;i++) {
1333
Py_INCREF(Py_None);
1334
PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None);
1335
}
1336
if (xa != NULL)
1337
for (i=(*nofargs);i<siz;i++) {
1338
tmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs));
1339
Py_INCREF(tmp);
1340
PyTuple_SET_ITEM(*args,i,tmp);
1341
}
1342
CFUNCSMESS(\"create_cb_arglist-end\\n\");
1343
Py_DECREF(tmp_fun);
1344
return 1;
1345
1346
capi_fail:
1347
if (PyErr_Occurred() == NULL)
1348
PyErr_SetString(#modulename#_error, errmess);
1349
Py_XDECREF(tmp_fun);
1350
return 0;
1351
}
1352
"""
1353
1354
1355
def buildcfuncs():
1356
from .capi_maps import c2capi_map
1357
for k in c2capi_map.keys():
1358
m = 'pyarr_from_p_%s1' % k
1359
cppmacros[
1360
m] = '#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))' % (m, c2capi_map[k])
1361
k = 'string'
1362
m = 'pyarr_from_p_%s1' % k
1363
# NPY_CHAR compatibility, NPY_STRING with itemsize 1
1364
cppmacros[
1365
m] = '#define %s(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))' % (m)
1366
1367
1368
############ Auxiliary functions for sorting needs ###################
1369
1370
def append_needs(need, flag=1):
1371
# This function modifies the contents of the global `outneeds` dict.
1372
if isinstance(need, list):
1373
for n in need:
1374
append_needs(n, flag)
1375
elif isinstance(need, str):
1376
if not need:
1377
return
1378
if need in includes0:
1379
n = 'includes0'
1380
elif need in includes:
1381
n = 'includes'
1382
elif need in typedefs:
1383
n = 'typedefs'
1384
elif need in typedefs_generated:
1385
n = 'typedefs_generated'
1386
elif need in cppmacros:
1387
n = 'cppmacros'
1388
elif need in cfuncs:
1389
n = 'cfuncs'
1390
elif need in callbacks:
1391
n = 'callbacks'
1392
elif need in f90modhooks:
1393
n = 'f90modhooks'
1394
elif need in commonhooks:
1395
n = 'commonhooks'
1396
else:
1397
errmess('append_needs: unknown need %s\n' % (repr(need)))
1398
return
1399
if need in outneeds[n]:
1400
return
1401
if flag:
1402
tmp = {}
1403
if need in needs:
1404
for nn in needs[need]:
1405
t = append_needs(nn, 0)
1406
if isinstance(t, dict):
1407
for nnn in t.keys():
1408
if nnn in tmp:
1409
tmp[nnn] = tmp[nnn] + t[nnn]
1410
else:
1411
tmp[nnn] = t[nnn]
1412
for nn in tmp.keys():
1413
for nnn in tmp[nn]:
1414
if nnn not in outneeds[nn]:
1415
outneeds[nn] = [nnn] + outneeds[nn]
1416
outneeds[n].append(need)
1417
else:
1418
tmp = {}
1419
if need in needs:
1420
for nn in needs[need]:
1421
t = append_needs(nn, flag)
1422
if isinstance(t, dict):
1423
for nnn in t.keys():
1424
if nnn in tmp:
1425
tmp[nnn] = t[nnn] + tmp[nnn]
1426
else:
1427
tmp[nnn] = t[nnn]
1428
if n not in tmp:
1429
tmp[n] = []
1430
tmp[n].append(need)
1431
return tmp
1432
else:
1433
errmess('append_needs: expected list or string but got :%s\n' %
1434
(repr(need)))
1435
1436
1437
def get_needs():
1438
# This function modifies the contents of the global `outneeds` dict.
1439
res = {}
1440
for n in outneeds.keys():
1441
out = []
1442
saveout = copy.copy(outneeds[n])
1443
while len(outneeds[n]) > 0:
1444
if outneeds[n][0] not in needs:
1445
out.append(outneeds[n][0])
1446
del outneeds[n][0]
1447
else:
1448
flag = 0
1449
for k in outneeds[n][1:]:
1450
if k in needs[outneeds[n][0]]:
1451
flag = 1
1452
break
1453
if flag:
1454
outneeds[n] = outneeds[n][1:] + [outneeds[n][0]]
1455
else:
1456
out.append(outneeds[n][0])
1457
del outneeds[n][0]
1458
if saveout and (0 not in map(lambda x, y: x == y, saveout, outneeds[n])) \
1459
and outneeds[n] != []:
1460
print(n, saveout)
1461
errmess(
1462
'get_needs: no progress in sorting needs, probably circular dependence, skipping.\n')
1463
out = out + saveout
1464
break
1465
saveout = copy.copy(outneeds[n])
1466
if out == []:
1467
out = [n]
1468
res[n] = out
1469
return res
1470
1471