
    MZdr                       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@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZM d dlNmOZOmPZP d dlQmRZR d dlSmTZT d d	lUmVZV dd
ZWd ZXd ZYd ZZeZ G d d             Z[y)    )annotationsN)product)AnyCallable)EMulAddPow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)rP   MathematicaParserrL   
_parse_old)sadditional_translationsparsers      ;/usr/lib/python3/dist-packages/sympy/parsing/mathematica.pymathematicarZ      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))
    )rT   parse)rV   rX   s     rY   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
isinstancerI   rK   rJ   rH   xreplace	enumerateSyntaxError)rh   argra   slotsanumbersnumber_of_arguments	variablesivbodys              rY   _parse_Functionrw   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_classrb   s    rY   _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)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   d/z   Znej                         ez   d/z   Zej                  e	ei       X d0d1d2d3d4Z ej                  d5ej                         d6f ej                  d7ej                         d6f ej                  d8ej                         d9f 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d@edA<   i Zd@edB<   i Zd@edC<   edD        Zd dFZedG        ZdH ZdI ZedJ        ZedK        Z edL        Z!edM        Z"dN Z#dO Z$dPZ%dQZ&dRZ'dSZ(dTZ)dUZ*e'dEdVdW ife%e(dVdXife%e)dYdZd[d\d]d^d_fe%e*d`da ife'dEdbdcife%e*dddeife%e)dfdgdhfe%e*didjife%e(dkdlife'dEdmdndofe%e(dpdqife%e(drdsife&dEdtduife%e(dvdwdxfe%e(dydzd{d|d}d~dfe%dEddife%e(dddfe%e(dddfe%e(ddife&dEd d dfe%e)ddife%e)dddd dfe'dEdddddfe%dEd d dfe&dEd d dfe%dEddife'dEd d d d dfe%dEdd ife&dEdddfgZ+ded<   d d dZ,dZ-dZ.g dZ/g dZ0ed        Z1ed        Z2dEZ3d 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dd dd ddĄ deCdeDdeEdeFdeGdeHdeIdeJdeKdeLddЄ i deMdeNdeOdePdeQdeRdeSdeTdeUdeVdeWdeXdeYdeZde[de\de]i de^j                  de_de`deadebdecdeddeedefdd degdehdeidejdekdeldemi dendeodepdeqderdesdetdeudevd~ewd}exd|eyd{ezdye{dqe|dse}dce~ZeedZd Zd ZyE(
  rT   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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	airybi(x)zairybiprime(x)z li(x)z
primepi(x)zprime(x)z
isprime(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]rp   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 ry   )_compile_dictionaryCORRESPONDENCESr   update)rc   ds     rY   rz   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   rj   dict
ValueErrorr   r   )selfrW   r   s      rY   __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fsrh   pat)items_check_input_apply_rules_replace
FM_PATTERNsearchformatr   group	_get_argsstartrf   joinARGS_PATTERN_TEMPLATErecompileVERBOSE)rc   dicr   fmr   merrfm_namerh   endkey_argkeyxre_argsxyzpatStrr   s                    rY   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   rV   r   scannedcurr   r   rh   r   bgns
             rY   _convert_functionz#MathematicaParser._convert_functionT  s     oo

