gruntz.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. """
  2. Limits
  3. ======
  4. Implemented according to the PhD thesis
  5. http://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.numbers import ilcm, I, oo
  96. from sympy.core.symbol import Dummy, Wild
  97. from sympy.core.traversal import bottom_up
  98. from sympy.functions import log, exp, sign as _sign
  99. from sympy.series.order import Order
  100. from sympy.simplify import logcombine
  101. from sympy.simplify.powsimp import powsimp, powdenest
  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. e = powsimp(e, deep=True, combine='exp')
  195. if not isinstance(e, Basic):
  196. raise TypeError("e should be an instance of Basic")
  197. if not e.has(x):
  198. return SubsSet(), e
  199. elif e == x:
  200. s = SubsSet()
  201. return s, s[x]
  202. elif e.is_Mul or e.is_Add:
  203. i, d = e.as_independent(x) # throw away x-independent terms
  204. if d.func != e.func:
  205. s, expr = mrv(d, x)
  206. return s, e.func(i, expr)
  207. a, b = d.as_two_terms()
  208. s1, e1 = mrv(a, x)
  209. s2, e2 = mrv(b, x)
  210. return mrv_max1(s1, s2, e.func(i, e1, e2), x)
  211. elif e.is_Pow and e.base != S.Exp1:
  212. e1 = S.One
  213. while e.is_Pow:
  214. b1 = e.base
  215. e1 *= e.exp
  216. e = b1
  217. if b1 == 1:
  218. return SubsSet(), b1
  219. if e1.has(x):
  220. base_lim = limitinf(b1, x)
  221. if base_lim is S.One:
  222. return mrv(exp(e1 * (b1 - 1)), x)
  223. return mrv(exp(e1 * log(b1)), x)
  224. else:
  225. s, expr = mrv(b1, x)
  226. return s, expr**e1
  227. elif isinstance(e, log):
  228. s, expr = mrv(e.args[0], x)
  229. return s, log(expr)
  230. elif isinstance(e, exp) or (e.is_Pow and e.base == S.Exp1):
  231. # We know from the theory of this algorithm that exp(log(...)) may always
  232. # be simplified here, and doing so is vital for termination.
  233. if isinstance(e.exp, log):
  234. return mrv(e.exp.args[0], x)
  235. # if a product has an infinite factor the result will be
  236. # infinite if there is no zero, otherwise NaN; here, we
  237. # consider the result infinite if any factor is infinite
  238. li = limitinf(e.exp, x)
  239. if any(_.is_infinite for _ in Mul.make_args(li)):
  240. s1 = SubsSet()
  241. e1 = s1[e]
  242. s2, e2 = mrv(e.exp, x)
  243. su = s1.union(s2)[0]
  244. su.rewrites[e1] = exp(e2)
  245. return mrv_max3(s1, e1, s2, exp(e2), su, e1, x)
  246. else:
  247. s, expr = mrv(e.exp, x)
  248. return s, exp(expr)
  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 derviatives"
  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. e = logcombine(e)
  326. return _sign(e)
  327. elif e == x:
  328. return 1
  329. elif e.is_Mul:
  330. a, b = e.as_two_terms()
  331. sa = sign(a, x)
  332. if not sa:
  333. return 0
  334. return sa * sign(b, x)
  335. elif isinstance(e, exp):
  336. return 1
  337. elif e.is_Pow:
  338. if e.base == S.Exp1:
  339. return 1
  340. s = sign(e.base, x)
  341. if s == 1:
  342. return 1
  343. if e.exp.is_Integer:
  344. return s**e.exp
  345. elif isinstance(e, log):
  346. return sign(e.args[0] - 1, x)
  347. # if all else fails, do it the hard way
  348. c0, e0 = mrv_leadterm(e, x)
  349. return sign(c0, x)
  350. @debug
  351. @timeit
  352. @cacheit
  353. def limitinf(e, x, leadsimp=False):
  354. """Limit e(x) for x-> oo.
  355. Explanation
  356. ===========
  357. If ``leadsimp`` is True, an attempt is made to simplify the leading
  358. term of the series expansion of ``e``. That may succeed even if
  359. ``e`` cannot be simplified.
  360. """
  361. # rewrite e in terms of tractable functions only
  362. if not e.has(x):
  363. return e # e is a constant
  364. if e.has(Order):
  365. e = e.expand().removeO()
  366. if not x.is_positive or x.is_integer:
  367. # We make sure that x.is_positive is True and x.is_integer is None
  368. # so we get all the correct mathematical behavior from the expression.
  369. # We need a fresh variable.
  370. p = Dummy('p', positive=True)
  371. e = e.subs(x, p)
  372. x = p
  373. e = e.rewrite('tractable', deep=True, limitvar=x)
  374. e = powdenest(e)
  375. c0, e0 = mrv_leadterm(e, x)
  376. sig = sign(e0, x)
  377. if sig == 1:
  378. return S.Zero # e0>0: lim f = 0
  379. elif sig == -1: # e0<0: lim f = +-oo (the sign depends on the sign of c0)
  380. if c0.match(I*Wild("a", exclude=[I])):
  381. return c0*oo
  382. s = sign(c0, x)
  383. # the leading term shouldn't be 0:
  384. if s == 0:
  385. raise ValueError("Leading term should not be 0")
  386. return s*oo
  387. elif sig == 0:
  388. if leadsimp:
  389. c0 = c0.simplify()
  390. return limitinf(c0, x, leadsimp) # e0=0: lim f = lim c0
  391. else:
  392. raise ValueError("{} could not be evaluated".format(sig))
  393. def moveup2(s, x):
  394. r = SubsSet()
  395. for expr, var in s.items():
  396. r[expr.xreplace({x: exp(x)})] = var
  397. for var, expr in s.rewrites.items():
  398. r.rewrites[var] = s.rewrites[var].xreplace({x: exp(x)})
  399. return r
  400. def moveup(l, x):
  401. return [e.xreplace({x: exp(x)}) for e in l]
  402. @debug
  403. @timeit
  404. def calculate_series(e, x, logx=None):
  405. """ Calculates at least one term of the series of ``e`` in ``x``.
  406. This is a place that fails most often, so it is in its own function.
  407. """
  408. for t in e.lseries(x, logx=logx):
  409. # bottom_up function is required for a specific case - when e is
  410. # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p)
  411. t = bottom_up(t, lambda w:
  412. getattr(w, 'normal', lambda: w)())
  413. # And the expression
  414. # `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)`
  415. # from the first test of test_gruntz_eval_special needs to
  416. # be expanded. But other forms need to be have at least
  417. # factor_terms applied. `factor` accomplishes both and is
  418. # faster than using `factor_terms` for the gruntz suite. It
  419. # does not appear that use of `cancel` is necessary.
  420. # t = cancel(t, expand=False)
  421. t = t.factor()
  422. if t.has(exp) and t.has(log):
  423. t = powdenest(t)
  424. if not t.is_zero:
  425. break
  426. return t
  427. @debug
  428. @timeit
  429. @cacheit
  430. def mrv_leadterm(e, x):
  431. """Returns (c0, e0) for e."""
  432. Omega = SubsSet()
  433. if not e.has(x):
  434. return (e, S.Zero)
  435. if Omega == SubsSet():
  436. Omega, exps = mrv(e, x)
  437. if not Omega:
  438. # e really does not depend on x after simplification
  439. return exps, S.Zero
  440. if x in Omega:
  441. # move the whole omega up (exponentiate each term):
  442. Omega_up = moveup2(Omega, x)
  443. exps_up = moveup([exps], x)[0]
  444. # NOTE: there is no need to move this down!
  445. Omega = Omega_up
  446. exps = exps_up
  447. #
  448. # The positive dummy, w, is used here so log(w*2) etc. will expand;
  449. # a unique dummy is needed in this algorithm
  450. #
  451. # For limits of complex functions, the algorithm would have to be
  452. # improved, or just find limits of Re and Im components separately.
  453. #
  454. w = Dummy("w", positive=True)
  455. f, logw = rewrite(exps, Omega, x, w)
  456. series = calculate_series(f, w, logx=logw)
  457. try:
  458. lt = series.leadterm(w, logx=logw)
  459. except (ValueError, PoleError):
  460. lt = f.as_coeff_exponent(w)
  461. # as_coeff_exponent won't always split in required form. It may simply
  462. # return (f, 0) when a better form may be obtained. Example (-x)**(-pi)
  463. # can be written as (-1**(-pi), -pi) which as_coeff_exponent does not return
  464. if lt[0].has(w):
  465. base = f.as_base_exp()[0].as_coeff_exponent(w)
  466. ex = f.as_base_exp()[1]
  467. lt = (base[0]**ex, base[1]*ex)
  468. return (lt[0].subs(log(w), logw), lt[1])
  469. def build_expression_tree(Omega, rewrites):
  470. r""" Helper function for rewrite.
  471. We need to sort Omega (mrv set) so that we replace an expression before
  472. we replace any expression in terms of which it has to be rewritten::
  473. e1 ---> e2 ---> e3
  474. \
  475. -> e4
  476. Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
  477. To do this we assemble the nodes into a tree, and sort them by height.
  478. This function builds the tree, rewrites then sorts the nodes.
  479. """
  480. class Node:
  481. def __init__(self):
  482. self.before = []
  483. self.expr = None
  484. self.var = None
  485. def ht(self):
  486. return reduce(lambda x, y: x + y,
  487. [x.ht() for x in self.before], 1)
  488. nodes = {}
  489. for expr, v in Omega:
  490. n = Node()
  491. n.var = v
  492. n.expr = expr
  493. nodes[v] = n
  494. for _, v in Omega:
  495. if v in rewrites:
  496. n = nodes[v]
  497. r = rewrites[v]
  498. for _, v2 in Omega:
  499. if r.has(v2):
  500. n.before.append(nodes[v2])
  501. return nodes
  502. @debug
  503. @timeit
  504. def rewrite(e, Omega, x, wsym):
  505. """e(x) ... the function
  506. Omega ... the mrv set
  507. wsym ... the symbol which is going to be used for w
  508. Returns the rewritten e in terms of w and log(w). See test_rewrite1()
  509. for examples and correct results.
  510. """
  511. if not isinstance(Omega, SubsSet):
  512. raise TypeError("Omega should be an instance of SubsSet")
  513. if len(Omega) == 0:
  514. raise ValueError("Length cannot be 0")
  515. # all items in Omega must be exponentials
  516. for t in Omega.keys():
  517. if not isinstance(t, exp):
  518. raise ValueError("Value should be exp")
  519. rewrites = Omega.rewrites
  520. Omega = list(Omega.items())
  521. nodes = build_expression_tree(Omega, rewrites)
  522. Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
  523. # make sure we know the sign of each exp() term; after the loop,
  524. # g is going to be the "w" - the simplest one in the mrv set
  525. for g, _ in Omega:
  526. sig = sign(g.exp, x)
  527. if sig != 1 and sig != -1:
  528. raise NotImplementedError('Result depends on the sign of %s' % sig)
  529. if sig == 1:
  530. wsym = 1/wsym # if g goes to oo, substitute 1/w
  531. # O2 is a list, which results by rewriting each item in Omega using "w"
  532. O2 = []
  533. denominators = []
  534. for f, var in Omega:
  535. c = limitinf(f.exp/g.exp, x)
  536. if c.is_Rational:
  537. denominators.append(c.q)
  538. arg = f.exp
  539. if var in rewrites:
  540. if not isinstance(rewrites[var], exp):
  541. raise ValueError("Value should be exp")
  542. arg = rewrites[var].args[0]
  543. O2.append((var, exp((arg - c*g.exp).expand())*wsym**c))
  544. # Remember that Omega contains subexpressions of "e". So now we find
  545. # them in "e" and substitute them for our rewriting, stored in O2
  546. # the following powsimp is necessary to automatically combine exponentials,
  547. # so that the .xreplace() below succeeds:
  548. # TODO this should not be necessary
  549. f = powsimp(e, deep=True, combine='exp')
  550. for a, b in O2:
  551. f = f.xreplace({a: b})
  552. for _, var in Omega:
  553. assert not f.has(var)
  554. # finally compute the logarithm of w (logw).
  555. logw = g.exp
  556. if sig == 1:
  557. logw = -logw # log(w)->log(1/w)=-log(w)
  558. # Some parts of SymPy have difficulty computing series expansions with
  559. # non-integral exponents. The following heuristic improves the situation:
  560. exponent = reduce(ilcm, denominators, 1)
  561. f = f.subs({wsym: wsym**exponent})
  562. logw /= exponent
  563. return f, logw
  564. def gruntz(e, z, z0, dir="+"):
  565. """
  566. Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
  567. Explanation
  568. ===========
  569. ``z0`` can be any expression, including oo and -oo.
  570. For ``dir="+"`` (default) it calculates the limit from the right
  571. (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
  572. (oo or -oo), the dir argument doesn't matter.
  573. This algorithm is fully described in the module docstring in the gruntz.py
  574. file. It relies heavily on the series expansion. Most frequently, gruntz()
  575. is only used if the faster limit() function (which uses heuristics) fails.
  576. """
  577. if not z.is_symbol:
  578. raise NotImplementedError("Second argument must be a Symbol")
  579. # convert all limits to the limit z->oo; sign of z is handled in limitinf
  580. r = None
  581. if z0 == oo:
  582. e0 = e
  583. elif z0 == -oo:
  584. e0 = e.subs(z, -z)
  585. else:
  586. if str(dir) == "-":
  587. e0 = e.subs(z, z0 - 1/z)
  588. elif str(dir) == "+":
  589. e0 = e.subs(z, z0 + 1/z)
  590. else:
  591. raise NotImplementedError("dir must be '+' or '-'")
  592. try:
  593. r = limitinf(e0, z)
  594. except ValueError:
  595. r = limitinf(e0, z, leadsimp=True)
  596. # This is a bit of a heuristic for nice results... we always rewrite
  597. # tractable functions in terms of familiar intractable ones.
  598. # It might be nicer to rewrite the exactly to what they were initially,
  599. # but that would take some work to implement.
  600. return r.rewrite('intractable', deep=True)