K i7 dZddlmZddlmZddlmZddlmZddl m Z m Z ddl m Z idd d d d d d d d d ddddddddddddddddddddddddddddddd d!d"d#d$d% Zgd&ZGd'd(eZd,d*Zd+Zy))-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)RangeAbsabssincostanasinacosatanatan2explogerfsinhcoshtanhasinhacoshatanhfloorceilingsignmaxmin factorialgammadigammatrigammabetasqrt) rrrMaxMinr!r"r#r$r%r&)ifelserepeatwhilefunctionforinnextbreakTRUEFALSENULLInfNaNNA NA_integer_NA_real_ NA_complex_ NA_character_volatilec eZdZUdZdZdZeejfidide dZde d<d d d d Z iZ d e d<ifdZ dZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd Zd!Zfd"Z d#Z!d$Z"d%Z#d&Z$xZ%S)' RCodePrinterz;A printer to convert SymPy expressions to strings of R code_rcodeRT) precisionuser_functionscontract dereferencezdict[str, Any]_default_settings&|!)andornotzdict[str, str] _relationalsctj||tt|_|j di}|jj |t |j dg|_t t|_y)NrCrE) r__init__dictknown_functionsgetupdateset _dereferencereserved_words)selfsettings userfuncss Z/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/printing/rcode.pyrOzRCodePrinter.__init__asiT8,#O4LL!126  ##I. ]B ?@!.1c |dzS)N)rWps rZ_rate_index_positionz!RCodePrinter._rate_index_positionis s r[c d|zS)Nz%s;r^)rW codestrings rZ_get_statementzRCodePrinter._get_statementls z!!r[c$dj|S)Nz// {}format)rWtexts rZ _get_commentzRCodePrinter._get_commentos~~d##r[c&dj||S)Nz{} = {};re)rWnamevalues rZ_declare_number_constz"RCodePrinter._declare_number_constrs  u--r[c$|j|SN) indent_code)rWliness rZ _format_codezRCodePrinter._format_codeus&&r[cJ|j\}fdt|DS)Nc3FK|]}tD]}||f ywrn)range).0ijcolss rZ z8RCodePrinter._traverse_matrix_indices..zs%A1U4[AAAAs!)shapert)rWmatrowsrxs @rZ_traverse_matrix_indicesz%RCodePrinter._traverse_matrix_indicesxsYY dAd AAr[c g}g}d}|D]|}|j||j|j|j|jdz|j|jdzdz|jd~||fS)zPReturns a tuple (open_lines, close_lines) containing lists of codelines z#for (%(var)s in %(start)s:%(end)s){)varstartend})append_printlabellowerupper)rWindices open_lines close_lines loopstartrvs rZ_get_loop_opening_endingz%RCodePrinter._get_loop_opening_ending|s  9  $A   i{{177+QWWQY/{{177Q;/+11 2   s #  $;&&r[cd|jvr|j|St|}t|jdrd|j |j |zSt|jdrd|j|j zS|j |j |d|j |j|S)NPowz1.0/%sg?zsqrt(%s)^)rQ_print_Functionrrr parenthesizebaser)rWexprPRECs rZ _print_PowzRCodePrinter._print_Pows D(( (''- -$ " %t00DAB B $((C ( DII 66 6"// 4@!%!2!2488T!BD Dr[cdt|jt|j}}d||fzS)Nz %d.0/%d.0)intr_q)rWrr_rs rZ_print_RationalzRCodePrinter._print_Rationals*466{CK1aV##r[c|jDcgc]}|j|}}|j|jjddj |dScc}w)N[z, ])rrrrjoin)rWrrvindss rZ_print_IndexedzRCodePrinter._print_IndexedsJ)-7AQ77;;tyy74II8sA#cy)Nzexp(1)r^rWrs rZ _print_Exp1zRCodePrinter._print_Exp1sr[cy)Npir^rs rZ _print_PizRCodePrinter._print_Pisr[cy)Nr5r^rs rZ_print_InfinityzRCodePrinter._print_Infinitysr[cy)Nz-Infr^rs rZ_print_NegativeInfinityz$RCodePrinter._print_NegativeInfinitysr[c&ddlm}ddlm}ddlm}|j }|j}t||rag}|j|D]:\}} |||| f||| f} |j| } |j| <dj|S|jdr4|j|s|j|r|j||S|j|} |j|} |j!| d| S)Nr) Assignment) MatrixSymbol) IndexedBase rDz = )sympy.codegen.astr"sympy.matrices.expressions.matexprrsympy.tensor.indexedrlhsrhs isinstancer}rrr _settingshas_doprint_loopsrc)rWrrrrrrrprvrwtempcode0lhs_coderhs_codes rZ_print_AssignmentzRCodePrinter._print_Assignments0C4hhhh c< (E77< $A!#ad)SAY7 D) U# $99U# # ^^J 'SWW[-A $&&sC0 0{{3'H{{3'H&&Hh'GH Hr[c|jdjdk(r,d|j|jdjz}nUd|j|jdjd|j|jdjd}|}t |jddD]2\}}d|j|d|j|d|zdz}4|S)NrTz%szifelse(,z,NA)))argscondrrreversed)rWr last_linecodeecs rZ_print_PiecewisezRCodePrinter._print_Piecewises 99R=   %t{{499R=+=+=>>I &/3kk$))B-:L:L.Mt{{[_[d[deg[h[m[mOnoI TYYs^, NDAq%)[[^T[[^DTI#MD N r[cNddlm}|j|j|S)Nr) Piecewise)sympy.functionsrrrewrite)rWrrs rZ _print_ITEzRCodePrinter._print_ITEs-{{4<< 233r[cdj|j|jtdd|j|j |jj dzzS)Nz{}[{}]AtomT)strictr)rfrparentrrwrvrzrs rZ_print_MatrixElementz!RCodePrinter._print_MatrixElements[t00j>P 1 &&466$++*;*;A*>#>>@ @r[cdt||}||jvrdj|S|S)Nz(*{}))super _print_SymbolrUrf)rWrrj __class__s rZrzRCodePrinter._print_Symbols4w$T* 4$$ $>>$' 'Kr[c|j|j}|j|j}|j}dj |||S)Nz{} {} {})rrrrel_oprf)rWrrrops rZ_print_RelationalzRCodePrinter._print_RelationalsD;;txx(;;txx( [[  2x88r[c|j|j}|j}|j|j}dj |||S)Nz {} {} {};)rrrrrf)rWrrrrs rZ_print_AugmentedAssignmentz'RCodePrinter._print_AugmentedAssignmentsD;;txx( WW;;txx(!!(B99r[c |j|j}t|jtr|jj \}}}n t d|j|j}dj|||dz ||S)Nz*Only iterable currently supported is RangezCfor({target} in seq(from={start}, to={stop}, by={step}){{ {body} }}r)targetrstopstepbody) rrriterabler rNotImplementedErrorrrf)rWrrrrrrs rZ _print_ForzRCodePrinter._print_ForsT[[) dmmU + $ 2 2 E4%&RS S{{499%V]]eksx!V$T^3 3r[c lt|tr1|j|jd}dj |Sd}d}d}|Dcgc]}|j d}}|Dcgc]*}t tt|j|,}}|Dcgc]*}t tt|j|,}}g} d} t|D]C\} }|dvr| j|| || z} | j|| z|| || z } E| Scc}wcc}wcc}w) z0Accepts a string of code or a list of code linesTz ){(z{ z( )rrz r)rr) rstrro splitlinesrlstripranymapendswith startswith enumerater) rWr code_linestab inc_token dec_tokenlineincreasedecreaseprettylevelns rZrozRCodePrinter.indent_codes: dC ))$//$*?@J77:& &,  046U#66IMOSS :;<OO!%(S)<=>((  !GAtz! d# Xa[ E MMCIt4 5 Xa[ E  ! 7O(s D'*/D,/D1)&__name__ __module__ __qualname____doc__ printmethodlanguagerPrrFrT__annotations__ _operatorsrMrOr`rcrhrlrqr}rrrrrrrrrrrrrrrrro __classcell__)rs@rZr>r>NsEKH(,[-J-J)u O)~J $&L.% "2"$.'B ' D$J%IN 4@9 : 3r[r>Nc 8t|j||S)aConverts 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_torXs rZrcoder"sV  ! ) )$ ::r[c .tt|fi|y)z0Prints R representation of the given expression.N)printr)rrXs rZ print_rcoder s % ! !"r[rn)r __future__rtypingrsympy.core.numbersrsympy.printing.codeprinterrsympy.printing.precedencerrsympy.sets.fancysetsr rQrVr>rr r^r[rZrs:#+2<& 5 5 5   5   F  F F W 5 5 5 F F F  W!" W#$ W%&      ;F,Q;Qhk;\#r[