
    Riec/                        d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZm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.Z G d/ d0e
          Zd4d2Zd3 Zd1S )5z
Javascript code printer

The JavascriptCodePrinter converts single SymPy expressions into single
Javascript expressions, using the functions defined in the Javascript
Math object where possible.

    )annotations)Any)S)equal_valued)CodePrinter)
precedence
PRECEDENCEAbszMath.absacosz	Math.acosacoshz
Math.acoshasinz	Math.asinasinhz
Math.asinhatanz	Math.atanatan2z
Math.atan2atanhz
Math.atanhceilingz	Math.ceilcoszMath.coscoshz	Math.coshexpzMath.expfloorz
Math.floorlogzMath.logMaxzMath.maxMinzMath.minsignz	Math.signzMath.sinz	Math.sinhzMath.tanz	Math.tanh)sinsinhtantanhc                      e Zd ZU dZdZdZdddi dddd	Zd
ed<   i fdZd Z	d Z
d Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd  ZdS )!JavascriptCodePrinterzK"A Printer to convert Python expressions to strings of JavaScript code
    _javascript
JavaScriptNauto   TF)order	full_prec	precisionuser_functionshumanallow_unknown_functionscontractzdict[str, Any]_default_settingsc                    t          j        | |           t          t                    | _        |                    di           }| j                            |           d S )Nr(   )r   __init__dictknown_functionsgetupdate)selfsettings	userfuncss      5lib/python3.11/site-packages/sympy/printing/jscode.pyr.   zJavascriptCodePrinter.__init__>   sV    T8,,,#O44LL!1266	##I.....    c                    |dz  S )N    )r3   ps     r6   _rate_index_positionz*JavascriptCodePrinter._rate_index_positionD   s    s
r7   c                    d|z  S )Nz%s;r:   )r3   
codestrings     r6   _get_statementz$JavascriptCodePrinter._get_statementG   s    z!!r7   c                ,    d                     |          S )Nz// {})format)r3   texts     r6   _get_commentz"JavascriptCodePrinter._get_commentJ   s    ~~d###r7   c                j    d                     ||                    | j        d                             S )Nzvar {} = {};r'   )rA   evalf	_settings)r3   namevalues      r6   _declare_number_constz+JavascriptCodePrinter._declare_number_constM   s+    $$T5;;t~k7R+S+STTTr7   c                ,    |                      |          S N)indent_code)r3   liness     r6   _format_codez"JavascriptCodePrinter._format_codeP   s    &&&r7   c                N    |j         \  }fdt          |          D             S )Nc              3  D   K   | ]}t                    D ]}||fV  	d S rK   )range).0ijcolss      r6   	<genexpr>zAJavascriptCodePrinter._traverse_matrix_indices.<locals>.<genexpr>U   s:      AA1U4[[AAAAAAAAAAr7   )shaperQ   )r3   matrowsrU   s      @r6   _traverse_matrix_indicesz.JavascriptCodePrinter._traverse_matrix_indicesS   s.    Y
dAAAAdAAAAr7   c           
        g }g }d}|D ]~}|                     ||                     |j                  |                     |j                  |                     |j        dz             dz             |                     d           ||fS )NzAfor (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){   )varblestartend})append_printlabellowerupper)r3   indices
