
    wgۚ                       d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dlZd dlm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZN d dlOmPZPmQZQ d dlRmSZS d dlTmUZU d d	lVmWZW dd
ZXd ZYd ZZd Z[e[ G d d             Z\y)    )annotationsN)product)AnyCallable)FMulAddPowRationallogexpsqrtcossintanasinacosacotasecacscsinhcoshtanhasinhacoshatanhacothasechacschexpandimflattenpolylogcancelexpand_trigsignsimplifyUnevaluatedExprSatanatan2ModMaxMinrfEiSiCiairyaiairyaiprimeairybiprimepiprimeisprimecotseccsccschsechcothFunctionIpiTupleGreaterThanStrictGreaterThanStrictLessThanLessThanEqualityOrAndLambdaIntegerDummysymbols)sympify_sympify)airybiprime)li)sympy_deprecation_warningc                h    t        ddd       t        |      }t        |j                  |             S )NzThe ``mathematica`` function for the Mathematica parser is now
deprecated. Use ``parse_mathematica`` instead.
The parameter ``additional_translation`` can be replaced by SymPy's
.replace( ) or .subs( ) methods on the output expression instead.z1.11zmathematica-parser-new)deprecated_since_versionactive_deprecations_target)rQ   MathematicaParserrM   
_parse_old)sadditional_translationsparsers      ^/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/parsing/mathematica.pymathematicar[      s;    	E "(#; 67F6$$Q'((    c                8    t               }|j                  |       S )a  
    Translate a string containing a Wolfram Mathematica expression to a SymPy
    expression.

    If the translator is unable to find a suitable SymPy expression, the
    ``FullForm`` of the Mathematica expression will be output, using SymPy
    ``Function`` objects as nodes of the syntax tree.

    Examples
    ========

    >>> from sympy.parsing.mathematica import parse_mathematica
    >>> parse_mathematica("Sin[x]^2 Tan[y]")
    sin(x)**2*tan(y)
    >>> e = parse_mathematica("F[7,5,3]")
    >>> e
    F(7, 5, 3)
    >>> from sympy import Function, Max, Min
    >>> e.replace(Function("F"), lambda *x: Max(*x)*Min(*x))
    21

    Both standard input form and Mathematica full form are supported:

    >>> parse_mathematica("x*(a + b)")
    x*(a + b)
    >>> parse_mathematica("Times[x, Plus[a, b]]")
    x*(a + b)

    To get a matrix from Wolfram's code:

    >>> m = parse_mathematica("{{a, b}, {c, d}}")
    >>> m
    ((a, b), (c, d))
    >>> from sympy import Matrix
    >>> Matrix(m)
    Matrix([
    [a, b],
    [c, d]])

    If the translation into equivalent SymPy expressions fails, an SymPy
    expression equivalent to Wolfram Mathematica's "FullForm" will be created:

    >>> parse_mathematica("x_.")
    Optional(Pattern(x, Blank()))
    >>> parse_mathematica("Plus @@ {x, y, z}")
    Apply(Plus, (x, y, z))
    >>> parse_mathematica("f[x_, 3] := x^3 /; x > 0")
    SetDelayed(f(Pattern(x, Blank()), 3), Condition(x**3, x > 0))
    )rU   parse)rW   rY   s     rZ   parse_mathematicar_       s    d  F<<?r\   c                    t        |       dk(  r| d   }t        d      }|j                  |      }|D cg c]  }|j                  d    }}t	        |      }t        |t              rUt        d| t              }t        ||j                  t        |      D 	ci c]  \  }}	 ||dz         |	 c}	}            S t        d|      S t        |       dk(  r| d   }| d   }
t        ||
      S t        d      c c}w c c}	}w )	N   r   Slotzdummy0:cls    z&Function node expects 1 or 2 arguments)lenr>   atomsargsmax
