
    wg/                        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y1)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 eej                  fi di 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y)JavascriptCodePrinterzK"A Printer to convert Python expressions to strings of JavaScript code
    _javascript
JavaScript   T)	precisionuser_functionscontractzdict[str, Any]_default_settingsc                    t        j                  | |       t        t              | _        |j	                  di       }| j                  j                  |       y )Nr%   )r   __init__dictknown_functionsgetupdate)selfsettings	userfuncss      Z/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/printing/jscode.pyr)   zJavascriptCodePrinter.__init__:   sD    T8,#O4LL!126	##I.    c                    |dz  S )N    )r.   ps     r1   _rate_index_positionz*JavascriptCodePrinter._rate_index_position@   s    s
r2   c                    d|z  S )Nz%s;r5   )r.   
codestrings     r1   _get_statementz$JavascriptCodePrinter._get_statementC   s    z!!r2   c                $    dj                  |      S )Nz// {})format)r.   texts     r1   _get_commentz"JavascriptCodePrinter._get_commentF   s    ~~d##r2   c                ^    dj                  ||j                  | j                  d               S )Nzvar {} = {};r$   )r<   evalf	_settings)r.   namevalues      r1   _declare_number_constz+JavascriptCodePrinter._declare_number_constI   s'    $$T5;;t~~k7R+STTr2   c                $    | j                  |      S N)indent_code)r.   liness     r1   _format_codez"JavascriptCodePrinter._format_codeL   s    &&r2   c                J    |j                   \  }fdt        |      D        S )Nc              3  F   K   | ]  }t              D ]  }||f 
  y wrF   )range).0ijcolss      r1   	<genexpr>zAJavascriptCodePrinter._traverse_matrix_indices.<locals>.<genexpr>Q   s%     A1U4[AAAAs   !)shaperL   )r.   matrowsrP   s      @r1   _traverse_matrix_indicesz.JavascriptCodePrinter._traverse_matrix_indicesO   s    YY
