gruntz.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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, expand_mul
  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.utilities.exceptions import SymPyDeprecationWarning
  101. from sympy.utilities.misc import debug_decorator as debug
  102. from sympy.utilities.timeutils import timethis
  103. timeit = timethis('gruntz')
  104. def compare(a, b, x):
  105. """Returns "<" if a<b, "=" for a == b, ">" for a>b"""
  106. # log(exp(...)) must always be simplified here for termination
  107. la, lb = log(a), log(b)
  108. if isinstance(a, Basic) and (isinstance(a, exp) or (a.is_Pow and a.base == S.Exp1)):
  109. la = a.exp
  110. if isinstance(b, Basic) and (isinstance(b, exp) or (b.is_Pow and b.base == S.Exp1)):
  111. lb = b.exp
  112. c = limitinf(la/lb, x)
  113. if c == 0:
  114. return "<"
  115. elif c.is_infinite:
  116. return ">"
  117. else:
  118. return "="
  119. class SubsSet(dict):
  120. """
  121. Stores (expr, dummy) pairs, and how to rewrite expr-s.
  122. Explanation
  123. ===========
  124. The gruntz algorithm needs to rewrite certain expressions in term of a new
  125. variable w. We cannot use subs, because it is just too smart for us. For
  126. example::
  127. > Omega=[exp(exp(_p - exp(-_p))/(1 - 1/_p)), exp(exp(_p))]
  128. > O2=[exp(-exp(_p) + exp(-exp(-_p))*exp(_p)/(1 - 1/_p))/_w, 1/_w]
  129. > e = exp(exp(_p - exp(-_p))/(1 - 1/_p)) - exp(exp(_p))
  130. > e.subs(Omega[0],O2[0]).subs(Omega[1],O2[1])
  131. -1/w + exp(exp(p)*exp(-exp(-p))/(1 - 1/p))
  132. is really not what we want!
  133. So we do it the hard way and keep track of all the things we potentially
  134. want to substitute by dummy variables. Consider the expression::
  135. exp(x - exp(-x)) + exp(x) + x.
  136. The mrv set is {exp(x), exp(-x), exp(x - exp(-x))}.
  137. We introduce corresponding dummy variables d1, d2, d3 and rewrite::
  138. d3 + d1 + x.
  139. This class first of all keeps track of the mapping expr->variable, i.e.
  140. will at this stage be a dictionary::
  141. {exp(x): d1, exp(-x): d2, exp(x - exp(-x)): d3}.
  142. [It turns out to be more convenient this way round.]
  143. But sometimes expressions in the mrv set have other expressions from the
  144. mrv set as subexpressions, and we need to keep track of that as well. In
  145. this case, d3 is really exp(x - d2), so rewrites at this stage is::
  146. {d3: exp(x-d2)}.
  147. The function rewrite uses all this information to correctly rewrite our
  148. expression in terms of w. In this case w can be chosen to be exp(-x),
  149. i.e. d2. The correct rewriting then is::
  150. exp(-w)/w + 1/w + x.
  151. """
  152. def __init__(self):
  153. self.rewrites = {}
  154. def __repr__(self):
  155. return super().__repr__() + ', ' + self.rewrites.__repr__()
  156. def __getitem__(self, key):
  157. if key not in self:
  158. self[key] = Dummy()
  159. return dict.__getitem__(self, key)
  160. def do_subs(self, e):
  161. """Substitute the variables with expressions"""
  162. for expr, var in self.items():
  163. e = e.xreplace({var: expr})
  164. return e
  165. def meets(self, s2):
  166. """Tell whether or not self and s2 have non-empty intersection"""
  167. return set(self.keys()).intersection(list(s2.keys())) != set()
  168. def union(self, s2, exps=None):
  169. """Compute the union of self and s2, adjusting exps"""
  170. res = self.copy()
  171. tr = {}
  172. for expr, var in s2.items():
  173. if expr in self:
  174. if exps:
  175. exps = exps.xreplace({var: res[expr]})
  176. tr[var] = res[expr]
  177. else:
  178. res[expr] = var
  179. for var, rewr in s2.rewrites.items():
  180. res.rewrites[var] = rewr.xreplace(tr)
  181. return res, exps
  182. def copy(self):
  183. """Create a shallow copy of SubsSet"""
  184. r = SubsSet()
  185. r.rewrites = self.rewrites.copy()
  186. for expr, var in self.items():
  187. r[expr] = var
  188. return r
  189. @debug
  190. def mrv(e, x):
  191. """Returns a SubsSet of most rapidly varying (mrv) subexpressions of 'e',
  192. and e rewritten in terms of these"""
  193. from sympy.simplify.powsimp import powsimp
  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 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):
  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. def calculate_series(e, x, logx=None):
  408. """ Calculates at least one term of the series of ``e`` in ``x``.
  409. This is a place that fails most often, so it is in its own function.
  410. """
  411. SymPyDeprecationWarning(
  412. feature="calculate_series",
  413. useinstead="series() with suitable n, or as_leading_term",
  414. issue=21838,
  415. deprecated_since_version="1.12"
  416. ).warn()
  417. from sympy.simplify.powsimp import powdenest
  418. for t in e.lseries(x, logx=logx):
  419. # bottom_up function is required for a specific case - when e is
  420. # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p)
  421. t = bottom_up(t, lambda w:
  422. getattr(w, 'normal', lambda: w)())
  423. # And the expression
  424. # `(-sin(1/x) + sin((x + exp(x))*exp(-x)/x))*exp(x)`
  425. # from the first test of test_gruntz_eval_special needs to
  426. # be expanded. But other forms need to be have at least
  427. # factor_terms applied. `factor` accomplishes both and is
  428. # faster than using `factor_terms` for the gruntz suite. It
  429. # does not appear that use of `cancel` is necessary.
  430. # t = cancel(t, expand=False)
  431. t = t.factor()
  432. if t.has(exp) and t.has(log):
  433. t = powdenest(t)
  434. if not t.is_zero:
  435. break
  436. return t
  437. @debug
  438. @timeit
  439. @cacheit
  440. def mrv_leadterm(e, x):
  441. """Returns (c0, e0) for e."""
  442. Omega = SubsSet()
  443. if not e.has(x):
  444. return (e, S.Zero)
  445. if Omega == SubsSet():
  446. Omega, exps = mrv(e, x)
  447. if not Omega:
  448. # e really does not depend on x after simplification
  449. return exps, S.Zero
  450. if x in Omega:
  451. # move the whole omega up (exponentiate each term):
  452. Omega_up = moveup2(Omega, x)
  453. exps_up = moveup([exps], x)[0]
  454. # NOTE: there is no need to move this down!
  455. Omega = Omega_up
  456. exps = exps_up
  457. #
  458. # The positive dummy, w, is used here so log(w*2) etc. will expand;
  459. # a unique dummy is needed in this algorithm
  460. #
  461. # For limits of complex functions, the algorithm would have to be
  462. # improved, or just find limits of Re and Im components separately.
  463. #
  464. w = Dummy("w", positive=True)
  465. f, logw = rewrite(exps, Omega, x, w)
  466. try:
  467. lt = f.leadterm(w, logx=logw)
  468. except (NotImplementedError, PoleError, ValueError):
  469. n0 = 1
  470. _series = Order(1)
  471. incr = S.One
  472. while _series.is_Order:
  473. _series = f._eval_nseries(w, n=n0+incr, logx=logw)
  474. incr *= 2
  475. series = _series.expand().removeO()
  476. try:
  477. lt = series.leadterm(w, logx=logw)
  478. except (NotImplementedError, PoleError, ValueError):
  479. lt = f.as_coeff_exponent(w)
  480. if lt[0].has(w):
  481. base = f.as_base_exp()[0].as_coeff_exponent(w)
  482. ex = f.as_base_exp()[1]
  483. lt = (base[0]**ex, base[1]*ex)
  484. return (lt[0].subs(log(w), logw), lt[1])
  485. def build_expression_tree(Omega, rewrites):
  486. r""" Helper function for rewrite.
  487. We need to sort Omega (mrv set) so that we replace an expression before
  488. we replace any expression in terms of which it has to be rewritten::
  489. e1 ---> e2 ---> e3
  490. \
  491. -> e4
  492. Here we can do e1, e2, e3, e4 or e1, e2, e4, e3.
  493. To do this we assemble the nodes into a tree, and sort them by height.
  494. This function builds the tree, rewrites then sorts the nodes.
  495. """
  496. class Node:
  497. def __init__(self):
  498. self.before = []
  499. self.expr = None
  500. self.var = None
  501. def ht(self):
  502. return reduce(lambda x, y: x + y,
  503. [x.ht() for x in self.before], 1)
  504. nodes = {}
  505. for expr, v in Omega:
  506. n = Node()
  507. n.var = v
  508. n.expr = expr
  509. nodes[v] = n
  510. for _, v in Omega:
  511. if v in rewrites:
  512. n = nodes[v]
  513. r = rewrites[v]
  514. for _, v2 in Omega:
  515. if r.has(v2):
  516. n.before.append(nodes[v2])
  517. return nodes
  518. @debug
  519. @timeit
  520. def rewrite(e, Omega, x, wsym):
  521. """e(x) ... the function
  522. Omega ... the mrv set
  523. wsym ... the symbol which is going to be used for w
  524. Returns the rewritten e in terms of w and log(w). See test_rewrite1()
  525. for examples and correct results.
  526. """
  527. from sympy import AccumBounds
  528. if not isinstance(Omega, SubsSet):
  529. raise TypeError("Omega should be an instance of SubsSet")
  530. if len(Omega) == 0:
  531. raise ValueError("Length cannot be 0")
  532. # all items in Omega must be exponentials
  533. for t in Omega.keys():
  534. if not isinstance(t, exp):
  535. raise ValueError("Value should be exp")
  536. rewrites = Omega.rewrites
  537. Omega = list(Omega.items())
  538. nodes = build_expression_tree(Omega, rewrites)
  539. Omega.sort(key=lambda x: nodes[x[1]].ht(), reverse=True)
  540. # make sure we know the sign of each exp() term; after the loop,
  541. # g is going to be the "w" - the simplest one in the mrv set
  542. for g, _ in Omega:
  543. sig = sign(g.exp, x)
  544. if sig != 1 and sig != -1 and not sig.has(AccumBounds):
  545. raise NotImplementedError('Result depends on the sign of %s' % sig)
  546. if sig == 1:
  547. wsym = 1/wsym # if g goes to oo, substitute 1/w
  548. # O2 is a list, which results by rewriting each item in Omega using "w"
  549. O2 = []
  550. denominators = []
  551. for f, var in Omega:
  552. c = limitinf(f.exp/g.exp, x)
  553. if c.is_Rational:
  554. denominators.append(c.q)
  555. arg = f.exp
  556. if var in rewrites:
  557. if not isinstance(rewrites[var], exp):
  558. raise ValueError("Value should be exp")
  559. arg = rewrites[var].args[0]
  560. O2.append((var, exp((arg - c*g.exp).expand())*wsym**c))
  561. # Remember that Omega contains subexpressions of "e". So now we find
  562. # them in "e" and substitute them for our rewriting, stored in O2
  563. # the following powsimp is necessary to automatically combine exponentials,
  564. # so that the .xreplace() below succeeds:
  565. # TODO this should not be necessary
  566. from sympy.simplify.powsimp import powsimp
  567. f = powsimp(e, deep=True, combine='exp')
  568. for a, b in O2:
  569. f = f.xreplace({a: b})
  570. for _, var in Omega:
  571. assert not f.has(var)
  572. # finally compute the logarithm of w (logw).
  573. logw = g.exp
  574. if sig == 1:
  575. logw = -logw # log(w)->log(1/w)=-log(w)
  576. # Some parts of SymPy have difficulty computing series expansions with
  577. # non-integral exponents. The following heuristic improves the situation:
  578. exponent = reduce(ilcm, denominators, 1)
  579. f = f.subs({wsym: wsym**exponent})
  580. logw /= exponent
  581. # bottom_up function is required for a specific case - when f is
  582. # -exp(p/(p + 1)) + exp(-p**2/(p + 1) + p). No current simplification
  583. # methods reduce this to 0 while not expanding polynomials.
  584. f = bottom_up(f, lambda w: getattr(w, 'normal', lambda: w)())
  585. f = expand_mul(f)
  586. return f, logw
  587. def gruntz(e, z, z0, dir="+"):
  588. """
  589. Compute the limit of e(z) at the point z0 using the Gruntz algorithm.
  590. Explanation
  591. ===========
  592. ``z0`` can be any expression, including oo and -oo.
  593. For ``dir="+"`` (default) it calculates the limit from the right
  594. (z->z0+) and for ``dir="-"`` the limit from the left (z->z0-). For infinite z0
  595. (oo or -oo), the dir argument does not matter.
  596. This algorithm is fully described in the module docstring in the gruntz.py
  597. file. It relies heavily on the series expansion. Most frequently, gruntz()
  598. is only used if the faster limit() function (which uses heuristics) fails.
  599. """
  600. if not z.is_symbol:
  601. raise NotImplementedError("Second argument must be a Symbol")
  602. # convert all limits to the limit z->oo; sign of z is handled in limitinf
  603. r = None
  604. if z0 in (oo, I*oo):
  605. e0 = e
  606. elif z0 in (-oo, -I*oo):
  607. e0 = e.subs(z, -z)
  608. else:
  609. if str(dir) == "-":
  610. e0 = e.subs(z, z0 - 1/z)
  611. elif str(dir) == "+":
  612. e0 = e.subs(z, z0 + 1/z)
  613. else:
  614. raise NotImplementedError("dir must be '+' or '-'")
  615. r = limitinf(e0, z)
  616. # This is a bit of a heuristic for nice results... we always rewrite
  617. # tractable functions in terms of familiar intractable ones.
  618. # It might be nicer to rewrite the exactly to what they were initially,
  619. # but that would take some work to implement.
  620. return r.rewrite('intractable', deep=True)