
    \h                       % S r SSKJr  SSKJr  SSKrSSKrSSKrSSKrSSK	r	SSK
r
SSKJr  SSKJr  SSKJr  SSKJrJrJrJr  SS	KJr  S
SS/0r0 rS\S'   0 rS\S'   0 rS\S'   SS0rS\S'   SS0rS\S'   SS0rS\S'   SS0r S\S'   0 r!S\S'   SS0r"S\S'   0 r#S\S'   0 r$S\S'   \RK                  5       r&\RK                  5       r'\RK                  5       r(\RK                  5       r)\RK                  5       r*\RK                  5       r+\ RK                  5       r,\!RK                  5       r-\"RK                  5       r.\#RK                  5       r/\$RK                  5       r0SSSS.r10 r2S\S '   0 S!S"_S#S$_S%S&_S'S(_S)S*_S+S_S,S-_S.S/_S0S1_S2S_SS3_S4S_S5S6_S7S8_S9S:_S;S:_S<S=_S>S?S@SASBSCSDSESFSG.	Er3SHSI0r4S\SJ'   SKSLSM.r5S\SN'   0 r6S\SO'   0 r7S\SP'   0 r8S\SQ'   0 r9S\SR'   0 r:S\SS'   \&\\1ST4\'\\2SU4\(\\3SV4\)\\4SW4\*\\5SX4\+\\6SY4\,\ \7SZ4\-\!\8S[4\.\"\9S\4\/\#0 S]4\0\$\:S^4S_.r;SqS` jr<Saq=\" SbScSd9  SrSe j5       r>Sf r?Sg r@Sh rASsSi jrB " Sj Sk5      rC " Sl Sm\C5      rDStSn jrESo rFSp rGg)uz
This module provides convenient functions to transform SymPy expressions to
lambda functions which can be used to calculate numerical values very fast.
    )annotations)AnyN)import_module)sympy_deprecation_warning)doctest_depends_on)is_sequenceiterableNotIterableflatten)
