K i,YdZddlZddlmZmZmZmZddlmZddl m Z ddl m Z ddl Z GddZGd d Zd ZGd d Zy)a rewrite of lambdify - This stuff is not stable at all. It is for internal use in the new plotting module. It may (will! see the Q'n'A in the source) be rewritten. It's completely self contained. Especially it does not use lambdarepr. It does not aim to replace the current lambdify. Most importantly it will never ever support anything else than SymPy expressions (no Matrices, dictionaries and so on). N)I NumberSymboloozoo)Symbol)numbered_symbols) import_moduleceZdZdZdZdZy)vectorized_lambdifya3 Return a sufficiently smart, vectorized and lambdified function. Returns only reals. Explanation =========== This function uses experimental_lambdify to created a lambdified expression ready to be used with numpy. Many of the functions in SymPy are not implemented in numpy so in some cases we resort to Python cmath or even to evalf. The following translations are tried: only numpy complex - on errors raised by SymPy trying to work with ndarray: only Python cmath and then vectorize complex128 When using Python cmath there is no need for evalf or float/complex because Python cmath calls those. This function never tries to mix numpy directly with evalf because numpy does not understand SymPy Float. If this is needed one can use the float_wrap_evalf/complex_wrap_evalf options of experimental_lambdify or better one can be explicit about the dtypes that numpy works with. Check numpy bug http://projects.scipy.org/numpy/ticket/1013 to know what types of errors to expect. c@||_||_td|_t ||d|_|j |_t ||d|_|jj|jtg|_ |j |_ d|_ y)NnumpyT)use_np)use_python_cmath)otypesF) argsexprr npexperimental_lambdify lambda_func_1 vector_func_1 lambda_func_2 vectorizecomplex vector_func_2 vector_funcfailureselfrrs j/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/plotting/experimental_lambdify.py__init__zvectorized_lambdify.__init__ms  (2 $t%!//2 $/!WW..   y/2 -- c|j fd|D}|j|}jjj |j dj |zkD|j d}|S#t$rL|jrd|_|j|_tjd|j|cYSwxYw)Nc3LK|]}j|tyw))dtypeN)arrayr).0ars r z/vectorized_lambdify.__call__..sB!73Bs!$Hz>F)copyTThe evaluation of the expression is problematic. We are trying a failback method that may still work. Please report this as a bug.) rrma masked_whereabsimagreal ValueErrorrrwarningswarn__call__)rr temp_argsresultsrs @rr4zvectorized_lambdify.__call__~s WW (BTBI&d&& 2Gee((w||$tbffWo'== 5)*GN (||DL#11D  MM/ 0!4==$' ' (sA1BACCN__name__ __module__ __qualname____doc__r r4r!rr r Qs6"(r!r ceZdZdZdZdZy)lambdifya.Returns the lambdified function. Explanation =========== This function uses experimental_lambdify to create a lambdified expression. It uses cmath to lambdify the expression. If the function is not implemented in Python cmath, Python cmath calls evalf on those functions. c||_||_t||dd|_t||dd|_t||dd|_|j|_d|_y)NT)r use_evalf)use_python_mathr@)r@complex_wrap_evalfF)rrrrr lambda_func_3 lambda_funcrrs rr zlambdify.__init__sh  2 $?2 $>2 $$4A-- r!c t|j|}t|jdt|zkDry|jS#t t f$rYyt$r}|jr||j|jk(r'|j|_|j|cYd}~Sd|_|j|_tjdd|j|cYd}~Sd}~wwxYw)Nr)Tr+) stacklevel)rrDr.r/r0ZeroDivisionError OverflowError TypeErrorrrrr4rCr2r3)rrresultes rr4zlambdify.__call__s 'T--d34F6;;$V"44;; !=1  '||4#5#55#'#5#5 }}T**DL#11D  MM/;< >==& & 's6>A  A C>C>&AC9.C>4?C93C>9C>Nr7r<r!rr>r>s  'r!r>ct|i|}|SN) Lambdifier)rkwargsls rrrsD#F#A Hr!ceZdZ d6dZdZddddZddiZgd Zd d d d ddddddddddddZddddZ gdZ ddddZ d d!d"Z gd#Z dd$d%Zd&d'd"Zd d!d"Zgd(Zd)d*dd+Zd,Zd-Zd.Zed/Zd0Zd1Zd2Zed3Zed4Zy5)7rOc L||_||_||_||_||_||_| |_| |_td|Ds tdt|j} |D cgc] } t| } } |jtt|| }dj!| Dcgc] }t#|c}}~ ~ ~|j%|_|j)|_t#|}|j-|j/|}i}|j1|j3||j1|j5|ddlm}|j1d|i|j1dd i|j1d d i|r|j1d t;d i| r|j1d t;d i|r |j1dt;di| r;|j1dt;ddgi|j1d t;d i|jr t?|d|d|d}||_ tCd|z||d|_"ycc} wcc}w#t<$r t=dwxYw)Nc3<K|]}t|tywrN) isinstancer)r&r's rr(z&Lambdifier.__init__..s7Q:a(7szThe arguments must be Symbols.)excludez, r)sqrtrWEqc ||k(SrNr<xys rz%Lambdifier.__init__.. Q!Vr!Nec ||k7SrNr<rZs rr]z%Lambdifier.__init__..r^r!mathcmathrr z-experimental_lambdify failed to import numpy.imathzsympy.plotting.intervalmath intervalmath)fromlistzlambda z : ( z )zMYNEWLAMBDA = %s MYNEWLAMBDA)# print_lambdar@float_wrap_evalfrBrrAr use_intervalallr1r free_symbolsnextxreplacedictzipjoinstr get_dict_strdict_str get_dict_fundict_funtree2str_translatestr2treeupdatesympy_atoms_namespacesympy_expression_namespace(sympy.functions.elementary.miscellaneousrW __import__ ImportErrorprinteval_strexecrD)rrrrgr@rhrBrrArrisyms_newargsr'argstrexprstrnewexpr namespacerWrs rr zLambdifier.__init__s )" 0"4 . 0(7$77=> >(9(9:'+,!4:,,}}T#dG"456G4qCF45 '4))+ ))+ d)))$--*@A 33D9:88>? B&$($ 345$ 345    fj&89 :    gz'':; <  E  $ 7(;!<=    gz-8H(JK L   fj&89 :    'N+17;   ( *I6$]3Y-48 E!CEE Es0J7J *JJ#c&|j|i|SrN)rD)rrrPs rr4zLambdifier.__call__st000r!minmaxr.)MinMaxAbsr1j) sincostansinhcoshtanhexplogrWfloor conjugatesignarccosarccoshanglearcsinarcsinharctanarctan2arctanhceilr/ramaxaminr0)acosacoshargasinasinhatanatan2atanhceilingimlnrrrerznp.piznp.infznp.e)pirE)rrrrrrrrrrrrrrrerfrWr factorialgammalgamma)rrloggammazmath.pizmath.e)rr)rrrrrrrrrrrrrrrWphase)rrzcmath.pizcmath.e)rrrrrrrWrrrrrrrrrrAndOriminimax)rrrcht|j}|jr|j|j|j r|j|j |jr|j|j|jr|j|j|SrN) rnbuiltin_not_functionsrrxnumpy_not_functionsrAmath_not_functionsrcmath_not_functionsriinterval_not_functions)rrss rrrzLambdifier.get_dict_strs223 ;; OOD44 5    OOD33 4  OOD44 5    OOD77 8r!ct|j}|jrC|jD] }d|z||< |jj D] \}}d|z||<|j rC|jD] }d|z||< |jj D] \}}d|z||<|jrC|jD] }d|z||< |jj D] \}}d|z||<|jrC|jD] }d|z||< |jj D] \}}d|z||<|S)Nznp.zmath.zcmath.zimath.)rnbuiltin_functions_differentrnumpy_functions_samenumpy_functions_differentitemsrAmath_functions_samemath_functions_differentrcmath_functions_samecmath_functions_differentriinterval_functions_sameinterval_functions_different)rruskvs rrtzLambdifier.get_dict_funs}889 ;;.. (#ai  (66<<> (1#ai  (   -- *%k  *55;;= *1%k  *  .. +&l  +66<<> +1&l  +   11 +&l  +99??A +1&l  +r!cTtjd|}||S|j}|j}|d|}|||}||d}d}t |D]!\} } | dk(r|dz }n | dk(r|dz}|dk(s!n|j |d } |j || d}||| f|fS)aConverts an expression string to a tree. Explanation =========== Functions are represented by ('func_name(', tree_of_arguments). Other expressions are (head_string, mid_tree, tail_str). Expressions that do not contain functions are directly returned. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy import Integral, sin >>> from sympy.plotting.experimental_lambdify import Lambdifier >>> str2tree = Lambdifier([x], x).str2tree >>> str2tree(str(Integral(x, (x, 1, y)))) ('', ('Integral(', 'x, (x, 1, y)'), ')') >>> str2tree(str(x+y)) 'x + y' >>> str2tree(str(x+y*sin(z)+1)) ('x + y*', ('sin(', 'z'), ') + 1') >>> str2tree('sin(y*(y + 1.1) + (sin(y)))') ('', ('sin(', ('y*(y + 1.1) + (', ('sin(', 'y'), '))')), ')') z(\w+\()Nr())rsearchstartend enumeraterw) rr first_parrrheadfunctailcountic func_tails rrwzLambdifier.str2trees8IIj'2  NOO%E--/C6E?D5%D34=DE!$ 18QJE#XQJEB;   d2Ah/I==ab*D4+T2 2r!cpt|tr|Sdjt|j|S)aConverts a tree to string without translations. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy import sin >>> from sympy.plotting.experimental_lambdify import Lambdifier >>> str2tree = Lambdifier([x], x).str2tree >>> tree2str = Lambdifier([x], x).tree2str >>> tree2str(str2tree(str(x+y*sin(z)+1))) 'x + y*sin(z) + 1' )rUrqrpmaptree2str)clstrees rrzLambdifier.tree2strs- dC K773s||T23 3r!ct|tr|j|St|tr)t |dk(r|j |ddd|dSdj |Dcgc]}|j|c}Scc}w)zConverts a tree to string with translations. Explanation =========== Function names are translated by translate_func. Other strings are translated by translate_str. rFrNrrr)rUrq translate_strtuplelentranslate_funcrprv)rrts rrvzLambdifier.tree2str_translate s| dC %%d+ + e $Ta&&tAws|T!W= =77E1D33A6EF FEs*B cx|jjD]\}}tj|||}|S)zWTranslate substrings of estr using in order the dictionaries in dict_tuple_str.)rsrrsub)restrpatternrepls rrzLambdifier.translate_strs;"]]002 3MGTvvgtT2 3 r!c||jvr(|j|}|j|}|dz|zS|dvr)ddd}dj|||j|S|jrdnd}|jrd|z}n|j rd |z}|j}|j }d |_d |_|||j|fz} ||_||_| S) aLTranslate function names and the tree of arguments. Explanation =========== If the function name is not in the dictionaries of dict_tuple_fun then the function is surrounded by a float((...).evalf()). The use of float is necessary as np.(sympy.Float(..)) raises an error.r)rXr_z==z!=z(lambda x, y: x {} y)({}z(%s(%s)).evalf(z%s(%sz float(%s)z complex(%s)F)rurvformatr@rhrB) r func_nameargtreenew_nameroptemplaterhrBrets rrzLambdifier.translate_func s  %}}Y/H,,W5Fc>F* * , &D)B-44R ]DD[D[\cDde e,0NN(H$$&1(((83 $44 !%!8!8 $)D !&+D #y$*A*A'*JKKC$4D !&8D #Jr!c|iSt|j}ddg}|D].}tj||}||j d}0i}|j D]L}t |ttfs|tttfvr-|j|j|N|j||ji|S)a[Traverses the (func, args) tree of an expression and creates a SymPy namespace. All other modules are imported only as a module name. That way the namespace is not polluted and rests quite small. It probably causes much more variable lookups and so it takes more time, but there are no tests on that for the moment.z!$z$r)rqrrmatchgroupsrrUrrrrrrxrz)rrfuncname regexlistrm args_dictr's rrzz%Lambdifier.sympy_expression_namespaceHs <I499~H&51I  -HHQ)= xxz!}H - IYY Hq6<"89Q1c2,=N$$S%C%CA%FG  H   h 2 3 r!c|jttttt }i}|D]}||t |<|S)zmFor no real reason this function is separated from sympy_expression_namespace. It can be moved to it.)atomsrrrrrrq)rrdr's rryz Lambdifier.sympy_atoms_namespacexsB 6<C<  AAc!fI r!N)FFFFFFFF)r8r9r:r r4rrrrrrrrrrrrrrrrrtrw classmethodrrvrrrz staticmethodryr<r!rrOrOsjAFrrOr<r!rr sM  99$6t) A(A(H/'/'d uur!