K i? dZddlZddlZddlmZddlmZddlm Z m Z m Z m Z m Z mZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZmZmZdd lm Z m!Z!m"Z"m#Z#m$Z$ddl%m&Z&gdZ'GddZ(GddZ)e)dddddde)dddddde)dddddddZ*dZ+dGd Z,Gd!d"Z-Gd#d$e-Z.Gd%d&e.Z/Gd'd(Z0Gd)d*e.e0Z1Gd+d,e.e0Z2Gd-d.e-e0Z3Gd/d0Z4Gd1d2e5Z6Gd3d4e5Z7d5Z8Gd6d7e4Z9Gd8d9e9Z:Gd:d;e9Z;Gd<d=e4Z<Gd>d?e4Z=Gd@dAe4Z>GdBdCe4Z?dHdDZ@ dIdEZA dJdFZBy)Ka% module for generating C, C++, Fortran77, Fortran90, Julia, Rust and Octave/Matlab routines that evaluate SymPy expressions. This module is work in progress. Only the milestones with a '+' character in the list below have been completed. --- How is sympy.utilities.codegen different from sympy.printing.ccode? --- We considered the idea to extend the printing routines for SymPy functions in such a way that it prints complete compilable code, but this leads to a few unsurmountable issues that can only be tackled with dedicated code generator: - For C, one needs both a code and a header file, while the printing routines generate just one string. This code generator can be extended to support .pyf files for f2py. - SymPy functions are not concerned with programming-technical issues, such as input, output and input-output arguments. Other examples are contiguous or non-contiguous arrays, including headers of other libraries such as gsl or others. - It is highly interesting to evaluate several SymPy functions in one C routine, eventually sharing common intermediate results with the help of the cse routine. This is more than just printing. - From the programming perspective, expressions with constants should be evaluated in the code generator as much as possible. This is different for printing. --- Basic assumptions --- * A generic Routine data structure describes the routine that must be translated into C/Fortran/... code. This data structure covers all features present in one or more of the supported languages. * Descendants from the CodeGen class transform multiple Routine instances into compilable code. Each derived class translates into a specific language. * In many cases, one wants a simple workflow. The friendly functions in the last part are a simple api on top of the Routine/CodeGen stuff. They are easier to use, but are less powerful. --- Milestones --- + First working version with scalar input arguments, generating C code, tests + Friendly functions that are easier to use than the rigorous Routine/CodeGen workflow. + Integer and Real numbers as input and output + Output arguments + InputOutput arguments + Sort input/output arguments properly + Contiguous array arguments (numpy matrices) + Also generate .pyf code for f2py (in autowrap module) + Isolate constants and evaluate them beforehand in double precision + Fortran 90 + Octave/Matlab - Common Subexpression Elimination - User defined comments in the generated code - Optional extra include lines for libraries/objects that can eval special functions - Test other C compilers and libraries: gcc, tcc, libtcc, gcc+gsl, ... - Contiguous array arguments (SymPy matrices) - Non-contiguous array arguments (SymPy matrices) - ccode must raise an error when it encounters something that cannot be translated into c. ccode(integrate(sin(x)/x, x)) does not make sense. - Complex numbers as input and output - A default complex datatype - Include extra information in the header: date, user, hostname, sha1 hash, ... - Fortran 77 - C++ - Python - Julia - Rust - ... N)StringIO) __version__)SymbolSTupleEqualityFunctionBasic)c_code_printers)AssignmentError) FCodePrinter)JuliaCodePrinter)OctaveCodePrinter)RustCodePrinter)IdxIndexed IndexedBase) MatrixSymbolImmutableMatrix MatrixBase MatrixExpr MatrixSlice) is_sequence)RoutineDataTypedefault_datatypesget_default_datatypeArgument InputArgumentOutputArgumentResultCodeGenCCodeGenFCodeGen JuliaCodeGen OctaveCodeGen RustCodeGencodegen make_routinec@eZdZdZdZdZeZedZedZ y)raGeneric description of evaluation routine for set of expressions. A CodeGen class can translate instances of this class into code in a particular language. The routine specification covers all the features present in these languages. The CodeGen part must raise an exception when certain features are not present in the target language. For example, multiple return values are possible in Python, but not in C or Fortran. Another example: Fortran and Python support complex numbers, while C does not. c t}t}|D]}t|trF|j|jj |jj tz Zt|tr|j|jt|tra|j|j|j|jj |jj tz td|z|D]e} t| tstd| z|j| jj | jj tz gt} |D]} t| tra|j| jj | jj tz | j| jt| j| |D chc] } t| tr | jn| "}} |j!|j#| j#|} | tk7r4tddj%| D cgc] } t'| c} z||_ ||_||_||_||_ycc} wcc} w)aInitialize a Routine instance. Parameters ========== name : string Name of the routine. arguments : list of Arguments These are things that appear in arguments of a routine, often appearing on the right-hand side of a function call. These are commonly InputArguments but in some languages, they can also be OutputArguments or InOutArguments (e.g., pass-by-reference in C code). results : list of Results These are the return values of the routine, often appearing on the left-hand side of a function call. The difference between Results and OutputArguments and when you should use each is language-specific. local_vars : list of Results These are variables that will be defined at the beginning of the function. global_vars : list of Symbols Variables which will not be passed into the function. zUnknown Routine argument: %szUnknown Routine result: %sz+Symbols needed for output are not in input , N)set isinstancer updateexpr free_symbolsatomsrraddname InOutArgument ValueErrorr!rlabel differenceunionjoinstr argumentsresults local_vars global_vars)selfr4r<r=r>r? input_symbolssymbolsargr local_symbolss notcoveredxs ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/utilities/codegen.py__init__zRoutine.__init__sK@ % GC#~.sxx44sxx~~g7NNOC/!!#((+C/!!#((+sxx44sxx~~g7NNO !?#!EFF G HAa( !=!ABB NN166..g1FF G H   %A!V$qvv22QVV\\'5JJK!!!&&)!!!$  %BIIAjC0177a7II ''    . 4 4[ AC  J!YY 'C1A'CDEF F " $&J(Ds %KKch|jjdjdi|jzS)Nz?({name!r}, {arguments}, {results}, {local_vars}, {global_vars})) __class____name__format__dict__r@s rI__str__zRoutine.__str__sD~~&&)q)j)q)q*CtxuBuB*CC Cct|j}|jd|jD|jd|jD|S)zReturns a set of all variables possibly used in the routine. For routines with unnamed return values, the dummies that may or may not be used will be included in the set. c34K|]}|jywNr4).0rCs rI z$Routine.variables..s4c4c34K|]}|jywrV) result_var)rXress rIrYz$Routine.variables..s8C8rZ)r-r>r/r<r=)r@vs rI variableszRoutine.variablessC   4T^^44 84<<88rSc|jDcgc]}t|ttfs|}}|j |j |Scc}w)zReturns a list of OutputArgument, InOutArgument and Result. If return values are present, they are at the end of the list. )r<r.r r5extendr=)r@rCargss rIresult_variableszRoutine.result_variablessL $~~3 .-02233 DLL! 3s AAN) rN __module__ __qualname____doc__rJrR__repr__propertyr_rcrLrSrIrrusA I'VCH   rSrceZdZdZdZy)rz? ? jeT]CFH H ~~__&&ooOO  %"rScN|jjd|jdS)N())rMrNr4rQs rIrRzVariable.__str__Js>>22DII>>rSc|jSrV)rrQs rIr4z Variable.nameOs zzrSc |j|jS#t$r(tddj |jzwxYw)aQReturns the datatype string for the requested language. Examples ======== >>> from sympy import Symbol >>> from sympy.utilities.codegen import Variable >>> x = Variable(Symbol('x')) >>> x.get_datatype('c') 'double' >>> x.get_datatype('fortran') 'REAL*8' zHas datatypes for languages: %sr,)rupperKeyError CodeGenErrorr:)r@languages rI get_datatypezVariable.get_datatypeSsQ />>(.."23 3 /@IIdnn- ./ / /s 1ANNN) rNrdrerfrJrRrgrhr4rrLrSrIrrs.&*#X?H /rSrceZdZdZy)rz{An abstract Argument data structure: a name and a data type. This structure is refined in the descendants below. N)rNrdrerfrLrSrIrris   rSrc eZdZy)rNrNrdrerLrSrIrrrrSrc eZdZdZdZdZeZy) ResultBasezBase class for all "outgoing" information from a routine. Objects of this class stores a SymPy expression, and a SymPy object representing a result variable that will be used in the generated code only if necessary. c ||_||_yrV)r0r\)r@r0r\s rIrJzResultBase.__init__~s $rSch|jjd|jd|jdSNrr,r)rMrNr0r\rQs rIrRzResultBase.__str__s&#~~66 OO rSNrNrdrerfrJrRrgrLrSrIrrvs%HrSrc"eZdZdZddZdZeZy)r z5OutputArgument are always initialized in the routine.Ncdtj|||||tj|||y)arReturn a new variable. Parameters ========== name : Symbol, MatrixSymbol The name of this variable. When used for code generation, this might appear, for example, in the prototype of function in the argument list. result_var : Symbol, Indexed Something that can be used to assign a value to this variable. Typically the same as `name` but for Indexed this should be e.g., "y[i]" whereas `name` should be the Symbol "y". expr : object The expression that should be output, typically a SymPy expression. datatype : optional When not given, the data type will be guessed based on the assumptions on the symbol argument. dimensions : sequence containing tuples, optional If present, the argument is interpreted as an array, where this sequence of tuples specifies (lower, upper) bounds for each index of the array. precision : int, optional Controls the precision of floating point constants. N)rrJrr@r4r\r0rrrs rIrJzOutputArgument.__init__s-D $h IFD$ 3rSc|jjd|jd|jd|jdSr)rMrNr4r\r0rQs rIrRzOutputArgument.__str__s*#'>>#:#:DIItX\XaXabbrSrrrLrSrIr r s?#4JcHrSr cXeZdZdZddZejje_dZeZy)r5z3InOutArgument are never initialized in the routine.Nc~|s t|}tj|||||tj|||yrV)rrrJrrs rIrJzInOutArgument.__init__s7+D1H$h IFD$ 3rSc|jjd|jd|jd|jdSr)rMrNr4r0r\rQs rIrRzInOutArgument.__str__,#'>>#:#:DIItyy OO rSr)rNrdrerfrJr rRrgrLrSrIr5r5s,=4 &..66HHrSr5c&eZdZdZ ddZdZeZy)r!a9An expression for a return value. The name result is used to avoid conflicts with the reserved word "return" in the Python language. It is also shorter than ReturnValue. These may or may not need a name in the destination (e.g., "return(x*y)" might return a value without ever naming it). Nct|ttfs td|dt t |z}| t |}t|tr8t|ttfrt|g|j}n t|}||}tj|||||tj|||y)aInitialize a return value. Parameters ========== expr : SymPy expression name : Symbol, MatrixSymbol, optional The name of this return variable. When used for code generation, this might appear, for example, in the prototype of function in a list of return values. A dummy name is generated if omitted. result_var : Symbol, Indexed, optional Something that can be used to assign a value to this variable. Typically the same as `name` but for Indexed this should be e.g., "y[i]" whereas `name` should be the Symbol "y". Defaults to `name` if omitted. datatype : optional When not given, the data type will be guessed based on the assumptions on the expr argument. dimensions : sequence containing tuples, optional If present, this variable is interpreted as an array, where this sequence of tuples specifies (lower, upper) bounds for each index of the array. precision : int, optional Controls the precision of floating point constants. z.The first argument must be a SymPy expression.Nz result_%d)rrr)r.r rrabshashrr;rrshaperrrJr)r@r0r4r\rrrs rIrJzResult.__init__sD$ 34LM M <T$Z0D  +D1H dC $Z 89#D64::6d|  J$x%/9  FD$ 3rSc|jjd|jd|jd|jdSr)rMrNr0r4r\rQs rIrRzResult.__str__ rrS)NNNNNrrLrSrIr!r!s#CG,074rHrSr!cHeZdZdZdZdZd dZdZd dZd dZ d dZ dd Z y)r"z'Abstract class for the code generators.Nc8|jj|SrV)printer indent_coder@ codeliness rI _indent_codezCodeGen._indent_codes||'' 22rScf|xsi}|Dcic]}||jj|}}|jD]\}}||jj|< t|j||i|}|jD]\}}||jj|< |Scc}wrV)r _settingsitemsgetattr) r@methodsettingsrbkwargskorir^results rI_printer_method_with_settingsz%CodeGen._printer_method_with_settings s>r5=>q$,,((++>>NN$ *DAq()DLL " "1 % *.v.??IIK *DAq()DLL " "1 % * ?s!B.c|jjdr+|jj|}|j S|jj|\}}}|s|rtdt |z|j S)z&Returns the symbol as fcode prints it.humanzFailed to print %s)rrdoprintr6r;strip)r@rFexpr_str constants not_supporteds rI _get_symbolzCodeGen._get_symbol*s{ << ! !' *||++A.H ~~261E1Ea1H .I}hM !5A!>??~~rSc ||_||_y)zInitialize a code generator. Derived classes will offer more options that affect the generated code. Nprojectcse)r@rrs rIrJzCodeGen.__init__4s rSc  |jrRddlm}t|rt|tt fs|s t d|D](}|jrtdj||Dcgc]}|j}}||\}} t|| Dcgc]\}}t|j|}}}nLt|tr/||j\}} t|j| d}n ||\}} | }|D cgc]\} } t| | } } } |D chc]\} } |  }} } t|D cgc]\} } |  c} } }n t}t|r,t|tt fs|s t dt|}n t|}|jrC|j!t"Dchc]}|j$c}t'k7r9td|j!t"Dchc]}|j$} }| }| t'n t'|}|j(|j(zz |z }t'}|j+||D]m}t|t"r9|j-||j+|j.dj(t|t0s]|j-|o|}g}g}|D] }t|trE|j}|j}t|t0rMt3|j4Dcgc]}t6j8|dz fc}}|j:j$}nit|t<rg}|}nTt|t>r9t3|j4Dcgc]}t6j8|dz fc}}|}n td|jA|r|jCtE||||n|jCtG||||| vsG|j-|Zt|tHtJfrt?d tMtO|zg|j4}t3|j4Dcgc]}t6j8|dz fc}}|jCtG|||||jCt| g}d }i}|j!t0|j!t0zD]}|||j:j$<|j!t>|j!t>zD]}|||< tQ|tR D]3}||vr||}d ||i}ni}|jCtU|fi|5|jWd |jY||g}|D]?} t| tZr|jC| j$/|jC| A|}|D!cgc]}!|!j\|vs|!}"}!|"rOd}#|#jdj_|"D$cgc]}$tS|$j\c}$}#ta|#|"|D!cic]}!|!j\|!}%}!g}&|D]} |&jC|%||&}te||| |Scc}wcc}}wcc} } wcc} } wcc} } wcc}wcc}wcc}wcc}wcc}wcc}!wcc}$wcc}!w#tb$rAt|tZt>fr d ||i}ni}|&jCtU|fi|YwxYw)aqCreates an Routine object that is appropriate for this language. This implementation is appropriate for at least C/Fortran. Subclasses can override this if necessary. Here, we assume at most one return value (the l-value) which must be scalar. Additional outputs are OutputArguments (e.g., pointers on right-hand-side or pass-by-reference). Matrices are always returned via OutputArguments. If ``argument_sequence`` is None, arguments will be ordered alphabetically, but with all InputArguments first, and then OutputArgument and InOutArguments. r)rNo expression givenz7Lists of expressions must all be Equalities. {} is not.z9CSE and Indexed expressions do not play well together yetBOnly Indexed, Symbol, or MatrixSymbol can define output arguments.rzout_%scf|jDcgc]}tj|dz fc}Scc}wNr)rrZero)rFdims rIrz#CodeGen.routine..dimensionss'129#QVVS1W%9 99s.keyrc,t|jSrVr;r4rHs rIz!CodeGen.routine..s166{rS"Argument list didn't specify: {0} r,)3rsympy.simplify.cse_mainrr.rrr6 is_EqualityrrOrhsziprlhsr!rr2rr7r-r1r/removerbrrrrrbaserrhasappendr5r rrrrsortedr;rsortrarr4r:CodeGenArgumentListErrorrr)'r@r4r0argument_sequencer?rercommon simplifiedabr>_rElocal_expressions expressionsirB new_symbolssymbol return_val output_argsout_argrdimsarg_listr array_symbolsarraymetadata new_sequencerCrHmissingmsgm name_arg_dictnew_argss' rIroutinezCodeGen.routine>s 88 34 D:z:R)S$%:;;pA==*+d+k+klm+noop '++quu++%(X" #>#>?&'*""6*  +   # 0D$)((xxgw/  !NAFFC!G#4!NOD$\\//F0D$F6  !NAFFC!G#4!NOD$F&(FGG88F#&&%fgtMO &&&vwNP+NN6*D?K"@A&x#d4j/'AODJJO7==ICqvvsQw/IJ"""7GTdKM!!&,/G# 0J  :  &&w/2C2I2I'2RR 4E.3M%**** + 4 &&|47H7N7N|7\\ )E#(M%  )W#. ?F&%f-(*U*;< OOM&=H= > ? 23 $  (L( -c;/ '' 2 '',  - !- "*NQaff  ? MFFs B&&B/ c|j|}|D]}|r|jd|j|j||j|j ||j|j ||j|j ||r|jd|j|j||r|jd|j|j||jdj|}|r#dj|j|gz}|r|j|yy)a(Write the code by calling language specific methods. The generated file contains all the definitions of the routines in low-level code and refers to the header file if appropriate. Parameters ========== routines : list A list of Routine instances. f : file-like Where to write the file. prefix : string The filename prefix, used to refer to the proper header file. Only the basename of the prefix is used. header : bool, optional When True, a header comment is included on top of each source file. [default : True] empty : bool, optional When True, empty lines are included to structure the source files. [default : True]  rrN) _preprocessor_statementsrra_get_routine_opening_declare_arguments_declare_globals_declare_locals _call_printer_get_routine_endingrr: _get_headerr)r@rrrrr code_linesr s rI dump_codezCodeGen.dump_codes>:226:  AG!!$'   d77@ A   d55g> ?   d33G< =   d227; <!!$'   d009 :!!$'   d66w? @ A&&rwwz':; !1!1!3zl!BCJ  GGJ  rSrV)rF)NN)FTTTT) rNrdrerfrrrrrJr rr&rLrSrIr"r"s11G3 lL\)V3 rSr"c eZdZy)rNrrLrSrIrrMrrSrceZdZedZy)rc |jdSr)rbrQs rI missing_argsz%CodeGenArgumentListError.missing_argsRsyy|rSN)rNrdrerhr+rLrSrIrrQs rSrz{Code generated with SymPy %(version)s See http://www.sympy.org/ for more information. This file is part of '%(project)s' ceZdZdZdZdZdZ dfd ZdZdZ dZ d Z d Z d Z d Zd ZdZddZee_ej(je_ddZee_eegZxZS)r#zGenerator for C code. The .write() method inherited from CodeGen will output a code file and an interface file, .c and .h respectively. chc99ct||||xs%t|jj |_||_| dg|_yy)Nrz#include )superrJr standardlowerrpreprocessor_statements)r@rrr4rrMs rIrJzCCodeGen.__init__ksT c2J/$--2E2E2G"H"J '>$ " *,?+@D ( +rScg}|jdtt|jdz}|j D]%}|jd|j dz'|jd|S)/Writes a common header for the generated files.zP/****************************************************************************** versionrz *%s* LzQ ******************************************************************************/ rheader_comment sympy_versionr splitlinescenterr@r%tmplines rIr$zCCodeGen._get_headertst -.=+/<< 99NN$ ;D   i$++b/9 : ;./rScjt|jdkDr tdt|jdk(r|jdjd}nd}g}|jD]}|j j |j}|jst|tr&|j|jdd|zfj|j|jd|fdj|Dcgc]}d|z c}}|d |jd |d Scc}w) Returns a string for the function prototype of the routine. If the routine has multiple result objects, an CodeGenError is raised. See: https://en.wikipedia.org/wiki/Function_prototype rz,C only supports a single or no return value.rrvoid*%sr,z%s %s rr) lenr=rrr<rrr4rr.rrr:)r@r ctype type_argsrCr4tr<s rI get_prototypezCCodeGen.get_prototypes  w ! #MN N  !Q &OOA&33C8EE $$ @C<<''1D~~C!<  #"2"23"7!FG  #"2"23"7!>?  @ IIY?! ?@ #W\\9==@s D0cg}|jdjtjj ||j |j |Dcgc]}dj|}}|Scc}w)Nz#include "{}.h"z{} )rrOospathbasenamerar4)r@rr%ls rIrz!CCodeGen._preprocessor_statementssk +222773C3CF3KLM$6670:;1fmmA&; ;r!r\r"rOrr0rrrr;rr)r@r r]rCr%rr`rJrrrnot_cc_exprr4values rIr!zCCodeGen._declare_localss  $$ -C#z*3>>""388, - (( ?Fff-{{f///IPPQWXYY I##C(A&++ J'?@{{((!!."7"73y>4PQ7SWXYSZ?"[\$++A.'+'I'IU;RWX y(J(2 $Iuf &iS9 M e!!tU"KL M   hooff= >3 ?6rSc g}g}|jD];}t|ts|jr!|j |j =d}|j D]}t|trM|j dz}|jd}|j dj|t||}n |j} |jdd|dd|j|\} } } t| t D]\} } |j d | d | d |j d | z|r|j d|z|S#t$re|j}|j |jddt|d |jdd|dd|j|\} } } YwxYw)N_resultr-z{} {}; rFr\r_rFrcrrarb%s z return %s; )r<r.rrrr4rcr!rrOr;r\rr0r r)r@r r%r]rCrrr`rJrrdrer4rfs rIr"zCCodeGen._call_printers  $$ -C#z*3>>""388, - .. /F&&)#LL94 '',!!*"3"3As9~"FG& "--  6+/+M+M{V[\KK9,N,6( 5& &iS9 M e!!tU"KL M   fvo ./ /2    /*< =# 6"-- !!"("5"5c":C NKM+/+M+M{V[\KK9,N,6( 5&  6s 'EA+F>=F>cdgSNz} rLrXs rIr#zCCodeGen._get_routine_ending wrSc.|j|||||yrVr&r@rrrrrs rIdump_czCCodeGen.dump_c xFFE:rSc|r*tdj|j||jj ddj d|j ddj d}|r t|td|z|td |z||r t||D]#}|j |}td |z|%|r t|td ||r t|y y ) aWrites the C header file. This file contains all the function declarations. Parameters ========== routines : list A list of Routine instances. f : file-like Where to write the file. prefix : string The filename prefix, used to construct the include guards. Only the basename of the prefix is used. header : bool, optional When True, a header comment is included on top of each source file. [default : True] empty : bool, optional When True, empty lines are included to structure the source files. [default : True] rrfilerFr__/__Hz #ifndef %sz #define %sz%s;z#endifN)printr:r$rreplacerrK) r@rrrrr guard_namer rUs rIdump_hzCCodeGen.dump_hs6  "''$**,-A 6$(LL$8$8 %eg%%~~c37==?A   qM lZ'a0 lZ'a0  qM -G**73I %)#! , -  qM hQ  qM rS)rNNFr')rNrdrerfcode_extensioninterface_extensionr2rJr$rKrrrr r!r"r#rprr"r&r{r  __classcell__rMs@rIr#r#_sNH2638A >4&&P'R;%F&&..FN/`+FHrSr#ceZdZdZy) C89CodeGenC89NrNrdrer2rLrSrIrr;HrSrceZdZdZy) C99CodeGenC99NrrLrSrIrr>rrSrceZdZdZdZdZdfd ZdZdZdZ dZ d Z d Z d Z d Zd ZdZddZee_ej(je_ddZee_eegZxZS)r$zGenerator for Fortran 95 code The .write() method inherited from CodeGen will output a code file and an interface file, .f90 and .h respectively. f90r.cJt|||xs t|_yrV)r1rJr rr@rrrMs rIrJzFCodeGen.__init__Ls !0,. rScg}|jdtt|jdz}|j D]%}|jd|j dz'|jd|S)r6zP!****************************************************************************** r7z!*%s* r9r:r?s rIr$zFCodeGen._get_headerPst -.=|| %%NN$ ;D   i$++b/9 : ;-.rScgSrVrLr@rs rIrz!FCodeGen._preprocessor_statements[ rScbg}t|jdkDr tdt|jdk(rA|jd}|j|j d|jdn|jddj fd|j D}d j|j|}d j tj|d d dz}|j|dj |g}|jd|S)z6Returns the opening statements of the fortran routine.rz2Fortran only supports a single or no return value.rfortranfunction subroutiner,c3ZK|]"}dj|jz$yw)%sN)rr4)rXrCr@s rIrYz0FCodeGen._get_routine_opening..ks-6 0 0 ::6s(+z{}({}) z & <F)widthbreak_long_wordsrrFzimplicit none ) rGr=rrrr:r<rOr4textwrapwrap)r@r  code_listrrbcall_sigs` rIrzFCodeGen._get_routine_opening^s w ! #DF F  !Q &__Q'F   V00; <   Z (   \ *yy6#*#4#466$$W\\48;;x}}X35>C EFHLM "XXi() *+rSc g}g}g}|jD]?}t|trd|jdz}nat|trd|jdz}n.>y.IIC/.1A1A)1LLC0,s/?/? /JJ"#>c#JKK%%F~~"~~$/3q6A:&s1vz(:%<$/0-66!!(F388r;rrrlr)r@r rvarrs rIr!zFCodeGen._declare_localss\ ',,#6 8C+C0H    0 0 57 8 8rSc>t|jdk(rdgSdgS)z6Returns the closing statements of the fortran routine.rz end function zend subroutine )rGr=rXs rIr#zFCodeGen._get_routine_endings% w 1 $$% %&' 'rSc dg}|j|j||j|j||j|j||j ddj |S)aReturns a string for the function interface. The routine should have a single result object, which can be None. If the routine has multiple result objects, a CodeGenError is raised. See: https://en.wikipedia.org/wiki/Function_prototype z interface zend interface rr)rarrr#rr:rTs rI get_interfacezFCodeGen.get_interfacesu$% 227;<009:11':;*+wwy!!rSc g}g}|jD]'}t|tr |j}n"t|tt fr |j }|jdddddd|j\}}}t|tD]4\} } t| } |j| jd| d | d 6t|tD]M} t| } t| tr | j} n| } |j| jd | d O|jd |z*||zS) NrFfree_)r source_formatr2r^r_rz, parameter :: rbrrri)rcr.r!r4r r5r\rr0rr;rrrlr func) r@r  declarationsr%rr`r not_fortranf_exprobjr^rJr4s rIr"zFCodeGen._call_printers=  .. /F&&)#LL F^]$CD"-- -1-O-OUVQS_de y.P.2 *I{F!4 FQ(-##45GGS!DF Fks3 D(-c8,88DD##AGGT$BC  D   fvo .- /.j((rSc0|jddddd|S)NrFr)rrr^rrs rIrzFCodeGen._indent_codes&11 UVuUW`b brSc |D]}|jDchc]}t|j}}|jDchc] }t|} }t|t| ksmt ddj |jD cgc] } t| c} z|j |||||ycc}wcc}wcc} w)Nz%Fortran ignores case. Got symbols: %sr,)r_r;r3rGrr:r&) r@rrrrrrDrH lowercase orig_casers rIdump_f95zFCodeGen.dump_f95s HA12=AQ=I=)*5AQ5I59~I."#J #DCH#DE$GHH  H xFFE: >5$Es CC Cc|r*tdj|j||r t||D]$}|j|}|j |&|r t|yy)afWrites the interface to a header file. This file contains all the function declarations. Parameters ========== routines : list A list of Routine instances. f : file-like Where to write the file. prefix : string The filename prefix. header : bool, optional When True, a header comment is included on top of each source file. [default : True] empty : bool, optional When True, empty lines are included to structure the source files. [default : True] rrrsN)rxr:r$rr)r@rrrrrr rUs rIr{zFCodeGen.dump_hsi4  "''$**,-A 6  qM G**73I GGI    qM rSrNr')rNrdrerfr|r}rJr$rrrr r!r#rr"rrrr"r&r{r r~rs@rIr$r$AsN1 6 D ("$)8b;(H((00H#H+F&!HrSr$ceZdZdZdZdfd ZdZdZdZdZ dZ d Z d Z d Z d Zd ZddZee_ej&je_egZxZS)r%zxGenerator for Julia code. The .write() method inherited from CodeGen will output a code file .jl. jlcJt|||xs t|_yrV)r1rJrrrs rIrJzJuliaCodeGen.__init__"s  !4"2"4 rSc \t|r,t|ttfs|s t dt |}n t |}|j tDchc]}|j}}| tn t|}|j|z |z }t} |D]]} t| tr)| j| jdj.ZrrSrrr,),rr.rrr6rr2rr7r-r1r/rbrr3 enumeraterrrrrrOnerrr5rrrr!rrrrrr;rrr4rOr:rrr)r@r4r0rr?rrr> old_symbolsrBrF return_valsrrrrrrrrrrCrHrrrrrs rIr zJuliaCodeGen.routine&s t Zz:6N%O !677,K+K(3'8'8'=>!agg> > +2ceK8H "..;kI % A!S!qvvay5567+ A    ";/ GIQ$)((xx gw/ 7==!ICAEE3$233# }=> D4#3#3CHH#==>  ? yyw||T:;ggi(* rScgSrVrLrXs rIrzJuliaCodeGen._declare_argumentsrrScgSrVrLrXs rIr zJuliaCodeGen._declare_globalsrrScgSrVrLrXs rIr!zJuliaCodeGen._declare_localsrrScg}|jD]J}t|tr|j|j}n t d|j |Lddj|zdzgS)N$unexpected object in Routine resultszreturn r,z end )r=r.r!rr4rrr:)r@r outsrrFs rIr#z JuliaCodeGen._get_routine_endingsloo F&&)$$V[[1"#IJJ KKN  DIIdO+i788rScg}g}|jD]}t|tr |j}n t d|j dddd|j |\}}}t|tD]\} } |j| d| dt|tD]5} t| tr | j} n| } |jd | z7|jd |z||zS) NrrFrr^r_rrbrz# unsupported: %s ri r=r.r!r\rrr0rr;rr r) r@r rr%rr`rrjl_exprrr^r4s rIr"zJuliaCodeGen._call_printers   oo 2F&&)"-- "#IJJ040R0RUe ?}}Y''rSc.|j|||||yrVrnros rIdump_jlzJuliaCodeGen.dump_jlrqrSrr')rNrdrerfr|rJr r$rrrr r!r#r"rrrr"r&r r~rs@rIr%r%stN5YMv & 9)2( ;'G''//GOyHrSr%ceZdZdZdZdfd ZdZdZdZdZ dZ d Z d Z d Z d Zd ZddZee_ej&je_egZxZS)r&aGenerator for Octave code. The .write() method inherited from CodeGen will output a code file .m. Octave .m files usually contain one function. That function name should match the filename (``prefix``). If you pass multiple ``name_expr`` pairs, the latter ones are presumed to be private functions accessed by the primary function. You should only pass inputs to ``argument_sequence``: outputs are ordered according to their order in ``name_expr``. rcJt|||xs t|_yrV)r1rJrrrs rIrJzOctaveCodeGen.__init__s  !5"3"5 rSc nt|r,t|ttfs|s t dt |}n t |}|j tDchc]}|j}}| tn t|}|j|z |z }t} |D]]} t| tr)| j| jdj|vs|}}|rOd}|jAd jC|Dcgc]}t9|j>c}}tE|||Dcic]}|j>|}}g}|D]} |j/|| |}tI||| ||Scc}wcc}wcc}wcc}w#tF$r|j/t;| YdwxYw) z(Specialized Routine creation for Octave.rrrrrrWrrr,)%rr.rrr6rr2rr7r-r1r/rbrr3rrrrrrrrrr!rrrr;rrr4rOr:rrr)r@r4r0rr?rrr>rrBrFrrrrrrrrCrHrrrrrs rIr zOctaveCodeGen.routines{ t Zz:6N%O !677,K+K(3'8'8'=>!agg> > +2ceK8H "..;kI % A!S!qvvay5567+ A   ";/ GIQ$)((xx gw/$\\//F!'GV\+JK&(FGG""6$V#PQxx'NN6*""6$W!_#EF' G,  &&w/ 4E.3M%**** + 4 &&|4 )E#(M%  )W#. 3F OOM&1 2 3  (L( -c;/ '' 2 '',  - !- "*NQaffN 5N N#N43N4cg}tt|jdz}|jD]-}|dk(r|j d|j d|z/|S)r6r7rrz% z%% %s rr?s rIr$zOctaveCodeGen._get_headerQse =|| %%NN$ 6Drz!!%(!!+"45  6 rScgSrVrLrs rIrz&OctaveCodeGen._preprocessor_statements]rrSc Dg}|jdg}|jD]J}t|tr|j |j }n t d|j|Lt|dkDr'|jddj|zdzn |jdj||jdg}|jD]v}t|ttfr t d tt|zt|tsJ|jd |j |j zxdj|}|j|j d |d dj|g}|S) rrrr[r,]rrrbz#Octave: invalid argument of type %srrr)rr=r.r!rr4rrGr:r<r r5r;rr)r@r rrrrFrbrCs rIrz"OctaveCodeGen._get_routine_opening`sg %oo F&&)$$V[[1"#IJJ KKN   t9q=   SDIIdO4s: ;   RWWT] +$$ ?C# >?"#H#&tCy>$233#}- D4#3#3CHH#==>  ? yyw||T:;ggi(* rScgSrVrLrXs rIrz OctaveCodeGen._declare_argumentsrrSc |jsgSdjt|jDcgc]}|j|c}}d|zdzgScc}w)NrFzglobal r)r?r:rr)r@r grFs rIr zOctaveCodeGen._declare_globalssW""I HHV':M:MNQT--a0NO PA $%%OsA cgSrVrLrXs rIr!zOctaveCodeGen._declare_localsrrScdgS)Nzend rLrXs rIr#z!OctaveCodeGen._get_routine_endings yrSc g}g}|jD]}t|tr |j}n t d|j dddd|j |\}}}t|tD]\} } |jd| d| d t|tD]5} t| tr | j} n| } |jd | z7|jd |z||zS) NrrFrr_rz rbz; % constant z %% unsupported: %s rir) r@r rr%rr`rroct_exprrr^r4s rIr"zOctaveCodeGen._call_printers   oo 3F&&)"-- "#IJJ151S1SUe.>.@&AB   d55g> ?   d33G< =   d227; <!!$'   d009 :!!$'   d66w? @) A,&&rwwz':;  GGJ  rSr)TTT)rNrdrerfr|rJr r$rrrr r!r#r"rrrr"r&r r~rs@rIr&r&sw N6XMt  D& )2I @&F&&..FNxHrSr&ceZdZdZdZdfd ZdZdZdZdZ dZ d Z d Z d Z d Zd ZddZee_ej&je_egZxZS)r'zvGenerator for Rust code. The .write() method inherited from CodeGen will output a code file .rs rscLt|||xs t|_y)N)r)r1rJrrrs rIrJzRustCodeGen.__init__s" )3/"3 rSc t|r,t|ttfs|s t dt |}n t |}|j tDchc]}|j}}| tn t|}|j|z |z |j tz }g} g} t|D]1\}}t|tr|j} |j}| } t| trgt!| j"D cgc]} t$j&| fc} }| j(j} | j+t-| | ||t| tt.t0fs t3d| j+t5|| | |j7| r|j9| | j+t5|d|dzz4| j;d t=| }i}|j tD]}|||j(j<|j t0D]}|||< t?|t@ D]} |j+tC| |g}|D]?}t|tDr|j+|j/|j+|A|}|Dcgc]}|jF|vs|}}|rOd }|jId jK|Dcgc]}tA|jFc}}tM|||Dcic]}|jF|}}g}|D]} |j+|| |}tQ||| ||Scc}wcc} wcc}wcc}wcc}w#tN$r|j+tC| YiwxYw) z&Specialized Routine creation for Rust.rrrrrrrWc,t|jSrVrrs rIrz%RustCodeGen.routine..rrSrrr,))rr.rrr6rr2rr7r-r1rrrrrrrrrrrr5rrrr!rrrrrr;rrr4rOr:rrr)r@r4r0rr?rrr>rBrrrrrrrrrrrCrHrrrrrs rIr zRustCodeGen.routines t Zz:6N%O !677,K+K(3'8'8'=>!agg> > +2ceK8H **Z7+E HYHYZaHbb  ";/ GIQ$)((xx gw/ 7==!ICAEE3rstripr?s rIr$zRustCodeGen._get_header9s &!=+/<< 99NN$ JD   v B7??ADH I J'"rSc|jDcgc]}|jd}}t|dk(r d|dz}n2t|jdkDrddj|zdz}nd}g}|jD]}|j j |j}|jst|tr&|jd |z|jdfj|j||jdfdj|Dcgc]}d |z c}} d |jd | d|Scc}wcc}w) rCRustrz -> rz -> (r,rrrrEz%s: %szfn r) r=rrGr:r<rrr4rr.rr) r@r rr=rstyperIrCr4rJr<s rIrKzRustCodeGen.get_prototypeDs,4;??Ca1>>&)CC w<1 gaj(F  !A %tyy11C7FF $$ CC<<''1D~~C!<  %$,0@0@0H!IJ  $(8(8(@!AB  C IIi@1 @A ' i@@#D As E E c g}|SrVrL)r@rr%s rIrz$RustCodeGen._preprocessor_statements`s  rSc0|j|}d|zgSrRrSrTs rIrz RustCodeGen._get_routine_openingerVrScgSrVrLrXs rIrzRustCodeGen._declare_argumentsirYrScgSrVrLrXs rIr zRustCodeGen._declare_globalsmrYrScgSrVrLrXs rIr!zRustCodeGen._declare_localsqrYrSc Jg}g}g}g}|jD];}t|ts|jr!|j |j =|j D]}t|tr1|j}|j t|jn td|jdddd|j|\} } } t| tD]\} } |j d| d| d t| tD]5}t|tr |j} n|} |j d | z7|j d | zt!|d kDrd dj#|zdzg}|j d||z|zS)NrrFrr_rzconst z: f64 = rcz// unsupported: %s zlet %s rrr,rr)r<r.rrrr4r=r!r\r;rrr0rr rrGr:)r@r r%rreturnsr]rCrr`rrrs_exprr4rfrs rIr"zRustCodeGen._call_printerus    $$ -C#z*3>>""388, -oo 4F&&)"-- s6#4#456"#IJJ040R0RUe:XEFF  ))rSc | | &td| tdt||| | } t|dtr|g}||dd}g} |D](\} }| j | j | |||*| j | ||||S)aGenerate source code for expressions in a given language. Parameters ========== name_expr : tuple, or list of tuples A single (name, expression) tuple or a list of (name, expression) tuples. Each tuple corresponds to a routine. If the expression is an equality (an instance of class Equality) the left hand side is considered an output argument. If expression is an iterable, then the routine will have multiple outputs. language : string, A string that indicates the source code language. This is case insensitive. Currently, 'C', 'F95' and 'Octave' are supported. 'Octave' generates code compatible with both Octave and Matlab. prefix : string, optional A prefix for the names of the files that contain the source code. Language-dependent suffixes will be appended. If omitted, the name of the first name_expr tuple is used. project : string, optional A project name, used for making unique preprocessor instructions. [default: "project"] to_files : bool, optional When True, the code will be written to one or more files with the given prefix, otherwise strings with the names and contents of these files are returned. [default: False] header : bool, optional When True, a header is written on top of each source file. [default: True] empty : bool, optional When True, empty lines are used to structure the code. [default: True] argument_sequence : iterable, optional Sequence of arguments for the routine in a preferred order. A CodeGenError is raised if required arguments are missing. Redundant arguments are used without warning. If omitted, arguments will be ordered alphabetically, but with all input arguments first, and then output or in-out arguments. global_vars : iterable, optional Sequence of global variables used by the routine. Variables listed here will not show up as function arguments. standard : string, optional code_gen : CodeGen instance, optional An instance of a CodeGen subclass. Overrides ``language``. printer : Printer instance, optional An instance of a Printer subclass. Examples ======== >>> from sympy.utilities.codegen import codegen >>> from sympy.abc import x, y, z >>> [(c_name, c_code), (h_name, c_header)] = codegen( ... ("f", x+y*z), "C89", "test", header=False, empty=False) >>> print(c_name) test.c >>> print(c_code) #include "test.h" #include double f(double x, double y, double z) { double f_result; f_result = x + y*z; return f_result; } >>> print(h_name) test.h >>> print(c_header) #ifndef PROJECT__TEST__H #define PROJECT__TEST__H double f(double x, double y, double z); #endif Another example using Equality objects to give named outputs. Here the filename (prefix) is taken from the first (name, expr) pair. >>> from sympy.abc import f, g >>> from sympy import Eq >>> [(c_name, c_code), (h_name, c_header)] = codegen( ... [("myfcn", x + y), ("fcn2", [Eq(f, 2*x), Eq(g, y)])], ... "C99", header=False, empty=False) >>> print(c_name) myfcn.c >>> print(c_code) #include "myfcn.h" #include double myfcn(double x, double y) { double myfcn_result; myfcn_result = x + y; return myfcn_result; } void fcn2(double x, double y, double *f, double *g) { (*f) = 2*x; (*g) = y; } If the generated function(s) will be part of a larger project where various global variables have been defined, the 'global_vars' option can be used to remove the specified variables from the function signature >>> from sympy.utilities.codegen import codegen >>> from sympy.abc import x, y, z >>> [(f_name, f_code), header] = codegen( ... ("f", x+y*z), "F95", header=False, empty=False, ... argument_sequence=(x, y), global_vars=(z,)) >>> print(f_code) REAL*8 function f(x, y) implicit none REAL*8, intent(in) :: x REAL*8, intent(in) :: y f = x + y*z end function z Need either language or code_genz.You cannot specify both language and code_gen.r)r6r r.r;rr r) name_exprrrrrrrrr?r2code_genrrr4r0s rIr(r(sJ  ?@ @  MN N%h7K)A,$K  ~1aH7 d((t5F)46 77 >>(FHfe DDrSc@t|}|j||||S)a A factory that makes an appropriate Routine from an expression. Parameters ========== name : string The name of this routine in the generated code. expr : expression or list/tuple of expressions A SymPy expression that the Routine instance will represent. If given a list or tuple of expressions, the routine will be considered to have multiple return values and/or output arguments. argument_sequence : list or tuple, optional List arguments for the routine in a preferred order. If omitted, the results are language dependent, for example, alphabetical order or in the same order as the given expressions. global_vars : iterable, optional Sequence of global variables used by the routine. Variables listed here will not show up as function arguments. language : string, optional Specify a target language. The Routine itself should be language-agnostic but the precise way one is created, error checking, etc depend on the language. [default: "F95"]. Notes ===== A decision about whether to use output arguments or return values is made depending on both the language and the particular mathematical expressions. For an expression of type Equality, the left hand side is typically made into an OutputArgument (or perhaps an InOutArgument if appropriate). Otherwise, typically, the calculated expression is made a return values of the routine. Examples ======== >>> from sympy.utilities.codegen import make_routine >>> from sympy.abc import x, y, f, g >>> from sympy import Eq >>> r = make_routine('test', [Eq(f, 2*x), Eq(g, x + y)]) >>> [arg.result_var for arg in r.results] [] >>> [arg.name for arg in r.arguments] [x, y, f, g] >>> [arg.name for arg in r.result_variables] [f, g] >>> r.local_vars set() Another more complicated example with a mixture of specified and automatically-assigned names. Also has Matrix output. >>> from sympy import Matrix >>> r = make_routine('fcn', [x*y, Eq(f, 1), Eq(g, x + g), Matrix([[x, 2]])]) >>> [arg.result_var for arg in r.results] # doctest: +SKIP [result_5397460570204848505] >>> [arg.expr for arg in r.results] [x*y] >>> [arg.name for arg in r.arguments] # doctest: +SKIP [x, y, f, g, out_8598435338387848786] We can examine the various arguments more closely: >>> from sympy.utilities.codegen import (InputArgument, OutputArgument, ... InOutArgument) >>> [a.name for a in r.arguments if isinstance(a, InputArgument)] [x, y] >>> [a.name for a in r.arguments if isinstance(a, OutputArgument)] # doctest: +SKIP [f, out_8598435338387848786] >>> [a.expr for a in r.arguments if isinstance(a, OutputArgument)] [1, Matrix([[x, 2]])] >>> [a.name for a in r.arguments if isinstance(a, InOutArgument)] [g] >>> [a.expr for a in r.arguments if isinstance(a, InOutArgument)] [g + x] )r r )r4r0rr?rrs rIr)r)ds'n"(+H   D$(9; GGrSrVr) NNrFTTNNNNN)NNr)CrfrMriorsympyrr< sympy.corerrrrr r sympy.printing.cr sympy.printing.codeprinterr sympy.printing.fortranr sympy.printing.juliarsympy.printing.octaversympy.printing.rustr sympy.tensorrrrsympy.matricesrrrrrsympy.utilities.iterablesr__all__rrrryrrrrrr r5r!r" Exceptionrrr;r#rrr$r%r&r'r r(r)rLrSrIrsOb .BB,6/13/22551 "ssl E;r2u = h'2r5 A, 2r7K.2K/K/\ x  H &+Xz+\Hj$HXzH^r r j  9 y Z wZ xT"wT"nF7FRrGrhV'Vv*,