autowrap.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. """Module for compiling codegen output, and wrap the binary for use in
  2. python.
  3. .. note:: To use the autowrap module it must first be imported
  4. >>> from sympy.utilities.autowrap import autowrap
  5. This module provides a common interface for different external backends, such
  6. as f2py, fwrap, Cython, SWIG(?) etc. (Currently only f2py and Cython are
  7. implemented) The goal is to provide access to compiled binaries of acceptable
  8. performance with a one-button user interface, e.g.,
  9. >>> from sympy.abc import x,y
  10. >>> expr = (x - y)**25
  11. >>> flat = expr.expand()
  12. >>> binary_callable = autowrap(flat)
  13. >>> binary_callable(2, 3)
  14. -1.0
  15. Although a SymPy user might primarily be interested in working with
  16. mathematical expressions and not in the details of wrapping tools
  17. needed to evaluate such expressions efficiently in numerical form,
  18. the user cannot do so without some understanding of the
  19. limits in the target language. For example, the expanded expression
  20. contains large coefficients which result in loss of precision when
  21. computing the expression:
  22. >>> binary_callable(3, 2)
  23. 0.0
  24. >>> binary_callable(4, 5), binary_callable(5, 4)
  25. (-22925376.0, 25165824.0)
  26. Wrapping the unexpanded expression gives the expected behavior:
  27. >>> e = autowrap(expr)
  28. >>> e(4, 5), e(5, 4)
  29. (-1.0, 1.0)
  30. The callable returned from autowrap() is a binary Python function, not a
  31. SymPy object. If it is desired to use the compiled function in symbolic
  32. expressions, it is better to use binary_function() which returns a SymPy
  33. Function object. The binary callable is attached as the _imp_ attribute and
  34. invoked when a numerical evaluation is requested with evalf(), or with
  35. lambdify().
  36. >>> from sympy.utilities.autowrap import binary_function
  37. >>> f = binary_function('f', expr)
  38. >>> 2*f(x, y) + y
  39. y + 2*f(x, y)
  40. >>> (2*f(x, y) + y).evalf(2, subs={x: 1, y:2})
  41. 0.e-110
  42. When is this useful?
  43. 1) For computations on large arrays, Python iterations may be too slow,
  44. and depending on the mathematical expression, it may be difficult to
  45. exploit the advanced index operations provided by NumPy.
  46. 2) For *really* long expressions that will be called repeatedly, the
  47. compiled binary should be significantly faster than SymPy's .evalf()
  48. 3) If you are generating code with the codegen utility in order to use
  49. it in another project, the automatic Python wrappers let you test the
  50. binaries immediately from within SymPy.
  51. 4) To create customized ufuncs for use with numpy arrays.
  52. See *ufuncify*.
  53. When is this module NOT the best approach?
  54. 1) If you are really concerned about speed or memory optimizations,
  55. you will probably get better results by working directly with the
  56. wrapper tools and the low level code. However, the files generated
  57. by this utility may provide a useful starting point and reference
  58. code. Temporary files will be left intact if you supply the keyword
  59. tempdir="path/to/files/".
  60. 2) If the array computation can be handled easily by numpy, and you
  61. do not need the binaries for another project.
  62. """
  63. import sys
  64. import os
  65. import shutil
  66. import tempfile
  67. from subprocess import STDOUT, CalledProcessError, check_output
  68. from string import Template
  69. from warnings import warn
  70. from sympy.core.cache import cacheit
  71. from sympy.core.function import Lambda
  72. from sympy.core.relational import Eq
  73. from sympy.core.symbol import Dummy, Symbol
  74. from sympy.tensor.indexed import Idx, IndexedBase
  75. from sympy.utilities.codegen import (make_routine, get_code_generator,
  76. OutputArgument, InOutArgument,
  77. InputArgument, CodeGenArgumentListError,
  78. Result, ResultBase, C99CodeGen)
  79. from sympy.utilities.iterables import iterable
  80. from sympy.utilities.lambdify import implemented_function
  81. from sympy.utilities.decorator import doctest_depends_on
  82. _doctest_depends_on = {'exe': ('f2py', 'gfortran', 'gcc'),
  83. 'modules': ('numpy',)}
  84. class CodeWrapError(Exception):
  85. pass
  86. class CodeWrapper:
  87. """Base Class for code wrappers"""
  88. _filename = "wrapped_code"
  89. _module_basename = "wrapper_module"
  90. _module_counter = 0
  91. @property
  92. def filename(self):
  93. return "%s_%s" % (self._filename, CodeWrapper._module_counter)
  94. @property
  95. def module_name(self):
  96. return "%s_%s" % (self._module_basename, CodeWrapper._module_counter)
  97. def __init__(self, generator, filepath=None, flags=[], verbose=False):
  98. """
  99. generator -- the code generator to use
  100. """
  101. self.generator = generator
  102. self.filepath = filepath
  103. self.flags = flags
  104. self.quiet = not verbose
  105. @property
  106. def include_header(self):
  107. return bool(self.filepath)
  108. @property
  109. def include_empty(self):
  110. return bool(self.filepath)
  111. def _generate_code(self, main_routine, routines):
  112. routines.append(main_routine)
  113. self.generator.write(
  114. routines, self.filename, True, self.include_header,
  115. self.include_empty)
  116. def wrap_code(self, routine, helpers=None):
  117. helpers = helpers or []
  118. if self.filepath:
  119. workdir = os.path.abspath(self.filepath)
  120. else:
  121. workdir = tempfile.mkdtemp("_sympy_compile")
  122. if not os.access(workdir, os.F_OK):
  123. os.mkdir(workdir)
  124. oldwork = os.getcwd()
  125. os.chdir(workdir)
  126. try:
  127. sys.path.append(workdir)
  128. self._generate_code(routine, helpers)
  129. self._prepare_files(routine)
  130. self._process_files(routine)
  131. mod = __import__(self.module_name)
  132. finally:
  133. sys.path.remove(workdir)
  134. CodeWrapper._module_counter += 1
  135. os.chdir(oldwork)
  136. if not self.filepath:
  137. try:
  138. shutil.rmtree(workdir)
  139. except OSError:
  140. # Could be some issues on Windows
  141. pass
  142. return self._get_wrapped_function(mod, routine.name)
  143. def _process_files(self, routine):
  144. command = self.command
  145. command.extend(self.flags)
  146. try:
  147. retoutput = check_output(command, stderr=STDOUT)
  148. except CalledProcessError as e:
  149. raise CodeWrapError(
  150. "Error while executing command: %s. Command output is:\n%s" % (
  151. " ".join(command), e.output.decode('utf-8')))
  152. if not self.quiet:
  153. print(retoutput)
  154. class DummyWrapper(CodeWrapper):
  155. """Class used for testing independent of backends """
  156. template = """# dummy module for testing of SymPy
  157. def %(name)s():
  158. return "%(expr)s"
  159. %(name)s.args = "%(args)s"
  160. %(name)s.returns = "%(retvals)s"
  161. """
  162. def _prepare_files(self, routine):
  163. return
  164. def _generate_code(self, routine, helpers):
  165. with open('%s.py' % self.module_name, 'w') as f:
  166. printed = ", ".join(
  167. [str(res.expr) for res in routine.result_variables])
  168. # convert OutputArguments to return value like f2py
  169. args = filter(lambda x: not isinstance(
  170. x, OutputArgument), routine.arguments)
  171. retvals = []
  172. for val in routine.result_variables:
  173. if isinstance(val, Result):
  174. retvals.append('nameless')
  175. else:
  176. retvals.append(val.result_var)
  177. print(DummyWrapper.template % {
  178. 'name': routine.name,
  179. 'expr': printed,
  180. 'args': ", ".join([str(a.name) for a in args]),
  181. 'retvals': ", ".join([str(val) for val in retvals])
  182. }, end="", file=f)
  183. def _process_files(self, routine):
  184. return
  185. @classmethod
  186. def _get_wrapped_function(cls, mod, name):
  187. return getattr(mod, name)
  188. class CythonCodeWrapper(CodeWrapper):
  189. """Wrapper that uses Cython"""
  190. setup_template = """\
  191. from setuptools import setup
  192. from setuptools import Extension
  193. from Cython.Build import cythonize
  194. cy_opts = {cythonize_options}
  195. {np_import}
  196. ext_mods = [Extension(
  197. {ext_args},
  198. include_dirs={include_dirs},
  199. library_dirs={library_dirs},
  200. libraries={libraries},
  201. extra_compile_args={extra_compile_args},
  202. extra_link_args={extra_link_args}
  203. )]
  204. setup(ext_modules=cythonize(ext_mods, **cy_opts))
  205. """
  206. _cythonize_options = {'compiler_directives':{'language_level' : "3"}}
  207. pyx_imports = (
  208. "import numpy as np\n"
  209. "cimport numpy as np\n\n")
  210. pyx_header = (
  211. "cdef extern from '{header_file}.h':\n"
  212. " {prototype}\n\n")
  213. pyx_func = (
  214. "def {name}_c({arg_string}):\n"
  215. "\n"
  216. "{declarations}"
  217. "{body}")
  218. std_compile_flag = '-std=c99'
  219. def __init__(self, *args, **kwargs):
  220. """Instantiates a Cython code wrapper.
  221. The following optional parameters get passed to ``setuptools.Extension``
  222. for building the Python extension module. Read its documentation to
  223. learn more.
  224. Parameters
  225. ==========
  226. include_dirs : [list of strings]
  227. A list of directories to search for C/C++ header files (in Unix
  228. form for portability).
  229. library_dirs : [list of strings]
  230. A list of directories to search for C/C++ libraries at link time.
  231. libraries : [list of strings]
  232. A list of library names (not filenames or paths) to link against.
  233. extra_compile_args : [list of strings]
  234. Any extra platform- and compiler-specific information to use when
  235. compiling the source files in 'sources'. For platforms and
  236. compilers where "command line" makes sense, this is typically a
  237. list of command-line arguments, but for other platforms it could be
  238. anything. Note that the attribute ``std_compile_flag`` will be
  239. appended to this list.
  240. extra_link_args : [list of strings]
  241. Any extra platform- and compiler-specific information to use when
  242. linking object files together to create the extension (or to create
  243. a new static Python interpreter). Similar interpretation as for
  244. 'extra_compile_args'.
  245. cythonize_options : [dictionary]
  246. Keyword arguments passed on to cythonize.
  247. """
  248. self._include_dirs = kwargs.pop('include_dirs', [])
  249. self._library_dirs = kwargs.pop('library_dirs', [])
  250. self._libraries = kwargs.pop('libraries', [])
  251. self._extra_compile_args = kwargs.pop('extra_compile_args', [])
  252. self._extra_compile_args.append(self.std_compile_flag)
  253. self._extra_link_args = kwargs.pop('extra_link_args', [])
  254. self._cythonize_options = kwargs.pop('cythonize_options', self._cythonize_options)
  255. self._need_numpy = False
  256. super().__init__(*args, **kwargs)
  257. @property
  258. def command(self):
  259. command = [sys.executable, "setup.py", "build_ext", "--inplace"]
  260. return command
  261. def _prepare_files(self, routine, build_dir=os.curdir):
  262. # NOTE : build_dir is used for testing purposes.
  263. pyxfilename = self.module_name + '.pyx'
  264. codefilename = "%s.%s" % (self.filename, self.generator.code_extension)
  265. # pyx
  266. with open(os.path.join(build_dir, pyxfilename), 'w') as f:
  267. self.dump_pyx([routine], f, self.filename)
  268. # setup.py
  269. ext_args = [repr(self.module_name), repr([pyxfilename, codefilename])]
  270. if self._need_numpy:
  271. np_import = 'import numpy as np\n'
  272. self._include_dirs.append('np.get_include()')
  273. else:
  274. np_import = ''
  275. with open(os.path.join(build_dir, 'setup.py'), 'w') as f:
  276. includes = str(self._include_dirs).replace("'np.get_include()'",
  277. 'np.get_include()')
  278. f.write(self.setup_template.format(
  279. ext_args=", ".join(ext_args),
  280. np_import=np_import,
  281. include_dirs=includes,
  282. library_dirs=self._library_dirs,
  283. libraries=self._libraries,
  284. extra_compile_args=self._extra_compile_args,
  285. extra_link_args=self._extra_link_args,
  286. cythonize_options=self._cythonize_options
  287. ))
  288. @classmethod
  289. def _get_wrapped_function(cls, mod, name):
  290. return getattr(mod, name + '_c')
  291. def dump_pyx(self, routines, f, prefix):
  292. """Write a Cython file with Python wrappers
  293. This file contains all the definitions of the routines in c code and
  294. refers to the header file.
  295. Arguments
  296. ---------
  297. routines
  298. List of Routine instances
  299. f
  300. File-like object to write the file to
  301. prefix
  302. The filename prefix, used to refer to the proper header file.
  303. Only the basename of the prefix is used.
  304. """
  305. headers = []
  306. functions = []
  307. for routine in routines:
  308. prototype = self.generator.get_prototype(routine)
  309. # C Function Header Import
  310. headers.append(self.pyx_header.format(header_file=prefix,
  311. prototype=prototype))
  312. # Partition the C function arguments into categories
  313. py_rets, py_args, py_loc, py_inf = self._partition_args(routine.arguments)
  314. # Function prototype
  315. name = routine.name
  316. arg_string = ", ".join(self._prototype_arg(arg) for arg in py_args)
  317. # Local Declarations
  318. local_decs = []
  319. for arg, val in py_inf.items():
  320. proto = self._prototype_arg(arg)
  321. mat, ind = [self._string_var(v) for v in val]
  322. local_decs.append(" cdef {} = {}.shape[{}]".format(proto, mat, ind))
  323. local_decs.extend([" cdef {}".format(self._declare_arg(a)) for a in py_loc])
  324. declarations = "\n".join(local_decs)
  325. if declarations:
  326. declarations = declarations + "\n"
  327. # Function Body
  328. args_c = ", ".join([self._call_arg(a) for a in routine.arguments])
  329. rets = ", ".join([self._string_var(r.name) for r in py_rets])
  330. if routine.results:
  331. body = ' return %s(%s)' % (routine.name, args_c)
  332. if rets:
  333. body = body + ', ' + rets
  334. else:
  335. body = ' %s(%s)\n' % (routine.name, args_c)
  336. body = body + ' return ' + rets
  337. functions.append(self.pyx_func.format(name=name, arg_string=arg_string,
  338. declarations=declarations, body=body))
  339. # Write text to file
  340. if self._need_numpy:
  341. # Only import numpy if required
  342. f.write(self.pyx_imports)
  343. f.write('\n'.join(headers))
  344. f.write('\n'.join(functions))
  345. def _partition_args(self, args):
  346. """Group function arguments into categories."""
  347. py_args = []
  348. py_returns = []
  349. py_locals = []
  350. py_inferred = {}
  351. for arg in args:
  352. if isinstance(arg, OutputArgument):
  353. py_returns.append(arg)
  354. py_locals.append(arg)
  355. elif isinstance(arg, InOutArgument):
  356. py_returns.append(arg)
  357. py_args.append(arg)
  358. else:
  359. py_args.append(arg)
  360. # Find arguments that are array dimensions. These can be inferred
  361. # locally in the Cython code.
  362. if isinstance(arg, (InputArgument, InOutArgument)) and arg.dimensions:
  363. dims = [d[1] + 1 for d in arg.dimensions]
  364. sym_dims = [(i, d) for (i, d) in enumerate(dims) if
  365. isinstance(d, Symbol)]
  366. for (i, d) in sym_dims:
  367. py_inferred[d] = (arg.name, i)
  368. for arg in args:
  369. if arg.name in py_inferred:
  370. py_inferred[arg] = py_inferred.pop(arg.name)
  371. # Filter inferred arguments from py_args
  372. py_args = [a for a in py_args if a not in py_inferred]
  373. return py_returns, py_args, py_locals, py_inferred
  374. def _prototype_arg(self, arg):
  375. mat_dec = "np.ndarray[{mtype}, ndim={ndim}] {name}"
  376. np_types = {'double': 'np.double_t',
  377. 'int': 'np.int_t'}
  378. t = arg.get_datatype('c')
  379. if arg.dimensions:
  380. self._need_numpy = True
  381. ndim = len(arg.dimensions)
  382. mtype = np_types[t]
  383. return mat_dec.format(mtype=mtype, ndim=ndim, name=self._string_var(arg.name))
  384. else:
  385. return "%s %s" % (t, self._string_var(arg.name))
  386. def _declare_arg(self, arg):
  387. proto = self._prototype_arg(arg)
  388. if arg.dimensions:
  389. shape = '(' + ','.join(self._string_var(i[1] + 1) for i in arg.dimensions) + ')'
  390. return proto + " = np.empty({shape})".format(shape=shape)
  391. else:
  392. return proto + " = 0"
  393. def _call_arg(self, arg):
  394. if arg.dimensions:
  395. t = arg.get_datatype('c')
  396. return "<{}*> {}.data".format(t, self._string_var(arg.name))
  397. elif isinstance(arg, ResultBase):
  398. return "&{}".format(self._string_var(arg.name))
  399. else:
  400. return self._string_var(arg.name)
  401. def _string_var(self, var):
  402. printer = self.generator.printer.doprint
  403. return printer(var)
  404. class F2PyCodeWrapper(CodeWrapper):
  405. """Wrapper that uses f2py"""
  406. def __init__(self, *args, **kwargs):
  407. ext_keys = ['include_dirs', 'library_dirs', 'libraries',
  408. 'extra_compile_args', 'extra_link_args']
  409. msg = ('The compilation option kwarg {} is not supported with the f2py '
  410. 'backend.')
  411. for k in ext_keys:
  412. if k in kwargs.keys():
  413. warn(msg.format(k))
  414. kwargs.pop(k, None)
  415. super().__init__(*args, **kwargs)
  416. @property
  417. def command(self):
  418. filename = self.filename + '.' + self.generator.code_extension
  419. args = ['-c', '-m', self.module_name, filename]
  420. command = [sys.executable, "-c", "import numpy.f2py as f2py2e;f2py2e.main()"]+args
  421. return command
  422. def _prepare_files(self, routine):
  423. pass
  424. @classmethod
  425. def _get_wrapped_function(cls, mod, name):
  426. return getattr(mod, name)
  427. # Here we define a lookup of backends -> tuples of languages. For now, each
  428. # tuple is of length 1, but if a backend supports more than one language,
  429. # the most preferable language is listed first.
  430. _lang_lookup = {'CYTHON': ('C99', 'C89', 'C'),
  431. 'F2PY': ('F95',),
  432. 'NUMPY': ('C99', 'C89', 'C'),
  433. 'DUMMY': ('F95',)} # Dummy here just for testing
  434. def _infer_language(backend):
  435. """For a given backend, return the top choice of language"""
  436. langs = _lang_lookup.get(backend.upper(), False)
  437. if not langs:
  438. raise ValueError("Unrecognized backend: " + backend)
  439. return langs[0]
  440. def _validate_backend_language(backend, language):
  441. """Throws error if backend and language are incompatible"""
  442. langs = _lang_lookup.get(backend.upper(), False)
  443. if not langs:
  444. raise ValueError("Unrecognized backend: " + backend)
  445. if language.upper() not in langs:
  446. raise ValueError(("Backend {} and language {} are "
  447. "incompatible").format(backend, language))
  448. @cacheit
  449. @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
  450. def autowrap(expr, language=None, backend='f2py', tempdir=None, args=None,
  451. flags=None, verbose=False, helpers=None, code_gen=None, **kwargs):
  452. """Generates Python callable binaries based on the math expression.
  453. Parameters
  454. ==========
  455. expr
  456. The SymPy expression that should be wrapped as a binary routine.
  457. language : string, optional
  458. If supplied, (options: 'C' or 'F95'), specifies the language of the
  459. generated code. If ``None`` [default], the language is inferred based
  460. upon the specified backend.
  461. backend : string, optional
  462. Backend used to wrap the generated code. Either 'f2py' [default],
  463. or 'cython'.
  464. tempdir : string, optional
  465. Path to directory for temporary files. If this argument is supplied,
  466. the generated code and the wrapper input files are left intact in the
  467. specified path.
  468. args : iterable, optional
  469. An ordered iterable of symbols. Specifies the argument sequence for the
  470. function.
  471. flags : iterable, optional
  472. Additional option flags that will be passed to the backend.
  473. verbose : bool, optional
  474. If True, autowrap will not mute the command line backends. This can be
  475. helpful for debugging.
  476. helpers : 3-tuple or iterable of 3-tuples, optional
  477. Used to define auxiliary expressions needed for the main expr. If the
  478. main expression needs to call a specialized function it should be
  479. passed in via ``helpers``. Autowrap will then make sure that the
  480. compiled main expression can link to the helper routine. Items should
  481. be 3-tuples with (<function_name>, <sympy_expression>,
  482. <argument_tuple>). It is mandatory to supply an argument sequence to
  483. helper routines.
  484. code_gen : CodeGen instance
  485. An instance of a CodeGen subclass. Overrides ``language``.
  486. include_dirs : [string]
  487. A list of directories to search for C/C++ header files (in Unix form
  488. for portability).
  489. library_dirs : [string]
  490. A list of directories to search for C/C++ libraries at link time.
  491. libraries : [string]
  492. A list of library names (not filenames or paths) to link against.
  493. extra_compile_args : [string]
  494. Any extra platform- and compiler-specific information to use when
  495. compiling the source files in 'sources'. For platforms and compilers
  496. where "command line" makes sense, this is typically a list of
  497. command-line arguments, but for other platforms it could be anything.
  498. extra_link_args : [string]
  499. Any extra platform- and compiler-specific information to use when
  500. linking object files together to create the extension (or to create a
  501. new static Python interpreter). Similar interpretation as for
  502. 'extra_compile_args'.
  503. Examples
  504. ========
  505. >>> from sympy.abc import x, y, z
  506. >>> from sympy.utilities.autowrap import autowrap
  507. >>> expr = ((x - y + z)**(13)).expand()
  508. >>> binary_func = autowrap(expr)
  509. >>> binary_func(1, 4, 2)
  510. -1.0
  511. """
  512. if language:
  513. if not isinstance(language, type):
  514. _validate_backend_language(backend, language)
  515. else:
  516. language = _infer_language(backend)
  517. # two cases 1) helpers is an iterable of 3-tuples and 2) helpers is a
  518. # 3-tuple
  519. if iterable(helpers) and len(helpers) != 0 and iterable(helpers[0]):
  520. helpers = helpers if helpers else ()
  521. else:
  522. helpers = [helpers] if helpers else ()
  523. args = list(args) if iterable(args, exclude=set) else args
  524. if code_gen is None:
  525. code_gen = get_code_generator(language, "autowrap")
  526. CodeWrapperClass = {
  527. 'F2PY': F2PyCodeWrapper,
  528. 'CYTHON': CythonCodeWrapper,
  529. 'DUMMY': DummyWrapper
  530. }[backend.upper()]
  531. code_wrapper = CodeWrapperClass(code_gen, tempdir, flags if flags else (),
  532. verbose, **kwargs)
  533. helps = []
  534. for name_h, expr_h, args_h in helpers:
  535. helps.append(code_gen.routine(name_h, expr_h, args_h))
  536. for name_h, expr_h, args_h in helpers:
  537. if expr.has(expr_h):
  538. name_h = binary_function(name_h, expr_h, backend='dummy')
  539. expr = expr.subs(expr_h, name_h(*args_h))
  540. try:
  541. routine = code_gen.routine('autofunc', expr, args)
  542. except CodeGenArgumentListError as e:
  543. # if all missing arguments are for pure output, we simply attach them
  544. # at the end and try again, because the wrappers will silently convert
  545. # them to return values anyway.
  546. new_args = []
  547. for missing in e.missing_args:
  548. if not isinstance(missing, OutputArgument):
  549. raise
  550. new_args.append(missing.name)
  551. routine = code_gen.routine('autofunc', expr, args + new_args)
  552. return code_wrapper.wrap_code(routine, helpers=helps)
  553. @doctest_depends_on(exe=('f2py', 'gfortran'), modules=('numpy',))
  554. def binary_function(symfunc, expr, **kwargs):
  555. """Returns a SymPy function with expr as binary implementation
  556. This is a convenience function that automates the steps needed to
  557. autowrap the SymPy expression and attaching it to a Function object
  558. with implemented_function().
  559. Parameters
  560. ==========
  561. symfunc : SymPy Function
  562. The function to bind the callable to.
  563. expr : SymPy Expression
  564. The expression used to generate the function.
  565. kwargs : dict
  566. Any kwargs accepted by autowrap.
  567. Examples
  568. ========
  569. >>> from sympy.abc import x, y
  570. >>> from sympy.utilities.autowrap import binary_function
  571. >>> expr = ((x - y)**(25)).expand()
  572. >>> f = binary_function('f', expr)
  573. >>> type(f)
  574. <class 'sympy.core.function.UndefinedFunction'>
  575. >>> 2*f(x, y)
  576. 2*f(x, y)
  577. >>> f(x, y).evalf(2, subs={x: 1, y: 2})
  578. -1.0
  579. """
  580. binary = autowrap(expr, **kwargs)
  581. return implemented_function(symfunc, binary)
  582. #################################################################
  583. # UFUNCIFY #
  584. #################################################################
  585. _ufunc_top = Template("""\
  586. #include "Python.h"
  587. #include "math.h"
  588. #include "numpy/ndarraytypes.h"
  589. #include "numpy/ufuncobject.h"
  590. #include "numpy/halffloat.h"
  591. #include ${include_file}
  592. static PyMethodDef ${module}Methods[] = {
  593. {NULL, NULL, 0, NULL}
  594. };""")
  595. _ufunc_outcalls = Template("*((double *)out${outnum}) = ${funcname}(${call_args});")
  596. _ufunc_body = Template("""\
  597. static void ${funcname}_ufunc(char **args, npy_intp *dimensions, npy_intp* steps, void* data)
  598. {
  599. npy_intp i;
  600. npy_intp n = dimensions[0];
  601. ${declare_args}
  602. ${declare_steps}
  603. for (i = 0; i < n; i++) {
  604. ${outcalls}
  605. ${step_increments}
  606. }
  607. }
  608. PyUFuncGenericFunction ${funcname}_funcs[1] = {&${funcname}_ufunc};
  609. static char ${funcname}_types[${n_types}] = ${types}
  610. static void *${funcname}_data[1] = {NULL};""")
  611. _ufunc_bottom = Template("""\
  612. #if PY_VERSION_HEX >= 0x03000000
  613. static struct PyModuleDef moduledef = {
  614. PyModuleDef_HEAD_INIT,
  615. "${module}",
  616. NULL,
  617. -1,
  618. ${module}Methods,
  619. NULL,
  620. NULL,
  621. NULL,
  622. NULL
  623. };
  624. PyMODINIT_FUNC PyInit_${module}(void)
  625. {
  626. PyObject *m, *d;
  627. ${function_creation}
  628. m = PyModule_Create(&moduledef);
  629. if (!m) {
  630. return NULL;
  631. }
  632. import_array();
  633. import_umath();
  634. d = PyModule_GetDict(m);
  635. ${ufunc_init}
  636. return m;
  637. }
  638. #else
  639. PyMODINIT_FUNC init${module}(void)
  640. {
  641. PyObject *m, *d;
  642. ${function_creation}
  643. m = Py_InitModule("${module}", ${module}Methods);
  644. if (m == NULL) {
  645. return;
  646. }
  647. import_array();
  648. import_umath();
  649. d = PyModule_GetDict(m);
  650. ${ufunc_init}
  651. }
  652. #endif\
  653. """)
  654. _ufunc_init_form = Template("""\
  655. ufunc${ind} = PyUFunc_FromFuncAndData(${funcname}_funcs, ${funcname}_data, ${funcname}_types, 1, ${n_in}, ${n_out},
  656. PyUFunc_None, "${module}", ${docstring}, 0);
  657. PyDict_SetItemString(d, "${funcname}", ufunc${ind});
  658. Py_DECREF(ufunc${ind});""")
  659. _ufunc_setup = Template("""\
  660. from setuptools.extension import Extension
  661. from setuptools import setup
  662. from numpy import get_include
  663. if __name__ == "__main__":
  664. setup(ext_modules=[
  665. Extension('${module}',
  666. sources=['${module}.c', '${filename}.c'],
  667. include_dirs=[get_include()])])
  668. """)
  669. class UfuncifyCodeWrapper(CodeWrapper):
  670. """Wrapper for Ufuncify"""
  671. def __init__(self, *args, **kwargs):
  672. ext_keys = ['include_dirs', 'library_dirs', 'libraries',
  673. 'extra_compile_args', 'extra_link_args']
  674. msg = ('The compilation option kwarg {} is not supported with the numpy'
  675. ' backend.')
  676. for k in ext_keys:
  677. if k in kwargs.keys():
  678. warn(msg.format(k))
  679. kwargs.pop(k, None)
  680. super().__init__(*args, **kwargs)
  681. @property
  682. def command(self):
  683. command = [sys.executable, "setup.py", "build_ext", "--inplace"]
  684. return command
  685. def wrap_code(self, routines, helpers=None):
  686. # This routine overrides CodeWrapper because we can't assume funcname == routines[0].name
  687. # Therefore we have to break the CodeWrapper private API.
  688. # There isn't an obvious way to extend multi-expr support to
  689. # the other autowrap backends, so we limit this change to ufuncify.
  690. helpers = helpers if helpers is not None else []
  691. # We just need a consistent name
  692. funcname = 'wrapped_' + str(id(routines) + id(helpers))
  693. workdir = self.filepath or tempfile.mkdtemp("_sympy_compile")
  694. if not os.access(workdir, os.F_OK):
  695. os.mkdir(workdir)
  696. oldwork = os.getcwd()
  697. os.chdir(workdir)
  698. try:
  699. sys.path.append(workdir)
  700. self._generate_code(routines, helpers)
  701. self._prepare_files(routines, funcname)
  702. self._process_files(routines)
  703. mod = __import__(self.module_name)
  704. finally:
  705. sys.path.remove(workdir)
  706. CodeWrapper._module_counter += 1
  707. os.chdir(oldwork)
  708. if not self.filepath:
  709. try:
  710. shutil.rmtree(workdir)
  711. except OSError:
  712. # Could be some issues on Windows
  713. pass
  714. return self._get_wrapped_function(mod, funcname)
  715. def _generate_code(self, main_routines, helper_routines):
  716. all_routines = main_routines + helper_routines
  717. self.generator.write(
  718. all_routines, self.filename, True, self.include_header,
  719. self.include_empty)
  720. def _prepare_files(self, routines, funcname):
  721. # C
  722. codefilename = self.module_name + '.c'
  723. with open(codefilename, 'w') as f:
  724. self.dump_c(routines, f, self.filename, funcname=funcname)
  725. # setup.py
  726. with open('setup.py', 'w') as f:
  727. self.dump_setup(f)
  728. @classmethod
  729. def _get_wrapped_function(cls, mod, name):
  730. return getattr(mod, name)
  731. def dump_setup(self, f):
  732. setup = _ufunc_setup.substitute(module=self.module_name,
  733. filename=self.filename)
  734. f.write(setup)
  735. def dump_c(self, routines, f, prefix, funcname=None):
  736. """Write a C file with Python wrappers
  737. This file contains all the definitions of the routines in c code.
  738. Arguments
  739. ---------
  740. routines
  741. List of Routine instances
  742. f
  743. File-like object to write the file to
  744. prefix
  745. The filename prefix, used to name the imported module.
  746. funcname
  747. Name of the main function to be returned.
  748. """
  749. if funcname is None:
  750. if len(routines) == 1:
  751. funcname = routines[0].name
  752. else:
  753. msg = 'funcname must be specified for multiple output routines'
  754. raise ValueError(msg)
  755. functions = []
  756. function_creation = []
  757. ufunc_init = []
  758. module = self.module_name
  759. include_file = "\"{}.h\"".format(prefix)
  760. top = _ufunc_top.substitute(include_file=include_file, module=module)
  761. name = funcname
  762. # Partition the C function arguments into categories
  763. # Here we assume all routines accept the same arguments
  764. r_index = 0
  765. py_in, _ = self._partition_args(routines[0].arguments)
  766. n_in = len(py_in)
  767. n_out = len(routines)
  768. # Declare Args
  769. form = "char *{0}{1} = args[{2}];"
  770. arg_decs = [form.format('in', i, i) for i in range(n_in)]
  771. arg_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
  772. declare_args = '\n '.join(arg_decs)
  773. # Declare Steps
  774. form = "npy_intp {0}{1}_step = steps[{2}];"
  775. step_decs = [form.format('in', i, i) for i in range(n_in)]
  776. step_decs.extend([form.format('out', i, i+n_in) for i in range(n_out)])
  777. declare_steps = '\n '.join(step_decs)
  778. # Call Args
  779. form = "*(double *)in{0}"
  780. call_args = ', '.join([form.format(a) for a in range(n_in)])
  781. # Step Increments
  782. form = "{0}{1} += {0}{1}_step;"
  783. step_incs = [form.format('in', i) for i in range(n_in)]
  784. step_incs.extend([form.format('out', i, i) for i in range(n_out)])
  785. step_increments = '\n '.join(step_incs)
  786. # Types
  787. n_types = n_in + n_out
  788. types = "{" + ', '.join(["NPY_DOUBLE"]*n_types) + "};"
  789. # Docstring
  790. docstring = '"Created in SymPy with Ufuncify"'
  791. # Function Creation
  792. function_creation.append("PyObject *ufunc{};".format(r_index))
  793. # Ufunc initialization
  794. init_form = _ufunc_init_form.substitute(module=module,
  795. funcname=name,
  796. docstring=docstring,
  797. n_in=n_in, n_out=n_out,
  798. ind=r_index)
  799. ufunc_init.append(init_form)
  800. outcalls = [_ufunc_outcalls.substitute(
  801. outnum=i, call_args=call_args, funcname=routines[i].name) for i in
  802. range(n_out)]
  803. body = _ufunc_body.substitute(module=module, funcname=name,
  804. declare_args=declare_args,
  805. declare_steps=declare_steps,
  806. call_args=call_args,
  807. step_increments=step_increments,
  808. n_types=n_types, types=types,
  809. outcalls='\n '.join(outcalls))
  810. functions.append(body)
  811. body = '\n\n'.join(functions)
  812. ufunc_init = '\n '.join(ufunc_init)
  813. function_creation = '\n '.join(function_creation)
  814. bottom = _ufunc_bottom.substitute(module=module,
  815. ufunc_init=ufunc_init,
  816. function_creation=function_creation)
  817. text = [top, body, bottom]
  818. f.write('\n\n'.join(text))
  819. def _partition_args(self, args):
  820. """Group function arguments into categories."""
  821. py_in = []
  822. py_out = []
  823. for arg in args:
  824. if isinstance(arg, OutputArgument):
  825. py_out.append(arg)
  826. elif isinstance(arg, InOutArgument):
  827. raise ValueError("Ufuncify doesn't support InOutArguments")
  828. else:
  829. py_in.append(arg)
  830. return py_in, py_out
  831. @cacheit
  832. @doctest_depends_on(exe=('f2py', 'gfortran', 'gcc'), modules=('numpy',))
  833. def ufuncify(args, expr, language=None, backend='numpy', tempdir=None,
  834. flags=None, verbose=False, helpers=None, **kwargs):
  835. """Generates a binary function that supports broadcasting on numpy arrays.
  836. Parameters
  837. ==========
  838. args : iterable
  839. Either a Symbol or an iterable of symbols. Specifies the argument
  840. sequence for the function.
  841. expr
  842. A SymPy expression that defines the element wise operation.
  843. language : string, optional
  844. If supplied, (options: 'C' or 'F95'), specifies the language of the
  845. generated code. If ``None`` [default], the language is inferred based
  846. upon the specified backend.
  847. backend : string, optional
  848. Backend used to wrap the generated code. Either 'numpy' [default],
  849. 'cython', or 'f2py'.
  850. tempdir : string, optional
  851. Path to directory for temporary files. If this argument is supplied,
  852. the generated code and the wrapper input files are left intact in
  853. the specified path.
  854. flags : iterable, optional
  855. Additional option flags that will be passed to the backend.
  856. verbose : bool, optional
  857. If True, autowrap will not mute the command line backends. This can
  858. be helpful for debugging.
  859. helpers : iterable, optional
  860. Used to define auxiliary expressions needed for the main expr. If
  861. the main expression needs to call a specialized function it should
  862. be put in the ``helpers`` iterable. Autowrap will then make sure
  863. that the compiled main expression can link to the helper routine.
  864. Items should be tuples with (<funtion_name>, <sympy_expression>,
  865. <arguments>). It is mandatory to supply an argument sequence to
  866. helper routines.
  867. kwargs : dict
  868. These kwargs will be passed to autowrap if the `f2py` or `cython`
  869. backend is used and ignored if the `numpy` backend is used.
  870. Notes
  871. =====
  872. The default backend ('numpy') will create actual instances of
  873. ``numpy.ufunc``. These support ndimensional broadcasting, and implicit type
  874. conversion. Use of the other backends will result in a "ufunc-like"
  875. function, which requires equal length 1-dimensional arrays for all
  876. arguments, and will not perform any type conversions.
  877. References
  878. ==========
  879. .. [1] https://numpy.org/doc/stable/reference/ufuncs.html
  880. Examples
  881. ========
  882. >>> from sympy.utilities.autowrap import ufuncify
  883. >>> from sympy.abc import x, y
  884. >>> import numpy as np
  885. >>> f = ufuncify((x, y), y + x**2)
  886. >>> type(f)
  887. <class 'numpy.ufunc'>
  888. >>> f([1, 2, 3], 2)
  889. array([ 3., 6., 11.])
  890. >>> f(np.arange(5), 3)
  891. array([ 3., 4., 7., 12., 19.])
  892. For the 'f2py' and 'cython' backends, inputs are required to be equal length
  893. 1-dimensional arrays. The 'f2py' backend will perform type conversion, but
  894. the Cython backend will error if the inputs are not of the expected type.
  895. >>> f_fortran = ufuncify((x, y), y + x**2, backend='f2py')
  896. >>> f_fortran(1, 2)
  897. array([ 3.])
  898. >>> f_fortran(np.array([1, 2, 3]), np.array([1.0, 2.0, 3.0]))
  899. array([ 2., 6., 12.])
  900. >>> f_cython = ufuncify((x, y), y + x**2, backend='Cython')
  901. >>> f_cython(1, 2) # doctest: +ELLIPSIS
  902. Traceback (most recent call last):
  903. ...
  904. TypeError: Argument '_x' has incorrect type (expected numpy.ndarray, got int)
  905. >>> f_cython(np.array([1.0]), np.array([2.0]))
  906. array([ 3.])
  907. """
  908. if isinstance(args, Symbol):
  909. args = (args,)
  910. else:
  911. args = tuple(args)
  912. if language:
  913. _validate_backend_language(backend, language)
  914. else:
  915. language = _infer_language(backend)
  916. helpers = helpers if helpers else ()
  917. flags = flags if flags else ()
  918. if backend.upper() == 'NUMPY':
  919. # maxargs is set by numpy compile-time constant NPY_MAXARGS
  920. # If a future version of numpy modifies or removes this restriction
  921. # this variable should be changed or removed
  922. maxargs = 32
  923. helps = []
  924. for name, expr, args in helpers:
  925. helps.append(make_routine(name, expr, args))
  926. code_wrapper = UfuncifyCodeWrapper(C99CodeGen("ufuncify"), tempdir,
  927. flags, verbose)
  928. if not isinstance(expr, (list, tuple)):
  929. expr = [expr]
  930. if len(expr) == 0:
  931. raise ValueError('Expression iterable has zero length')
  932. if len(expr) + len(args) > maxargs:
  933. msg = ('Cannot create ufunc with more than {0} total arguments: '
  934. 'got {1} in, {2} out')
  935. raise ValueError(msg.format(maxargs, len(args), len(expr)))
  936. routines = [make_routine('autofunc{}'.format(idx), exprx, args) for
  937. idx, exprx in enumerate(expr)]
  938. return code_wrapper.wrap_code(routines, helpers=helps)
  939. else:
  940. # Dummies are used for all added expressions to prevent name clashes
  941. # within the original expression.
  942. y = IndexedBase(Dummy('y'))
  943. m = Dummy('m', integer=True)
  944. i = Idx(Dummy('i', integer=True), m)
  945. f_dummy = Dummy('f')
  946. f = implemented_function('%s_%d' % (f_dummy.name, f_dummy.dummy_index), Lambda(args, expr))
  947. # For each of the args create an indexed version.
  948. indexed_args = [IndexedBase(Dummy(str(a))) for a in args]
  949. # Order the arguments (out, args, dim)
  950. args = [y] + indexed_args + [m]
  951. args_with_indices = [a[i] for a in indexed_args]
  952. return autowrap(Eq(y[i], f(*args_with_indices)), language, backend,
  953. tempdir, args, flags, verbose, helpers, **kwargs)