dAdAAr2   c           
        g }g }d}|D ]y  }|j                  || j                  |j                        | j                  |j                        | j                  |j                  dz         dz         |j                  d       { ||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	loopstartrN   s         r1   _get_loop_opening_endingz.JavascriptCodePrinter._get_loop_opening_endingS   s    
W	 	$Ai++agg.QWW-{{177Q;/+1 1 2 s#	$ ;&&r2   c                   t        |      }t        |j                  d      rd| j                  |j                  |      z  S t        |j                  d      rd| j                  |j                        z  S |j                  t        j                  dz  k(  rd| j                  |j                        z  S d| j                  |j                        d| j                  |j                        d	S )
Nz1/%sg      ?zMath.sqrt(%s)   zMath.cbrt(%s)z	Math.pow(z, ))r   r   r   parenthesizebaser]   r   One)r.   exprPRECs      r1   
_print_Powz JavascriptCodePrinter._print_Pow`   s    $"%T..tyy$?@@$((C("T[[%;;;XXq "T[[%;;; ! *.TYY)?!%TXX!68 8r2   c                d    t        |j                        t        |j                        }}d||fz  S )Nz%d/%d)intr6   q)r.   rm   r6   rr   s       r1   _print_Rationalz%JavascriptCodePrinter._print_Rationall   s*    466{CK1!Qr2   c                $   |j                   \  }}t        |      }|j                   D cg c]  }| j                  ||       c}\  }}|j                  r|j                  s|j                  r|j                  r| d| S d| d| d| d| S c c}w )Nz % ((z) + z) % )argsr   rj   is_nonnegativeis_nonpositive)r.   rm   numdenrn   argsnumsdens           r1   
_print_Modz JavascriptCodePrinter._print_Modp   s    99S$>BiiHsd''T2H
d 3#5#53#5#5V3tf%%D6TF$tfD77 Is   Bc                    | j                  |j                        }| j                  |j                        }|j                  }dj	                  |||      S )Nz{} {} {})r]   lhsrhsrel_opr<   )r.   rm   lhs_coderhs_codeops        r1   _print_Relationalz'JavascriptCodePrinter._print_Relational|   sD    ;;txx(;;txx([[  2x88r2   c                N   |j                   }t        j                  }t        j                  }t	        t        |j                              D ]  }||j                  |   |z  z  }|||   z  }! | j                  |j                  j                        d| j                  |      dS )N[])rR   r   Zerorl   reversedrL   rankra   r]   rk   r^   )r.   rm   dimselemoffsetrN   s         r1   _print_Indexedz$JavascriptCodePrinter._print_Indexed   s    zzvv%		*+ 	ADLLOF**Dd1gF	  ;;tyy7T9JKKr2   c                8    | j                  |j                        S rF   )r]   r^   r.   rm   s     r1   
_print_Idxz JavascriptCodePrinter._print_Idx   s    {{4::&&r2   c                     y)NzMath.Er5   r   s     r1   _print_Exp1z!JavascriptCodePrinter._print_Exp1   s    r2   c                     y)NzMath.PIr5   r   s     r1   	_print_PizJavascriptCodePrinter._print_Pi   s    r2   c                     y)NzNumber.POSITIVE_INFINITYr5   r   s     r1   _print_Infinityz%JavascriptCodePrinter._print_Infinity       )r2   c                     y)NzNumber.NEGATIVE_INFINITYr5   r   s     r1   _print_NegativeInfinityz-JavascriptCodePrinter._print_NegativeInfinity   r   r2   c           
        ddl m} |j                  d   j                  dk7  rt	        d      g }|j                  |      rt        |j                        D ]  \  }\  }}|dk(  r$|j                  d| j                  |      z         nU|t        |j                        dz
  k(  r|dk(  r|j                  d       n#|j                  d	| j                  |      z         | j                  |      }|j                  |       |j                  d
        dj                  |      S |j                  d d D cg c],  \  }}d| j                  |      d| j                  |      d. }}}d| j                  |j                  d   j                        z  }	dj                  |      |	z   dj                  dt        |      z  g      z   S c c}}w )Nr   )
Assignmentrg   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) {rW   zelse {zelse if (%s) {r[   
ru   z) ? (
z
)
z: (
%s
)z:  ri   )sympy.codegen.astr   rv   cond
ValueErrorhas	enumerater\   r]   lenjoinrm   )
r.   rm   r   rH   rN   eccode0ecpairs	last_lines
             r1   _print_Piecewisez&JavascriptCodePrinter._print_Piecewise   s   099R=%  / 0 0
 88J&tyy1 	"	6Aq6LLt{{1~!=>#dii.1,,dLL*LL!1DKKN!BCAU#S!	" 99U## !%		#201 04{{1~t{{1~N 0G 0$t{{499R=3E3E'FFI99W%	1CHHc#g,>N=O4PPP0s   51Gc                    dj                  | j                  |j                  t        d   d      |j                  |j
                  |j                  j                  d   z  z         S )Nz{}[{}]AtomT)strictrW   )r<   rj   parentr	   rO   rN   rR   r   s     r1   _print_MatrixElementz*JavascriptCodePrinter._print_MatrixElement   sY    t00vt  1  -FFTVVDKK--a0002 	2r2   c                l   t        |t              r1| j                  |j                  d            }dj	                  |      S d}d}d}|D cg c]  }|j                  d       }}|D cg c]*  }t        t        t        |j                  |                  , }}|D cg c]*  }t        t        t        |j                  |                  , }}g }	d}
t        |      D ]C  \  }}|dv r|	j                  |       |
||   z  }
|	j                  ||
z  |       |
||   z  }
E |	S c c}w c c}w c c}w )	z0Accepts a string of code or a list of code linesT z   ){(z{
z(
)r[   ri   z 	r   )r   r   )
isinstancestrrG   
splitlinesr   lstriprq   anymapendswith
startswithr   r\   )r.   code
code_linestab	inc_token	dec_tokenlineincreasedecreaseprettylevelns               r1   rG   z!JavascriptCodePrinter.indent_code   s:    dC ))$//$*?@J77:&&,		046U#66IMOSS	:;<OO!%( S)<=> ( (   	!GAtz!d#Xa[ EMMCIt45Xa[ E	!  7O(s   D'*/D,/D1N)__name__
__module____qualname____doc__printmethodlanguager*   r   r'   __annotations__r)   r7   r:   r>   rD   rI   rU   re   ro   rs   r~   r   r   r   r   r   r   r   r   r   rG   r5   r2   r1   r    r    .   s    KH(,[-J-J )O )~  !# /"$U'B'
8 
89L'**QB2
r2   r    Nc                8    t        |      j                  | |      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)rm   	assign_tor/   s      r1   jscoder      s    R !*224CCr2   c                .    t        t        | fi |       y)zPrints the Javascript representation of the given expression.

       See jscode for the meaning of the optional arguments.
    N)printr   )rm   r/   s     r1   print_jscoder   J  s    
 
&
"
"#r2   rF   )r   
__future__r   typingr   
sympy.corer   sympy.core.numbersr   sympy.printing.codeprinterr   sympy.printing.precedencer   r	   r+   r    r   r   r5   r2   r1   <module>r      s   #   + 2 <
	:
K \ K	
 \ K \ \ { 
: K 
: \ 
: 
:  
:!" K#$ +2mK m`iDX$r2   