risch.py 66 KB

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