1Ay1. ) B q)ID# '')C **1b$SAA C q#wG #$A7 r[   c                   |t        |      f| j                  v r?|t        |      f}| j                  |   d   }t        ||      D 	ci c]  \  }}	||	
 }
}}	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 c c}	}w )
Nrh   r   r   ,z'{f}' is out of the whitelist.r   r   r   r}   )rf   r   ziprl   r   r   r   r   r   r   r   )r   rV   r   rh   r   r   r   x_argskru   r   rt   r   r   templater   r   r   r   xbgns                       rY   r   z'MathematicaParser._convert_one_function{  s   D	?d///s4y/C &&s+F3F #&fd"34$!QA4A4 #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#$'o 5s   E1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 functionr`   Nr   r   r   r   r   )stringr   rl   appendpop)rc   r   rV   ancsquarecurlyrh   r   rt   cfunc_ends              rY   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 ry   )REPLACEMENTSreplace)rc   rV   befafts       rY   r   zMathematicaParser._replace  s'    s#IIc3r[   c                J    | j                   |   \  }}|j                  ||      S ry   )RULESsub)rc   rV   r   r   r   s        rY   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   r`   r   r   r   z Currently list is not supported.)countr   r   )rc   rV   bracketr   s       rY   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   rV   s     rY   rU   zMathematicaParser._parse_old  s    ! a. MM!S! a*a* ""1% MM!S! a& r[   c                l    | j                  |      }| j                  |      }| j                  |      }|S ry   )_from_mathematica_to_tokens_from_tokens_to_fullformlist_from_fullformlist_to_sympy)r   rV   s2s3s4s        rY   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)rj   listr   s    rY   <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 ry   rd   r   ys     rY   r   zMathematicaParser.<lambda>'  s
    1a& r[   &r=   z/.
ReplaceAllRuleRuleDelayed)z->z:>z/;	Conditionr   AlternativesRepeatedRepeatedNull)z..z...z||rF   z&&rG   !NotSameQUnsameQ)z===z=!=EqualUnequal	LessEqualLessGreaterEqualGreater)z==z!=z<=<z>=>z;;SpanPlus+-Times)r   /.Dotc                ,    t         j                  |       S ry   )rT   _get_negr   s    rY   r   zMathematicaParser.<lambda>7  s    '8'A'A!'D r[   c                    | S ry   rd   r   s    rY   r   zMathematicaParser.<lambda>8  s    q r[   )r  r  r   PowerApplyMapMapAllc                    d| |ddggS )Nr(  List1rd   r  s     rY   r   zMathematicaParser.<lambda>:  s    ZacdfgjpruivYw r[   )z@@z/@z//@z@@@
Derivative	Factorial
Factorial2	Decrement)'r  z!!z--c                    | g|S ry   rd   r  s     rY   r   zMathematicaParser.<lambda><  s    !a r[   c                    d| g|S )NPartrd   r  s     rY   r   zMathematicaParser.<lambda><  s    fa_RS_ r[   )r   [[c                    dg| S )Nr,  rd   r   s    rY   r   zMathematicaParser.<lambda>=  s    || r[   c                    | d   S )Nr   rd   r   s    rY   r   zMathematicaParser.<lambda>=  s
    AaD r[   )r   r   ?PatternTestc                    d| dggS NPatternBlankrd   r   s    rY   r   zMathematicaParser.<lambda>@  s    Iq7)4 r[   c                    dd| dgggS )NOptionalr=  r>  rd   r   s    rY   r   zMathematicaParser.<lambda>A  s    Z)Q	)BC r[   c                    d| dggS )Nr=  BlankSequencerd   r   s    rY   r   zMathematicaParser.<lambda>B  s    YO+<= r[   c                    d| dggS )Nr=  BlankNullSequencerd   r   s    rY   r   zMathematicaParser.<lambda>C  s    i-@,AB r[   )_z_._____rE  c                    d| d|ggS r<  rd   r  s     rY   r   zMathematicaParser.<lambda>E  s    )Q!)E r[   ra   SlotSequence)#z##z7list[tuple[str, str | None, dict[str, str | Callable]]]_mathematica_op_precedencec                 
    ddgS )Nra   r-  rd   rd   r[   rY   r   zMathematicaParser.<lambda>J  s
    fc] r[   c                 
    ddgS )NrI  r-  rd   rd   r[   rY   r   zMathematicaParser.<lambda>K  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)rj   strr   matchrT   _numberrc   r   s     rY   r%  zMathematicaParser._get_negT  s;    $Q,:K:S:SUV1W1#wo^egkmn]oor[   c                    d|dgS )Nr'  rP  rd   rT  s     rY   _get_invzMathematicaParser._get_invX  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 ry   )rf   r   s    rY   r   z2MathematicaParser._get_tokenizer.<locals>.<lambda>g  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symdictr   	tokenizers           rY   _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(?<!\\)"r`   z"mismatch in string "  " expression_Strz\"z(*z*)zmismatch in comment (*  *) codere   rY  )rh  findrf   r   r   r   rm   r   r   rl   rj   r   rQ  isasciifindallr   )r   coderg  code_splitsstring_start	match_end