open_linesclose_lines	loopstartrS   s         r6   _get_loop_opening_endingz.JavascriptCodePrinter._get_loop_opening_endingW   s    
W	 	$ 	$Ai++ag..QW--{{17Q;//+1 +1 1 2 2 2 s####;&&r7   c                   t          |          }t          |j        d          rd|                     |j        |          z  S t          |j        d          rd|                     |j                  z  S |j        t          j        dz  k    rd|                     |j                  z  S d|                     |j                  d|                     |j                  d	S )
Nz1/%sg      ?zMath.sqrt(%s)   zMath.cbrt(%s)z	Math.pow(z, ))r   r   r   parenthesizebaserb   r   One)r3   exprPRECs      r6   
_print_Powz JavascriptCodePrinter._print_Powd   s    $"%% 	8T..ty$??@@$(C(( 	8"T[[%;%;;;Xq  "T[[%;%;;; ! *.TY)?)?)?)?!%TX!6!6!6!68 8r7   c                `    t          |j                  t          |j                  }}d||fz  S )Nz%d/%d)intr;   q)r3   rr   r;   rw   s       r6   _print_Rationalz%JavascriptCodePrinter._print_Rationalp   s*    46{{CKK1!Qr7   c                     |j         \  }}t          |           fd|j         D             \  }}|j        r|j        s|j        r|j        r| d| S d| d| d| d| S )Nc                <    g | ]}                     |          S r:   )ro   )rR   argrs   r3   s     r6   
<listcomp>z4JavascriptCodePrinter._print_Mod.<locals>.<listcomp>w   s)    HHHsd''T22HHHr7   z % ((z) + z) % )argsr   is_nonnegativeis_nonpositive)r3   rr   numdensnumsdenrs   s   `     @r6   
_print_Modz JavascriptCodePrinter._print_Modt   s    9S$HHHHHdiHHH
d  	&3#5 	&	&#&#5	&%%t%%%7D77T77t77777r7   c                    |                      |j                  }|                      |j                  }|j        }d                    |||          S )Nz{} {} {})rb   lhsrhsrel_oprA   )r3   rr   lhs_coderhs_codeops        r6   _print_Relationalz'JavascriptCodePrinter._print_Relational   sG    ;;tx((;;tx(([  2x888r7   c                4   |j         }t          j        }t          j        }t	          t          |j                            D ] }||j        |         |z  z  }|||         z  }!|                     |j	        j
                  d|                     |          dS )N[])rW   r   Zerorq   reversedrQ   rankrf   rb   rp   rc   )r3   rr   dimselemoffsetrS   s         r6   _print_Indexedz$JavascriptCodePrinter._print_Indexed   s    zv%	**++ 	 	ADLOF**Dd1gFF;;ty7777T9J9J9J9JKKr7   c                6    |                      |j                  S rK   )rb   rc   r3   rr   s     r6   
_print_Idxz JavascriptCodePrinter._print_Idx   s    {{4:&&&r7   c                    dS )NzMath.Er:   r   s     r6   _print_Exp1z!JavascriptCodePrinter._print_Exp1   s    xr7   c                    dS )NzMath.PIr:   r   s     r6   	_print_PizJavascriptCodePrinter._print_Pi   s    yr7   c                    dS )NzNumber.POSITIVE_INFINITYr:   r   s     r6   _print_Infinityz%JavascriptCodePrinter._print_Infinity       ))r7   c                    dS )NzNumber.NEGATIVE_INFINITYr:   r   s     r6   _print_NegativeInfinityz-JavascriptCodePrinter._print_NegativeInfinity   r   r7   c                    ddl m} |j        d         j        dk    rt	          d          g }|                    |          rt          |j                  D ]\  }\  }}|dk    r,|                    d                     |          z             nb|t          |j                  dz
  k    r|dk    r|                    d           n+|                    d	                     |          z                                  |          }|                    |           |                    d
           d
                    |          S  fd|j        d d         D             }d                     |j        d         j                  z  }	d
                    |          |	z   d
                    dt          |          z  g          z   S )Nr   )
Assignmentrl   TzAll Piecewise expressions must contain an (expr, True) statement to be used as a default condition. Without one, the generated expression may not evaluate to anything under some condition.z	if (%s) {r\   zelse {zelse if (%s) {r`   
c                t    g | ]4\  }}d                      |          d                     |          d5S )r}   z) ? (
z
)
)rb   )rR   ecr3   s      r6   r|   z:JavascriptCodePrinter._print_Piecewise.<locals>.<listcomp>   sP     0 0 011 04{{1~~~~t{{1~~~~N 0 0 0r7   z: (
%s
)z:  rn   )sympy.codegen.astr   r~   cond
ValueErrorhas	enumeratera   rb   lenjoinrr   )
r3   rr   r   rM   rS   r   r   code0ecpairs	last_lines
   `         r6   _print_Piecewisez&JavascriptCodePrinter._print_Piecewise   s   0000009R=%%  / 0 0 0
 88J 	Q&ty11 	" 	"	6Aq66LLt{{1~~!=>>>>#di..1,,,dLL****LL!1DKKNN!BCCCAU###S!!!!99U###0 0 0 0 $	#2#0 0 0G$t{{49R=3E'F'FFI99W%%	1CHHc#g,,>N=O4P4PPPr7   c                    d                     |                     |j        t          d         d          |j        |j        |j        j        d         z  z             S )Nz{}[{}]AtomT)strictr\   )rA   ro   parentr	   rT   rS   rW   r   s     r6   _print_MatrixElementz*JavascriptCodePrinter._print_MatrixElement   sX    t00vt  1  -  -FTVDK-a0002 2 	2r7   c                  
 t          |t                    r=|                     |                    d                    }d                    |          S d}dd
d |D             }fd|D             }
fd|D             }g }d	}t          |          D ]Q\  }}	|	d
v r|                    |	           |||         z  }|                    ||z  |	           |||         z  }R|S )z0Accepts a string of code or a list of code linesT z   ){(z{
z(
)r`   rn   c                8    g | ]}|                     d           S )z 	)lstrip)rR   lines     r6   r|   z5JavascriptCodePrinter.indent_code.<locals>.<listcomp>   s$    666U##666r7   c           
     n    g | ]1}t          t          t          |j                                      2S r:   )rv   anymapendswith)rR   r   	inc_tokens     r6   r|   z5JavascriptCodePrinter.indent_code.<locals>.<listcomp>   s5    OOOSS	::;;<<OOOr7   c           
     n    g | ]1}t          t          t          |j                                      2S r:   )rv   r   r   
