
    \h7                       S r SSKJr  SSKJr  SSKJr  SSKJr  SSK	J
r
Jr  SSKJr  0 SS	_S
S
_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SS_SSSSSSS S!S"S#S$S%.Er/ S&Qr " S' S(\5      rS,S* jrS+ rg))-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            	      $  ^  \ rS rSr% SrSrSr\" \R                  40 S0 S\
" 5       S.D6r	S\S	'   S
SSS.r0 rS\S'   0 4S jrS rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS  rS! rS" r U 4S# jr!S$ r"S% r#S& r$S' r%S(r&U =r'$ ))RCodePrinterN   z;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                   [         R                  " X5        [        [        5      U l        UR	                  S0 5      nU R                  R                  U5        [        UR	                  S/ 5      5      U l        [        [        5      U l        g )NrD   rF   )	r   __init__dictknown_functionsgetupdateset_dereferencereserved_words)selfsettings	userfuncss      L/var/www/auris/envauris/lib/python3.13/site-packages/sympy/printing/rcode.pyrP   RCodePrinter.__init__a   sg    T,#O4LL!126	##I.]B ?@!.1    c                    US-  $ )N    )rX   ps     r[   _rate_index_position!RCodePrinter._rate_index_positioni   s    s
r]   c                    SU-  $ )Nz%s;r`   )rX   
codestrings     r[   _get_statementRCodePrinter._get_statementl   s    z!!r]   c                $    SR                  U5      $ )Nz// {}format)rX   texts     r[   _get_commentRCodePrinter._get_commento   s    ~~d##r]   c                $    SR                  X5      $ )Nz{} = {};ri   )rX   namevalues      r[   _declare_number_const"RCodePrinter._declare_number_constr   s      --r]   c                $    U R                  U5      $ N)indent_code)rX   liness     r[   _format_codeRCodePrinter._format_codeu   s    &&r]   c                L   ^ UR                   u  nmU4S j[        U5       5       $ )Nc              3  P   >#    U  H  n[        T5        H  o!U4v   M
     M     g 7frt   )range).0ijcolss      r[   	<genexpr>8RCodePrinter._traverse_matrix_indices.<locals>.<genexpr>z   s     A1U4[A[s   #&)shaper{   )rX   matrowsr   s      @r[   _traverse_matrix_indices%RCodePrinter._traverse_matrix_indicesx   s    YY
dAdAAr]   c           
        / n/ nSnU H}  nUR                  UU R                  UR                  5      U R                  UR                  S-   5      U R                  UR                  S-   5      S.-  5        UR                  S5        M     X#4$ )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)rX   indices
open_linesclose_lines	loopstartr}   s         r[   _get_loop_opening_ending%RCodePrinter._get_loop_opening_ending|   s     
9	Ai{{177+QWWQY/{{177Q;/+1 1 2 s#  &&r]   c                   SU R                   ;   a  U R                  U5      $ [        U5      n[        UR                  S5      (       a  SU R                  UR                  U5      -  $ [        UR                  S5      (       a  SU R                  UR                  5      -  $ U R                  UR                  U5      < SU R                  UR                  U5      < 3$ )NPowz1.0/%sg      ?zsqrt(%s)^)rR   _print_Functionr   r   r   parenthesizebaser   )rX   exprPRECs      r[   
_print_Pow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                `    [        UR                  5      [        UR                  5      p2SX#4-  $ )Nz	%d.0/%d.0)intra   q)rX   r   ra   r   s       r[   _print_RationalRCodePrinter._print_Rational   s&    466{CK1aV##r]   c                    UR                    Vs/ s H  o R                  U5      PM     nnU R                  UR                  R                  5      < SSR	                  U5      < S3$ s  snf )N[z, ])r   r   r   r   join)rX   r   r}   indss       r[   _print_IndexedRCodePrinter._print_Indexed   sI    )-7AQ7;;tyy74II 8s   A'c                    g)Nzexp(1)r`   rX   r   s     r[   _print_Exp1RCodePrinter._print_Exp1   s    r]   c                    g)Npir`   r   s     r[   	_print_PiRCodePrinter._print_Pi   s    r]   c                    g)Nr5   r`   r   s     r[   _print_InfinityRCodePrinter._print_Infinity   s    r]   c                    g)Nz-Infr`   r   s     r[   _print_NegativeInfinity$RCodePrinter._print_NegativeInfinity   s    r]   c                L   SSK Jn  SSKJn  SSKJn  UR                  nUR                  n[        XS5      (       a`  / nU R                  U5       H8  u  pU" XXU	4   XhU	4   5      n
U R                  U
5      nUR                  U5        M:     SR                  U5      $ U R                  S   (       a=  UR                  U5      (       d  UR                  U5      (       a  U R                  Xe5      $ U R                  U5      nU R                  U5      nU R!                  U< SU< 35      $ )Nr   )
Assignment)MatrixSymbol)IndexedBase
rE   z = )sympy.codegen.astr   "sympy.matrices.expressions.matexprr   sympy.tensor.indexedr   lhsrhs
isinstancer   r   r   r   	_settingshas_doprint_loopsrf   )rX   r   r   r   r   r   r   rv   r}   r~   tempcode0lhs_coderhs_codes                 r[   _print_AssignmentRCodePrinter._print_Assignment   s    0C4hhhh c(( E77<!#d)SAY7D)U# = 99U##^^J'SWW[-A-A$$ &&s00{{3'H{{3'H&&Hh'GHHr]   c                   UR                   S   R                  S:X  a,  SU R                  UR                   S   R                  5      -  nOWSU R                  UR                   S   R                  5      < SU R                  UR                   S   R                  5      < S3nUn[	        UR                   S S 5       H4  u  pESU R                  U5      < SU R                  U5      < S3U-   S-   nM6     U$ )Nr   Tz%szifelse(,z,NA)))argscondr   r   reversed)rX   r   	last_linecodeecs         r[   _print_PiecewiseRCodePrinter._print_Piecewise   s     99R=%t{{499R=+=+=>>I & /3kk$))B-:L:L.Mt{{[_[d[deg[h[m[mOnoITYYs^,DAq%)[[^T[[^DTI#MD -r]   c                N    SSK Jn  U R                  UR                  U5      5      $ )Nr   )	Piecewise)sympy.functionsr   r   rewrite)rX   r   r   s      r[   
_print_ITERCodePrinter._print_ITE   s    -{{4<<	233r]   c                    SR                  U R                  UR                  [        S   SS9UR                  UR
                  UR                  R                  S   -  -   5      $ )Nz{}[{}]AtomT)strictr   )rj   r   parentr   r~   r}   r   r   s     r[   _print_MatrixElement!RCodePrinter._print_MatrixElement   s[    t00j>P  1  &&466$++*;*;A*>#>>@ 	@r]   c                f   > [         TU ]  U5      nXR                  ;   a  SR                  U5      $ U$ )Nz(*{}))super_print_SymbolrV   rj   )rX   r   ro   	__class__s      r[   r   RCodePrinter._print_Symbol   s2    w$T*$$$>>$''Kr]   c                    U R                  UR                  5      nU R                  UR                  5      nUR                  nSR	                  X$U5      $ )Nz{} {} {})r   r   r   rel_oprj   )rX   r   r   r   ops        r[   _print_RelationalRCodePrinter._print_Relational   sB    ;;txx(;;txx([[  x88r]   c                    U R                  UR                  5      nUR                  nU R                  UR                  5      nSR	                  X#U5      $ )Nz	{} {} {};)r   r   r   r   rj   )rX   r   r   r   r   s        r[   _print_AugmentedAssignment'RCodePrinter._print_AugmentedAssignment   sB    ;;txx(WW;;txx(!!(99r]   c                   U R                  UR                  5      n[        UR                  [        5      (       a  UR                  R
                  u  p4nO[        S5      eU R                  UR                  5      nSR                  X#US-
  XVS9$ )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   rj   )rX   r   r   r   r   r   r   s          r[   
_print_ForRCodePrinter._print_For   s|    T[[)dmmU++ $ 2 2E%&RSS{{499%V]]ek!V$ ^ 3 	3r]   c                   [        U[        5      (       a1  U R                  UR                  S5      5      nSR	                  U5      $ SnSnSnU Vs/ s H  ofR                  S5      PM     nnU Vs/ s H+  n[        [        [        UR                  U5      5      5      PM-     nnU Vs/ s H+  n[        [        [        UR                  U5      5      5      PM-     nn/ n	Sn
[        U5       HE  u  pUS;   a  U	R                  U5        M  XU   -  n
U	R                  X:-  < U< 35        XU   -  n
MG     U	$ s  snf s  snf s  snf )	z0Accepts a string of code or a list of code linesT z   ){(z{
z(
)r   r   z 	r   )r   r   )r   strru   
splitlinesr   lstripr   anymapendswith
startswith	enumerater   )rX   r   
code_linestab	inc_token	dec_tokenlineincreasedecreaseprettylevelns               r[   ru   RCodePrinter.indent_code  s3    dC  ))$//$*?@J77:&&,		046U#6IMOSS	:;<O!%(!% S)<=>!% 	 (  GAz!d#a[ EMMCIt45a[ E '  7O(s   D712D<)2E)rV   rR   rW   )(__name__
__module____qualname____firstlineno____doc__printmethodlanguagerQ   r   rG   rU   __annotations__
_operatorsrN   rP   rb   rf   rl   rq   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ru   __static_attributes____classcell__)r   s   @r[   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                6    [        U5      R                  X5      $ )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_torY   s      r[   rcoder$  "  s    V !))$::r]   c                .    [        [        U 40 UD65        g)z0Prints R representation of the given expression.N)printr$  )r   rY   s     r[   print_rcoder'    s    	%
!
!"r]   rt   )r  
__future__r   typingr   sympy.core.numbersr   sympy.printing.codeprinterr   sympy.printing.precedencer   r   sympy.sets.fancysetsr	   rR   rW   r>   r$  r'  r`   r]   r[   <module>r.     s:   #  + 2 < &	5 
5 
5	
 
5 F F F W 
5 
5 
5 F F F  W!" W#$ W%& ;F,Q; Qhk;\#r]   