a
    SG5d*                     @   sF  d Z ddlmZmZ ddlZddlZddlZddlZddl	Z	ddl
mZ ddlmZ ddlmZ ddlmZmZmZmZ ddlmZ d	d
dgiZi Zi ZddiZddiZddiZddiZi Zi Zi Z e! Z"e! Z#e! Z$e! Z%e! Z&e! Z'e! Z(e! Z)e ! Z*ddddZ+ddddddddddddddddddd d!d"d#d$d%d&d'Z,d(d)iZ-i Z.i Z/i Z0i Z1i Z2e"ee+d*fe#ee,d+fe$ee-d,fe%ee.d-fe&ee/d.fe'ee0d/fe(ee1d0fe)ei d1fe*e e2d2fd3	Z3dNd5d6Z4d7a5ed8d9d:dOd<d=Z6d>d? Z7d@dA Z8dBdC Z9dPdDdEZ:G dFdG dGZ;G dHdI dIe;Z<dQdJdKZ=dLdM Z>dS )Rz
This module provides convenient functions to transform SymPy expressions to
lambda functions which can be used to calculate numerical values very fast.
    )AnyDictN)import_module)sympy_deprecation_warning)doctest_depends_on)is_sequenceiterableNotIterableflatten)
filldedent)lambdifynumpy
tensorflowIy              ?ceilelog)ceilingElnfabsellipkellipfellipeellippichebytchebyujinflambertwmatrixconjaltzetaeishichisicirfffbetainc)Abs
elliptic_k
elliptic_f
elliptic_eelliptic_pir   
chebyshevt
chebyshevur   r   r   ooLambertWMutableDenseMatrixImmutableDenseMatrix	conjugatedirichlet_etaEiShiChiSiCiRisingFactorialFallingFactorialbetainc_regularized	Heaviside	heaviside)zfrom math 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from sympy.functions import *zfrom sympy.matrices import *z2from sympy import Integral, pi, oo, nan, zoo, E, I)zimport_module('numexpr'))	mathmpmathr   scipycupyjaxr   sympynumexprFc           	   	   C   s   zt |  \}}}}W n ty2   td|  Y n0 ||krX|rT|  || ndS |D ]f}|drt|} | dur|| j q\n(zt|i | W q\W n t	y   Y n0 t	d| |f q\|
 D ]\}}|| ||< qd|vrt|d< dS )a  
    Creates a global translation dictionary for module.

    The argument module has to be one of the following strings: "math",
    "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 '%s' with '%s' commandr+   )MODULESKeyError	NameErrorclearupdate
startswitheval__dict__execImportErroritemsabs)	modulereload	namespaceZnamespace_defaulttranslationsZimport_commandsZimport_commandZ	sympynametranslation rZ   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/sympy/utilities/lambdify.py_importw   s>    	


	r\      )r   rD   r   )   )modulespython_versionTc           '         s  ddl m} ddlm} |du rvztd W n@ tyl   ztd W n ty`   g d}Y n0 dg}Y n
0 ddg}g }	|r|	t| t|t	t
fst|ds|	| n*td	|rt|d
krtd|	t|7 }	i }
|	ddd D ]}t|}|
| qt|dr8||}|D ]}|
t
||i q|du rjtd|	r\ddlm} ntd|	rvddlm} ntd|	rddlm} ntd|	rddlm} nttd|	rddlm} nZtd	|	rddlm} n@td|	rddlm} n&td|	rddlm} nddlm} i }|	ddd D ]&}t|t	r0|D ]}|||< qDq0|ddd|d}t| t rt!dd d!d" t| |r| fn| }g }t"# j$j%& }t'|D ]f\} t d#r| j( nB fd$d%|D }t|d
kr||d  n|d&t
|  qd'}td|	r:t)||}n
t*||}|dkrldd(l+m,} ||dd)\}}n"t-|r||\}}n
d*| }}|j.||||d+}g }t/|d,dpi & D ]v\}}|D ]f}||
vrd-||f } zt0| i |
 W n. ty   d.|||f } t0| i |
 Y n0 ||  qƐq|
