powsimp.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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
  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. if b != binv and binv in c_powers:
  159. if b.as_numer_denom()[0] is S.One:
  160. c_powers.pop(b)
  161. c_powers[binv] -= e
  162. else:
  163. skip.add(binv)
  164. e = c_powers.pop(binv)
  165. c_powers[b] -= e
  166. # check for base and negated base pairs
  167. be = list(c_powers.items())
  168. _n = S.NegativeOne
  169. for b, e in be:
  170. if (b.is_Symbol or b.is_Add) and -b in c_powers and b in c_powers:
  171. if (b.is_positive is not None or e.is_integer):
  172. if e.is_integer or b.is_negative:
  173. c_powers[-b] += c_powers.pop(b)
  174. else: # (-b).is_positive so use its e
  175. e = c_powers.pop(-b)
  176. c_powers[b] += e
  177. if _n in c_powers:
  178. c_powers[_n] += e
  179. else:
  180. c_powers[_n] = e
  181. # filter c_powers and convert to a list
  182. c_powers = [(b, e) for b, e in c_powers.items() if e]
  183. # ==============================================================
  184. # check for Mul bases of Rational powers that can be combined with
  185. # separated bases, e.g. x*sqrt(x*y)*sqrt(x*sqrt(x*y)) ->
  186. # (x*sqrt(x*y))**(3/2)
  187. # ---------------- helper functions
  188. def ratq(x):
  189. '''Return Rational part of x's exponent as it appears in the bkey.
  190. '''
  191. return bkey(x)[0][1]
  192. def bkey(b, e=None):
  193. '''Return (b**s, c.q), c.p where e -> c*s. If e is not given then
  194. it will be taken by using as_base_exp() on the input b.
  195. e.g.
  196. x**3/2 -> (x, 2), 3
  197. x**y -> (x**y, 1), 1
  198. x**(2*y/3) -> (x**y, 3), 2
  199. exp(x/2) -> (exp(a), 2), 1
  200. '''
  201. if e is not None: # coming from c_powers or from below
  202. if e.is_Integer:
  203. return (b, S.One), e
  204. elif e.is_Rational:
  205. return (b, Integer(e.q)), Integer(e.p)
  206. else:
  207. c, m = e.as_coeff_Mul(rational=True)
  208. if c is not S.One:
  209. if m.is_integer:
  210. return (b, Integer(c.q)), m*Integer(c.p)
  211. return (b**m, Integer(c.q)), Integer(c.p)
  212. else:
  213. return (b**e, S.One), S.One
  214. else:
  215. return bkey(*b.as_base_exp())
  216. def update(b):
  217. '''Decide what to do with base, b. If its exponent is now an
  218. integer multiple of the Rational denominator, then remove it
  219. and put the factors of its base in the common_b dictionary or
  220. update the existing bases if necessary. If it has been zeroed
  221. out, simply remove the base.
  222. '''
  223. newe, r = divmod(common_b[b], b[1])
  224. if not r:
  225. common_b.pop(b)
  226. if newe:
  227. for m in Mul.make_args(b[0]**newe):
  228. b, e = bkey(m)
  229. if b not in common_b:
  230. common_b[b] = 0
  231. common_b[b] += e
  232. if b[1] != 1:
  233. bases.append(b)
  234. # ---------------- end of helper functions
  235. # assemble a dictionary of the factors having a Rational power
  236. common_b = {}
  237. done = []
  238. bases = []
  239. for b, e in c_powers:
  240. b, e = bkey(b, e)
  241. if b in common_b:
  242. common_b[b] = common_b[b] + e
  243. else:
  244. common_b[b] = e
  245. if b[1] != 1 and b[0].is_Mul:
  246. bases.append(b)
  247. bases.sort(key=default_sort_key) # this makes tie-breaking canonical
  248. bases.sort(key=measure, reverse=True) # handle longest first
  249. for base in bases:
  250. if base not in common_b: # it may have been removed already
  251. continue
  252. b, exponent = base
  253. last = False # True when no factor of base is a radical
  254. qlcm = 1 # the lcm of the radical denominators
  255. while True:
  256. bstart = b
  257. qstart = qlcm
  258. bb = [] # list of factors
  259. ee = [] # (factor's expo. and it's current value in common_b)
  260. for bi in Mul.make_args(b):
  261. bib, bie = bkey(bi)
  262. if bib not in common_b or common_b[bib] < bie:
  263. ee = bb = [] # failed
  264. break
  265. ee.append([bie, common_b[bib]])
  266. bb.append(bib)
  267. if ee:
  268. # find the number of integral extractions possible
  269. # e.g. [(1, 2), (2, 2)] -> min(2/1, 2/2) -> 1
  270. min1 = ee[0][1]//ee[0][0]
  271. for i in range(1, len(ee)):
  272. rat = ee[i][1]//ee[i][0]
  273. if rat < 1:
  274. break
  275. min1 = min(min1, rat)
  276. else:
  277. # update base factor counts
  278. # e.g. if ee = [(2, 5), (3, 6)] then min1 = 2
  279. # and the new base counts will be 5-2*2 and 6-2*3
  280. for i in range(len(bb)):
  281. common_b[bb[i]] -= min1*ee[i][0]
  282. update(bb[i])
  283. # update the count of the base
  284. # e.g. x**2*y*sqrt(x*sqrt(y)) the count of x*sqrt(y)
  285. # will increase by 4 to give bkey (x*sqrt(y), 2, 5)
  286. common_b[base] += min1*qstart*exponent
  287. if (last # no more radicals in base
  288. or len(common_b) == 1 # nothing left to join with
  289. or all(k[1] == 1 for k in common_b) # no rad's in common_b
  290. ):
  291. break
  292. # see what we can exponentiate base by to remove any radicals
  293. # so we know what to search for
  294. # e.g. if base were x**(1/2)*y**(1/3) then we should
  295. # exponentiate by 6 and look for powers of x and y in the ratio
  296. # of 2 to 3
  297. qlcm = lcm([ratq(bi) for bi in Mul.make_args(bstart)])
  298. if qlcm == 1:
  299. break # we are done
  300. b = bstart**qlcm
  301. qlcm *= qstart
  302. if all(ratq(bi) == 1 for bi in Mul.make_args(b)):
  303. last = True # we are going to be done after this next pass
  304. # this base no longer can find anything to join with and
  305. # since it was longer than any other we are done with it
  306. b, q = base
  307. done.append((b, common_b.pop(base)*Rational(1, q)))
  308. # update c_powers and get ready to continue with powsimp
  309. c_powers = done
  310. # there may be terms still in common_b that were bases that were
  311. # identified as needing processing, so remove those, too
  312. for (b, q), e in common_b.items():
  313. if (b.is_Pow or isinstance(b, exp)) and \
  314. q is not S.One and not b.exp.is_Rational:
  315. b, be = b.as_base_exp()
  316. b = b**(be/q)
  317. else:
  318. b = root(b, q)
  319. c_powers.append((b, e))
  320. check = len(c_powers)
  321. c_powers = dict(c_powers)
  322. assert len(c_powers) == check # there should have been no duplicates
  323. # ==============================================================
  324. # rebuild the expression
  325. newexpr = expr.func(*(newexpr + [Pow(b, e) for b, e in c_powers.items()]))
  326. if combine == 'exp':
  327. return expr.func(newexpr, expr.func(*nc_part))
  328. else:
  329. return recurse(expr.func(*nc_part), combine='base') * \
  330. recurse(newexpr, combine='base')
  331. elif combine == 'base':
  332. # Build c_powers and nc_part. These must both be lists not
  333. # dicts because exp's are not combined.
  334. c_powers = []
  335. nc_part = []
  336. for term in expr.args:
  337. if term.is_commutative:
  338. c_powers.append(list(term.as_base_exp()))
  339. else:
  340. nc_part.append(term)
  341. # Pull out numerical coefficients from exponent if assumptions allow
  342. # e.g., 2**(2*x) => 4**x
  343. for i in range(len(c_powers)):
  344. b, e = c_powers[i]
  345. if not (all(x.is_nonnegative for x in b.as_numer_denom()) or e.is_integer or force or b.is_polar):
  346. continue
  347. exp_c, exp_t = e.as_coeff_Mul(rational=True)
  348. if exp_c is not S.One and exp_t is not S.One:
  349. c_powers[i] = [Pow(b, exp_c), exp_t]
  350. # Combine bases whenever they have the same exponent and
  351. # assumptions allow
  352. # first gather the potential bases under the common exponent
  353. c_exp = defaultdict(list)
  354. for b, e in c_powers:
  355. if deep:
  356. e = recurse(e)
  357. if e.is_Add and (b.is_positive or e.is_integer):
  358. e = factor_terms(e)
  359. if _coeff_isneg(e):
  360. e = -e
  361. b = 1/b
  362. c_exp[e].append(b)
  363. del c_powers
  364. # Merge back in the results of the above to form a new product
  365. c_powers = defaultdict(list)
  366. for e in c_exp:
  367. bases = c_exp[e]
  368. # calculate the new base for e
  369. if len(bases) == 1:
  370. new_base = bases[0]
  371. elif e.is_integer or force:
  372. new_base = expr.func(*bases)
  373. else:
  374. # see which ones can be joined
  375. unk = []
  376. nonneg = []
  377. neg = []
  378. for bi in bases:
  379. if bi.is_negative:
  380. neg.append(bi)
  381. elif bi.is_nonnegative:
  382. nonneg.append(bi)
  383. elif bi.is_polar:
  384. nonneg.append(
  385. bi) # polar can be treated like non-negative
  386. else:
  387. unk.append(bi)
  388. if len(unk) == 1 and not neg or len(neg) == 1 and not unk:
  389. # a single neg or a single unk can join the rest
  390. nonneg.extend(unk + neg)
  391. unk = neg = []
  392. elif neg:
  393. # their negative signs cancel in groups of 2*q if we know
  394. # that e = p/q else we have to treat them as unknown
  395. israt = False
  396. if e.is_Rational:
  397. israt = True
  398. else:
  399. p, d = e.as_numer_denom()
  400. if p.is_integer and d.is_integer:
  401. israt = True
  402. if israt:
  403. neg = [-w for w in neg]
  404. unk.extend([S.NegativeOne]*len(neg))
  405. else:
  406. unk.extend(neg)
  407. neg = []
  408. del israt
  409. # these shouldn't be joined
  410. for b in unk:
  411. c_powers[b].append(e)
  412. # here is a new joined base
  413. new_base = expr.func(*(nonneg + neg))
  414. # if there are positive parts they will just get separated
  415. # again unless some change is made
  416. def _terms(e):
  417. # return the number of terms of this expression
  418. # when multiplied out -- assuming no joining of terms
  419. if e.is_Add:
  420. return sum([_terms(ai) for ai in e.args])
  421. if e.is_Mul:
  422. return prod([_terms(mi) for mi in e.args])
  423. return 1
  424. xnew_base = expand_mul(new_base, deep=False)
  425. if len(Add.make_args(xnew_base)) < _terms(new_base):
  426. new_base = factor_terms(xnew_base)
  427. c_powers[new_base].append(e)
  428. # break out the powers from c_powers now
  429. c_part = [Pow(b, ei) for b, e in c_powers.items() for ei in e]
  430. # we're done
  431. return expr.func(*(c_part + nc_part))
  432. else:
  433. raise ValueError("combine must be one of ('all', 'exp', 'base').")
  434. def powdenest(eq, force=False, polar=False):
  435. r"""
  436. Collect exponents on powers as assumptions allow.
  437. Explanation
  438. ===========
  439. Given ``(bb**be)**e``, this can be simplified as follows:
  440. * if ``bb`` is positive, or
  441. * ``e`` is an integer, or
  442. * ``|be| < 1`` then this simplifies to ``bb**(be*e)``
  443. Given a product of powers raised to a power, ``(bb1**be1 *
  444. bb2**be2...)**e``, simplification can be done as follows:
  445. - if e is positive, the gcd of all bei can be joined with e;
  446. - all non-negative bb can be separated from those that are negative
  447. and their gcd can be joined with e; autosimplification already
  448. handles this separation.
  449. - integer factors from powers that have integers in the denominator
  450. of the exponent can be removed from any term and the gcd of such
  451. integers can be joined with e
  452. Setting ``force`` to ``True`` will make symbols that are not explicitly
  453. negative behave as though they are positive, resulting in more
  454. denesting.
  455. Setting ``polar`` to ``True`` will do simplifications on the Riemann surface of
  456. the logarithm, also resulting in more denestings.
  457. When there are sums of logs in exp() then a product of powers may be
  458. obtained e.g. ``exp(3*(log(a) + 2*log(b)))`` - > ``a**3*b**6``.
  459. Examples
  460. ========
  461. >>> from sympy.abc import a, b, x, y, z
  462. >>> from sympy import Symbol, exp, log, sqrt, symbols, powdenest
  463. >>> powdenest((x**(2*a/3))**(3*x))
  464. (x**(2*a/3))**(3*x)
  465. >>> powdenest(exp(3*x*log(2)))
  466. 2**(3*x)
  467. Assumptions may prevent expansion:
  468. >>> powdenest(sqrt(x**2))
  469. sqrt(x**2)
  470. >>> p = symbols('p', positive=True)
  471. >>> powdenest(sqrt(p**2))
  472. p
  473. No other expansion is done.
  474. >>> i, j = symbols('i,j', integer=True)
  475. >>> powdenest((x**x)**(i + j)) # -X-> (x**x)**i*(x**x)**j
  476. x**(x*(i + j))
  477. But exp() will be denested by moving all non-log terms outside of
  478. the function; this may result in the collapsing of the exp to a power
  479. with a different base:
  480. >>> powdenest(exp(3*y*log(x)))
  481. x**(3*y)
  482. >>> powdenest(exp(y*(log(a) + log(b))))
  483. (a*b)**y
  484. >>> powdenest(exp(3*(log(a) + log(b))))
  485. a**3*b**3
  486. If assumptions allow, symbols can also be moved to the outermost exponent:
  487. >>> i = Symbol('i', integer=True)
  488. >>> powdenest(((x**(2*i))**(3*y))**x)
  489. ((x**(2*i))**(3*y))**x
  490. >>> powdenest(((x**(2*i))**(3*y))**x, force=True)
  491. x**(6*i*x*y)
  492. >>> powdenest(((x**(2*a/3))**(3*y/i))**x)
  493. ((x**(2*a/3))**(3*y/i))**x
  494. >>> powdenest((x**(2*i)*y**(4*i))**z, force=True)
  495. (x*y**2)**(2*i*z)
  496. >>> n = Symbol('n', negative=True)
  497. >>> powdenest((x**i)**y, force=True)
  498. x**(i*y)
  499. >>> powdenest((n**i)**x, force=True)
  500. (n**i)**x
  501. """
  502. from sympy.simplify.simplify import posify
  503. if force:
  504. def _denest(b, e):
  505. if not isinstance(b, (Pow, exp)):
  506. return b.is_positive, Pow(b, e, evaluate=False)
  507. return _denest(b.base, b.exp*e)
  508. reps = []
  509. for p in eq.atoms(Pow, exp):
  510. if isinstance(p.base, (Pow, exp)):
  511. ok, dp = _denest(*p.args)
  512. if ok is not False:
  513. reps.append((p, dp))
  514. if reps:
  515. eq = eq.subs(reps)
  516. eq, reps = posify(eq)
  517. return powdenest(eq, force=False, polar=polar).xreplace(reps)
  518. if polar:
  519. eq, rep = polarify(eq)
  520. return unpolarify(powdenest(unpolarify(eq, exponents_only=True)), rep)
  521. new = powsimp(eq)
  522. return new.xreplace(Transform(
  523. _denest_pow, filter=lambda m: m.is_Pow or isinstance(m, exp)))
  524. _y = Dummy('y')
  525. def _denest_pow(eq):
  526. """
  527. Denest powers.
  528. This is a helper function for powdenest that performs the actual
  529. transformation.
  530. """
  531. from sympy.simplify.simplify import logcombine
  532. b, e = eq.as_base_exp()
  533. if b.is_Pow or isinstance(b, exp) and e != 1:
  534. new = b._eval_power(e)
  535. if new is not None:
  536. eq = new
  537. b, e = new.as_base_exp()
  538. # denest exp with log terms in exponent
  539. if b is S.Exp1 and e.is_Mul:
  540. logs = []
  541. other = []
  542. for ei in e.args:
  543. if any(isinstance(ai, log) for ai in Add.make_args(ei)):
  544. logs.append(ei)
  545. else:
  546. other.append(ei)
  547. logs = logcombine(Mul(*logs))
  548. return Pow(exp(logs), Mul(*other))
  549. _, be = b.as_base_exp()
  550. if be is S.One and not (b.is_Mul or
  551. b.is_Rational and b.q != 1 or
  552. b.is_positive):
  553. return eq
  554. # denest eq which is either pos**e or Pow**e or Mul**e or
  555. # Mul(b1**e1, b2**e2)
  556. # handle polar numbers specially
  557. polars, nonpolars = [], []
  558. for bb in Mul.make_args(b):
  559. if bb.is_polar:
  560. polars.append(bb.as_base_exp())
  561. else:
  562. nonpolars.append(bb)
  563. if len(polars) == 1 and not polars[0][0].is_Mul:
  564. return Pow(polars[0][0], polars[0][1]*e)*powdenest(Mul(*nonpolars)**e)
  565. elif polars:
  566. return Mul(*[powdenest(bb**(ee*e)) for (bb, ee) in polars]) \
  567. *powdenest(Mul(*nonpolars)**e)
  568. if b.is_Integer:
  569. # use log to see if there is a power here
  570. logb = expand_log(log(b))
  571. if logb.is_Mul:
  572. c, logb = logb.args
  573. e *= c
  574. base = logb.args[0]
  575. return Pow(base, e)
  576. # if b is not a Mul or any factor is an atom then there is nothing to do
  577. if not b.is_Mul or any(s.is_Atom for s in Mul.make_args(b)):
  578. return eq
  579. # let log handle the case of the base of the argument being a Mul, e.g.
  580. # sqrt(x**(2*i)*y**(6*i)) -> x**i*y**(3**i) if x and y are positive; we
  581. # will take the log, expand it, and then factor out the common powers that
  582. # now appear as coefficient. We do this manually since terms_gcd pulls out
  583. # fractions, terms_gcd(x+x*y/2) -> x*(y + 2)/2 and we don't want the 1/2;
  584. # gcd won't pull out numerators from a fraction: gcd(3*x, 9*x/2) -> x but
  585. # we want 3*x. Neither work with noncommutatives.
  586. def nc_gcd(aa, bb):
  587. a, b = [i.as_coeff_Mul() for i in [aa, bb]]
  588. c = gcd(a[0], b[0]).as_numer_denom()[0]
  589. g = Mul(*(a[1].args_cnc(cset=True)[0] & b[1].args_cnc(cset=True)[0]))
  590. return _keep_coeff(c, g)
  591. glogb = expand_log(log(b))
  592. if glogb.is_Add:
  593. args = glogb.args
  594. g = reduce(nc_gcd, args)
  595. if g != 1:
  596. cg, rg = g.as_coeff_Mul()
  597. glogb = _keep_coeff(cg, rg*Add(*[a/g for a in args]))
  598. # now put the log back together again
  599. if isinstance(glogb, log) or not glogb.is_Mul:
  600. if glogb.args[0].is_Pow or isinstance(glogb.args[0], exp):
  601. glogb = _denest_pow(glogb.args[0])
  602. if (abs(glogb.exp) < 1) == True:
  603. return Pow(glogb.base, glogb.exp*e)
  604. return eq
  605. # the log(b) was a Mul so join any adds with logcombine
  606. add = []
  607. other = []
  608. for a in glogb.args:
  609. if a.is_Add:
  610. add.append(a)
  611. else:
  612. other.append(a)
  613. return Pow(exp(logcombine(Mul(*add))), e*Mul(*other))