
    wgQM                        U d Z ddlmZ ddlmZmZ ddlmZ ddl	m
Z
 ddlZddlmZ ddlmZ dd	lmZ  G d
 de      Zi Zded<   i Zded<   eZ G d d      Zd Zd Z	 	 ddZd Zd ZddlmZ y)z0sympify -- convert objects SymPy internal format    )annotations)AnyCallableN)getmro)choice   )global_parameters)iterablec                      e Zd ZddZd Zy)SympifyErrorNc                     || _         || _        y N)exprbase_exc)selfr   r   s      W/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/core/sympify.py__init__zSympifyError.__init__   s    	     c                    | j                   d| j                  S d| j                  d| j                   j                  j                  dt	        | j                         S )NzSympifyError: zSympify of expression 'z-' failed, because of exception being raised:
z: )r   r   	__class____name__str)r   s    r   __str__zSympifyError.__str__   sO    == )-44 ! "&DMM,C,C,L,L  	!r   r   )r   
__module____qualname__r   r    r   r   r   r      s    !!r   r   z'dict[type[Any], Callable[[Any], Basic]]	converter_sympy_converterc                      e Zd ZdZdZy)CantSympifya  
    Mix in this trait to a class to disallow sympification of its instances.

    Examples
    ========

    >>> from sympy import sympify
    >>> from sympy.core.sympify import CantSympify

    >>> class Something(dict):
    ...     pass
    ...
    >>> sympify(Something())
    {}

    >>> class Something(dict, CantSympify):
    ...     pass
    ...
    >>> sympify(Something())
    Traceback (most recent call last):
    ...
    SympifyError: SympifyError: {}

    r   N)r   r   r   __doc__	__slots__r   r   r   r    r    '   s    2 Ir   r    c                L    t        d t        |       j                  D              S )zM
    Checks if an object is an instance of a type from the numpy module.
    c              3  :   K   | ]  }|j                   d k(    yw)numpyN)r   ).0type_s     r   	<genexpr>z%_is_numpy_instance.<locals>.<genexpr>J   s#      - 7* -s   )anytype__mro__as    r   _is_numpy_instancer.   D   s&      - GOO- - -r   c                |   ddl }t        | |j                        sK|j                  |       r t	        t
           | j                               S t        | j                         fi |S ddlm	} |j                  |       j                  dz   }| j                         \  }}t        j                  |||      }  || |      S )zG
    Converts a numpy datatype input to an appropriate SymPy type.
    r   Nr   )Float)	precision)r%   
isinstancefloating	iscomplexr   complexitemsympifynumbersr0   finfonmantas_integer_ratiomlibfrom_rational)r-   sympify_argsnpr0   precpqs          r   _convert_numpy_typesrC   N   s     a%<<?#G,QVVX6616684|44"xx{  1$ !!#1q!T*Q$''r   c                   t        | dd      }|du r| S ||s| S t        |       t        | t              rt        |       t        | dd      }t	        |      D ]:  }t
        j                  |      }	|	t        j                  |      }	|	2 |	|       c S  |t        d      u r|rt        |       | S |t        j                  }t        |       r&ddl}
