cfuncs.py 44 KB

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