U
     ‹Ñh]7  ã                   @  sà   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 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d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8gZG d9d:„ d:eƒZd@d<d=„Zd>d?„ Zd;S )Az˜
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Ú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)ZAbsr
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ZMaxZMinr   r    r!   r"   r#   r$   ÚifÚelseÚrepeatÚwhileÚfunctionÚforÚinÚnextÚbreakÚTRUEÚFALSEZNULLÚInfÚNaNZNAZNA_integer_ZNA_real_ZNA_complex_ZNA_character_Zvolatilec                      s(  e Zd ZU dZdZdZeejfdi de	ƒ dœŽZde
d< d	d
ddœZi Zde
d< i fdd„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd5d6„ Z ‡ fd7d8„Z!d9d:„ Z"d;d<„ Z#d=d>„ Z$d?d@„ Z%‡  Z&S )AÚRCodePrinterz;A printer to convert SymPy expressions to strings of R codeZ_rcodeÚRé   T)Z	precisionÚuser_functionsÚcontractÚdereferencezdict[str, Any]Ú_default_settingsú&ú|ú!)ÚandÚorÚnotzdict[str, str]Ú_relationalsc                 C  sN   t  | |¡ ttƒ| _| di ¡}| j |¡ t| dg ¡ƒ| _ttƒ| _d S )Nr5   r7   )	r   Ú__init__ÚdictÚknown_functionsÚgetÚupdateÚsetÚ_dereferenceÚreserved_words)ÚselfÚsettingsZ	userfuncs© rJ   úB/tmp/user/2202/pip-unpacked-wheel-qe3242ng/sympy/printing/rcode.pyr@   a   s    
zRCodePrinter.__init__c                 C  s   |d S )Né   rJ   )rH   ÚprJ   rJ   rK   Ú_rate_index_positioni   s    z!RCodePrinter._rate_index_positionc                 C  s   d| S )Nz%s;rJ   )rH   Z
codestringrJ   rJ   rK   Ú_get_statementl   s    zRCodePrinter._get_statementc                 C  s
   d  |¡S )Nz// {}©Úformat)rH   ÚtextrJ   rJ   rK   Ú_get_commento   s    zRCodePrinter._get_commentc                 C  s   d  ||¡S )Nz{} = {};rP   )rH   ÚnameÚvaluerJ   rJ   rK   Ú_declare_number_constr   s    z"RCodePrinter._declare_number_constc                 C  s
   |   |¡S ©N)Úindent_code)rH   ÚlinesrJ   rJ   rK   Ú_format_codeu   s    zRCodePrinter._format_codec                   s    |j \}‰ ‡ fdd„t|ƒD ƒS )Nc                 3  s$   | ]}t ˆ ƒD ]}||fV  qqd S rW   )Úrange)Ú.0ÚiÚj©ÚcolsrJ   rK   Ú	<genexpr>z   s     
  z8RCodePrinter._traverse_matrix_indices.<locals>.<genexpr>)Úshaper[   )rH   ÚmatZrowsrJ   r_   rK   Ú_traverse_matrix_indicesx   s    
z%RCodePrinter._traverse_matrix_indicesc              
   C  s^   g }g }d}|D ]D}|  ||  |j¡|  |jd ¡|  |jd ¡dœ ¡ |  d¡ q||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)rH   ÚindicesZ
open_linesZclose_linesZ	loopstartr]   rJ   rJ   rK   Ú_get_loop_opening_ending|   s    
ý
z%RCodePrinter._get_loop_opening_endingc                 C  sz   d| j kr|  |¡S t|ƒ}t|jdƒr:d|  |j|¡ S t|jdƒrVd|  |j¡ S d|  |j|¡|  |j|¡f S d S )NZPowéÿÿÿÿz1.0/%sg      à?zsqrt(%s)z%s^%s)rB   Z_print_Functionr   r   r   ÚparenthesizeÚbaserk   )rH   ÚexprZPRECrJ   rJ   rK   Ú
_print_Pow‹   s    