isinstancerJ   rL   rK   rI   xreplace	enumerateSyntaxError)ri   argrb   slotsanumbersnumber_of_arguments	variablesivbodys              rZ   _parse_Functionrx   V   s    
4yA~1g		$&+,166!9,,!'l)73'*=)> ?UKI)S\\IV_L`2aDAq4!9a<2a%bccb#	TaG	Awi&&BCC - 3bs   C7C<c                &    | j                          | S N)_initialize_classrc   s    rZ   _decor|   i   s    Jr\   c            !          e Zd ZU dZi 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ddddd d!d"d#d$d%d&d'd(d)d*Z ed+d,d-      D ]V  \  ZZZeez   ez   d.z   Z	erd/ej                         z   ez   d0z   Znej                         ez   d0z   Zej                  e	ei       X d1d2d3d4d5Z ej                  d6ej                         d7f ej                  d8ej                         d7f ej                  d9ej                         d:f ej                  d;ej                         d<fd=Z ej                  d>ej                         Z ej                  d?ej                         Zd@Zi ZdAedB<   i ZdAedC<   i ZdAedD<   edE        ZddGZedH        ZdI ZdJ ZedK        ZedL        Z edM        Z!edN        Z"dO Z#dP Z$dQZ%dRZ&dSZ'dTZ(dUZ)dVZ*e'dFdWdX ife%e(dWdYife%e)dZd[d\d]d^d_d`fe%e*dadb ife'dFdcddife%e*dedfife%e)dgdhdife%e*djdkife%e(dldmife'dFdndodpfe%e(dqdrife%e(dsdtife&dFdudvife%e(dwdxdyfe%e(dzd{d|d}d~ddfe%dFddife%e(dddfe%e(dddfe%e(ddife&dFd d dfe%e)ddife%e)dddd dfe'dFdddddfe%dFd d dfe&dFd d dfe%dFddife'dFd d d d dfe%dFdd ife&dFdddfgZ+ded<   d d dZ,dZ-dZ.g dZ/g dZ0ed        Z1ed        Z2dFZ3d Z4ddZ5ddZ6ddZ7ddZ8ddZ9ddZ:ddZ;dd	dZ<d
dZ=ddZ>ddZ?i de@deAdeBdeCdd ddĄ ddƄ deCdeDdeEdeFdeGdeHdeIdeJdeKdeLi deMdd҄ deNdeOdePdeQdeRdeSdeTdeUdeVdeWdeXdeYdeZde[de\i de]de^de_j                  de`deadebdecdeddeedefdegdd dehdeidejdekdeli demdendeodepdeqderdesdetdeudevdewdexd~eyd}ezd|e{dze|dre}e~edZeed Zd Zd ZyF(  rU   ap  
    An instance of this class converts a string of a Wolfram Mathematica
    expression to a SymPy expression.

    The main parser acts internally in three stages:

    1. tokenizer: tokenizes the Mathematica expression and adds the missing *
        operators. Handled by ``_from_mathematica_to_tokens(...)``
    2. full form list: sort the list of strings output by the tokenizer into a
        syntax tree of nested lists and strings, equivalent to Mathematica's
        ``FullForm`` expression output. This is handled by the function
        ``_from_tokens_to_fullformlist(...)``.
    3. SymPy expression: the syntax tree expressed as full form list is visited
        and the nodes with equivalent classes in SymPy are replaced. Unknown
        syntax tree nodes are cast to SymPy ``Function`` objects. This is
        handled by ``_from_fullformlist_to_sympy(...)``.

    zSqrt[x]zsqrt(x)zRational[x,y]zRational(x,y)zExp[x]zexp(x)zLog[x]zlog(x)zLog[x,y]zlog(y,x)zLog2[x]zlog(x,2)zLog10[x]z	log(x,10)zMod[x,y]zMod(x,y)zMax[*x]zMax(*x)zMin[*x]zMin(*x)zPochhammer[x,y]zrf(x,y)zArcTan[x,y]z
atan2(y,x)zExpIntegralEi[x]zEi(x)zSinIntegral[x]zSi(x)zCosIntegral[x]zCi(x)z	AiryAi[x]z	airyai(x)zAiryAiPrime[x]zairyaiprime(x)z	airybi(x)zairybiprime(x)z li(x)z
primepi(x)zprime(x)z
isprime(x))z	AiryBi[x]zAiryBiPrime[x]zLogIntegral[x]z
PrimePi[x]zPrime[x]z	PrimeQ[x]) Arc)SinCosTanCotSecCsc)r~   hz[x]rq   z(x)r~   z**[]) ^{}z
                (?:(?<=[a-zA-Z\d])|(?<=\d\.))     # a letter or a number
                \s+                               # any number of whitespaces
                (?:(?=[a-zA-Z\d])|(?=\.\d))       # a letter or a number
                *z
                (?:(?<=[])\d])|(?<=\d\.))       # ], ) or a number
                                                # ''
                (?=[(a-zA-Z])                   # ( or a single letter
                z
                (?<=[a-zA-Z])       # a letter
                \(                  # ( as a character
                (?=.)               # any characters
                z*(z
                (?:
                \A|(?<=[^a-zA-Z])
                )
                Pi                  # 'Pi' is 3.14159... in Mathematica
                (?=[^a-zA-Z])
                r@   )
whitespaceadd*_1add*_2Piz
                (?:
                \A|(?<=[^a-zA-Z])   # at the top or a non-letter
                )
                [A-Z][a-zA-Z\d]*    # Function
                (?=\[)              # [ as a character
                z(
                \{.*\}
                z
                (?:
                \A|(?<=[^a-zA-Z])
                )
                {arguments}         # model argument like x, y,...
                (?=[^a-zA-Z])
                z%dict[tuple[str, int], dict[str, Any]]TRANSLATIONScache_originalcache_compiledc                p    | j                  | j                        }| j                  j                  |       y rz   )_compile_dictionaryCORRESPONDENCESr   update)rd   ds     rZ   r{   z#MathematicaParser._initialize_class   s.     ##C$7$78"r\   Nc                   i | _         | j                   j                  | j                         |i }| j                  j                  |k7  rNt        |t              st        d      | j                  |      }|| j                  _        || j                  _	        | j                   j                  | j                  j                         y )NzThe argument must be dict type)
translationsr   r   	__class__r   rk   dict
ValueErrorr   r   )selfrX   r   s      rZ   __init__zMathematicaParser.__init__   s     	  !2!23"*&(# >>((,CC5t< !ABB (()@AA -DDNN),-DNN) 	  !>!>?r\   c                   i }|j                         D ]  \  }}| j                  |       | j                  |       | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  j                  |      }|dj                  |      }t        |      |j                         }| j                  |      \  }}	|j                         dk7  s|	t        |      k7  rdj                  |      }t        |      |d   d   dk(  rd}
nt        |      }
||
f}|D cg c]  }|d   dk7  r|nd|z    }}d	d
j                  |      z   dz   }| j                  j                  |      }t        j                  |t        j                         }i ||<   |||   d<   |||   d<   |||   d<    |S c c}w )Nr   r   '{f}' function form is invalid.fr   r   \z(?:(|z)))	argumentsfsri   pat)items_check_input_apply_rules_replace
FM_PATTERNsearchformatr   group	_get_argsstartrg   joinARGS_PATTERN_TEMPLATErecompileVERBOSE)rd   dicr   fmr   merrfm_nameri   endkey_argkeyxre_argsxyzpatStrr   s                    rZ   r   z%MathematicaParser._compile_dictionary  s    iik 7	 FBR R  !!"l3B!!"l3B b#&Bb#&B %%b)A y7>>>D o% ggiG a(ID# wwyA~B7>>>D o% Bx{c!d)G$C @DD!AaDCKqTAX5DGD 388G,,t3C ..555DF**VRZZ0C AcFAcF4L!AcF6NAcF5Mo7	 r ! Es   Gc                   | j                   }d}d}	 |j                  |      }|||z  }	 |S |j                         }| j                  |      \  }}|j	                         }	| j                  ||||	|      }|	}||d| z  }||d }t)z'Parse Mathematica function to SymPy oner~   r   N)r   r   r   r   r   _convert_one_function)
r   rW   r   scannedcurr   r   ri   r   bgns
             rZ   _convert_functionz#MathematicaParser._convert_functionU  s     oo

1Ay1. ) B q)ID# '')C **1b$SAA C q#wG #$A7 r\   c                   |t        |      f| j                  v r5|t        |      f}| j                  |   d   }t        t        ||            }n|df| j                  v rU|df}| j                  |   d   }i }t	        |      D ].  \  }	}
|
d   dk(  rdj                  ||	d        ||
<    n(||	   ||
<   0 ndj                  |      }t        |      | j                  |   d   }| j                  |   d   }d	}d}	 |j                  |      }|||z  }nD|j                         }
|j                         }||d | ||
   z   z  }|j                         }||d  }]|d | |z   ||d  z   }|S )
Nri   r   r   ,z'{f}' is out of the whitelist.r   r   r   r~   )rg   r   r   ziprm   r   r   r   r   r   r   r   )r   rW   r   ri   r   r   r   x_argsr   ru   r   r   templater   r   r   r   xbgns                     rZ   r   z'MathematicaParser._convert_one_function|  s   D	?d///s4y/C &&s+F3F S&'A #Y$+++s)C &&s+F3F A!&) 1Q43;88DH-AaDAw!	 399B9?CS/! $$S)$/ $U+

8$Ay8# 	A 779D x1--G %%'C  ~H) . dsGg#$'r\   c                   |j                   }|j                         dz   }g g }}g }|}t        ||d |      D ]  \  }}	|	dk(  r|s|s|j                  |||        |dz   }|	dk(  r|j                  |	       n|	dk(  r|j	                          |	dk(  r|j                  |	       k|	dk(  sq|r|j	                          |j                  |||         n dz   }
||
fS )z'Get arguments of a Mathematica functionra   Nr   r   r   r   r   )stringr   rm   appendpop)rd   r   rW   ancsquarecurlyri   r   ru   cfunc_ends              rZ   r   zMathematicaParser._get_args  s     HHeegkB ags+ 	DAqCx%Ac!H%!e CxQc		 Cxa cJJLKK#a))	. q5X~r\   c                H    | j                   |   }|j                  ||      }|S rz   )REPLACEMENTSreplace)rd   rW   befafts       rZ   r   zMathematicaParser._replace  s'    s#IIc3r\   c                J    | j                   |   \  }}|j                  ||      S rz   )RULESsub)rd   rW   r   r   r   s        rZ   r   zMathematicaParser._apply_rules  s#    99S>SwwsAr\   c                    dD ]H  }|j                  |d         |j                  |d         k7  s-dj                  |      }t        |       d|v rd}t        |      y )N))r   r   )r   r   )()r   ra   r   r   r   z Currently list is not supported.)countr   r   )rd   rW   bracketr   s       rZ   r   zMathematicaParser._check_input  sm    ; 	&Gwwwqz"agggaj&997>>>C o%	&
 !84CS/! r\   c                "   | j                  |       | j                  |d      }| j                  |d      }| j                  |d      }| j                  |d      }| j                  |      }| j                  |d      }| j                  |d      }|S )Nr   r   r   r   r   r   )r   r   r   r   )r   rW   s     rZ   rV   zMathematicaParser._parse_old  s    ! a. MM!S! a*a* ""1% MM!S! a& r\   c                l    | j                  |      }| j                  |      }| j                  |      }|S rz   )_from_mathematica_to_tokens_from_tokens_to_fullformlist_from_fullformlist_to_sympy)r   rW   s2s3s4s        rZ   r^   zMathematicaParser.parse  s7    --a0..r2--b1	r\   InfixPrefixPostfixFlatRightLeft;c                L    t        | t              r| r| d   dk(  r| dgz   S d| dgS )Nr   CompoundExpressionNull)rk   listr   s    rZ   <lambda>zMathematicaParser.<lambda>%  sE    
1d8KPQVWXYVZ^rVrVH   zN  PQ  SY  yZ r\   r   Set
SetDelayedAddToSubtractFromTimesByDivideBy)=z:=z+=z-=z*=z/=z//c                
    | |gS rz   re   r   ys     rZ   r   zMathematicaParser.<lambda>(  s
    1a& r\   &r>   z/.
ReplaceAllRuleRuleDelayed)z->z:>z/;	Conditionr   AlternativesRepeatedRepeatedNull)z..z...z||rG   z&&rH   !NotSameQUnsameQ)z===z=!=EqualUnequal	LessEqualLessGreaterEqualGreater)z==z!=z<=<z>=>z;;SpanPlus+-Times)r   /.Dotc                ,    t         j                  |       S rz   )rU   _get_negr   s    rZ   r   zMathematicaParser.<lambda>8  s    '8'A'A!'D r\   c                    | S rz   re   r   s    rZ   r   zMathematicaParser.<lambda>9  s    q r\   )r  r  r   PowerApplyMapMapAllc                    d| |ddggS )Nr(  List1re   r  s     rZ   r   zMathematicaParser.<lambda>;  s    ZacdfgjpruivYw r\   )z@@z/@z//@z@@@
Derivative	Factorial
Factorial2	Decrement)'r  z!!z--c                    | g|S rz   re   r  s     rZ   r   zMathematicaParser.<lambda>=  s    !a r\   c                    d| g|S )NPartre   r  s     rZ   r   zMathematicaParser.<lambda>=  s    fa_RS_ r\   )r   [[c                    dg| S )Nr,  re   r   s    rZ   r   zMathematicaParser.<lambda>>  s    || r\   c                    | d   S )Nr   re   r   s    rZ   r   zMathematicaParser.<lambda>>  s
    AaD r\   )r   r   ?PatternTestc                    d| dggS NPatternBlankre   r   s    rZ   r   zMathematicaParser.<lambda>A  s    Iq7)4 r\   c                    dd| dgggS )NOptionalr=  r>  re   r   s    rZ   r   zMathematicaParser.<lambda>B  s    Z)Q	)BC r\   c                    d| dggS )Nr=  BlankSequencere   r   s    rZ   r   zMathematicaParser.<lambda>C  s    YO+<= r\   c                    d| dggS )Nr=  BlankNullSequencere   r   s    rZ   r   zMathematicaParser.<lambda>D  s    i-@,AB r\   )_z_._____rE  c                    d| d|ggS r<  re   r  s     rZ   r   zMathematicaParser.<lambda>F  s    )Q!)E r\   rb   SlotSequence)#z##z7list[tuple[str, str | None, dict[str, str | Callable]]]_mathematica_op_precedencec                 
    ddgS )Nrb   r-  re   re   r\   rZ   r   zMathematicaParser.<lambda>K  s
    fc] r\   c                 
    ddgS )NrI  r-  re   re   r\   rZ   r   zMathematicaParser.<lambda>L  s    ~s+ r\   z[A-Za-z][A-Za-z0-9]*z (?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+))r   r   r6  r   )r   r   ]]r   c                ~    t        |t              r)t        j                  t        j
                  |      rd| S dd|gS )Nr  r   -1)rk   strr   matchrU   _numberrd   r   s     rZ   r%  zMathematicaParser._get_negU  s;    $Q,:K:S:SUV1W1#wo^egkmn]oor\   c                    d|dgS )Nr'  rP  re   rT  s     rZ   _get_invzMathematicaParser._get_invY  s    D!!r\   c                0   | j                   | j                   S | j                  | j                  g}| j                  d d  | j                  d d  z   }| j
                  D ]  \  }}}|D ]  }|j                  |          |j                  d        |j                  t        t        j                  |             |j                  d       |j                  d       t        j                  ddj                  |      z   dz         }|| _         | j                   S )Nc                    t        |        S rz   )rg   r   s    rZ   r   z2MathematicaParser._get_tokenizer.<locals>.<lambda>h  s    #a& r\   )r   r   
r   r   r   )_regex_tokenizer_literalrS  _enclosure_open_enclosure_closerK  r   sortextendmapr   escaper   r   )r   tokenstokens_escapetypstratsymdictk	tokenizers           rZ   _get_tokenizerz MathematicaParser._get_tokenizer_  s      ,(((--.,,Q/$2G2G2JJ#'#B#B 	(C ($$Q'(	( 	01c"))]34cdJJsSXXf%55;<	 )$$$r\   c                   | j                         }g }	 |j                  d      }|dk(  r t        |      dkD  r|j                  |       nt	        j
                  d||dz   d        }|t        d      ||j                         z   dz   }|dkD  r|j                  |d |        |j                  d||dz   | j                  dd      g       ||dz   d  }t        |      D ]h  \  }}t        |t              r	 |j                  d	      }	|	dk(  rn5|j                  d
      }
|
dk(  s|
|	k  rt        d      |d |	 ||
dz   d  z   }L|||<   j |D cg c]6  }t        |t              r!|j                         r|j                  |      n|g8 }}|D cg c]  }|D ]  }|  }}}|r$|d   dk(  r|j                  d       |r	|d   dk(  r|r$|d   dk(  r|j                  d       |r	|d   dk(  r|S c c}w c c}}w )N"r   r   z(?<!\\)"ra   z"mismatch in string "  " expression_Strz\"z(*z*)zmismatch in comment (*  *) coderf   rY  )ri  findrg   r   r   r   rn   r   r   rm   rk   r   rQ  isasciifindallr   )r   coderh  code_splitsstring_start	match_end
string_endru   
code_splitpos_comment_startpos_comment_endtoken_listsjrb  s                 rZ   r   z-MathematicaParser._from_mathematica_to_tokensp  sN   '')	 )+99T?Lr!t9q=&&t,		+tLNO/DEI !"FGG%	(99A=Ja""4#67\!^J(G(O(OPUWZ([\]
1&D   '{3 	(MAz*d+$.OOD$9!$*",//$"7"b(O>O,O%&GHH'(:):;jYZIZI[>\\
  (KN	( epp_`z!S/Aaiiky((+XYWZZpp(4!4Q!4!44 d*JJqM d* t+JJrN t+  q4s   ;G1G6c                    t        |t              ryt        j                  | j                  |      ryt        j                  d| j
                  z   |      ryy)NFz-?T)rk   r   r   rR  r[  rS  r   tokens     rZ   _is_opzMathematicaParser._is_op  sA    eT"88DMM5)88D4<<'/r\   c                0    |dv ry| j                  |       S )N)r   r   Tr}  r{  s     rZ   _is_valid_star1z!MathematicaParser._is_valid_star1      J;;u%%%r\   c                0    |dv ry| j                  |       S )N)r   r   Tr  r{  s     rZ   _is_valid_star2z!MathematicaParser._is_valid_star2  r  r\   c                n   g g}g }d}|t        |      k  rs||   }|| j                  v r8|d   j                  |       |j                  |       |j                  g        n|dk(  rZt        |d         dk(  r|d   d   |d   k(  rt        d|d   z        | j	                  |d         |d<   |j                  g        n|| j
                  v r| j
                  j                  |      }| j                  |   |d   k7  rt        d      }|dk(  rm|d   dk(  re|d   dk(  r|j                  |d	z   d
       nI|d   dk(  rA||d	z      d
k(  r	d||d	z   <   n-||d	z      dk(  rd||d	z   <   |j                  |dz   d
       n||t        |d         dk(  r|d   d   dk(  rt        d      | j	                  |d   d      }||d<   g }	|d   d   |d   k7  r.|	j                  |j                                |d   d   |d   k7  r.|	j                          |d   dk(  r%t        |	      d	k7  rt        dt        |	      z        |d   j                  |	       |j                  d       n|d   j                  |       |d	z  }|t        |      k  rst        |      d	k7  rt        d      | j	                  |d         S )Nr   r   r   z %s cannot be followed by comma ,zunmatched enclosurerN  r   ra   r   r6  rf   r   z( ) not valid syntaxTz1( must be followed by one expression, %i detectedz"Stack should have only one element)rg   r\  r   rn   _parse_after_bracesr]  indexinsertr   reverseRuntimeError)
r   rb  stackopen_seqpointerr|  indunmatched_enclosure
last_stacknew_stack_elements
             rZ   r   z.MathematicaParser._from_tokens_to_fullformlist  s   DF#7OE,,,b	  '&R #uRy>Q&59R=HRL+H%&H8TV<&WXX 44U2Y?b	R $///++11%8'',<*56K*L'}")<#B<3.
 #MM'!)S9%b\T1%gai0C748wqy 1!'	!2d!:48wqy 1 &gai =&9 911uRy>Q&59R=C+?%&<==!55eBiF
&b	$&!Bimx|3%,,UYY[9 Bimx|3!))+B<3&3/@+AQ+F%&Y\_`q\r&rssb	  !23R b	  'qLG] F#^ u:?CDD''a11r\   c                   d}t        |      }||k  r||   }|dk(  r|r|j                  |       |dz  }(|dk(  r|j                  d       |dz  }D|dkD  r	 | j                  |d | |      }n|d   }t        |      dkD  r|d   dk(  r|j	                  |dd         n|j                  |       t        |      D ]  }|j                  d        ||z  }d}|dz  }||k  ry y # t        $ r |j                  |       |dz  }Y w xY w)Nr   rY  ra   r   )rg   r   r  rn   r_  r   range)	r   linesrb  inside_enclosurer  sizer|  	prev_exprru   s	            rZ   _util_remove_newlinesz'MathematicaParser._util_remove_newlines  s1   6{n7OE}#JJw'AIDa<JJqMAIDQ;!$($<$<VHW=MO_$`	 !'q	Iy>A%)A,:N*NLL12/LL+w "AJJqM"qLG= n ' !

7+	 !s   C% %DDc                   t        |      }d}||k  rw|dkD  rf| j                  ||dz
           rO| j                  ||         r;||   dk(  rd||<   ||dz      d   ||dz   <   n|j                  |d       |dz  }|dz  }|dz  }||k  rvy y )Nr   ra   r   r   )rg   r  r  r  )r   rb  r  r  s       rZ   _util_add_missing_asterisksz-MathematicaParser._util_add_missing_asterisks  s    Kn!((!)<=((9
 '?c)&)F7O*01*=a*@F7Q;'MM'3/qLGAIDqLG! nr\   c                8   d}g }| j                  |||       t        | j                        D ]  \  }}}d|v r| j                  |       t	        |      }d}	|	|k  s0||	   }
t        |
t              r|
|v r||
   }t        |t              r|g}d}ng }d}|
dv r1|| j                  k(  r"|	dkD  r| j                  ||	dz
           s|	dz  }	u|| j                  k(  rA|	dk(  s6|	|dz
  k(  s.| j                  ||	dz
           s| j                  ||	dz            r|	dz  }	d}|||	<   || j                  k(  r~|j                  |	dz
        }|j                  |	      }|
dk(  r| j                  |      }n|
dk(  r| j                  |      }|	dz  }	|d	z  }|j                  |       |}|| j                  k(  r|	d	z   |k  r| j                  ||	dz      |
      r|j                  |       |j                  |	dz         }|j                  |	dz         }|dk(  r| j                  |      }n|dk(  r| j                  |      }|d	z  }|	d	z   |k  r| j                  ||	dz      |
      r|j                  |       n:|| j                   k(  r|	d	z   |k  rd||	dz      |
k(  rY|j                  ||g       |d
   }|j                  |	dz          |j                  |	dz         }|d	z  }|	d	z   |k  r||	dz      |