startswith)rR   r   	dec_tokens     r6   r|   z5JavascriptCodePrinter.indent_code.<locals>.<listcomp>   sE     ( ( ( S)<<==>> ( ( (r7   r   )r   r   )
isinstancestrrL   
splitlinesr   r   ra   )r3   code
code_linestabincreasedecreaseprettylevelnr   r   r   s             @@r6   rL   z!JavascriptCodePrinter.indent_code   s3    dC   	'))$//$*?*?@@J77:&&&,		66666OOOOOOO( ( ( (!%( ( (   	! 	!GAtz!!d###Xa[ EMMCIItt4555Xa[ EEr7   )__name__
__module____qualname____doc__printmethodlanguager,   __annotations__r.   r<   r?   rC   rI   rN   rZ   rj   rt   rx   r   r   r   r   r   r   r   r   r   r   rL   r:   r7   r6   r    r    .   s         KH #() )     !# / / / /  " " "$ $ $U U U' ' 'B B B' ' '
8 
8 
8     
8 
8 
89 9 9L L L' ' '    * * ** * *Q Q QB2 2 2
    r7   r    Nc                H    t          |                              | |          S )a  Converts an expr to a string of javascript code

    Parameters
    ==========

    expr : Expr
        A SymPy expression to be converted.
    assign_to : optional
        When given, the argument is used as the name of the variable to which
        the expression is assigned. Can be a string, ``Symbol``,
        ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
        line-wrapping, or for expressions that generate multi-line statements.
    precision : integer, optional
        The precision for numbers such as pi [default=15].
    user_functions : dict, optional
        A dictionary where keys are ``FunctionClass`` instances and values are
        their string representations. Alternatively, the dictionary value can
        be a list of tuples i.e. [(argument_test, js_function_string)]. See
        below for examples.
    human : bool, optional
        If True, the result is a single string that may contain some constant
        declarations for the number symbols. If False, the same information is
        returned in a tuple of (symbols_to_declare, not_supported_functions,
        code_text). [default=True].
    contract: bool, optional
        If True, ``Indexed`` instances are assumed to obey tensor contraction
        rules and the corresponding nested loops over indices are generated.
        Setting contract=False will not generate loops, instead the user is
        responsible to provide values for the indices in the code.
        [default=True].

    Examples
    ========

    >>> from sympy import jscode, symbols, Rational, sin, ceiling, Abs
    >>> x, tau = symbols("x, tau")
    >>> jscode((2*tau)**Rational(7, 2))
    '8*Math.sqrt(2)*Math.pow(tau, 7/2)'
    >>> jscode(sin(x), assign_to="s")
    's = Math.sin(x);'

    Custom printing can be defined for certain types by passing a dictionary of
    "type" : "function" to the ``user_functions`` kwarg. Alternatively, the
    dictionary value can be a list of tuples i.e. [(argument_test,
    js_function_string)].

    >>> custom_functions = {
    ...   "ceiling": "CEIL",
    ...   "Abs": [(lambda x: not x.is_integer, "fabs"),
    ...           (lambda x: x.is_integer, "ABS")]
    ... }
    >>> jscode(Abs(x) + ceiling(x), user_functions=custom_functions)
    'fabs(x) + CEIL(x)'

    ``Piecewise`` expressions are converted into conditionals. If an
    ``assign_to`` variable is provided an if statement is created, otherwise
    the ternary operator is used. Note that if the ``Piecewise`` lacks a
    default term, represented by ``(expr, True)`` then an error will be thrown.
    This is to prevent generating an expression that may not evaluate to
    anything.

    >>> from sympy import Piecewise
    >>> expr = Piecewise((x + 1, x > 0), (x, True))
    >>> print(jscode(expr, tau))
    if (x > 0) {
       tau = x + 1;
    }
    else {
       tau = x;
    }

    Support for loops is provided through ``Indexed`` types. With
    ``contract=True`` these expressions will be turned into loops, whereas
    ``contract=False`` will just print the assignment expression that should be
    looped over:

    >>> from sympy import Eq, IndexedBase, Idx
    >>> len_y = 5
    >>> y = IndexedBase('y', shape=(len_y,))
    >>> t = IndexedBase('t', shape=(len_y,))
    >>> Dy = IndexedBase('Dy', shape=(len_y-1,))
    >>> i = Idx('i', len_y-1)
    >>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
    >>> jscode(e.rhs, assign_to=e.lhs, contract=False)
    'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

    Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
    must be provided to ``assign_to``. Note that any expression that can be
    generated normally can also exist inside a Matrix:

    >>> from sympy import Matrix, MatrixSymbol
    >>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
    >>> A = MatrixSymbol('A', 3, 1)
    >>> print(jscode(mat, A))
    A[0] = Math.pow(x, 2);
    if (x > 0) {
       A[1] = x + 1;
    }
    else {
       A[1] = x;
    }
    A[2] = Math.sin(x);
    )r    doprint)rr   	assign_tor4   s      r6   jscoder      s#    R !**224CCCr7   c                :    t          t          | fi |           dS )zPrints the Javascript representation of the given expression.

       See jscode for the meaning of the optional arguments.
    N)printr   )rr   r4   s     r6   print_jscoder   N  s(    
 
&
"
"
"
"#####r7   rK   )r   
__future__r   typingr   
sympy.corer   sympy.core.numbersr   sympy.printing.codeprinterr   sympy.printing.precedencer   r	   r0   r    r   r   r:   r7   r6   <module>r      s    # " " " " "             + + + + + + 2 2 2 2 2 2 < < < < < < < <
	:
K \ K	
 \ K \ \ { 
: K 
: \ 
: 
:  
:!" K#$ +  2q q q q qK q q qhiD iD iD iDX$ $ $ $ $r7   