filldedent)lambdifynumpy
tensorflowzdict[str, Any]MATH_DEFAULTCMATH_DEFAULTMPMATH_DEFAULTIy              ?NUMPY_DEFAULTSCIPY_DEFAULTCUPY_DEFAULTJAX_DEFAULTTENSORFLOW_DEFAULTTORCH_DEFAULTSYMPY_DEFAULTNUMEXPR_DEFAULTceilelog)ceilingElnzdict[str, str]CMATH_TRANSLATIONSAbsfabs
elliptic_kellipk
elliptic_fellipf
elliptic_eellipeelliptic_piellippir   
chebyshevtchebyt
chebyshevuchebyuassoc_legendrelegenpr    jr!   ooinfLambertWlambertwMutableDenseMatrixmatrixImmutableDenseMatrix	conjugateconjaltzetaeishichisicirfffbetainc)	dirichlet_etaEiShiChiSiCiRisingFactorialFallingFactorialbetainc_regularized	Heaviside	heavisideNUMPY_TRANSLATIONSspherical_jnspherical_yn)jnynSCIPY_TRANSLATIONSCUPY_TRANSLATIONSJAX_TRANSLATIONSTENSORFLOW_TRANSLATIONSTORCH_TRANSLATIONSNUMEXPR_TRANSLATIONS)zfrom math import *)z!import cmath; from cmath import *)zfrom mpmath import *)z=import numpy; from numpy import *; from numpy.linalg import *)z7import scipy; import numpy; from scipy.special import *)zimport cupy)z
import jax)zimport tensorflow)zimport torch)zfrom sympy.functions import *zfrom sympy.matrices import *z2from sympy import Integral, pi, oo, nan, zoo, E, I)zimport_module('numexpr'))mathcmathmpmathr   scipycupyjaxr   torchsympynumexprc                    [         U    u  p#pEX#:w  a*  U(       a"  UR                  5         UR	                  U5        OgU Hg  nUR                  S5      (       a,  [        U5      n U b  UR	                  U R                  5        MD  O [        U0 U5        MU  [        SU < SU< S35      e   UR                  5        H  u  pxX(   X''   M     SU;  a
  [        US'   gg! [         a    [        SU -  5      ef = f! [         a     Nnf = f)a	  
Creates a global translation dictionary for module.

The argument module has to be one of the following strings: "math","cmath"
"mpmath", "numpy", "sympy", "tensorflow", "jax".
These dictionaries map names of Python functions to their equivalent in
other modules.
z-'%s' module cannot be used for lambdificationNr   zCannot import 'z' with 'z	' commandr#   )MODULESKeyError	NameErrorclearupdate
startswitheval__dict__execImportErroritemsabs)	modulereload	namespacenamespace_defaulttranslationsimport_commandsimport_command	sympynametranslations	            P/var/www/auris/envauris/lib/python3.13/site-packages/sympy/utilities/lambdify.py_importr|      s.   FFMGC	l %OO./)$$_55.)F!  1 "^R3 6<nMO 	O *$ #/"4"4"6	(5	 #7 I	% S  F;fDF 	FF0  s   C C6C36
DD   )r   r_   r   )   )modulespython_versionc                    SSK Jn  SSKJn	  Uc   [	        S5        SS/n/ n
U(       a  U
R                  [        U5      5        [        U[        [        45      (       d  [        US5      (       d  U
R                  U5        O9[        S	U5      (       a  [        U5      S
:  a  [        S5      eU
[        U5      -  n
0 nU
SSS2    H  n[!        U5      nUR#                  U5        M!     [        US5      (       a6  UR%                  U5      nU H  nUR#                  [        U5      U05        M!     UGc9  [        SU
5      (       a  SSKJn  O[        SU
5      (       a  SSKJn  O[        SU
5      (       a  SSKJn  O[        SU
5      (       a  SSKJn  O[        SU
5      (       a  SSKJn  O~[        S	U
5      (       a  SSKJn  Of[        SU
5      (       a  SSKJn  ON[        SU
5      (       a  SSKJn  O6[        SU
5      (       a  SSKJ n  O[        SU
5      (       a  SSKJ!n  OSSKJ"n  0 nU
SSS2    H(  n[        U[        5      (       d  M  U H  nUUU'   M
     M*     U" S S!S!US".5      n[        U [F        5      (       a  [I        S#S$S%S&9  [        X	5      (       a  U 4OU n/ n[J        RL                  " 5       RN                  RP                  RS                  5       n[U        U5       H  u  nn[        US'5      (       a  UR                  URV                  5        M4  U VVs/ s H  u  nnUUL d  M  UPM     nnn[        U5      S
:X  a  UR                  US   5        Mw  UR                  S([        U5      -   5        M     S)n[        SU
5      (       a  [Y        X55      nO[[        X55      nUS!:X  a  SS*K.J/n  U" US S+9u  nnO [a        U5      (       a  U" U5      u  nnOS,UnnURc                  UUUUS-9n / n![e        US.S5      =(       d    0 RS                  5        H@  u  n"n#U# H4  nUU;  d  M  S/U"< S0U< 3n$ [g        U$0 U5        U!R                  U$5        M6     MB     UR#                  [h        [j        S3.5        0 n%S4[l        -  n&[l        S
-  q6[o        U U&S55      n'[g        U'UU%5        [        U 5      SU Rq                  S!5      U&4[r        Rt                  U&'   S6 n(U%U   n)[v        Rx                  " U)U(" U&5      5        S7R{                  S8R}                  S9 U 5       5      5      n*[~        R                  " U*S:S;9n*[        X5      (       a  S<n+S=n,O9[        U5      n+[        U+5      S>:  a  [~        R                  " U+S?5      S   S@-   n+U n,SAR{                  U*U+U,SBR}                  U!5      SC9U)lC        U)$ ! [
         a)     [	        S5        S/n GN! [
         a	    / SQn  GNf = ff = fs  snnf ! [
         a    U< S1U"< S2U< 3n$[g        U$0 U5         GNf = f)DaM  Convert a SymPy expression into a function that allows for fast
numeric evaluation.

.. warning::
   This function uses ``exec``, and thus should not be used on
   unsanitized input.

.. deprecated:: 1.7
   Passing a set for the *args* parameter is deprecated as sets are
   unordered. Use an ordered iterable such as a list or tuple.

Explanation
===========

For example, to convert the SymPy expression ``sin(x) + cos(x)`` to an
equivalent NumPy function that numerically evaluates it:

>>> from sympy import sin, cos, symbols, lambdify
>>> import numpy as np
>>> x = symbols('x')
>>> expr = sin(x) + cos(x)
>>> expr
sin(x) + cos(x)
>>> f = lambdify(x, expr, 'numpy')
>>> a = np.array([1, 2])
>>> f(a)
[1.38177329 0.49315059]

The primary purpose of this function is to provide a bridge from SymPy
expressions to numerical libraries such as NumPy, SciPy, NumExpr, mpmath,
and tensorflow. In general, SymPy functions do not work with objects from
other libraries, such as NumPy arrays, and functions from numeric
libraries like NumPy or mpmath do not work on SymPy expressions.
``lambdify`` bridges the two by converting a SymPy expression to an
equivalent numeric function.

The basic workflow with ``lambdify`` is to first create a SymPy expression
representing whatever mathematical function you wish to evaluate. This
should be done using only SymPy functions and expressions. Then, use
``lambdify`` to convert this to an equivalent function for numerical
evaluation. For instance, above we created ``expr`` using the SymPy symbol
``x`` and SymPy functions ``sin`` and ``cos``, then converted it to an
equivalent NumPy function ``f``, and called it on a NumPy array ``a``.

Parameters
==========

args : List[Symbol]
    A variable or a list of variables whose nesting represents the
    nesting of the arguments that will be passed to the function.

    Variables can be symbols, undefined functions, or matrix symbols.

    >>> from sympy import Eq
    >>> from sympy.abc import x, y, z

    The list of variables should match the structure of how the
    arguments will be passed to the function. Simply enclose the
    parameters as they will be passed in a list.

    To call a function like ``f(x)`` then ``[x]``
    should be the first argument to ``lambdify``; for this
    case a single ``x`` can also be used:

    >>> f = lambdify(x, x + 1)
    >>> f(1)
    2
    >>> f = lambdify([x], x + 1)
    >>> f(1)
    2

    To call a function like ``f(x, y)`` then ``[x, y]`` will
    be the first argument of the ``lambdify``:

    >>> f = lambdify([x, y], x + y)
    >>> f(1, 1)
    2

    To call a function with a single 3-element tuple like
    ``f((x, y, z))`` then ``[(x, y, z)]`` will be the first
    argument of the ``lambdify``:

    >>> f = lambdify([(x, y, z)], Eq(z**2, x**2 + y**2))
    >>> f((3, 4, 5))
    True

    If two args will be passed and the first is a scalar but
    the second is a tuple with two arguments then the items
    in the list should match that structure:

    >>> f = lambdify([x, (y, z)], x + y + z)
    >>> f(1, (2, 3))
    6

expr : Expr
    An expression, list of expressions, or matrix to be evaluated.

    Lists may be nested.
    If the expression is a list, the output will also be a list.

    >>> f = lambdify(x, [x, [x + 1, x + 2]])
    >>> f(1)
    [1, [2, 3]]

    If it is a matrix, an array will be returned (for the NumPy module).

    >>> from sympy import Matrix
    >>> f = lambdify(x, Matrix([x, x + 1]))
    >>> f(1)
    [[1]
    [2]]

    Note that the argument order here (variables then expression) is used
    to emulate the Python ``lambda`` keyword. ``lambdify(x, expr)`` works
    (roughly) like ``lambda x: expr``
    (see :ref:`lambdify-how-it-works` below).

modules : str, optional
    Specifies the numeric library to use.

    If not specified, *modules* defaults to:

    - ``["scipy", "numpy"]`` if SciPy is installed
    - ``["numpy"]`` if only NumPy is installed
    - ``["math","cmath", "mpmath", "sympy"]`` if neither is installed.

    That is, SymPy functions are replaced as far as possible by
    either ``scipy`` or ``numpy`` functions if available, and Python's
    standard library ``math`` and ``cmath``, or ``mpmath`` functions otherwise.

    *modules* can be one of the following types:

    - The strings ``"math"``, ``"cmath"``, ``"mpmath"``, ``"numpy"``, ``"numexpr"``,
      ``"scipy"``, ``"sympy"``, or ``"tensorflow"`` or ``"jax"``. This uses the
      corresponding printer and namespace mapping for that module.
    - A module (e.g., ``math``). This uses the global namespace of the
      module. If the module is one of the above known modules, it will
      also use the corresponding printer and namespace mapping
      (i.e., ``modules=numpy`` is equivalent to ``modules="numpy"``).
    - A dictionary that maps names of SymPy functions to arbitrary
      functions
      (e.g., ``{'sin': custom_sin}``).
    - A list that contains a mix of the arguments above, with higher
      priority given to entries appearing first
      (e.g., to use the NumPy module but override the ``sin`` function
      with a custom version, you can use
      ``[{'sin': custom_sin}, 'numpy']``).

dummify : bool, optional
    Whether or not the variables in the provided expression that are not
    valid Python identifiers are substituted with dummy symbols.

    This allows for undefined functions like ``Function('f')(t)`` to be
    supplied as arguments. By default, the variables are only dummified
    if they are not valid Python identifiers.

    Set ``dummify=True`` to replace all arguments with dummy symbols
    (if ``args`` is not a string) - for example, to ensure that the
    arguments do not redefine any built-in names.

cse : bool, or callable, optional
    Large expressions can be computed more efficiently when
    common subexpressions are identified and precomputed before
    being used multiple time. Finding the subexpressions will make
    creation of the 'lambdify' function slower, however.

    When ``True``, ``sympy.simplify.cse`` is used, otherwise (the default)
    the user may pass a function matching the ``cse`` signature.

docstring_limit : int or None
    When lambdifying large expressions, a significant proportion of the time
    spent inside ``lambdify`` is spent producing a string representation of
    the expression for use in the automatically generated docstring of the
    returned function. For expressions containing hundreds or more nodes the
    resulting docstring often becomes so long and dense that it is difficult
    to read. To reduce the runtime of lambdify, the rendering of the full
    expression inside the docstring can be disabled.

    When ``None``, the full expression is rendered in the docstring. When
    ``0`` or a negative ``int``, an ellipsis is rendering in the docstring
    instead of the expression. When a strictly positive ``int``, if the
    number of nodes in the expression exceeds ``docstring_limit`` an
    ellipsis is rendered in the docstring, otherwise a string representation
    of the expression is rendered as normal. The default is ``1000``.

Examples
========

>>> from sympy.utilities.lambdify import implemented_function
>>> from sympy import sqrt, sin, Matrix
>>> from sympy import Function
>>> from sympy.abc import w, x, y, z

>>> f = lambdify(x, x**2)
>>> f(2)
4
>>> f = lambdify((x, y, z), [z, y, x])
>>> f(1,2,3)
[3, 2, 1]
>>> f = lambdify(x, sqrt(x))
>>> f(4)
2.0
>>> f = lambdify((x, y), sin(x*y)**2)
>>> f(0, 5)
0.0
>>> row = lambdify((x, y), Matrix((x, x + y)).T, modules='sympy')
>>> row(1, 2)
Matrix([[1, 3]])

``lambdify`` can be used to translate SymPy expressions into mpmath
functions. This may be preferable to using ``evalf`` (which uses mpmath on
the backend) in some cases.

>>> f = lambdify(x, sin(x), 'mpmath')
>>> f(1)
0.8414709848078965

Tuple arguments are handled and the lambdified function should
be called with the same type of arguments as were used to create
the function:

>>> f = lambdify((x, (y, z)), x + y)
>>> f(1, (2, 4))
3

The ``flatten`` function can be used to always work with flattened
arguments:

>>> from sympy.utilities.iterables import flatten
>>> args = w, (x, (y, z))
>>> vals = 1, (2, (3, 4))
>>> f = lambdify(flatten(args), w + x + y + z)
>>> f(*flatten(vals))
10

Functions present in ``expr`` can also carry their own numerical
implementations, in a callable attached to the ``_imp_`` attribute. This
can be used with undefined functions using the ``implemented_function``
factory:

>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> func = lambdify(x, f(x))
>>> func(4)
5

``lambdify`` always prefers ``_imp_`` implementations to implementations
in other namespaces, unless the ``use_imps`` input parameter is False.

Usage with Tensorflow:

>>> import tensorflow as tf
>>> from sympy import Max, sin, lambdify
>>> from sympy.abc import x

>>> f = Max(x, sin(x))
>>> func = lambdify(x, f, 'tensorflow')

After tensorflow v2, eager execution is enabled by default.
If you want to get the compatible result across tensorflow v1 and v2
as same as this tutorial, run this line.

>>> tf.compat.v1.enable_eager_execution()

If you have eager execution enabled, you can get the result out
immediately as you can use numpy.

If you pass tensorflow objects, you may get an ``EagerTensor``
object instead of value.

>>> result = func(tf.constant(1.0))
>>> print(result)
tf.Tensor(1.0, shape=(), dtype=float32)
>>> print(result.__class__)
<class 'tensorflow.python.framework.ops.EagerTensor'>

You can use ``.numpy()`` to get the numpy value of the tensor.

>>> result.numpy()
1.0

>>> var = tf.Variable(2.0)
>>> result = func(var) # also works for tf.Variable and tf.Placeholder
>>> result.numpy()
2.0

And it works with any shape array.

>>> tensor = tf.constant([[1.0, 2.0], [3.0, 4.0]])
>>> result = func(tensor)
>>> result.numpy()
[[1. 2.]
 [3. 4.]]

Notes
=====

- For functions involving large array calculations, numexpr can provide a
  significant speedup over numpy. Please note that the available functions
  for numexpr are more limited than numpy but can be expanded with
  ``implemented_function`` and user defined subclasses of Function. If
  specified, numexpr may be the only option in modules. The official list
  of numexpr functions can be found at:
  https://numexpr.readthedocs.io/en/latest/user_guide.html#supported-functions

- In the above examples, the generated functions can accept scalar
  values or numpy arrays as arguments.  However, in some cases
  the generated function relies on the input being a numpy array:

  >>> import numpy
  >>> from sympy import Piecewise
  >>> from sympy.testing.pytest import ignore_warnings
  >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "numpy")

  >>> with ignore_warnings(RuntimeWarning):
  ...     f(numpy.array([-1, 0, 1, 2]))
  [-1.   0.   1.   0.5]

  >>> f(0)
  Traceback (most recent call last):
      ...
  ZeroDivisionError: division by zero

  In such cases, the input should be wrapped in a numpy array:

  >>> with ignore_warnings(RuntimeWarning):
  ...     float(f(numpy.array([0])))
  0.0

  Or if numpy functionality is not required another module can be used:

  >>> f = lambdify(x, Piecewise((x, x <= 1), (1/x, x > 1)), "math")
  >>> f(0)
  0

.. _lambdify-how-it-works:

How it works
============

When using this function, it helps a great deal to have an idea of what it
is doing. At its core, lambdify is nothing more than a namespace
translation, on top of a special printer that makes some corner cases work
properly.

To understand lambdify, first we must properly understand how Python
namespaces work. Say we had two files. One called ``sin_cos_sympy.py``,
with

.. code:: python

    # sin_cos_sympy.py

    from sympy.functions.elementary.trigonometric import (cos, sin)

    def sin_cos(x):
        return sin(x) + cos(x)


and one called ``sin_cos_numpy.py`` with

.. code:: python

    # sin_cos_numpy.py

    from numpy import sin, cos

    def sin_cos(x):
        return sin(x) + cos(x)

The two files define an identical function ``sin_cos``. However, in the
first file, ``sin`` and ``cos`` are defined as the SymPy ``sin`` and
``cos``. In the second, they are defined as the NumPy versions.

If we were to import the first file and use the ``sin_cos`` function, we
would get something like

>>> from sin_cos_sympy import sin_cos # doctest: +SKIP
>>> sin_cos(1) # doctest: +SKIP
cos(1) + sin(1)

On the other hand, if we imported ``sin_cos`` from the second file, we
would get

>>> from sin_cos_numpy import sin_cos # doctest: +SKIP
>>> sin_cos(1) # doctest: +SKIP
1.38177329068

In the first case we got a symbolic output, because it used the symbolic
``sin`` and ``cos`` functions from SymPy. In the second, we got a numeric
result, because ``sin_cos`` used the numeric ``sin`` and ``cos`` functions
from NumPy. But notice that the versions of ``sin`` and ``cos`` that were
used was not inherent to the ``sin_cos`` function definition. Both
``sin_cos`` definitions are exactly the same. Rather, it was based on the
names defined at the module where the ``sin_cos`` function was defined.

The key point here is that when function in Python references a name that
is not defined in the function, that name is looked up in the "global"
namespace of the module where that function is defined.

Now, in Python, we can emulate this behavior without actually writing a
file to disk using the ``exec`` function. ``exec`` takes a string
containing a block of Python code, and a dictionary that should contain
the global variables of the module. It then executes the code "in" that
dictionary, as if it were the module globals. The following is equivalent
to the ``sin_cos`` defined in ``sin_cos_sympy.py``:

>>> import sympy
>>> module_dictionary = {'sin': sympy.sin, 'cos': sympy.cos}
>>> exec('''
... def sin_cos(x):
...     return sin(x) + cos(x)
... ''', module_dictionary)
>>> sin_cos = module_dictionary['sin_cos']
>>> sin_cos(1)
cos(1) + sin(1)

and similarly with ``sin_cos_numpy``:

>>> import numpy
>>> module_dictionary = {'sin': numpy.sin, 'cos': numpy.cos}
>>> exec('''
... def sin_cos(x):
...     return sin(x) + cos(x)
... ''', module_dictionary)
>>> sin_cos = module_dictionary['sin_cos']
>>> sin_cos(1)
1.38177329068

So now we can get an idea of how ``lambdify`` works. The name "lambdify"
comes from the fact that we can think of something like ``lambdify(x,
sin(x) + cos(x), 'numpy')`` as ``lambda x: sin(x) + cos(x)``, where
``sin`` and ``cos`` come from the ``numpy`` namespace. This is also why
the symbols argument is first in ``lambdify``, as opposed to most SymPy
functions where it comes after the expression: to better mimic the
``lambda`` keyword.

``lambdify`` takes the input expression (like ``sin(x) + cos(x)``) and

1. Converts it to a string
2. Creates a module globals dictionary based on the modules that are
   passed in (by default, it uses the NumPy module)
3. Creates the string ``"def func({vars}): return {expr}"``, where ``{vars}`` is the
   list of variables separated by commas, and ``{expr}`` is the string
   created in step 1., then ``exec``s that string with the module globals
   namespace and returns ``func``.

In fact, functions returned by ``lambdify`` support inspection. So you can
see exactly how they are defined by using ``inspect.getsource``, or ``??`` if you
are using IPython or the Jupyter notebook.

>>> f = lambdify(x, sin(x) + cos(x))
>>> import inspect
>>> print(inspect.getsource(f))
def _lambdifygenerated(x):
    return sin(x) + cos(x)

This shows us the source code of the function, but not the namespace it
was defined in. We can inspect that by looking at the ``__globals__``
attribute of ``f``:

>>> f.__globals__['sin']
<ufunc 'sin'>
>>> f.__globals__['cos']
<ufunc 'cos'>
>>> f.__globals__['sin'] is numpy.sin
True

This shows us that ``sin`` and ``cos`` in the namespace of ``f`` will be
``numpy.sin`` and ``numpy.cos``.

Note that there are some convenience layers in each of these steps, but at
the core, this is how ``lambdify`` works. Step 1 is done using the
``LambdaPrinter`` printers defined in the printing module (see
:mod:`sympy.printing.lambdarepr`). This allows different SymPy expressions
to define how they should be converted to a string for different modules.
You can change which printer ``lambdify`` uses by passing a custom printer
in to the ``printer`` argument.

Step 2 is augmented by certain translations. There are default
translations for each module, but you can provide your own by passing a
list to the ``modules`` argument. For instance,

>>> def mysin(x):
...     print('taking the sin of', x)
...     return numpy.sin(x)
...
>>> f = lambdify(x, sin(x), [{'sin': mysin}, 'numpy'])
>>> f(1)
taking the sin of 1
0.8414709848078965

The globals dictionary is generated from the list by merging the
dictionary ``{'sin': mysin}`` and the module dictionary for NumPy. The
merging is done so that earlier items take precedence, which is why
``mysin`` is used above instead of ``numpy.sin``.

If you want to modify the way ``lambdify`` works for a given function, it
is usually easiest to do so by modifying the globals dictionary as such.
In more complicated cases, it may be necessary to create and pass in a
custom printer.

Finally, step 3 is augmented with certain convenience operations, such as
the addition of a docstring.

Understanding how ``lambdify`` works can make it easier to avoid certain
gotchas when using it. For instance, a common mistake is to create a
lambdified function for one module (say, NumPy), and pass it objects from
another (say, a SymPy expression).

For instance, say we create

>>> from sympy.abc import x
>>> f = lambdify(x, x + 1, 'numpy')

Now if we pass in a NumPy array, we get that array plus 1

>>> import numpy
>>> a = numpy.array([1, 2])
>>> f(a)
[2 3]

But what happens if you make the mistake of passing in a SymPy expression
instead of a NumPy array:

>>> f(x + 1)
x + 2

This worked, but it was only by accident. Now take a different lambdified
function:

>>> from sympy import sin
>>> g = lambdify(x, x + sin(x), 'numpy')

This works as expected on NumPy arrays:

>>> g(a)
[1.84147098 2.90929743]

But if we try to pass in a SymPy expression, it fails

>>> g(x + 1)
Traceback (most recent call last):
...
TypeError: loop of ufunc does not support argument 0 of type Add which has
           no callable sin method

Now, let's look at what happened. The reason this fails is that ``g``
calls ``numpy.sin`` on the input expression, and ``numpy.sin`` does not
know how to operate on a SymPy object. **As a general rule, NumPy
functions do not know how to operate on SymPy expressions, and SymPy
functions do not know how to operate on NumPy arrays. This is why lambdify
exists: to provide a bridge between SymPy and NumPy.**

However, why is it that ``f`` did work? That's because ``f`` does not call
any functions, it only adds 1. So the resulting function that is created,
``def _lambdifygenerated(x): return x + 1`` does not depend on the globals
namespace it is defined in. Thus it works, but only by accident. A future
version of ``lambdify`` may remove this behavior.

Be aware that certain implementation details described here may change in
future versions of SymPy. The API of passing in custom modules and
printers will not change, but the details of how a lambda function is
created may change. However, the basic idea will remain the same, and
understanding it will be helpful to understanding the behavior of
lambdify.

**In general: you should create lambdified functions for one module (say,
NumPy), and only pass it input types that are compatible with that module
(say, NumPy arrays).** Remember that by default, if the ``module``
argument is not provided, ``lambdify`` creates functions using the NumPy
and SciPy namespaces.
r   )SymbolExprNr_   r   )r\   r^   rc   __iter__rd   r}   z*numexpr must be the only item in 'modules'atomsr^   )MpmathPrinter)SciPyPrinter)NumPyPrinterr`   )CuPyPrinterra   )
JaxPrinter)NumExprPrinterr   )TensorflowPrinterrb   )TorchPrinterrc   )SymPyPrinterr]   )CmathPrinter)PythonCodePrinterFT)fully_qualified_modulesinlineallow_unknown_functionsuser_functionsz
Passing the function arguments to lambdify() as a set is deprecated. This
leads to unpredictable results since sets are unordered. Instead, use a list
or tuple for the function arguments.
            z1.6.3z!deprecated-lambdify-arguments-set)deprecated_since_versionactive_deprecations_targetnamearg__lambdifygenerated)cse)list csesmodule_importszfrom z import z = .)builtinsrangez<lambdifygenerated-%s>rn   c                   ^  U 4S jnU$ )Nc                 R   > T [         R                  ;   a  [         R                  T 	 g g N)	linecachecache)filenames   r{   _cleanup5lambdify.<locals>.cleanup_linecache.<locals>._cleanup  s     9??*OOH- +    r   )r   r   s   ` r{   cleanup_linecache#lambdify.<locals>.cleanup_linecache  s    	. r   zfunc({}), c              3  8   #    U  H  n[        U5      v   M     g 7fr   str).0is     r{   	<genexpr>lambdify.<locals>.<genexpr>  s     %<ec!ffe   z        )subsequent_indentzEEXPRESSION REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)zFSOURCE CODE REDACTED DUE TO LENGTH, (see lambdify's `docstring_limit`)N   K   z...zqCreated with lambdify. Signature:

{sig}

Expression:

{expr}

Source code:

{src}

Imported modules:

{imp_mods}
)sigexprsrcimp_mods)Dsympy.core.symbolr   sympy.core.exprr   r|   ro   append_imp_namespace
isinstancedictr   hasattr_module_presentlen	TypeErrorr   _get_namespacerj   r   sympy.printing.pycoder   sympy.printing.numpyr   r   r   r   sympy.printing.lambdareprr   sympy.printing.tensorflowr   sympy.printing.pytorchr   r   r   r   setr   inspectcurrentframef_backf_localsrp   	enumerater   _TensorflowEvaluatorPrinter_EvaluatorPrintersympy.simplify.cse_mainr   callabledoprintgetattrrn   r   r   _lambdify_generated_countercompile
splitlinesr   r   weakreffinalizeformatjointextwrapfill_too_large_for_docstringwrap__doc__)-argsr   r   printeruse_impsdummifyr   docstring_limitr   r   
namespacesrt   mbufsymstermPrinterr   kiterable_argsnamescallers_local_varsnvarvar_namevar_val	name_listfuncnamefuncprinter_cser   _exprfuncstrimp_mod_linesmodkeysr!   
funclocalsr   cr   funcr   expr_strsrc_strs-                                                r{   r   r      s   ~ )$ 	)G (G J../'D#;''ww
/K/K'" 9g..3w<!3CHIId7m#
I"Q  tW zz&!Dc$i./  8Z00FWj11DWj11DVZ00CUJ//BY
33K\:66NWj11FWj11EWj11EJDbD!A!T""A()N1%  " et6:-;= > $!
 &-'J	  *$55TG4ME !--/66??EEGM*33LL" <N ';M&7h#~ ";MI '9~"Yq\* Vc!f_- + $H|Z001'C'9
d{74e,e	#$ie$e!!(M5t!LG Mg'7>D"KKM	TA	!,/3,R+ $$R(  N 59:J'*EEH1$6*AIz"!$WtW5G5G5Mx XIOOH hDT,X67 

DII%<e%<<
=C
--u
5C66ZZt9x=2}}Xr215=H	 &SxWtyy?W&
X 	L Kc  		$$  #)  6 6	6		$z'@ # , *+C3BR+,sM   V) W-W3W%)
W4W?WWWWW%$XXc                l    X;   a  gU H(  n[        US5      (       d  M  UR                  U :X  d  M(    g   g)NT__name__F)r   r  )modnamemodlistr   s      r{   r   r     s5    1j!!ajjG&;  r   c                    [        U [        5      (       a  [        U 5        [        U    S   $ [        U [        5      (       a  U $ [        U S5      (       a  U R                  $ [        SU -  5      e)z3
This is used by _lambdify to parse its arguments.
r   rm   z>Argument must be either a string, dict or module but it is: %s)r   r   r|   rf   r   r   rm   r   )r   s    r{   r   r     sa     !S
qz!}	At			J		zzX[\\]]r   c                  ^  SSK Jn  SSKJn  [	        XU45      (       a  T " U5      $ [        U5      (       ay  [	        U[        5      (       a  Su  pEO>[	        U[        5      (       a  Su  pEU(       d  gO[        S[        U5      < SU< 35      eUSR                  U 4S	 jU 5       5      -   U-   $ [	        U[        5      (       a  U$ T " U5      $ )
zFunctions in lambdify accept both SymPy types and non-SymPy types such as python
lists and tuples. This method ensures that we only call the doprint method of the
printer with SymPy types (so that the printer safely can use SymPy-methods).r   
MatrixBaseBasic)[])(z,)z()zunhandled type: r   c              3  <   >#    U  H  n[        TU5      v   M     g 7fr   )_recursive_to_string)r   r   r   s     r{   r   '_recursive_to_string.<locals>.<genexpr>  s     MA3GQ??   )sympy.matrices.matrixbaser  sympy.core.basicr  r   r	   r   tupleNotImplementedErrortyper   r   )r   argr  r  leftrights   `     r{   r  r    s     5&#z*++s|	#c4  "KD%U###KD  &$s)S&QRRTYYMMMMPUUU	C		
s|r   c                  ^^^^^^^^^^^^ SSK Jm  SSKJm  SSKJmJm  SSKJmJ	m  SSK
Jm  TbG  [        R                  " T5      (       a  TnO/[        R                  " T5      (       a  U4S jnOU4S	 jnOSS
KJn  UUUUUU4S jmUUU4S jmU4S jmUU4S jmUc'  [#        UUU4S jT" U 5      (       a  U OU / 5       5      nT" U 5      (       a  [#        U4S jU  5       5      (       a  [%        ['        U 5      5       Vs/ s H  n[)        T" [)        U5      5      5      PM     nnSR+                  T" U 5       VVs/ s H3  nXgS      SR+                  USS  Vs/ s H  nSU-  PM
     sn5      -   PM5     snn5      n	[-        [/        U 5      UTUS9n
SSR+                  U5      < SU
< SU	< S3$ 0 nU(       a	  T" X5      n O=[1        U [(        5      (       a  O'[3        U TS9(       a  SR+                  S U  5       5      n U(       a  [1        U[(        5      (       a  OT" X5      n[5        XA5      nSU < SU< S3$ s  snf s  snf s  snnf )a%  
Returns a string that can be evaluated to a lambda function.

Examples
========

>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import lambdastr
>>> lambdastr(x, x**2)
'lambda x: (x**2)'
>>> lambdastr((x,y,z), [z,y,x])
'lambda x,y,z: ([z, y, x])'

Although tuples may not appear as arguments to lambda in Python 3,
lambdastr will create a lambda function that will unpack the original
arguments so that nested arguments can be handled:

>>> lambdastr((x, (y, z)), x + y)
'lambda _0,_1: (lambda x,y,z: (x + y))(_0,_1[0],_1[1])'
r   DeferredVectorr  
DerivativeFunction)Dummyr   sympifyNc                0   > T" 5       R                  U 5      $ r   r   r   r   s    r{   <lambda>lambdastr.<locals>.<lambda>  s    ')*;*;D*Ar   c                &   > TR                  U 5      $ r   r-  r.  s    r{   r/  r0    s    '//$*?r   )
lambdareprc           	       > [        U [        5      (       a  U $ [        U T5      (       a  [        U 5      $ [        U 5      (       a:  [        U  Vs/ s H  nT	" X!5      PM     sn5      nSR	                  S U 5       5      $ [        U TTT45      (       a$  T" 5       nUR                  X05        [        U5      $ [        U 5      $ s  snf )N,c              3  8   #    U  H  n[        U5      v   M     g 7fr   r   r   as     r{   r   .lambdastr.<locals>.sub_args.<locals>.<genexpr>  s     4GqCFFGr   )r   r   r	   r   r   rj   )
r   dummies_dictr7  dummiesr%  r'  r)  r(  r   sub_argss
       r{   r;  lambdastr.<locals>.sub_args  s    dC  Kn--t9d^^$G$Qx8$GHG884G444 $6: >??'##T$457|#4y  Hs   Cc                   > T" U 5      n [        U T5      (       a  U R                  U5      n U $ [        U [        5      (       a  U  Vs/ s H  nT" X!5      PM     n nU $ s  snf r   )r   xreplacer   )r   r9  r7  r  sub_exprr+  s      r{   r?  lambdastr.<locals>.sub_expr'  s`    t}dE""==.D  d##7;<t!HQ-tD< =s   Ac                .   > [        U [        T[        4S9$ )Nexclude)r	   r   r
   )lr%  s    r{   isiterlambdastr.<locals>.isiter2  s    C#EFFr   c              3     >#    SnU  H2  nT" U5      (       a  T" U5       H  nU4U-   v   M     OU4v   US-  nM4     g 7fNr   r}   r   )r	   r   elndeepflat_indexesrE  s       r{   rK  lambdastr.<locals>.flat_indexes5  sK     Bbzz)"-E$,& . d
FA    <?c              3  n   >#    U  H*  n[        UT5      =(       a    UR                  TT5      v   M,     g 7fr   )r   r   )r   r7  r  r'  r(  s     r{   r   lambdastr.<locals>.<genexpr>B  s:      /, /0 !E* *GGHj)*,s   25c              3  4   >#    U  H  nT" U5      v   M     g 7fr   r   )r   r   rE  s     r{   r   rO  F  s     4t!F1IIts   r4   r}   z[%s])r   r   zlambda z: (z)()rB  c              3  8   #    U  H  n[        U5      v   M     g 7fr   r   r6  s     r{   r   rO  X  s     1DqCFFDr   )sympy.matricesr%  r  r  sympy.core.functionr'  r(  r   r)  r   sympy.core.sympifyr+  r   
isfunctionisclassr   r2  anyr   r   r   r   	lambdastrr   r   r	   r  )r   r   r   r   r2  r   dum_argsindr   indexed_argslstrr9  r  r%  r'  r)  r(  r   rK  rE  r;  r?  r+  s     `         @@@@@@@@@@@r{   rZ  rZ    s   , .&:1*g&& Jw''A
?
 	9! !"G
  /4LLDtf,/ / d||4t44405c$i0@A0@1Cc!f&0@Axx+D1!31 VrwwCG'DGq
G'DEE1!3 4 gwO(+(:D,OOL+dC  dN3881D11D dC  D/D
1D $d++5 B (E!3s   $II
 I/I
I
c                  ^    \ rS rSrSS jrSS.S jr\S 5       rSS jrS	 r	S
 r
S rS rSrg)r   ic  Nc                   X l         SSKJn  Uc  U" 5       n[        R                  " U5      (       a  Xl        O3[        R                  " U5      (       a  U" 5       nUR                  U l        U" 5       R                  U l        g )Nr   )LambdaPrinter)	_dummifyr   ra  r   rW  	_exprreprrX  r   _argrepr)selfr   r   ra  s       r{   __init___EvaluatorPrinter.__init__d  s`     	<?#oGg&&$Nw''!)$__DN &//r   r   r   c          	     j   SSK Jn  / n[        U5      (       d  U/nU(       aK  [        U5      n[	        U6 u  pxU/[        U5      -   n	U R                  X)US9u  pU	S   U	SS p[	        Xx5      nOU R                  X#5      u  p/ n/ nU
 Hn  n[        U5      (       aJ  UR                  U R                  U" 5       5      5        UR                  U R                  XS   5      5        M]  UR                  U5        Mp     SR                  USR                  U5      5      nUR                  U R                  U5      5        UR                  U5        U Hy  u  nnUc1  UR                  S	R                  U R                  U5      5      5        M:  UR                  S
R                  U R                  U5      U R                  U5      5      5        M{     / nU R                  UUS9nU HE  u  nnUR                  S
R                  U R                  U5      U R                  U5      5      5        MG     [        U R                  U5      nSU;   a  SR                  U5      nUR                  SR                  U5      5        U/nUR                  U Vs/ s H  nSU-   PM
     sn5        SR                  U5      S-   $ s  snf )z3
Returns the function definition code as a string.
r   r)  r   r}   Nr   zdef {}({}):r   zdel {}{} = {})outr   z({})z	return {}z    )r   r)  r	   r   zip_preprocessr   rd  extend_print_unpackingr   r   _print_funcargwrappingrc  _handle_Subsr  )re  r   r   r   r   r)  funcbodysubvarssubexprsexprsargstrsfuncargs
unpackingsargstrfuncsigsr   subs_assignmentslhsrhsstr_expr	funclineslines                          r{   r   _EvaluatorPrinter.doprint~  s`    	,~~6D:D #T
GFT(^+E!--d-ENG"1XuQRy(w)D ,,T8MG 
Feg 67!!$"7"7"MN'   &&x81DE 	33H=>
#DAqyq0A BC	 0 01BDNNSTDU VW	    +; <(HCOOI,,T^^C-@$..QTBUVW ) (=8}}X.H**845I	H=HD&4-H=>yy#d** >s   J0c                    [        U[        5      =(       a2    UR                  5       =(       a    [        R                  " U5      (       + $ r   )r   r   isidentifierkeyword	iskeyword)clsidents     r{   _is_safe_ident _EvaluatorPrinter._is_safe_ident  s7    %% 1%*<*<*> 1))%00	1r   c                  ^^^ SSK Jn  SSKJn  SSKJnJn  SSKJmJ	n	  SSK
Jn
  SSKJn  U R                  =(       d    [        U4S j[!        U5       5       5      nS	/[#        U5      -  nTc  0 mUU4S
 jn[%        ['        U" [)        U[+        [#        U5      5      5      5      5      5       GHF  u  nn[-        U5      (       a  U R/                  XTTS9u  nnGO[1        X5      (       a  [3        U5      nO[1        X5      (       a  UR4                  (       a  [3        U5      nU(       d  U R7                  U5      (       dV  T" 5       n[1        X+5      (       a  U	" UR8                  US S9nU R;                  U5      nU" UU5        U R=                  UT5      nOXU(       d  [1        XU45      (       a4  T" 5       nU R;                  U5      nU" UU5        U R=                  UT5      nO[3        U5      nUUU'   GMI     X4$ )zPreprocess args, expr to replace arguments that do not map
to valid Python identifiers.

Returns string form of args, and updated expr.
r   r  )orderedr&  )r)  uniquely_named_symbolr$  r   c              3  <   >#    U  H  n[        UT5      v   M     g 7fr   )r   )r   r   r)  s     r{   r   0_EvaluatorPrinter._preprocess.<locals>.<genexpr>  s      '=.;sJsE""mr  Nc                T   > UTU '   T H  u  p#U R                  X205      n UTU '   M     g r   )r>  )r   dummyreplsub_dummies_dictr   s       r{   update_dummies5_EvaluatorPrinter._preprocess.<locals>.update_dummies  s3    !&M#!	llC;/%*c" "r   )r   r  c                    SU -   $ )N_r   )r{  s    r{   r/  /_EvaluatorPrinter._preprocess.<locals>.<lambda>  s    sQwr   )modify)r  r  sympy.core.sortingr  rU  r'  r(  r   r)  r  rT  r%  r   r   rb  rY  r   r   reversedr   rl  r   r	   rm  r   r   	is_symbolr  r   rd  _subexpr)re  r   r   r   r  r  r  r'  r(  r  r%  r   r   rv  r  r   r   r{  r  r)  s      ``              @r{   rm  _EvaluatorPrinter._preprocess  s    	+.>B1(
 -- =3 '=.5dm'= $= &T" M	+ tGCeCI6F,G$HIJFC}}**34}*]4C00HC''CMMH$"5"5a"8"8!GE!$-- 5!JJ5F!He,A"3.==}=DJsz,BCCMM%(sE*}}T=9HGAJ- K. }r   c                  ^ ^^ SSK Jn  SSKJm  T" U5      n[	        USS 5      nUb
  U" T5      nU$ [        X5      (       a   U$ [        U[        5      (       a  UR                  5        Vs/ s H  nT R                  T" U5      T5      PM     nnUR                  5        Vs/ s H  nT R                  T" U5      T5      PM     nn[        [        Xg5      5      nU$ [        U[        5      (       a  [        UU U4S jU 5       5      nU$ [        U[        5      (       a(  U Vs/ s H  nT R                  T" U5      T5      PM     nnU$ s  snf s  snf s  snf )Nr   r$  r*  r>  c              3  T   >#    U  H  nTR                  T" U5      T5      v   M     g 7fr   )r  )r   r7  r9  re  r+  s     r{   r   -_EvaluatorPrinter._subexpr.<locals>.<genexpr>  s#     SdT]]71:|DDds   %()rT  r%  rV  r+  r   r   r   r  r  valuesrl  r  r   )	re  r   r9  r%  r>  r7  r   vr+  s	   ` `     @r{   r  _EvaluatorPrinter._subexpr  s/   1.t}4T2L)D  $//  D$''FJiikRkT]]71:|<kRFJkkmTmT]]71:|<mTCI
 	 D%((SdSS  D$''IMNAgaj,?N ST
 Os   ,"E	""E#"Ec                    / $ )zGenerate argument wrapping code.

args is the argument list of the generated function (strings).

Return value is a list of lines of code that will be inserted  at
the beginning of the function definition.
r   )re  r   s     r{   rp  (_EvaluatorPrinter._print_funcargwrapping  s	     	r   c                B   ^ U4S jmSR                  T" U5      U5      /$ )zGenerate argument unpacking code.

arg is the function argument to be unpacked (a string), and
unpackto is a list or nested lists of the variable names (strings) to
unpack to.
c                X   > SR                  SR                  U4S jU  5       5      5      $ )Nz[{}]r   c              3  X   >#    U  H  n[        U5      (       a  T" U5      OUv   M!     g 7fr   r	   )r   val
unpack_lhss     r{   r   I_EvaluatorPrinter._print_unpacking.<locals>.unpack_lhs.<locals>.<genexpr>  s&      +NELc8C==
3c9Ws   '*)r   r   )lvaluesr  s    r{   r  6_EvaluatorPrinter._print_unpacking.<locals>.unpack_lhs  s1    == +NEL+N "N O Or   rj  )r   )re  unpacktor   r  s      @r{   ro  "_EvaluatorPrinter._print_unpacking  s&    	O   H!5s;<<r   c           	       ^^ SSK Jn  SSKJn  SSKJm  SSKJn  UU4S jn[        XU45      (       a  UR                  XF5      nU$ [        U5      (       a1  [        U5      " U Vs/ s H  opR                  UT5      PM     sn5      nU$ s  snf )zCAny instance of Subs is extracted and returned as assignment pairs.r   r  )Subsri  r  c                   > 0 n[        X5       H"  u  pET" 5       nXcU'   TR                  Xe45        M$     U R                  U5      $ r   )rl  r   r>  )	ex	variablespointsafer}  r~  r  r)  rk  s	          r{   _replace0_EvaluatorPrinter._handle_Subs.<locals>._replace*  sF    D	1!S	

E<( 2 ;;t$$r   )r  r  rU  r  r   r)  r  r  r   replacer	   r  rq  )	re  r   rk  r  r  r  r  r   r)  s	     `     @r{   rq  _EvaluatorPrinter._handle_Subs#  sy    *,+8	% dJ/00<</D  d^^:$G$Q00C8$GHD Hs   &B
)rd  rb  rc  )NF)r   N)r  
__module____qualname____firstlineno__rf  r   classmethodr  rm  r  rp  ro  rq  __static_attributes__r   r   r{   r   r   c  s@    04 57 <+| 1 14l*=r   r   c                      \ rS rSrS rSrg)r   i8  c                   ^^ U4S jmSR                  U4S jT" U5       5       5      nSR                  SR                  [        U5      5      U5      /$ )zGenerate argument unpacking code.

This method is used when the input value is not iterable,
but can be indexed (see issue #14655).
c              3     >#    SnU  H5  n[        U5      (       a  T" U5       H  nU4U-   v   M     OU4v   US-  nM7     g 7frH  r  )elemsr   rI  rJ  rK  s       r{   rK  B_TensorflowEvaluatorPrinter._print_unpacking.<locals>.flat_indexes@  sK     AB<<!-b!1 dUl* "2 $JQ s   ?Ar   c           
   3     >#    U  H4  nS R                  TSR                  [        [        U5      5      5      v   M6     g7f)z{}[{}]z][N)r   r   mapr   )r   r\  rvalues     r{   r   ?_TensorflowEvaluatorPrinter._print_unpacking.<locals>.<genexpr>L  s6      B+@C %OOFDIIc#sm4LMM+@rM  z[{}] = [{}])r   r   r   )re  r  r  indexedrK  s     ` @r{   ro  ,_TensorflowEvaluatorPrinter._print_unpacking9  sS    
	 )) B+7+@B B $$TYYww/?%@'JKKr   r   N)r  r  r  r  ro  r  r   r   r{   r   r   8  s    Lr   r   c                   SSK Jn  Uc  0 n[        U 5      (       a  U  H  n[        X15        M     U$ [	        U [
        5      (       a1  U R                  5        H  u  pE[        XA5        [        XQ5        M     U$ [        U SS5      n[	        Xb5      (       aE  [        USS5      nUb5  U R                  R                  nX;   a  X   U:w  a  [        SU-  5      eXqU'   [        U S5      (       a  U R                   H  n[        X15        M     U$ )a  Return namespace dict with function implementations

We need to search for functions in anything that can be thrown at
us - that is - anything that could be passed as ``expr``.  Examples
include SymPy expressions, as well as tuples, lists and dicts that may
contain SymPy expressions.

Parameters
----------
expr : object
   Something passed to lambdify, that will generate valid code from
   ``str(expr)``.
namespace : None or mapping
   Namespace to fill.  None results in new empty dict

Returns
-------
namespace : dict
   dict with keys of implemented function names within ``expr`` and
   corresponding values being the numerical implementation of
   function

Examples
========

>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function, _imp_namespace
>>> from sympy import Function
>>> f = implemented_function(Function('f'), lambda x: x+1)
>>> g = implemented_function(Function('g'), lambda x: x*10)
>>> namespace = _imp_namespace(f(g(x)))
>>> sorted(namespace.keys())
['f', 'g']
r   )FunctionClassNr  _imp_z4We found more than one implementation with name "%s"r   )rU  r  r   r   r   r   rp   r   r  r  
ValueErrorr   r   )	r   rt   r  r   keyr  r  impr   s	            r{   r   r   Q  s   H 2	4C3* 	D$		

HC3*3* % 4&D$&&dGT*?99%%D Y_%;  "(*."/ 0 0 "dOtV99C3* r   c                   SSK Jn  0 n[        X5      (       a  U R                  nU R                  n [        U [
        5      (       a  U" U 4S[        U5      0UD6n U $ [        X5      (       d  [        [        S5      5      eU $ )av  Add numerical ``implementation`` to function ``symfunc``.

``symfunc`` can be an ``UndefinedFunction`` instance, or a name string.
In the latter case we create an ``UndefinedFunction`` instance with that
name.

Be aware that this is a quick workaround, not a general method to create
special symbolic functions. If you want to create a symbolic function to be
used by all the machinery of SymPy you should subclass the ``Function``
class.

Parameters
----------
symfunc : ``str`` or ``UndefinedFunction`` instance
   If ``str``, then create new ``UndefinedFunction`` with this as
   name.  If ``symfunc`` is an Undefined function, create a new function
   with the same name and the implemented function attached.
implementation : callable
   numerical implementation to be called by ``evalf()`` or ``lambdify``

Returns
-------
afunc : sympy.FunctionClass instance
   function with attached implementation

Examples
========

>>> from sympy.abc import x
>>> from sympy.utilities.lambdify import implemented_function
>>> from sympy import lambdify
>>> f = implemented_function('f', lambda x: x+1)
>>> lam_f = lambdify(x, f(x))
>>> lam_f(4)
5
r   )UndefinedFunctionr  z\
            symfunc should be either a string or
            an UndefinedFunction instance.)	rU  r  r   _kwargsr  r   staticmethodr  r   )symfuncimplementationr  kwargss       r{   implemented_functionr    s    L 6F'--""'3 $C'7C;AC N	 33 %. / 0 	0 Nr   c                R    SSK Jn  Uc  gSnU" U 5       H  nUS-  nX1:  d  M    g   g)aW	  Decide whether an ``Expr`` is too large to be fully rendered in a
``lambdify`` docstring.

This is a fast alternative to ``count_ops``, which can become prohibitively
slow for large expressions, because in this instance we only care whether
``limit`` is exceeded rather than counting the exact number of nodes in the
expression.

Parameters
==========
expr : ``Expr``, (nested) ``list`` of ``Expr``, or ``Matrix``
    The same objects that can be passed to the ``expr`` argument of
    ``lambdify``.
limit : ``int`` or ``None``
    The threshold above which an expression contains too many nodes to be
    usefully rendered in the docstring. If ``None`` then there is no limit.

Returns
=======
bool
    ``True`` if the number of nodes in the expression exceeds the limit,
    ``False`` otherwise.

Examples
========

>>> from sympy.abc import x, y, z
>>> from sympy.utilities.lambdify import _too_large_for_docstring
>>> expr = x
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
False
>>> _too_large_for_docstring(expr, 1)
False
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True

Does this split it?

>>> expr = [x, y, z]
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
False
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True

>>> expr = [x, [y], z, [[x+y], [x*y*z, [x+y+z]]]]
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
False
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True

>>> expr = ((x + y + z)**5).expand()
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 100)
True
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True

>>> from sympy import Matrix
>>> expr = Matrix([[(x + y + z), ((x + y + z)**2).expand(),
...                 ((x + y + z)**3).expand(), ((x + y + z)**4).expand()]])
>>> _too_large_for_docstring(expr, None)
False
>>> _too_large_for_docstring(expr, 1000)
False
>>> _too_large_for_docstring(expr, 100)
True
>>> _too_large_for_docstring(expr, 1)
True
>>> _too_large_for_docstring(expr, 0)
True
>>> _too_large_for_docstring(expr, -1)
True

r   )postorder_traversalFr}   T)sympy.core.traversalr  )r   limitr  r   r  s        r{   r   r     s:    B 9}	A &	Q9 ' r   )F)NNTFFi  )NNr   )Hr   
__future__r   typingr   r   r   r  r   r   r   sympy.externalr   sympy.utilities.exceptionsr   sympy.utilities.decoratorr   sympy.utilities.iterablesr   r	   r
   r   sympy.utilities.miscr   __doctest_requires__r   __annotations__r   r   r   r   r   r   r   r   r   r   copyMATHCMATHMPMATHNUMPYSCIPYCUPYJAX
TENSORFLOWTORCHSYMPYNUMEXPRMATH_TRANSLATIONSr"   MPMATH_TRANSLATIONSrQ   rV   rW   rX   rY   rZ   r[   rf   r|   r   r   r   r   r  rZ  r   r   r   r  r   r   r   r{   <module>r     s  
 #        ) @ 8  + &'>? 
  "n !!} !!# #!$b	~ )!$b	~ ) #Ryn ("Bi^ '%' N '!$b	~ ) "~ ""$ $ 				$$&




 
 	
  &( N '	6( ( (	
 9 v ( ( h   	% 	%  
!" (#$ H%& '( 


$9 @ & N  & N  %' > &#% . %*,  ,%' N '') n ) <!24KL]$68^_~':<UV]$68z{]$68tu<!24DE.@13JLbc]$68IJ]B )? @ /+?/1&6t    =dS>B7;v Tvp^2s,jS SjL"3 L2AH5pkr   