
    wg]7                       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
mZ ddl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dd d!d"d#d$d%Zg d&Z G d' d(e      Zd,d*Zd+ Zy))-z
R code printer

The RCodePrinter converts single SymPy expressions into single R expressions,
using the functions defined in math.h where possible.



    )annotations)Any)equal_valued)CodePrinter)
precedence
PRECEDENCE)RangeAbsabssincostanasinacosatanatan2explogerfsinhcoshtanhasinhacoshatanhfloorceilingsignmaxmin	factorialgammadigammatrigammabetasqrt)r   r   r   MaxMinr!   r"   r#   r$   r%   r&   )ifelserepeatwhilefunctionforinnextbreakTRUEFALSENULLInfNaNNANA_integer_NA_real_NA_complex_NA_character_volatilec            	          e Zd ZU dZdZdZ eej                  fi di d e	       dZde
d<   d	d
ddZi 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  fd#Z!d$ Z"d% Z#d& Z$d' Z% xZ&S )(RCodePrinterz;A printer to convert SymPy expressions to strings of R code_rcodeR   T)	precisionuser_functionscontractdereferencezdict[str, Any]_default_settings&|!)andornotzdict[str, str]_relationalsc                   t        j                  | |       t        t              | _        |j	                  di       }| j                  j                  |       t        |j	                  dg             | _        t        t              | _        y )NrC   rE   )	r   __init__dictknown_functionsgetupdateset_dereferencereserved_words)selfsettings	userfuncss      Y/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/printing/rcode.pyrO   zRCodePrinter.__init__a   si    T8,#O4LL!126	##I.]B ?@!.1    c                    |dz  S )N    )rW   ps     rZ   _rate_index_positionz!RCodePrinter._rate_index_positioni   s    s
r[   c                    d|z  S )Nz%s;r^   )rW   
codestrings     rZ   _get_statementzRCodePrinter._get_statementl   s    z!!r[   c                $    dj                  |      S )Nz// {}format)rW   texts     rZ   _get_commentzRCodePrinter._get_commento   s    ~~d##r[   c                &    dj                  ||      S )Nz{} = {};re   )rW   namevalues      rZ   _declare_number_constz"RCodePrinter._declare_number_constr   s      u--r[   c                $    | j                  |      S N)indent_code)rW   liness     rZ   _format_codezRCodePrinter._format_codeu   s    &&r[   c                J    |j                   \  }fdt        |      D        S )Nc              3  F   K   | ]  }t              D ]  }||f 
  y wrn   )range).0ijcolss      rZ   	<genexpr>z8RCodePrinter._traverse_matrix_indices.<locals>.<genexpr>z   s%     A1U4[AAAAs   !)shapert   )rW   matrowsrx   s      @rZ   _traverse_matrix_indicesz%RCodePrinter._traverse_matrix_indicesx   s    YY
dAdAAr[   c           
        g }g }d}|D ]|  }|j                  || j                  |j                        | j                  |j                  dz         | j                  |j                  dz         dz         |j                  d       ~ ||fS )zPReturns a tuple (open_lines, close_lines) containing lists of codelines
        z#for (%(var)s in %(start)s:%(end)s){   )varstartend})append_printlabellowerupper)rW   indices
