
    Rier                       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[dS )    )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                    t          ddd           t          |          }t          |                    |                     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      9lib/python3.11/site-packages/sympy/parsing/mathematica.pymathematicarZ      sS    	E "(#;    677F6$$Q''(((    c                H    t                      }|                    |           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            	     0   t          |           dk    r| d         }t          d          |                              }d |D             }t          |          }t	          |t
                    rUt          d| t                    }t          ||	                    fdt          |          D                                 S t          d|          S t          |           d	k    r | d         }| d         }t          ||          S t          d
          )N   r   Slotc                (    g | ]}|j         d          S )r   )args).0as     rY   
<listcomp>z#_parse_Function.<locals>.<listcomp>[   s    ,,,16!9,,,r[   zdummy0:clsc                4    i | ]\  }} |d z             |S )r`    )rd   ivra   s      rY   
<dictcomp>z#_parse_Function.<locals>.<dictcomp>_   s+    2a2a2aDAq44!99a2a2a2ar[   rj      z&Function node expects 1 or 2 arguments)lenr=   atomsmax
isinstancerI   rK   rJ   rH   xreplace	enumerateSyntaxError)rc   argslotsnumbersnumber_of_arguments	variablesbodyra   s          @rY   _parse_Functionr|   V   s   
4yyA~~1g		$,,e,,,!'ll)733 	d ?*= ? ?UKKKI)S\\2a2a2a2aIV_L`L`2a2a2a%b%bcccb#	TaG	Awi&&&BCCCr[   c                .    |                                   | S N)_initialize_classrg   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 ]b\  ZZZeez   ez   d-z   Z	erd.e
                                z   ez   d/z   Zne
                                ez   d/z   Ze                    e	ei           cd0d1d2d3d4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d ekdeldemi dendeodepdeqderdesd	etd
eudevd~ewd}exd|eyd{ezdye{dqe|dse}dce~ZeedZd Zd ZdES (  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]re   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                n    |                      | j                  }| j                            |           d S r~   )_compile_dictionaryCORRESPONDENCESr   update)rh   ds     rY   r   z#MathematicaParser._initialize_class   s7     ##C$788"""""r[   Nc                d   i | _         | j                             | j                   |i }| j        j        |k    rQt          |t                    st          d          |                     |          }|| j        _        || j        _	        | j                             | j        j	                   d S )NzThe argument must be dict type)
translationsr   r   	__class__r   rr   dict
ValueErrorr   r   )selfrW   r   s      rY   __init__zMathematicaParser.__init__   s     	  !2333"*&(# >(,CCC5t<< C !ABBB (()@AAA -DDN),-DN) 	  !>?????r[   c                   i }|                                 D ]\  }}|                     |           |                     |           |                     |d          }|                     |d          }|                     |d          }|                     |d          }| j                            |          }|%d                    |          }t          |          |                                }| 	                    |          \  }}	|
                                dk    s|	t          |          k    r%d                    |          }t          |          |d         d         dk    rd}
nt          |          }
||
f}d |D             }d	d
                    |          z   dz   }| j                            |          }t          j        |t          j                  }i ||<   |||         d<   |||         d<   |||         d<   |S )Nr   r   '{f}' function form is invalid.fr   r   c                4    g | ]}|d          dk    r|nd|z   S )r   r   \rj   )rd   xs     rY   rf   z9MathematicaParser._compile_dictionary.<locals>.<listcomp>B  s,    DDD!AaDCKKqqTAXDDDr[   z(?:(|z)))	argumentsfsrc   pat)items_check_input_apply_rules_replace
