K iJddlmZddlmZddlmZddlmZmZm Z m Z m Z m Z ddl mZddlmZmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZm Z GddZ!Gdde"Z#Gdde$Z%dZ&GddeZ'ddZ(dZ)d dZ*dZ+d!dZ,d dZ-dZ.y)") annotations)Anywraps)AddMulPowSsympifyFloat)Basic)ExprUnevaluatedExpr)Lambda) _keep_coeff)default_sort_key)Symbol)re) StrPrinter) precedence PRECEDENCEceZdZdZdZdZy)requiresz: Decorator for registering requirements on print methods. c ||_yN)_req)selfkwargss `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/printing/codeprinter.py__init__zrequires.__init__s  c4fd}t|S)NcjjD] \}}t||j|"|g|i|Sr)ritemsgetattrupdate)self_argsrkvmethodrs r_method_wrapperz*requires.__call__.._method_wrappersK ) ,1q!((+ ,%1$1&1 1r!r)rr+r,s`` r__call__zrequires.__call__s 2uV}_--r!N)__name__ __module__ __qualname____doc__r r-r!rrrsD.r!rceZdZdZy)AssignmentErrorzA Raised if an assignment variable for a loop is missing. Nr.r/r0r1r2r!rr4r4  r!r4ceZdZdZy)PrintMethodNotImplementedErrorz@ Raised if a _print_* method is missing in the Printer. Nr5r2r!rr8r8%r6r!r8ct|trddlm}|d|DSt|trt d|DS|S)Nr)Listc32K|]}t|ywr_convert_python_lists.0es r z(_convert_python_lists...s<1+A.<c32K|]}t|ywrr<r>s rrAz(_convert_python_lists..0s;!*1-;rB) isinstancelistsympy.codegen.abstract_nodesr:tuple)argr:s rr=r=+s@#t5<<== C ;s;;; r!c (eZdZUdZddddZdddd d dddd Zd ed <iddgfddgfddgfddgfddgfddgfddgfddgfddgfddgfd dgfd!dgfd"d#gfd$d%gfd&d%gfd'd#gfd(dd)gfid*d+gfd,d#gfd-d#d)gfd.d/gfd0d#d)gfd1d#d)gfd2d#gfd3d+gfd4d)gfd5d)gfd6d)gfd7d8gfd9d8gfd:d;gfdgfd?d>d#gfd@d)gfiZdlfdA ZdBZ dldCZ dldDZ dEZ dFZ dGZdHZdIZdJZdKZdLZdMZdNZdOZdPZdQZdRZdSZdTZdUZdVZfdWZdXZdYZ e Z!dZZ"dZ#d[Z$d\Z%d]Z&d^Z'd_Z(d`Z)daZ*dbZ+dcZ,ddZ-deZ.dfZ/dgZ0dhZ1diZ2djZ3dkZ4e4Z5e4Z6e4Z7e4Z8e4Z9e4Z:e4Z;e4Ze4Z?e4Z@e4ZAe4ZBe4ZCe4ZDe4ZEe4ZFe4ZGe4ZHe4ZIe4ZJxZKS)m CodePrinterz6 The base class for code-printing subclasses. z&&z||!)andornotNautoF_T)order full_precerror_on_reservedreserved_word_suffixhumaninlineallow_unknown_functionsstrictzdict[str, Any]_default_settingscottancscsinseccosacotatanacscasinasecacoscothexpcschsechacothlogacschasechcatalangamma fibonaccisqrtlucasbetasinc PiecewiseModfloor factorial factorial2 subfactorial uppergammaRisingFactorialFallingFactorialbinomialfracMaxMin Heavisideerf2erferfcLiliEi dirichlet_etazeta riemann_xiSingularityFunctionct|||jjdddk(r,|jjdddk(|jd<t |dst |_yy)N)settingsrXTrUreserved_words)superr _settingsgethasattrsetr)rr __class__s rr zCodePrinter.__init__tsj (+ >>  h - 5'+~~'9'9'4'HD'PDNN8 $t-."%%D /r!c0|jtdS)Ncnt|tr|jdjr|St |S)Nr)rDrr(is_realr)rHs rz5CodePrinter._handle_UnevaluatedExpr..}s2: 4"&)hhqk&9&9-0?A#wr!)replacerrexprs r_handle_UnevaluatedExprz#CodePrinter._handle_UnevaluatedExpr|s||B!GH Hr!c2 ddlm ddlm m  fdt |}||}j |}t_t_ j|j}jdrg}jr|jjdjj t#jt$D]5}|jjt'|j(7t#jt$D]&\}}|jj+||(||z}j-|}dj/|}n^j-|}jD chc]\}} |j| f} }} | jdj/|f}t_t_ |Scc} }w) a Print the expression as code. Parameters ---------- expr : Expression The expression to be printed. assign_to : Symbol, string, MatrixSymbol, list of strings or Symbols (optional) If provided, the printed code will set the expression to a variable or multiple variables with the name or names given in ``assign_to``. r MatrixSymbol) CodeBlock Assignmentc H| t|St|ttfrmt |t |k7r-t dj t |t |t||Dcgc]\}}||c}}St|tr,|jr|g|j}nSt|}nGt|ts7tdj tjt|||Scc}}w)Nz;Failed to assign an expression of length {} to {} variablesz%{} cannot assign to object of type {})r rDrErGlen ValueErrorformatzipstr is_Matrixshaperr TypeErrortyper.) r assign_tolhsrhsrrr_handle_assign_tors rrz.CodePrinter.doprint.._handle_assign_tos  t}$)dE]3t9I.$%b%i%ijmnrjsuxzCvD&EFF sSWYbOc"d83#4S##>"dee)S)>> ,Y D DI &y 1I 51 G N NT ++T)_!>??i. .#es:D rUzNot supported in {}:key )"sympy.matrices.expressions.matexprrsympy.codegen.astrrr=rr_not_supported_number_symbols_print splitlinesrappend _get_commentrlanguagesortedrrr._declare_number_const _format_codejoin)rrrlines frontlinesnamevalueresultr)r*num_symsrrrrs` @@@@rdoprintzCodePrinter.doprints D; / /"%T* y1++D1"e"u D!,,. >>' "J""!!$"3"3.55dmmD#FG"4#6#6C@ND%%d&7&7T 8K8K&LMN%d&:&:D K e!!$"<">  j$ / >224CG/5GGdWoG";;GD) 7?%%dC,?@D%%dA.Dkk),  ;  LL "$** T+JK LL  LL #( 0A!U#..q$7*.*G*G+' K$AJ"0DwQU0WAaffh0W07 >1>1? 2NPP%,"1 D#FF88I.",.B#CC X. Z0,79K9K )d"2:4 5 T%8%8%>? [1 Y/E"0 ( 0TyyG1X>s  I / I cddlm}||\}}||\}}|r|s|}||k7rtd|z|j||S)Nr) get_indicesz2lhs indices must match non-dummy rhs indices in %s)rrrr)rrrrrindsjunklindss rrz#CodePrinter._get_expression_indicessc,!$' t!), t E E>)+/01 1##E955r!c ddlm}|sgSi |D]}d |< |j|}|D]<}t|jD]"\}} |xx|j |z cc<$>t| fdS#t $rYBwxYw)Nr)Indexedc|Srr2)x score_tables rrz-CodePrinter._sort_optimized..5s [^r!r)sympy.tensor.indexedratoms enumerater_rate_index_positionKeyErrorr) rrrriarraysarrpindrs @rrzCodePrinter._sort_optimized s0I  AKN G$ C#CKK0 3$(A(A!(DD$  g#;<< s A<< BBctd)zfunction to calculate score based on position among indices This method is used to sort loops in an optimized order, see CodePrinter._sort_optimized() =This function must be implemented by subclass of CodePrinter.r)rrs rrz CodePrinter._rate_index_position7s "#=> >r!ctd)z1Formats a codestring with the proper line ending.rr)r codestrings rrzCodePrinter._get_statement@!#=> >r!ctd)z#Formats a text string as a comment.rr)rrs rrzCodePrinter._get_commentErr!ctd)z3Declare a numeric constant at the top of a functionrr)rrrs rrz!CodePrinter._declare_number_constJrr!ctd)z~Take in a list of lines of code, and format them accordingly. This may include indenting, wrapping long lines, etc...rr)rrs rrzCodePrinter._format_codeOs"#=> >r!ctd)zOReturns a tuple (open_lines, close_lines) containing lists of codelinesrr)rrs rrz$CodePrinter._get_loop_opening_endingVs"#=> >r!c|jjdrd|jzSd|j|jfzS)NDummy_rPz%s_%d)r startswith dummy_indexrs r _print_DummyzCodePrinter._print_Dummy\s< 99   )? "dii)9)9:: :r!c8|j|jSr)rlabelrs r _print_IdxzCodePrinter._print_Idxbs{{4::&&r!c|dj|jDcgc]}|j|c}Scc}w)Nr)rr(r)rrrs r_print_CodeBlockzCodePrinter._print_CodeBlockes+yy$)).s H3dkk# H)rrrrrop)rrrrs` r_print_AugmentedAssignmentz&CodePrinter._print_AugmentedAssignments`;;txx(;;txx(""#4:#4#4 H8TWWh*G H$JK Kr!cl|jddjfd|jDdS)N(, c3@K|]}j|ywrr!r"s rrAz2CodePrinter._print_FunctionCall..sFCt{{3'Fr#))rr function_argsrs` r_print_FunctionCallzCodePrinter._print_FunctionCalls. II IIF43E3EF GI Ir!c8|j|jSr)rsymbolrs r_print_VariablezCodePrinter._print_Variables{{4;;''r!ct||}||jvr=|jdrd}t |j |||jdzS|S)NrSzVThis expression includes the symbol "{}" which is a reserved keyword in this language.rT)r _print_Symbolrrrr)rrrmsgrs rr1zCodePrinter._print_Symbolsbw$T* 4&& &~~12< D!122$..)?@@ @Kr!cZ||jvxst|dj|dS)z Check if function ``name`` is either a known function or has its own printing method. Used to check if rewriting is possible.z _print_{}F)known_functionsr%r)rrs r _can_printzCodePrinter._can_prints0t+++]wt[=O=OPT=UW\/]]r!c |jjjvrj|jj}t|tr"|dj |j ddS|D]\}}||j sn ||j Dcgc]}j|dc}St|drBt|jtr(j|j|j S|jjjvrqj|jj\}}j|r:tfd|Dr&dj|j!|zdzS|j"rjj$j'ddrNj|jddj)t+j|j dSj-|Scc}w#t$r%|dj |j ddcYSwxYw) Nr'r(r*r_imp_c3@K|]}j|ywr)r5)r?rrs rrAz.CodePrinter._print_Function..s0Y1C0Yr#rWF)funcr.r4rDr stringifyr( parenthesizerrr7rr_rewriteable_functionsr5allrewrite is_Functionrrrmap_print_not_supported)rr cond_funccondr9itemtarget_f required_fss` r_print_FunctionzCodePrinter._print_Functions 99  !5!5 5,,TYY-?-?@I)S)#,dnnTYY.MNN"+JD$TYY'#R#TYY%WTd&7&7a&@%WXXT7 # 4::v(F;;ztzz49956 6 YY  4#>#> >$($?$? @R@R$S !Hkx(S0Y[0Y-YT[[h)?@@3FF    2 23Le T#{{4995tyyT[[RVR[R[A\7]^ ^,,T2 2&X$R+/ 41PQQRs$H2(H-H2-H22+I I c|j^}}|jD]0}|jrtd|jjzd|j jz}t ||d}|Y|jjddr,tdt|dt|d|zdz|j|St|}|jDcgc]}|| } }||j| Scc}w) NzL%s._print_Derivative(...) only supports functions with symbols as arguments.z_print_Derivative_%srXFUnsupported by : z Printer has no method: V Set the printer option 'strict' to False in order to generate partially printed code.) r( is_Symbolrrr.r9r%rrr8rrAdict) rrobjwrt_order_pairsfunc_arg meth_namepmethordersrH seq_orderss r_print_DerivativezCodePrinter._print_Derivatives $ o :H%% !o!%!8!8"9:: :+SXX->->> i. =~~!!(E24%d4j\DJ<@/ {;<mn ,,T2 2o&-0XX6cfSk6 6SXXz**7s( D c @|jjddr6|jt|j |jdS|j j |t|j |jdft|S)NrVF precision)rrrr evalfraddrrs r_print_NumberSymbolzCodePrinter._print_NumberSymbols >>  h .;;uTZZ{0K%LMN N  $ $ddjj !<=>&@ At9 r!c$|j|SrrZrs r_print_CatalanzCodePrinter._print_Catalan''--r!c$|j|Srr\rs r_print_EulerGammazCodePrinter._print_EulerGammar^r!c$|j|Srr\rs r_print_GoldenRatiozCodePrinter._print_GoldenRatior^r!c$|j|Srr\rs r_print_TribonacciConstantz%CodePrinter._print_TribonacciConstantr^r!c$|j|Srr\rs r _print_Exp1zCodePrinter._print_Exp1r^r!c$|j|Srr\rs r _print_PizCodePrinter._print_Pir^r!ct|djdzjfdt|jt DS)N %s rLc3BK|]}j|ywrr;r?aPRECrs rrAz)CodePrinter._print_And..s(6B7;6G6G46P6Brr _operatorsrrr(rrrros` @r _print_AndzCodePrinter._print_AndsK$//556B /?@6BB Br!ct|djdzjfdt|jt DS)NrjrMc3BK|]}j|ywrrlrms rrAz(CodePrinter._print_Or..s(5B6:5F5Fq$5O5Brprrqrss` @r _print_OrzCodePrinter._print_OrsK$..445B /?@5BB Br!cjjdj|jSt |djdzj fd|j DS)Nxorrjc3BK|]}j|ywrrlrms rrAz)CodePrinter._print_Xor..s&6$7;6G6G46P6$rprrrrto_nnfrrr(rss` @r _print_XorzCodePrinter._print_Xor si ??  u % -;;t{{}- -$//556$6$$ $r!cjjdj|jSt |djdzj fd|j DS)N equivalentrjc3BK|]}j|ywrrlrms rrAz0CodePrinter._print_Equivalent..s(=$>B=N=NqRV=W=$rpr{rss` @r_print_EquivalentzCodePrinter._print_Equivalentsi ??  | , 4;;t{{}- -$66<<=$=$$ $r!cvt|}|jd|j|jd|zS)NrNr)rrrr;r(rss r _print_NotzCodePrinter._print_Nots5$u%(9(9$))A,(MMMr!c@|j|jSr)rr|rs r_print_BooleanFunctionz"CodePrinter._print_BooleanFunctions{{4;;=))r!c:d|j|jzS)Nz isnan(%s)rr(rs r _print_isnanzCodePrinter._print_isnan [T[[#((333r!c:d|j|jzS)Nz isinf(%s)rrs r _print_isinfzCodePrinter._print_isinf#rr!ct|}|j\}}|dkrt| |}d}nd}g}g}g}|jdvr|j } nt j |} | D]} | jr| jr| jjr| jjr| jdk7r3|jt| j| j dt| j dj dk7r+t#| jt r|j| |jt| j| j  |j| |xst$j&g}t|dk(r0|dk(r+|j)|dd t*d t*d zzg} n|D cgc]} |j)| |} } |D cgc]} |j)| |} } |D]N} | j|vsd | |j-| jz| |j-| j<P|s|d j/| zSt|dk(r|d j/| zdz| dzS|d j/| zdd j/| zzScc} wcc} w)Nr-)oldnoneF)evaluateg?r rz(%s)*/z/(%s))r as_coeff_MulrrQas_ordered_factorsr make_argsis_commutativeis_Powrg is_Rational is_negativerr baserr(rDr Oner;rindexr)rrprecrr@signrnb pow_parenr(rDa_strrb_strs r _print_MulzCodePrinter._print_Mul&s$  "1 q5r1%DDD   ::_ ,**,D==&D D""t{{txx7K7KPTPXPXPdPd88r>HHSTXXIFG499Q<,,-2z$))S7Q!((.HHSTXXI67  L!%% q6Q;43; &&qtS*U2CJuDU2U-VWXE9:;AT&&q$/;E;567""1d+77 ODyyA~,2U177499;M5N,Naggdii() O#((5/) ) Vq[#((5/)C/%(: :#((5/)Gchhuo,EE E<7s )K K%c|jjddr&tdt|dt|dz |jj ||j|S#t $rYwxYw)NrXFrIrJrK)rrr8rrrYr emptyPrinterrs rrAz CodePrinter._print_not_supported`s >>  h .0!$t*RT |<ij      # #D )  &&   sA00 A<;A<r)Lr.r/r0r1rrrY__annotations__r<r rrrrrrrrrrrrrrr rrrr%r,r/r1r5rG _print_ExprrU_print_HeavisiderZr]r`rbrdrfrhrtrwr}rrrrrrrA _print_Basic_print_ComplexInfinity_print_ExprCondPair_print_GeometryEntity_print_Infinity_print_Integral_print_Interval_print_AccumulationBounds _print_Limit_print_MatrixBase_print_DeferredVector _print_NaN_print_NegativeInfinity _print_Order _print_RootOf_print_RootsOf_print_RootSum_print_Uniform _print_Unit _print_Wild_print_WildFunction_print_Relational __classcell__)rs@rrJrJ5s J" ##( )~ $ E2;$ E2;$ E2;$ VRL $ VRL $ VRL $ UBK$ UBK$ UBK$ eR[$ eR[$ eR[$ }$ &"$ fb\$ WbM!$" U[M*#$$ GR=%$& '2'$( 7[M2)$* \2.+$, +7-$. ;- 8/$0 " 1$2 WbM3$4 K$5$6 K$7$8 +r*9$: UBK;$< UBK=$> 4*?$@ 4*A$B fb\C$D 6G9-E$F "K#4G$L(HAFM ^ 6=.>> > > >> ; '>!.#IJK I ( ^ 38"K+*......B B $$N*448Ft '(L1.0*O*O*O 4'L,0%J2'L(M)N)N)N&K&K.,r!rJNc `ddlm}||j|j||S)aConverts an expr to a string of c 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. standard : str, optional String specifying the standard. If your compiler supports a more modern standard you may set this to 'c99' to allow the printer to use more math functions. [default='c89']. precision : integer, optional The precision for numbers such as pi [default=17]. user_functions : dict, optional A dictionary where the keys are string representations of either ``FunctionClass`` or ``UndefinedFunction`` instances and the values are their desired C string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)] or [(argument_test, cfunction_formater)]. See below for examples. dereference : iterable, optional An iterable of symbols that should be dereferenced in the printed code expression. These would be values passed by address to the function. For example, if ``dereference=[a]``, the resulting code would print ``(*a)`` instead of ``a``. 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 ccode, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> expr = (2*tau)**Rational(7, 2) >>> ccode(expr) '8*M_SQRT2*pow(tau, 7.0/2.0)' >>> ccode(expr, math_macros={}) '8*sqrt(2)*pow(tau, 7.0/2.0)' >>> ccode(sin(x), assign_to="s") 's = sin(x);' >>> from sympy.codegen.ast import real, float80 >>> ccode(expr, type_aliases={real: float80}) '8*M_SQRT2l*powl(tau, 7.0L/2.0L)' 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') >>> ccode(func(Abs(x) + ceiling(x)), standard='C89', user_functions=custom_functions) 'f(fabs(x) + CEIL(x))' or if the C-function takes a subset of the original arguments: >>> ccode(2**x + 3**x, standard='C99', 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(ccode(expr, tau, standard='C89')) if (x > 0) { tau = x + 1; } else { tau = 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])) >>> ccode(e.rhs, assign_to=e.lhs, contract=False, standard='C89') '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(ccode(mat, A, standard='C89')) A[0] = pow(x, 2); if (x > 0) { A[1] = x + 1; } else { A[1] = x; } A[2] = sin(x); r)c_code_printers)sympy.printing.crlowerr)rrstandardrrs rccoders.D1 ,?8>>+ ,X 6 > >tY OOr!c .tt|fi|y)z0Prints C representation of the given expression.N)printrrrs r print_ccoders % ! !"r!c >ddlm}||j||S)aKConverts an expr to a string of fortran 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 DEPRECATED. Use type_mappings instead. The precision for numbers such as pi [default=17]. user_functions : dict, optional A dictionary where keys are ``FunctionClass`` instances and values are their string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. 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]. source_format : optional The source format can be either 'fixed' or 'free'. [default='fixed'] standard : integer, optional The Fortran standard to be followed. This is specified as an integer. Acceptable standards are 66, 77, 90, 95, 2003, and 2008. Default is 77. Note that currently the only distinction internally is between standards before 95, and those 95 and after. This may change later as more features are added. name_mangling : bool, optional If True, then the variables that would become identical in case-insensitive Fortran are mangled by appending different number of ``_`` at the end. If False, SymPy Will not interfere with naming of variables. [default=True] Examples ======== >>> from sympy import fcode, symbols, Rational, sin, ceiling, floor >>> x, tau = symbols("x, tau") >>> fcode((2*tau)**Rational(7, 2)) ' 8*sqrt(2.0d0)*tau**(7.0d0/2.0d0)' >>> fcode(sin(x), assign_to="s") ' s = sin(x)' 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", ... "floor": [(lambda x: not x.is_integer, "FLOOR1"), ... (lambda x: x.is_integer, "FLOOR2")] ... } >>> fcode(floor(x) + ceiling(x), user_functions=custom_functions) ' CEIL(x) + FLOOR1(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(fcode(expr, tau)) if (x > 0) then tau = x + 1 else tau = x end if 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])) >>> fcode(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(fcode(mat, A)) A(1, 1) = x**2 if (x > 0) then A(2, 1) = x + 1 else A(2, 1) = x end if A(3, 1) = sin(x) r) FCodePrinter)sympy.printing.fortranrr)rrrrs rfcoders h4  ! ) )$ ::r!c .tt|fi|y)z|Prints the Fortran representation of the given expression. See fcode for the meaning of the optional arguments. N)rrrs r print_fcoders  % ! !"r!c `ddlm}||j|j||S)z$ C++ equivalent of :func:`~.ccode`. r)cxx_code_printers)sympy.printing.cxxrrr)rrrrrs rcxxcoders,4 . X^^- .x 8 @ @y QQr!c ddlm}||}|j|}t|tr4|j j D]\}}|j||}|j||S)aConverts an expr to a string of Rust 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 C string representations. Alternatively, the dictionary value can be a list of tuples i.e. [(argument_test, cfunction_string)]. See below for examples. dereference : iterable, optional An iterable of symbols that should be dereferenced in the printed code expression. These would be values passed by address to the function. For example, if ``dereference=[a]``, the resulting code would print ``(*a)`` instead of ``a``. 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 rust_code, symbols, Rational, sin, ceiling, Abs, Function >>> x, tau = symbols("x, tau") >>> rust_code((2*tau)**Rational(7, 2)) '8.0*1.4142135623731*tau.powf(7_f64/2.0)' >>> rust_code(sin(x), assign_to="s") 's = x.sin();' 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", 4), ... (lambda x: x.is_integer, "ABS", 4)], ... "func": "f" ... } >>> func = Function('func') >>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions) '(fabs(x) + x.ceil()).f()' ``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(rust_code(expr, tau)) tau = if (x > 0.0) { x + 1 } else { 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])) >>> rust_code(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(rust_code(mat, A)) A = [x.powi(2), if (x > 0.0) { x + 1 } else { x }, x.sin()]; r)RustCodePrinter) sympy.printing.rustr_rewrite_known_functionsrDrfunction_overridesvaluesrr)rrrrprintersrc_funcdst_funcs r rust_coderspX4h'G  + +D 1D$")"<"<"C"C"E 4 Hh<<(3D 4 ??4 ++r!c .tt|fi|y)z3Prints Rust representation of the given expression.N)rrrs rprint_rust_coder s )D %H %&r!)Nc99r)Nzc++11)/ __future__rtypingr functoolsr sympy.corerrr r r r sympy.core.basicr sympy.core.exprrrsympy.core.functionrsympy.core.mulrsympy.core.sortingrsympy.core.symbolr$sympy.functions.elementary.complexesrsympy.printing.strrsympy.printing.precedencerrr Exceptionr4rr8r=rJrrrrrrrr2r!rrs"77"1&&/$3)< . . i  %8 N -*N -jCPJ#u;p#R r,j'r!