string_endrt   
code_splitpos_comment_startpos_comment_endtoken_listsjrb  s                 rY   r   z-MathematicaParser._from_mathematica_to_tokenso  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)rj   r   r   rR  r[  rS  r   tokens     rY   _is_opzMathematicaParser._is_op  sA    eT"88DMM5)88D4<<'/r[   c                0    |dv ry| j                  |       S )N)r   r   Tr|  rz  s     rY   _is_valid_star1z!MathematicaParser._is_valid_star1      J;;u%%%r[   c                0    |dv ry| j                  |       S )N)r   r   Tr~  rz  s     rY   _is_valid_star2z!MathematicaParser._is_valid_star2  r  r[   c                \   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	k(  sJ | j	                  |d         S )Nr   r   r   z %s cannot be followed by comma ,zunmatched enclosurerN  r   r`   r   r6  re   r   z( ) not valid syntaxTz1( must be followed by one expression, %i detected)
rf   r\  r   rm   _parse_after_bracesr]  indexinsertr   reverse)
r   rb  stackopen_seqpointerr{  indunmatched_enclosure
last_stacknew_stack_elements
             rY   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#^ 5zQ''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  r`   r   )rf   r   r  rm   r_  r   range)	r   linesrb  inside_enclosurer  sizer{  	prev_exprrt   s	            rY   _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   r`   r   r   )rf   r  r  r  )r   rb  r  r  s       rY   _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                   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(  rd|J |	|dz
  k(  s| j                  ||	dz            r | j$                  |
          ||	<   n|j                  |j                  |	dz                |dz  }nt|| j&                  k(  re|J |	dk(  s| j                  ||	dz
           r | j$                  |
          ||	<   n-|j                  |j                  |	dz
               |	dz  }	|dz  }t        |t(              rVt+        j,                  t(        |      } || }|j/                          t        |t0              r|j3                  |       n|||	<   |	dz  }	|	|k  r t	        |      dkD  st	        |      dk(  r-t	        |      dk(  r|r| j5                  ||      S t7        d      t	        |      dkD  r!|d   r|d   d   dk(  r|d   dd  }dg||}|S |d   S )NFr   r   r`   r  Tr!  r  re   r   z0unable to create a single AST for the expressionr   )r  reversedrK  r  rf   rj   rQ  PREFIXr|  INFIXr   rV  r%  r   FLAT_check_op_compatibleRIGHTLEFT_missing_arguments_defaultPOSTFIXr   typingcastclearr   r_  r  rm   )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                        rY   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55"dQh.$++fWq[>Q2R.Td.M.Me.T.VF7O KK

719(=> AID DLL0-55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q 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  Frd   )r   op1op2muldivaddsubs        rY   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	            rY   _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   r`   zEmpty list of expressions)rj   r   rf   r   rQ  rM   )exprheadrn   rh   r=   r  	converters       rY   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     @@@rY   #_from_fullformlist_to_fullformsympyz5MathematicaParser._from_fullformlist_to_fullformsympy  s    *	&   r[   Logc                 $    t        t        |        S ry   )r
   r  rp   s    rY   r   zMathematicaParser.<lambda>  s    #x{+ r[   Log2c                    t        | d      S Nre   r
   r   s    rY   r   zMathematicaParser.<lambda>  s    #a) r[   Log10c                    t        | d      S )N
   r  r   s    rY   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  )rf   r)   r  r(   r  s    rY   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 ry   )r'   Zeror  s    rY   r   zMathematicaParser.<lambda>  s
    166 r[   r*   r+   r,   
PochhammerExpIntegralEiSinIntegralCosIntegralAiryAiAiryAiPrimeAiryBiAiryBiPrimeLogIntegralPrimePiPrimePrimeQr,  )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   r`   )rj   r   _node_conversionsgetr=   _atom_conversionsrL   )r  r  rn   recurser   s      rY   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rd   )r   full_form_listr	  s   ` @rY   r   z-MathematicaParser._from_fullformlist_to_sympy%  s    	G ~&&r[   c                    |}| j                   j                         D ]   \  }}|j                  t        |      |      }" |S ry   )r  r   r   r=   )r   mformr  mma_form
sympy_nodes        rY   _from_fullformsympy_to_sympyz.MathematicaParser._from_fullformsympy_to_sympy3  sF    $($:$:$@$@$B 	@ Hj<< 2J?D	@r[   ry   )ro  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   classmethodrz   r   r   r   r   r   r   r   r   rU   r]   r  r  r  r  r  r  rK  r  r[  rS  r\  r]  r%  rV  rZ  rh  r   r|  r  r  r   r  r  r  r  r  r  r   r   r	   r   r   r   r   r   r7   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   rN   rO   r4   r5   r6   r@   rB   rA   rC   rD   rE   rF   rG   rw   r  r>   r?   r  r   r  rd   r[   rY   rT   rT   n   s	   (9( 	( 	J	
 	: 	K 	J 	9 	9 	) 	l 	G 	' 	' 	[  	*!" 	[#$ +!"!-O4 { -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 " " %"-^&
&
42l!F*un	6!$PPP 	P 	+	P
 	#P 	%P 	sP 	P 	sP 	sP 	sP 	sP 	sP 	sP" 	$#P$ 	$%P& 	M'P( 	$)P* 	$+P, 	$-P0 	1P2 	3P4 	5P6 	7P8 	9P: 	;P> 	5?P@ 	5APB 	5CPD 	5EPF 	5GPH 	5IPL 	&MPN 	bOPP 	ehhQPR 	7SPT 	7UPV 	&WPZ 	k[P\ 	]P^ 	H_P` 	aPb 	AcPj 	!kPl 	smPn 	soPp 	sqPr 	bsPt 	uPv 	rwPx 	ryPz 	&{P| 	{}P~ 	&P@ 	{APB 	rCPD 	7EPF 	GPH 	'IPL 	MPN 	$OPP 	QPR 	SPT 	XUPV 	WPX 	bYPZ 	s[P^ 	O_Pf 
'r[   rT   ry   )\
__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   sympy.core.sympifyrL   rM   sympy.functions.special.besselrN   'sympy.functions.special.error_functionsrO   sympy.utilities.exceptionsrP   rZ   r^   rw   r{   rT   rd   r[   rY   <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&
 I I Ir[   