o
     ôjÍ.  ã                   @  sî   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/d0„ d0e
ƒZd6d2d3„Zd4d5„ Zd1S )7zÅ
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                   @  sà   e Zd ZU dZdZdZeejfi di ddœ¤ŽZde	d< i fd	d
„Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1S )2ÚJavascriptCodePrinterzK"A Printer to convert Python expressions to strings of JavaScript code
    Z_javascriptZ
JavaScripté   T)Ú	precisionÚuser_functionsÚcontractzdict[str, Any]Ú_default_settingsc                 C  s2   t  | |¡ ttƒ| _| di ¡}| j |¡ d S )Nr!   )r   Ú__init__ÚdictÚknown_functionsÚgetÚupdate)ÚselfÚsettingsÚ	userfuncs© r,   úh/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/sympy/printing/jscode.pyr$   :   s   
zJavascriptCodePrinter.__init__c                 C  s   |d S )Né   r,   )r)   Úpr,   r,   r-   Ú_rate_index_position@   ó   z*JavascriptCodePrinter._rate_index_positionc                 C  s   d| S )Nz%s;r,   )r)   Ú
codestringr,   r,   r-   Ú_get_statementC   r1   z$JavascriptCodePrinter._get_statementc                 C  s
   d  |¡S )Nz// {})Úformat)r)   Útextr,   r,   r-   Ú_get_commentF   ó   
z"JavascriptCodePrinter._get_commentc                 C  s   d  || | jd ¡¡S )Nzvar {} = {};r    )r4   ÚevalfÚ	_settings)r)   ÚnameÚvaluer,   r,   r-   Ú_declare_number_constI   s   z+JavascriptCodePrinter._declare_number_constc                 C  s
   |   |¡S ©N)Úindent_code)r)   Úlinesr,   r,   r-   Ú_format_codeL   r7   z"JavascriptCodePrinter._format_codec                   s    |j \}‰ ‡ fdd„t|ƒD ƒS )Nc                 3  s&   � | ]}t ˆ ƒD ]}||fV  qqd S r=   )Úrange)Ú.0ÚiÚj©Úcolsr,   r-   Ú	<genexpr>Q   s   €$ zAJavascriptCodePrinter._traverse_matrix_indices.<locals>.<genexpr>)ÚshaperA   )r)   ÚmatÚrowsr,   rE   r-   Ú_traverse_matrix_indicesO   s   
z.JavascriptCodePrinter._traverse_matrix_indicesc              
   C  sZ   g }g }d}|D ] }|  ||  |j¡|  |j¡|  |jd ¡dœ ¡ |  d¡ q||fS )NzAfor (var %(varble)s=%(start)s; %(varble)s<%(end)s; %(varble)s++){é   )ÚvarbleÚstartÚendÚ})ÚappendÚ_printÚlabelÚlowerÚupper)r)   ÚindicesÚ
open_linesÚclose_linesÚ	loopstartrC   r,   r,   r-   Ú_get_loop_opening_endingS   s   


ýz.JavascriptCodePrinter._get_loop_opening_endingc                 C  s~   t |ƒ}t|jdƒrd|  |j|¡ S t|jdƒr!d|  |j¡ S |jtjd kr1d|  |j¡ S d|  |j¡|  |j¡f S )Néÿÿÿÿz1/%sg      à?zMath.sqrt(%s)é   zMath.cbrt(%s)zMath.pow(%s, %s))r   r   r   ÚparenthesizeÚbaserR   r   ÚOne)r)   ÚexprÚPRECr,   r,   r-   Ú
_print_Pow`   s   
ÿz JavascriptCodePrinter._print_Powc                 C  s"   t |jƒt |jƒ}}d||f S )Nz%d/%d)Úintr/   Úq)r)   r`   r/   rd   r,   r,   r-   Ú_print_Rationall   s   z%JavascriptCodePrinter._print_Rationalc                   sn   |j \}}t|ƒ‰ ‡ ‡fdd„|j D ƒ\}}|jr|js"|jr)|jr)|› d|› �S d|› d|› d|› d|› �S )Nc                   s   g | ]}ˆ  |ˆ ¡‘qS r,   )r]   )rB   Úarg©ra   r)   r,   r-   Ú
<listcomp>s   s    z4JavascriptCodePrinter._print_Mod.<locals>.<listcomp>z % z((z) + z) % )Úargsr   Úis_nonnegativeÚis_nonpositive)r)   r`   ÚnumÚdenZsnumZsdenr,   rg   r-   Ú
_print_Modp   s   
ÿÿz JavascriptCodePrinter._print_Modc                 C  s,   |   |j¡}|   |j¡}|j}d |||¡S )Nz{} {} {})rR   ÚlhsÚrhsÚrel_opr4   )r)   r`   Úlhs_codeÚrhs_codeÚopr,   r,   r-   Ú_print_Relational|   s   z'JavascriptCodePrinter._print_Relationalc                 C  s`   |j }tj}tj}tt|jƒƒD ]}||j| | 7 }||| 9 }qd|  |j	j
¡|  |¡f S )Nz%s[%s])rH   r   ÚZeror_   ÚreversedrA   ÚrankrV   rR   r^   rS   )r)   r`   ÚdimsÚelemÚoffsetrC   r,   r,   r-   Ú_print_Indexed‚   s   z$JavascriptCodePrinter._print_Indexedc                 C  ó   dS )NzMath.Er,   ©r)   r`   r,   r,   r-   Ú_print_Exp1Œ   ó   z!JavascriptCodePrinter._print_Exp1c                 C  r}   )NzMath.PIr,   r~   r,   r,   r-   Ú	_print_Pi�   r€   zJavascriptCodePrinter._print_Pic                 C  r}   )NzNumber.POSITIVE_INFINITYr,   r~   r,   r,   r-   Ú_print_Infinity’   r€   z%JavascriptCodePrinter._print_Infinityc                 C  r}   )NzNumber.NEGATIVE_INFINITYr,   r~   r,   r,   r-   Ú_print_NegativeInfinity•   r€   z-JavascriptCodePrinter._print_NegativeInfinityc           
        s  ddl m} |jd jdkrtdƒ‚g }| |¡ret|jƒD ]A\}\}}|dkr3| dˆ  |¡ ¡ n|t	|jƒd krF|dkrF| d¡ n