k(  rY|j                  |       n|| j"                  k(  r|	dz   |k  rw||	dz      |
k(  rlt        |t              r|||   |g||<   n |||   |      ||<   |j                  |	dz          |j                  |	dz         }|d	z  }|	dz   |k  r||	dz      |
k(  rl|j                  |       n|j                  |       n|| j                  k(  rm|t%        d      |	|dz
  k(  s| j                  ||	dz            r | j&                  |
          ||	<   n|j                  |j                  |	dz                |dz  }n}|| j(                  k(  rn|t%        d      |	dk(  s| j                  ||	dz
           r | j&                  |
          ||	<   n-|j                  |j                  |	dz
               |	dz  }	|dz  }t        |t*              rVt-        j.                  t*        |      } || }|j1                          t        |t2              r|j5                  |       n|||	<   |	dz  }	|	|k  r t	        |      dkD  st	        |      dk(  r-t	        |      dk(  r|r| j7                  ||      S t9        d      t	        |      dkD  r!|d   r|d   d   dk(  r|d   dd  }dg||}|S |d   S )NFr   r   ra   r  Tr!  r  rf   r   z1'Prefix' op_type should not have a grouping stratz0unable to create a single AST for the expressionr   )r  reversedrK  r  rg   rk   rQ  PREFIXr}  INFIXr   rV  r%  r   FLAT_check_op_compatibleRIGHTLEFT	TypeError_missing_arguments_defaultPOSTFIXr   typingcastclearr   r_  r  rn   )r   rb  r  changedr  op_typegrouping_stratop_dictr  r  r|  op_namenodefirst_indexarg1arg2node_pother_opop_callnew_nodecompound_expressions                        rZ   r  z%MathematicaParser._parse_after_braces!  s   ""5&2BC089X9X0Y _	,G^Wg~008FDGD.weS)ew.>.5enG "'3/ 'y&'!&'
