lambdify.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  1. """
  2. This module provides convenient functions to transform SymPy expressions to
  3. lambda functions which can be used to calculate numerical values very fast.
  4. """
  5. from typing import Any, Dict as tDict, Iterable, Union as tUnion, TYPE_CHECKING
  6. import builtins
  7. import inspect
  8. import keyword
  9. import textwrap
  10. import linecache
  11. # Required despite static analysis claiming it is not used
  12. from sympy.external import import_module # noqa:F401
  13. from sympy.utilities.exceptions import sympy_deprecation_warning
  14. from sympy.utilities.decorator import doctest_depends_on
  15. from sympy.utilities.iterables import (is_sequence, iterable,
  16. NotIterable, flatten)
  17. from sympy.utilities.misc import filldedent
  18. if TYPE_CHECKING:
  19. import sympy.core.expr
  20. __doctest_requires__ = {('lambdify',): ['numpy', 'tensorflow']}
  21. # Default namespaces, letting us define translations that can't be defined
  22. # by simple variable maps, like I => 1j
  23. MATH_DEFAULT = {} # type: tDict[str, Any]
  24. MPMATH_DEFAULT = {} # type: tDict[str, Any]
  25. NUMPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
  26. SCIPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
  27. CUPY_DEFAULT = {"I": 1j} # type: tDict[str, Any]
  28. TENSORFLOW_DEFAULT = {} # type: tDict[str, Any]
  29. SYMPY_DEFAULT = {} # type: tDict[str, Any]
  30. NUMEXPR_DEFAULT = {} # type: tDict[str, Any]
  31. # These are the namespaces the lambda functions will use.
  32. # These are separate from the names above because they are modified
  33. # throughout this file, whereas the defaults should remain unmodified.
  34. MATH = MATH_DEFAULT.copy()
  35. MPMATH = MPMATH_DEFAULT.copy()
  36. NUMPY = NUMPY_DEFAULT.copy()
  37. SCIPY = SCIPY_DEFAULT.copy()
  38. CUPY = CUPY_DEFAULT.copy()
  39. TENSORFLOW = TENSORFLOW_DEFAULT.copy()
  40. SYMPY = SYMPY_DEFAULT.copy()
  41. NUMEXPR = NUMEXPR_DEFAULT.copy()
  42. # Mappings between SymPy and other modules function names.
  43. MATH_TRANSLATIONS = {
  44. "ceiling": "ceil",
  45. "E": "e",
  46. "ln": "log",
  47. }
  48. # NOTE: This dictionary is reused in Function._eval_evalf to allow subclasses
  49. # of Function to automatically evalf.
  50. MPMATH_TRANSLATIONS = {
  51. "Abs": "fabs",
  52. "elliptic_k": "ellipk",
  53. "elliptic_f": "ellipf",
  54. "elliptic_e": "ellipe",
  55. "elliptic_pi": "ellippi",
  56. "ceiling": "ceil",
  57. "chebyshevt": "chebyt",
  58. "chebyshevu": "chebyu",
  59. "E": "e",
  60. "I": "j",
  61. "ln": "log",
  62. #"lowergamma":"lower_gamma",
  63. "oo": "inf",
  64. #"uppergamma":"upper_gamma",
  65. "LambertW": "lambertw",
  66. "MutableDenseMatrix": "matrix",
  67. "ImmutableDenseMatrix": "matrix",
  68. "conjugate": "conj",
  69. "dirichlet_eta": "altzeta",
  70. "Ei": "ei",
  71. "Shi": "shi",
  72. "Chi": "chi",
  73. "Si": "si",
  74. "Ci": "ci",
  75. "RisingFactorial": "rf",
  76. "FallingFactorial": "ff",
  77. "betainc_regularized": "betainc",
  78. }
  79. NUMPY_TRANSLATIONS = {
  80. "Heaviside": "heaviside",
  81. } # type: tDict[str, str]
  82. SCIPY_TRANSLATIONS = {} # type: tDict[str, str]
  83. CUPY_TRANSLATIONS = {} # type: tDict[str, str]
  84. TENSORFLOW_TRANSLATIONS = {} # type: tDict[str, str]
  85. NUMEXPR_TRANSLATIONS = {} # type: tDict[str, str]
  86. # Available modules:
  87. MODULES = {
  88. "math": (MATH, MATH_DEFAULT, MATH_TRANSLATIONS, ("from math import *",)),
  89. "mpmath": (MPMATH, MPMATH_DEFAULT, MPMATH_TRANSLATIONS, ("from mpmath import *",)),
  90. "numpy": (NUMPY, NUMPY_DEFAULT, NUMPY_TRANSLATIONS, ("import numpy; from numpy import *; from numpy.linalg import *",)),
  91. "scipy": (SCIPY, SCIPY_DEFAULT, SCIPY_TRANSLATIONS, ("import numpy; import scipy; from scipy import *; from scipy.special import *",)),
  92. "cupy": (CUPY, CUPY_DEFAULT, CUPY_TRANSLATIONS, ("import cupy",)),
  93. "tensorflow": (TENSORFLOW, TENSORFLOW_DEFAULT, TENSORFLOW_TRANSLATIONS, ("import tensorflow",)),
  94. "sympy": (SYMPY, SYMPY_DEFAULT, {}, (
  95. "from sympy.functions import *",
  96. "from sympy.matrices import *",
  97. "from sympy import Integral, pi, oo, nan, zoo, E, I",)),
  98. "numexpr" : (NUMEXPR, NUMEXPR_DEFAULT, NUMEXPR_TRANSLATIONS,
  99. ("import_module('numexpr')", )),
  100. }
  101. def _import(module, reload=False):
  102. """
  103. Creates a global translation dictionary for module.
  104. The argument module has to be one of the following strings: "math",
  105. "mpmath", "numpy", "sympy", "tensorflow".
  106. These dictionaries map names of Python functions to their equivalent in
  107. other modules.
  108. """
  109. try:
  110. namespace, namespace_default, translations, import_commands = MODULES[
  111. module]
  112. except KeyError:
  113. raise NameError(
  114. "'%s' module cannot be used for lambdification" % module)
  115. # Clear namespace or exit
  116. if namespace != namespace_default:
  117. # The namespace was already generated, don't do it again if not forced.
  118. if reload:
  119. namespace.clear()
  120. namespace.update(namespace_default)
  121. else:
  122. return
  123. for import_command in import_commands:
  124. if import_command.startswith('import_module'):
  125. module = eval(import_command)
  126. if module is not None:
  127. namespace.update(module.__dict__)
  128. continue
  129. else:
  130. try:
  131. exec(import_command, {}, namespace)
  132. continue
  133. except ImportError:
  134. pass
  135. raise ImportError(
  136. "Cannot import '%s' with '%s' command" % (module, import_command))
  137. # Add translated names to namespace
  138. for sympyname, translation in translations.items():
  139. namespace[sympyname] = namespace[translation]
  140. # For computing the modulus of a SymPy expression we use the builtin abs
  141. # function, instead of the previously used fabs function for all
  142. # translation modules. This is because the fabs function in the math
  143. # module does not accept complex valued arguments. (see issue 9474). The
  144. # only exception, where we don't use the builtin abs function is the
  145. # mpmath translation module, because mpmath.fabs returns mpf objects in
  146. # contrast to abs().
  147. if 'Abs' not in namespace:
  148. namespace['Abs'] = abs
  149. # Used for dynamically generated filenames that are inserted into the
  150. # linecache.
  151. _lambdify_generated_counter = 1
  152. @doctest_depends_on(modules=('numpy', 'scipy', 'tensorflow',), python_version=(3,))
  153. def lambdify(args: tUnion[Iterable, 'sympy.core.expr.Expr'], expr: 'sympy.core.expr.Expr', modules=None, printer=None, use_imps=True,
  154. dummify=False, cse=False):
  155. """Convert a SymPy expression into a function that allows for fast
  156. numeric evaluation.
  157. .. warning::
  158. This function uses ``exec``, and thus shouldn't be used on
  159. unsanitized input.
  160. .. deprecated:: 1.7
  161. Passing a set for the *args* parameter is deprecated as sets are
  162. unordered. Use an ordered iterable such as a list or tuple.
  163. Explanation
  164. ===========
  165. For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an
  166. equivalent NumPy function that numerically evaluates it:
  167. >>> from sympy import sin, cos, symbols, lambdify
  168. >>> import numpy as np
  169. >>> x = symbols('x')
  170. >>> expr = sin(x) + cos(x)
  171. >>> expr
  172. sin(x) + cos(x)
  173. >>> f = lambdify(x, expr, 'numpy')
  174. >>> a = np.array([1, 2])
  175. >>> f(a)
  176. [1.38177329 0.49315059]
  177. The primary purpose of this function is to provide a bridge from SymPy
  178. expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath,
  179. and tensorflow. In general, SymPy functions do not work with objects from
  180. other libraries, such as NumPy arrays, and functions from numeric
  181. libraries like NumPy or mpmath do not work on SymPy expressions.
  182. ``lambdify`` bridges the two by converting a SymPy expression to an
  183. equivalent numeric function.
  184. The basic workflow with ``lambdify`` is to first create a SymPy expression
  185. representing whatever mathematical function you wish to evaluate. This
  186. should be done using only SymPy functions and expressions. Then, use
  187. ``lambdify`` to convert this to an equivalent function for numerical
  188. evaluation. For instance, above we created ``expr`` using the SymPy symbol
  189. ``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an
  190. equivalent NumPy function ``f``, and called it on a NumPy array ``a``.
  191. Parameters
  192. ==========
  193. args : List[Symbol]
  194. A variable or a list of variables whose nesting represents the
  195. nesting of the arguments that will be passed to the function.
  196. Variables can be symbols, undefined functions, or matrix symbols.
  197. >>> from sympy import Eq
  198. >>> from sympy.abc import x, y, z
  199. The list of variables should match the structure of how the
  200. arguments will be passed to the function. Simply enclose the
  201. parameters as they will be passed in a list.
  202. To call a function like ``f(x)`` then ``[x]``
  203. should be the first argument to ``lambdify``; for this
  204. case a single ``x`` can also be used:
  205. >>> f = lambdify(x, x + 1)
  206. >>> f(1)
  207. 2
  208. >>> f = lambdify([x], x + 1)
  209. >>> f(1)
  210. 2
  211. To call a function like ``f(x, y)`` then ``[x, y]`` will
  212. be the first argument of the ``lambdify``:
  213. >>> f = lambdify([x, y], x + y)
  214. >>> f(1, 1)
  215. 2
  216. To call a function with a single 3-element tuple like
  217. ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first
  218. argument of the ``lambdify``:
  219. >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2))
  220. >>> f((3, 4, 5))
  221. True
  222. If two args will be passed and the first is a scalar but
  223. the second is a tuple with two arguments then the items
  224. in the list should match that structure:
  225. >>> f = lambdify([x, (y, z)], x + y + z)
  226. >>> f(1, (2, 3))
  227. 6
  228. expr : Expr
  229. An expression, list of expressions, or matrix to be evaluated.
  230. Lists may be nested.
  231. If the expression is a list, the output will also be a list.
  232. >>> f = lambdify(x, [x, [x + 1, x + 2]])
  233. >>> f(1)
  234. [1, [2, 3]]
  235. If it is a matrix, an array will be returned (for the NumPy module).
  236. >>> from sympy import Matrix
  237. >>> f = lambdify(x, Matrix([x, x + 1]))
  238. >>> f(1)
  239. [[1]
  240. [2]]
  241. Note that the argument order here (variables then expression) is used
  242. to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works
  243. (roughly) like ``lambda x: expr``
  244. (see :ref:`lambdify-how-it-works` below).
  245. modules : str, optional
  246. Specifies the numeric library to use.
  247. If not specified, *modules* defaults to:
  248. - ``["scipy", "numpy"]`` if SciPy is installed
  249. - ``["numpy"]`` if only NumPy is installed
  250. - ``["math", "mpmath", "sympy"]`` if neither is installed.
  251. That is, SymPy functions are replaced as far as possible by
  252. either ``scipy`` or ``numpy`` functions if available, and Python's
  253. standard library ``math``, or ``mpmath`` functions otherwise.
  254. *modules* can be one of the following types:
  255. - The strings ``"math"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``,
  256. ``"scipy"``, ``"sympy"``, or ``"tensorflow"``. This uses the
  257. corresponding printer and namespace mapping for that module.
  258. - A module (e.g., ``math``). This uses the global namespace of the
  259. module. If the module is one of the above known modules, it will
  260. also use the corresponding printer and namespace mapping
  261. (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``).
  262. - A dictionary that maps names of SymPy functions to arbitrary
  263. functions
  264. (e.g., ``{'sin': custom_sin}``).
  265. - A list that contains a mix of the arguments above, with higher
  266. priority given to entries appearing first
  267. (e.g., to use the NumPy module but override the ``sin`` function
  268. with a custom version, you can use
  269. ``[{'sin': custom_sin}, 'numpy']``).
  270. dummify : bool, optional
  271. Whether or not the variables in the provided expression that are not
  272. valid Python identifiers are substituted with dummy symbols.
  273. This allows for undefined functions like ``Function('f')(t)`` to be
  274. supplied as arguments. By default, the variables are only dummified
  275. if they are not valid Python identifiers.
  276. Set ``dummify=True`` to replace all arguments with dummy symbols
  277. (if ``args`` is not a string) - for example, to ensure that the
  278. arguments do not redefine any built-in names.
  279. cse : bool, or callable, optional
  280. Large expressions can be computed more efficiently when
  281. common subexpressions are identified and precomputed before
  282. being used multiple time. Finding the subexpressions will make
  283. creation of the 'lambdify' function slower, however.
  284. When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default)
  285. the user may pass a function matching the ``cse`` signature.
  286. Examples
  287. ========
  288. >>> from sympy.utilities.lambdify import implemented_function
  289. >>> from sympy import sqrt, sin, Matrix
  290. >>> from sympy import Function
  291. >>> from sympy.abc import w, x, y, z
  292. >>> f = lambdify(x, x**2)
  293. >>> f(2)
  294. 4
  295. >>> f = lambdify((x, y, z), [z, y, x])
  296. >>> f(1,2,3)
  297. [3, 2, 1]
  298. >>> f = lambdify(x, sqrt(x))
  299. >>> f(4)
  300. 2.0
  301. >>> f = lambdify((x, y), sin(x*y)**2)
  302. >>> f(0, 5)
  303. 0.0
  304. >>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
  305. >>> row(1, 2)
  306. Matrix([[1, 3]])
  307. ``lambdify`` can be used to translate SymPy expressions into mpmath
  308. functions. This may be preferable to using ``evalf`` (which uses mpmath on
  309. the backend) in some cases.
  310. >>> f = lambdify(x, sin(x), 'mpmath')
  311. >>> f(1)
  312. 0.8414709848078965
  313. Tuple arguments are handled and the lambdified function should
  314. be called with the same type of arguments as were used to create
  315. the function:
  316. >>> f = lambdify((x, (y, z)), x + y)
  317. >>> f(1, (2, 4))
  318. 3
  319. The ``flatten`` function can be used to always work with flattened
  320. arguments:
  321. >>> from sympy.utilities.iterables import flatten
  322. >>> args = w, (x, (y, z))
  323. >>> vals = 1, (2, (3, 4))
  324. >>> f = lambdify(flatten(args), w + x + y + z)
  325. >>> f(*flatten(vals))
  326. 10
  327. Functions present in ``expr`` can also carry their own numerical
  328. implementations, in a callable attached to the ``_imp_`` attribute. This
  329. can be used with undefined functions using the ``implemented_function``
  330. factory:
  331. >>> f = implemented_function(Function('f'), lambda x: x+1)
  332. >>> func = lambdify(x, f(x))
  333. >>> func(4)
  334. 5
  335. ``lambdify`` always prefers ``_imp_`` implementations to implementations
  336. in other namespaces, unless the ``use_imps`` input parameter is False.
  337. Usage with Tensorflow:
  338. >>> import tensorflow as tf
  339. >>> from sympy import Max, sin, lambdify
  340. >>> from sympy.abc import x
  341. >>> f = Max(x, sin(x))
  342. >>> func = lambdify(x, f, 'tensorflow')
  343. After tensorflow v2, eager execution is enabled by default.
  344. If you want to get the compatible result across tensorflow v1 and v2
  345. as same as this tutorial, run this line.
  346. >>> tf.compat.v1.enable_eager_execution()
  347. If you have eager execution enabled, you can get the result out
  348. immediately as you can use numpy.
  349. If you pass tensorflow objects, you may get an ``EagerTensor``
  350. object instead of value.
  351. >>> result = func(tf.constant(1.0))
  352. >>> print(result)
  353. tf.Tensor(1.0, shape=(), dtype=float32)
  354. >>> print(result.__class__)
  355. <class 'tensorflow.python.framework.ops.EagerTensor'>
  356. You can use ``.numpy()`` to get the numpy value of the tensor.
  357. >>> result.numpy()
  358. 1.0
  359. >>> var = tf.Variable(2.0)
  360. >>> result = func(var) # also works for tf.Variable and tf.Placeholder
  361. >>> result.numpy()
  362. 2.0
  363. And it works with any shape array.
  364. >>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
  365. >>> result = func(tensor)
  366. >>> result.numpy()
  367. [[1. 2.]
  368. [3. 4.]]
  369. Notes
  370. =====
  371. - For functions involving large array calculations, numexpr can provide a
  372. significant speedup over numpy. Please note that the available functions
  373. for numexpr are more limited than numpy but can be expanded with
  374. ``implemented_function`` and user defined subclasses of Function. If
  375. specified, numexpr may be the only option in modules. The official list
  376. of numexpr functions can be found at:
  377. https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions
  378. - In previous versions of SymPy, ``lambdify`` replaced ``Matrix`` with
  379. ``numpy.matrix`` by default. As of SymPy 1.0 ``numpy.array`` is the
  380. default. To get the old default behavior you must pass in
  381. ``[{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']`` to the
  382. ``modules`` kwarg.
  383. >>> from sympy import lambdify, Matrix
  384. >>> from sympy.abc import x, y
  385. >>> import numpy
  386. >>> array2mat = [{'ImmutableDenseMatrix': numpy.matrix}, 'numpy']
  387. >>> f = lambdify((x, y), Matrix([x, y]), modules=array2mat)
  388. >>> f(1, 2)
  389. [[1]
  390. [2]]
  391. - In the above examples, the generated functions can accept scalar
  392. values or numpy arrays as arguments. However, in some cases
  393. the generated function relies on the input being a numpy array:
  394. >>> from sympy import Piecewise
  395. >>> from sympy.testing.pytest import ignore_warnings
  396. >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy")
  397. >>> with ignore_warnings(RuntimeWarning):
  398. ... f(numpy.array([-1, 0, 1, 2]))
  399. [-1. 0. 1. 0.5]
  400. >>> f(0)
  401. Traceback (most recent call last):
  402. ...
  403. ZeroDivisionError: division by zero
  404. In such cases, the input should be wrapped in a numpy array:
  405. >>> with ignore_warnings(RuntimeWarning):
  406. ... float(f(numpy.array([0])))
  407. 0.0
  408. Or if numpy functionality is not required another module can be used:
  409. >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math")
  410. >>> f(0)
  411. 0
  412. .. _lambdify-how-it-works:
  413. How it works
  414. ============
  415. When using this function, it helps a great deal to have an idea of what it
  416. is doing. At its core, lambdify is nothing more than a namespace
  417. translation, on top of a special printer that makes some corner cases work
  418. properly.
  419. To understand lambdify, first we must properly understand how Python
  420. namespaces work. Say we had two files. One called ``sin_cos_sympy.py``,
  421. with
  422. .. code:: python
  423. # sin_cos_sympy.py
  424. from sympy.functions.elementary.trigonometric import (cos, sin)
  425. def sin_cos(x):
  426. return sin(x) + cos(x)
  427. and one called ``sin_cos_numpy.py`` with
  428. .. code:: python
  429. # sin_cos_numpy.py
  430. from numpy import sin, cos
  431. def sin_cos(x):
  432. return sin(x) + cos(x)
  433. The two files define an identical function ``sin_cos``. However, in the
  434. first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and
  435. ``cos``. In the second, they are defined as the NumPy versions.
  436. If we were to import the first file and use the ``sin_cos`` function, we
  437. would get something like
  438. >>> from sin_cos_sympy import sin_cos # doctest: +SKIP
  439. >>> sin_cos(1) # doctest: +SKIP
  440. cos(1) + sin(1)
  441. On the other hand, if we imported ``sin_cos`` from the second file, we
  442. would get
  443. >>> from sin_cos_numpy import sin_cos # doctest: +SKIP
  444. >>> sin_cos(1) # doctest: +SKIP
  445. 1.38177329068
  446. In the first case we got a symbolic output, because it used the symbolic
  447. ``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric
  448. result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions
  449. from NumPy. But notice that the versions of ``sin`` and ``cos`` that were
  450. used was not inherent to the ``sin_cos`` function definition. Both
  451. ``sin_cos`` definitions are exactly the same. Rather, it was based on the
  452. names defined at the module where the ``sin_cos`` function was defined.
  453. The key point here is that when function in Python references a name that
  454. is not defined in the function, that name is looked up in the "global"
  455. namespace of the module where that function is defined.
  456. Now, in Python, we can emulate this behavior without actually writing a
  457. file to disk using the ``exec`` function. ``exec`` takes a string
  458. containing a block of Python code, and a dictionary that should contain
  459. the global variables of the module. It then executes the code "in" that
  460. dictionary, as if it were the module globals. The following is equivalent
  461. to the ``sin_cos`` defined in ``sin_cos_sympy.py``:
  462. >>> import sympy
  463. >>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos}
  464. >>> exec('''
  465. ... def sin_cos(x):
  466. ... return sin(x) + cos(x)
  467. ... ''', module_dictionary)
  468. >>> sin_cos = module_dictionary['sin_cos']
  469. >>> sin_cos(1)
  470. cos(1) + sin(1)
  471. and similarly with ``sin_cos_numpy``:
  472. >>> import numpy
  473. >>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos}
  474. >>> exec('''
  475. ... def sin_cos(x):
  476. ... return sin(x) + cos(x)
  477. ... ''', module_dictionary)
  478. >>> sin_cos = module_dictionary['sin_cos']
  479. >>> sin_cos(1)
  480. 1.38177329068
  481. So now we can get an idea of how ``lambdify`` works. The name "lambdify"
  482. comes from the fact that we can think of something like ``lambdify(x,
  483. sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where
  484. ``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why
  485. the symbols argument is first in ``lambdify``, as opposed to most SymPy
  486. functions where it comes after the expression: to better mimic the
  487. ``lambda`` keyword.
  488. ``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and
  489. 1. Converts it to a string
  490. 2. Creates a module globals dictionary based on the modules that are
  491. passed in (by default, it uses the NumPy module)
  492. 3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the
  493. list of variables separated by commas, and ``{expr}`` is the string
  494. created in step 1., then ``exec``s that string with the module globals
  495. namespace and returns ``func``.
  496. In fact, functions returned by ``lambdify`` support inspection. So you can
  497. see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you
  498. are using IPython or the Jupyter notebook.
  499. >>> f = lambdify(x, sin(x) + cos(x))
  500. >>> import inspect
  501. >>> print(inspect.getsource(f))
  502. def _lambdifygenerated(x):
  503. return sin(x) + cos(x)
  504. This shows us the source code of the function, but not the namespace it
  505. was defined in. We can inspect that by looking at the ``__globals__``
  506. attribute of ``f``:
  507. >>> f.__globals__['sin']
  508. <ufunc 'sin'>
  509. >>> f.__globals__['cos']
  510. <ufunc 'cos'>
  511. >>> f.__globals__['sin'] is numpy.sin
  512. True
  513. This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be
  514. ``numpy.sin`` and ``numpy.cos``.
  515. Note that there are some convenience layers in each of these steps, but at
  516. the core, this is how ``lambdify`` works. Step 1 is done using the
  517. ``LambdaPrinter`` printers defined in the printing module (see
  518. :mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions
  519. to define how they should be converted to a string for different modules.
  520. You can change which printer ``lambdify`` uses by passing a custom printer
  521. in to the ``printer`` argument.
  522. Step 2 is augmented by certain translations. There are default
  523. translations for each module, but you can provide your own by passing a
  524. list to the ``modules`` argument. For instance,
  525. >>> def mysin(x):
  526. ... print('taking the sin of', x)
  527. ... return numpy.sin(x)
  528. ...
  529. >>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy'])
  530. >>> f(1)
  531. taking the sin of 1
  532. 0.8414709848078965
  533. The globals dictionary is generated from the list by merging the
  534. dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The
  535. merging is done so that earlier items take precedence, which is why
  536. ``mysin`` is used above instead of ``numpy.sin``.
  537. If you want to modify the way ``lambdify`` works for a given function, it
  538. is usually easiest to do so by modifying the globals dictionary as such.
  539. In more complicated cases, it may be necessary to create and pass in a
  540. custom printer.
  541. Finally, step 3 is augmented with certain convenience operations, such as
  542. the addition of a docstring.
  543. Understanding how ``lambdify`` works can make it easier to avoid certain
  544. gotchas when using it. For instance, a common mistake is to create a
  545. lambdified function for one module (say, NumPy), and pass it objects from
  546. another (say, a SymPy expression).
  547. For instance, say we create
  548. >>> from sympy.abc import x
  549. >>> f = lambdify(x, x + 1, 'numpy')
  550. Now if we pass in a NumPy array, we get that array plus 1
  551. >>> import numpy
  552. >>> a = numpy.array([1, 2])
  553. >>> f(a)
  554. [2 3]
  555. But what happens if you make the mistake of passing in a SymPy expression
  556. instead of a NumPy array:
  557. >>> f(x + 1)
  558. x + 2
  559. This worked, but it was only by accident. Now take a different lambdified
  560. function:
  561. >>> from sympy import sin
  562. >>> g = lambdify(x, x + sin(x), 'numpy')
  563. This works as expected on NumPy arrays:
  564. >>> g(a)
  565. [1.84147098 2.90929743]
  566. But if we try to pass in a SymPy expression, it fails
  567. >>> try:
  568. ... g(x + 1)
  569. ... # NumPy release after 1.17 raises TypeError instead of
  570. ... # AttributeError
  571. ... except (AttributeError, TypeError):
  572. ... raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL
  573. Traceback (most recent call last):
  574. ...
  575. AttributeError:
  576. Now, let's look at what happened. The reason this fails is that ``g``
  577. calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not
  578. know how to operate on a SymPy object. **As a general rule, NumPy
  579. functions do not know how to operate on SymPy expressions, and SymPy
  580. functions do not know how to operate on NumPy arrays. This is why lambdify
  581. exists: to provide a bridge between SymPy and NumPy.**
  582. However, why is it that ``f`` did work? That's because ``f`` doesn't call
  583. any functions, it only adds 1. So the resulting function that is created,
  584. ``def _lambdifygenerated(x): return x + 1`` does not depend on the globals
  585. namespace it is defined in. Thus it works, but only by accident. A future
  586. version of ``lambdify`` may remove this behavior.
  587. Be aware that certain implementation details described here may change in
  588. future versions of SymPy. The API of passing in custom modules and
  589. printers will not change, but the details of how a lambda function is
  590. created may change. However, the basic idea will remain the same, and
  591. understanding it will be helpful to understanding the behavior of
  592. lambdify.
  593. **In general: you should create lambdified functions for one module (say,
  594. NumPy), and only pass it input types that are compatible with that module
  595. (say, NumPy arrays).** Remember that by default, if the ``module``
  596. argument is not provided, ``lambdify`` creates functions using the NumPy
  597. and SciPy namespaces.
  598. """
  599. from sympy.core.symbol import Symbol
  600. from sympy.core.expr import Expr
  601. # If the user hasn't specified any modules, use what is available.
  602. if modules is None:
  603. try:
  604. _import("scipy")
  605. except ImportError:
  606. try:
  607. _import("numpy")
  608. except ImportError:
  609. # Use either numpy (if available) or python.math where possible.
  610. # XXX: This leads to different behaviour on different systems and
  611. # might be the reason for irreproducible errors.
  612. modules = ["math", "mpmath", "sympy"]
  613. else:
  614. modules = ["numpy"]
  615. else:
  616. modules = ["numpy", "scipy"]
  617. # Get the needed namespaces.
  618. namespaces = []
  619. # First find any function implementations
  620. if use_imps:
  621. namespaces.append(_imp_namespace(expr))
  622. # Check for dict before iterating
  623. if isinstance(modules, (dict, str)) or not hasattr(modules, '__iter__'):
  624. namespaces.append(modules)
  625. else:
  626. # consistency check
  627. if _module_present('numexpr', modules) and len(modules) > 1:
  628. raise TypeError("numexpr must be the only item in 'modules'")
  629. namespaces += list(modules)
  630. # fill namespace with first having highest priority
  631. namespace = {} # type: tDict[str, Any]
  632. for m in namespaces[::-1]:
  633. buf = _get_namespace(m)
  634. namespace.update(buf)
  635. if hasattr(expr, "atoms"):
  636. #Try if you can extract symbols from the expression.
  637. #Move on if expr.atoms in not implemented.
  638. syms = expr.atoms(Symbol)
  639. for term in syms:
  640. namespace.update({str(term): term})
  641. if printer is None:
  642. if _module_present('mpmath', namespaces):
  643. from sympy.printing.pycode import MpmathPrinter as Printer # type: ignore
  644. elif _module_present('scipy', namespaces):
  645. from sympy.printing.numpy import SciPyPrinter as Printer # type: ignore
  646. elif _module_present('numpy', namespaces):
  647. from sympy.printing.numpy import NumPyPrinter as Printer # type: ignore
  648. elif _module_present('cupy', namespaces):
  649. from sympy.printing.numpy import CuPyPrinter as Printer # type: ignore
  650. elif _module_present('numexpr', namespaces):
  651. from sympy.printing.lambdarepr import NumExprPrinter as Printer # type: ignore
  652. elif _module_present('tensorflow', namespaces):
  653. from sympy.printing.tensorflow import TensorflowPrinter as Printer # type: ignore
  654. elif _module_present('sympy', namespaces):
  655. from sympy.printing.pycode import SymPyPrinter as Printer # type: ignore
  656. else:
  657. from sympy.printing.pycode import PythonCodePrinter as Printer # type: ignore
  658. user_functions = {}
  659. for m in namespaces[::-1]:
  660. if isinstance(m, dict):
  661. for k in m:
  662. user_functions[k] = k
  663. printer = Printer({'fully_qualified_modules': False, 'inline': True,
  664. 'allow_unknown_functions': True,
  665. 'user_functions': user_functions})
  666. if isinstance(args, set):
  667. sympy_deprecation_warning(
  668. """
  669. Passing the function arguments to lambdify() as a set is deprecated. This
  670. leads to unpredictable results since sets are unordered. Instead, use a list
  671. or tuple for the function arguments.
  672. """,
  673. deprecated_since_version="1.6.3",
  674. active_deprecations_target="deprecated-lambdify-arguments-set",
  675. )
  676. # Get the names of the args, for creating a docstring
  677. iterable_args: Iterable = (args,) if isinstance(args, Expr) else args
  678. names = []
  679. # Grab the callers frame, for getting the names by inspection (if needed)
  680. callers_local_vars = inspect.currentframe().f_back.f_locals.items() # type: ignore
  681. for n, var in enumerate(iterable_args):
  682. if hasattr(var, 'name'):
  683. names.append(var.name)
  684. else:
  685. # It's an iterable. Try to get name by inspection of calling frame.
  686. name_list = [var_name for var_name, var_val in callers_local_vars
  687. if var_val is var]
  688. if len(name_list) == 1:
  689. names.append(name_list[0])
  690. else:
  691. # Cannot infer name with certainty. arg_# will have to do.
  692. names.append('arg_' + str(n))
  693. # Create the function definition code and execute it
  694. funcname = '_lambdifygenerated'
  695. if _module_present('tensorflow', namespaces):
  696. funcprinter = _TensorflowEvaluatorPrinter(printer, dummify) # type: _EvaluatorPrinter
  697. else:
  698. funcprinter = _EvaluatorPrinter(printer, dummify)
  699. if cse == True:
  700. from sympy.simplify.cse_main import cse as _cse
  701. cses, _expr = _cse(expr, list=False)
  702. elif callable(cse):
  703. cses, _expr = cse(expr)
  704. else:
  705. cses, _expr = (), expr
  706. funcstr = funcprinter.doprint(funcname, iterable_args, _expr, cses=cses)
  707. # Collect the module imports from the code printers.
  708. imp_mod_lines = []
  709. for mod, keys in (getattr(printer, 'module_imports', None) or {}).items():
  710. for k in keys:
  711. if k not in namespace:
  712. ln = "from %s import %s" % (mod, k)
  713. try:
  714. exec(ln, {}, namespace)
  715. except ImportError:
  716. # Tensorflow 2.0 has issues with importing a specific
  717. # function from its submodule.
  718. # https://github.com/tensorflow/tensorflow/issues/33022
  719. ln = "%s = %s.%s" % (k, mod, k)
  720. exec(ln, {}, namespace)
  721. imp_mod_lines.append(ln)
  722. # Provide lambda expression with builtins, and compatible implementation of range
  723. namespace.update({'builtins':builtins, 'range':range})
  724. funclocals = {} # type: tDict[str, Any]
  725. global _lambdify_generated_counter
  726. filename = '<lambdifygenerated-%s>' % _lambdify_generated_counter
  727. _lambdify_generated_counter += 1
  728. c = compile(funcstr, filename, 'exec')
  729. exec(c, namespace, funclocals)
  730. # mtime has to be None or else linecache.checkcache will remove it
  731. linecache.cache[filename] = (len(funcstr), None, funcstr.splitlines(True), filename) # type: ignore
  732. func = funclocals[funcname]
  733. # Apply the docstring
  734. sig = "func({})".format(", ".join(str(i) for i in names))
  735. sig = textwrap.fill(sig, subsequent_indent=' '*8)
  736. expr_str = str(expr)
  737. if len(expr_str) > 78:
  738. expr_str = textwrap.wrap(expr_str, 75)[0] + '...'
  739. func.__doc__ = (
  740. "Created with lambdify. Signature:\n\n"
  741. "{sig}\n\n"
  742. "Expression:\n\n"
  743. "{expr}\n\n"
  744. "Source code:\n\n"
  745. "{src}\n\n"
  746. "Imported modules:\n\n"
  747. "{imp_mods}"
  748. ).format(sig=sig, expr=expr_str, src=funcstr, imp_mods='\n'.join(imp_mod_lines))
  749. return func
  750. def _module_present(modname, modlist):
  751. if modname in modlist:
  752. return True
  753. for m in modlist:
  754. if hasattr(m, '__name__') and m.__name__ == modname:
  755. return True
  756. return False
  757. def _get_namespace(m):
  758. """
  759. This is used by _lambdify to parse its arguments.
  760. """
  761. if isinstance(m, str):
  762. _import(m)
  763. return MODULES[m][0]
  764. elif isinstance(m, dict):
  765. return m
  766. elif hasattr(m, "__dict__"):
  767. return m.__dict__
  768. else:
  769. raise TypeError("Argument must be either a string, dict or module but it is: %s" % m)
  770. def _recursive_to_string(doprint, arg):
  771. """Functions in lambdify accept both SymPy types and non-SymPy types such as python
  772. lists and tuples. This method ensures that we only call the doprint method of the
  773. printer with SymPy types (so that the printer safely can use SymPy-methods)."""
  774. from sympy.matrices.common import MatrixOperations
  775. from sympy.core.basic import Basic
  776. if isinstance(arg, (Basic, MatrixOperations)):
  777. return doprint(arg)
  778. elif iterable(arg):
  779. if isinstance(arg, list):
  780. left, right = "[]"
  781. elif isinstance(arg, tuple):
  782. left, right = "()"
  783. else:
  784. raise NotImplementedError("unhandled type: %s, %s" % (type(arg), arg))
  785. return left +', '.join(_recursive_to_string(doprint, e) for e in arg) + right
  786. elif isinstance(arg, str):
  787. return arg
  788. else:
  789. return doprint(arg)
  790. def lambdastr(args, expr, printer=None, dummify=None):
  791. """
  792. Returns a string that can be evaluated to a lambda function.
  793. Examples
  794. ========
  795. >>> from sympy.abc import x, y, z
  796. >>> from sympy.utilities.lambdify import lambdastr
  797. >>> lambdastr(x, x**2)
  798. 'lambda x: (x**2)'
  799. >>> lambdastr((x,y,z), [z,y,x])
  800. 'lambda x,y,z: ([z, y, x])'
  801. Although tuples may not appear as arguments to lambda in Python 3,
  802. lambdastr will create a lambda function that will unpack the original
  803. arguments so that nested arguments can be handled:
  804. >>> lambdastr((x, (y, z)), x + y)
  805. 'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'
  806. """
  807. # Transforming everything to strings.
  808. from sympy.matrices import DeferredVector
  809. from sympy.core.basic import Basic
  810. from sympy.core.function import (Derivative, Function)
  811. from sympy.core.symbol import (Dummy, Symbol)
  812. from sympy.core.sympify import sympify
  813. if printer is not None:
  814. if inspect.isfunction(printer):
  815. lambdarepr = printer
  816. else:
  817. if inspect.isclass(printer):
  818. lambdarepr = lambda expr: printer().doprint(expr)
  819. else:
  820. lambdarepr = lambda expr: printer.doprint(expr)
  821. else:
  822. #XXX: This has to be done here because of circular imports
  823. from sympy.printing.lambdarepr import lambdarepr
  824. def sub_args(args, dummies_dict):
  825. if isinstance(args, str):
  826. return args
  827. elif isinstance(args, DeferredVector):
  828. return str(args)
  829. elif iterable(args):
  830. dummies = flatten([sub_args(a, dummies_dict) for a in args])
  831. return ",".join(str(a) for a in dummies)
  832. else:
  833. # replace these with Dummy symbols
  834. if isinstance(args, (Function, Symbol, Derivative)):
  835. dummies = Dummy()
  836. dummies_dict.update({args : dummies})
  837. return str(dummies)
  838. else:
  839. return str(args)
  840. def sub_expr(expr, dummies_dict):
  841. expr = sympify(expr)
  842. # dict/tuple are sympified to Basic
  843. if isinstance(expr, Basic):
  844. expr = expr.xreplace(dummies_dict)
  845. # list is not sympified to Basic
  846. elif isinstance(expr, list):
  847. expr = [sub_expr(a, dummies_dict) for a in expr]
  848. return expr
  849. # Transform args
  850. def isiter(l):
  851. return iterable(l, exclude=(str, DeferredVector, NotIterable))
  852. def flat_indexes(iterable):
  853. n = 0
  854. for el in iterable:
  855. if isiter(el):
  856. for ndeep in flat_indexes(el):
  857. yield (n,) + ndeep
  858. else:
  859. yield (n,)
  860. n += 1
  861. if dummify is None:
  862. dummify = any(isinstance(a, Basic) and
  863. a.atoms(Function, Derivative) for a in (
  864. args if isiter(args) else [args]))
  865. if isiter(args) and any(isiter(i) for i in args):
  866. dum_args = [str(Dummy(str(i))) for i in range(len(args))]
  867. indexed_args = ','.join([
  868. dum_args[ind[0]] + ''.join(["[%s]" % k for k in ind[1:]])
  869. for ind in flat_indexes(args)])
  870. lstr = lambdastr(flatten(args), expr, printer=printer, dummify=dummify)
  871. return 'lambda %s: (%s)(%s)' % (','.join(dum_args), lstr, indexed_args)
  872. dummies_dict = {}
  873. if dummify:
  874. args = sub_args(args, dummies_dict)
  875. else:
  876. if isinstance(args, str):
  877. pass
  878. elif iterable(args, exclude=DeferredVector):
  879. args = ",".join(str(a) for a in args)
  880. # Transform expr
  881. if dummify:
  882. if isinstance(expr, str):
  883. pass
  884. else:
  885. expr = sub_expr(expr, dummies_dict)
  886. expr = _recursive_to_string(lambdarepr, expr)
  887. return "lambda %s: (%s)" % (args, expr)
  888. class _EvaluatorPrinter:
  889. def __init__(self, printer=None, dummify=False):
  890. self._dummify = dummify
  891. #XXX: This has to be done here because of circular imports
  892. from sympy.printing.lambdarepr import LambdaPrinter
  893. if printer is None:
  894. printer = LambdaPrinter()
  895. if inspect.isfunction(printer):
  896. self._exprrepr = printer
  897. else:
  898. if inspect.isclass(printer):
  899. printer = printer()
  900. self._exprrepr = printer.doprint
  901. #if hasattr(printer, '_print_Symbol'):
  902. # symbolrepr = printer._print_Symbol
  903. #if hasattr(printer, '_print_Dummy'):
  904. # dummyrepr = printer._print_Dummy
  905. # Used to print the generated function arguments in a standard way
  906. self._argrepr = LambdaPrinter().doprint
  907. def doprint(self, funcname, args, expr, *, cses=()):
  908. """
  909. Returns the function definition code as a string.
  910. """
  911. from sympy.core.symbol import Dummy
  912. funcbody = []
  913. if not iterable(args):
  914. args = [args]
  915. argstrs, expr = self._preprocess(args, expr)
  916. # Generate argument unpacking and final argument list
  917. funcargs = []
  918. unpackings = []
  919. for argstr in argstrs:
  920. if iterable(argstr):
  921. funcargs.append(self._argrepr(Dummy()))
  922. unpackings.extend(self._print_unpacking(argstr, funcargs[-1]))
  923. else:
  924. funcargs.append(argstr)
  925. funcsig = 'def {}({}):'.format(funcname, ', '.join(funcargs))
  926. # Wrap input arguments before unpacking
  927. funcbody.extend(self._print_funcargwrapping(funcargs))
  928. funcbody.extend(unpackings)
  929. for s, e in cses:
  930. if e is None:
  931. funcbody.append('del {}'.format(s))
  932. else:
  933. funcbody.append('{} = {}'.format(s, self._exprrepr(e)))
  934. str_expr = _recursive_to_string(self._exprrepr, expr)
  935. if '\n' in str_expr:
  936. str_expr = '({})'.format(str_expr)
  937. funcbody.append('return {}'.format(str_expr))
  938. funclines = [funcsig]
  939. funclines.extend([' ' + line for line in funcbody])
  940. return '\n'.join(funclines) + '\n'
  941. @classmethod
  942. def _is_safe_ident(cls, ident):
  943. return isinstance(ident, str) and ident.isidentifier() \
  944. and not keyword.iskeyword(ident)
  945. def _preprocess(self, args, expr):
  946. """Preprocess args, expr to replace arguments that do not map
  947. to valid Python identifiers.
  948. Returns string form of args, and updated expr.
  949. """
  950. from sympy.core.basic import Basic
  951. from sympy.core.sorting import ordered
  952. from sympy.core.function import (Derivative, Function)
  953. from sympy.core.symbol import Dummy, uniquely_named_symbol
  954. from sympy.matrices import DeferredVector
  955. from sympy.core.expr import Expr
  956. # Args of type Dummy can cause name collisions with args
  957. # of type Symbol. Force dummify of everything in this
  958. # situation.
  959. dummify = self._dummify or any(
  960. isinstance(arg, Dummy) for arg in flatten(args))
  961. argstrs = [None]*len(args)
  962. for arg, i in reversed(list(ordered(zip(args, range(len(args)))))):
  963. if iterable(arg):
  964. s, expr = self._preprocess(arg, expr)
  965. elif isinstance(arg, DeferredVector):
  966. s = str(arg)
  967. elif isinstance(arg, Basic) and arg.is_symbol:
  968. s = self._argrepr(arg)
  969. if dummify or not self._is_safe_ident(s):
  970. dummy = Dummy()
  971. if isinstance(expr, Expr):
  972. dummy = uniquely_named_symbol(
  973. dummy.name, expr, modify=lambda s: '_' + s)
  974. s = self._argrepr(dummy)
  975. expr = self._subexpr(expr, {arg: dummy})
  976. elif dummify or isinstance(arg, (Function, Derivative)):
  977. dummy = Dummy()
  978. s = self._argrepr(dummy)
  979. expr = self._subexpr(expr, {arg: dummy})
  980. else:
  981. s = str(arg)
  982. argstrs[i] = s
  983. return argstrs, expr
  984. def _subexpr(self, expr, dummies_dict):
  985. from sympy.matrices import DeferredVector
  986. from sympy.core.sympify import sympify
  987. expr = sympify(expr)
  988. xreplace = getattr(expr, 'xreplace', None)
  989. if xreplace is not None:
  990. expr = xreplace(dummies_dict)
  991. else:
  992. if isinstance(expr, DeferredVector):
  993. pass
  994. elif isinstance(expr, dict):
  995. k = [self._subexpr(sympify(a), dummies_dict) for a in expr.keys()]
  996. v = [self._subexpr(sympify(a), dummies_dict) for a in expr.values()]
  997. expr = dict(zip(k, v))
  998. elif isinstance(expr, tuple):
  999. expr = tuple(self._subexpr(sympify(a), dummies_dict) for a in expr)
  1000. elif isinstance(expr, list):
  1001. expr = [self._subexpr(sympify(a), dummies_dict) for a in expr]
  1002. return expr
  1003. def _print_funcargwrapping(self, args):
  1004. """Generate argument wrapping code.
  1005. args is the argument list of the generated function (strings).
  1006. Return value is a list of lines of code that will be inserted at
  1007. the beginning of the function definition.
  1008. """
  1009. return []
  1010. def _print_unpacking(self, unpackto, arg):
  1011. """Generate argument unpacking code.
  1012. arg is the function argument to be unpacked (a string), and
  1013. unpackto is a list or nested lists of the variable names (strings) to
  1014. unpack to.
  1015. """
  1016. def unpack_lhs(lvalues):
  1017. return '[{}]'.format(', '.join(
  1018. unpack_lhs(val) if iterable(val) else val for val in lvalues))
  1019. return ['{} = {}'.format(unpack_lhs(unpackto), arg)]
  1020. class _TensorflowEvaluatorPrinter(_EvaluatorPrinter):
  1021. def _print_unpacking(self, lvalues, rvalue):
  1022. """Generate argument unpacking code.
  1023. This method is used when the input value is not interable,
  1024. but can be indexed (see issue #14655).
  1025. """
  1026. def flat_indexes(elems):
  1027. n = 0
  1028. for el in elems:
  1029. if iterable(el):
  1030. for ndeep in flat_indexes(el):
  1031. yield (n,) + ndeep
  1032. else:
  1033. yield (n,)
  1034. n += 1
  1035. indexed = ', '.join('{}[{}]'.format(rvalue, ']['.join(map(str, ind)))
  1036. for ind in flat_indexes(lvalues))
  1037. return ['[{}] = [{}]'.format(', '.join(flatten(lvalues)), indexed)]
  1038. def _imp_namespace(expr, namespace=None):
  1039. """ Return namespace dict with function implementations
  1040. We need to search for functions in anything that can be thrown at
  1041. us - that is - anything that could be passed as ``expr``. Examples
  1042. include SymPy expressions, as well as tuples, lists and dicts that may
  1043. contain SymPy expressions.
  1044. Parameters
  1045. ----------
  1046. expr : object
  1047. Something passed to lambdify, that will generate valid code from
  1048. ``str(expr)``.
  1049. namespace : None or mapping
  1050. Namespace to fill. None results in new empty dict
  1051. Returns
  1052. -------
  1053. namespace : dict
  1054. dict with keys of implemented function names within ``expr`` and
  1055. corresponding values being the numerical implementation of
  1056. function
  1057. Examples
  1058. ========
  1059. >>> from sympy.abc import x
  1060. >>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
  1061. >>> from sympy import Function
  1062. >>> f = implemented_function(Function('f'), lambda x: x+1)
  1063. >>> g = implemented_function(Function('g'), lambda x: x*10)
  1064. >>> namespace = _imp_namespace(f(g(x)))
  1065. >>> sorted(namespace.keys())
  1066. ['f', 'g']
  1067. """
  1068. # Delayed import to avoid circular imports
  1069. from sympy.core.function import FunctionClass
  1070. if namespace is None:
  1071. namespace = {}
  1072. # tuples, lists, dicts are valid expressions
  1073. if is_sequence(expr):
  1074. for arg in expr:
  1075. _imp_namespace(arg, namespace)
  1076. return namespace
  1077. elif isinstance(expr, dict):
  1078. for key, val in expr.items():
  1079. # functions can be in dictionary keys
  1080. _imp_namespace(key, namespace)
  1081. _imp_namespace(val, namespace)
  1082. return namespace
  1083. # SymPy expressions may be Functions themselves
  1084. func = getattr(expr, 'func', None)
  1085. if isinstance(func, FunctionClass):
  1086. imp = getattr(func, '_imp_', None)
  1087. if imp is not None:
  1088. name = expr.func.__name__
  1089. if name in namespace and namespace[name] != imp:
  1090. raise ValueError('We found more than one '
  1091. 'implementation with name '
  1092. '"%s"' % name)
  1093. namespace[name] = imp
  1094. # and / or they may take Functions as arguments
  1095. if hasattr(expr, 'args'):
  1096. for arg in expr.args:
  1097. _imp_namespace(arg, namespace)
  1098. return namespace
  1099. def implemented_function(symfunc, implementation):
  1100. """ Add numerical ``implementation`` to function ``symfunc``.
  1101. ``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
  1102. In the latter case we create an ``UndefinedFunction`` instance with that
  1103. name.
  1104. Be aware that this is a quick workaround, not a general method to create
  1105. special symbolic functions. If you want to create a symbolic function to be
  1106. used by all the machinery of SymPy you should subclass the ``Function``
  1107. class.
  1108. Parameters
  1109. ----------
  1110. symfunc : ``str`` or ``UndefinedFunction`` instance
  1111. If ``str``, then create new ``UndefinedFunction`` with this as
  1112. name. If ``symfunc`` is an Undefined function, create a new function
  1113. with the same name and the implemented function attached.
  1114. implementation : callable
  1115. numerical implementation to be called by ``evalf()`` or ``lambdify``
  1116. Returns
  1117. -------
  1118. afunc : sympy.FunctionClass instance
  1119. function with attached implementation
  1120. Examples
  1121. ========
  1122. >>> from sympy.abc import x
  1123. >>> from sympy.utilities.lambdify import lambdify, implemented_function
  1124. >>> f = implemented_function('f', lambda x: x+1)
  1125. >>> lam_f = lambdify(x, f(x))
  1126. >>> lam_f(4)
  1127. 5
  1128. """
  1129. # Delayed import to avoid circular imports
  1130. from sympy.core.function import UndefinedFunction
  1131. # if name, create function to hold implementation
  1132. kwargs = {}
  1133. if isinstance(symfunc, UndefinedFunction):
  1134. kwargs = symfunc._kwargs
  1135. symfunc = symfunc.__name__
  1136. if isinstance(symfunc, str):
  1137. # Keyword arguments to UndefinedFunction are added as attributes to
  1138. # the created class.
  1139. symfunc = UndefinedFunction(
  1140. symfunc, _imp_=staticmethod(implementation), **kwargs)
  1141. elif not isinstance(symfunc, UndefinedFunction):
  1142. raise ValueError(filldedent('''
  1143. symfunc should be either a string or
  1144. an UndefinedFunction instance.'''))
  1145. return symfunc