FM_PATTERNsearchformatr   group	_get_argsstartro   joinARGS_PATTERN_TEMPLATErecompileVERBOSE)rh   dicr   fmr   merrfm_namerc   endkey_argkeyre_argsxyzpatStrr   s                   rY   r   z%MathematicaParser._compile_dictionary  s    iikk 7	  7	 FBR   R    !!"l33B!!"l33B b#&&Bb#&&B %%b))A y7>>>DD oo% ggiiG a((ID# wwyyA~~B7>>>DD oo% Bx{c!!d))G$C EDtDDDG 388G,,,t3C .555DDF*VRZ00C AcFAcF4L!AcF6NAcF5MMr[   c                >   | j         }d}d}	 |                    |          }|||z  }ns|                                }|                     |          \  }}|                                }	|                     ||||	|          }|	}||d|         z  }||d         }|S )z'Parse Mathematica function to SymPy oner   r   TN)r   r   r   r   r   _convert_one_function)
r   rV   r   scannedcurr   r   rc   r   bgns
             rY   _convert_functionz#MathematicaParser._convert_functionT  s     o	

1Ay1 B q))ID# ''))C **1b$SAAA C q#wG #$$A7	: r[   c                ^   |t          |          f| j        v r?|t          |          f}| j        |         d         }d t          ||          D             }n|df| j        v rh|df}| j        |         d         }i }t          |          D ]>\  }	}
|
d         dk    r"d                    ||	d                    ||
<    n||	         ||
<   ?n%d                    |          }t          |          | j        |         d         }| j        |         d	         }d
}d}	 |                    |          }|||z  }n]|                                }
|	                                }||d |         ||
         z   z  }|
                                }||d          }z|d |         |z   ||d          z   }|S )Nrc   c                    i | ]\  }}||	S rj   rj   )rd   krl   s      rY   rm   z;MathematicaParser._convert_one_function.<locals>.<dictcomp>  s    444$!QA444r[   r   r   ,z'{f}' is out of the whitelist.r   r   r   r   )ro   r   ziprt   r   r   r   r   r   r   r   )r   rV   r   rc   r   r   r   x_argsr   rk   r   r   templater   r   r   r   xbgns                     rY   r   z'MathematicaParser._convert_one_function{  s   D		?d///s4yy/C &s+F3F 54#fd"3"3444AA #Y$+++s)C &s+F3F A!&))  1Q43;;88DH--AaDEAw! 399B9??CS//! $S)$/ $U+	&