*w$++/E'TU+^b^i^ijpqx{|q|j}^~  1 $**,"a<7dQh+>$++fU\_`U`NaBbfjfqfqrx  zA  DE  zE  sF  gG#qLG$"G&*F7O$**,%zz'!)4%zz'2 C<#'==#6D"c\#'==#6D1	D)!%)TYY6")A+"49R9RSYZabcZcSdfk9l &d 3+1::gai+@'-zz'!)'<#+s?+/==+>D%-_+/==+>D $	 #*A+"49R9RSYZabcZcSdfk9l #MM$/+tzz9")A+"4	9Je9S &wo >)/ &

719 5'-zz'!)'< $	 #*A+"4	9Je9S #MM$/+tyy8")A+"4	9Je9S#-gs#;;BF;DWY]:^F;$7:A&BUW[:\F;$7 &

719 5'-zz'!)'< $	 #*A+"4	9Je9S #MM$/ KK- DKK/)5"+,_"``"dQh.$++fWq[>Q2R.Td.M.Me.T.VF7O KK

719(=> AID DLL0)5"+,_"``"a<4;;vgk7J+K.Td.M.Me.T.VF7O KK

719(=>#qLG AID!'84,2KK',J#*D>

%h5 KK1.6F7O1u D._	@ v;?s5zQ3v;!3C //8HIIPQQu:>ayVAYq\-AA12#7"I%"I&"I&&ayr\   c                D    ||k(  ryddh}ddh}||v r||v ry||v r||v ryy)NTr   r!  r  r  Fre   )r   op1op2muldivaddsubs        rZ   r  z&MathematicaParser._check_op_compatible  sA    #:ss&=SF]&=SF]r\   c                   g }|g}t        j                  d|      }d}|D ]  }| |d   S |j                         }||| j                  dd      j                  dd      j                  dd      j	                         }|j                         dk(  r|dk7  r|d   j                  |       n||j                         dk(  r*|dk7  r|d   j                  |       |j                          n?|j                         dk(  r,|d   j                  |g       |j                  |d   d          |j                         } |d   S )zH
        Parses FullForm[Downvalues[]] generated by Mathematica
        z[\[\],]r   r   r~   r   r   r   )	r   finditerr   r   stripr   r   r   r   )	r   wmexproutr  	generatorlast_posrR  position	last_exprs	            rZ   _from_fullform_to_fullformlistz0MathematicaParser._from_fullform_to_fullformlist  s6    KK
