
    Ed7                         d Z ddlmZ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d'S )+z
R code printer

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



    )AnyDict)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dZdZdZdddi dd e            dd	d
	ZddddZi Z	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RNauto   TF_)	order	full_prec	precisionuser_functionshumancontractdereferenceerror_on_reservedreserved_word_suffix&|!)andornotc                 D   t          j        | |           t          t                    | _        |                    di           }| j                            |           t          |                    dg                     | _        t          t                    | _        d S )NrF   rI   )	r   __init__dictknown_functionsgetupdateset_dereferencereserved_words)selfsettings	userfuncss      4lib/python3.11/site-packages/sympy/printing/rcode.pyrS   zRCodePrinter.__init__e   s    T8,,,#O44LL!1266	##I...]B ? ?@@!.11    c                     |dz  S )N    )r[   ps     r^   _rate_index_positionz!RCodePrinter._rate_index_positionm   s    s
r_   c                     d|z  S )Nz%s;rb   )r[   
codestrings     r^   _get_statementzRCodePrinter._get_statementp   s    z!!r_   c                 ,    d                     |          S )Nz// {}format)r[   texts     r^   _get_commentzRCodePrinter._get_comments   s    ~~d###r_   c                 .    d                     ||          S )Nz{} = {};ri   )r[   namevalues      r^   _declare_number_constz"RCodePrinter._declare_number_constv   s      u---r_   c                 ,    |                      |          S N)indent_code)r[   liness     r^   _format_codezRCodePrinter._format_codey   s    &&&r_   c                 N    |j         \  }fdt          |          D             S )Nc              3   D   K   | ]}t                    D ]}||fV  	d S rr   )range).0ijcolss      r^   	<genexpr>z8RCodePrinter._traverse_matrix_indices.<locals>.<genexpr>~   s:      AA1U4[[AAAAAAAAAAr_   )shaperx   )r[   matrowsr|   s      @r^   _traverse_matrix_indicesz%RCodePrinter._traverse_matrix_indices|   s.    Y
dAAAAdAAAAr_   c           
         g }g }d}|D ]}|                     ||                     |j                  |                     |j        dz             |                     |j        dz             dz             |                     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)r[   indices
open_linesclose_lines	loopstartrz   s         r^   _get_loop_opening_endingz%RCodePrinter._get_loop_opening_ending   s     
9	 	$ 	$Ai{{17++QWQY//{{17Q;//+1 +1 1 2 2 2 s####;&&r_   c                 p   d| j         v r|                     |          S t          |          }|j        dk    rd|                     |j        |          z  S |j        dk    rd|                     |j                  z  S |                     |j        |          d|                     |j        |          S )NPowz1.0/%sg      ?zsqrt(%s)^)rU   _print_Functionr   r   parenthesizebaser   )r[   exprPRECs      r^   
_print_PowzRCodePrinter._print_Pow   s    D(( 	.''---$8r> 	Dt00DAABBX_ 	DDI 6 666"//	4@@@@!%!2!248T!B!B!BD Dr_   c                 `    t          |j                  t          |j                  }}d||fz  S )Nz	%d.0/%d.0)intrc   q)r[   r   rc   r   s       r^   _print_RationalzRCodePrinter._print_Rational   s*    46{{CKK1aV##r_   c                       fd|j         D             }                     |j        j                  dd                    |          dS )Nc                 :    g | ]}                     |          S rb   )r   )ry   rz   r[   s     r^   
<listcomp>z/RCodePrinter._print_Indexed.<locals>.<listcomp>   s#    777AQ777r_   [z, ])r   r   r   r   join)r[   r   indss   `  r^   _print_IndexedzRCodePrinter._print_Indexed   sM    7777777;;ty77774IIr_   c                 6    |                      |j                  S rr   )r   r   r[   r   s     r^   
_print_IdxzRCodePrinter._print_Idx   s    {{4:&&&r_   c                     dS )Nzexp(1)rb   r   s     r^   _print_Exp1zRCodePrinter._print_Exp1   s    xr_   c                     dS )Npirb   r   s     r^   	_print_PizRCodePrinter._print_Pi   s    tr_   c                     dS )Nr4   rb   r   s     r^   _print_InfinityzRCodePrinter._print_Infinity   s    ur_   c                     dS )Nz-Infrb   r   s     r^   _print_NegativeInfinityz$RCodePrinter._print_NegativeInfinity   s    vr_   c                 t   ddl m} ddlm} ddlm} |j        }|j        }t          ||          rxg }| 	                    |          D ]K\  }}	 ||||	f         |||	f                   }
| 
                    |
          }|                    |           Ld                    |          S | j        d         r@|                    |          s|                    |          r|                     ||          S | 
                    |          }| 
                    |          }|                     |d|          S )Nr   )
