gruntz.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. """
  2. Limits
  3. ======
  4. Implemented according to the PhD thesis
  5. https://www.cybertester.com/data/gruntz.pdf, which contains very thorough
  6. descriptions of the algorithm including many examples. We summarize here
  7. the gist of it.
  8. All functions are sorted according to how rapidly varying they are at
  9. infinity using the following rules. Any two functions f and g can be
  10. compared using the properties of L:
  11. L=lim log|f(x)| / log|g(x)| (for x -> oo)
  12. We define >, < ~ according to::
  13. 1. f > g .... L=+-oo
  14. we say that:
  15. - f is greater than any power of g
  16. - f is more rapidly varying than g
  17. - f goes to infinity/zero faster than g
  18. 2. f < g .... L=0
  19. we say that:
  20. - f is lower than any power of g
  21. 3. f ~ g .... L!=0, +-oo
  22. we say that:
  23. - both f and g are bounded from above and below by suitable integral
  24. powers of the other
  25. Examples
  26. ========
  27. ::
  28. 2 < x < exp(x) < exp(x**2) < exp(exp(x))
  29. 2 ~ 3 ~ -5
  30. x ~ x**2 ~ x**3 ~ 1/x ~ x**m ~ -x
  31. exp(x) ~ exp(-x) ~ exp(2x) ~ exp(x)**2 ~ exp(x+exp(-x))
  32. f ~ 1/f
  33. So we can divide all the functions into comparability classes (x and x^2
  34. belong to one class, exp(x) and exp(-x) belong to some other class). In
  35. principle, we could compare any two functions, but in our algorithm, we
  36. do not compare anything below the class 2~3~-5 (for example log(x) is
  37. below this), so we set 2~3~-5 as the lowest comparability class.
  38. Given the function f, we find the list of most rapidly varying (mrv set)
  39. subexpressions of it. This list belongs to the same comparability class.
  40. Let's say it is {exp(x), exp(2x)}. Using the rule f ~ 1/f we find an
  41. element "w" (either from the list or a new one) from the same
  42. comparability class which goes to zero at infinity. In our example we
  43. set w=exp(-x) (but we could also set w=exp(-2x) or w=exp(-3x) ...). We
  44. rewrite the mrv set using w, in our case {1/w, 1/w^2}, and substitute it
  45. into f. Then we expand f into a series in w::
  46. f = c0*w^e0 + c1*w^e1 + ... + O(w^en), where e0<e1<...<en, c0!=0
  47. but for x->oo, lim f = lim c0*w^e0, because all the other terms go to zero,
  48. because w goes to zero faster than the ci and ei. So::
  49. for e0>0, lim f = 0
  50. for e0<0, lim f = +-oo (the sign depends on the sign of c0)
  51. for e0=0, lim f = lim c0
  52. We need to recursively compute limits at several places of the algorithm, but
  53. as is shown in the PhD thesis, it always finishes.
  54. Important functions from the implementation:
  55. compare(a, b, x) compares "a" and "b" by computing the limit L.
  56. mrv(e, x) returns list of most rapidly varying (mrv) subexpressions of "e"
  57. rewrite(e, Omega, x, wsym) rewrites "e" in terms of w
  58. leadterm(f, x) returns the lowest power term in the series of f
  59. mrv_leadterm(e, x) returns the lead term (c0, e0) for e
  60. limitinf(e, x) computes lim e (for x->oo)
  61. limit(e, z, z0) computes any limit by converting it to the case x->oo
  62. All the functions are really simple and straightforward except
  63. rewrite(), which is the most difficult/complex part of the algorithm.
  64. When the algorithm fails, the bugs are usually in the series expansion
  65. (i.e. in SymPy) or in rewrite.
  66. This code is almost exact rewrite of the Maple code inside the Gruntz
  67. thesis.
  68. Debugging
  69. ---------
  70. Because the gruntz algorithm is highly recursive, it's difficult to
  71. figure out what went wrong inside a debugger. Instead, turn on nice
  72. debug prints by defining the environment variable SYMPY_DEBUG. For
  73. example:
  74. [user@localhost]: SYMPY_DEBUG=True ./bin/isympy
  75. In [1]: limit(sin(x)/x, x, 0)
  76. limitinf(_x*sin(1/_x), _x) = 1
  77. +-mrv_leadterm(_x*sin(1/_x), _x) = (1, 0)
  78. | +-mrv(_x*sin(1/_x), _x) = set([_x])
  79. | | +-mrv(_x, _x) = set([_x])
  80. | | +-mrv(sin(1/_x), _x) = set([_x])
  81. | | +-mrv(1/_x, _x) = set([_x])
  82. | | +-mrv(_x, _x) = set([_x])
  83. | +-mrv_leadterm(exp(_x)*sin(exp(-_x)), _x, set([exp(_x)])) = (1, 0)
  84. | +-rewrite(exp(_x)*sin(exp(-_x)), set([exp(_x)]), _x, _w) = (1/_w*sin(_w), -_x)
  85. | +-sign(_x, _x) = 1
  86. | +-mrv_leadterm(1, _x) = (1, 0)
  87. +-sign(0, _x) = 0
  88. +-limitinf(1, _x) = 1
  89. And check manually which line is wrong. Then go to the source code and
  90. debug this function to figure out the exact problem.
  91. """
  92. from functools import reduce
  93. from sympy.core import Basic, S, Mul, PoleError
  94. from sympy.core.cache import cacheit
  95. from sympy.core.function import AppliedUndef
  96. from sympy.core.intfunc import ilcm
  97. from sympy.core.numbers import I, oo
  98. from sympy.core.symbol import Dummy, Wild
  99. from sympy.core.traversal import bottom_up
  100. from sympy.functions import log, exp, sign as _sign
  101. from sympy.series.order import Order
  102. from sympy.utilities.misc import debug_decorator as debug
  103. from sympy.utilities.timeutils import timethis
  104. timeit = timethis('gruntz')
  105. def compare(a, b, x):
  106. """Returns "<" if a<b, "=" for a == b, ">" for a>b"""
  107. # log(exp(...)) must always be simplified here for termination
  108. la, lb = log(a), log(b)
  109. if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
  110. la = a.exp
  111. if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
  112. lb = b.exp
  113. c = limitinf(la/lb, x)
  114. if c == 0:
  115. return "<"
  116. elif c.is_infinite:
  117. return ">"
  118. else:
  119. return "="
  120. class SubsSet(dict):
  121. """
  122. Stores (expr, dummy) pairs, and how to rewrite expr-s.
  123. Explanation
  124. ===========
  125. The gruntz algorithm needs to rewrite certain expressions in term of a new
  126. variable w. We cannot use subs, because it is just too smart for us. For
  127. example::
  128. > Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
  129. > O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
  130. > e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
  131. > e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
  132. -1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
  133. is really not what we want!
  134. So we do it the hard way and keep track of all the things we potentially
  135. want to substitute by dummy variables. Consider the expression::
  136. exp(x - exp(-x)) + exp(x) + x.
  137. The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
  138. We introduce corresponding dummy variables d1, d2, d3 and rewrite::
  139. d3 + d1 + x.
  140. This class first of all keeps track of the mapping expr->variable, i.e.
  141. will at this stage be a dictionary::
  142. {exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
  143. [It turns out to be more convenient this way round.]
  144. But sometimes expressions in the mrv set have other expressions from the
  145. mrv set as subexpressions, and we need to keep track of that as well. In
  146. this case, d3 is really exp(x - d2), so rewrites at this stage is::
  147. {d3: exp(x-d2)}.
  148. The function rewrite uses all this information to correctly rewrite our
  149. expression in terms of w. In this case w can be chosen to be exp(-x),
  150. i.e. d2. The correct rewriting then is::
  151. exp(-w)/w + 1/w + x.
  152. """
  153. def __init__(self):
  154. self.rewrites = {}
  155. def __repr__(self):
  156. return super().__repr__() + ', ' + self.rewrites.__repr__()
  157. def __getitem__(self, key):
  158. if key not in self:
  159. self[key] = Dummy()
  160. return dict.__getitem__(self, key)
  161. def do_subs(self, e):
  162. """Substitute the variables with expressions"""
  163. for expr, var in self.items():
  164. e = e.xreplace({var: expr})
  165. return e
  166. def meets(self, s2):
  167. """Tell whether or not self and s2 have non-empty intersection"""
  168. return set(self.keys()).intersection(list(s2.keys())) != set()
  169. def union(self, s2, exps=None):
  170. """Compute the union of self and s2, adjusting exps"""
  171. res = self.copy()
  172. tr = {}
  173. for expr, var in s2.items():
  174. if expr in self:
  175. if exps:
  176. exps = exps.xreplace({var: res[expr]})
  177. tr[var] = res[expr]
  178. else:
  179. res[expr] = var
  180. for var, rewr in s2.rewrites.items():
  181. res.rewrites[var] = rewr.xreplace(tr)
  182. return res, exps
  183. def copy(self):
  184. """Create a shallow copy of SubsSet"""
  185. r = SubsSet()
  186. r.rewrites = self.rewrites.copy()
  187. for expr, var in self.items():
  188. r[expr] = var
  189. return r
  190. @debug
  191. def mrv(e, x):
  192. """Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
  193. and e rewritten in terms of these"""
  194. from sympy.simplify.powsimp import powsimp
  195. e = powsimp(e, deep=True, combine='exp')
  196. if not isinstance(e, Basic):
  197. raise TypeError("e should be an instance of Basic")
  198. if not e.has(x):
  199. return SubsSet(), e
  200. elif e == x:
  201. s = SubsSet()
  202. return s, s[x]
  203. elif e.is_Mul or e.is_Add:
  204. i, d = e.as_independent(x) # throw away x-independent terms
  205. if d.func != e.func:
  206. s, expr = mrv(d, x)
  207. return s, e.func(i, expr)
  208. a, b = d.as_two_terms()
  209. s1, e1 = mrv(a, x)
  210. s2, e2 = mrv(b, x)
  211. return mrv_max1(s1, s2, e.func(i, e1, e2), x)
  212. elif e.is_Pow and e.base != S.Exp1:
  213. e1 = S.One
  214. while e.is_Pow:
  215. b1 = e.base
  216. e1 *= e.exp
  217. e = b1
  218. if b1 == 1:
  219. return SubsSet(), b1
  220. if e1.has(x):
  221. return mrv(exp(e1*log(b1)), x)
  222. else:
  223. s, expr = mrv(b1, x)
  224. return s, expr**e1
  225. elif isinstance(e, log):
  226. s, expr = mrv(e.args[0], x)
  227. return s, log(expr)
  228. elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
  229. # We know from the theory of this algorithm that exp(log(...)) may always
  230. # be simplified here, and doing so is vital for termination.
  231. if isinstance(e.exp, log):
  232. return mrv(e.exp.args[0], x)
  233. # if a product has an infinite factor the result will be
  234. # infinite if there is no zero, otherwise NaN; here, we
  235. # consider the result infinite if any factor is infinite
  236. li = limitinf(e.exp, x)
  237. if any(_.is_infinite for _ in Mul.make_args(li)):
  238. s1 = SubsSet()
  239. e1 = s1[e]
  240. s2, e2 = mrv(e.exp, x)
  241. su = s1.union(s2)[0]
  242. su.rewrites[e1] = exp(e2)
  243. return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
  244. else:
  245. s, expr = mrv(e.exp, x)
  246. return s, exp(expr)
  247. elif isinstance(e, AppliedUndef):
  248. raise ValueError("MRV set computation for UndefinedFunction is not allowed")
  249. elif e.is_Function:
  250. l = [mrv(a, x) for a in e.args]
  251. l2 = [s for (s, _) in l if s != SubsSet()]
  252. if len(l2) != 1:
  253. # e.g. something like BesselJ(x, x)
  254. raise NotImplementedError("MRV set computation for functions in"
  255. " several variables not implemented.")
  256. s, ss = l2[0], SubsSet()
  257. args = [ss.do_subs(x[1]) for x in l]
  258. return s, e.func(*args)
  259. elif e.is_Derivative:
  260. raise NotImplementedError("MRV set computation for derivatives"
  261. " not implemented yet.")
  262. raise NotImplementedError(
  263. "Don't know how to calculate the mrv of '%s'" % e)
  264. def mrv_max3(f, expsf, g, expsg, union, expsboth, x):
  265. """
  266. Computes the maximum of two sets of expressions f and g, which
  267. are in the same comparability class, i.e. max() compares (two elements of)
  268. f and g and returns either (f, expsf) [if f is larger], (g, expsg)
  269. [if g is larger] or (union, expsboth) [if f, g are of the same class].
  270. """
  271. if not isinstance(f, SubsSet):
  272. raise TypeError("f should be an instance of SubsSet")
  273. if not isinstance(g, SubsSet):
  274. raise TypeError("g should be an instance of SubsSet")
  275. if f == SubsSet():
  276. return g, expsg
  277. elif g == SubsSet():
  278. return f, expsf
  279. elif f.meets(g):
  280. return union, expsboth
  281. c = compare(list(f.keys())[0], list(g.keys())[0], x)
  282. if c == ">":
  283. return f, expsf
  284. elif c == "<":
  285. return g, expsg
  286. else:
  287. if c != "=":
  288. raise ValueError("c should be =")
  289. return union, expsboth
  290. def mrv_max1(f, g, exps, x):
  291. """Computes the maximum of two sets of expressions f and g, which
  292. are in the same comparability class, i.e. mrv_max1() compares (two elements of)
  293. f and g and returns the set, which is in the higher comparability class
  294. of the union of both, if they have the same order of variation.
  295. Also returns exps, with the appropriate substitutions made.
  296. """
  297. u, b = f.union(g, exps)
  298. return mrv_max3(f, g.do_subs(exps), g, f.do_subs(exps),
  299. u, b, x)
  300. @debug
  301. @cacheit
  302. @timeit
  303. def sign(e, x):
  304. """
  305. Returns a sign of an expression e(x) for x->oo.
  306. ::
  307. e > 0 for x sufficiently large ... 1
  308. e == 0 for x sufficiently large ... 0
  309. e < 0 for x sufficiently large ... -1
  310. The result of this function is currently undefined if e changes sign
  311. arbitrarily often for arbitrarily large x (e.g. sin(x)).
  312. Note that this returns zero only if e is *constantly* zero
  313. for x sufficiently large. [If e is constant, of course, this is just
  314. the same thing as the sign of e.]
  315. """
  316. if not isinstance(e, Basic):
  317. raise TypeError("e should be an instance of Basic")
  318. if e.is_positive:
  319. return 1
  320. elif e.is_negative:
  321. return -1
  322. elif e.is_zero:
  323. return 0
  324. elif not e.has(x):
  325. from sympy.simplify import logcombine
  326. e = logcombine(e)
  327. return _sign(e)
  328. elif e == x:
  329. return 1
  330. elif e.is_Mul:
  331. a, b = e.as_two_terms()
  332. sa = sign(a, x)
  333. if not sa:
  334. return 0
  335. return sa * sign(b, x)
  336. elif isinstance(e, exp):
  337. return 1
  338. elif e.is_Pow:
  339. if e.base == S.Exp1:
  340. return 1
  341. s = sign(e.base, x)
  342. if s == 1:
  343. return 1
  344. if e.exp.is_Integer:
  345. return s**e.exp
  346. elif isinstance(e, log) and e.args[0].is_positive:
  347. return sign(e.args[0] - 1, x)
  348. # if all else fails, do it the hard way
  349. c0, e0 = mrv_leadterm(e, x)
  350. return sign(c0, x)
  351. @debug
  352. @timeit
  353. @cacheit
  354. def limitinf(e, x):
  355. """Limit e(x) for x-> oo."""
  356. # rewrite e in terms of tractable functions only
  357. old = e
  358. if not e.has(x):
  359. return e # e is a constant
  360. from sympy.simplify.powsimp import powdenest
  361. from sympy.calculus.util import AccumBounds
  362. if e.has(Order):
  363. e = e.expand().removeO()
  364. if not x.is_positive or x.is_integer:
  365. # We make sure that x.is_positive is True and x.is_integer is None
  366. # so we get all the correct mathematical behavior from the expression.
  367. # We need a fresh variable.
  368. p = Dummy('p', positive=True)
  369. e = e.subs(x, p)
  370. x = p
  371. e = e.rewrite('tractable', deep=True, limitvar=x)
  372. e = powdenest(e)
  373. if isinstance(e, AccumBounds):
  374. if mrv_leadterm(e.min, x) != mrv_leadterm(e.max, x):
  375. raise NotImplementedError
  376. c0, e0 = mrv_leadterm(e.min, x)
  377. else:
  378. c0, e0 = mrv_leadterm(e, x)
  379. sig = sign(e0, x)
  380. if sig == 1:
  381. return S.Zero # e0>0: lim f = 0
  382. elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0)
  383. if c0.match(I*Wild("a", exclude=[I])):
  384. return c0*oo
  385. s = sign(c0, x)
  386. # the leading term shouldn't be 0:
  387. if s == 0:
  388. raise ValueError("Leading term should not be 0")
  389. return s*oo
  390. elif sig == 0:
  391. if c0 == old:
  392. c0 = c0.cancel()
  393. return limitinf(c0, x) # e0=0: lim f = lim c0
  394. else:
  395. raise ValueError("{} could not be evaluated".format(sig))
  396. def moveup2(s, x):
  397. r = SubsSet()
  398. for expr, var in s.items():
  399. r[expr.xreplace({x: exp(x)})] = var
  400. for var, expr in s.rewrites.items():
  401. r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
  402. return r
  403. def moveup(l, x):
  404. return [e.xreplace({x: exp(x)}) for e in l]
  405. @debug
  406. @timeit
  407. @cacheit
  408. def mrv_leadterm(e, x):
  409. """Returns (c0, e0) for e."""
  410. Omega = SubsSet()
  411. if not e.has(x):
  412. return (e, S.Zero)
  413. if Omega == SubsSet():
  414. Omega, exps = mrv(e, x)
  415. if not Omega:
  416. # e really does not depend on x after simplification
  417. return exps, S.Zero
  418. if x in Omega:
  419. # move the whole omega up (exponentiate each term):
  420. Omega_up = moveup2(Omega, x)
  421. exps_up = moveup([exps], x)[0]
  422. # NOTE: there is no need to move this down!
  423. Omega = Omega_up
  424. exps = exps_up
  425. #
  426. # The positive dummy, w, is used here so log(w*2) etc. will expand;
  427. # a unique dummy is needed in this algorithm
  428. #
  429. # For limits of complex functions, the algorithm would have to be
  430. # improved, or just find limits of Re and Im components separately.
  431. #
  432. w = Dummy("w", positive=True)
  433. f, logw = rewrite(exps, Omega, x, w)
  434. # Ensure expressions of the form exp(log(...)) don't get simplified automatically in the previous steps.
  435. # see: https://github.com/sympy/sympy/issues/15323#issuecomment-478639399
  436. f = f.replace(lambda f: f.is_Pow and f.has(x), lambda f: exp(log(f.base)*f.exp))
  437. try:
  438. lt = f.leadterm(w, logx=logw)
  439. except (NotImplementedError, PoleError, ValueError):
  440. n0 = 1
  441. _series = Order(1)
  442. incr = S.One
  443. while _series.is_Order:
  444. _series = f._eval_nseries(w, n=n0+incr, logx=logw)
  445. incr *= 2
  446. series = _series.expand().removeO()
  447. try:
  448. lt = series.leadterm(w, logx=logw)
  449. except (NotImplementedError, PoleError, ValueError):
  450. lt = f.as_coeff_exponent(w)
  451. if lt[0].has(w):
  452. base = f.as_base_exp()[0].as_coeff_exponent(w)
  453. ex = f.as_base_exp()[1]
  454. lt = (base[0]**ex, base[1]*ex)
  455. return (lt[0].subs(log(w), logw), lt[1])
  456. def build_expression_tree(Omega, rewrites):
  457. r""" Helper function for rewrite.
  458. We need to sort Omega (mrv set) so that we replace an expression before
  459. we replace any expression in terms of which it has to be rewritten::
  460. e1 ---> e2 ---> e3
  461. \
  462. -> e4
  463. Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
  464. To do this we assemble the nodes into a tree, and sort them by height.
  465. This function builds the tree, rewrites then sorts the nodes.
  466. """
  467. class Node:
  468. def __init__(self):
  469. self.before = []
  470. self.expr = None
  471. self.var = None
  472. def ht(self):
  473. return reduce(lambda x, y: x + y,
  474. [x.ht() for x in self.before], 1)
  475. nodes = {}
  476. for expr, v in Omega:
  477. n = Node()
  478. n.var = v
  479. n.expr = expr
  480. nodes[v] = n
  481. for _, v in Omega:
  482. if v in rewrites:
  483. n = nodes[v]
  484. r = rewrites[v]
  485. for _, v2 in Omega:
  486. if r.has(v2):
  487. n.before.append(nodes[v2])
  488. return nodes
  489. @debug
  490. @timeit
  491. def rewrite(e, Omega, x, wsym):
  492. """e(x) ... the function
  493. Omega ... the mrv set
  494. wsym ... the symbol which is going to be used for w
  495. Returns the rewritten e in terms of w and log(w). See test_rewrite1()
  496. for examples and correct results.
  497. """
  498. from sympy import AccumBounds
  499. if not isinstance(Omega, SubsSet):
  500. raise TypeError("Omega should be an instance of SubsSet")
  501. if len(Omega) == 0:
  502. raise ValueError("Length cannot be 0")
  503. # all items in Omega must be exponentials
  504. for t in Omega.keys():
  505. if not isinstance(t, exp):
  506. raise ValueError("Value should be exp")
  507. rewrites = Omega.rewrites
  508. Omega = list(Omega.items())
  509. nodes = build_expression_tree(Omega, rewrites)
  510. Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
  511. # make sure we know the sign of each exp() term; after the loop,
  512. # g is going to be the "w" - the simplest one in the mrv set
  513. for g, _ in Omega:
  514. sig = sign(g.exp, x)
  515. if sig != 1 and sig != -1 and not sig.has(AccumBounds):
  516. raise NotImplementedError('Result depends on the sign of %s' % sig)
  517. if sig == 1:
  518. wsym = 1/wsym # if g goes to oo, substitute 1/w
  519. # O2 is a list, which results by rewriting each item in Omega using "w"
  520. O2 = []
  521. denominators = []
  522. for f, var in Omega:
  523. c = limitinf(f.exp/g.exp, x)
  524. if c.is_Rational:
  525. denominators.append(c.q)
  526. arg = f.exp
  527. if var in rewrites:
  528. if not isinstance(rewrites[var], exp):
  529. raise ValueError("Value should be exp")
  530. arg = rewrites[var].args[0]
  531. O2.append((var, exp((arg - c*g.exp))*wsym**c))
  532. # Remember that Omega contains subexpressions of "e". So now we find
  533. # them in "e" and substitute them for our rewriting, stored in O2
  534. # the following powsimp is necessary to automatically combine exponentials,
  535. # so that the .xreplace() below succeeds:
  536. # TODO this should not be necessary
  537. from sympy.simplify.powsimp import powsimp
  538. f = powsimp(e, deep=True, combine='exp')
  539. for a, b in O2:
  540. f = f.xreplace({a: b})
  541. for _, var in Omega:
  542. assert not f.has(var)
  543. # finally compute the logarithm of w (logw).
  544. logw = g.exp
  545. if sig == 1:
  546. logw = -logw # log(w)->log(1/w)=-log(w)
  547. # Some parts of SymPy have difficulty computing series expansions with
  548. # non-integral exponents. The following heuristic improves the situation:
  549. exponent = reduce(ilcm, denominators, 1)
  550. f = f.subs({wsym: wsym**exponent})
  551. logw /= exponent
  552. # bottom_up function is required for a specific case - when f is
  553. # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p). No current simplification
  554. # methods reduce this to 0 while not expanding polynomials.
  555. f = bottom_up(f, lambda w: getattr(w, 'normal', lambda: w)())
  556. return f, logw
  557. def gruntz(e, z, z0, dir="+"):
  558. """
  559. Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
  560. Explanation
  561. ===========
  562. ``z0`` can be any expression, including oo and -oo.
  563. For ``dir="+"`` (default) it calculates the limit from the right
  564. (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
  565. (oo or -oo), the dir argument does not matter.
  566. This algorithm is fully described in the module docstring in the gruntz.py
  567. file. It relies heavily on the series expansion. Most frequently, gruntz()
  568. is only used if the faster limit() function (which uses heuristics) fails.
  569. """
  570. if not z.is_symbol:
  571. raise NotImplementedError("Second argument must be a Symbol")
  572. # convert all limits to the limit z->oo; sign of z is handled in limitinf
  573. r = None
  574. if z0 in (oo, I*oo):
  575. e0 = e
  576. elif z0 in (-oo, -I*oo):
  577. e0 = e.subs(z, -z)
  578. else:
  579. if str(dir) == "-":
  580. e0 = e.subs(z, z0 - 1/z)
  581. elif str(dir) == "+":
  582. e0 = e.subs(z, z0 + 1/z)
  583. else:
  584. raise NotImplementedError("dir must be '+' or '-'")
  585. r = limitinf(e0, z)
  586. # This is a bit of a heuristic for nice results... we always rewrite
  587. # tractable functions in terms of familiar intractable ones.
  588. # It might be nicer to rewrite the exactly to what they were initially,
  589. # but that would take some work to implement.
  590. return r.rewrite('intractable', deep=True)