ÿzRCodePrinter._print_Powc                 C  s"   t |jƒt |jƒ }}d||f S )Nz	%d.0/%d.0)ÚintrM   Úq)rH   rt   rM   rw   rJ   rJ   rK   Ú_print_Rational˜   s    zRCodePrinter._print_Rationalc                   s0   ‡ fdd„|j D ƒ}dˆ  |jj¡d |¡f S )Nc                   s   g | ]}ˆ   |¡‘qS rJ   )rk   )r\   r]   ©rH   rJ   rK   Ú
<listcomp>�   s     z/RCodePrinter._print_Indexed.<locals>.<listcomp>z%s[%s]z, )ro   rk   rs   rl   Újoin)rH   rt   ZindsrJ   ry   rK   Ú_print_Indexedœ   s    zRCodePrinter._print_Indexedc                 C  s   |   |j¡S rW   )rk   rl   ©rH   rt   rJ   rJ   rK   Ú
_print_Idx    s    zRCodePrinter._print_Idxc                 C  s   dS )Nzexp(1)rJ   r}   rJ   rJ   rK   Ú_print_Exp1£   s    zRCodePrinter._print_Exp1c                 C  s   dS )NÚpirJ   r}   rJ   rJ   rK   Ú	_print_Pi¦   s    zRCodePrinter._print_Pic                 C  s   dS )Nr0   rJ   r}   rJ   rJ   rK   Ú_print_Infinity©   s    zRCodePrinter._print_Infinityc                 C  s   dS )Nz-InfrJ   r}   rJ   rJ   rK   Ú_print_NegativeInfinity¬   s    z$RCodePrinter._print_NegativeInfinityc                 C  sÞ   ddl m} ddlm} ddlm} |j}|j}t||ƒrŠg }|  	|¡D ]6\}}	||||	f |||	f ƒ}
|  
|
¡}| |¡ qHd |¡S | jd r´| |¡s¨| |¡r´|  ||¡S |  
|¡}|  
|¡}|  d||f ¡S d S )Nr   )Ú
Assignment)ÚMatrixSymbol)ÚIndexedBaseÚ
r6   z%s = %s)Zsympy.codegen.astr„   Z"sympy.matrices.expressions.matexprr…   Zsympy.tensor.indexedr†   ÚlhsÚrhsÚ
isinstancerd   rk   rj   r{   Z	_settingsZhasZ_doprint_loopsrO   )rH   rt   r„   r…   r†   rˆ   r‰   rY   r]   r^   ÚtempZcode0Úlhs_codeÚrhs_coderJ   rJ   rK   Ú_print_Assignment¯   s&    


ÿ

zRCodePrinter._print_Assignmentc                 C  s”   |j d jdkr(d|  |j d j¡ }n(d|  |j d j¡|  |j d j¡f }|}t|j d d… ƒD ](\}}d|  |¡|  |¡f | d }qf|S )Nrq   Tz%szifelse(%s,%s,NA)zifelse(%s,%s,ú))ÚargsZcondrk   rt   Úreversed)rH   rt   Ú	last_lineÚcodeÚeÚcrJ   rJ   rK   Ú_print_PiecewiseÖ   s    ("zRCodePrinter._print_Piecewisec                 C  s   ddl m} |  | |¡¡S )Nr   )Ú	Piecewise)Zsympy.functionsr—   rk   Zrewrite)rH   rt   r—   rJ   rJ   rK   Ú
_print_ITEâ   s    zRCodePrinter._print_ITEc                 C  s2   d  | j|jtd dd�|j|j|jjd   ¡S )Nz{}[{}]ZAtomT)Ústrictre   )rQ   rr   Úparentr   r^   r]   rb   r}   rJ   rJ   rK   Ú_print_MatrixElementæ   s
    ÿÿz!RCodePrinter._print_MatrixElementc                   s(   t ƒ  |¡}|| jkr d |¡S |S d S )Nz(*{}))ÚsuperÚ_print_SymbolrF   rQ   )rH   rt   rT   ©Ú	__class__rJ   rK   r�   ê   s    