| d	ˆ  |¡ ¡ ˆ  |¡}| |¡ | d
¡ qd 
|¡S ‡ fdd„|jd d… D ƒ}dˆ  |jd j¡ }	d 
|¡|	 d 
dt	|ƒ g¡ S )Nr   )Ú
Assignmentr[   Tz¼All 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) {rL   zelse {zelse if (%s) {rP   Ú
c                   s(   g | ]\}}d ˆ   |¡ˆ   |¡f ‘qS )z((%s) ? (
%s
)
)rR   )rB   ÚeÚc©r)   r,   r-   rh   ´   s    ÿz:JavascriptCodePrinter._print_Piecewise.<locals>.<listcomp>z: (
%s
)z: ú ú))Úsympy.codegen.astr„   ri   ÚcondÚ
ValueErrorÚhasÚ	enumeraterQ   rR   ÚlenÚjoinr`   )
r)   r`   r„   r?   rC   r†   r‡   Úcode0ÚecpairsÚ	last_liner,   rˆ   r-   Ú_print_Piecewise˜   s(   




ÿ"z&JavascriptCodePrinter._print_Piecewisec                 C  s2   d  | j|jtd dd�|j|j|jjd   ¡S )Nz{}[{}]ÚAtomT)ÚstrictrL   )r4   r]   Úparentr   rD   rC   rH   r~   r,   r,   r-   Ú_print_MatrixElement¹   s
   ÿþz*JavascriptCodePrinter._print_MatrixElementc           
        sÂ   t |tƒr|  | d¡¡}d |¡S d}d‰d‰ dd„ |D ƒ}‡fdd„|D ƒ}‡ fd	d„|D ƒ}g }d
}t|ƒD ]%\}}	|	dv rG| |	¡ q9||| 8 }| d|| |	f ¡ ||| 7 }q9|S )z0Accepts a string of code or a list of code linesTÚ z   )Ú{ú(z{
z(
)rP   rŠ   c                 S  s   g | ]}|  d ¡‘qS )z 	)Úlstrip©rB   Úliner,   r,   r-   rh   É   s    z5JavascriptCodePrinter.indent_code.<locals>.<listcomp>c                   ó    g | ]}t tt|jˆ ƒƒƒ‘qS r,   )rc   ÚanyÚmapÚendswithrž   )Ú	inc_tokenr,   r-   rh   Ë   s     c                   r    r,   )rc   r¡   r¢   Ú
startswithrž   )Ú	dec_tokenr,   r-   rh   Ì   s    ÿr   )rš   r…   z%s%s)Ú
isinstanceÚstrr>   Ú
splitlinesr‘   r�   rQ   )
r)   ÚcodeÚ
code_linesÚtabÚincreaseÚdecreaseÚprettyÚlevelÚnrŸ   r,   )r¦   r¤   r-   r>   ¾   s*   


ÿ
z!JavascriptCodePrinter.indent_codeN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚprintmethodÚlanguager%   r   r#   Ú__annotations__r$   r0   r3   r6   r<   r@   rK   rZ   rb   re   rn   ru   r|   r   r�   r‚   rƒ   r•   r™   r>   r,   r,   r,   r-   r   .   s:   
 
ý
!r   Nc                 K  s   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)r`   Ú	assign_tor*   r,   r,   r-   ÚjscodeÛ   s   ir»   c                 K  s   t t| fi |¤Žƒ dS )z€Prints the Javascript representation of the given expression.

       See jscode for the meaning of the optional arguments.
    N)Úprintr»   )r`   r*   r,   r,   r-   Úprint_jscodeG  s   r½   r=   )rµ   Ú
__future__r   Útypingr   Ú
sympy.corer   Úsympy.core.numbersr   Zsympy.printing.codeprinterr   Úsympy.printing.precedencer   r   r&   r   r»   r½   r,   r,   r,   r-   Ú<module>   sf    	ÿþýüûúùø	÷
öõôóòñðïë 
.l