F3	 	#E} 1v {{}Hx199#rBJJ3PRS[[\_acdjjlI{{}#?"I$$Y/#%?"I$$Y/		#%b	  )-U2Yr]+yy{H!	#" 1vr\   c                6    ddl mm fd |      S )Nr   )r>   Symbolc                    t        | t              rAt        |       dkD  r(| d   }| dd  D cg c]
  } |       }}  |      | S t        d      t        | t              r |       S t        |       S c c}w )Nr   ra   zEmpty list of expressions)rk   r   rg   r   rQ  rN   )exprheadro   ri   r>   r  	converters       rZ   r  zHMathematicaParser._from_fullformlist_to_fullformsympy.<locals>.converter  s    $%t9q=7D6:12h?sIcN?D?)8D>400$%@AAD#&d|#~% @s   A6)sympyr>   r  )r   pylistr>   r  r  s     @@@rZ   #_from_fullformlist_to_fullformsympyz5MathematicaParser._from_fullformlist_to_fullformsympy  s    *	&   r\   r
   Logc                 $    t        t        |        S rz   )r   r  rq   s    rZ   r   zMathematicaParser.<lambda>  s    #x{+ r\   Log2c                    t        | d      S Nrf   r   r   s    rZ   r   zMathematicaParser.<lambda>  s    #a) r\   Log10c                    t        | d      S )N
   r  r   s    rZ   r   zMathematicaParser.<lambda>  s    3q": r\   ExpSqrtr   r   r   r   r   r   ArcSinArcCosArcTanc                 P    t        |       dk(  rt        t        |        S t        |  S r  )rg   r*   r  r)   r  s    rZ   r   zMathematicaParser.<lambda>  s!    CFaKUHQK0 T1X r\   ArcCotArcSecArcCscSinhCoshTanhCothSechCschArcSinhArcCoshArcTanhArcCothArcSechArcCschExpandImReFlattenPolylogCancel