t1t2d/ i }!d0t3 }"t3d
7 a3t4||"d1}#t0|#|
|! t|d|5d|"ft6j7|"< |!| }$d28d39d4d5 |D }%t:j;|%d6d7}%t
|}&t|&d8krt:<|&d9d d: }&d;j8|%|&|d<9|d=|$_=|$S )>aP  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", "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``, or ``mpmath`` functions otherwise.

        *modules* can be one of the following types:

        - The strings ``"math"``, ``"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.


    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

    >>> try:
    ...     g(x + 1)
    ... # NumPy release after 1.17 raises TypeError instead of
    ... # AttributeError
    ... except (AttributeError, TypeError):
    ...     raise AttributeError() # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    ...
    AttributeError:

    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ExprNrD   r   )rB   rC   rG   __iter__rH   r]   z*numexpr must be the only item in 'modules'atomsrC   )MpmathPrinter)SciPyPrinter)NumPyPrinterrE   )CuPyPrinterrF   )
JaxPrinter)NumExprPrinterr   )TensorflowPrinterrG   )SymPyPrinter)PythonCodePrinterFT)Zfully_qualified_modulesinlineZ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namec                    s   g | ]\}}| u r|qS rZ   rZ   ).0var_nameZvar_valvarrZ   r[   
<listcomp>I  s   zlambdify.<locals>.<listcomp>Zarg_Z_lambdifygenerated)cse)listrZ   csesZmodule_importszfrom %s import %sz
%s = %s.%s)builtinsrangez<lambdifygenerated-%s>rQ   zfunc({}), c                 s   s   | ]}t |V  qd S Nstrru   irZ   rZ   r[   	<genexpr>      zlambdify.<locals>.<genexpr>z        )subsequent_indentN   K   z...zqCreated with lambdify. Signature:

{sig}

Expression:

{expr}

Source code:

{src}

Imported modules:

{imp_mods}
)sigexprsrcZimp_mods)>sympy.core.symbolra   sympy.core.exprrc   r\   rR   append_imp_namespace
isinstancedictr   hasattr_module_presentlen	TypeErrorr{   _get_namespacerM   rf   Zsympy.printing.pycoderg   Zsympy.printing.numpyrh   ri   rj   rk   sympy.printing.lambdareprrl   Zsympy.printing.tensorflowrm   rn   ro   setr   inspectcurrentframef_backf_localsrS   	enumeratert   _TensorflowEvaluatorPrinter_EvaluatorPrinterZsympy.simplify.cse_mainrz   callabledoprintgetattrrQ   r~   r   _lambdify_generated_countercompile
splitlines	linecachecacheformatjointextwrapfillwrap__doc__)'argsr   r_   printerZuse_impsdummifyrz   ra   rc   
namespacesrW   mbufZsymstermZPrinterrq   kZiterable_argsnamesZcallers_local_varsn	name_listfuncnameZfuncprinterZ_cser}   Z_exprZfuncstrZimp_mod_linesmodkeysr   Z
funclocalsfilenamecfuncr   Zexpr_strrZ   rw   r[   r      s        8






	
r   c                 C   s4   | |v rdS |D ]}t |dr|j| kr dS qdS )NT__name__F)r   r   )modnameZmodlistr   rZ   rZ   r[   r     s    r   c                 C   sL   t | trt|  t|  d S t | tr,| S t| dr<| jS td|  dS )z;
    This is used by _lambdify to parse its arguments.
    r   rP   z>Argument must be either a string, dict or module but it is: %sN)r   r   r\   rI   r   r   rP   r   )r   rZ   rZ   r[   r     s    


r   c                    s   ddl m} ddlm} t|||fr. |S t|rt|trJd\}}n(t|tr^d\}}ntdt	||f |d
 fdd	|D  | S t|tr|S  |S d