Assignment)MatrixSymbol)IndexedBase
rH   z = )sympy.codegen.astr   "sympy.matrices.expressions.matexprr   sympy.tensor.indexedr   lhsrhs
isinstancer   r   r   r   	_settingshas_doprint_loopsrg   )r[   r   r   r   r   r   r   rt   rz   r{   tempcode0lhs_coderhs_codes                 r^   _print_AssignmentzRCodePrinter._print_Assignment   sn   000000CCCCCC444444hh c<(( 	I E77<< $ $A!z#ad)SAY77D))U####99U###^J' 	ISWW[-A-A 	I$$	I &&sC000{{3''H{{3''H&&HHHhh'GHHHr_   c                    |j         d         j        dk    r)d|                     |j         d         j                  z  }nOd|                     |j         d         j                  d|                     |j         d         j                  d}|}t	          |j         d d                   D ]:\  }}d|                     |          d|                     |          d|z   dz   };|S )Nr   Tz%szifelse(,z,NA)))argscondr   r   reversed)r[   r   	last_linecodeecs         r^   _print_PiecewisezRCodePrinter._print_Piecewise   s     9R=% 	pt{{49R=+=>>>II	p /3kk$)B-:L.M.M.M.Mt{{[_[deg[h[mOnOnOnOnoITYss^,, 	N 	NDAqq%)[[^^^^T[[^^^^DTI#MDDr_   c                 ^    ddl m} |                     |                    |                    S )Nr   )	Piecewise)sympy.functionsr   r   rewrite)r[   r   r   s      r^   
_print_ITEzRCodePrinter._print_ITE   s2    ------{{4<<	22333r_   c                     d                     |                     |j        t          d         d          |j        |j        |j        j        d         z  z             S )Nz{}[{}]AtomT)strictr   )rj   r   parentr   r{   rz   r~   r   s     r^   _print_MatrixElementz!RCodePrinter._print_MatrixElement   s[    t00j>P  1    &46$+*;A*>#>>@ @ 	@r_   c                     t                                          |          }|| j        v rd                    |          S |S )Nz(*{}))super_print_SymbolrY   rj   )r[   r   rn   	__class__s      r^   r   zRCodePrinter._print_Symbol   sA    ww$$T**4$$ 	>>$'''Kr_   c                     |                      |j                  }|                      |j                  }|j        }d                    |||          S )Nz{} {} {})r   r   r   rel_oprj   )r[   r   r   r   ops        r^   _print_RelationalzRCodePrinter._print_Relational   sG    ;;tx((;;tx(([  2x888r_   c                     |                      |j                  }|j        }|                      |j                  }d                    |||          S )Nz	{} {} {};)r   r   r   r   rj   )r[   r   r   r   r   s        r^   _print_AugmentedAssignmentz'RCodePrinter._print_AugmentedAssignment   sG    ;;tx((W;;tx((!!(B999r_   c                    |                      |j                  }t          |j        t                    r|j        j        \  }}}nt          d          |                      |j                  }d                    |||||          S )Nz*Only iterable currently supported is RangezLfor ({target} = {start}; {target} < {stop}; {target} += {step}) {{
{body}
}})targetr   stopstepbody)	r   r   r   iterabler   r   NotImplementedErrorr   rj   )r[   r   r   r   r   r   r   s          r^   
_print_ForzRCodePrinter._print_For  s    T[))dmU++ 	T $ 2E4%&RSSS{{49%%)*0&e4 +1 +1 +1	1r_   c                   
 t          |t                    r=|                     |                    d                    }d                    |          S d}dd
d |D             }fd|D             }
fd|D             }g }d	}t          |          D ]Q\  }}	|	d
v r|                    |	           |||         z  }|                    ||z  |	           |||         z  }R|S )z0Accepts a string of code or a list of code linesT z   ){(z{
z(
)r   r   c                 8    g | ]}|                     d           S )z 	)lstrip)ry   lines     r^   r   z,RCodePrinter.indent_code.<locals>.<listcomp>  s$    666U##666r_   c           
      n    g | ]1}t          t          t          |j                                      2S rb   )r   anymapendswith)ry   r   	inc_tokens     r^   r   z,RCodePrinter.indent_code.<locals>.<listcomp>  s5    OOOSS	::;;<<OOOr_   c           
      n    g | ]1}t          t          t          |j                                      2S rb   )r   r   r   
startswith)ry   r   	dec_tokens     r^   r   z,RCodePrinter.indent_code.<locals>.<listcomp>  sE     ( ( ( S)<<==>> ( ( (r_   r   )r   r   )r   strrs   
splitlinesr   	enumerater   )r[   r   
code_linestabincreasedecreaseprettylevelnr   r   r   s             @@r^   rs   zRCodePrinter.indent_code  s5    dC   	'))$//$*?*?@@J77:&&&,		66666OOOOOOO( ( ( (!%( ( (   	! 	!GAtz! d###Xa[ EMMCIItt4555Xa[ EEr_   )$__name__
__module____qualname____doc__printmethodlanguagerX   _default_settings
_operators_relationalsrS   rd   rg   rl   rp   ru   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rs   __classcell__)r   s   @r^   r=   r=   L   s       EEKH suu" #
 
  JL !# 2 2 2 2  " " "$ $ $. . .' ' 'B B B' ' '
D 
D 
D$ $ $J J J' ' '        %I %I %IN
 
 
4 4 4@ @ @    9 9 9: : :	1 	1 	1      r_   r=   Nc                 H    t          |                              | |          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_tor\   s      r^   rcoder  *  s#    V !!))$	:::r_   c                 :    t          t          | fi |           dS )z0Prints R representation of the given expression.N)printr  )r   r\   s     r^   print_rcoder    s&    	%
!
!
!
!"""""r_   rr   )r
  typingr   r   tDictsympy.printing.codeprinterr   sympy.printing.precedencer   r   sympy.sets.fancysetsr   rU   rZ   r=   r  r  rb   r_   r^   <module>r     s    & % % % % % % % 2 2 2 2 2 2 < < < < < < < < & & & & & &	5 
5 
5	
 
5 F F F W 
5 
5 
5 F F F  W!" W#$ W%& ;  F  ,[ [ [ [ [; [ [ [|k; k; k; k;\# # # # #r_   