TrigExpandSignSimplifyDeferIdentityr   c                 "    t         j                  S rz   )r(   Zeror  s    rZ   r   zMathematicaParser.<lambda>	  s
    166 r\   r+   r,   r-   
PochhammerExpIntegralEiSinIntegralCosIntegralAiryAiAiryAiPrimeAiryBiAiryBiPrimeLogIntegralPrimePiPrimePrimeQr,  )rH   r>   )r?   r   c                "      fd |      S )Nc                D   t        | t              rft        | d   t              r | d         }n+j                  j                  | d   t	        | d               } || dd  D cg c]
  } |       c} S j
                  j                  | t        |             S c c}w )Nr   ra   )rk   r   _node_conversionsgetr>   _atom_conversionsrM   )r  r  ro   recurser   s      rZ   r  z>MathematicaParser._from_fullformlist_to_sympy.<locals>.recurse-  s    $%d1gt,"47+D1155d1gxQ?PQDd12h?sgcl?@@--11$FF @s   %Bre   )r   full_form_listr  s   ` @rZ   r   z-MathematicaParser._from_fullformlist_to_sympy+  s    	G ~&&r\   c                    |}| j                   j                         D ]   \  }}|j                  t        |      |      }" |S rz   )r	  r   r   r>   )r   mformr  mma_form
