powsimp.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. from collections import defaultdict
  2. from functools import reduce
  3. from math import prod
  4. from sympy.core.function import expand_log, count_ops, _coeff_isneg
  5. from sympy.core import sympify, Basic, Dummy, S, Add, Mul, Pow, expand_mul, factor_terms
  6. from sympy.core.sorting import ordered, default_sort_key
  7. from sympy.core.numbers import Integer, Rational, equal_valued
  8. from sympy.core.mul import _keep_coeff
  9. from sympy.core.rules import Transform
  10. from sympy.functions import exp_polar, exp, log, root, polarify, unpolarify
  11. from sympy.matrices.expressions.matexpr import MatrixSymbol
  12. from sympy.polys import lcm, gcd
  13. from sympy.ntheory.factor_ import multiplicity
  14. def powsimp(expr, deep=False, combine='all', force=False, measure=count_ops):
  15. """
  16. Reduce expression by combining powers with similar bases and exponents.
  17. Explanation
  18. ===========
  19. If ``deep`` is ``True`` then powsimp() will also simplify arguments of
  20. functions. By default ``deep`` is set to ``False``.
  21. If ``force`` is ``True`` then bases will be combined without checking for
  22. assumptions, e.g. sqrt(x)*sqrt(y) -> sqrt(x*y) which is not true
  23. if x and y are both negative.
  24. You can make powsimp() only combine bases or only combine exponents by
  25. changing combine='base' or combine='exp'. By default, combine='all',
  26. which does both. combine='base' will only combine::
  27. a a a 2x x
  28. x * y => (x*y) as well as things like 2 => 4
  29. and combine='exp' will only combine
  30. ::
  31. a b (a + b)
  32. x * x => x
  33. combine='exp' will strictly only combine exponents in the way that used
  34. to be automatic. Also use deep=True if you need the old behavior.
  35. When combine='all', 'exp' is evaluated first. Consider the first
  36. example below for when there could be an ambiguity relating to this.
  37. This is done so things like the second example can be completely
  38. combined. If you want 'base' combined first, do something like
  39. powsimp(powsimp(expr, combine='base'), combine='exp').
  40. Examples
  41. ========
  42. >>> from sympy import powsimp, exp, log, symbols
  43. >>> from sympy.abc import x, y, z, n
  44. >>> powsimp(x**y*x**z*y**z, combine='all')
  45. x**(y + z)*y**z
  46. >>> powsimp(x**y*x**z*y**z, combine='exp')
  47. x**(y + z)*y**z
  48. >>> powsimp(x**y*x**z*y**z, combine='base', force=True)
  49. x**y*(x*y)**z
  50. >>> powsimp(x**z*x**y*n**z*n**y, combine='all', force=True)
  51. (n*x)**(y + z)
  52. >>> powsimp(x**z*x**y*n**z*n**y, combine='exp')
  53. n**(y + z)*x**(y + z)
  54. >>> powsimp(x**z*x**y*n**z*n**y, combine='base', force=True)
  55. (n*x)**y*(n*x)**z
  56. >>> x, y = symbols('x y', positive=True)
  57. >>> powsimp(log(exp(x)*exp(y)))
  58. log(exp(x)*exp(y))
  59. >>> powsimp(log(exp(x)*exp(y)), deep=True)
  60. x + y
  61. Radicals with Mul bases will be combined if combine='exp'
  62. >>> from sympy import sqrt
  63. >>> x, y = symbols('x y')
  64. Two radicals are automatically joined through Mul:
  65. >>> a=sqrt(x*sqrt(y))
  66. >>> a*a**3 == a**4
  67. True
  68. But if an integer power of that radical has been
  69. autoexpanded then Mul does not join the resulting factors:
  70. >>> a**4 # auto expands to a Mul, no longer a Pow
  71. x**2*y
  72. >>> _*a # so Mul doesn't combine them
  73. x**2*y*sqrt(x*sqrt(y))
  74. >>> powsimp(_) # but powsimp will
  75. (x*sqrt(y))**(5/2)
  76. >>> powsimp(x*y*a) # but won't when doing so would violate assumptions
  77. x*y*sqrt(x*sqrt(y))
  78. """
  79. def recurse(arg, **kwargs):
  80. _deep = kwargs.get('deep', deep)
  81. _combine = kwargs.get('combine', combine)
  82. _force = kwargs.get('force', force)
  83. _measure = kwargs.get('measure', measure)
  84. return powsimp(arg, _deep, _combine, _force, _measure)
  85. expr = sympify(expr)
  86. if (not isinstance(expr, Basic) or isinstance(expr, MatrixSymbol) or (
  87. expr.is_Atom or expr in (exp_polar(0), exp_polar(1)))):
  88. return expr
  89. if deep or expr.is_Add or expr.is_Mul and _y not in expr.args:
  90. expr = expr.func(*[recurse(w) for w in expr.args])
  91. if expr.is_Pow:
  92. return recurse(expr*_y, deep=False)/_y
  93. if not expr.is_Mul:
  94. return expr
  95. # handle the Mul
  96. if combine in ('exp', 'all'):
  97. # Collect base/exp data, while maintaining order in the
  98. # non-commutative parts of the product
  99. c_powers = defaultdict(list)
  100. nc_part = []
  101. newexpr = []
  102. coeff = S.One
  103. for term in expr.args:
  104. if term.is_Rational:
  105. coeff *= term
  106. continue
  107. if term.is_Pow:
  108. term = _denest_pow(term)
  109. if term.is_commutative:
  110. b, e = term.as_base_exp()
  111. if deep:
  112. b, e = [recurse(i) for i in [b, e]]
  113. if b.is_Pow or isinstance(b, exp):
  114. # don't let smthg like sqrt(x**a) split into x**a, 1/2
  115. # or else it will be joined as x**(a/2) later
  116. b, e = b**e, S.One
  117. c_powers[b].append(e)
  118. else:
  119. # This is the logic that combines exponents for equal,
  120. # but non-commutative bases: A**x*A**y == A**(x+y).
  121. if nc_part:
  122. b1, e1 = nc_part[-1].as_base_exp()
  123. b2, e2 = term.as_base_exp()
  124. if (b1 == b2 and
  125. e1.is_commutative and e2.is_commutative):
  126. nc_part[-1] = Pow(b1, Add(e1, e2))
  127. continue
  128. nc_part.append(term)
  129. # add up exponents of common bases
  130. for b, e in ordered(iter(c_powers.items())):
  131. # allow 2**x/4 -> 2**(x - 2); don't do this when b and e are
  132. # Numbers since autoevaluation will undo it, e.g.
  133. # 2**(1/3)/4 -> 2**(1/3 - 2) -> 2**(1/3)/4
  134. if (b and b.is_Rational and not all(ei.is_Number for ei in e) and \
  135. coeff is not S.One and
  136. b not in (S.One, S.NegativeOne)):
  137. m = multiplicity(abs(b), abs(coeff))
  138. if m:
  139. e.append(m)
  140. coeff /= b**m
  141. c_powers[b] = Add(*e)
  142. if coeff is not S.One:
  143. if coeff in c_powers:
  144. c_powers[coeff] += S.One
  145. else:
  146. c_powers[coeff] = S.One
  147. # convert to plain dictionary
  148. c_powers = dict(c_powers)
  149. # check for base and inverted base pairs
  150. be = list(c_powers.items())
  151. skip = set() # skip if we already saw them
  152. for b, e in be:
  153. if b in skip:
  154. continue
  155. bpos = b.is_positive or b.is_polar
  156. if bpos:
  157. binv = 1/b
  158. #Special case for float 1
  159. if b.is_Float and equal_valued(b, 1):
  160. c_powers[b] = S.One
  161. continue
  162. if b != binv and binv in c_powers:
  163. if b.as_numer_denom()[0] is S.One:
  164. c_powers.pop(b)
  165. c_powers[binv] -= e
  166. else:
  167. skip.add(binv)
  168. e = c_powers.pop(binv)
  169. c_powers[b] -= e
  170. # check for base and negated base pairs
  171. be = list(c_powers.items())
  172. _n = S.NegativeOne
  173. for b, e in be:
  174. if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers:
  175. if (b.is_positive is not None or e.is_integer):
  176. if e.is_integer or b.is_negative:
  177. c_powers[-b] += c_powers.pop(b)
  178. else: # (-b).is_positive so use its e
  179. e = c_powers.pop(-b)
  180. c_powers[b] += e
  181. if _n in c_powers:
  182. c_powers[_n] += e
  183. else:
  184. c_powers[_n] = e
  185. # filter c_powers and convert to a list
  186. c_powers = [(b, e) for b, e in c_powers.items() if e]
  187. # ==============================================================
  188. # check for Mul bases of Rational powers that can be combined with
  189. # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) ->
  190. # (x*sqrt(x*y))**(3/2)
  191. # ---------------- helper functions
  192. def ratq(x):
  193. '''Return Rational part of x's exponent as it appears in the bkey.
  194. '''
  195. return bkey(x)[0][1]
  196. def bkey(b, e=None):
  197. '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then
  198. it will be taken by using as_base_exp() on the input b.
  199. e.g.
  200. x**3/2 -> (x, 2), 3
  201. x**y -> (x**y, 1), 1
  202. x**(2*y/3) -> (x**y, 3), 2
  203. exp(x/2) -> (exp(a), 2), 1
  204. '''
  205. if e is not None: # coming from c_powers or from below
  206. if e.is_Integer:
  207. return (b, S.One), e
  208. elif e.is_Rational:
  209. return (b, Integer(e.q)), Integer(e.p)
  210. else:
  211. c, m = e.as_coeff_Mul(rational=True)
  212. if c is not S.One:
  213. if m.is_integer:
  214. return (b, Integer(c.q)), m*Integer(c.p)
  215. return (b**m, Integer(c.q)), Integer(c.p)
  216. else:
  217. return (b**e, S.One), S.One
  218. else:
  219. return bkey(*b.as_base_exp())
  220. def update(b):
  221. '''Decide what to do with base, b. If its exponent is now an
  222. integer multiple of the Rational denominator, then remove it
  223. and put the factors of its base in the common_b dictionary or
  224. update the existing bases if necessary. If it has been zeroed
  225. out, simply remove the base.
  226. '''
  227. newe, r = divmod(common_b[b], b[1])
  228. if not r:
  229. common_b.pop(b)
  230. if newe:
  231. for m in Mul.make_args(b[0]**newe):
  232. b, e = bkey(m)
  233. if b not in common_b:
  234. common_b[b] = 0
  235. common_b[b] += e
  236. if b[1] != 1:
  237. bases.append(b)
  238. # ---------------- end of helper functions
  239. # assemble a dictionary of the factors having a Rational power
  240. common_b = {}
  241. done = []
  242. bases = []
  243. for b, e in c_powers:
  244. b, e = bkey(b, e)
  245. if b in common_b:
  246. common_b[b] = common_b[b] + e
  247. else:
  248. common_b[b] = e
  249. if b[1] != 1 and b[0].is_Mul:
  250. bases.append(b)
  251. bases.sort(key=default_sort_key) # this makes tie-breaking canonical
  252. bases.sort(key=measure, reverse=True) # handle longest first
  253. for base in bases:
  254. if base not in common_b: # it may have been removed already
  255. continue
  256. b, exponent = base
  257. last = False # True when no factor of base is a radical
  258. qlcm = 1 # the lcm of the radical denominators
  259. while True:
  260. bstart = b
  261. qstart = qlcm
  262. bb = [] # list of factors
  263. ee = [] # (factor's expo. and it's current value in common_b)
  264. for bi in Mul.make_args(b):
  265. bib, bie = bkey(bi)
  266. if bib not in common_b or common_b[bib] < bie:
  267. ee = bb = [] # failed
  268. break
  269. ee.append([bie, common_b[bib]])
  270. bb.append(bib)
  271. if ee:
  272. # find the number of integral extractions possible
  273. # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1
  274. min1 = ee[0][1]//ee[0][0]
  275. for i in range(1, len(ee)):
  276. rat = ee[i][1]//ee[i][0]
  277. if rat < 1:
  278. break
  279. min1 = min(min1, rat)
  280. else:
  281. # update base factor counts
  282. # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2
  283. # and the new base counts will be 5-2*2 and 6-2*3
  284. for i in range(len(bb)):
  285. common_b[bb[i]] -= min1*ee[i][0]
  286. update(bb[i])
  287. # update the count of the base
  288. # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y)
  289. # will increase by 4 to give bkey (x*sqrt(y), 2, 5)
  290. common_b[base] += min1*qstart*exponent
  291. if (last # no more radicals in base
  292. or len(common_b) == 1 # nothing left to join with
  293. or all(k[1] == 1 for k in common_b) # no rad's in common_b
  294. ):
  295. break
  296. # see what we can exponentiate base by to remove any radicals
  297. # so we know what to search for
  298. # e.g. if base were x**(1/2)*y**(1/3) then we should
  299. # exponentiate by 6 and look for powers of x and y in the ratio
  300. # of 2 to 3
  301. qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)])
  302. if qlcm == 1:
  303. break # we are done
  304. b = bstart**qlcm
  305. qlcm *= qstart
  306. if all(ratq(bi) == 1 for bi in Mul.make_args(b)):
  307. last = True # we are going to be done after this next pass
  308. # this base no longer can find anything to join with and
  309. # since it was longer than any other we are done with it
  310. b, q = base
  311. done.append((b, common_b.pop(base)*Rational(1, q)))
  312. # update c_powers and get ready to continue with powsimp
  313. c_powers = done
  314. # there may be terms still in common_b that were bases that were
  315. # identified as needing processing, so remove those, too
  316. for (b, q), e in common_b.items():
  317. if (b.is_Pow or isinstance(b, exp)) and \
  318. q is not S.One and not b.exp.is_Rational:
  319. b, be = b.as_base_exp()
  320. b = b**(be/q)
  321. else:
  322. b = root(b, q)
  323. c_powers.append((b, e))
  324. check = len(c_powers)
  325. c_powers = dict(c_powers)
  326. assert len(c_powers) == check # there should have been no duplicates
  327. # ==============================================================
  328. # rebuild the expression
  329. newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()]))
  330. if combine == 'exp':
  331. return expr.func(newexpr, expr.func(*nc_part))
  332. else:
  333. return recurse(expr.func(*nc_part), combine='base') * \
  334. recurse(newexpr, combine='base')
  335. elif combine == 'base':
  336. # Build c_powers and nc_part. These must both be lists not
  337. # dicts because exp's are not combined.
  338. c_powers = []
  339. nc_part = []
  340. for term in expr.args:
  341. if term.is_commutative:
  342. c_powers.append(list(term.as_base_exp()))
  343. else:
  344. nc_part.append(term)
  345. # Pull out numerical coefficients from exponent if assumptions allow
  346. # e.g., 2**(2*x) => 4**x
  347. for i in range(len(c_powers)):
  348. b, e = c_powers[i]
  349. if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar):
  350. continue
  351. exp_c, exp_t = e.as_coeff_Mul(rational=True)
  352. if exp_c is not S.One and exp_t is not S.One:
  353. c_powers[i] = [Pow(b, exp_c), exp_t]
  354. # Combine bases whenever they have the same exponent and
  355. # assumptions allow
  356. # first gather the potential bases under the common exponent
  357. c_exp = defaultdict(list)
  358. for b, e in c_powers:
  359. if deep:
  360. e = recurse(e)
  361. if e.is_Add and (b.is_positive or e.is_integer):
  362. e = factor_terms(e)
  363. if _coeff_isneg(e):
  364. e = -e
  365. b = 1/b
  366. c_exp[e].append(b)
  367. del c_powers
  368. # Merge back in the results of the above to form a new product
  369. c_powers = defaultdict(list)
  370. for e in c_exp:
  371. bases = c_exp[e]
  372. # calculate the new base for e
  373. if len(bases) == 1:
  374. new_base = bases[0]
  375. elif e.is_integer or force:
  376. new_base = expr.func(*bases)
  377. else:
  378. # see which ones can be joined
  379. unk = []
  380. nonneg = []
  381. neg = []
  382. for bi in bases:
  383. if bi.is_negative:
  384. neg.append(bi)
  385. elif bi.is_nonnegative:
  386. nonneg.append(bi)
  387. elif bi.is_polar:
  388. nonneg.append(
  389. bi) # polar can be treated like non-negative
  390. else:
  391. unk.append(bi)
  392. if len(unk) == 1 and not neg or len(neg) == 1 and not unk:
  393. # a single neg or a single unk can join the rest
  394. nonneg.extend(unk + neg)
  395. unk = neg = []
  396. elif neg:
  397. # their negative signs cancel in groups of 2*q if we know
  398. # that e = p/q else we have to treat them as unknown
  399. israt = False
  400. if e.is_Rational:
  401. israt = True
  402. else:
  403. p, d = e.as_numer_denom()
  404. if p.is_integer and d.is_integer:
  405. israt = True
  406. if israt:
  407. neg = [-w for w in neg]
  408. unk.extend([S.NegativeOne]*len(neg))
  409. else:
  410. unk.extend(neg)
  411. neg = []
  412. del israt
  413. # these shouldn't be joined
  414. for b in unk:
  415. c_powers[b].append(e)
  416. # here is a new joined base
  417. new_base = expr.func(*(nonneg + neg))
  418. # if there are positive parts they will just get separated
  419. # again unless some change is made
  420. def _terms(e):
  421. # return the number of terms of this expression
  422. # when multiplied out -- assuming no joining of terms
  423. if e.is_Add:
  424. return sum(_terms(ai) for ai in e.args)
  425. if e.is_Mul:
  426. return prod([_terms(mi) for mi in e.args])
  427. return 1
  428. xnew_base = expand_mul(new_base, deep=False)
  429. if len(Add.make_args(xnew_base)) < _terms(new_base):
  430. new_base = factor_terms(xnew_base)
  431. c_powers[new_base].append(e)
  432. # break out the powers from c_powers now
  433. c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e]
  434. # we're done
  435. return expr.func(*(c_part + nc_part))
  436. else:
  437. raise ValueError("combine must be one of ('all', 'exp', 'base').")
  438. def powdenest(eq, force=False, polar=False):
  439. r"""
  440. Collect exponents on powers as assumptions allow.
  441. Explanation
  442. ===========
  443. Given ``(bb**be)**e``, this can be simplified as follows:
  444. * if ``bb`` is positive, or
  445. * ``e`` is an integer, or
  446. * ``|be| < 1`` then this simplifies to ``bb**(be*e)``
  447. Given a product of powers raised to a power, ``(bb1**be1 *
  448. bb2**be2...)**e``, simplification can be done as follows:
  449. - if e is positive, the gcd of all bei can be joined with e;
  450. - all non-negative bb can be separated from those that are negative
  451. and their gcd can be joined with e; autosimplification already
  452. handles this separation.
  453. - integer factors from powers that have integers in the denominator
  454. of the exponent can be removed from any term and the gcd of such
  455. integers can be joined with e
  456. Setting ``force`` to ``True`` will make symbols that are not explicitly
  457. negative behave as though they are positive, resulting in more
  458. denesting.
  459. Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of
  460. the logarithm, also resulting in more denestings.
  461. When there are sums of logs in exp() then a product of powers may be
  462. obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``.
  463. Examples
  464. ========
  465. >>> from sympy.abc import a, b, x, y, z
  466. >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest
  467. >>> powdenest((x**(2*a/3))**(3*x))
  468. (x**(2*a/3))**(3*x)
  469. >>> powdenest(exp(3*x*log(2)))
  470. 2**(3*x)
  471. Assumptions may prevent expansion:
  472. >>> powdenest(sqrt(x**2))
  473. sqrt(x**2)
  474. >>> p = symbols('p', positive=True)
  475. >>> powdenest(sqrt(p**2))
  476. p
  477. No other expansion is done.
  478. >>> i, j = symbols('i,j', integer=True)
  479. >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j
  480. x**(x*(i + j))
  481. But exp() will be denested by moving all non-log terms outside of
  482. the function; this may result in the collapsing of the exp to a power
  483. with a different base:
  484. >>> powdenest(exp(3*y*log(x)))
  485. x**(3*y)
  486. >>> powdenest(exp(y*(log(a) + log(b))))
  487. (a*b)**y
  488. >>> powdenest(exp(3*(log(a) + log(b))))
  489. a**3*b**3
  490. If assumptions allow, symbols can also be moved to the outermost exponent:
  491. >>> i = Symbol('i', integer=True)
  492. >>> powdenest(((x**(2*i))**(3*y))**x)
  493. ((x**(2*i))**(3*y))**x
  494. >>> powdenest(((x**(2*i))**(3*y))**x, force=True)
  495. x**(6*i*x*y)
  496. >>> powdenest(((x**(2*a/3))**(3*y/i))**x)
  497. ((x**(2*a/3))**(3*y/i))**x
  498. >>> powdenest((x**(2*i)*y**(4*i))**z, force=True)
  499. (x*y**2)**(2*i*z)
  500. >>> n = Symbol('n', negative=True)
  501. >>> powdenest((x**i)**y, force=True)
  502. x**(i*y)
  503. >>> powdenest((n**i)**x, force=True)
  504. (n**i)**x
  505. """
  506. from sympy.simplify.simplify import posify
  507. if force:
  508. def _denest(b, e):
  509. if not isinstance(b, (Pow, exp)):
  510. return b.is_positive, Pow(b, e, evaluate=False)
  511. return _denest(b.base, b.exp*e)
  512. reps = []
  513. for p in eq.atoms(Pow, exp):
  514. if isinstance(p.base, (Pow, exp)):
  515. ok, dp = _denest(*p.args)
  516. if ok is not False:
  517. reps.append((p, dp))
  518. if reps:
  519. eq = eq.subs(reps)
  520. eq, reps = posify(eq)
  521. return powdenest(eq, force=False, polar=polar).xreplace(reps)
  522. if polar:
  523. eq, rep = polarify(eq)
  524. return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep)
  525. new = powsimp(eq)
  526. return new.xreplace(Transform(
  527. _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp)))
  528. _y = Dummy('y')
  529. def _denest_pow(eq):
  530. """
  531. Denest powers.
  532. This is a helper function for powdenest that performs the actual
  533. transformation.
  534. """
  535. from sympy.simplify.simplify import logcombine
  536. b, e = eq.as_base_exp()
  537. if b.is_Pow or isinstance(b, exp) and e != 1:
  538. new = b._eval_power(e)
  539. if new is not None:
  540. eq = new
  541. b, e = new.as_base_exp()
  542. # denest exp with log terms in exponent
  543. if b is S.Exp1 and e.is_Mul:
  544. logs = []
  545. other = []
  546. for ei in e.args:
  547. if any(isinstance(ai, log) for ai in Add.make_args(ei)):
  548. logs.append(ei)
  549. else:
  550. other.append(ei)
  551. logs = logcombine(Mul(*logs))
  552. return Pow(exp(logs), Mul(*other))
  553. _, be = b.as_base_exp()
  554. if be is S.One and not (b.is_Mul or
  555. b.is_Rational and b.q != 1 or
  556. b.is_positive):
  557. return eq
  558. # denest eq which is either pos**e or Pow**e or Mul**e or
  559. # Mul(b1**e1, b2**e2)
  560. # handle polar numbers specially
  561. polars, nonpolars = [], []
  562. for bb in Mul.make_args(b):
  563. if bb.is_polar:
  564. polars.append(bb.as_base_exp())
  565. else:
  566. nonpolars.append(bb)
  567. if len(polars) == 1 and not polars[0][0].is_Mul:
  568. return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e)
  569. elif polars:
  570. return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \
  571. *powdenest(Mul(*nonpolars)**e)
  572. if b.is_Integer:
  573. # use log to see if there is a power here
  574. logb = expand_log(log(b))
  575. if logb.is_Mul:
  576. c, logb = logb.args
  577. e *= c
  578. base = logb.args[0]
  579. return Pow(base, e)
  580. # if b is not a Mul or any factor is an atom then there is nothing to do
  581. if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)):
  582. return eq
  583. # let log handle the case of the base of the argument being a Mul, e.g.
  584. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we
  585. # will take the log, expand it, and then factor out the common powers that
  586. # now appear as coefficient. We do this manually since terms_gcd pulls out
  587. # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2;
  588. # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but
  589. # we want 3*x. Neither work with noncommutatives.
  590. def nc_gcd(aa, bb):
  591. a, b = [i.as_coeff_Mul() for i in [aa, bb]]
  592. c = gcd(a[0], b[0]).as_numer_denom()[0]
  593. g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0]))
  594. return _keep_coeff(c, g)
  595. glogb = expand_log(log(b))
  596. if glogb.is_Add:
  597. args = glogb.args
  598. g = reduce(nc_gcd, args)
  599. if g != 1:
  600. cg, rg = g.as_coeff_Mul()
  601. glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args]))
  602. # now put the log back together again
  603. if isinstance(glogb, log) or not glogb.is_Mul:
  604. if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp):
  605. glogb = _denest_pow(glogb.args[0])
  606. if (abs(glogb.exp) < 1) == True:
  607. return Pow(glogb.base, glogb.exp*e)
  608. return eq
  609. # the log(b) was a Mul so join any adds with logcombine
  610. add = []
  611. other = []
  612. for a in glogb.args:
  613. if a.is_Add:
  614. add.append(a)
  615. else:
  616. other.append(a)
  617. return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))