8$$Ay8# 		A 7799D x1--G %%''C  ~H)	&. dsdGg#$$'r[   c                   |j         }|                                dz   }g g }}g }|}t          ||d         |          D ]\  }}	|	dk    r&|s$|s"|                    |||                    |dz   }|	dk    r|                    |	           n|	dk    r|                                 |	dk    r|                    |	           |	dk    r6|r|                                 |                    |||                     n|dz   }
||
fS )z'Get arguments of a Mathematica functionr`   Nr   r   r   r   r   )stringr   rt   appendpop)rh   r   rV   ancsquarecurlyrc   r   rk   cfunc_ends              rY   r   zMathematicaParser._get_args  s5    HeeggkB ags++ 	 	DAqCxxx%xAc!eH%%%!e CxxQc		 Cxxa    c JJLLLLKK#a%)))E  q5X~r[   c                L    | j         |         }|                    ||          }|S r~   )REPLACEMENTSreplace)rh   rV   befafts       rY   r   zMathematicaParser._replace  s'    s#IIc3r[   c                N    | j         |         \  }}|                    ||          S r~   )RULESsub)rh   rV   r   r   r   s        rY   r   zMathematicaParser._apply_rules  s#    9S>SwwsAr[   c                    dD ]_}|                     |d                   |                     |d                   k    r%d                    |          }t          |          `d|v rd}t          |          d S )N))r   r   )r   r   )()r   r`   r   r   r   z Currently list is not supported.)countr   r   )rh   rV   bracketr   s       rY   r   zMathematicaParser._check_input  s    ; 	& 	&Gwwwqz""agggaj&9&9997>>>CC oo% : !884CS//! 8r[   c                b   |                      |           |                     |d          }|                     |d          }|                     |d          }|                     |d          }|                     |          }|                     |d          }|                     |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                    |                      |          }|                     |          }|                     |          }|S r~   )_from_mathematica_to_tokens_from_tokens_to_fullformlist_from_fullformlist_to_sympy)r   rV   s2s3s4s        rY   r]   zMathematicaParser.parse  s@    --a00..r22--b11	r[   InfixPrefixPostfixFlatRightLeft;c                ^    t          | t                    r| r| d         dk    r| dgz   nd| dgS )Nr   CompoundExpressionNull)rr   listr   s    rY   <lambda>zMathematicaParser.<lambda>$  sW    
1d8K8K  )ZPQ  )ZVWXYVZ^rVrVr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 r~   rj   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                6    t                               |           S r~   )rT   _get_negr  s    rY   r  zMathematicaParser.<lambda>7  s    '8'A'A!'D'D r[   c                    | S r~   rj   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1rj   r  s     rY   r  zMathematicaParser.<lambda>:  s    ZacdfgjpruivYw r[   )z@@z/@z//@z@@@
Derivative	Factorial
Factorial2	Decrement)'r  z!!z--c                    | g|S r~   rj   r  s     rY   r  zMathematicaParser.<lambda><  s    !a r[   c                    d| g|S )NPartrj   r  s     rY   r  zMathematicaParser.<lambda><  s    fa_RS_ r[   )r   [[c                    dg| S )Nr3  rj   r  s    rY   r  zMathematicaParser.<lambda>=  s    || r[   c                    | d         S )Nr   rj   r  s    rY   r  zMathematicaParser.<lambda>=  s
    AaD r[   )r   r   ?PatternTestc                    d| dggS NPatternBlankrj   r  s    rY   r  zMathematicaParser.<lambda>@  s    Iq7)4 r[   c                    dd| dgggS )NOptionalrD  rE  rj   r  s    rY   r  zMathematicaParser.<lambda>A  s    Z)Q	)BC r[   c                    d| dggS )NrD  BlankSequencerj   r  s    rY   r  zMathematicaParser.<lambda>B  s    YO+<= r[   c                    d| dggS )NrD  BlankNullSequencerj   r  s    rY   r  zMathematicaParser.<lambda>C  s    i-@,AB r[   )_z_._____rL  c                    d| d|ggS rC  rj   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   r4  rj   rj   r[   rY   r  zMathematicaParser.<lambda>J  s
    fc] r[   c                 
    ddgS )NrP  r4  rj   rj   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   r=  r   )r   r   ]]r   c                ~    t          |t                    r$t          j        t          j        |          rd| ndd|gS )Nr&  r'  -1)rr   strr   matchrT   _numberrh   r   s     rY   r,  zMathematicaParser._get_negT  sA    $Q,,o:K:SUV1W1Wow1www^egkmn]oor[   c                    d|dgS )Nr.  rW  rj   r[  s     rY   _get_invzMathematicaParser._get_invX  s    D!!r[   c                   | j         | j         S | j        | j        g}| j        d d          | j        d d          z   }| j        D ] \  }}}|D ]}|                    |           !|                    d            |                    t          t          j        |                     |                    d           |                    d           t          j        dd                    |          z   dz             }|| _         | j         S )Nc                "    t          |            S r~   )ro   r  s    rY   r  z2MathematicaParser._get_tokenizer.<locals>.<lambda>g  s    #a&& r[   )r   r   
r   r   r   )_regex_tokenizer_literalrZ  _enclosure_open_enclosure_closerR  r   sortextendmapr   escaper   r   )r   tokenstokens_escapetypstratsymdictr   	tokenizers           rY   _get_tokenizerz MathematicaParser._get_tokenizer^  s    ,((-.,QQQ/$2G2JJ#'#B 	( 	(C ( ($$Q''''(00111c")]33444cdJsSXXf%5%55;<<	 )$$r[   coderX  c                F   |                                  g }	 |                    d          }|dk    r)t          |          dk    r|                    |           nt	          j        d||dz   d                    }|t          d          ||                                z   dz   }|dk    r|                    |d |                    |                    d||dz   |                             d	d          g           ||dz   d          }t          |          D ]\  }}t          |t                    r	 |                    d
          }|dk    rnI|                    d          }	|	dk    s|	|k     rt          d          |d |         ||	dz   d          z   }e|||<   fd|D             }
