cfuncs.py 44 KB

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