zRCodePrinter._print_Symbolc                 C  s,   |   |j¡}|   |j¡}|j}d |||¡S )Nz{} {} {})rk   rˆ   r‰   Zrel_oprQ   )rH   rt   rŒ   r�   ÚoprJ   rJ   rK   Ú_print_Relationalñ   s    zRCodePrinter._print_Relationalc                 C  s,   |   |j¡}|j}|   |j¡}d |||¡S )Nz	{} {} {};)rk   rˆ   r    r‰   rQ   )rH   rt   rŒ   r    r�   rJ   rJ   rK   Ú_print_AugmentedAssignment÷   s    z'RCodePrinter._print_AugmentedAssignmentc                 C  sT   |   |j¡}t|jtƒr(|jj\}}}ntdƒ‚|   |j¡}dj|||d ||d�S )Nz*Only iterable currently supported is RangezCfor({target} in seq(from={start}, to={stop}, by={step}){{
{body}
}}re   )Útargetrg   ÚstopÚstepÚbody)	rk   r£   rŠ   Úiterabler   r�   ÚNotImplementedErrorr¦   rQ   )rH   rt   r£   rg   r¤   r¥   r¦   rJ   rJ   rK   Ú
_print_Forý   s      ÿzRCodePrinter._print_Forc           
        sÂ   t |tƒr$|  | d¡¡}d |¡S d}d‰d‰ dd„ |D ƒ}‡fdd„|D ƒ}‡ fd	d„|D ƒ}g }d
}t|ƒD ]J\}}	|	dkrŽ| |	¡ qr||| 8 }| d|| |	f ¡ ||| 7 }qr|S )z0Accepts a string of code or a list of code linesTÚ z   )Ú{ú(z{
z(
)ri   r�   c                 S  s   g | ]}|  d ¡‘qS )z 	)Úlstrip©r\   ÚlinerJ   rJ   rK   rz     s     z,RCodePrinter.indent_code.<locals>.<listcomp>c                   s    g | ]}t tt|jˆ ƒƒƒ‘qS rJ   )rv   ÚanyÚmapÚendswithr®   )Ú	inc_tokenrJ   rK   rz     s     c                   s    g | ]}t tt|jˆ ƒƒƒ‘qS rJ   )rv   r°   r±   Ú
startswithr®   )Ú	dec_tokenrJ   rK   rz     s   ÿr   )rª   r‡   z%s%s)rŠ   ÚstrrX   Ú
splitlinesr{   Ú	enumeraterj   )
rH   r“   Z
code_linesÚtabZincreaseZdecreaseÚprettyÚlevelÚnr¯   rJ   )rµ   r³   rK   rX     s*    


ÿ
zRCodePrinter.indent_code)'Ú__name__Ú
__module__Ú__qualname__Ú__doc__ZprintmethodÚlanguagerA   r   r8   rE   Ú__annotations__Ú
_operatorsr?   r@   rN   rO   rS   rV   rZ   rd   rp   ru   rx   r|   r~   r   r�   r‚   rƒ   rŽ   r–   r˜   r›   r�   r¡   r¢   r©   rX   Ú__classcell__rJ   rJ   rž   rK   r2   N   sN   
üý'r2   Nc                 K  s   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);

    )r2   Zdoprint)rt   Z	assign_torI   rJ   rJ   rK   Úrcode%  s    krÅ   c                 K  s   t t| f|Žƒ dS )z0Prints R representation of the given expression.N)ÚprintrÅ   )rt   rI   rJ   rJ   rK   Úprint_rcode“  s    rÇ   )N)rÀ   Ú
__future__r   Útypingr   Zsympy.core.numbersr   Zsympy.printing.codeprinterr   Zsympy.printing.precedencer   r   Zsympy.sets.fancysetsr   rB   rG   r2   rÅ   rÇ   rJ   rJ   rJ   rK   Ú<module>   sx   
ã#í X
n