d |
D             }|r/|d         dk    r#|                    d           |r|d         dk    #|r/|d         dk    r#|                    d           |r|d         dk    #|S )NT"r   r   z(?<!\\)"r`   z"mismatch in string "  " expression_Strz\"z(*z*)zmismatch in comment (*  *) codern   c                    g | ]C}t          |t                    r)|                                r                    |          n|gDS rj   )rr   rX  isasciifindall)rd   rk   rn  s     rY   rf   zAMathematicaParser._from_mathematica_to_tokens.<locals>.<listcomp>  sM    ppp_`z!S/A/AZaiikkZy((+++XYWZpppr[   c                    g | ]	}|D ]}|
S rj   rj   )rd   rk   js      rY   rf   zAMathematicaParser._from_mathematica_to_tokens.<locals>.<listcomp>  s%    444!44Q!4444r[   r`  )ro  findro   r   r   r   ru   r   r   rt   rr   r  r   )r   rp  code_splitsstring_start	match_end
string_endrk   
code_splitpos_comment_startpos_comment_endtoken_listsri  rn  s               @rY   r   z-MathematicaParser._from_mathematica_to_tokenso  s   ''))	 )+	'99T??Lr!!t99q==&&t,,,	+tLNOO/DEEI !"FGGG%	(9(99A=Ja""4#6777\!^J-F(G(O(OPUWZ([([\]]]
1&D	'  '{33 	( 	(MAz*d++ ]$.OOD$9$9!$**",//$"7"7"b((O>O,O,O%&GHHH'(:):(:;jYZIZI[I[>\\
] (KNN qpppdoppp44[444  	d**JJqMMM  	d**  	t++JJrNNN  	t++ r[   token
str | listreturnboolc                    t          |t                    rdS t          j        | j        |          rdS t          j        d| j        z   |          rdS dS )NFz-?T)rr   r  r   rY  rb  rZ  r   r  s     rY   _is_opzMathematicaParser._is_op  sY    eT"" 	58DM5)) 	58D4<'// 	5tr[   c                :    |dv rdS |                      |           S )N)r   r   Tr  r  s     rY   _is_valid_star1z!MathematicaParser._is_valid_star1  '    J4;;u%%%%r[   c                :    |dv rdS |                      |           S )N)r   r   Tr  r  s     rY   _is_valid_star2z!MathematicaParser._is_valid_star2  r  r[   ri  r  c                   g g}g }d}|t          |          k     r#||         }|| j        v rG|d                             |           |                    |           |                    g            n|dk    r~t          |d                   dk    r0|d         d         |d         k    rt          d|d         z            |                     |d                   |d<   |                    g            n.|| j        v r	| j                            |          }| j        |         |d         k    rt          d          }|dk    r|d         dk    r~|d         dk    r|                    |d	z   d
           nZ|d         dk    rK||d	z            d
k    r	d||d	z   <   n6||d	z            dk    r"d||d	z   <   |                    |dz   d
           n|n|t          |d                   dk    r!|d         d         dk    rt          d          |                     |d         d          }||d<   g }	|d         d         |d         k    r?|	                    |                                           |d         d         |d         k    ?|		                                 |d         dk    r2t          |	          d	k    rt          dt          |	          z            |d                             |	           |                    d           n|d                             |           |d	z  }|t          |          k     #t          |          d	k    sJ |                     |d                   S )Nr   r   r   z %s cannot be followed by comma ,zunmatched enclosurerU  r   r`   r   r=  rn   r   z( ) not valid syntaxTz1( must be followed by one expression, %i detected)
ro   rc  r   ru   _parse_after_bracesrd  indexinsertr   reverse)
r   ri  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+H%&H8TV<&WXXX 44U2Y??b	R    $///+11%88',<<*56K*L*L'}}")<)<#B<3..
 #MM'!)S9999%b\T11%gai0C7748wqy 1 1!'	!2d!:!:48wqy 1 &gai = = = =&9 9 2 21uRy>>Q&&59R=C+?+?%&<===!55eBiFF