S )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   )MatrixOperationsBasic)[])(z,)zunhandled type: %s, %sr   c                 3   s   | ]}t  |V  qd S r   )_recursive_to_string)ru   r   r   rZ   r[   r     r   z'_recursive_to_string.<locals>.<genexpr>N)Zsympy.matrices.commonr   sympy.core.basicr   r   r   r{   tupleNotImplementedErrortyper   r   )r   argr   r   leftrightrZ   r   r[   r     s    



 
r   c                    s  ddl m ddlm  ddlmm ddlmm	 ddl
m 	durt	r\	}qt	rt	fdd	}q	fd
d	}nddlm} 
fdd
 fddfddfdd|du rt fdd| r| n| gD }| r~tfdd| D r~fddtt| D dfdd| D }tt| |	|d}dd||f S i }|r
| |} n0t| trn"t| drddd | D } |rt|trn
||}t||}d| |f S ) aa  
    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)Dummyra   sympifyNc                    s      | S r   r   r   r   rZ   r[   <lambda>  r   zlambdastr.<locals>.<lambda>c                    s
     | S r   r   r   r   rZ   r[   r     r   )
lambdareprc                    s   t | tr| S t | r t| S t| rTt fdd| D }ddd |D S t | fr } | |i t|S t| S d S )Nc                    s   g | ]}| qS rZ   rZ   ru   a)dummies_dictsub_argsrZ   r[   ry     r   z/lambdastr.<locals>.sub_args.<locals>.<listcomp>,c                 s   s   | ]}t |V  qd S r   r   r   rZ   rZ   r[   r     r   z.lambdastr.<locals>.sub_args.<locals>.<genexpr>)r   r   r   r
   r   rM   )r   r   dummies)r   r   r   r   ra   r   r   r[   r     s    

zlambdastr.<locals>.sub_argsc                    s@   | } t | r|  } nt | tr< fdd| D } | S )Nc                    s   g | ]}| qS rZ   rZ   r   )r   sub_exprrZ   r[   ry     r   z/lambdastr.<locals>.sub_expr.<locals>.<listcomp>)r   xreplacer{   )r   r   )r   r   r   r   r[   r     s    

zlambdastr.<locals>.sub_exprc                    s   t | t tfdS )Nexclude)r   r   r	   )lr   rZ   r[   isiter  s    zlambdastr.<locals>.isiterc                 3   sF   d}| D ]8}|r0 |D ]}|f| V  qn|fV  |d7 }qd S Nr   r]   rZ   )r   r   elndeep)flat_indexesr   rZ   r[   r     s    zlambdastr.<locals>.flat_indexesc                 3   s$   | ]}t | o|V  qd S r   )r   rf   r   )r   r   r   rZ   r[   r     s   
zlambdastr.<locals>.<genexpr>c                 3   s   | ]} |V  qd S r   rZ   r   )r   rZ   r[   r     r   c                    s   g | ]}t  t |qS rZ   r   r   r   rZ   r[   ry     r   zlambdastr.<locals>.<listcomp>r   c              	      s4   g | ],} |d   d dd |dd D  qS )r    c                 S   s   g | ]}d | qS )z[%s]rZ   )ru   r   rZ   rZ   r[   ry     r   z(lambdastr.<locals>.<listcomp>.<listcomp>r]   N)r   ru   ind)dum_argsrZ   r[   ry     s   )r   r   zlambda %s: (%s)(%s)r   c                 s   s   | ]}t |V  qd S r   r   r   rZ   rZ   r[   r   )  r   zlambda %s: (%s))sympy.matricesr   r   r   sympy.core.functionr   r   r   r   ra   sympy.core.sympifyr   r   
isfunctionisclassr   r   anyr   r   r   	lambdastrr
   r   r   r   r   )r   r   r   r   r   Zindexed_argsZlstrr   rZ   )r   r   r   r   r   ra   r   r   r   r   r   r   r   r[   r     sP    

"

r   c                   @   sP   e Zd ZdddZddddZed	d
 Zdd Zdd Zdd Z	dd Z
dS )r   NFc                 C   sX   || _ ddlm} |d u r | }t|r2|| _nt|rB| }|j| _| j| _d S )Nr   )LambdaPrinter)	_dummifyr   r   r   r   	_exprreprr   r   _argrepr)selfr   r   r   rZ   rZ   r[   __init__5  s    

	z_EvaluatorPrinter.__init__rZ   r|   c             	   C   s  ddl m} g }t|s|g}|rnt| \}}|gt| }	| ||	\}
}	|	d |	dd  }}t||}n| ||\}
}g }g }|
D ]@}t|r|| |  || 	||d  q|| qd
|d|}|| | || |D ]<\}}|du r |d
| q|d	
|| | qt| j|}d
|v rZd
|}|d
| |g}|dd |D  d
|d
 S )zC
        Returns the function definition code as a string.
        r   r   r]   Nre   zdef {}({}):r   zdel {}{} = {}r   z({})z	return {}c                 S   s   g | ]}d | qS )z    rZ   )ru   linerZ   rZ   r[   ry     r   z-_EvaluatorPrinter.doprint.<locals>.<listcomp>)r   r   r   zipr{   _preprocessr   r   extend_print_unpackingr   r   _print_funcargwrappingr   r   )r   r   r   r   r}   r   ZfuncbodyZsubvarsZsubexprsexprsargstrsZfuncargsZ