open_linesclose_lines	loopstartrv   s         rZ   _get_loop_opening_endingz%RCodePrinter._get_loop_opening_ending|   s     
9	 	$Ai{{177+QWWQY/{{177Q;/+1 1 2 s#	$ ;&&r[   c                   d| j                   v r| j                  |      S t        |      }t        |j                  d      rd| j                  |j                  |      z  S t        |j                  d      rd| j                  |j                        z  S | j                  |j                  |      d| j                  |j                  |      S )NPowz1.0/%sg      ?zsqrt(%s)^)rQ   _print_Functionr   r   r   parenthesizebaser   )rW   exprPRECs      rZ   
_print_PowzRCodePrinter._print_Pow   s    D(((''--$"%t00DABB$((C(DII 666"//		4@!%!2!2488T!BD Dr[   c                d    t        |j                        t        |j                        }}d||fz  S )Nz	%d.0/%d.0)intr_   q)rW   r   r_   r   s       rZ   _print_RationalzRCodePrinter._print_Rational   s*    466{CK1aV##r[   c                    |j                   D cg c]  }| j                  |       }}| j                  |j                  j                        ddj	                  |      dS c c}w )N[z, ])r   r   r   r   join)rW   r   rv   indss       rZ   _print_IndexedzRCodePrinter._print_Indexed   sJ    )-7AQ77;;tyy74II 8s   A#c                8    | j                  |j                        S rn   )r   r   rW   r   s     rZ   
_print_IdxzRCodePrinter._print_Idx   s    {{4::&&r[   c                     y)Nzexp(1)r^   r   s     rZ   _print_Exp1zRCodePrinter._print_Exp1   s    r[   c                     y)Npir^   r   s     rZ   	_print_PizRCodePrinter._print_Pi   s    r[   c                     y)Nr5   r^   r   s     rZ   _print_InfinityzRCodePrinter._print_Infinity   s    r[   c                     y)Nz-Infr^   r   s     rZ   _print_NegativeInfinityz$RCodePrinter._print_NegativeInfinity   s    r[   c                &   ddl m} ddlm} ddlm} |j                  }|j                  }t        ||      rag }| j                  |      D ]:  \  }}	 ||||	f   |||	f         }
| j                  |
      }|j                  |       < dj                  |      S | j                  d   r4|j                  |      s|j                  |      r| j                  ||      S | j                  |      }| j                  |      }| j!                  |d|      S )Nr   )