&b	$&!Bimx|33%,,UYY[[999 Bimx|33!))+++B<3&&3/@+A+AQ+F+F%&Y\_`q\r\r&rsssb	  !2333R    b	  '''qLG] F##^ 5zzQ''a111r[   linesinside_enclosurec                   d}t          |          }||k     r5||         }|dk    r|r|                    |           |dz  }3|dk    r|                    d           |dz  }T|dk    rJ	 |                     |d |         |          }n2# t          $ r |                    |           |dz  }Y w xY w|d         }t          |          dk    r*|d         dk    r|                    |dd                     n|                    |           t          |          D ]}|                    d           ||z  }d}.|dz  }||k     3d S d S )Nr   r`  r`   r   )ro   r   r  ru   rf  r   range)	r   r  ri  r  r  sizer  	prev_exprrk   s	            rY   _util_remove_newlinesz'MathematicaParser._util_remove_newlines  s   6{{nn7OE}}# JJw'''AIDa<<JJqMMMAIDQ;;!$($<$<VHWH=MO_$`$`		& ! ! !

7+++	 !
 !'q	Iy>>A%%)A,:N*N*NLL122////LL+++w " "AJJqMMMMqLG= nnnnnns   -B $B32B3c                ^   t          |          }d}||k     r|dk    r|                     ||dz
                     rd|                     ||                   rI||         dk    rd||<   ||dz            d         ||dz   <   n |                    |d           |dz  }|dz  }|dz  }||k     d S d S )Nr   r`   r   r   )ro   r  r  r  )r   ri  r  r  s       rY   _util_add_missing_asterisksz-MathematicaParser._util_add_missing_asterisks
  s    KKnn!((!)<== ((99  '?c))&)F7O*01*=a*@F7Q;''MM'3///qLGAIDqLG! nnnnnnr[   Fc                   d}g }|                      |||           t          | j                  D ]\  }}}d|v r|                     |           t	          |          }d}	|	|k     rl||	         }
t          |
t                    rB|
|v r=||
         }t          |t                    r|g}d}ng }d}|
dv r5|| j        k    r*|	dk    r$|                     ||	dz
                     s|	dz  }	|| j	        k    rQ|	dk    sE|	|dz
  k    s<|                     ||	dz
                     s|                     ||	dz                      r|	dz  }	d}|||	<   || j	        k    r|
                    |	dz
            }|
                    |	          }|
dk    r|                     |          }n|
dk    r|                     |          }|	dz  }	|d	z  }|                    |           |}|| j        k    r|	d	z   |k     r|                     ||	dz            |
          r|                    |           |
                    |	dz             }|
                    |	dz             }|dk    r|                     |          }n|dk    r|                     |          }|d	z  }|	d	z   |k     r|                     ||	dz            |
          |                    |           n~|| j        k    r|	d	z   |k     r{||	dz            |
k    rl|                    ||g           |d
         }|
                    |	dz              |
                    |	dz             }|d	z  }|	d	z   |k     r||	dz            |
k    l|                    |           n|| j        k    r|	dz   |k     r||	dz            |
k    rt          |t                    r|||         |g||<   n |||         |          ||<   |
                    |	dz              |
                    |	dz             }|d	z  }|	dz   |k     r||	dz            |
k    |                    |           n|                    |           n|| j        k    ru|J |	|dz
  k    s|                     ||	dz                      r | j        |
                     ||	<   n|                    |
                    |	dz                        |dz  }n|| j        k    rv|J |	dk    s|                     ||	dz
                     r | j        |
                     ||	<   n5|                    |
                    |	dz
                       |	dz  }	|dz  }t          |t(                    rct+          j        t(          |          } || }|                                 t          |t0                    r|                    |           n|||	<   |	dz  }	|	|k     lt	          |          dk    s&t	          |          dk    r:t	          |          dk    r'|r|                     ||          S t7          d          t	          |          dk    r3|d         r"|d         d         dk    r|d         dd          }dg||}|S |d         S )NFr   r   r`   r$  Tr(  r&  rn   r   z0unable to create a single AST for the expressionr   )r  reversedrR  r  ro   rr   rX  PREFIXr  INFIXr   r]  r,  r   FLAT_check_op_compatibleRIGHTLEFT_missing_arguments_defaultPOSTFIXr   typingcastclearr  rf  r  ru   )r   ri  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  sc   ""5&2BCCC089X0Y0Y ]	 ]	,G^Wg~~00888FDGD..weS)) U7ew.>.>.5enG "'3// ( 'y&'!&'