unpackingsargstrZfuncsigsr   Zstr_exprZ	funclinesrZ   rZ   r[   r   O  s@    



z_EvaluatorPrinter.doprintc                 C   s   t |to| ot| S r   )r   r   isidentifierkeyword	iskeyword)clsidentrZ   rZ   r[   _is_safe_ident  s    
z _EvaluatorPrinter._is_safe_identc                    s  ddl m} ddlm} ddlm}m} ddlm m	} ddl
m} ddlm}	 | jpnt fdd	t|D }
d
gt| }tt|t|tt|D ]\}}t|r| ||\}}nt||rt|}nt||rD|jrD| |}|
s| |s  }t||	r(||j|dd d}| |}| |||i}n@|
sZt|||fr|  }| |}| |||i}nt|}|||< q||fS )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   rb   c                 3   s   | ]}t | V  qd S r   )r   )ru   r   r   rZ   r[   r     s   z0_EvaluatorPrinter._preprocess.<locals>.<genexpr>Nc                 S   s   d|  S )N_rZ   )r  rZ   rZ   r[   r     r   z/_EvaluatorPrinter._preprocess.<locals>.<lambda>)modify)r   r   sympy.core.sortingr  r   r   r   r   r   r  r   r   r   rc   r   r   r
   r   reversedr{   r  r   r   r  r   r   	is_symbolr   r  rt   _subexpr)r   r   r   r   r  r   r   r  r   rc   r   r
  r   r   r  dummyrZ   r   r[   r    s@    &





z_EvaluatorPrinter._preprocessc                    s   ddl m} ddlm |}t|dd }|d ur>| }nt||rJnt|tr fdd| D } fdd| D }tt	||}nFt|t
rt
 fdd	|D }n t|trއ fd
d|D }|S )Nr   r   r   r   c                    s   g | ]} | qS rZ   r  r   r   r   r   rZ   r[   ry     r   z._EvaluatorPrinter._subexpr.<locals>.<listcomp>c                    s   g | ]} | qS rZ   r  r   r  rZ   r[   ry     r   c                 3   s   | ]} | V  qd S r   r  r   r  rZ   r[   r     r   z-_EvaluatorPrinter._subexpr.<locals>.<genexpr>c                    s   g | ]} | qS rZ   r  r   r  rZ   r[   ry     r   )r   r   r   r   r   r   r   r   valuesr  r   r{   )r   r   r   r   r   r   vrZ   r  r[   r    s"    




z_EvaluatorPrinter._subexprc                 C   s   g S )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.
        rZ   )r   r   rZ   rZ   r[   r    s    z(_EvaluatorPrinter._print_funcargwrappingc                    s    fdd d  ||gS )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                    s   d d fdd| D S )Nz[{}]r   c                 3   s"   | ]}t |r |n|V  qd S r   r   )ru   val
