powsimp.py 26 KB

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