**w$+/E/E'TU++^b^i^ijpqx{|q|j}^~^~+  1 $*,,"a<<7dQh+>+>$++fU\_`U`NaBbBb+>fjfqfqrx  zA  DE  zE  sF  gG  gG+>#qLG$"G&*F7O$*,,%zz'!)44%zz'22 C<<#'==#6#6DD"c\\#'==#6#6D1	D)))!%)TY66")A+"4"49R9RSYZabcZcSdfk9l9l"4 &d 3 3 3+1::gai+@+@'-zz'!)'<'<#+s??+/==+>+>DD%-__+/==+>+>D $	 #*A+"4"49R9RSYZabcZcSdfk9l9l"4 #MM$////+tz99")A+"4"4	9Je9S9S &wo > > >)/ &

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

719 5 5 5'-zz'!)'<'< $	 #*A+"4"4	9Je9S9S #MM$//// KK---- DK//-555"dQh..$++fWq[>Q2R2R..Td.Me.T.V.VF7OO KK

719(=(=>>> AIDD DL00-555"a<<4;;vgk7J+K+K<.Td.Me.T.V.VF7OO KK

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

%h55 7 KK1111.6F7O1q D..r v;;??s5zzQ3v;;!3C3C J //8HIIIPQQQu::>>ay 'VAYq\-AAA122#7"I%"I&"I&&ayr[   op1op2c                N    ||k    rdS ddh}ddh}||v r||v rdS ||v r||v rdS dS )NTr   r(  r%  r&  Frj   )r   r  r  muldivaddsubs        rY   r  z&MathematicaParser._check_op_compatible  sS    #::4ss&==SF]]4&==SF]]4ur[   wmexprc                   g }|g}t          j        d|          }d}|D ]e}| n_|                                }|||                             dd                              dd                              dd                                          }|                                dk    r"|dk    r|d                             |           n|                                dk    r6|dk    r|d                             |           |                                 nU|                                dk    r=|d                             |g           |                    |d         d                    |                                }g|d         S )	zH
        Parses FullForm[Downvalues[]] generated by Mathematica
        z[\[\],]r   Nr   r   r   r   r   )	r   finditerr   r   stripr   r   r   r   )	r   r  outr  	generatorlast_posrY  position	last_exprs	            rY   _from_fullform_to_fullformlistz0MathematicaParser._from_fullform_to_fullformlist  sq    K
F33	 	# 	#E}{{}}Hx0199#rBBJJ3PRSS[[\_acddjjllI{{}}##??"I$$Y///#%%??"I$$Y///		#%%b	  )---U2Yr]+++yy{{HH1vr[   pylistc                <    ddl mm fd |          S )Nr   )r=   Symbolc                (   t          | t                    rNt          |           dk    r,| d         }fd| dd          D             }  |          | S t          d          t          | t                    r |           S t          |           S )Nr   c                &    g | ]} |          S rj   rj   )rd   rv   	converters     rY   rf   z\MathematicaParser._from_fullformlist_to_fullformsympy.<locals>.converter.<locals>.<listcomp>  s!    ???sIIcNN???r[   r`   zEmpty list of expressions)rr   r  ro   r   rX  rM   )exprheadrc   r=   r  r  s      rY   r  zHMathematicaParser._from_fullformlist_to_fullformsympy.<locals>.converter  s    $%% 
&t99q==7D????d122h???D)88D>>400$%@AAAD#&& &vd||#~~%r[   )sympyr=   r  )r   r  r=   r  r  s     @@@rY   #_from_fullformlist_to_fullformsympyz5MathematicaParser._from_fullformlist_to_fullformsympy  sR    ********	& 	& 	& 	& 	& 	& 	& y   r[   Logc                 .    t          t          |            S r~   )r
   r  re   s    rY   r  zMathematicaParser.<lambda>  s    #x{{+ r[   Log2c                "    t          | d          S Nrn   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                 f    t          |           dk    rt          t          |            nt          |  S r  )ro   r)   r  r(   r  s    rY   r  zMathematicaParser.<lambda>  s(    CFFaKKUHQKK00T1X 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 r~   )r'   Zeror  s    rY   r  zMathematicaParser.<lambda>  s    16 r[   r*   r+   r,   