unpack_lhsrZ   r[   r     s   zI_EvaluatorPrinter._print_unpacking.<locals>.unpack_lhs.<locals>.<genexpr>)r   r   )lvaluesr"  rZ   r[   r#    s    z6_EvaluatorPrinter._print_unpacking.<locals>.unpack_lhsr  )r   )r   Zunpacktor   rZ   r"  r[   r    s    z"_EvaluatorPrinter._print_unpacking)NF)r   
__module____qualname__r  r   classmethodr  r  r  r  r  rZ   rZ   rZ   r[   r   4  s   
7
+
r   c                   @   s   e Zd Zdd ZdS )r   c                    s@    fdd d fdd |D }dd t||gS )zGenerate argument unpacking code.

        This method is used when the input value is not interable,
        but can be indexed (see issue #14655).
        c                 3   sF   d}| D ]8}t |r0 |D ]}|f| V  qn|fV  |d7 }qd S r   r   )elemsr   r   r   )r   rZ   r[   r     s    zB_TensorflowEvaluatorPrinter._print_unpacking.<locals>.flat_indexesr   c              	   3   s&   | ]}d   dtt|V  qdS )z{}[{}]z][N)r   r   mapr   r   )rvaluerZ   r[   r     s   z?_TensorflowEvaluatorPrinter._print_unpacking.<locals>.<genexpr>z[{}] = [{}])r   r   r
   )r   r$  r*  indexedrZ   )r   r*  r[   r    s
    z,_TensorflowEvaluatorPrinter._print_unpackingN)r   r%  r&  r  rZ   rZ   rZ   r[   r     s   r   c           	      C   s   ddl m} |du ri }t| r8| D ]}t|| q$|S t| trl|  D ]\}}t|| t|| qJ|S t| dd}t||rt|dd}|dur| jj	}||v r|| |krt
d| |||< t| dr| jD ]}t|| q|S )ao   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   )r   r,  r   r   r   r   rS   r   r   r   
ValueErrorr   r   )	r   rW   r,  r   keyr!  r   imprt   rZ   rZ   r[   r     s4    $




r   c                 C   sd   ddl m} i }t| |r&| j}| j} t| trJ|| fdt|i|} nt| |s`ttd| S )a   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.)	r   r1  r   _kwargsr   r   staticmethodr.  r   )Zsymfuncimplementationr1  kwargsrZ   rZ   r[   implemented_function?  s     &


r6  )F)NNTFF)NN)N)?r   typingr   r   tDictr~   r   r  r   r   sympy.externalr   sympy.utilities.exceptionsr   sympy.utilities.decoratorr   sympy.utilities.iterablesr   r   r	   r
   sympy.utilities.miscr   Z__doctest_requires__ZMATH_DEFAULTZMPMATH_DEFAULTZNUMPY_DEFAULTZSCIPY_DEFAULTZCUPY_DEFAULTZJAX_DEFAULTZTENSORFLOW_DEFAULTZSYMPY_DEFAULTZNUMEXPR_DEFAULTcopyZMATHZMPMATHZNUMPYZSCIPYZCUPYZJAXZ
TENSORFLOWZSYMPYZNUMEXPRZMATH_TRANSLATIONSZMPMATH_TRANSLATIONSZNUMPY_TRANSLATIONSZSCIPY_TRANSLATIONSZCUPY_TRANSLATIONSZJAX_TRANSLATIONSZTENSORFLOW_TRANSLATIONSZNUMEXPR_TRANSLATIONSrI   r\   r   r   r   r   r   r   r   r   r   r6  rZ   rZ   rZ   r[   <module>   s   	








;
       `
u /
D