|
j                  |       rt        | |||||      S t        | dd      }|| j                         S |sAt        | dd      }|2t        | d	d      }|#dd
lm}  || j$                  | j&                        S t        | t(              st        |       raddl}
t        | |
j*                        rJ t        | |
j,                        ro| j.                  dk(  r`	 t1        | j3                         |||||      S t5        | d      rt1        t7        |             S t5        | d      rt1        t9        |             S |rt        |       t;        |       r.	  t        |       | D cg c]  }t1        |||||       c}      S t        | t(              st        dt        |       z        ddlm }m!}m"} ddlm#} ddlm$} |}|r||fz  }|r||fz  }	 | jK                  dd      }  || |||      }|S # t        $ r Y w xY wc c}w # t<        $ r Y w xY w# |tL        f$ r}t        d| z  |      d}~ww xY w)a"  
    Converts an arbitrary expression to a type that can be used inside SymPy.

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

    It will convert Python ints into instances of :class:`~.Integer`, floats
    into instances of :class:`~.Float`, etc. It is also able to coerce
    symbolic expressions which inherit from :class:`~.Basic`. This can be
    useful in cooperation with SAGE.

    .. warning::
        Note that this function uses ``eval``, and thus shouldn't be used on
        unsanitized input.

    If the argument is already a type that SymPy understands, it will do
    nothing but return that value. This can be used at the beginning of a
    function to ensure you are working with the correct type.

    Examples
    ========

    >>> from sympy import sympify

    >>> sympify(2).is_integer
    True
    >>> sympify(2).is_real
    True

    >>> sympify(2.0).is_real
    True
    >>> sympify("2.0").is_real
    True
    >>> sympify("2e-45").is_real
    True

    If the expression could not be converted, a SympifyError is raised.

    >>> sympify("x***2")
    Traceback (most recent call last):
    ...
    SympifyError: SympifyError: "could not parse 'x***2'"

    When attempting to parse non-Python syntax using ``sympify``, it raises a
    ``SympifyError``:

    >>> sympify("2x+1")
    Traceback (most recent call last):
    ...
    SympifyError: Sympify of expression 'could not parse '2x+1'' failed

    To parse non-Python syntax, use ``parse_expr`` from ``sympy.parsing.sympy_parser``.

    >>> from sympy.parsing.sympy_parser import parse_expr
    >>> parse_expr("2x+1", transformations="all")
    2*x + 1

    For more details about ``transformations``: see :func:`~sympy.parsing.sympy_parser.parse_expr`

    Locals
    ------

    The sympification happens with access to everything that is loaded
    by ``from sympy import *``; anything used in a string that is not
    defined by that import will be converted to a symbol. In the following,
    the ``bitcount`` function is treated as a symbol and the ``O`` is
    interpreted as the :class:`~.Order` object (used with series) and it raises
    an error when used improperly:

    >>> s = 'bitcount(42)'
    >>> sympify(s)
    bitcount(42)
    >>> sympify("O(x)")
    O(x)
    >>> sympify("O + 1")
    Traceback (most recent call last):
    ...
    TypeError: unbound method...

    In order to have ``bitcount`` be recognized it can be imported into a
    namespace dictionary and passed as locals:

    >>> ns = {}
    >>> exec('from sympy.core.evalf import bitcount', ns)
    >>> sympify(s, locals=ns)
    6

    In order to have the ``O`` interpreted as a Symbol, identify it as such
    in the namespace dictionary. This can be done in a variety of ways; all
    three of the following are possibilities:

    >>> from sympy import Symbol
    >>> ns["O"] = Symbol("O")  # method 1
    >>> exec('from sympy.abc import O', ns)  # method 2
    >>> ns.update(dict(O=Symbol("O")))  # method 3
    >>> sympify("O + 1", locals=ns)
    O + 1

    If you want *all* single-letter and Greek-letter variables to be symbols
    then you can use the clashing-symbols dictionaries that have been defined
    there as private variables: ``_clash1`` (single-letter variables),
    ``_clash2`` (the multi-letter Greek names) or ``_clash`` (both single and
    multi-letter names that are defined in ``abc``).

    >>> from sympy.abc import _clash1
    >>> set(_clash1)  # if this fails, see issue #23903
    {'E', 'I', 'N', 'O', 'Q', 'S'}
    >>> sympify('I & Q', _clash1)
    I & Q

    Strict
    ------

    If the option ``strict`` is set to ``True``, only the types for which an
    explicit conversion has been defined are converted. In the other
    cases, a SympifyError is raised.

    >>> print(sympify(None))
    None
    >>> sympify(None, strict=True)
    Traceback (most recent call last):
    ...
    SympifyError: SympifyError: None

    .. deprecated:: 1.6

       ``sympify(obj)`` automatically falls back to ``str(obj)`` when all
       other conversion methods fail, but this is deprecated. ``strict=True``
       will disable this deprecated behavior. See
       :ref:`deprecated-sympify-string-fallback`.

    Evaluation
    ----------

    If the option ``evaluate`` is set to ``False``, then arithmetic and
    operators will be converted into their SymPy equivalents and the
    ``evaluate=False`` option will be added. Nested ``Add`` or ``Mul`` will
    be denested first. This is done via an AST transformation that replaces
    operators with their SymPy equivalents, so if an operand redefines any
    of those operations, the redefined operators will not be used. If
    argument a is not a string, the mathematical expression is evaluated
    before being passed to sympify, so adding ``evaluate=False`` will still
    return the evaluated result of expression.

    >>> sympify('2**2 / 3 + 5')
    19/3
    >>> sympify('2**2 / 3 + 5', evaluate=False)
    2**2/3 + 5
    >>> sympify('4/2+7', evaluate=True)
    9
    >>> sympify('4/2+7', evaluate=False)
    4/2 + 7
    >>> sympify(4/2+7, evaluate=False)
    9.00000000000000

    Extending
    ---------

    To extend ``sympify`` to convert custom objects (not derived from ``Basic``),
    just define a ``_sympy_`` method to your class. You can do that even to
    classes that you do not own by subclassing or adding the method at runtime.

    >>> from sympy import Matrix
    >>> class MyList1(object):
    ...     def __iter__(self):
    ...         yield 1
    ...         yield 2
    ...         return
    ...     def __getitem__(self, i): return list(self)[i]
    ...     def _sympy_(self): return Matrix(self)
    >>> sympify(MyList1())
    Matrix([
    [1],
    [2]])

    If you do not have control over the class definition you could also use the
    ``converter`` global dictionary. The key is the class and the value is a
    function that takes a single argument and returns the desired SymPy
    object, e.g. ``converter[MyList] = lambda x: Matrix(x)``.

    >>> class MyList2(object):   # XXX Do not do this if you control the class!
    ...     def __iter__(self):  #     Use _sympy_!
    ...         yield 1
    ...         yield 2
    ...         return
    ...     def __getitem__(self, i): return list(self)[i]
    >>> from sympy.core.sympify import converter
    >>> converter[MyList2] = lambda x: Matrix(x)
    >>> sympify(MyList2())
    Matrix([
    [1],
    [2]])

    Notes
    =====

    The keywords ``rational`` and ``convert_xor`` are only used
    when the input is a string.

    convert_xor
    -----------

    >>> sympify('x^y',convert_xor=True)
    x**y
    >>> sympify('x^y',convert_xor=False)
    x ^ y

    rational
    --------

    >>> sympify('0.1',rational=False)
    0.1
    >>> sympify('0.1',rational=True)
    1/10

    Sometimes autosimplification during sympification results in expressions
    that are very different in structure than what was entered. Until such
    autosimplification is no longer done, the ``kernS`` function might be of
    some use. In the example below you can see how an expression reduces to
    $-1$ by autosimplification, but does not do so when ``kernS`` is used.

    >>> from sympy.core.sympify import kernS
    >>> from sympy.abc import x
    >>> -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1
    -1
    >>> s = '-2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1'
    >>> sympify(s)
    -1
    >>> kernS(s)
    -2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) - 1

    Parameters
    ==========

    a :
        - any object defined in SymPy
        - standard numeric Python types: ``int``, ``long``, ``float``, ``Decimal``
        - strings (like ``"0.09"``, ``"2e-19"`` or ``'sin(x)'``)
        - booleans, including ``None`` (will leave ``None`` unchanged)
        - dicts, lists, sets or tuples containing any of the above

    convert_xor : bool, optional
        If true, treats ``^`` as exponentiation.
        If False, treats ``^`` as XOR itself.
        Used only when input is a string.

    locals : any object defined in SymPy, optional
        In order to have strings be recognized it can be imported
        into a namespace dictionary and passed as locals.

    strict : bool, optional
        If the option strict is set to ``True``, only the types for which
        an explicit conversion has been defined are converted. In the
        other cases, a SympifyError is raised.

    rational : bool, optional
        If ``True``, converts floats into :class:`~.Rational`.
        If ``False``, it lets floats remain as it is.
        Used only when input is a string.

    evaluate : bool, optional
        If False, then arithmetic and operators will be converted into
        their SymPy equivalents. If True the expression will be evaluated
        and the result will be returned.

    	__sympy__NTr   r   )localsconvert_xorstrictrationalevaluate_sympy_flatshape)Array	__float____int__)rF   rG   rI   rJ   z cannot sympify object of type %r)
parse_expr
TokenErrorstandard_transformations)rG   )rationalize
 )
local_dicttransformationsrJ   zcould not parse %r)'getattrr   r2   r    r   _external_convertergetr   r*   r	   rJ   r.   r%   isscalarrC   rK   sympy.tensor.arrayrN   rL   rM   r   numberndarrayndimr7   r6   hasattrfloatintr
   	TypeErrorsympy.parsing.sympy_parserrQ   rR   rS   rG   rT   replaceSyntaxError)r-   rF   rG   rH   rI   rJ   is_sympycls
superclassconvr?   rK   rL   rM   rN   xrQ   rR   rS   t_convert_xort_rationalizerX   r   excs                           r   r7   r7   b   s@   h q+t,H4		Hq/!![!1o
![$
'C Sk 
"&&z2<#''
3D7N d4jq/!H$-- !;;q>'&'!# # aD)Gyy{ q&$'Aw-E 4QVVQWW--aa !!RYY///!RZZ( 66Q;&qvvx.43>.40808 : : Q$ 58$$Q	"3q6?"1o{	47?@B:; $Af+!H6 B C C a=QGHHF FGG.OM++M++:IIdB!Zbc KS ( B 		, $ :/!3S99:sN   3K +K :KK (K+ 	KKK 	K('K(+L
6LL
c                    t        | d      S )a[  
    Short version of :func:`~.sympify` for internal usage for ``__add__`` and
    ``__eq__`` methods where it is ok to allow some things (like Python
    integers and floats) in the expression. This excludes things (like strings)
    that are unwise to allow into such an expression.

    >>> from sympy import Integer
    >>> Integer(1) == 1
    True

    >>> Integer(1) == '1'
    False

    >>> from sympy.abc import x
    >>> x + 1
    x + 1

    >>> x + '1'
    Traceback (most recent call last):
    ...
    TypeError: unsupported operand type(s) for +: 'Symbol' and 'str'

    see: sympify

    T)rH   )r7   r,   s    r   _sympifyrq     s    4 1T""r   c                   d}d| v xs d| v }d| v rp|sm| j                  d      | j                  d      k7  rt        d      dj                  | j                               } | }| j	                  dd	      } | j	                  d
d      } d}| j	                  d|      } dx}}|j                  d      sJ 	 | j                  ||      }|dk(  rna|t        |      dz
  z  }t        |t        |             D ]$  }| |   dk(  r|dz  }n| |   dk(  r|dz  }|dk(  s$ n | d| dz   | |d z   } |dz   }yd| v rOd}|| v r2|t        t        j                  t        j                  z         z  }|| v r2| j	                  d|      } || v }nd}t        d      D ]  }	 t        |       }	 n |s	S ddlm}
  |
      difd 	      }	|	S # t        $ r |r} d}Y Gt        |       }	Y Tw xY w)a  Use a hack to try keep autosimplification from distributing a
    a number into an Add; this modification does not
    prevent the 2-arg Mul from becoming an Add, however.

    Examples
    ========

    >>> from sympy.core.sympify import kernS
    >>> from sympy.abc import x, y

    The 2-arg Mul distributes a number (or minus sign) across the terms
    of an expression, but kernS will prevent that:

    >>> 2*(x + y), -(x + 1)
    (2*x + 2*y, -x - 1)
    >>> kernS('2*(x + y)')
    2*(x + y)
    >>> kernS('-(x + 1)')
    -(x + 1)

    If use of the hack fails, the un-hacked string will be passed to sympify...
    and you get what you get.

    XXX This hack should not be necessary once issue 4596 has been resolved.
    F"'()zunmatched left parenthesisrV   z*(z* *(z** *z**z-( *(z-(r   r   N    _)Symbolc                    t        | t        t        t        f      r% t	        |       | D cg c]
  } |       c}      S t        | d      r| j                  d      S | S c c}w )NsubsT)hack2)r2   listtuplesetr*   ra   r}   )r   e_clearreps     r   r   zkernS.<locals>._clear`  s[    dT5#./4:$7Qvay7884 99S9-- 8s   A#)countr   joinsplitrf   endswithfindlenranger   stringascii_lettersdigitsr7   rd   symbolr{   )shitquotedoldstargetinestjkernr   r{   r   r   s              @@r   kernSr     s7   4 CAX!F
ax773<1773<';<< GGAGGI
 IIdF#IIfd# IIdF# Ds###vq!ABwVq A1c!f% Q43;AIDqTS[AID19 "1ae#AAA  !8D!)v33fmmCDD !)		#t$A!)CC1X 		1:D	 $<
C $<DK)  	1:D	s   GG$G$#G$)Basic)NTFFN) r!   
__future__r   typingr   r   mpmath.libmplibmpr<   inspectr   r   sympy.core.randomr   
parametersr	   sympy.utilities.iterablesr
   
ValueErrorr   r   __annotations__r   rZ   r    r.   rC   r7   rq   r   basicr   r   r   r   <module>r      s    6 "      $ ) .!: ! 68	2 7 =? 9 >    :-(( FKCL#:cN r   