PochhammerExpIntegralEiSinIntegralCosIntegralAiryAiAiryAiPrimeAiryBiAiryBiPrimeLogIntegralPrimePiPrimePrimeQr3  )r>   r   c                (      fd |          S )Nc                r   t          | t                    rzt          | d         t                    r | d                   }n4j                            | d         t	          | d                             } |fd| dd          D              S j                            | t          |                     S )Nr   c                &    g | ]} |          S rj   rj   )rd   rv   recurses     rY   rf   zRMathematicaParser._from_fullformlist_to_sympy.<locals>.recurse.<locals>.<listcomp>-  s!    ???sggcll???r[   r`   )rr   r  _node_conversionsgetr=   _atom_conversionsrL   )r  r  r  r   s     rY   r  z>MathematicaParser._from_fullformlist_to_sympy.<locals>.recurse'  s    $%% Gd1gt,, R"747++DD155d1gxQ?P?PQQDt????d122h???@@-11$FFFr[   rj   )r   full_form_listr  s   ` @rY   r   z-MathematicaParser._from_fullformlist_to_sympy%  s:    	G 	G 	G 	G 	G 	G w~&&&r[   c                    |}| j                                         D ](\  }}|                    t          |          |          })|S r~   )r  r   r   r=   )r   mformr  mma_form
sympy_nodes        rY   _from_fullformsympy_to_sympyz.MathematicaParser._from_fullformsympy_to_sympy3  sN    $($:$@$@$B$B 	@ 	@ Hj<< 2 2J??DDr[   r~   )rp  rX  )r  r  r  r  )ri  r  )r  r  ri  r  r  r  )F)ri  r  r  r  )r  rX  r  rX  )r  rX  )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   rU   r]   r  r  r  r  r  r  rR  r  rb  rZ  rc  rd  r,  r]  ra  ro  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   r|   r  r>   r?   r  r   r  rj   r[   rY   rT   rT   n   s,         (9( 	( 	J	
 	: 	K 	J 	9 	9 	) 	l 	G 	' 	' 	[  	*!" 	[#$ +!"!-  O4 w{ -67@B B ) )S!3Y]U" 	)syy{{"Q&.BBq5(BBx(((( 	 L BJ  Z	! !
  BJ  Z	! !
  BJ  Z	! !
  BJ  Z! ! ;& &ER   Z! !J "rz #Z! !
 ;=L<<<< =?N>>>> =?N>>>># # [#
@ @ @ @0 = = [=~% % %N@ @ @D # # [#J   [
   [ " " ["  :   EFGDED 
$  Z  Z  [  	\	s012	U,g^clt~  	A	t0012	$j)*	t\*+	fM::;	t[)*	sN+,	$z.AAB	tTl#	tUm$	U|$	gi889	WI[v]kr{||}	tVn%	F001	G'223	sEl#	DD([* * 	+	W~&	gU8LwLwxxy	$lLXcdde	008T8TUUV	33..IIJ	sM*+	$44CC==BB	
 
 	 
sEEFG	V>::;G$[ $ $ $ $N #"++" "
 'H1G+++O,,,p p [p " " [" % % %"- - - -^   & & & &
& & & &
42 42 42 42l! ! ! !F   *u u u u 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M'P 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 PP 	ehQ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 P 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 Pf  
' ' '    r[   rT   r~   )\
__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^   r|   r   rT   rj   r[   rY   <module>r.     s   " " " " " " 				                        A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A A
 1 0 0 0 0 0 0 0 6 6 6 6 6 6 6 6 6 6 6 6 @ @ @ @ @ @
) 
) 
) 
)3 3 3lD D D&  
 I I I I I I I I I Ir[   