+
    i7                       R t ^ RIHt ^ RIHt ^ RIHt ^ RIHt ^ RI	H
t
Ht ^ RIHt / RRbR	R	bR
R
bRRbRRbRRbRRbRRbRRbRRbRRbRRbRRbRRbRRbRRbRRbRRRRRRRRRRR R R!R!R"R"R#R#R$R$R%R%/Ct. R+Ot ! R& R']4      tR,R) ltR* tR(# )-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maxMinmin	factorialgammadigammatrigammabetasqrtc                  .  a  ] tR t^Nt$ RtRtRt]! ]P                  3/ R^R/ RRR]
! 4       /B t	R	]R
&   RRRRRR/t/ tR]R&   / 3R ltR tR tR tR tR tR tR tR tR tR tR tR tR  tR! tR" tR# tR$ tR% t V 3R& lt!R' t"R( t#R) t$R* t%R+t&V ;t'# ),RCodePrinterz;A printer to convert SymPy expressions to strings of R code_rcodeR	precisionuser_functionscontractTdereferencezdict[str, Any]_default_settingsand&or|not!zdict[str, str]_relationalsc                	   \         P                  ! W4       \        \        4      V n        VP	                  R / 4      pV P                  P                  V4       \        VP	                  R. 4      4      V n        \        \        4      V n        R# )r-   r/   N)	r   __init__dictknown_functionsgetupdateset_dereferencereserved_words)selfsettings	userfuncss   && t/Users/tonyclaw/.openclaw/workspace/skills/math-calculator/venv/lib/python3.14/site-packages/sympy/printing/rcode.pyr9   RCodePrinter.__init__a   sg    T,#O4LL!126	##I.]B ?@!.1    c                	    V^,          # )    )rA   ps   &&rD   _rate_index_position!RCodePrinter._rate_index_positioni   s    s
rF   c                	    R V,          # )z%s;rI   )rA   
codestrings   &&rD   _get_statementRCodePrinter._get_statementl   s    z!!rF   c                	$    R P                  V4      # )z// {}format)rA   texts   &&rD   _get_commentRCodePrinter._get_commento   s    ~~d##rF   c                	$    R P                  W4      # )z{} = {};rR   )rA   namevalues   &&&rD   _declare_number_const"RCodePrinter._declare_number_constr   s      --rF   c                	$    V P                  V4      # N)indent_code)rA   liness   &&rD   _format_codeRCodePrinter._format_codeu   s    &&rF   c                	L   a VP                   w  poV3R  l\        V4       4       # )c              3  N   <"   T F  p\        S4       F  q!V3x  K
  	  K  	  R # 5ir]   )range).0ijcolss   &  rD   	<genexpr>8RCodePrinter._traverse_matrix_indices.<locals>.<genexpr>z   s     A1U4[A[s   "%)shaperd   )rA   matrowsrh   s   && @rD   _traverse_matrix_indices%RCodePrinter._traverse_matrix_indicesx   s    YY
dAdAArF   c                6   . p. pRpV F  pVP                  VRV P                  VP                  4      RV P                  VP                  ^,           4      RV P                  VP                  ^,           4      /,          4       VP                  R4       K  	  W#3# )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)rA   indices
open_linesclose_lines	loopstartrf   s   &&    rD   _get_loop_opening_ending%RCodePrinter._get_loop_opening_ending|   s     
9	Ait{{177+QWWQY/t{{177Q;/+1 1 2 s#  &&rF   c                	   R V P                   9   d   V P                  V4      # \        V4      p\        VP                  R4      '       d$   RV P                  VP                  V4      ,          # \        VP                  R4      '       d#   RV P                  VP                  4      ,          # V P                  VP                  V4      : RV P                  VP                  V4      : 2# )Powz1.0/%sg      ?zsqrt(%s)^)r;   _print_Functionr   r   r   parenthesizebaserv   )rA   exprPRECs   && rD   
_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rF   c                	h    \        VP                  4      \        VP                  4      r2R W#3,          # )z	%d.0/%d.0)intrJ   q)rA   r   rJ   r   s   &&  rD   _print_RationalRCodePrinter._print_Rational   s&    466{CK1aV##rF   c                	    VP                    Uu. uF  q P                  V4      NK  	  ppV P                  VP                  P                  4      : R RP	                  V4      : R2# u upi )[z, ])rz   rv   r   rw   join)rA   r   rf   indss   &&  rD   _print_IndexedRCodePrinter._print_Indexed   sI    )-7AQ7;;tyy74II 8s   A&c                	    R # )zexp(1)rI   rA   r   s   &&rD   _print_Exp1RCodePrinter._print_Exp1   s    rF   c                	    R # )pirI   r   s   &&rD   	_print_PiRCodePrinter._print_Pi   s    rF   c                	    R # )InfrI   r   s   &&rD   _print_InfinityRCodePrinter._print_Infinity   s    rF   c                	    R # )z-InfrI   r   s   &&rD   _print_NegativeInfinity$RCodePrinter._print_NegativeInfinity   s    rF   c                	l   ^ RI Hp ^ RIHp ^ RIHp VP                  pVP                  p\        WS4      '       di   . pV P                  V4       F@  w  rV! WXV	3,          WhV	3,          4      p
V P                  V
4      pVP                  V4       KB  	  RP                  V4      # V P                  R,          '       d@   VP                  V4      '       g   VP                  V4      '       d   V P                  We4      # V P                  V4      pV P                  V4      pV P!                  V: RV: 24      # )    )
Assignment)MatrixSymbol)IndexedBase
r.   z = )sympy.codegen.astr   "sympy.matrices.expressions.matexprr   sympy.tensor.indexedr   lhsrhs
isinstancern   rv   ru   r   	_settingshas_doprint_loopsrO   )rA   r   r   r   r   r   r   r_   rf   rg   tempcode0lhs_coderhs_codes   &&            rD   _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HrF   c                	$   VP                   R,          P                  R8X  d5   RV P                  VP                   R,          P                  4      ,          pM_RV P                  VP                   R,          P                  4      : RV P                  VP                   R,          P                  4      : R2pTp\	        VP                   RR 4       F<  w  rERV P                  V4      : RV P                  V4      : R2V,           R,           pK>  	  V# )	   Tz%szifelse(,z,NA)N)r   )argscondrv   r   reversed)rA   r   	last_linecodeecs   &&    rD   _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 -rF   c                	N    ^ RI Hp V P                  VP                  V4      4      # )r   )	Piecewise)sympy.functionsr   rv   rewrite)rA   r   r   s   && rD   
_print_ITERCodePrinter._print_ITE   s    -{{4<<	233rF   c                	    R P                  V P                  VP                  \        R,          RR7      VP                  VP
                  VP                  P                  ^,          ,          ,           4      # )z{}[{}]AtomT)strict)rS   r   parentr   rg   rf   rk   r   s   &&rD   _print_MatrixElement!RCodePrinter._print_MatrixElement   s[    t00j>P  1  &&466$++*;*;A*>#>>@ 	@rF   c                	h   < \         SV `  V4      pWP                  9   d   R P                  V4      # V# )z(*{}))super_print_Symbolr?   rS   )rA   r   rX   	__class__s   && rD   r   RCodePrinter._print_Symbol   s2    w$T*$$$>>$''KrF   c                	    V P                  VP                  4      pV P                  VP                  4      pVP                  pR P	                  W$V4      # )z{} {} {})rv   r   r   rel_oprS   )rA   r   r   r   ops   &&   rD   _print_RelationalRCodePrinter._print_Relational   sB    ;;txx(;;txx([[  x88rF   c                	    V P                  VP                  4      pVP                  pV P                  VP                  4      pR P	                  W#V4      # )z	{} {} {};)rv   r   r   r   rS   )rA   r   r   r   r   s   &&   rD   _print_AugmentedAssignment'RCodePrinter._print_AugmentedAssignment   sB    ;;txx(WW;;txx(!!(99rF   c                	.   V P                  VP                  4      p\        VP                  \        4      '       d   VP                  P
                  w  r4pM\        R 4      hV P                  VP                  4      pRP                  W#V^,
          WVR7      # )z*Only iterable currently supported is RangezCfor({target} in seq(from={start}, to={stop}, by={step}){{
{body}
}})targetrr   stopstepbody)	rv   r   r   iterabler   r   NotImplementedErrorr   rS   )rA   r   r   rr   r   r   r   s   &&     rD   
_print_ForRCodePrinter._print_For   s|    T[[)dmmU++ $ 2 2E%&RSS{{499%V]]ek!V$ ^ 3 	3rF   c                   \        V\        4      '       d2   V P                  VP                  R4      4      pRP	                  V4      # RpRpRpV Uu. uF  qfP                  R4      NK  	  ppV Uu. uF+  p\        \        \        VP                  V4      4      4      NK-  	  ppV Uu. uF+  p\        \        \        VP                  V4      4      4      NK-  	  pp. p	^ p
\        V4       FZ  w  rVR9   d   V	P                  V4       K  WV,          ,          p
V	P                  W:,          : V: 24       WV,          ,          p
K\  	  V	# u upi u upi u upi )z0Accepts a string of code or a list of code linesT z   z 	){(z{
z(
)rt   r   )r   r   )r   strr^   
splitlinesr   lstripr   anymapendswith
startswith	enumerateru   )rA   r   
code_linestab	inc_token	dec_tokenlineincreasedecreaseprettylevelns   &&          rD   r^   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   E
11E(1E)r?   r;   r@   )(__name__
__module____qualname____firstlineno____doc__printmethodlanguager:   r   r0   r>   __annotations__
_operatorsr7   r9   rK   rO   rU   rZ   r`   rn   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r^   __static_attributes____classcell__)r   s   @rD   r)   r)   N   s    EKH(,[-J-J )R"Dsu	O )~  cccJ $&L.% " 2"$.'B'
D$J%IN
4@9:3 rF   r)   Nc                6    \        V4      P                  W4      # )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_torB   s   &&,rD   rcoder  "  s    V !))$::rF   c                0    \        \        V 3/ VB 4       R# )z0Prints R representation of the given expression.N)printr  )r   rB   s   &,rD   print_rcoder    s    	%
!
!"rF   )ifelserepeatwhilefunctionforinnextbreakTRUEFALSENULLr   NaNNANA_integer_NA_real_NA_complex_NA_character_volatiler]   )r  
__future__r   typingr   sympy.core.numbersr   sympy.printing.codeprinterr   sympy.printing.precedencer   r   sympy.sets.fancysetsr   r;   r@   r)   r  r  rI   rF   rD   <module>r,     sP   #  + 2 < &	5 
5 
5	
 
5 F F F W 
5 
5 
5 F F F  W!" W#$ W%& Wy
F	5	5Wy

F
F;F,Q; Qhk;\#rF   