risch.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. """
  2. The Risch Algorithm for transcendental function integration.
  3. The core algorithms for the Risch algorithm are here. The subproblem
  4. algorithms are in the rde.py and prde.py files for the Risch
  5. Differential Equation solver and the parametric problems solvers,
  6. respectively. All important information concerning the differential extension
  7. for an integrand is stored in a DifferentialExtension object, which in the code
  8. is usually called DE. Throughout the code and Inside the DifferentialExtension
  9. object, the conventions/attribute names are that the base domain is QQ and each
  10. differential extension is x, t0, t1, ..., tn-1 = DE.t. DE.x is the variable of
  11. integration (Dx == 1), DE.D is a list of the derivatives of
  12. x, t1, t2, ..., tn-1 = t, DE.T is the list [x, t1, t2, ..., tn-1], DE.t is the
  13. outer-most variable of the differential extension at the given level (the level
  14. can be adjusted using DE.increment_level() and DE.decrement_level()),
  15. k is the field C(x, t0, ..., tn-2), where C is the constant field. The
  16. numerator of a fraction is denoted by a and the denominator by
  17. d. If the fraction is named f, fa == numer(f) and fd == denom(f).
  18. Fractions are returned as tuples (fa, fd). DE.d and DE.t are used to
  19. represent the topmost derivation and extension variable, respectively.
  20. The docstring of a function signifies whether an argument is in k[t], in
  21. which case it will just return a Poly in t, or in k(t), in which case it
  22. will return the fraction (fa, fd). Other variable names probably come
  23. from the names used in Bronstein's book.
  24. """
  25. from types import GeneratorType
  26. from functools import reduce
  27. from sympy.core.function import Lambda
  28. from sympy.core.mul import Mul
  29. from sympy.core.numbers import ilcm, I, oo
  30. from sympy.core.power import Pow
  31. from sympy.core.relational import Ne
  32. from sympy.core.singleton import S
  33. from sympy.core.sorting import ordered, default_sort_key
  34. from sympy.core.symbol import Dummy, Symbol
  35. from sympy.functions.elementary.exponential import log, exp
  36. from sympy.functions.elementary.hyperbolic import (cosh, coth, sinh,
  37. tanh)
  38. from sympy.functions.elementary.piecewise import Piecewise
  39. from sympy.functions.elementary.trigonometric import (atan, sin, cos,
  40. tan, acot, cot, asin, acos)
  41. from .integrals import integrate, Integral
  42. from .heurisch import _symbols
  43. from sympy.polys.polyerrors import DomainError, PolynomialError
  44. from sympy.polys.polytools import (real_roots, cancel, Poly, gcd,
  45. reduced)
  46. from sympy.polys.rootoftools import RootSum
  47. from sympy.utilities.iterables import numbered_symbols
  48. def integer_powers(exprs):
  49. """
  50. Rewrites a list of expressions as integer multiples of each other.
  51. Explanation
  52. ===========
  53. For example, if you have [x, x/2, x**2 + 1, 2*x/3], then you can rewrite
  54. this as [(x/6) * 6, (x/6) * 3, (x**2 + 1) * 1, (x/6) * 4]. This is useful
  55. in the Risch integration algorithm, where we must write exp(x) + exp(x/2)
  56. as (exp(x/2))**2 + exp(x/2), but not as exp(x) + sqrt(exp(x)) (this is
  57. because only the transcendental case is implemented and we therefore cannot
  58. integrate algebraic extensions). The integer multiples returned by this
  59. function for each term are the smallest possible (their content equals 1).
  60. Returns a list of tuples where the first element is the base term and the
  61. second element is a list of `(item, factor)` terms, where `factor` is the
  62. integer multiplicative factor that must multiply the base term to obtain
  63. the original item.
  64. The easiest way to understand this is to look at an example:
  65. >>> from sympy.abc import x
  66. >>> from sympy.integrals.risch import integer_powers
  67. >>> integer_powers([x, x/2, x**2 + 1, 2*x/3])
  68. [(x/6, [(x, 6), (x/2, 3), (2*x/3, 4)]), (x**2 + 1, [(x**2 + 1, 1)])]
  69. We can see how this relates to the example at the beginning of the
  70. docstring. It chose x/6 as the first base term. Then, x can be written as
  71. (x/2) * 2, so we get (0, 2), and so on. Now only element (x**2 + 1)
  72. remains, and there are no other terms that can be written as a rational
  73. multiple of that, so we get that it can be written as (x**2 + 1) * 1.
  74. """
  75. # Here is the strategy:
  76. # First, go through each term and determine if it can be rewritten as a
  77. # rational multiple of any of the terms gathered so far.
  78. # cancel(a/b).is_Rational is sufficient for this. If it is a multiple, we
  79. # add its multiple to the dictionary.
  80. terms = {}
  81. for term in exprs:
  82. for trm, trm_list in terms.items():
  83. a = cancel(term/trm)
  84. if a.is_Rational:
  85. trm_list.append((term, a))
  86. break
  87. else:
  88. terms[term] = [(term, S.One)]
  89. # After we have done this, we have all the like terms together, so we just
  90. # need to find a common denominator so that we can get the base term and
  91. # integer multiples such that each term can be written as an integer
  92. # multiple of the base term, and the content of the integers is 1.
  93. newterms = {}
  94. for term, term_list in terms.items():
  95. common_denom = reduce(ilcm, [i.as_numer_denom()[1] for _, i in
  96. term_list])
  97. newterm = term/common_denom
  98. newmults = [(i, j*common_denom) for i, j in term_list]
  99. newterms[newterm] = newmults
  100. return sorted(iter(newterms.items()), key=lambda item: item[0].sort_key())
  101. class DifferentialExtension:
  102. """
  103. A container for all the information relating to a differential extension.
  104. Explanation
  105. ===========
  106. The attributes of this object are (see also the docstring of __init__):
  107. - f: The original (Expr) integrand.
  108. - x: The variable of integration.
  109. - T: List of variables in the extension.
  110. - D: List of derivations in the extension; corresponds to the elements of T.
  111. - fa: Poly of the numerator of the integrand.
  112. - fd: Poly of the denominator of the integrand.
  113. - Tfuncs: Lambda() representations of each element of T (except for x).
  114. For back-substitution after integration.
  115. - backsubs: A (possibly empty) list of further substitutions to be made on
  116. the final integral to make it look more like the integrand.
  117. - exts:
  118. - extargs:
  119. - cases: List of string representations of the cases of T.
  120. - t: The top level extension variable, as defined by the current level
  121. (see level below).
  122. - d: The top level extension derivation, as defined by the current
  123. derivation (see level below).
  124. - case: The string representation of the case of self.d.
  125. (Note that self.T and self.D will always contain the complete extension,
  126. regardless of the level. Therefore, you should ALWAYS use DE.t and DE.d
  127. instead of DE.T[-1] and DE.D[-1]. If you want to have a list of the
  128. derivations or variables only up to the current level, use
  129. DE.D[:len(DE.D) + DE.level + 1] and DE.T[:len(DE.T) + DE.level + 1]. Note
  130. that, in particular, the derivation() function does this.)
  131. The following are also attributes, but will probably not be useful other
  132. than in internal use:
  133. - newf: Expr form of fa/fd.
  134. - level: The number (between -1 and -len(self.T)) such that
  135. self.T[self.level] == self.t and self.D[self.level] == self.d.
  136. Use the methods self.increment_level() and self.decrement_level() to change
  137. the current level.
  138. """
  139. # __slots__ is defined mainly so we can iterate over all the attributes
  140. # of the class easily (the memory use doesn't matter too much, since we
  141. # only create one DifferentialExtension per integration). Also, it's nice
  142. # to have a safeguard when debugging.
  143. __slots__ = ('f', 'x', 'T', 'D', 'fa', 'fd', 'Tfuncs', 'backsubs',
  144. 'exts', 'extargs', 'cases', 'case', 't', 'd', 'newf', 'level',
  145. 'ts', 'dummy')
  146. def __init__(self, f=None, x=None, handle_first='log', dummy=False, extension=None, rewrite_complex=None):
  147. """
  148. Tries to build a transcendental extension tower from ``f`` with respect to ``x``.
  149. Explanation
  150. ===========
  151. If it is successful, creates a DifferentialExtension object with, among
  152. others, the attributes fa, fd, D, T, Tfuncs, and backsubs such that
  153. fa and fd are Polys in T[-1] with rational coefficients in T[:-1],
  154. fa/fd == f, and D[i] is a Poly in T[i] with rational coefficients in
  155. T[:i] representing the derivative of T[i] for each i from 1 to len(T).
  156. Tfuncs is a list of Lambda objects for back replacing the functions
  157. after integrating. Lambda() is only used (instead of lambda) to make
  158. them easier to test and debug. Note that Tfuncs corresponds to the
  159. elements of T, except for T[0] == x, but they should be back-substituted
  160. in reverse order. backsubs is a (possibly empty) back-substitution list
  161. that should be applied on the completed integral to make it look more
  162. like the original integrand.
  163. If it is unsuccessful, it raises NotImplementedError.
  164. You can also create an object by manually setting the attributes as a
  165. dictionary to the extension keyword argument. You must include at least
  166. D. Warning, any attribute that is not given will be set to None. The
  167. attributes T, t, d, cases, case, x, and level are set automatically and
  168. do not need to be given. The functions in the Risch Algorithm will NOT
  169. check to see if an attribute is None before using it. This also does not
  170. check to see if the extension is valid (non-algebraic) or even if it is
  171. self-consistent. Therefore, this should only be used for
  172. testing/debugging purposes.
  173. """
  174. # XXX: If you need to debug this function, set the break point here
  175. if extension:
  176. if 'D' not in extension:
  177. raise ValueError("At least the key D must be included with "
  178. "the extension flag to DifferentialExtension.")
  179. for attr in extension:
  180. setattr(self, attr, extension[attr])
  181. self._auto_attrs()
  182. return
  183. elif f is None or x is None:
  184. raise ValueError("Either both f and x or a manual extension must "
  185. "be given.")
  186. if handle_first not in ('log', 'exp'):
  187. raise ValueError("handle_first must be 'log' or 'exp', not %s." %
  188. str(handle_first))
  189. # f will be the original function, self.f might change if we reset
  190. # (e.g., we pull out a constant from an exponential)
  191. self.f = f
  192. self.x = x
  193. # setting the default value 'dummy'
  194. self.dummy = dummy
  195. self.reset()
  196. exp_new_extension, log_new_extension = True, True
  197. # case of 'automatic' choosing
  198. if rewrite_complex is None:
  199. rewrite_complex = I in self.f.atoms()
  200. if rewrite_complex:
  201. rewritables = {
  202. (sin, cos, cot, tan, sinh, cosh, coth, tanh): exp,
  203. (asin, acos, acot, atan): log,
  204. }
  205. # rewrite the trigonometric components
  206. for candidates, rule in rewritables.items():
  207. self.newf = self.newf.rewrite(candidates, rule)
  208. self.newf = cancel(self.newf)
  209. else:
  210. if any(i.has(x) for i in self.f.atoms(sin, cos, tan, atan, asin, acos)):
  211. raise NotImplementedError("Trigonometric extensions are not "
  212. "supported (yet!)")
  213. exps = set()
  214. pows = set()
  215. numpows = set()
  216. sympows = set()
  217. logs = set()
  218. symlogs = set()
  219. while True:
  220. if self.newf.is_rational_function(*self.T):
  221. break
  222. if not exp_new_extension and not log_new_extension:
  223. # We couldn't find a new extension on the last pass, so I guess
  224. # we can't do it.
  225. raise NotImplementedError("Couldn't find an elementary "
  226. "transcendental extension for %s. Try using a " % str(f) +
  227. "manual extension with the extension flag.")
  228. exps, pows, numpows, sympows, log_new_extension = \
  229. self._rewrite_exps_pows(exps, pows, numpows, sympows, log_new_extension)
  230. logs, symlogs = self._rewrite_logs(logs, symlogs)
  231. if handle_first == 'exp' or not log_new_extension:
  232. exp_new_extension = self._exp_part(exps)
  233. if exp_new_extension is None:
  234. # reset and restart
  235. self.f = self.newf
  236. self.reset()
  237. exp_new_extension = True
  238. continue
  239. if handle_first == 'log' or not exp_new_extension:
  240. log_new_extension = self._log_part(logs)
  241. self.fa, self.fd = frac_in(self.newf, self.t)
  242. self._auto_attrs()
  243. return
  244. def __getattr__(self, attr):
  245. # Avoid AttributeErrors when debugging
  246. if attr not in self.__slots__:
  247. raise AttributeError("%s has no attribute %s" % (repr(self), repr(attr)))
  248. return None
  249. def _rewrite_exps_pows(self, exps, pows, numpows,
  250. sympows, log_new_extension):
  251. """
  252. Rewrite exps/pows for better processing.
  253. """
  254. from .prde import is_deriv_k
  255. # Pre-preparsing.
  256. #################
  257. # Get all exp arguments, so we can avoid ahead of time doing
  258. # something like t1 = exp(x), t2 = exp(x/2) == sqrt(t1).
  259. # Things like sqrt(exp(x)) do not automatically simplify to
  260. # exp(x/2), so they will be viewed as algebraic. The easiest way
  261. # to handle this is to convert all instances of (a**b)**Rational
  262. # to a**(Rational*b) before doing anything else. Note that the
  263. # _exp_part code can generate terms of this form, so we do need to
  264. # do this at each pass (or else modify it to not do that).
  265. ratpows = [i for i in self.newf.atoms(Pow).union(self.newf.atoms(exp))
  266. if (i.base.is_Pow or isinstance(i.base, exp) and i.exp.is_Rational)]
  267. ratpows_repl = [
  268. (i, i.base.base**(i.exp*i.base.exp)) for i in ratpows]
  269. self.backsubs += [(j, i) for i, j in ratpows_repl]
  270. self.newf = self.newf.xreplace(dict(ratpows_repl))
  271. # To make the process deterministic, the args are sorted
  272. # so that functions with smaller op-counts are processed first.
  273. # Ties are broken with the default_sort_key.
  274. # XXX Although the method is deterministic no additional work
  275. # has been done to guarantee that the simplest solution is
  276. # returned and that it would be affected be using different
  277. # variables. Though it is possible that this is the case
  278. # one should know that it has not been done intentionally, so
  279. # further improvements may be possible.
  280. # TODO: This probably doesn't need to be completely recomputed at
  281. # each pass.
  282. exps = update_sets(exps, self.newf.atoms(exp),
  283. lambda i: i.exp.is_rational_function(*self.T) and
  284. i.exp.has(*self.T))
  285. pows = update_sets(pows, self.newf.atoms(Pow),
  286. lambda i: i.exp.is_rational_function(*self.T) and
  287. i.exp.has(*self.T))
  288. numpows = update_sets(numpows, set(pows),
  289. lambda i: not i.base.has(*self.T))
  290. sympows = update_sets(sympows, set(pows) - set(numpows),
  291. lambda i: i.base.is_rational_function(*self.T) and
  292. not i.exp.is_Integer)
  293. # The easiest way to deal with non-base E powers is to convert them
  294. # into base E, integrate, and then convert back.
  295. for i in ordered(pows):
  296. old = i
  297. new = exp(i.exp*log(i.base))
  298. # If exp is ever changed to automatically reduce exp(x*log(2))
  299. # to 2**x, then this will break. The solution is to not change
  300. # exp to do that :)
  301. if i in sympows:
  302. if i.exp.is_Rational:
  303. raise NotImplementedError("Algebraic extensions are "
  304. "not supported (%s)." % str(i))
  305. # We can add a**b only if log(a) in the extension, because
  306. # a**b == exp(b*log(a)).
  307. basea, based = frac_in(i.base, self.t)
  308. A = is_deriv_k(basea, based, self)
  309. if A is None:
  310. # Nonelementary monomial (so far)
  311. # TODO: Would there ever be any benefit from just
  312. # adding log(base) as a new monomial?
  313. # ANSWER: Yes, otherwise we can't integrate x**x (or
  314. # rather prove that it has no elementary integral)
  315. # without first manually rewriting it as exp(x*log(x))
  316. self.newf = self.newf.xreplace({old: new})
  317. self.backsubs += [(new, old)]
  318. log_new_extension = self._log_part([log(i.base)])
  319. exps = update_sets(exps, self.newf.atoms(exp), lambda i:
  320. i.exp.is_rational_function(*self.T) and i.exp.has(*self.T))
  321. continue
  322. ans, u, const = A
  323. newterm = exp(i.exp*(log(const) + u))
  324. # Under the current implementation, exp kills terms
  325. # only if they are of the form a*log(x), where a is a
  326. # Number. This case should have already been killed by the
  327. # above tests. Again, if this changes to kill more than
  328. # that, this will break, which maybe is a sign that you
  329. # shouldn't be changing that. Actually, if anything, this
  330. # auto-simplification should be removed. See
  331. # http://groups.google.com/group/sympy/browse_thread/thread/a61d48235f16867f
  332. self.newf = self.newf.xreplace({i: newterm})
  333. elif i not in numpows:
  334. continue
  335. else:
  336. # i in numpows
  337. newterm = new
  338. # TODO: Just put it in self.Tfuncs
  339. self.backsubs.append((new, old))
  340. self.newf = self.newf.xreplace({old: newterm})
  341. exps.append(newterm)
  342. return exps, pows, numpows, sympows, log_new_extension
  343. def _rewrite_logs(self, logs, symlogs):
  344. """
  345. Rewrite logs for better processing.
  346. """
  347. atoms = self.newf.atoms(log)
  348. logs = update_sets(logs, atoms,
  349. lambda i: i.args[0].is_rational_function(*self.T) and
  350. i.args[0].has(*self.T))
  351. symlogs = update_sets(symlogs, atoms,
  352. lambda i: i.has(*self.T) and i.args[0].is_Pow and
  353. i.args[0].base.is_rational_function(*self.T) and
  354. not i.args[0].exp.is_Integer)
  355. # We can handle things like log(x**y) by converting it to y*log(x)
  356. # This will fix not only symbolic exponents of the argument, but any
  357. # non-Integer exponent, like log(sqrt(x)). The exponent can also
  358. # depend on x, like log(x**x).
  359. for i in ordered(symlogs):
  360. # Unlike in the exponential case above, we do not ever
  361. # potentially add new monomials (above we had to add log(a)).
  362. # Therefore, there is no need to run any is_deriv functions
  363. # here. Just convert log(a**b) to b*log(a) and let
  364. # log_new_extension() handle it from there.
  365. lbase = log(i.args[0].base)
  366. logs.append(lbase)
  367. new = i.args[0].exp*lbase
  368. self.newf = self.newf.xreplace({i: new})
  369. self.backsubs.append((new, i))
  370. # remove any duplicates
  371. logs = sorted(set(logs), key=default_sort_key)
  372. return logs, symlogs
  373. def _auto_attrs(self):
  374. """
  375. Set attributes that are generated automatically.
  376. """
  377. if not self.T:
  378. # i.e., when using the extension flag and T isn't given
  379. self.T = [i.gen for i in self.D]
  380. if not self.x:
  381. self.x = self.T[0]
  382. self.cases = [get_case(d, t) for d, t in zip(self.D, self.T)]
  383. self.level = -1
  384. self.t = self.T[self.level]
  385. self.d = self.D[self.level]
  386. self.case = self.cases[self.level]
  387. def _exp_part(self, exps):
  388. """
  389. Try to build an exponential extension.
  390. Returns
  391. =======
  392. Returns True if there was a new extension, False if there was no new
  393. extension but it was able to rewrite the given exponentials in terms
  394. of the existing extension, and None if the entire extension building
  395. process should be restarted. If the process fails because there is no
  396. way around an algebraic extension (e.g., exp(log(x)/2)), it will raise
  397. NotImplementedError.
  398. """
  399. from .prde import is_log_deriv_k_t_radical
  400. new_extension = False
  401. restart = False
  402. expargs = [i.exp for i in exps]
  403. ip = integer_powers(expargs)
  404. for arg, others in ip:
  405. # Minimize potential problems with algebraic substitution
  406. others.sort(key=lambda i: i[1])
  407. arga, argd = frac_in(arg, self.t)
  408. A = is_log_deriv_k_t_radical(arga, argd, self)
  409. if A is not None:
  410. ans, u, n, const = A
  411. # if n is 1 or -1, it's algebraic, but we can handle it
  412. if n == -1:
  413. # This probably will never happen, because
  414. # Rational.as_numer_denom() returns the negative term in
  415. # the numerator. But in case that changes, reduce it to
  416. # n == 1.
  417. n = 1
  418. u **= -1
  419. const *= -1
  420. ans = [(i, -j) for i, j in ans]
  421. if n == 1:
  422. # Example: exp(x + x**2) over QQ(x, exp(x), exp(x**2))
  423. self.newf = self.newf.xreplace({exp(arg): exp(const)*Mul(*[
  424. u**power for u, power in ans])})
  425. self.newf = self.newf.xreplace({exp(p*exparg):
  426. exp(const*p) * Mul(*[u**power for u, power in ans])
  427. for exparg, p in others})
  428. # TODO: Add something to backsubs to put exp(const*p)
  429. # back together.
  430. continue
  431. else:
  432. # Bad news: we have an algebraic radical. But maybe we
  433. # could still avoid it by choosing a different extension.
  434. # For example, integer_powers() won't handle exp(x/2 + 1)
  435. # over QQ(x, exp(x)), but if we pull out the exp(1), it
  436. # will. Or maybe we have exp(x + x**2/2), over
  437. # QQ(x, exp(x), exp(x**2)), which is exp(x)*sqrt(exp(x**2)),
  438. # but if we use QQ(x, exp(x), exp(x**2/2)), then they will
  439. # all work.
  440. #
  441. # So here is what we do: If there is a non-zero const, pull
  442. # it out and retry. Also, if len(ans) > 1, then rewrite
  443. # exp(arg) as the product of exponentials from ans, and
  444. # retry that. If const == 0 and len(ans) == 1, then we
  445. # assume that it would have been handled by either
  446. # integer_powers() or n == 1 above if it could be handled,
  447. # so we give up at that point. For example, you can never
  448. # handle exp(log(x)/2) because it equals sqrt(x).
  449. if const or len(ans) > 1:
  450. rad = Mul(*[term**(power/n) for term, power in ans])
  451. self.newf = self.newf.xreplace({exp(p*exparg):
  452. exp(const*p)*rad for exparg, p in others})
  453. self.newf = self.newf.xreplace(dict(list(zip(reversed(self.T),
  454. reversed([f(self.x) for f in self.Tfuncs])))))
  455. restart = True
  456. break
  457. else:
  458. # TODO: give algebraic dependence in error string
  459. raise NotImplementedError("Cannot integrate over "
  460. "algebraic extensions.")
  461. else:
  462. arga, argd = frac_in(arg, self.t)
  463. darga = (argd*derivation(Poly(arga, self.t), self) -
  464. arga*derivation(Poly(argd, self.t), self))
  465. dargd = argd**2
  466. darga, dargd = darga.cancel(dargd, include=True)
  467. darg = darga.as_expr()/dargd.as_expr()
  468. self.t = next(self.ts)
  469. self.T.append(self.t)
  470. self.extargs.append(arg)
  471. self.exts.append('exp')
  472. self.D.append(darg.as_poly(self.t, expand=False)*Poly(self.t,
  473. self.t, expand=False))
  474. if self.dummy:
  475. i = Dummy("i")
  476. else:
  477. i = Symbol('i')
  478. self.Tfuncs += [Lambda(i, exp(arg.subs(self.x, i)))]
  479. self.newf = self.newf.xreplace(
  480. {exp(exparg): self.t**p for exparg, p in others})
  481. new_extension = True
  482. if restart:
  483. return None
  484. return new_extension
  485. def _log_part(self, logs):
  486. """
  487. Try to build a logarithmic extension.
  488. Returns
  489. =======
  490. Returns True if there was a new extension and False if there was no new
  491. extension but it was able to rewrite the given logarithms in terms
  492. of the existing extension. Unlike with exponential extensions, there
  493. is no way that a logarithm is not transcendental over and cannot be
  494. rewritten in terms of an already existing extension in a non-algebraic
  495. way, so this function does not ever return None or raise
  496. NotImplementedError.
  497. """
  498. from .prde import is_deriv_k
  499. new_extension = False
  500. logargs = [i.args[0] for i in logs]
  501. for arg in ordered(logargs):
  502. # The log case is easier, because whenever a logarithm is algebraic
  503. # over the base field, it is of the form a1*t1 + ... an*tn + c,
  504. # which is a polynomial, so we can just replace it with that.
  505. # In other words, we don't have to worry about radicals.
  506. arga, argd = frac_in(arg, self.t)
  507. A = is_deriv_k(arga, argd, self)
  508. if A is not None:
  509. ans, u, const = A
  510. newterm = log(const) + u
  511. self.newf = self.newf.xreplace({log(arg): newterm})
  512. continue
  513. else:
  514. arga, argd = frac_in(arg, self.t)
  515. darga = (argd*derivation(Poly(arga, self.t), self) -
  516. arga*derivation(Poly(argd, self.t), self))
  517. dargd = argd**2
  518. darg = darga.as_expr()/dargd.as_expr()
  519. self.t = next(self.ts)
  520. self.T.append(self.t)
  521. self.extargs.append(arg)
  522. self.exts.append('log')
  523. self.D.append(cancel(darg.as_expr()/arg).as_poly(self.t,
  524. expand=False))
  525. if self.dummy:
  526. i = Dummy("i")
  527. else:
  528. i = Symbol('i')
  529. self.Tfuncs += [Lambda(i, log(arg.subs(self.x, i)))]
  530. self.newf = self.newf.xreplace({log(arg): self.t})
  531. new_extension = True
  532. return new_extension
  533. @property
  534. def _important_attrs(self):
  535. """
  536. Returns some of the more important attributes of self.
  537. Explanation
  538. ===========
  539. Used for testing and debugging purposes.
  540. The attributes are (fa, fd, D, T, Tfuncs, backsubs,
  541. exts, extargs).
  542. """
  543. return (self.fa, self.fd, self.D, self.T, self.Tfuncs,
  544. self.backsubs, self.exts, self.extargs)
  545. # NOTE: this printing doesn't follow the Python's standard
  546. # eval(repr(DE)) == DE, where DE is the DifferentialExtension object,
  547. # also this printing is supposed to contain all the important
  548. # attributes of a DifferentialExtension object
  549. def __repr__(self):
  550. # no need to have GeneratorType object printed in it
  551. r = [(attr, getattr(self, attr)) for attr in self.__slots__
  552. if not isinstance(getattr(self, attr), GeneratorType)]
  553. return self.__class__.__name__ + '(dict(%r))' % (r)
  554. # fancy printing of DifferentialExtension object
  555. def __str__(self):
  556. return (self.__class__.__name__ + '({fa=%s, fd=%s, D=%s})' %
  557. (self.fa, self.fd, self.D))
  558. # should only be used for debugging purposes, internally
  559. # f1 = f2 = log(x) at different places in code execution
  560. # may return D1 != D2 as True, since 'level' or other attribute
  561. # may differ
  562. def __eq__(self, other):
  563. for attr in self.__class__.__slots__:
  564. d1, d2 = getattr(self, attr), getattr(other, attr)
  565. if not (isinstance(d1, GeneratorType) or d1 == d2):
  566. return False
  567. return True
  568. def reset(self):
  569. """
  570. Reset self to an initial state. Used by __init__.
  571. """
  572. self.t = self.x
  573. self.T = [self.x]
  574. self.D = [Poly(1, self.x)]
  575. self.level = -1
  576. self.exts = [None]
  577. self.extargs = [None]
  578. if self.dummy:
  579. self.ts = numbered_symbols('t', cls=Dummy)
  580. else:
  581. # For testing
  582. self.ts = numbered_symbols('t')
  583. # For various things that we change to make things work that we need to
  584. # change back when we are done.
  585. self.backsubs = []
  586. self.Tfuncs = []
  587. self.newf = self.f
  588. def indices(self, extension):
  589. """
  590. Parameters
  591. ==========
  592. extension : str
  593. Represents a valid extension type.
  594. Returns
  595. =======
  596. list: A list of indices of 'exts' where extension of
  597. type 'extension' is present.
  598. Examples
  599. ========
  600. >>> from sympy.integrals.risch import DifferentialExtension
  601. >>> from sympy import log, exp
  602. >>> from sympy.abc import x
  603. >>> DE = DifferentialExtension(log(x) + exp(x), x, handle_first='exp')
  604. >>> DE.indices('log')
  605. [2]
  606. >>> DE.indices('exp')
  607. [1]
  608. """
  609. return [i for i, ext in enumerate(self.exts) if ext == extension]
  610. def increment_level(self):
  611. """
  612. Increment the level of self.
  613. Explanation
  614. ===========
  615. This makes the working differential extension larger. self.level is
  616. given relative to the end of the list (-1, -2, etc.), so we do not need
  617. do worry about it when building the extension.
  618. """
  619. if self.level >= -1:
  620. raise ValueError("The level of the differential extension cannot "
  621. "be incremented any further.")
  622. self.level += 1
  623. self.t = self.T[self.level]
  624. self.d = self.D[self.level]
  625. self.case = self.cases[self.level]
  626. return None
  627. def decrement_level(self):
  628. """
  629. Decrease the level of self.
  630. Explanation
  631. ===========
  632. This makes the working differential extension smaller. self.level is
  633. given relative to the end of the list (-1, -2, etc.), so we do not need
  634. do worry about it when building the extension.
  635. """
  636. if self.level <= -len(self.T):
  637. raise ValueError("The level of the differential extension cannot "
  638. "be decremented any further.")
  639. self.level -= 1
  640. self.t = self.T[self.level]
  641. self.d = self.D[self.level]
  642. self.case = self.cases[self.level]
  643. return None
  644. def update_sets(seq, atoms, func):
  645. s = set(seq)
  646. s = atoms.intersection(s)
  647. new = atoms - s
  648. s.update(list(filter(func, new)))
  649. return list(s)
  650. class DecrementLevel:
  651. """
  652. A context manager for decrementing the level of a DifferentialExtension.
  653. """
  654. __slots__ = ('DE',)
  655. def __init__(self, DE):
  656. self.DE = DE
  657. return
  658. def __enter__(self):
  659. self.DE.decrement_level()
  660. def __exit__(self, exc_type, exc_value, traceback):
  661. self.DE.increment_level()
  662. class NonElementaryIntegralException(Exception):
  663. """
  664. Exception used by subroutines within the Risch algorithm to indicate to one
  665. another that the function being integrated does not have an elementary
  666. integral in the given differential field.
  667. """
  668. # TODO: Rewrite algorithms below to use this (?)
  669. # TODO: Pass through information about why the integral was nonelementary,
  670. # and store that in the resulting NonElementaryIntegral somehow.
  671. pass
  672. def gcdex_diophantine(a, b, c):
  673. """
  674. Extended Euclidean Algorithm, Diophantine version.
  675. Explanation
  676. ===========
  677. Given ``a``, ``b`` in K[x] and ``c`` in (a, b), the ideal generated by ``a`` and
  678. ``b``, return (s, t) such that s*a + t*b == c and either s == 0 or s.degree()
  679. < b.degree().
  680. """
  681. # Extended Euclidean Algorithm (Diophantine Version) pg. 13
  682. # TODO: This should go in densetools.py.
  683. # XXX: Bettter name?
  684. s, g = a.half_gcdex(b)
  685. s *= c.exquo(g) # Inexact division means c is not in (a, b)
  686. if s and s.degree() >= b.degree():
  687. _, s = s.div(b)
  688. t = (c - s*a).exquo(b)
  689. return (s, t)
  690. def frac_in(f, t, *, cancel=False, **kwargs):
  691. """
  692. Returns the tuple (fa, fd), where fa and fd are Polys in t.
  693. Explanation
  694. ===========
  695. This is a common idiom in the Risch Algorithm functions, so we abstract
  696. it out here. ``f`` should be a basic expression, a Poly, or a tuple (fa, fd),
  697. where fa and fd are either basic expressions or Polys, and f == fa/fd.
  698. **kwargs are applied to Poly.
  699. """
  700. if isinstance(f, tuple):
  701. fa, fd = f
  702. f = fa.as_expr()/fd.as_expr()
  703. fa, fd = f.as_expr().as_numer_denom()
  704. fa, fd = fa.as_poly(t, **kwargs), fd.as_poly(t, **kwargs)
  705. if cancel:
  706. fa, fd = fa.cancel(fd, include=True)
  707. if fa is None or fd is None:
  708. raise ValueError("Could not turn %s into a fraction in %s." % (f, t))
  709. return (fa, fd)
  710. def as_poly_1t(p, t, z):
  711. """
  712. (Hackish) way to convert an element ``p`` of K[t, 1/t] to K[t, z].
  713. In other words, ``z == 1/t`` will be a dummy variable that Poly can handle
  714. better.
  715. See issue 5131.
  716. Examples
  717. ========
  718. >>> from sympy import random_poly
  719. >>> from sympy.integrals.risch import as_poly_1t
  720. >>> from sympy.abc import x, z
  721. >>> p1 = random_poly(x, 10, -10, 10)
  722. >>> p2 = random_poly(x, 10, -10, 10)
  723. >>> p = p1 + p2.subs(x, 1/x)
  724. >>> as_poly_1t(p, x, z).as_expr().subs(z, 1/x) == p
  725. True
  726. """
  727. # TODO: Use this on the final result. That way, we can avoid answers like
  728. # (...)*exp(-x).
  729. pa, pd = frac_in(p, t, cancel=True)
  730. if not pd.is_monomial:
  731. # XXX: Is there a better Poly exception that we could raise here?
  732. # Either way, if you see this (from the Risch Algorithm) it indicates
  733. # a bug.
  734. raise PolynomialError("%s is not an element of K[%s, 1/%s]." % (p, t, t))
  735. d = pd.degree(t)
  736. one_t_part = pa.slice(0, d + 1)
  737. r = pd.degree() - pa.degree()
  738. t_part = pa - one_t_part
  739. try:
  740. t_part = t_part.to_field().exquo(pd)
  741. except DomainError as e:
  742. # issue 4950
  743. raise NotImplementedError(e)
  744. # Compute the negative degree parts.
  745. one_t_part = Poly.from_list(reversed(one_t_part.rep.rep), *one_t_part.gens,
  746. domain=one_t_part.domain)
  747. if 0 < r < oo:
  748. one_t_part *= Poly(t**r, t)
  749. one_t_part = one_t_part.replace(t, z) # z will be 1/t
  750. if pd.nth(d):
  751. one_t_part *= Poly(1/pd.nth(d), z, expand=False)
  752. ans = t_part.as_poly(t, z, expand=False) + one_t_part.as_poly(t, z,
  753. expand=False)
  754. return ans
  755. def derivation(p, DE, coefficientD=False, basic=False):
  756. """
  757. Computes Dp.
  758. Explanation
  759. ===========
  760. Given the derivation D with D = d/dx and p is a polynomial in t over
  761. K(x), return Dp.
  762. If coefficientD is True, it computes the derivation kD
  763. (kappaD), which is defined as kD(sum(ai*Xi**i, (i, 0, n))) ==
  764. sum(Dai*Xi**i, (i, 1, n)) (Definition 3.2.2, page 80). X in this case is
  765. T[-1], so coefficientD computes the derivative just with respect to T[:-1],
  766. with T[-1] treated as a constant.
  767. If ``basic=True``, the returns a Basic expression. Elements of D can still be
  768. instances of Poly.
  769. """
  770. if basic:
  771. r = 0
  772. else:
  773. r = Poly(0, DE.t)
  774. t = DE.t
  775. if coefficientD:
  776. if DE.level <= -len(DE.T):
  777. # 'base' case, the answer is 0.
  778. return r
  779. DE.decrement_level()
  780. D = DE.D[:len(DE.D) + DE.level + 1]
  781. T = DE.T[:len(DE.T) + DE.level + 1]
  782. for d, v in zip(D, T):
  783. pv = p.as_poly(v)
  784. if pv is None or basic:
  785. pv = p.as_expr()
  786. if basic:
  787. r += d.as_expr()*pv.diff(v)
  788. else:
  789. r += (d.as_expr()*pv.diff(v).as_expr()).as_poly(t)
  790. if basic:
  791. r = cancel(r)
  792. if coefficientD:
  793. DE.increment_level()
  794. return r
  795. def get_case(d, t):
  796. """
  797. Returns the type of the derivation d.
  798. Returns one of {'exp', 'tan', 'base', 'primitive', 'other_linear',
  799. 'other_nonlinear'}.
  800. """
  801. if not d.expr.has(t):
  802. if d.is_one:
  803. return 'base'
  804. return 'primitive'
  805. if d.rem(Poly(t, t)).is_zero:
  806. return 'exp'
  807. if d.rem(Poly(1 + t**2, t)).is_zero:
  808. return 'tan'
  809. if d.degree(t) > 1:
  810. return 'other_nonlinear'
  811. return 'other_linear'
  812. def splitfactor(p, DE, coefficientD=False, z=None):
  813. """
  814. Splitting factorization.
  815. Explanation
  816. ===========
  817. Given a derivation D on k[t] and ``p`` in k[t], return (p_n, p_s) in
  818. k[t] x k[t] such that p = p_n*p_s, p_s is special, and each square
  819. factor of p_n is normal.
  820. Page. 100
  821. """
  822. kinv = [1/x for x in DE.T[:DE.level]]
  823. if z:
  824. kinv.append(z)
  825. One = Poly(1, DE.t, domain=p.get_domain())
  826. Dp = derivation(p, DE, coefficientD=coefficientD)
  827. # XXX: Is this right?
  828. if p.is_zero:
  829. return (p, One)
  830. if not p.expr.has(DE.t):
  831. s = p.as_poly(*kinv).gcd(Dp.as_poly(*kinv)).as_poly(DE.t)
  832. n = p.exquo(s)
  833. return (n, s)
  834. if not Dp.is_zero:
  835. h = p.gcd(Dp).to_field()
  836. g = p.gcd(p.diff(DE.t)).to_field()
  837. s = h.exquo(g)
  838. if s.degree(DE.t) == 0:
  839. return (p, One)
  840. q_split = splitfactor(p.exquo(s), DE, coefficientD=coefficientD)
  841. return (q_split[0], q_split[1]*s)
  842. else:
  843. return (p, One)
  844. def splitfactor_sqf(p, DE, coefficientD=False, z=None, basic=False):
  845. """
  846. Splitting Square-free Factorization.
  847. Explanation
  848. ===========
  849. Given a derivation D on k[t] and ``p`` in k[t], returns (N1, ..., Nm)
  850. and (S1, ..., Sm) in k[t]^m such that p =
  851. (N1*N2**2*...*Nm**m)*(S1*S2**2*...*Sm**m) is a splitting
  852. factorization of ``p`` and the Ni and Si are square-free and coprime.
  853. """
  854. # TODO: This algorithm appears to be faster in every case
  855. # TODO: Verify this and splitfactor() for multiple extensions
  856. kkinv = [1/x for x in DE.T[:DE.level]] + DE.T[:DE.level]
  857. if z:
  858. kkinv = [z]
  859. S = []
  860. N = []
  861. p_sqf = p.sqf_list_include()
  862. if p.is_zero:
  863. return (((p, 1),), ())
  864. for pi, i in p_sqf:
  865. Si = pi.as_poly(*kkinv).gcd(derivation(pi, DE,
  866. coefficientD=coefficientD,basic=basic).as_poly(*kkinv)).as_poly(DE.t)
  867. pi = Poly(pi, DE.t)
  868. Si = Poly(Si, DE.t)
  869. Ni = pi.exquo(Si)
  870. if not Si.is_one:
  871. S.append((Si, i))
  872. if not Ni.is_one:
  873. N.append((Ni, i))
  874. return (tuple(N), tuple(S))
  875. def canonical_representation(a, d, DE):
  876. """
  877. Canonical Representation.
  878. Explanation
  879. ===========
  880. Given a derivation D on k[t] and f = a/d in k(t), return (f_p, f_s,
  881. f_n) in k[t] x k(t) x k(t) such that f = f_p + f_s + f_n is the
  882. canonical representation of f (f_p is a polynomial, f_s is reduced
  883. (has a special denominator), and f_n is simple (has a normal
  884. denominator).
  885. """
  886. # Make d monic
  887. l = Poly(1/d.LC(), DE.t)
  888. a, d = a.mul(l), d.mul(l)
  889. q, r = a.div(d)
  890. dn, ds = splitfactor(d, DE)
  891. b, c = gcdex_diophantine(dn.as_poly(DE.t), ds.as_poly(DE.t), r.as_poly(DE.t))
  892. b, c = b.as_poly(DE.t), c.as_poly(DE.t)
  893. return (q, (b, ds), (c, dn))
  894. def hermite_reduce(a, d, DE):
  895. """
  896. Hermite Reduction - Mack's Linear Version.
  897. Given a derivation D on k(t) and f = a/d in k(t), returns g, h, r in
  898. k(t) such that f = Dg + h + r, h is simple, and r is reduced.
  899. """
  900. # Make d monic
  901. l = Poly(1/d.LC(), DE.t)
  902. a, d = a.mul(l), d.mul(l)
  903. fp, fs, fn = canonical_representation(a, d, DE)
  904. a, d = fn
  905. l = Poly(1/d.LC(), DE.t)
  906. a, d = a.mul(l), d.mul(l)
  907. ga = Poly(0, DE.t)
  908. gd = Poly(1, DE.t)
  909. dd = derivation(d, DE)
  910. dm = gcd(d.to_field(), dd.to_field()).as_poly(DE.t)
  911. ds, _ = d.div(dm)
  912. while dm.degree(DE.t) > 0:
  913. ddm = derivation(dm, DE)
  914. dm2 = gcd(dm.to_field(), ddm.to_field())
  915. dms, _ = dm.div(dm2)
  916. ds_ddm = ds.mul(ddm)
  917. ds_ddm_dm, _ = ds_ddm.div(dm)
  918. b, c = gcdex_diophantine(-ds_ddm_dm.as_poly(DE.t),
  919. dms.as_poly(DE.t), a.as_poly(DE.t))
  920. b, c = b.as_poly(DE.t), c.as_poly(DE.t)
  921. db = derivation(b, DE).as_poly(DE.t)
  922. ds_dms, _ = ds.div(dms)
  923. a = c.as_poly(DE.t) - db.mul(ds_dms).as_poly(DE.t)
  924. ga = ga*dm + b*gd
  925. gd = gd*dm
  926. ga, gd = ga.cancel(gd, include=True)
  927. dm = dm2
  928. q, r = a.div(ds)
  929. ga, gd = ga.cancel(gd, include=True)
  930. r, d = r.cancel(ds, include=True)
  931. rra = q*fs[1] + fp*fs[1] + fs[0]
  932. rrd = fs[1]
  933. rra, rrd = rra.cancel(rrd, include=True)
  934. return ((ga, gd), (r, d), (rra, rrd))
  935. def polynomial_reduce(p, DE):
  936. """
  937. Polynomial Reduction.
  938. Explanation
  939. ===========
  940. Given a derivation D on k(t) and p in k[t] where t is a nonlinear
  941. monomial over k, return q, r in k[t] such that p = Dq + r, and
  942. deg(r) < deg_t(Dt).
  943. """
  944. q = Poly(0, DE.t)
  945. while p.degree(DE.t) >= DE.d.degree(DE.t):
  946. m = p.degree(DE.t) - DE.d.degree(DE.t) + 1
  947. q0 = Poly(DE.t**m, DE.t).mul(Poly(p.as_poly(DE.t).LC()/
  948. (m*DE.d.LC()), DE.t))
  949. q += q0
  950. p = p - derivation(q0, DE)
  951. return (q, p)
  952. def laurent_series(a, d, F, n, DE):
  953. """
  954. Contribution of ``F`` to the full partial fraction decomposition of A/D.
  955. Explanation
  956. ===========
  957. Given a field K of characteristic 0 and ``A``,``D``,``F`` in K[x] with D monic,
  958. nonzero, coprime with A, and ``F`` the factor of multiplicity n in the square-
  959. free factorization of D, return the principal parts of the Laurent series of
  960. A/D at all the zeros of ``F``.
  961. """
  962. if F.degree()==0:
  963. return 0
  964. Z = _symbols('z', n)
  965. z = Symbol('z')
  966. Z.insert(0, z)
  967. delta_a = Poly(0, DE.t)
  968. delta_d = Poly(1, DE.t)
  969. E = d.quo(F**n)
  970. ha, hd = (a, E*Poly(z**n, DE.t))
  971. dF = derivation(F,DE)
  972. B, _ = gcdex_diophantine(E, F, Poly(1,DE.t))
  973. C, _ = gcdex_diophantine(dF, F, Poly(1,DE.t))
  974. # initialization
  975. F_store = F
  976. V, DE_D_list, H_list= [], [], []
  977. for j in range(0, n):
  978. # jth derivative of z would be substituted with dfnth/(j+1) where dfnth =(d^n)f/(dx)^n
  979. F_store = derivation(F_store, DE)
  980. v = (F_store.as_expr())/(j + 1)
  981. V.append(v)
  982. DE_D_list.append(Poly(Z[j + 1],Z[j]))
  983. DE_new = DifferentialExtension(extension = {'D': DE_D_list}) #a differential indeterminate
  984. for j in range(0, n):
  985. zEha = Poly(z**(n + j), DE.t)*E**(j + 1)*ha
  986. zEhd = hd
  987. Pa, Pd = cancel((zEha, zEhd))[1], cancel((zEha, zEhd))[2]
  988. Q = Pa.quo(Pd)
  989. for i in range(0, j + 1):
  990. Q = Q.subs(Z[i], V[i])
  991. Dha = (hd*derivation(ha, DE, basic=True).as_poly(DE.t)
  992. + ha*derivation(hd, DE, basic=True).as_poly(DE.t)
  993. + hd*derivation(ha, DE_new, basic=True).as_poly(DE.t)
  994. + ha*derivation(hd, DE_new, basic=True).as_poly(DE.t))
  995. Dhd = Poly(j + 1, DE.t)*hd**2
  996. ha, hd = Dha, Dhd
  997. Ff, _ = F.div(gcd(F, Q))
  998. F_stara, F_stard = frac_in(Ff, DE.t)
  999. if F_stara.degree(DE.t) - F_stard.degree(DE.t) > 0:
  1000. QBC = Poly(Q, DE.t)*B**(1 + j)*C**(n + j)
  1001. H = QBC
  1002. H_list.append(H)
  1003. H = (QBC*F_stard).rem(F_stara)
  1004. alphas = real_roots(F_stara)
  1005. for alpha in list(alphas):
  1006. delta_a = delta_a*Poly((DE.t - alpha)**(n - j), DE.t) + Poly(H.eval(alpha), DE.t)
  1007. delta_d = delta_d*Poly((DE.t - alpha)**(n - j), DE.t)
  1008. return (delta_a, delta_d, H_list)
  1009. def recognize_derivative(a, d, DE, z=None):
  1010. """
  1011. Compute the squarefree factorization of the denominator of f
  1012. and for each Di the polynomial H in K[x] (see Theorem 2.7.1), using the
  1013. LaurentSeries algorithm. Write Di = GiEi where Gj = gcd(Hn, Di) and
  1014. gcd(Ei,Hn) = 1. Since the residues of f at the roots of Gj are all 0, and
  1015. the residue of f at a root alpha of Ei is Hi(a) != 0, f is the derivative of a
  1016. rational function if and only if Ei = 1 for each i, which is equivalent to
  1017. Di | H[-1] for each i.
  1018. """
  1019. flag =True
  1020. a, d = a.cancel(d, include=True)
  1021. _, r = a.div(d)
  1022. Np, Sp = splitfactor_sqf(d, DE, coefficientD=True, z=z)
  1023. j = 1
  1024. for s, _ in Sp:
  1025. delta_a, delta_d, H = laurent_series(r, d, s, j, DE)
  1026. g = gcd(d, H[-1]).as_poly()
  1027. if g is not d:
  1028. flag = False
  1029. break
  1030. j = j + 1
  1031. return flag
  1032. def recognize_log_derivative(a, d, DE, z=None):
  1033. """
  1034. There exists a v in K(x)* such that f = dv/v
  1035. where f a rational function if and only if f can be written as f = A/D
  1036. where D is squarefree,deg(A) < deg(D), gcd(A, D) = 1,
  1037. and all the roots of the Rothstein-Trager resultant are integers. In that case,
  1038. any of the Rothstein-Trager, Lazard-Rioboo-Trager or Czichowski algorithm
  1039. produces u in K(x) such that du/dx = uf.
  1040. """
  1041. z = z or Dummy('z')
  1042. a, d = a.cancel(d, include=True)
  1043. _, a = a.div(d)
  1044. pz = Poly(z, DE.t)
  1045. Dd = derivation(d, DE)
  1046. q = a - pz*Dd
  1047. r, _ = d.resultant(q, includePRS=True)
  1048. r = Poly(r, z)
  1049. Np, Sp = splitfactor_sqf(r, DE, coefficientD=True, z=z)
  1050. for s, _ in Sp:
  1051. # TODO also consider the complex roots
  1052. # incase we have complex roots it should turn the flag false
  1053. a = real_roots(s.as_poly(z))
  1054. if not all(j.is_Integer for j in a):
  1055. return False
  1056. return True
  1057. def residue_reduce(a, d, DE, z=None, invert=True):
  1058. """
  1059. Lazard-Rioboo-Rothstein-Trager resultant reduction.
  1060. Explanation
  1061. ===========
  1062. Given a derivation ``D`` on k(t) and f in k(t) simple, return g
  1063. elementary over k(t) and a Boolean b in {True, False} such that f -
  1064. Dg in k[t] if b == True or f + h and f + h - Dg do not have an
  1065. elementary integral over k(t) for any h in k<t> (reduced) if b ==
  1066. False.
  1067. Returns (G, b), where G is a tuple of tuples of the form (s_i, S_i),
  1068. such that g = Add(*[RootSum(s_i, lambda z: z*log(S_i(z, t))) for
  1069. S_i, s_i in G]). f - Dg is the remaining integral, which is elementary
  1070. only if b == True, and hence the integral of f is elementary only if
  1071. b == True.
  1072. f - Dg is not calculated in this function because that would require
  1073. explicitly calculating the RootSum. Use residue_reduce_derivation().
  1074. """
  1075. # TODO: Use log_to_atan() from rationaltools.py
  1076. # If r = residue_reduce(...), then the logarithmic part is given by:
  1077. # sum([RootSum(a[0].as_poly(z), lambda i: i*log(a[1].as_expr()).subs(z,
  1078. # i)).subs(t, log(x)) for a in r[0]])
  1079. z = z or Dummy('z')
  1080. a, d = a.cancel(d, include=True)
  1081. a, d = a.to_field().mul_ground(1/d.LC()), d.to_field().mul_ground(1/d.LC())
  1082. kkinv = [1/x for x in DE.T[:DE.level]] + DE.T[:DE.level]
  1083. if a.is_zero:
  1084. return ([], True)
  1085. _, a = a.div(d)
  1086. pz = Poly(z, DE.t)
  1087. Dd = derivation(d, DE)
  1088. q = a - pz*Dd
  1089. if Dd.degree(DE.t) <= d.degree(DE.t):
  1090. r, R = d.resultant(q, includePRS=True)
  1091. else:
  1092. r, R = q.resultant(d, includePRS=True)
  1093. R_map, H = {}, []
  1094. for i in R:
  1095. R_map[i.degree()] = i
  1096. r = Poly(r, z)
  1097. Np, Sp = splitfactor_sqf(r, DE, coefficientD=True, z=z)
  1098. for s, i in Sp:
  1099. if i == d.degree(DE.t):
  1100. s = Poly(s, z).monic()
  1101. H.append((s, d))
  1102. else:
  1103. h = R_map.get(i)
  1104. if h is None:
  1105. continue
  1106. h_lc = Poly(h.as_poly(DE.t).LC(), DE.t, field=True)
  1107. h_lc_sqf = h_lc.sqf_list_include(all=True)
  1108. for a, j in h_lc_sqf:
  1109. h = Poly(h, DE.t, field=True).exquo(Poly(gcd(a, s**j, *kkinv),
  1110. DE.t))
  1111. s = Poly(s, z).monic()
  1112. if invert:
  1113. h_lc = Poly(h.as_poly(DE.t).LC(), DE.t, field=True, expand=False)
  1114. inv, coeffs = h_lc.as_poly(z, field=True).invert(s), [S.One]
  1115. for coeff in h.coeffs()[1:]:
  1116. L = reduced(inv*coeff.as_poly(inv.gens), [s])[1]
  1117. coeffs.append(L.as_expr())
  1118. h = Poly(dict(list(zip(h.monoms(), coeffs))), DE.t)
  1119. H.append((s, h))
  1120. b = not any(cancel(i.as_expr()).has(DE.t, z) for i, _ in Np)
  1121. return (H, b)
  1122. def residue_reduce_to_basic(H, DE, z):
  1123. """
  1124. Converts the tuple returned by residue_reduce() into a Basic expression.
  1125. """
  1126. # TODO: check what Lambda does with RootOf
  1127. i = Dummy('i')
  1128. s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
  1129. return sum(RootSum(a[0].as_poly(z), Lambda(i, i*log(a[1].as_expr()).subs(
  1130. {z: i}).subs(s))) for a in H)
  1131. def residue_reduce_derivation(H, DE, z):
  1132. """
  1133. Computes the derivation of an expression returned by residue_reduce().
  1134. In general, this is a rational function in t, so this returns an
  1135. as_expr() result.
  1136. """
  1137. # TODO: verify that this is correct for multiple extensions
  1138. i = Dummy('i')
  1139. return S(sum(RootSum(a[0].as_poly(z), Lambda(i, i*derivation(a[1],
  1140. DE).as_expr().subs(z, i)/a[1].as_expr().subs(z, i))) for a in H))
  1141. def integrate_primitive_polynomial(p, DE):
  1142. """
  1143. Integration of primitive polynomials.
  1144. Explanation
  1145. ===========
  1146. Given a primitive monomial t over k, and ``p`` in k[t], return q in k[t],
  1147. r in k, and a bool b in {True, False} such that r = p - Dq is in k if b is
  1148. True, or r = p - Dq does not have an elementary integral over k(t) if b is
  1149. False.
  1150. """
  1151. Zero = Poly(0, DE.t)
  1152. q = Poly(0, DE.t)
  1153. if not p.expr.has(DE.t):
  1154. return (Zero, p, True)
  1155. from .prde import limited_integrate
  1156. while True:
  1157. if not p.expr.has(DE.t):
  1158. return (q, p, True)
  1159. Dta, Dtb = frac_in(DE.d, DE.T[DE.level - 1])
  1160. with DecrementLevel(DE): # We had better be integrating the lowest extension (x)
  1161. # with ratint().
  1162. a = p.LC()
  1163. aa, ad = frac_in(a, DE.t)
  1164. try:
  1165. rv = limited_integrate(aa, ad, [(Dta, Dtb)], DE)
  1166. if rv is None:
  1167. raise NonElementaryIntegralException
  1168. (ba, bd), c = rv
  1169. except NonElementaryIntegralException:
  1170. return (q, p, False)
  1171. m = p.degree(DE.t)
  1172. q0 = c[0].as_poly(DE.t)*Poly(DE.t**(m + 1)/(m + 1), DE.t) + \
  1173. (ba.as_expr()/bd.as_expr()).as_poly(DE.t)*Poly(DE.t**m, DE.t)
  1174. p = p - derivation(q0, DE)
  1175. q = q + q0
  1176. def integrate_primitive(a, d, DE, z=None):
  1177. """
  1178. Integration of primitive functions.
  1179. Explanation
  1180. ===========
  1181. Given a primitive monomial t over k and f in k(t), return g elementary over
  1182. k(t), i in k(t), and b in {True, False} such that i = f - Dg is in k if b
  1183. is True or i = f - Dg does not have an elementary integral over k(t) if b
  1184. is False.
  1185. This function returns a Basic expression for the first argument. If b is
  1186. True, the second argument is Basic expression in k to recursively integrate.
  1187. If b is False, the second argument is an unevaluated Integral, which has
  1188. been proven to be nonelementary.
  1189. """
  1190. # XXX: a and d must be canceled, or this might return incorrect results
  1191. z = z or Dummy("z")
  1192. s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
  1193. g1, h, r = hermite_reduce(a, d, DE)
  1194. g2, b = residue_reduce(h[0], h[1], DE, z=z)
  1195. if not b:
  1196. i = cancel(a.as_expr()/d.as_expr() - (g1[1]*derivation(g1[0], DE) -
  1197. g1[0]*derivation(g1[1], DE)).as_expr()/(g1[1]**2).as_expr() -
  1198. residue_reduce_derivation(g2, DE, z))
  1199. i = NonElementaryIntegral(cancel(i).subs(s), DE.x)
  1200. return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) +
  1201. residue_reduce_to_basic(g2, DE, z), i, b)
  1202. # h - Dg2 + r
  1203. p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2,
  1204. DE, z) + r[0].as_expr()/r[1].as_expr())
  1205. p = p.as_poly(DE.t)
  1206. q, i, b = integrate_primitive_polynomial(p, DE)
  1207. ret = ((g1[0].as_expr()/g1[1].as_expr() + q.as_expr()).subs(s) +
  1208. residue_reduce_to_basic(g2, DE, z))
  1209. if not b:
  1210. # TODO: This does not do the right thing when b is False
  1211. i = NonElementaryIntegral(cancel(i.as_expr()).subs(s), DE.x)
  1212. else:
  1213. i = cancel(i.as_expr())
  1214. return (ret, i, b)
  1215. def integrate_hyperexponential_polynomial(p, DE, z):
  1216. """
  1217. Integration of hyperexponential polynomials.
  1218. Explanation
  1219. ===========
  1220. Given a hyperexponential monomial t over k and ``p`` in k[t, 1/t], return q in
  1221. k[t, 1/t] and a bool b in {True, False} such that p - Dq in k if b is True,
  1222. or p - Dq does not have an elementary integral over k(t) if b is False.
  1223. """
  1224. t1 = DE.t
  1225. dtt = DE.d.exquo(Poly(DE.t, DE.t))
  1226. qa = Poly(0, DE.t)
  1227. qd = Poly(1, DE.t)
  1228. b = True
  1229. if p.is_zero:
  1230. return(qa, qd, b)
  1231. from sympy.integrals.rde import rischDE
  1232. with DecrementLevel(DE):
  1233. for i in range(-p.degree(z), p.degree(t1) + 1):
  1234. if not i:
  1235. continue
  1236. elif i < 0:
  1237. # If you get AttributeError: 'NoneType' object has no attribute 'nth'
  1238. # then this should really not have expand=False
  1239. # But it shouldn't happen because p is already a Poly in t and z
  1240. a = p.as_poly(z, expand=False).nth(-i)
  1241. else:
  1242. # If you get AttributeError: 'NoneType' object has no attribute 'nth'
  1243. # then this should really not have expand=False
  1244. a = p.as_poly(t1, expand=False).nth(i)
  1245. aa, ad = frac_in(a, DE.t, field=True)
  1246. aa, ad = aa.cancel(ad, include=True)
  1247. iDt = Poly(i, t1)*dtt
  1248. iDta, iDtd = frac_in(iDt, DE.t, field=True)
  1249. try:
  1250. va, vd = rischDE(iDta, iDtd, Poly(aa, DE.t), Poly(ad, DE.t), DE)
  1251. va, vd = frac_in((va, vd), t1, cancel=True)
  1252. except NonElementaryIntegralException:
  1253. b = False
  1254. else:
  1255. qa = qa*vd + va*Poly(t1**i)*qd
  1256. qd *= vd
  1257. return (qa, qd, b)
  1258. def integrate_hyperexponential(a, d, DE, z=None, conds='piecewise'):
  1259. """
  1260. Integration of hyperexponential functions.
  1261. Explanation
  1262. ===========
  1263. Given a hyperexponential monomial t over k and f in k(t), return g
  1264. elementary over k(t), i in k(t), and a bool b in {True, False} such that
  1265. i = f - Dg is in k if b is True or i = f - Dg does not have an elementary
  1266. integral over k(t) if b is False.
  1267. This function returns a Basic expression for the first argument. If b is
  1268. True, the second argument is Basic expression in k to recursively integrate.
  1269. If b is False, the second argument is an unevaluated Integral, which has
  1270. been proven to be nonelementary.
  1271. """
  1272. # XXX: a and d must be canceled, or this might return incorrect results
  1273. z = z or Dummy("z")
  1274. s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
  1275. g1, h, r = hermite_reduce(a, d, DE)
  1276. g2, b = residue_reduce(h[0], h[1], DE, z=z)
  1277. if not b:
  1278. i = cancel(a.as_expr()/d.as_expr() - (g1[1]*derivation(g1[0], DE) -
  1279. g1[0]*derivation(g1[1], DE)).as_expr()/(g1[1]**2).as_expr() -
  1280. residue_reduce_derivation(g2, DE, z))
  1281. i = NonElementaryIntegral(cancel(i.subs(s)), DE.x)
  1282. return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) +
  1283. residue_reduce_to_basic(g2, DE, z), i, b)
  1284. # p should be a polynomial in t and 1/t, because Sirr == k[t, 1/t]
  1285. # h - Dg2 + r
  1286. p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2,
  1287. DE, z) + r[0].as_expr()/r[1].as_expr())
  1288. pp = as_poly_1t(p, DE.t, z)
  1289. qa, qd, b = integrate_hyperexponential_polynomial(pp, DE, z)
  1290. i = pp.nth(0, 0)
  1291. ret = ((g1[0].as_expr()/g1[1].as_expr()).subs(s) \
  1292. + residue_reduce_to_basic(g2, DE, z))
  1293. qas = qa.as_expr().subs(s)
  1294. qds = qd.as_expr().subs(s)
  1295. if conds == 'piecewise' and DE.x not in qds.free_symbols:
  1296. # We have to be careful if the exponent is S.Zero!
  1297. # XXX: Does qd = 0 always necessarily correspond to the exponential
  1298. # equaling 1?
  1299. ret += Piecewise(
  1300. (qas/qds, Ne(qds, 0)),
  1301. (integrate((p - i).subs(DE.t, 1).subs(s), DE.x), True)
  1302. )
  1303. else:
  1304. ret += qas/qds
  1305. if not b:
  1306. i = p - (qd*derivation(qa, DE) - qa*derivation(qd, DE)).as_expr()/\
  1307. (qd**2).as_expr()
  1308. i = NonElementaryIntegral(cancel(i).subs(s), DE.x)
  1309. return (ret, i, b)
  1310. def integrate_hypertangent_polynomial(p, DE):
  1311. """
  1312. Integration of hypertangent polynomials.
  1313. Explanation
  1314. ===========
  1315. Given a differential field k such that sqrt(-1) is not in k, a
  1316. hypertangent monomial t over k, and p in k[t], return q in k[t] and
  1317. c in k such that p - Dq - c*D(t**2 + 1)/(t**1 + 1) is in k and p -
  1318. Dq does not have an elementary integral over k(t) if Dc != 0.
  1319. """
  1320. # XXX: Make sure that sqrt(-1) is not in k.
  1321. q, r = polynomial_reduce(p, DE)
  1322. a = DE.d.exquo(Poly(DE.t**2 + 1, DE.t))
  1323. c = Poly(r.nth(1)/(2*a.as_expr()), DE.t)
  1324. return (q, c)
  1325. def integrate_nonlinear_no_specials(a, d, DE, z=None):
  1326. """
  1327. Integration of nonlinear monomials with no specials.
  1328. Explanation
  1329. ===========
  1330. Given a nonlinear monomial t over k such that Sirr ({p in k[t] | p is
  1331. special, monic, and irreducible}) is empty, and f in k(t), returns g
  1332. elementary over k(t) and a Boolean b in {True, False} such that f - Dg is
  1333. in k if b == True, or f - Dg does not have an elementary integral over k(t)
  1334. if b == False.
  1335. This function is applicable to all nonlinear extensions, but in the case
  1336. where it returns b == False, it will only have proven that the integral of
  1337. f - Dg is nonelementary if Sirr is empty.
  1338. This function returns a Basic expression.
  1339. """
  1340. # TODO: Integral from k?
  1341. # TODO: split out nonelementary integral
  1342. # XXX: a and d must be canceled, or this might not return correct results
  1343. z = z or Dummy("z")
  1344. s = list(zip(reversed(DE.T), reversed([f(DE.x) for f in DE.Tfuncs])))
  1345. g1, h, r = hermite_reduce(a, d, DE)
  1346. g2, b = residue_reduce(h[0], h[1], DE, z=z)
  1347. if not b:
  1348. return ((g1[0].as_expr()/g1[1].as_expr()).subs(s) +
  1349. residue_reduce_to_basic(g2, DE, z), b)
  1350. # Because f has no specials, this should be a polynomial in t, or else
  1351. # there is a bug.
  1352. p = cancel(h[0].as_expr()/h[1].as_expr() - residue_reduce_derivation(g2,
  1353. DE, z).as_expr() + r[0].as_expr()/r[1].as_expr()).as_poly(DE.t)
  1354. q1, q2 = polynomial_reduce(p, DE)
  1355. if q2.expr.has(DE.t):
  1356. b = False
  1357. else:
  1358. b = True
  1359. ret = (cancel(g1[0].as_expr()/g1[1].as_expr() + q1.as_expr()).subs(s) +
  1360. residue_reduce_to_basic(g2, DE, z))
  1361. return (ret, b)
  1362. class NonElementaryIntegral(Integral):
  1363. """
  1364. Represents a nonelementary Integral.
  1365. Explanation
  1366. ===========
  1367. If the result of integrate() is an instance of this class, it is
  1368. guaranteed to be nonelementary. Note that integrate() by default will try
  1369. to find any closed-form solution, even in terms of special functions which
  1370. may themselves not be elementary. To make integrate() only give
  1371. elementary solutions, or, in the cases where it can prove the integral to
  1372. be nonelementary, instances of this class, use integrate(risch=True).
  1373. In this case, integrate() may raise NotImplementedError if it cannot make
  1374. such a determination.
  1375. integrate() uses the deterministic Risch algorithm to integrate elementary
  1376. functions or prove that they have no elementary integral. In some cases,
  1377. this algorithm can split an integral into an elementary and nonelementary
  1378. part, so that the result of integrate will be the sum of an elementary
  1379. expression and a NonElementaryIntegral.
  1380. Examples
  1381. ========
  1382. >>> from sympy import integrate, exp, log, Integral
  1383. >>> from sympy.abc import x
  1384. >>> a = integrate(exp(-x**2), x, risch=True)
  1385. >>> print(a)
  1386. Integral(exp(-x**2), x)
  1387. >>> type(a)
  1388. <class 'sympy.integrals.risch.NonElementaryIntegral'>
  1389. >>> expr = (2*log(x)**2 - log(x) - x**2)/(log(x)**3 - x**2*log(x))
  1390. >>> b = integrate(expr, x, risch=True)
  1391. >>> print(b)
  1392. -log(-x + log(x))/2 + log(x + log(x))/2 + Integral(1/log(x), x)
  1393. >>> type(b.atoms(Integral).pop())
  1394. <class 'sympy.integrals.risch.NonElementaryIntegral'>
  1395. """
  1396. # TODO: This is useful in and of itself, because isinstance(result,
  1397. # NonElementaryIntegral) will tell if the integral has been proven to be
  1398. # elementary. But should we do more? Perhaps a no-op .doit() if
  1399. # elementary=True? Or maybe some information on why the integral is
  1400. # nonelementary.
  1401. pass
  1402. def risch_integrate(f, x, extension=None, handle_first='log',
  1403. separate_integral=False, rewrite_complex=None,
  1404. conds='piecewise'):
  1405. r"""
  1406. The Risch Integration Algorithm.
  1407. Explanation
  1408. ===========
  1409. Only transcendental functions are supported. Currently, only exponentials
  1410. and logarithms are supported, but support for trigonometric functions is
  1411. forthcoming.
  1412. If this function returns an unevaluated Integral in the result, it means
  1413. that it has proven that integral to be nonelementary. Any errors will
  1414. result in raising NotImplementedError. The unevaluated Integral will be
  1415. an instance of NonElementaryIntegral, a subclass of Integral.
  1416. handle_first may be either 'exp' or 'log'. This changes the order in
  1417. which the extension is built, and may result in a different (but
  1418. equivalent) solution (for an example of this, see issue 5109). It is also
  1419. possible that the integral may be computed with one but not the other,
  1420. because not all cases have been implemented yet. It defaults to 'log' so
  1421. that the outer extension is exponential when possible, because more of the
  1422. exponential case has been implemented.
  1423. If ``separate_integral`` is ``True``, the result is returned as a tuple (ans, i),
  1424. where the integral is ans + i, ans is elementary, and i is either a
  1425. NonElementaryIntegral or 0. This useful if you want to try further
  1426. integrating the NonElementaryIntegral part using other algorithms to
  1427. possibly get a solution in terms of special functions. It is False by
  1428. default.
  1429. Examples
  1430. ========
  1431. >>> from sympy.integrals.risch import risch_integrate
  1432. >>> from sympy import exp, log, pprint
  1433. >>> from sympy.abc import x
  1434. First, we try integrating exp(-x**2). Except for a constant factor of
  1435. 2/sqrt(pi), this is the famous error function.
  1436. >>> pprint(risch_integrate(exp(-x**2), x))
  1437. /
  1438. |
  1439. | 2
  1440. | -x
  1441. | e dx
  1442. |
  1443. /
  1444. The unevaluated Integral in the result means that risch_integrate() has
  1445. proven that exp(-x**2) does not have an elementary anti-derivative.
  1446. In many cases, risch_integrate() can split out the elementary
  1447. anti-derivative part from the nonelementary anti-derivative part.
  1448. For example,
  1449. >>> pprint(risch_integrate((2*log(x)**2 - log(x) - x**2)/(log(x)**3 -
  1450. ... x**2*log(x)), x))
  1451. /
  1452. |
  1453. log(-x + log(x)) log(x + log(x)) | 1
  1454. - ---------------- + --------------- + | ------ dx
  1455. 2 2 | log(x)
  1456. |
  1457. /
  1458. This means that it has proven that the integral of 1/log(x) is
  1459. nonelementary. This function is also known as the logarithmic integral,
  1460. and is often denoted as Li(x).
  1461. risch_integrate() currently only accepts purely transcendental functions
  1462. with exponentials and logarithms, though note that this can include
  1463. nested exponentials and logarithms, as well as exponentials with bases
  1464. other than E.
  1465. >>> pprint(risch_integrate(exp(x)*exp(exp(x)), x))
  1466. / x\
  1467. \e /
  1468. e
  1469. >>> pprint(risch_integrate(exp(exp(x)), x))
  1470. /
  1471. |
  1472. | / x\
  1473. | \e /
  1474. | e dx
  1475. |
  1476. /
  1477. >>> pprint(risch_integrate(x*x**x*log(x) + x**x + x*x**x, x))
  1478. x
  1479. x*x
  1480. >>> pprint(risch_integrate(x**x, x))
  1481. /
  1482. |
  1483. | x
  1484. | x dx
  1485. |
  1486. /
  1487. >>> pprint(risch_integrate(-1/(x*log(x)*log(log(x))**2), x))
  1488. 1
  1489. -----------
  1490. log(log(x))
  1491. """
  1492. f = S(f)
  1493. DE = extension or DifferentialExtension(f, x, handle_first=handle_first,
  1494. dummy=True, rewrite_complex=rewrite_complex)
  1495. fa, fd = DE.fa, DE.fd
  1496. result = S.Zero
  1497. for case in reversed(DE.cases):
  1498. if not fa.expr.has(DE.t) and not fd.expr.has(DE.t) and not case == 'base':
  1499. DE.decrement_level()
  1500. fa, fd = frac_in((fa, fd), DE.t)
  1501. continue
  1502. fa, fd = fa.cancel(fd, include=True)
  1503. if case == 'exp':
  1504. ans, i, b = integrate_hyperexponential(fa, fd, DE, conds=conds)
  1505. elif case == 'primitive':
  1506. ans, i, b = integrate_primitive(fa, fd, DE)
  1507. elif case == 'base':
  1508. # XXX: We can't call ratint() directly here because it doesn't
  1509. # handle polynomials correctly.
  1510. ans = integrate(fa.as_expr()/fd.as_expr(), DE.x, risch=False)
  1511. b = False
  1512. i = S.Zero
  1513. else:
  1514. raise NotImplementedError("Only exponential and logarithmic "
  1515. "extensions are currently supported.")
  1516. result += ans
  1517. if b:
  1518. DE.decrement_level()
  1519. fa, fd = frac_in(i, DE.t)
  1520. else:
  1521. result = result.subs(DE.backsubs)
  1522. if not i.is_zero:
  1523. i = NonElementaryIntegral(i.function.subs(DE.backsubs),i.limits)
  1524. if not separate_integral:
  1525. result += i
  1526. return result
  1527. else:
  1528. if isinstance(i, NonElementaryIntegral):
  1529. return (result, i)
  1530. else:
  1531. return (result, 0)