sympy_nodes        rZ   _from_fullformsympy_to_sympyz.MathematicaParser._from_fullformsympy_to_sympy9  sF    $($:$:$@$@$B 	@ Hj<< 2J?D	@r\   rz   )rp  rQ  )r|  z
str | listreturnbool)rb  r   )r  r   rb  r   r  r  )F)rb  r   r  r  )r  rQ  r  rQ  )r  rQ  )r  r   )__name__
__module____qualname____doc__r   r   arctrir   r   lowerr   r   r   r   r   r   r   r   ARG_MTRX_PATTERNr   r   __annotations__r   r   classmethodr{   r   r   r   r   r   r   r   r   rV   r^   r  r  r  r  r  r  rK  r  r[  rS  r\  r]  r%  rV  rZ  ri  r   r}  r  r  r   r  r  r  r  r  r  r   r   r	   r
   r   r   r   r   r   r8   r9   r:   r   r   r   r   r   r   r   r   r=   r<   r;   r   r   r   r   r   r   r   r    r  r!   r"   r#   r$   r%   r&   r'   r(   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   rO   rP   r5   r6   r7   rA   rC   rB   rD   rE   rF   rG   rH   rx   r	  r?   r@   r  r   r  re   r\   rZ   rU   rU   n   s	   (9 	( 	(	
 	J 	: 	K 	J 	9 	9 	) 	l 	G 	' 	'  	[!" 	*#$ !*!"!/O6 { -67@B )S!3Y]U"syy{"Q&.Bq5(BBx() 	L BJJ  ZZ	!
  BJJ  ZZ	!
  BJJ  ZZ	!
  BJJ  ZZ! ;&ER   ZZ!J "rzz #ZZ!
 ;=L7< =?N9> =?N9># #
@0 = =~%N@D # #J  
   " ": EFGDED 
$  Z  [  	\	s012	U,g^clt~  	A	t012	$j)*	t\*+	fM:;	t[)*	sN+,	$z.AB	tTl#	tUm$	U|$	gi89	WI[v]kr{|}	tVn%	F01	G'23	sEl#	D(* 	+	W~&	gU8Lwxy	$lLXcde	08TUV	3.IJ	sM*+	$4C=B	
 	 
sEFG	V>:;G$[ W $N #+"
 'H1G+O,p p " " %"-^&
&
52n!F*wr	6!$RRR 	R 	H	R
 	+R 	#R 	%R 	HR 	sR 	R 	sR 	sR 	sR 	sR  	s!R" 	s#R& 	$'R( 	$)R* 	M+R, 	$-R. 	$/R0 	$1R4 	5R6 	7R8 	9R: 	;R< 	=R> 	?RB 	5CRD 	5ERF 	5GRH 	5IRJ 	5KRL 	5MRP 	&QRR 	bSRT 	ehhURV 	7WRX 	7YRZ 	&[R^ 	k_R` 	aRb 	HcRd 	eRf 	AgRn 	!oRp 	sqRr 	ssRt 	suRv 	bwRx 	yRz 	r{R| 	r}R~ 	&R@ 	{ARB 	&CRD 	{ERF 	rGRH 	7IRJ 	KRL 	'MRP 	QRR 	$SRT 	URV 	WRX 	XYRZ 	[R\ 	b]R^ #cRj 
'r\   rU   rz   )]
__future__r   r   r  	itertoolsr   r   r   r  r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   sympy.core.sympifyrM   rN   sympy.functions.special.besselrO   'sympy.functions.special.error_functionsrP   sympy.utilities.exceptionsrQ   r[   r_   rx   r|   rU   re   r\   rZ   <module>r%     s    " 	     A A A A A A A A A A A A A A A A A A
 1 6 6 @
)3lD&
 O O Or\   