K iVdZddlmZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZdd lmZdd lmZmZdd lmZmZdd lmZmZddlmZmZmZm Z ddl!m"Z"ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ddl,m-Z-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4m5Z5m6Z6m7Z7m8Z8ddl9m:Z:ddl;mdZ?GddZ@GddeAZBd ZCd!d"d#ZDd$ZEdd)ZId*ZJd+ZKd,ZLd-ZMd?d.ZNd?d/ZOd@d0ZPd1ZQd2ZRd3ZSd?d4ZTd5ZUdAd6ZVd7ZWd?d8ZXGd9d:e.ZY dBd;ZZy')Ca  The Risch Algorithm for transcendental function integration. The core algorithms for the Risch algorithm are here. The subproblem algorithms are in the rde.py and prde.py files for the Risch Differential Equation solver and the parametric problems solvers, respectively. All important information concerning the differential extension for an integrand is stored in a DifferentialExtension object, which in the code is usually called DE. Throughout the code and Inside the DifferentialExtension object, the conventions/attribute names are that the base domain is QQ and each differential extension is x, t0, t1, ..., tn-1 = DE.t. DE.x is the variable of integration (Dx == 1), DE.D is a list of the derivatives of x, t1, t2, ..., tn-1 = t, DE.T is the list [x, t1, t2, ..., tn-1], DE.t is the outer-most variable of the differential extension at the given level (the level can be adjusted using DE.increment_level() and DE.decrement_level()), k is the field C(x, t0, ..., tn-2), where C is the constant field. The numerator of a fraction is denoted by a and the denominator by d. If the fraction is named f, fa == numer(f) and fd == denom(f). Fractions are returned as tuples (fa, fd). DE.d and DE.t are used to represent the topmost derivation and extension variable, respectively. The docstring of a function signifies whether an argument is in k[t], in which case it will just return a Poly in t, or in k(t), in which case it will return the fraction (fa, fd). Other variable names probably come from the names used in Bronstein's book. ) GeneratorType)reduce)Lambda)Mul)ilcm)I)Pow)Ne)S)ordereddefault_sort_key)DummySymbollogexp)coshcothsinhtanh) Piecewise)atansincostanacotcotasinacos) integrateIntegral)_symbols)PolynomialError) real_rootscancelPolygcdreduced)RootSum)numbered_symbolsc i}|D]_}|jD]4\}}t||z }|js!|j||fI|tj fg||<ai}|jD]\\}}t t|D cgc]\}} | jdc} }} || z } |D cgc] \} } | | | zf} } } | || <^tt|jdScc} }wcc} } w)a Rewrites a list of expressions as integer multiples of each other. Explanation =========== For example, if you have [x, x/2, x**2 + 1, 2*x/3], then you can rewrite this as [(x/6) * 6, (x/6) * 3, (x**2 + 1) * 1, (x/6) * 4]. This is useful in the Risch integration algorithm, where we must write exp(x) + exp(x/2) as (exp(x/2))**2 + exp(x/2), but not as exp(x) + sqrt(exp(x)) (this is because only the transcendental case is implemented and we therefore cannot integrate algebraic extensions). The integer multiples returned by this function for each term are the smallest possible (their content equals 1). Returns a list of tuples where the first element is the base term and the second element is a list of `(item, factor)` terms, where `factor` is the integer multiplicative factor that must multiply the base term to obtain the original item. The easiest way to understand this is to look at an example: >>> from sympy.abc import x >>> from sympy.integrals.risch import integer_powers >>> integer_powers([x, x/2, x**2 + 1, 2*x/3]) [(x/6, [(x, 6), (x/2, 3), (2*x/3, 4)]), (x**2 + 1, [(x**2 + 1, 1)])] We can see how this relates to the example at the beginning of the docstring. It chose x/6 as the first base term. Then, x can be written as (x/2) * 2, so we get (0, 2), and so on. Now only element (x**2 + 1) remains, and there are no other terms that can be written as a rational multiple of that, so we get that it can be written as (x**2 + 1) * 1. r c(|djSNr)sort_key)items [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/integrals/risch.pyz integer_powers..us47;K;K;Mkey) itemsr& is_Rationalappendr Onerras_numer_denomsortediter)exprstermstermtrmtrm_listanewterms term_list_i common_denomnewtermjnewmultss r1integer_powersrK5sR E*"[[] *MCtCx A}}q *  * !!%%=/E$K*H ;;=%id %tq!Q%5%5%7%:% |#4=>DAqQ,'>>$ % $x~~'(.M NN %?s C==DczeZdZdZdZddZdZdZdZdZ d Z d Z e d Z d Zd ZdZdZdZdZdZy)DifferentialExtensiona A container for all the information relating to a differential extension. Explanation =========== The attributes of this object are (see also the docstring of __init__): - f: The original (Expr) integrand. - x: The variable of integration. - T: List of variables in the extension. - D: List of derivations in the extension; corresponds to the elements of T. - fa: Poly of the numerator of the integrand. - fd: Poly of the denominator of the integrand. - Tfuncs: Lambda() representations of each element of T (except for x). For back-substitution after integration. - backsubs: A (possibly empty) list of further substitutions to be made on the final integral to make it look more like the integrand. - exts: - extargs: - cases: List of string representations of the cases of T. - t: The top level extension variable, as defined by the current level (see level below). - d: The top level extension derivation, as defined by the current derivation (see level below). - case: The string representation of the case of self.d. (Note that self.T and self.D will always contain the complete extension, regardless of the level. Therefore, you should ALWAYS use DE.t and DE.d instead of DE.T[-1] and DE.D[-1]. If you want to have a list of the derivations or variables only up to the current level, use DE.D[:len(DE.D) + DE.level + 1] and DE.T[:len(DE.T) + DE.level + 1]. Note that, in particular, the derivation() function does this.) The following are also attributes, but will probably not be useful other than in internal use: - newf: Expr form of fa/fd. - level: The number (between -1 and -len(self.T)) such that self.T[self.level] == self.t and self.D[self.level] == self.d. Use the methods self.increment_level() and self.decrement_level() to change the current level. )fxTDfafdTfuncsbacksubsextsextargscasescasetdnewfleveltsdummyNc |r7d|vr td|D]}t|||||jy| td|dvrtdt|z||_|_||_|jd\}} | t|jjv}|rttttttt t"ft$t&t(t*t,ft.i} | j1D]&\} } |j2j5| | |_(t7|j2|_nUt9fd|jjtttt,t&t(Dr t;d t=} t=}t=}t=}t=}t=} |j2j>|j@rn|s| st;d t|zd z|jC| |||| \} }}}} |jE||\}}|d k(s| s7|jG| }|$|j2|_|jd }|dk(s|s|jI|} tK|j2|jL\|_'|_(|jy)a Tries to build a transcendental extension tower from ``f`` with respect to ``x``. Explanation =========== If it is successful, creates a DifferentialExtension object with, among others, the attributes fa, fd, D, T, Tfuncs, and backsubs such that fa and fd are Polys in T[-1] with rational coefficients in T[:-1], fa/fd == f, and D[i] is a Poly in T[i] with rational coefficients in T[:i] representing the derivative of T[i] for each i from 1 to len(T). Tfuncs is a list of Lambda objects for back replacing the functions after integrating. Lambda() is only used (instead of lambda) to make them easier to test and debug. Note that Tfuncs corresponds to the elements of T, except for T[0] == x, but they should be back-substituted in reverse order. backsubs is a (possibly empty) back-substitution list that should be applied on the completed integral to make it look more like the original integrand. If it is unsuccessful, it raises NotImplementedError. You can also create an object by manually setting the attributes as a dictionary to the extension keyword argument. You must include at least D. Warning, any attribute that is not given will be set to None. The attributes T, t, d, cases, case, x, and level are set automatically and do not need to be given. The functions in the Risch Algorithm will NOT check to see if an attribute is None before using it. This also does not check to see if the extension is valid (non-algebraic) or even if it is self-consistent. Therefore, this should only be used for testing/debugging purposes. rQzUAt least the key D must be included with the extension flag to DifferentialExtension.Nz8Either both f and x or a manual extension must be given.rz,handle_first must be 'log' or 'exp', not %s.)TTc3@K|]}|jywN)has).0rFrOs r1 z1DifferentialExtension.__init__..sS1558Ssz1Trigonometric extensions are not supported (yet!)TzJCouldn't find an elementary transcendental extension for %s. Try using a z)manual extension with the extension flag.rr)) ValueErrorsetattr _auto_attrsstrrNrOr_resetratomsrrrrrrrrrrrrrrr6r\rewriter&anyNotImplementedErrorsetis_rational_functionrP_rewrite_exps_pows _rewrite_logs _exp_part _log_partfrac_inrZrRrS)selfrNrO handle_firstr_ extensionrewrite_complexattrexp_new_extensionlog_new_extension rewritables candidatesruleexpspowsnumpowssympowslogssymlogss ` r1__init__zDifferentialExtension.__init__sD )# "CDD! 5dIdO4 5      Y!)  ~ -KL!"# #   /9,,  "466<<>1O c3T4t*+EGJ1v+N?+@AA ++D$J[\ }||j j |j|j jzzf@} }xj| D cgc] \}} | |f c} }z c_ jjt| _t|jjtfd}t|jjtfd}t|t|fd}t|t|t|z fd}t|D]}|} t|jt|j z} ||vr7|jjrt!dt#|zt%|j j&\} }|| |}|jj| | i_xj| | fgz c_ j)t|j g}t|jjtfd} |\}}}t|jt||zz}jj||i_n||vrs| }jj+| | fjj| |i_|j+||||||fScc}wcc}wcc} }w) z: Rewrite exps/pows for better processing. r  is_deriv_kc|jjjxr#|jjjSrbrrprPrcrFrvs r1r2z:DifferentialExtension._rewrite_exps_pows..P;0aee00$&&9 AEEIItvv r3c|jjjxr#|jjjSrbrrs r1r2z:DifferentialExtension._rewrite_exps_pows..Srr3cL|jjj Srb)basercrPrs r1r2z:DifferentialExtension._rewrite_exps_pows..Vs*!&&**dff--r3c||jjjxr|jj Srb)rrprPr is_Integerrs r1r2z:DifferentialExtension._rewrite_exps_pows..Xs51aff11466:!  r3z,Algebraic extensions are not supported (%s).c|jjjxr#|jjjSrbrrs r1r2z:DifferentialExtension._rewrite_exps_pows..vs8222DFF;R  466@Rr3)prderr\rkr isinstancerrr7rUxreplacedict update_setsror rrnrirurZrtr8)rvrrrrr|rrFratpows ratpows_replrIoldnewbaseabasedAansuconstrHs` r1rqz(DifferentialExtension._rewrite_exps_pows's %#iiooc2G!!&&#.1553D3DGG;BC56Q aeeAFFJJ./ 0C C \:TQ1a&:: II&&tL'9: 4!5  4!5  gs4y -/gs4y3w<'? !" 1 !ACaeeCK'(CG|55$$-/.03A/788 'qvvtvv6 uueT29!% 2 2C: >DIMMsCj\1M(,AFF }(E%&tTYY__S-ADSTD ! QaeeSZ!^45!II..7|< '! MM #s , **C>:DI KK c1 !fT7G->>>mGC:s9M2(AM7>M< cjjt}t||fd}t||fd}t |D]}t|j dj }|j||j dj|z}jj||i_jj||ftt|t}||fS)z5 Rewrite logs for better processing. c|jdjjxr&|jdjjSr.)argsrprPrcrs r1r2z5DifferentialExtension._rewrite_logs..sC4affQi44dff=# AFF1IMM466 "r3c|jjxrq|jdjxrV|jdjj jxr$|jdj j Sr.)rcrPris_Powrrprrrs r1r2z5DifferentialExtension._rewrite_logs..soeaeeTVVn))9)9) /AFF1INN / / 8)q (( (r3rr4)r\rkrrr rrr8rrrUr;ror )rvrrrkrFlbasers` r1rrz#DifferentialExtension._rewrite_logss $4 #$gu )*! +A q 'E KK &&)--%C **As84DI MM #q * +c$i%56W}r3c |js)|jDcgc]}|jc}|_|js|jd|_t |j|jDcgc]\}}t ||c}}|_d|_|j|j|_|j|j|_ |j |j|_ ycc}wcc}}w)zB Set attributes that are generated automatically. rN) rPrQgenrOzipget_caserXr]rZr[rY)rvrFr[rZs r1rhz!DifferentialExtension._auto_attrssvv%)VV,aee,DFvvVVAYDF14TVVTVV1DEAhq!nE   # #JJtzz* -Fs C:9C?c ddlm}d}d}|Dcgc]}|j}}t|}|D]c\}} | j dt ||j \} } || | |} | | \} }}}|dk(r#d}|dz}|dz}| Dcgc] \}}|| f } }}|dk(r|jjt|t|t| Dcgc] \}}||z c}}zi|_|jj| Dcic]?\}}t||zt||zt| Dcgc] \}}||z c}}zAc}}}}|_8|st| dkDrt| Dcgc] \}}|||z zc}}}|jj| Dcic]#\}}t||zt||z|z%c}}|_|jjtttt|jt|j Dcgc]}||j"c}|_d}n*t%d t ||j \} } | t't)| |j |z| t't)| |j |zz }| d z}|j+|d \}}|j-|j-z }t/|j0|_|jj3|j |j4j3||j6j3d |j8j3|j;|j d t)|j |j d z|j<r t?d}n tAd}|xj tC|t|jE|j"|gz c_|jj| Dcic]\}}t||j |z c}}|_d}f|ry|Scc}wcc}}wcc}}wcc}}wcc}}}}wcc}}wcc}}wcc}wcc}}w)a Try to build an exponential extension. Returns ======= Returns True if there was a new extension, False if there was no new extension but it was able to rewrite the given exponentials in terms of the existing extension, and None if the entire extension building process should be restarted. If the process fails because there is no way around an algebraic extension (e.g., exp(log(x)/2)), it will raise NotImplementedError. r )is_log_deriv_k_t_radicalFc |dS)Nr )rFs r1r2z1DifferentialExtension._exp_part..s adr3r4NrTz+Cannot integrate over algebraic extensions.includerexpandrF)#rrrrKsortrurZr\rrlenrlistrreversedrPrTrOrn derivationr'r&as_exprnextr^r8rWrVrQas_polyr_rrrsubs)rvrr new_extensionrestartrFexpargsipargothersargaargdrrrnrrIpowerexpargpr?radrNdargadargddargs r1rszDifferentialExtension._exp_partsY 3 "&'Q155'' G $T %KC KKNK + dff-JD$(tT:A}#$ Q57 A"HARKE/23tq!Ar73C36 $ 2 2CHc%j14O6%-Q5O6J7?748!9DI $ 2 2)/4141%FA58&ME!G sc,J(!UQX,J'KK5L41!2DI *C1 !s#K eD57O#KL$(II$6$6>D8F1:9a$||E4|@ u}}u}}6dgg dff% ##C(   ' dll466%l@dffFF5B**+::c As A q#chhtvvq.A*B CDD  II..AGHIFAVdffai/HJ $ iT %l u((4O6-K418$L8F&F6IsARR"R(,R4R.  R4R< 4(S 4S##S .R4c ddlm}d}|Dcgc]}|jd}}t|D]P}t ||j \}}||||} | @| \} } } t | | z} |jjt || i|_it ||j \}}|tt||j |z|tt||j |zz }|dz}|j|jz }t|j|_|jj|j |j j||j"jd|j$jt'|j|z j)|j d|j*r t-d}n t/d}|xj0t3|t |j5|j6|gz c_|jjt ||j i|_d }S|Scc}w) a; Try to build a logarithmic extension. Returns ======= Returns True if there was a new extension and False if there was no new extension but it was able to rewrite the given logarithms in terms of the existing extension. Unlike with exponential extensions, there is no way that a logarithm is not transcendental over and cannot be rewritten in terms of an already existing extension in a non-algebraic way, so this function does not ever return None or raise NotImplementedError. r rFrrrrrFT)rrrr rurZrr\rrr'rrr^rPr8rWrVrQr&rr_rrrTrrrO)rvrrrrFlogargsrrrrrrrrHrrrs r1rtzDifferentialExtension._log_part0s  % &*+166!9++7# %C !dff-JD$4t,A} ! Qe*q. II..C'/BC %S$&&1 djdDFF);TBBDtvv$6==>a}}u}}6dgg dff% ##C(   ' fT\\^C%78@@ A"#::c As A q#chhtvvq.A*B CDD  II..C$&&/AB $ ? %BE,sJc|j|j|j|j|j|j |j |jfS)z Returns some of the more important attributes of self. Explanation =========== Used for testing and debugging purposes. The attributes are (fa, fd, D, T, Tfuncs, backsubs, exts, extargs). )rRrSrQrPrTrUrVrWrvs r1_important_attrsz&DifferentialExtension._important_attrses@$&&$&&$++ MM499dll4 4r3c |jDcgc]*}tt||ts|t||f,}}|jj d|zzScc}w)Nz (dict(%r)))rrgetattrr __class____name__)rvrzrs r1__repr__zDifferentialExtension.__repr__ysb59^^ GT!'$"5}EGD$' ( G G~~&&);;; Gs/Ac|jjd|jd|jd|jdzS)Nz({fa=z, fd=z, D=z}))rrrRrSrQrs r1__str__zDifferentialExtension.__str__s1''$''466+++ ,r3c|jjD]2}t||t||}}t|tr,||k(r2yy)NFT)rrrrr)rvotherrzd1d2s r1__eq__zDifferentialExtension.__eq__sJNN,, DT4('%*>Br=1R2X r3cT|j|_|jg|_td|jg|_d|_dg|_dg|_|jrtdt|_ ntd|_ g|_ g|_ |j|_y)zD Reset self to an initial state. Used by __init__. r rNrZ)cls)rOrZrPr'rQr]rVrWr_r+rr^rUrTrNr\rs r1rjzDifferentialExtension.resets&&q$&&/" F v ::&s6DG's+DG  FF r3cjt|jDcgc] \}}||k(s |c}}Scc}}w)aV Parameters ========== extension : str Represents a valid extension type. Returns ======= list: A list of indices of 'exts' where extension of type 'extension' is present. Examples ======== >>> from sympy.integrals.risch import DifferentialExtension >>> from sympy import log, exp >>> from sympy.abc import x >>> DE = DifferentialExtension(log(x) + exp(x), x, handle_first='exp') >>> DE.indices('log') [2] >>> DE.indices('exp') [1] ) enumeraterV)rvrxrFexts r1indiceszDifferentialExtension.indicess,6!*$)) 4Ifay8HIIIs //c|jdk\r td|xjdz c_|j|j|_|j|j|_|j |j|_y)a, Increment the level of self. Explanation =========== This makes the working differential extension larger. self.level is given relative to the end of the list (-1, -2, etc.), so we do not need do worry about it when building the extension. rzJThe level of the differential extension cannot be incremented any further.r N)r]rfrPrZrQr[rXrYrs r1increment_levelz%DifferentialExtension.increment_levelsp :: ./ / a  # #JJtzz* r3c>|jt|j kr td|xjdzc_|j|j|_|j |j|_|j|j|_y)a, Decrease the level of self. Explanation =========== This makes the working differential extension smaller. self.level is given relative to the end of the list (-1, -2, etc.), so we do not need do worry about it when building the extension. zJThe level of the differential extension cannot be decremented any further.r N) r]rrPrfrZrQr[rXrYrs r1decrement_levelz%DifferentialExtension.decrement_levelsz ::#dff+ %./ / a  # #JJtzz* r3)NNrFNN)r __module__ __qualname____doc__rrrrqrrrhrsrtpropertyrrrrrjrrrrr3r1rMrMxsr(ZIun i?V D +kZ3j 4 4&<,*J:*r3rMct|}|j|}||z }|jtt ||t|Srb)ro intersectionupdaterfilter)seqrkfuncsrs r1rrsE CA 1A !)CHHT&s# $% 7Nr3c&eZdZdZdZdZdZdZy)DecrementLevelzR A context manager for decrementing the level of a DifferentialExtension. DEc||_yrbr)rvrs r1rzDecrementLevel.__init__s r3c8|jjyrb)rrrs r1 __enter__zDecrementLevel.__enter__ !r3c8|jjyrb)rr)rvexc_type exc_value tracebacks r1__exit__zDecrementLevel.__exit__rr3N)rrrrrrrrrr3r1rrsI""r3rceZdZdZy)NonElementaryIntegralExceptionz Exception used by subroutines within the Risch algorithm to indicate to one another that the function being integrated does not have an elementary integral in the given differential field. Nrrrrrr3r1r r s  r3r c|j|\}}||j|z}|r5|j|jk\r|j|\}}|||zz j|}||fS)a Extended Euclidean Algorithm, Diophantine version. Explanation =========== Given ``a``, ``b`` in K[x] and ``c`` in (a, b), the ideal generated by ``a`` and ``b``, return (s, t) such that s*a + t*b == c and either s == 0 or s.degree() < b.degree(). ) half_gcdexexquodegreediv)rBbcrgrErZs r1gcdex_diophantinersl <<?DAqOAQXXZ188: %uuQx1 QqSA q6Mr3Fr&c `t|tr&|\}}|j|jz }|jj\}}|j|fi||j|fi|}}|r|j |d\}}||t d|d|d||fS)ar Returns the tuple (fa, fd), where fa and fd are Polys in t. Explanation =========== This is a common idiom in the Risch Algorithm functions, so we abstract it out here. ``f`` should be a basic expression, a Poly, or a tuple (fa, fd), where fa and fd are either basic expressions or Polys, and f == fa/fd. **kwargs are applied to Poly. TrzCould not turn z into a fraction in .)rtuplerr:rr&rf)rNrZr&kwargsrRrSs r1ruru)s!UB JJL % YY[ ' ' )FB RZZ $V $jbjj&=f&=B 2t,B zRZq!LMM 8Or3ct||d\}}|jst|d|d|d|j|\}}|j ||d}|r|j }||z} |j |j z } |j|| | | zz} | j||jj|j} || j ||dz }|S)a  (Hackish) way to convert an element ``p`` of K[t, 1/t] to K[t, z]. In other words, ``z == 1/t`` will be a dummy variable that Poly can handle better. See issue 5131. Examples ======== >>> from sympy import random_poly >>> from sympy.integrals.risch import as_poly_1t >>> from sympy.abc import x, z >>> p1 = random_poly(x, 10, -10, 10) >>> p2 = random_poly(x, 10, -10, 10) >>> p = p1 + p2.subs(x, 1/x) >>> as_poly_1t(p, x, z).as_expr().subs(z, 1/x) == p True Trz is not an element of K[z, 1/z].Fr) ru is_monomialr$rroner transformreplaceto_field quo_groundLC) rrZzpapdt_part remainderrrtprz_parts r1 as_poly_1tr)As0Q$ 'FB >>1aPQQr FI ..Ae. ,Cmm sU IIK)**, ,$$S"-A51%..0;;BEEGD v~~a5~11 Jr3c|rd}ntd|j}|j}|r5|jt|j kr|S|j |j dt|j |jzdz}|jdt|j|jzdz}t||D]\}} |j| } | |r|j} |r&||j| j| zz }S||j| j| jzj|z }|r t|}|r|j|S)aC Computes Dp. Explanation =========== Given the derivation D with D = d/dx and p is a polynomial in t over K(x), return Dp. If coefficientD is True, it computes the derivation kD (kappaD), which is defined as kD(sum(ai*Xi**i, (i, 0, n))) == sum(Dai*Xi**i, (i, 1, n)) (Definition 3.2.2, page 80). X in this case is T[-1], so coefficientD computes the derivative just with respect to T[:-1], with T[-1] treated as a constant. If ``basic=True``, the returns a Basic expression. Elements of D can still be instances of Poly. rNr ) r'rZr]rrPrrQrrrdiffr&r) rr coefficientDbasicrrZrQrPr[vpvs r1rrosG&  BDDM A 88BDD z !H   &c"$$i"(("Q&'A  &c"$$i"(("Q&'AAq ?1 YYq\ :B  RWWQZ' 'A !))+bggaj0022;;A> >A? 1I  Hr3c$|jj|s|jryy|jt ||j ry|jt d|dzz|j ry|j |dkDryy) z Returns the type of the derivation d. Returns one of {'exp', 'tan', 'base', 'primitive', 'other_linear', 'other_nonlinear'}. r primitiverr rrother_nonlinear other_linear)exprrcis_oneremr'is_zeror)r[rZs r1rrst 66::a= 88uuT!QZ  uuT!ad(A ''xx{Q r3Nc|jd|jDcgc]}d|z  }}|r|j|td|j|j }t |||}|jr||fS|jj|jsY|j|j|j|j|j}|j|} | |fS|js|j|j} |j|j|jj} | j| }|j|jdk(r||fSt!|j|||} | d| d|zfS||fScc}w)a Splitting factorization. Explanation =========== Given a derivation D on k[t] and ``p`` in k[t], return (p_n, p_s) in k[t] x k[t] such that p = p_n*p_s, p_s is special, and each square factor of p_n is normal. Page. 100 Nr )domain)r,r)rPr]r8r'rZ get_domainrr7r4rcrr(rrr+r splitfactor) rrr,r"rOkinvr9Dprrhrq_splits r1r;r;sqirxx )AAaC )D ) A q"$$q||~ .C Ar 5Byy3x 66::bdd  AIIt  T!2 3 ; ;BDD A GGAJ1v :: EE"I    EE!&&,  ( ( * GGAJ 88BDD>Q s8Oaggaj"<H GAJqL))3x7 *s Gc |jd|jDcgc]}d|z  c}|jd|jz}|r|g}g}g}|j} |jr|dffdfS| D]\} } | j|j t | |||j|j |j} t| |j} t| |j} | j| } | js|j| | f| jr|j| | ft|t|fScc}w)aO Splitting Square-free Factorization. Explanation =========== Given a derivation D on k[t] and ``p`` in k[t], returns (N1, ..., Nm) and (S1, ..., Sm) in k[t]^m such that p = (N1*N2**2*...*Nm**m)*(S1*S2**2*...*Sm**m) is a splitting factorization of ``p`` and the Ni and Si are square-free and coprime. Nr r)r,r-) rPr]sqf_list_includer7rr(rrZr'rr5r8r)rrr,r"r-rOkkinvr Np_sqfpirFSiNis r1splitfactor_sqfrHsH$$y/ *QQqS *RTT)288_ rttwwy[+44&!" R 2r" " ((244.BDDKK- - q6Mr3cl|jdk(rytd|}td}|jd|t d|j }t d|j }|j ||z} || t ||z|j z} } t||} t| |t d|j \} }t| |t d|j \}}|}ggg}}}td|D]Y}t||}|j|dzz }|j||jt ||dz||[td|i}td|D]}t |||zz|j | |dzzz| z}| }t||fdt||fd}}|j |}td|dzD]}|j||||}| t| |dj|j z| t| |dj|j zz| t| |dj|j zz| t| |dj|j zz}t |dz|j | dzz}||} } |j!t#||\}}t%||j \} }!| j|j |!j|j z dkDst ||j | d|zzz|||zzz}"|"}#|j|#|"|!zj'| }#t)| }$t+|$D]}%|t |j |%z ||z z|j zt |#j-|%|j z}|t |j |%z ||z z|j z}|||fS) a Contribution of ``F`` to the full partial fraction decomposition of A/D. Explanation =========== Given a field K of characteristic 0 and ``A``,``D``,``F`` in K[x] with D monic, nonzero, coprime with A, and ``F`` the factor of multiplicity n in the square- free factorization of D, return the principal parts of the Laurent series of A/D at all the zeros of ``F``. rr"r rQ)rxrT)r-)rr#rinsertr'rZquorrrangerr8rMr&rrrr(rur6r%reval)&rBr[FrrZr"delta_adelta_dEhahddFBrECF_storeV DE_D_listH_listrIr.DE_newzEhazEhdPaPdQrFDhaDhdFfF_staraF_stardQBCHalphasalphas& r1laurent_seriesrps xxz1}aAs AHHQN1bddmG1bddmG ad A41bdd##B Ab B Q4"$$< 0DAq RD244L 1DAqGb"&yA 1a[.Wb) __ Q '  aAhqt,- .#Y/? @F 1a[FAAJ%a!a%j03t %a(&$*>q*AB FF2Jq!a% #AqtQqT"A #*R4088>>*R4088>>?*Rt4<>"$$ '.."6 6 :q"$$-AE *1q1u:5CA MM! W!!'*A(Ff F!$u A'>"EEQVVTY]\^\`\`Haa!$u A'>"EE F-F2 Wf %%r3cd}|j|d\}}|j|\}}t||d|\}}d} |D]C\} }t||| | |\} } } t || dj }||urd}|S| dz} E|S)a Compute the squarefree factorization of the denominator of f and for each Di the polynomial H in K[x] (see Theorem 2.7.1), using the LaurentSeries algorithm. Write Di = GiEi where Gj = gcd(Hn, Di) and gcd(Ei,Hn) = 1. Since the residues of f at the roots of Gj are all 0, and the residue of f at a root alpha of Ei is Hi(a) != 0, f is the derivative of a rational function if and only if Ei = 1 for each i, which is equivalent to Di | H[-1] for each i. Trr,r"r rF)r&rrHrr(r)rBr[rr"flagrErNpSprIrrmrnrrs r1recognize_derivativers D 88At8 $DAq 558DAq Q ;FB A1,Q1a<! 1R5M ! ! # A:D  K E  Kr3c|xs td}|j|d\}}|j|\}}t||j}t ||}|||zz }|j |d\}}t||}t||d|\} } | D]3\} }t| j|}td|Dr3yy)a There exists a v in K(x)* such that f = dv/v where f a rational function if and only if f can be written as f = A/D where D is squarefree,deg(A) < deg(D), gcd(A, D) = 1, and all the roots of the Rothstein-Trager resultant are integers. In that case, any of the Rothstein-Trager, Lazard-Rioboo-Trager or Czichowski algorithm produces u in K(x) such that du/dx = uf. r"Tr includePRSrc34K|]}|jywrb)r)rdrIs r1rez+recognize_log_derivative..s+A1<<+sF) rr&rr'rZr resultantrHr%rall) rBr[rr"rEpzDdrLrrrrs r1recognize_log_derivativers U3ZA 88At8 $DAq 558DAq aB Ar B BrE A ;;qT; *DAq Q A Q ;FB1 qyy| $+++  r3c ^xs td|j|d\}}|jjd|j z |jjd|j z }}j dj Dcgc]}d|z  c}j dj z}|jrgdfS|j|\}}tj}t|} ||| zz } | jj|jjkr|j| d\} } n| j|d\} } ig}} | D]}|| |j<t| } t| d\}}|D]P\}}||jjk(r.t|j}|j!||fS| j#|}|gt|j%jj jd}|j'd }|D]N\}}t|jdj)tt+|||zg|j}Pt|j}|rt|j%jj jdd }|j%dj-|t.j0g}}|j3ddD]M}t5||j%|j6z|gd}|j!|j9Ott;t=t?|jA|j}|j!||fStCfd |D }||fScc}w) aE Lazard-Rioboo-Rothstein-Trager resultant reduction. Explanation =========== Given a derivation ``D`` on k(t) and f in k(t) simple, return g elementary over k(t) and a Boolean b in {True, False} such that f - Dg in k[t] if b == True or f + h and f + h - Dg do not have an elementary integral over k(t) for any h in k (reduced) if b == False. Returns (G, b), where G is a tuple of tuples of the form (s_i, S_i), such that g = Add(*[RootSum(s_i, lambda z: z*log(S_i(z, t))) for S_i, s_i in G]). f - Dg is the remaining integral, which is elementary only if b == True, and hence the integral of f is elementary only if b == True. f - Dg is not calculated in this function because that would require explicitly calculating the RootSum. Use residue_reduce_derivation(). r"Trr Nrrfield)rF)rrc3K|]:\}}t|jjj<ywrb)r&rrcrZ)rdrFrErr"s r1rez!residue_reduce..=s1@TQqyy{#''a0@sAA)"rr&r mul_groundr!rPr]r7rr'rZrrrrHmonicr8getrrArr(invertr r9coeffsr)gensrrrrmonomsrm)rBr[rr"rrOrBrErrrLrRR_maprrFrrrr>h_lch_lc_sqfrIinvrcoeffLrs `` r1residue_reducers}6 U3ZA 88At8 $DAq ::< " "1QTTV8 ,ajjl.E.Eah.OqA$$y/ *QQqS *RTT)288_ .Jsh&qt||Aq!C! 4G4L4L A5Q3)&sA/A2)rrrrrPrTrOsum)rrr"rNrFrs ` @@r1residue_reduce_to_basicrBsc c A S"$$BII*Fq1RTT7*F!G HIA &#$& &&+GsA>c\tdttfd|DS)z Computes the derivation of an expression returned by residue_reduce(). In general, this is a rational function in t, so this returns an as_expr() result. rFc 3K|]~}t|djtt|dj j z|dj j z ywr)r*rrrrr)rdrBrrFr"s r1rez,residue_reduce_derivation..Ws~IAB1a&Aj1 7 GIdd1aj5!!"1!4!4Q!:5;+<=IsBB)rr r)rrr"rFs ``@r1residue_reduce_derivationrNs4 c A SIFGII JJr3c:td|j}td|j}|jj|js||dfSddlm} |jj|js||dfSt |j|j|jdz \}}t|5|j}t ||j\}} ||| ||fg|} | t| \\} } } ddd|j|j} dj|jt|j|dzz|dzz |jz j jz j|jt|j|z|jzz}|t!||z }||z}#t$r||dfcYcdddSwxYw#1swYxYw)aH Integration of primitive polynomials. Explanation =========== Given a primitive monomial t over k, and ``p`` in k[t], return q in k[t], r in k, and a bool b in {True, False} such that r = p - Dq is in k if b is True, or r = p - Dq does not have an elementary integral over k(t) if b is False. rTr )limited_integrateNF)r'rZr4rcrrrur[rPr]rr!r rrrr)rrZerorLrDtaDtbrBaaadrvbabdrrcrds r1integrate_primitive_polynomialr[s 244=D Q A 66::bdd a' vvzz"$$q$< 244bhhl!34S B  %AQ%FB %&r2c |R@:88 R! % HHRTTN qT\\"$$ RTTAE]AE%:BDD A A ZZ\"**, & / / 5d2447BDD6I IJ  2r" " F1  2 %1e}$ % % % % %s**H1G33H H H  HHc |xs td}ttt|jt|j Dcgc]}||j c}}t|||\}}}t|d|d||\} } | st|j|jz |dt|d|z|dt|d|zz j|ddzjz z t| ||z } tt| j||j } |dj|djz j|t| ||z| | fSt|dj|djz t| ||z |dj|djz z} | j!|j"} t%| |\} } } |dj|djz | jzj|t| ||z}| s=tt| jj||j } nt| j} || | fScc}w)a[ Integration of primitive functions. Explanation =========== Given a primitive monomial t over k and f in k(t), return g elementary over k(t), i in k(t), and b in {True, False} such that i = f - Dg is in k if b is True or i = f - Dg does not have an elementary integral over k(t) if b is False. This function returns a Basic expression for the first argument. If b is True, the second argument is Basic expression in k to recursively integrate. If b is False, the second argument is an unevaluated Integral, which has been proven to be nonelementary. r"rr r"r)rrrrrPrTrOrarr&rrrNonElementaryIntegralrrrrZr)rBr[rr"rNrg1r>rg2rrFrrLrets r1integrate_primitiverst$ U3ZA S"$$BII*Fq1RTT7*F!G HIAaB'HB1 1Q41rQ /EB 199;qyy{*beJr!ub4I.I qE*RUB' '/()0BqE1H3E3E3G.HH %b"a 01 2 "&).."3RTT :AA066q9 #BA ./0116 6 qt||~adlln,/H A01! ./ 0A "$$A,Q3GAq! qEMMOBqEMMO +aiik 9 ? ? BB* +C !&"5":":1"=rtt D 199;  A;7+GsKc |j}|jjt|j|j}td|j}td|j}d}|jr|||fSddlm}t|5t|j| |j|dzD]} | s| dkr$|j|dj| } n"|j|dj| } t| |jd\} } | j| d\} } t| ||z} t| |jd\}} |||t| |jt| |j|\}}t||f|d \}}||z|t|| zz|zz}||z} d d d |||fS#t$rd}Y6wxYw#1swY xYw) aG Integration of hyperexponential polynomials. Explanation =========== Given a hyperexponential monomial t over k and ``p`` in k[t, 1/t], return q in k[t, 1/t] and a bool b in {True, False} such that p - Dq in k if b is True, or p - Dq does not have an elementary integral over k(t) if b is False. rr T)rischDEFrrrrN)rZr[rr'r7sympy.integrals.rderrrirrnthrur&r )rrr"t1dttqaqdrrrFrBrriDtiDtaiDtdvavds r1%integrate_hyperexponential_polynomialrs B $$**T"$$% &C aB aB Ayy2qk+   |QXXb\A%56 AQIIaI.22A26IIbI/33A6QD1FBYYr4Y0FBq"+c/C bdd$7JD$  tT"bdd^T"bdd^RPB "b2d;BURRU ^B..b1 6 A; 2  +s2CG?3A G-="G?- G<8G?;G<<G??Hc p|xs td}ttt|jt|j Dcgc]}||j c}}t|||\}}} t|d|d||\} } | st|j|jz |dt|d|z|dt|d|zz j|ddzjz z t| ||z } tt| j||j } |dj|djz j|t| ||z| | fSt|dj|djz t| ||z | dj| djz z} t!| |j"|}t%|||\}}} |j'dd} |dj|djz j|t| ||z}|jj|}|jj|}|dk(ry|j |j(vra|t+||z t-|dft/| | z j|j"dj||j dfz }n|||z z }| sr| |t||z|t||zz j|dzjz z } tt| j||j } || | fScc}w)ap Integration of hyperexponential functions. Explanation =========== Given a hyperexponential monomial t over k and f in k(t), return g elementary over k(t), i in k(t), and a bool b in {True, False} such that i = f - Dg is in k if b is True or i = f - Dg does not have an elementary integral over k(t) if b is False. This function returns a Basic expression for the first argument. If b is True, the second argument is Basic expression in k to recursively integrate. If b is False, the second argument is an unevaluated Integral, which has been proven to be nonelementary. r"rr rr piecewiseT)rrrrrPrTrOrarr&rrrrrrr)rZrr free_symbolsrr r!)rBr[rr"condsrNrrr>rrrrFrpprrrqasqdss r1integrate_hyperexponentialrsT$ U3ZA S"$$BII*Fq1RTT7*F!G HIAaB'HB1 1Q41rQ /EB 199;qyy{*beJr!ub4I.I qE*RUB' '/()0BqE1H3E3E3G.HH %b"a 01 2 "&"3RTT :AA066q9 #BA ./0116 6 qt||~adlln,/H A01! ./ 0A ArttQ B5b"a@IBA q! A qEMMOBqEMMO + 1 1! 4 !"b! , -C **,  A C **,  A C C,<,< < yS"S!*%AE<<a055a8"$$?F  s3w Jr2&&Jr2,>)>>GGI UOO   !&).."3RTT : A;W+GsN3ct||\}}|jjt|jdzdz|j}t|j dd|j zz |j}||fS)ah Integration of hypertangent polynomials. Explanation =========== Given a differential field k such that sqrt(-1) is not in k, a hypertangent monomial t over k, and p in k[t], return q in k[t] and c in k such that p - Dq - c*D(t**2 + 1)/(t**1 + 1) is in k and p - Dq does not have an elementary integral over k(t) if Dc != 0. rr )rer[rr'rZrr)rrrLrrBrs r1!integrate_hypertangent_polynomialr/sm Q #DAq  4a! RTT*+A QUU1Xq} %rtt,A q6Mr3c |xs td}ttt|jt|j Dcgc]}||j c}}t|||\}}}t|d|d||\} } | sF|dj|djz j|t| ||z| fSt|dj|djz t| ||jz |dj|djz zj|j} t!| |\} } | j"j%|jrd} nd} t|dj|djz | jzj|t| ||z}|| fScc}w)a Integration of nonlinear monomials with no specials. Explanation =========== Given a nonlinear monomial t over k such that Sirr ({p in k[t] | p is special, monic, and irreducible}) is empty, and f in k(t), returns g elementary over k(t) and a Boolean b in {True, False} such that f - Dg is in k if b == True, or f - Dg does not have an elementary integral over k(t) if b == False. This function is applicable to all nonlinear extensions, but in the case where it returns b == False, it will only have proven that the integral of f - Dg is nonelementary if Sirr is empty. This function returns a Basic expression. r"rr rFT)rrrrrPrTrOrarrrrr&rrrZrer4rc)rBr[rr"rNrrr>rrrrq1q2rs r1integrate_nonlinear_no_specialsrBs, U3ZA S"$$BII*Fq1RTT7*F!G HIAaB'HB1 1Q41rQ /EB AA066q9 #BA ./013 3 qt||~adlln,/H A0wyQ4<<>!A$,,.89 ::A'"$$- q" %FB ww{{244   "Q%--/"Q%--/1BJJL@ A F Fq IB* +C 8O++GsHceZdZdZy)ra! Represents a nonelementary Integral. Explanation =========== If the result of integrate() is an instance of this class, it is guaranteed to be nonelementary. Note that integrate() by default will try to find any closed-form solution, even in terms of special functions which may themselves not be elementary. To make integrate() only give elementary solutions, or, in the cases where it can prove the integral to be nonelementary, instances of this class, use integrate(risch=True). In this case, integrate() may raise NotImplementedError if it cannot make such a determination. integrate() uses the deterministic Risch algorithm to integrate elementary functions or prove that they have no elementary integral. In some cases, this algorithm can split an integral into an elementary and nonelementary part, so that the result of integrate will be the sum of an elementary expression and a NonElementaryIntegral. Examples ======== >>> from sympy import integrate, exp, log, Integral >>> from sympy.abc import x >>> a = integrate(exp(-x**2), x, risch=True) >>> print(a) Integral(exp(-x**2), x) >>> type(a) >>> expr = (2*log(x)**2 - log(x) - x**2)/(log(x)**3 - x**2*log(x)) >>> b = integrate(expr, x, risch=True) >>> print(b) -log(-x + log(x))/2 + log(x + log(x))/2 + Integral(1/log(x), x) >>> type(b.atoms(Integral).pop()) Nr rr3r1rrqs (\ r3rcnt|}|xst|||d|}|j|j} }tj} t |j D]} |jj|jsV| jj|js1| dk(s,|jt|| f|j\}} |j| d\}} | dk(rt|| ||\} } }nq| dk(rt|| |\} } }nZ| dk(rJt|j!| j!z |j"d } d}tj} n t%d | | z } |r+|jt| |j\}} Q| j'|j(} | j*s9t-| j.j'|j(| j0} |s | | z } | cSt3| t,r| | fcS| d fcSy ) a The Risch Integration Algorithm. Explanation =========== Only transcendental functions are supported. Currently, only exponentials and logarithms are supported, but support for trigonometric functions is forthcoming. If this function returns an unevaluated Integral in the result, it means that it has proven that integral to be nonelementary. Any errors will result in raising NotImplementedError. The unevaluated Integral will be an instance of NonElementaryIntegral, a subclass of Integral. handle_first may be either 'exp' or 'log'. This changes the order in which the extension is built, and may result in a different (but equivalent) solution (for an example of this, see issue 5109). It is also possible that the integral may be computed with one but not the other, because not all cases have been implemented yet. It defaults to 'log' so that the outer extension is exponential when possible, because more of the exponential case has been implemented. If ``separate_integral`` is ``True``, the result is returned as a tuple (ans, i), where the integral is ans + i, ans is elementary, and i is either a NonElementaryIntegral or 0. This useful if you want to try further integrating the NonElementaryIntegral part using other algorithms to possibly get a solution in terms of special functions. It is False by default. Examples ======== >>> from sympy.integrals.risch import risch_integrate >>> from sympy import exp, log, pprint >>> from sympy.abc import x First, we try integrating exp(-x**2). Except for a constant factor of 2/sqrt(pi), this is the famous error function. >>> pprint(risch_integrate(exp(-x**2), x)) / | | 2 | -x | e dx | / The unevaluated Integral in the result means that risch_integrate() has proven that exp(-x**2) does not have an elementary anti-derivative. In many cases, risch_integrate() can split out the elementary anti-derivative part from the nonelementary anti-derivative part. For example, >>> pprint(risch_integrate((2*log(x)**2 - log(x) - x**2)/(log(x)**3 - ... x**2*log(x)), x)) / | log(-x + log(x)) log(x + log(x)) | 1 - ---------------- + --------------- + | ------ dx 2 2 | log(x) | / This means that it has proven that the integral of 1/log(x) is nonelementary. This function is also known as the logarithmic integral, and is often denoted as Li(x). risch_integrate() currently only accepts purely transcendental functions with exponentials and logarithms, though note that this can include nested exponentials and logarithms, as well as exponentials with bases other than E. >>> pprint(risch_integrate(exp(x)*exp(exp(x)), x)) / x\ \e / e >>> pprint(risch_integrate(exp(exp(x)), x)) / | | / x\ | \e / | e dx | / >>> pprint(risch_integrate(x*x**x*log(x) + x**x + x*x**x, x)) x x*x >>> pprint(risch_integrate(x**x, x)) / | | x | x dx | / >>> pprint(risch_integrate(-1/(x*log(x)*log(log(x))**2), x)) 1 ----------- log(log(x)) T)rwr_ryrrr)rr1F)rischzDOnly exponential and logarithmic extensions are currently supported.rN)r rMrRrSrrrXr4rcrZrrur&rrr!rrOrnrrUr7rfunctionlimitsr)rNrOrxrwseparate_integralryrrrRrSresultrYrrFrs r1risch_integratersX !A  9+Aq|9B UUBEEB VVF"%'ww{{244 RTT):46>    b"Xrtt,FB 2t,B 5=22r2UKICA [ +BB7ICA V^BJJL5rtt5ICAA%'23 3 #     Q%FB[[-F99)!**//"++*FqxxP$!  a!67"A;&"A;&K%'r3)FF)FN)FNFrb)NT)Nr)NrFNr)[rtypesr functoolsrsympy.core.functionrsympy.core.mulrsympy.core.intfuncrsympy.core.numbersrsympy.core.powerr sympy.core.relationalr sympy.core.singletonr sympy.core.sortingr r sympy.core.symbolrr&sympy.functions.elementary.exponentialrr%sympy.functions.elementary.hyperbolicrrrr$sympy.functions.elementary.piecewiser(sympy.functions.elementary.trigonometricrrrrrrrr integralsr!r"heurischr#sympy.polys.polyerrorsr$sympy.polys.polytoolsr%r&r'r(r)sympy.polys.rootoftoolsr*sympy.utilities.iterablesr+rKrMrr Exceptionr rrur)rrr;rHrOrarerrrrrrrrrrrrrrrr3r1rs42 &# $"8+;  :   *2  +6@OFq q h"""  Y  ."0+\1 h((V# L!45*p,?&D4B&,^/ H/ d8==A%X'r3