Assignment)MatrixSymbol)IndexedBase
rD   z = )sympy.codegen.astr   "sympy.matrices.expressions.matexprr   sympy.tensor.indexedr   lhsrhs
isinstancer}   r   r   r   	_settingshas_doprint_loopsrc   )rW   r   r   r   r   r   r   rp   rv   rw   tempcode0lhs_coderhs_codes                 rZ   _print_AssignmentzRCodePrinter._print_Assignment   s    0C4hhhh c<( E77< $A!#ad)SAY7D)U#$ 99U##^^J'SWW[-A$ &&sC00{{3'H{{3'H&&Hh'GHHr[   c                   |j                   d   j                  dk(  r,d| j                  |j                   d   j                        z  }nUd| j                  |j                   d   j                        d| j                  |j                   d   j                        d}|}t	        |j                   d d       D ]2  \  }}d| j                  |      d| j                  |      d|z   dz   }4 |S )Nr   Tz%szifelse(,z,NA)))argscondr   r   reversed)rW   r   	last_linecodeecs         rZ   _print_PiecewisezRCodePrinter._print_Piecewise   s     99R=%t{{499R=+=+=>>I & /3kk$))B-:L:L.Mt{{[_[d[deg[h[m[mOnoITYYs^, 	NDAq%)[[^T[[^DTI#MD	Nr[   c                N    ddl m} | j                  |j                  |            S )Nr   )	Piecewise)sympy.functionsr   r   rewrite)rW   r   r   s      rZ   
_print_ITEzRCodePrinter._print_ITE   s    -{{4<<	233r[   c                    dj                  | j                  |j                  t        d   d      |j                  |j
                  |j                  j                  d   z  z         S )Nz{}[{}]AtomT)strictr   )rf   r   parentr   rw   rv   rz   r   s     rZ   _print_MatrixElementz!RCodePrinter._print_MatrixElement   s[    t00j>P  1  &&466$++*;*;A*>#>>@ 	@r[   c                d    t         |   |      }|| j                  v rdj                  |      S |S )Nz(*{}))super_print_SymbolrU   rf   )rW   r   rj   	__class__s      rZ   r   zRCodePrinter._print_Symbol   s4    w$T*4$$$>>$''Kr[   c                    | j                  |j                        }| j                  |j                        }|j                  }dj	                  |||      S )Nz{} {} {})r   r   r   rel_oprf   )rW   r   r   r   ops        rZ   _print_RelationalzRCodePrinter._print_Relational   sD    ;;txx(;;txx([[  2x88r[   c                    | j                  |j                        }|j                  }| j                  |j                        }dj	                  |||      S )Nz	{} {} {};)r   r   r   r   rf   )rW   r   r   r   r   s        rZ   _print_AugmentedAssignmentz'RCodePrinter._print_AugmentedAssignment   sD    ;;txx(WW;;txx(!!(B99r[   c                    | j                  |j                        }t        |j                  t              r|j                  j
                  \  }}}nt        d      | j                  |j                        }dj                  |||dz
  ||      S )Nz*Only iterable currently supported is RangezCfor({target} in seq(from={start}, to={stop}, by={step}){{
{body}
}}r   )targetr   stopstepbody)	r   r   r   iterabler	   r   NotImplementedErrorr   rf   )rW   r   r   r   r   r   r   s          rZ   
_print_ForzRCodePrinter._print_For   s    T[[)dmmU+ $ 2 2E4%&RSS{{499%V]]eksx!V$T ^ 3 	3r[   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   r   z 	r   )r   r   )r   strro   
splitlinesr   lstripr   anymapendswith
startswith	enumerater   )rW   r   
code_linestab	inc_token	dec_tokenlineincreasedecreaseprettylevelns               rZ   ro   zRCodePrinter.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)'__name__
__module____qualname____doc__printmethodlanguagerP   r   rF   rT   __annotations__
_operatorsrM   rO   r`   rc   rh   rl   rq   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ro   __classcell__)r   s   @rZ   r>   r>   N   s    EKH(,[-J-J )u	O )~  J $&L.% " 2"$.'B'
D$J'%IN
4@9:3r[   r>   Nc                8    t        |      j                  | |      S )a  Converts an expr to a string of r 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 the keys are string representations of either
        ``FunctionClass`` or ``UndefinedFunction`` instances and the values
        are their desired R string representations. Alternatively, the
        dictionary value can be a list of tuples i.e. [(argument_test,
        rfunction_string)] or [(argument_test, rfunction_formater)]. 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 rcode, symbols, Rational, sin, ceiling, Abs, Function
    >>> x, tau = symbols("x, tau")
    >>> rcode((2*tau)**Rational(7, 2))
    '8*sqrt(2)*tau^(7.0/2.0)'
    >>> rcode(sin(x), assign_to="s")
    's = sin(x);'

    Simple 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, cfunction_string)].

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

    or if the R-function takes a subset of the original arguments:

    >>> rcode(2**x + 3**x, user_functions={'Pow': [
    ...   (lambda b, e: b == 2, lambda b, e: 'exp2(%s)' % e),
    ...   (lambda b, e: b != 2, 'pow')]})
    'exp2(x) + pow(3, 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(rcode(expr, assign_to=tau))
    tau = ifelse(x > 0,x + 1,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]))
    >>> rcode(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(rcode(mat, A))
    A[0] = x^2;
    A[1] = ifelse(x > 0,x + 1,x);
    A[2] = sin(x);

    )r>   doprint)r   	assign_torX   s      rZ   rcoder
  %  s    V !))$	::r[   c                .    t        t        | fi |       y)z0Prints R representation of the given expression.N)printr
  )r   rX   s     rZ   print_rcoder    s    	%
!
!"r[   rn   )r  
__future__r   typingr   sympy.core.numbersr   sympy.printing.codeprinterr   sympy.printing.precedencer   r   sympy.sets.fancysetsr	   rQ   rV   r>   r
  r  r^   r[   rZ   <module>r     s:   #  + 2 < &	5 
5 
5	
 
5 F F F W 
5 
5 
5 F F F  W!" W#$ W%& ;F,T; Tnk;\#r[   