m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2182 lines
75 KiB

6 months ago
  1. from typing import Tuple as tTuple
  2. from collections import defaultdict
  3. from functools import cmp_to_key, reduce
  4. from itertools import product
  5. import operator
  6. from .sympify import sympify
  7. from .basic import Basic
  8. from .singleton import S
  9. from .operations import AssocOp, AssocOpDispatcher
  10. from .cache import cacheit
  11. from .logic import fuzzy_not, _fuzzy_group
  12. from .expr import Expr
  13. from .parameters import global_parameters
  14. from .kind import KindDispatcher
  15. from .traversal import bottom_up
  16. from sympy.utilities.iterables import sift
  17. # internal marker to indicate:
  18. # "there are still non-commutative objects -- don't forget to process them"
  19. class NC_Marker:
  20. is_Order = False
  21. is_Mul = False
  22. is_Number = False
  23. is_Poly = False
  24. is_commutative = False
  25. # Key for sorting commutative args in canonical order
  26. _args_sortkey = cmp_to_key(Basic.compare)
  27. def _mulsort(args):
  28. # in-place sorting of args
  29. args.sort(key=_args_sortkey)
  30. def _unevaluated_Mul(*args):
  31. """Return a well-formed unevaluated Mul: Numbers are collected and
  32. put in slot 0, any arguments that are Muls will be flattened, and args
  33. are sorted. Use this when args have changed but you still want to return
  34. an unevaluated Mul.
  35. Examples
  36. ========
  37. >>> from sympy.core.mul import _unevaluated_Mul as uMul
  38. >>> from sympy import S, sqrt, Mul
  39. >>> from sympy.abc import x
  40. >>> a = uMul(*[S(3.0), x, S(2)])
  41. >>> a.args[0]
  42. 6.00000000000000
  43. >>> a.args[1]
  44. x
  45. Two unevaluated Muls with the same arguments will
  46. always compare as equal during testing:
  47. >>> m = uMul(sqrt(2), sqrt(3))
  48. >>> m == uMul(sqrt(3), sqrt(2))
  49. True
  50. >>> u = Mul(sqrt(3), sqrt(2), evaluate=False)
  51. >>> m == uMul(u)
  52. True
  53. >>> m == Mul(*m.args)
  54. False
  55. """
  56. args = list(args)
  57. newargs = []
  58. ncargs = []
  59. co = S.One
  60. while args:
  61. a = args.pop()
  62. if a.is_Mul:
  63. c, nc = a.args_cnc()
  64. args.extend(c)
  65. if nc:
  66. ncargs.append(Mul._from_args(nc))
  67. elif a.is_Number:
  68. co *= a
  69. else:
  70. newargs.append(a)
  71. _mulsort(newargs)
  72. if co is not S.One:
  73. newargs.insert(0, co)
  74. if ncargs:
  75. newargs.append(Mul._from_args(ncargs))
  76. return Mul._from_args(newargs)
  77. class Mul(Expr, AssocOp):
  78. """
  79. Expression representing multiplication operation for algebraic field.
  80. .. deprecated:: 1.7
  81. Using arguments that aren't subclasses of :class:`~.Expr` in core
  82. operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
  83. deprecated. See :ref:`non-expr-args-deprecated` for details.
  84. Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*``
  85. on most scalar objects in SymPy calls this class.
  86. Another use of ``Mul()`` is to represent the structure of abstract
  87. multiplication so that its arguments can be substituted to return
  88. different class. Refer to examples section for this.
  89. ``Mul()`` evaluates the argument unless ``evaluate=False`` is passed.
  90. The evaluation logic includes:
  91. 1. Flattening
  92. ``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)``
  93. 2. Identity removing
  94. ``Mul(x, 1, y)`` -> ``Mul(x, y)``
  95. 3. Exponent collecting by ``.as_base_exp()``
  96. ``Mul(x, x**2)`` -> ``Pow(x, 3)``
  97. 4. Term sorting
  98. ``Mul(y, x, 2)`` -> ``Mul(2, x, y)``
  99. Since multiplication can be vector space operation, arguments may
  100. have the different :obj:`sympy.core.kind.Kind()`. Kind of the
  101. resulting object is automatically inferred.
  102. Examples
  103. ========
  104. >>> from sympy import Mul
  105. >>> from sympy.abc import x, y
  106. >>> Mul(x, 1)
  107. x
  108. >>> Mul(x, x)
  109. x**2
  110. If ``evaluate=False`` is passed, result is not evaluated.
  111. >>> Mul(1, 2, evaluate=False)
  112. 1*2
  113. >>> Mul(x, x, evaluate=False)
  114. x*x
  115. ``Mul()`` also represents the general structure of multiplication
  116. operation.
  117. >>> from sympy import MatrixSymbol
  118. >>> A = MatrixSymbol('A', 2,2)
  119. >>> expr = Mul(x,y).subs({y:A})
  120. >>> expr
  121. x*A
  122. >>> type(expr)
  123. <class 'sympy.matrices.expressions.matmul.MatMul'>
  124. See Also
  125. ========
  126. MatMul
  127. """
  128. __slots__ = ()
  129. args: tTuple[Expr]
  130. is_Mul = True
  131. _args_type = Expr
  132. _kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True)
  133. @property
  134. def kind(self):
  135. arg_kinds = (a.kind for a in self.args)
  136. return self._kind_dispatcher(*arg_kinds)
  137. def could_extract_minus_sign(self):
  138. if self == (-self):
  139. return False # e.g. zoo*x == -zoo*x
  140. c = self.args[0]
  141. return c.is_Number and c.is_extended_negative
  142. def __neg__(self):
  143. c, args = self.as_coeff_mul()
  144. if args[0] is not S.ComplexInfinity:
  145. c = -c
  146. if c is not S.One:
  147. if args[0].is_Number:
  148. args = list(args)
  149. if c is S.NegativeOne:
  150. args[0] = -args[0]
  151. else:
  152. args[0] *= c
  153. else:
  154. args = (c,) + args
  155. return self._from_args(args, self.is_commutative)
  156. @classmethod
  157. def flatten(cls, seq):
  158. """Return commutative, noncommutative and order arguments by
  159. combining related terms.
  160. Notes
  161. =====
  162. * In an expression like ``a*b*c``, Python process this through SymPy
  163. as ``Mul(Mul(a, b), c)``. This can have undesirable consequences.
  164. - Sometimes terms are not combined as one would like:
  165. {c.f. https://github.com/sympy/sympy/issues/4596}
  166. >>> from sympy import Mul, sqrt
  167. >>> from sympy.abc import x, y, z
  168. >>> 2*(x + 1) # this is the 2-arg Mul behavior
  169. 2*x + 2
  170. >>> y*(x + 1)*2
  171. 2*y*(x + 1)
  172. >>> 2*(x + 1)*y # 2-arg result will be obtained first
  173. y*(2*x + 2)
  174. >>> Mul(2, x + 1, y) # all 3 args simultaneously processed
  175. 2*y*(x + 1)
  176. >>> 2*((x + 1)*y) # parentheses can control this behavior
  177. 2*y*(x + 1)
  178. Powers with compound bases may not find a single base to
  179. combine with unless all arguments are processed at once.
  180. Post-processing may be necessary in such cases.
  181. {c.f. https://github.com/sympy/sympy/issues/5728}
  182. >>> a = sqrt(x*sqrt(y))
  183. >>> a**3
  184. (x*sqrt(y))**(3/2)
  185. >>> Mul(a,a,a)
  186. (x*sqrt(y))**(3/2)
  187. >>> a*a*a
  188. x*sqrt(y)*sqrt(x*sqrt(y))
  189. >>> _.subs(a.base, z).subs(z, a.base)
  190. (x*sqrt(y))**(3/2)
  191. - If more than two terms are being multiplied then all the
  192. previous terms will be re-processed for each new argument.
  193. So if each of ``a``, ``b`` and ``c`` were :class:`Mul`
  194. expression, then ``a*b*c`` (or building up the product
  195. with ``*=``) will process all the arguments of ``a`` and
  196. ``b`` twice: once when ``a*b`` is computed and again when
  197. ``c`` is multiplied.
  198. Using ``Mul(a, b, c)`` will process all arguments once.
  199. * The results of Mul are cached according to arguments, so flatten
  200. will only be called once for ``Mul(a, b, c)``. If you can
  201. structure a calculation so the arguments are most likely to be
  202. repeats then this can save time in computing the answer. For
  203. example, say you had a Mul, M, that you wished to divide by ``d[i]``
  204. and multiply by ``n[i]`` and you suspect there are many repeats
  205. in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather
  206. than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the
  207. product, ``M*n[i]`` will be returned without flattening -- the
  208. cached value will be returned. If you divide by the ``d[i]``
  209. first (and those are more unique than the ``n[i]``) then that will
  210. create a new Mul, ``M/d[i]`` the args of which will be traversed
  211. again when it is multiplied by ``n[i]``.
  212. {c.f. https://github.com/sympy/sympy/issues/5706}
  213. This consideration is moot if the cache is turned off.
  214. NB
  215. --
  216. The validity of the above notes depends on the implementation
  217. details of Mul and flatten which may change at any time. Therefore,
  218. you should only consider them when your code is highly performance
  219. sensitive.
  220. Removal of 1 from the sequence is already handled by AssocOp.__new__.
  221. """
  222. from sympy.calculus.accumulationbounds import AccumBounds
  223. from sympy.matrices.expressions import MatrixExpr
  224. rv = None
  225. if len(seq) == 2:
  226. a, b = seq
  227. if b.is_Rational:
  228. a, b = b, a
  229. seq = [a, b]
  230. assert a is not S.One
  231. if not a.is_zero and a.is_Rational:
  232. r, b = b.as_coeff_Mul()
  233. if b.is_Add:
  234. if r is not S.One: # 2-arg hack
  235. # leave the Mul as a Mul?
  236. ar = a*r
  237. if ar is S.One:
  238. arb = b
  239. else:
  240. arb = cls(a*r, b, evaluate=False)
  241. rv = [arb], [], None
  242. elif global_parameters.distribute and b.is_commutative:
  243. newb = Add(*[_keep_coeff(a, bi) for bi in b.args])
  244. rv = [newb], [], None
  245. if rv:
  246. return rv
  247. # apply associativity, separate commutative part of seq
  248. c_part = [] # out: commutative factors
  249. nc_part = [] # out: non-commutative factors
  250. nc_seq = []
  251. coeff = S.One # standalone term
  252. # e.g. 3 * ...
  253. c_powers = [] # (base,exp) n
  254. # e.g. (x,n) for x
  255. num_exp = [] # (num-base, exp) y
  256. # e.g. (3, y) for ... * 3 * ...
  257. neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I
  258. pnum_rat = {} # (num-base, Rat-exp) 1/2
  259. # e.g. (3, 1/2) for ... * 3 * ...
  260. order_symbols = None
  261. # --- PART 1 ---
  262. #
  263. # "collect powers and coeff":
  264. #
  265. # o coeff
  266. # o c_powers
  267. # o num_exp
  268. # o neg1e
  269. # o pnum_rat
  270. #
  271. # NOTE: this is optimized for all-objects-are-commutative case
  272. for o in seq:
  273. # O(x)
  274. if o.is_Order:
  275. o, order_symbols = o.as_expr_variables(order_symbols)
  276. # Mul([...])
  277. if o.is_Mul:
  278. if o.is_commutative:
  279. seq.extend(o.args) # XXX zerocopy?
  280. else:
  281. # NCMul can have commutative parts as well
  282. for q in o.args:
  283. if q.is_commutative:
  284. seq.append(q)
  285. else:
  286. nc_seq.append(q)
  287. # append non-commutative marker, so we don't forget to
  288. # process scheduled non-commutative objects
  289. seq.append(NC_Marker)
  290. continue
  291. # 3
  292. elif o.is_Number:
  293. if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero:
  294. # we know for sure the result will be nan
  295. return [S.NaN], [], None
  296. elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo
  297. coeff *= o
  298. if coeff is S.NaN:
  299. # we know for sure the result will be nan
  300. return [S.NaN], [], None
  301. continue
  302. elif isinstance(o, AccumBounds):
  303. coeff = o.__mul__(coeff)
  304. continue
  305. elif o is S.ComplexInfinity:
  306. if not coeff:
  307. # 0 * zoo = NaN
  308. return [S.NaN], [], None
  309. coeff = S.ComplexInfinity
  310. continue
  311. elif o is S.ImaginaryUnit:
  312. neg1e += S.Half
  313. continue
  314. elif o.is_commutative:
  315. # e
  316. # o = b
  317. b, e = o.as_base_exp()
  318. # y
  319. # 3
  320. if o.is_Pow:
  321. if b.is_Number:
  322. # get all the factors with numeric base so they can be
  323. # combined below, but don't combine negatives unless
  324. # the exponent is an integer
  325. if e.is_Rational:
  326. if e.is_Integer:
  327. coeff *= Pow(b, e) # it is an unevaluated power
  328. continue
  329. elif e.is_negative: # also a sign of an unevaluated power
  330. seq.append(Pow(b, e))
  331. continue
  332. elif b.is_negative:
  333. neg1e += e
  334. b = -b
  335. if b is not S.One:
  336. pnum_rat.setdefault(b, []).append(e)
  337. continue
  338. elif b.is_positive or e.is_integer:
  339. num_exp.append((b, e))
  340. continue
  341. c_powers.append((b, e))
  342. # NON-COMMUTATIVE
  343. # TODO: Make non-commutative exponents not combine automatically
  344. else:
  345. if o is not NC_Marker:
  346. nc_seq.append(o)
  347. # process nc_seq (if any)
  348. while nc_seq:
  349. o = nc_seq.pop(0)
  350. if not nc_part:
  351. nc_part.append(o)
  352. continue
  353. # b c b+c
  354. # try to combine last terms: a * a -> a
  355. o1 = nc_part.pop()
  356. b1, e1 = o1.as_base_exp()
  357. b2, e2 = o.as_base_exp()
  358. new_exp = e1 + e2
  359. # Only allow powers to combine if the new exponent is
  360. # not an Add. This allow things like a**2*b**3 == a**5
  361. # if a.is_commutative == False, but prohibits
  362. # a**x*a**y and x**a*x**b from combining (x,y commute).
  363. if b1 == b2 and (not new_exp.is_Add):
  364. o12 = b1 ** new_exp
  365. # now o12 could be a commutative object
  366. if o12.is_commutative:
  367. seq.append(o12)
  368. continue
  369. else:
  370. nc_seq.insert(0, o12)
  371. else:
  372. nc_part.append(o1)
  373. nc_part.append(o)
  374. # We do want a combined exponent if it would not be an Add, such as
  375. # y 2y 3y
  376. # x * x -> x
  377. # We determine if two exponents have the same term by using
  378. # as_coeff_Mul.
  379. #
  380. # Unfortunately, this isn't smart enough to consider combining into
  381. # exponents that might already be adds, so things like:
  382. # z - y y
  383. # x * x will be left alone. This is because checking every possible
  384. # combination can slow things down.
  385. # gather exponents of common bases...
  386. def _gather(c_powers):
  387. common_b = {} # b:e
  388. for b, e in c_powers:
  389. co = e.as_coeff_Mul()
  390. common_b.setdefault(b, {}).setdefault(
  391. co[1], []).append(co[0])
  392. for b, d in common_b.items():
  393. for di, li in d.items():
  394. d[di] = Add(*li)
  395. new_c_powers = []
  396. for b, e in common_b.items():
  397. new_c_powers.extend([(b, c*t) for t, c in e.items()])
  398. return new_c_powers
  399. # in c_powers
  400. c_powers = _gather(c_powers)
  401. # and in num_exp
  402. num_exp = _gather(num_exp)
  403. # --- PART 2 ---
  404. #
  405. # o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow)
  406. # o combine collected powers (2**x * 3**x -> 6**x)
  407. # with numeric base
  408. # ................................
  409. # now we have:
  410. # - coeff:
  411. # - c_powers: (b, e)
  412. # - num_exp: (2, e)
  413. # - pnum_rat: {(1/3, [1/3, 2/3, 1/4])}
  414. # 0 1
  415. # x -> 1 x -> x
  416. # this should only need to run twice; if it fails because
  417. # it needs to be run more times, perhaps this should be
  418. # changed to a "while True" loop -- the only reason it
  419. # isn't such now is to allow a less-than-perfect result to
  420. # be obtained rather than raising an error or entering an
  421. # infinite loop
  422. for i in range(2):
  423. new_c_powers = []
  424. changed = False
  425. for b, e in c_powers:
  426. if e.is_zero:
  427. # canceling out infinities yields NaN
  428. if (b.is_Add or b.is_Mul) and any(infty in b.args
  429. for infty in (S.ComplexInfinity, S.Infinity,
  430. S.NegativeInfinity)):
  431. return [S.NaN], [], None
  432. continue
  433. if e is S.One:
  434. if b.is_Number:
  435. coeff *= b
  436. continue
  437. p = b
  438. if e is not S.One:
  439. p = Pow(b, e)
  440. # check to make sure that the base doesn't change
  441. # after exponentiation; to allow for unevaluated
  442. # Pow, we only do so if b is not already a Pow
  443. if p.is_Pow and not b.is_Pow:
  444. bi = b
  445. b, e = p.as_base_exp()
  446. if b != bi:
  447. changed = True
  448. c_part.append(p)
  449. new_c_powers.append((b, e))
  450. # there might have been a change, but unless the base
  451. # matches some other base, there is nothing to do
  452. if changed and len({
  453. b for b, e in new_c_powers}) != len(new_c_powers):
  454. # start over again
  455. c_part = []
  456. c_powers = _gather(new_c_powers)
  457. else:
  458. break
  459. # x x x
  460. # 2 * 3 -> 6
  461. inv_exp_dict = {} # exp:Mul(num-bases) x x
  462. # e.g. x:6 for ... * 2 * 3 * ...
  463. for b, e in num_exp:
  464. inv_exp_dict.setdefault(e, []).append(b)
  465. for e, b in inv_exp_dict.items():
  466. inv_exp_dict[e] = cls(*b)
  467. c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e])
  468. # b, e -> e' = sum(e), b
  469. # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
  470. comb_e = {}
  471. for b, e in pnum_rat.items():
  472. comb_e.setdefault(Add(*e), []).append(b)
  473. del pnum_rat
  474. # process them, reducing exponents to values less than 1
  475. # and updating coeff if necessary else adding them to
  476. # num_rat for further processing
  477. num_rat = []
  478. for e, b in comb_e.items():
  479. b = cls(*b)
  480. if e.q == 1:
  481. coeff *= Pow(b, e)
  482. continue
  483. if e.p > e.q:
  484. e_i, ep = divmod(e.p, e.q)
  485. coeff *= Pow(b, e_i)
  486. e = Rational(ep, e.q)
  487. num_rat.append((b, e))
  488. del comb_e
  489. # extract gcd of bases in num_rat
  490. # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
  491. pnew = defaultdict(list)
  492. i = 0 # steps through num_rat which may grow
  493. while i < len(num_rat):
  494. bi, ei = num_rat[i]
  495. grow = []
  496. for j in range(i + 1, len(num_rat)):
  497. bj, ej = num_rat[j]
  498. g = bi.gcd(bj)
  499. if g is not S.One:
  500. # 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2
  501. # this might have a gcd with something else
  502. e = ei + ej
  503. if e.q == 1:
  504. coeff *= Pow(g, e)
  505. else:
  506. if e.p > e.q:
  507. e_i, ep = divmod(e.p, e.q) # change e in place
  508. coeff *= Pow(g, e_i)
  509. e = Rational(ep, e.q)
  510. grow.append((g, e))
  511. # update the jth item
  512. num_rat[j] = (bj/g, ej)
  513. # update bi that we are checking with
  514. bi = bi/g
  515. if bi is S.One:
  516. break
  517. if bi is not S.One:
  518. obj = Pow(bi, ei)
  519. if obj.is_Number:
  520. coeff *= obj
  521. else:
  522. # changes like sqrt(12) -> 2*sqrt(3)
  523. for obj in Mul.make_args(obj):
  524. if obj.is_Number:
  525. coeff *= obj
  526. else:
  527. assert obj.is_Pow
  528. bi, ei = obj.args
  529. pnew[ei].append(bi)
  530. num_rat.extend(grow)
  531. i += 1
  532. # combine bases of the new powers
  533. for e, b in pnew.items():
  534. pnew[e] = cls(*b)
  535. # handle -1 and I
  536. if neg1e:
  537. # treat I as (-1)**(1/2) and compute -1's total exponent
  538. p, q = neg1e.as_numer_denom()
  539. # if the integer part is odd, extract -1
  540. n, p = divmod(p, q)
  541. if n % 2:
  542. coeff = -coeff
  543. # if it's a multiple of 1/2 extract I
  544. if q == 2:
  545. c_part.append(S.ImaginaryUnit)
  546. elif p:
  547. # see if there is any positive base this power of
  548. # -1 can join
  549. neg1e = Rational(p, q)
  550. for e, b in pnew.items():
  551. if e == neg1e and b.is_positive:
  552. pnew[e] = -b
  553. break
  554. else:
  555. # keep it separate; we've already evaluated it as
  556. # much as possible so evaluate=False
  557. c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False))
  558. # add all the pnew powers
  559. c_part.extend([Pow(b, e) for e, b in pnew.items()])
  560. # oo, -oo
  561. if coeff in (S.Infinity, S.NegativeInfinity):
  562. def _handle_for_oo(c_part, coeff_sign):
  563. new_c_part = []
  564. for t in c_part:
  565. if t.is_extended_positive:
  566. continue
  567. if t.is_extended_negative:
  568. coeff_sign *= -1
  569. continue
  570. new_c_part.append(t)
  571. return new_c_part, coeff_sign
  572. c_part, coeff_sign = _handle_for_oo(c_part, 1)
  573. nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign)
  574. coeff *= coeff_sign
  575. # zoo
  576. if coeff is S.ComplexInfinity:
  577. # zoo might be
  578. # infinite_real + bounded_im
  579. # bounded_real + infinite_im
  580. # infinite_real + infinite_im
  581. # and non-zero real or imaginary will not change that status.
  582. c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and
  583. c.is_extended_real is not None)]
  584. nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and
  585. c.is_extended_real is not None)]
  586. # 0
  587. elif coeff.is_zero:
  588. # we know for sure the result will be 0 except the multiplicand
  589. # is infinity or a matrix
  590. if any(isinstance(c, MatrixExpr) for c in nc_part):
  591. return [coeff], nc_part, order_symbols
  592. if any(c.is_finite == False for c in c_part):
  593. return [S.NaN], [], order_symbols
  594. return [coeff], [], order_symbols
  595. # check for straggling Numbers that were produced
  596. _new = []
  597. for i in c_part:
  598. if i.is_Number:
  599. coeff *= i
  600. else:
  601. _new.append(i)
  602. c_part = _new
  603. # order commutative part canonically
  604. _mulsort(c_part)
  605. # current code expects coeff to be always in slot-0
  606. if coeff is not S.One:
  607. c_part.insert(0, coeff)
  608. # we are done
  609. if (global_parameters.distribute and not nc_part and len(c_part) == 2 and
  610. c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add):
  611. # 2*(1+a) -> 2 + 2 * a
  612. coeff = c_part[0]
  613. c_part = [Add(*[coeff*f for f in c_part[1].args])]
  614. return c_part, nc_part, order_symbols
  615. def _eval_power(self, e):
  616. # don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
  617. cargs, nc = self.args_cnc(split_1=False)
  618. if e.is_Integer:
  619. return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \
  620. Pow(Mul._from_args(nc), e, evaluate=False)
  621. if e.is_Rational and e.q == 2:
  622. if self.is_imaginary:
  623. a = self.as_real_imag()[1]
  624. if a.is_Rational:
  625. from .power import integer_nthroot
  626. n, d = abs(a/2).as_numer_denom()
  627. n, t = integer_nthroot(n, 2)
  628. if t:
  629. d, t = integer_nthroot(d, 2)
  630. if t:
  631. from sympy.functions.elementary.complexes import sign
  632. r = sympify(n)/d
  633. return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p)
  634. p = Pow(self, e, evaluate=False)
  635. if e.is_Rational or e.is_Float:
  636. return p._eval_expand_power_base()
  637. return p
  638. @classmethod
  639. def class_key(cls):
  640. return 3, 0, cls.__name__
  641. def _eval_evalf(self, prec):
  642. c, m = self.as_coeff_Mul()
  643. if c is S.NegativeOne:
  644. if m.is_Mul:
  645. rv = -AssocOp._eval_evalf(m, prec)
  646. else:
  647. mnew = m._eval_evalf(prec)
  648. if mnew is not None:
  649. m = mnew
  650. rv = -m
  651. else:
  652. rv = AssocOp._eval_evalf(self, prec)
  653. if rv.is_number:
  654. return rv.expand()
  655. return rv
  656. @property
  657. def _mpc_(self):
  658. """
  659. Convert self to an mpmath mpc if possible
  660. """
  661. from .numbers import Float
  662. im_part, imag_unit = self.as_coeff_Mul()
  663. if imag_unit is not S.ImaginaryUnit:
  664. # ValueError may seem more reasonable but since it's a @property,
  665. # we need to use AttributeError to keep from confusing things like
  666. # hasattr.
  667. raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I")
  668. return (Float(0)._mpf_, Float(im_part)._mpf_)
  669. @cacheit
  670. def as_two_terms(self):
  671. """Return head and tail of self.
  672. This is the most efficient way to get the head and tail of an
  673. expression.
  674. - if you want only the head, use self.args[0];
  675. - if you want to process the arguments of the tail then use
  676. self.as_coef_mul() which gives the head and a tuple containing
  677. the arguments of the tail when treated as a Mul.
  678. - if you want the coefficient when self is treated as an Add
  679. then use self.as_coeff_add()[0]
  680. Examples
  681. ========
  682. >>> from sympy.abc import x, y
  683. >>> (3*x*y).as_two_terms()
  684. (3, x*y)
  685. """
  686. args = self.args
  687. if len(args) == 1:
  688. return S.One, self
  689. elif len(args) == 2:
  690. return args
  691. else:
  692. return args[0], self._new_rawargs(*args[1:])
  693. @cacheit
  694. def as_coefficients_dict(self):
  695. """Return a dictionary mapping terms to their coefficient.
  696. Since the dictionary is a defaultdict, inquiries about terms which
  697. were not present will return a coefficient of 0. The dictionary
  698. is considered to have a single term.
  699. Examples
  700. ========
  701. >>> from sympy.abc import a, x
  702. >>> (3*a*x).as_coefficients_dict()
  703. {a*x: 3}
  704. >>> _[a]
  705. 0
  706. """
  707. d = defaultdict(int)
  708. args = self.args
  709. if len(args) == 1 or not args[0].is_Number:
  710. d[self] = S.One
  711. else:
  712. d[self._new_rawargs(*args[1:])] = args[0]
  713. return d
  714. @cacheit
  715. def as_coeff_mul(self, *deps, rational=True, **kwargs):
  716. if deps:
  717. l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
  718. return self._new_rawargs(*l2), tuple(l1)
  719. args = self.args
  720. if args[0].is_Number:
  721. if not rational or args[0].is_Rational:
  722. return args[0], args[1:]
  723. elif args[0].is_extended_negative:
  724. return S.NegativeOne, (-args[0],) + args[1:]
  725. return S.One, args
  726. def as_coeff_Mul(self, rational=False):
  727. """
  728. Efficiently extract the coefficient of a product.
  729. """
  730. coeff, args = self.args[0], self.args[1:]
  731. if coeff.is_Number:
  732. if not rational or coeff.is_Rational:
  733. if len(args) == 1:
  734. return coeff, args[0]
  735. else:
  736. return coeff, self._new_rawargs(*args)
  737. elif coeff.is_extended_negative:
  738. return S.NegativeOne, self._new_rawargs(*((-coeff,) + args))
  739. return S.One, self
  740. def as_real_imag(self, deep=True, **hints):
  741. from sympy.functions.elementary.complexes import Abs, im, re
  742. other = []
  743. coeffr = []
  744. coeffi = []
  745. addterms = S.One
  746. for a in self.args:
  747. r, i = a.as_real_imag()
  748. if i.is_zero:
  749. coeffr.append(r)
  750. elif r.is_zero:
  751. coeffi.append(i*S.ImaginaryUnit)
  752. elif a.is_commutative:
  753. # search for complex conjugate pairs:
  754. for i, x in enumerate(other):
  755. if x == a.conjugate():
  756. coeffr.append(Abs(x)**2)
  757. del other[i]
  758. break
  759. else:
  760. if a.is_Add:
  761. addterms *= a
  762. else:
  763. other.append(a)
  764. else:
  765. other.append(a)
  766. m = self.func(*other)
  767. if hints.get('ignore') == m:
  768. return
  769. if len(coeffi) % 2:
  770. imco = im(coeffi.pop(0))
  771. # all other pairs make a real factor; they will be
  772. # put into reco below
  773. else:
  774. imco = S.Zero
  775. reco = self.func(*(coeffr + coeffi))
  776. r, i = (reco*re(m), reco*im(m))
  777. if addterms == 1:
  778. if m == 1:
  779. if imco.is_zero:
  780. return (reco, S.Zero)
  781. else:
  782. return (S.Zero, reco*imco)
  783. if imco is S.Zero:
  784. return (r, i)
  785. return (-imco*i, imco*r)
  786. from .function import expand_mul
  787. addre, addim = expand_mul(addterms, deep=False).as_real_imag()
  788. if imco is S.Zero:
  789. return (r*addre - i*addim, i*addre + r*addim)
  790. else:
  791. r, i = -imco*i, imco*r
  792. return (r*addre - i*addim, r*addim + i*addre)
  793. @staticmethod
  794. def _expandsums(sums):
  795. """
  796. Helper function for _eval_expand_mul.
  797. sums must be a list of instances of Basic.
  798. """
  799. L = len(sums)
  800. if L == 1:
  801. return sums[0].args
  802. terms = []
  803. left = Mul._expandsums(sums[:L//2])
  804. right = Mul._expandsums(sums[L//2:])
  805. terms = [Mul(a, b) for a in left for b in right]
  806. added = Add(*terms)
  807. return Add.make_args(added) # it may have collapsed down to one term
  808. def _eval_expand_mul(self, **hints):
  809. from sympy.simplify.radsimp import fraction
  810. # Handle things like 1/(x*(x + 1)), which are automatically converted
  811. # to 1/x*1/(x + 1)
  812. expr = self
  813. n, d = fraction(expr)
  814. if d.is_Mul:
  815. n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i
  816. for i in (n, d)]
  817. expr = n/d
  818. if not expr.is_Mul:
  819. return expr
  820. plain, sums, rewrite = [], [], False
  821. for factor in expr.args:
  822. if factor.is_Add:
  823. sums.append(factor)
  824. rewrite = True
  825. else:
  826. if factor.is_commutative:
  827. plain.append(factor)
  828. else:
  829. sums.append(Basic(factor)) # Wrapper
  830. if not rewrite:
  831. return expr
  832. else:
  833. plain = self.func(*plain)
  834. if sums:
  835. deep = hints.get("deep", False)
  836. terms = self.func._expandsums(sums)
  837. args = []
  838. for term in terms:
  839. t = self.func(plain, term)
  840. if t.is_Mul and any(a.is_Add for a in t.args) and deep:
  841. t = t._eval_expand_mul()
  842. args.append(t)
  843. return Add(*args)
  844. else:
  845. return plain
  846. @cacheit
  847. def _eval_derivative(self, s):
  848. args = list(self.args)
  849. terms = []
  850. for i in range(len(args)):
  851. d = args[i].diff(s)
  852. if d:
  853. # Note: reduce is used in step of Mul as Mul is unable to
  854. # handle subtypes and operation priority:
  855. terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One))
  856. return Add.fromiter(terms)
  857. @cacheit
  858. def _eval_derivative_n_times(self, s, n):
  859. from .function import AppliedUndef
  860. from .symbol import Symbol, symbols, Dummy
  861. if not isinstance(s, (AppliedUndef, Symbol)):
  862. # other types of s may not be well behaved, e.g.
  863. # (cos(x)*sin(y)).diff([[x, y, z]])
  864. return super()._eval_derivative_n_times(s, n)
  865. from .numbers import Integer
  866. args = self.args
  867. m = len(args)
  868. if isinstance(n, (int, Integer)):
  869. # https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
  870. terms = []
  871. from sympy.ntheory.multinomial import multinomial_coefficients_iterator
  872. for kvals, c in multinomial_coefficients_iterator(m, n):
  873. p = prod([arg.diff((s, k)) for k, arg in zip(kvals, args)])
  874. terms.append(c * p)
  875. return Add(*terms)
  876. from sympy.concrete.summations import Sum
  877. from sympy.functions.combinatorial.factorials import factorial
  878. from sympy.functions.elementary.miscellaneous import Max
  879. kvals = symbols("k1:%i" % m, cls=Dummy)
  880. klast = n - sum(kvals)
  881. nfact = factorial(n)
  882. e, l = (# better to use the multinomial?
  883. nfact/prod(map(factorial, kvals))/factorial(klast)*\
  884. prod([args[t].diff((s, kvals[t])) for t in range(m-1)])*\
  885. args[-1].diff((s, Max(0, klast))),
  886. [(k, 0, n) for k in kvals])
  887. return Sum(e, *l)
  888. def _eval_difference_delta(self, n, step):
  889. from sympy.series.limitseq import difference_delta as dd
  890. arg0 = self.args[0]
  891. rest = Mul(*self.args[1:])
  892. return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) *
  893. rest)
  894. def _matches_simple(self, expr, repl_dict):
  895. # handle (w*3).matches('x*5') -> {w: x*5/3}
  896. coeff, terms = self.as_coeff_Mul()
  897. terms = Mul.make_args(terms)
  898. if len(terms) == 1:
  899. newexpr = self.__class__._combine_inverse(expr, coeff)
  900. return terms[0].matches(newexpr, repl_dict)
  901. return
  902. def matches(self, expr, repl_dict=None, old=False):
  903. expr = sympify(expr)
  904. if self.is_commutative and expr.is_commutative:
  905. return self._matches_commutative(expr, repl_dict, old)
  906. elif self.is_commutative is not expr.is_commutative:
  907. return None
  908. # Proceed only if both both expressions are non-commutative
  909. c1, nc1 = self.args_cnc()
  910. c2, nc2 = expr.args_cnc()
  911. c1, c2 = [c or [1] for c in [c1, c2]]
  912. # TODO: Should these be self.func?
  913. comm_mul_self = Mul(*c1)
  914. comm_mul_expr = Mul(*c2)
  915. repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)
  916. # If the commutative arguments didn't match and aren't equal, then
  917. # then the expression as a whole doesn't match
  918. if not repl_dict and c1 != c2:
  919. return None
  920. # Now match the non-commutative arguments, expanding powers to
  921. # multiplications
  922. nc1 = Mul._matches_expand_pows(nc1)
  923. nc2 = Mul._matches_expand_pows(nc2)
  924. repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)
  925. return repl_dict or None
  926. @staticmethod
  927. def _matches_expand_pows(arg_list):
  928. new_args = []
  929. for arg in arg_list:
  930. if arg.is_Pow and arg.exp > 0:
  931. new_args.extend([arg.base] * arg.exp)
  932. else:
  933. new_args.append(arg)
  934. return new_args
  935. @staticmethod
  936. def _matches_noncomm(nodes, targets, repl_dict=None):
  937. """Non-commutative multiplication matcher.
  938. `nodes` is a list of symbols within the matcher multiplication
  939. expression, while `targets` is a list of arguments in the
  940. multiplication expression being matched against.
  941. """
  942. if repl_dict is None:
  943. repl_dict = dict()
  944. else:
  945. repl_dict = repl_dict.copy()
  946. # List of possible future states to be considered
  947. agenda = []
  948. # The current matching state, storing index in nodes and targets
  949. state = (0, 0)
  950. node_ind, target_ind = state
  951. # Mapping between wildcard indices and the index ranges they match
  952. wildcard_dict = {}
  953. while target_ind < len(targets) and node_ind < len(nodes):
  954. node = nodes[node_ind]
  955. if node.is_Wild:
  956. Mul._matches_add_wildcard(wildcard_dict, state)
  957. states_matches = Mul._matches_new_states(wildcard_dict, state,
  958. nodes, targets)
  959. if states_matches:
  960. new_states, new_matches = states_matches
  961. agenda.extend(new_states)
  962. if new_matches:
  963. for match in new_matches:
  964. repl_dict[match] = new_matches[match]
  965. if not agenda:
  966. return None
  967. else:
  968. state = agenda.pop()
  969. node_ind, target_ind = state
  970. return repl_dict
  971. @staticmethod
  972. def _matches_add_wildcard(dictionary, state):
  973. node_ind, target_ind = state
  974. if node_ind in dictionary:
  975. begin, end = dictionary[node_ind]
  976. dictionary[node_ind] = (begin, target_ind)
  977. else:
  978. dictionary[node_ind] = (target_ind, target_ind)
  979. @staticmethod
  980. def _matches_new_states(dictionary, state, nodes, targets):
  981. node_ind, target_ind = state
  982. node = nodes[node_ind]
  983. target = targets[target_ind]
  984. # Don't advance at all if we've exhausted the targets but not the nodes
  985. if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:
  986. return None
  987. if node.is_Wild:
  988. match_attempt = Mul._matches_match_wilds(dictionary, node_ind,
  989. nodes, targets)
  990. if match_attempt:
  991. # If the same node has been matched before, don't return
  992. # anything if the current match is diverging from the previous
  993. # match
  994. other_node_inds = Mul._matches_get_other_nodes(dictionary,
  995. nodes, node_ind)
  996. for ind in other_node_inds:
  997. other_begin, other_end = dictionary[ind]
  998. curr_begin, curr_end = dictionary[node_ind]
  999. other_targets = targets[other_begin:other_end + 1]
  1000. current_targets = targets[curr_begin:curr_end + 1]
  1001. for curr, other in zip(current_targets, other_targets):
  1002. if curr != other:
  1003. return None
  1004. # A wildcard node can match more than one target, so only the
  1005. # target index is advanced
  1006. new_state = [(node_ind, target_ind + 1)]
  1007. # Only move on to the next node if there is one
  1008. if node_ind < len(nodes) - 1:
  1009. new_state.append((node_ind + 1, target_ind + 1))
  1010. return new_state, match_attempt
  1011. else:
  1012. # If we're not at a wildcard, then make sure we haven't exhausted
  1013. # nodes but not targets, since in this case one node can only match
  1014. # one target
  1015. if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:
  1016. return None
  1017. match_attempt = node.matches(target)
  1018. if match_attempt:
  1019. return [(node_ind + 1, target_ind + 1)], match_attempt
  1020. elif node == target:
  1021. return [(node_ind + 1, target_ind + 1)], None
  1022. else:
  1023. return None
  1024. @staticmethod
  1025. def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):
  1026. """Determine matches of a wildcard with sub-expression in `target`."""
  1027. wildcard = nodes[wildcard_ind]
  1028. begin, end = dictionary[wildcard_ind]
  1029. terms = targets[begin:end + 1]
  1030. # TODO: Should this be self.func?
  1031. mult = Mul(*terms) if len(terms) > 1 else terms[0]
  1032. return wildcard.matches(mult)
  1033. @staticmethod
  1034. def _matches_get_other_nodes(dictionary, nodes, node_ind):
  1035. """Find other wildcards that may have already been matched."""
  1036. other_node_inds = []
  1037. for ind in dictionary:
  1038. if nodes[ind] == nodes[node_ind]:
  1039. other_node_inds.append(ind)
  1040. return other_node_inds
  1041. @staticmethod
  1042. def _combine_inverse(lhs, rhs):
  1043. """
  1044. Returns lhs/rhs, but treats arguments like symbols, so things
  1045. like oo/oo return 1 (instead of a nan) and ``I`` behaves like
  1046. a symbol instead of sqrt(-1).
  1047. """
  1048. from sympy.simplify.simplify import signsimp
  1049. from .symbol import Dummy
  1050. if lhs == rhs:
  1051. return S.One
  1052. def check(l, r):
  1053. if l.is_Float and r.is_comparable:
  1054. # if both objects are added to 0 they will share the same "normalization"
  1055. # and are more likely to compare the same. Since Add(foo, 0) will not allow
  1056. # the 0 to pass, we use __add__ directly.
  1057. return l.__add__(0) == r.evalf().__add__(0)
  1058. return False
  1059. if check(lhs, rhs) or check(rhs, lhs):
  1060. return S.One
  1061. if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)):
  1062. # gruntz and limit wants a literal I to not combine
  1063. # with a power of -1
  1064. d = Dummy('I')
  1065. _i = {S.ImaginaryUnit: d}
  1066. i_ = {d: S.ImaginaryUnit}
  1067. a = lhs.xreplace(_i).as_powers_dict()
  1068. b = rhs.xreplace(_i).as_powers_dict()
  1069. blen = len(b)
  1070. for bi in tuple(b.keys()):
  1071. if bi in a:
  1072. a[bi] -= b.pop(bi)
  1073. if not a[bi]:
  1074. a.pop(bi)
  1075. if len(b) != blen:
  1076. lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_)
  1077. rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_)
  1078. rv = lhs/rhs
  1079. srv = signsimp(rv)
  1080. return srv if srv.is_Number else rv
  1081. def as_powers_dict(self):
  1082. d = defaultdict(int)
  1083. for term in self.args:
  1084. for b, e in term.as_powers_dict().items():
  1085. d[b] += e
  1086. return d
  1087. def as_numer_denom(self):
  1088. # don't use _from_args to rebuild the numerators and denominators
  1089. # as the order is not guaranteed to be the same once they have
  1090. # been separated from each other
  1091. numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args]))
  1092. return self.func(*numers), self.func(*denoms)
  1093. def as_base_exp(self):
  1094. e1 = None
  1095. bases = []
  1096. nc = 0
  1097. for m in self.args:
  1098. b, e = m.as_base_exp()
  1099. if not b.is_commutative:
  1100. nc += 1
  1101. if e1 is None:
  1102. e1 = e
  1103. elif e != e1 or nc > 1:
  1104. return self, S.One
  1105. bases.append(b)
  1106. return self.func(*bases), e1
  1107. def _eval_is_polynomial(self, syms):
  1108. return all(term._eval_is_polynomial(syms) for term in self.args)
  1109. def _eval_is_rational_function(self, syms):
  1110. return all(term._eval_is_rational_function(syms) for term in self.args)
  1111. def _eval_is_meromorphic(self, x, a):
  1112. return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
  1113. quick_exit=True)
  1114. def _eval_is_algebraic_expr(self, syms):
  1115. return all(term._eval_is_algebraic_expr(syms) for term in self.args)
  1116. _eval_is_commutative = lambda self: _fuzzy_group(
  1117. a.is_commutative for a in self.args)
  1118. def _eval_is_complex(self):
  1119. comp = _fuzzy_group(a.is_complex for a in self.args)
  1120. if comp is False:
  1121. if any(a.is_infinite for a in self.args):
  1122. if any(a.is_zero is not False for a in self.args):
  1123. return None
  1124. return False
  1125. return comp
  1126. def _eval_is_finite(self):
  1127. if all(a.is_finite for a in self.args):
  1128. return True
  1129. if any(a.is_infinite for a in self.args):
  1130. if all(a.is_zero is False for a in self.args):
  1131. return False
  1132. def _eval_is_infinite(self):
  1133. if any(a.is_infinite for a in self.args):
  1134. if any(a.is_zero for a in self.args):
  1135. return S.NaN.is_infinite
  1136. if any(a.is_zero is None for a in self.args):
  1137. return None
  1138. return True
  1139. def _eval_is_rational(self):
  1140. r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True)
  1141. if r:
  1142. return r
  1143. elif r is False:
  1144. return self.is_zero
  1145. def _eval_is_algebraic(self):
  1146. r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True)
  1147. if r:
  1148. return r
  1149. elif r is False:
  1150. return self.is_zero
  1151. def _eval_is_zero(self):
  1152. zero = infinite = False
  1153. for a in self.args:
  1154. z = a.is_zero
  1155. if z:
  1156. if infinite:
  1157. return # 0*oo is nan and nan.is_zero is None
  1158. zero = True
  1159. else:
  1160. if not a.is_finite:
  1161. if zero:
  1162. return # 0*oo is nan and nan.is_zero is None
  1163. infinite = True
  1164. if zero is False and z is None: # trap None
  1165. zero = None
  1166. return zero
  1167. # without involving odd/even checks this code would suffice:
  1168. #_eval_is_integer = lambda self: _fuzzy_group(
  1169. # (a.is_integer for a in self.args), quick_exit=True)
  1170. def _eval_is_integer(self):
  1171. from sympy.ntheory.factor_ import trailing
  1172. is_rational = self._eval_is_rational()
  1173. if is_rational is False:
  1174. return False
  1175. numerators = []
  1176. denominators = []
  1177. unknown = False
  1178. for a in self.args:
  1179. hit = False
  1180. if a.is_integer:
  1181. if abs(a) is not S.One:
  1182. numerators.append(a)
  1183. elif a.is_Rational:
  1184. n, d = a.as_numer_denom()
  1185. if abs(n) is not S.One:
  1186. numerators.append(n)
  1187. if d is not S.One:
  1188. denominators.append(d)
  1189. elif a.is_Pow:
  1190. b, e = a.as_base_exp()
  1191. if not b.is_integer or not e.is_integer:
  1192. hit = unknown = True
  1193. if e.is_negative:
  1194. denominators.append(2 if a is S.Half else
  1195. Pow(a, S.NegativeOne))
  1196. elif not hit:
  1197. # int b and pos int e: a = b**e is integer
  1198. assert not e.is_positive
  1199. # for rational self and e equal to zero: a = b**e is 1
  1200. assert not e.is_zero
  1201. return # sign of e unknown -> self.is_integer unknown
  1202. else:
  1203. return
  1204. if not denominators and not unknown:
  1205. return True
  1206. allodd = lambda x: all(i.is_odd for i in x)
  1207. alleven = lambda x: all(i.is_even for i in x)
  1208. anyeven = lambda x: any(i.is_even for i in x)
  1209. from .relational import is_gt
  1210. if not numerators and denominators and all(is_gt(_, S.One)
  1211. for _ in denominators):
  1212. return False
  1213. elif unknown:
  1214. return
  1215. elif allodd(numerators) and anyeven(denominators):
  1216. return False
  1217. elif anyeven(numerators) and denominators == [2]:
  1218. return True
  1219. elif alleven(numerators) and allodd(denominators
  1220. ) and (Mul(*denominators, evaluate=False) - 1
  1221. ).is_positive:
  1222. return False
  1223. if len(denominators) == 1:
  1224. d = denominators[0]
  1225. if d.is_Integer and d.is_even:
  1226. # if minimal power of 2 in num vs den is not
  1227. # negative then we have an integer
  1228. if (Add(*[i.as_base_exp()[1] for i in
  1229. numerators if i.is_even]) - trailing(d.p)
  1230. ).is_nonnegative:
  1231. return True
  1232. if len(numerators) == 1:
  1233. n = numerators[0]
  1234. if n.is_Integer and n.is_even:
  1235. # if minimal power of 2 in den vs num is positive
  1236. # then we have have a non-integer
  1237. if (Add(*[i.as_base_exp()[1] for i in
  1238. denominators if i.is_even]) - trailing(n.p)
  1239. ).is_positive:
  1240. return False
  1241. def _eval_is_polar(self):
  1242. has_polar = any(arg.is_polar for arg in self.args)
  1243. return has_polar and \
  1244. all(arg.is_polar or arg.is_positive for arg in self.args)
  1245. def _eval_is_extended_real(self):
  1246. return self._eval_real_imag(True)
  1247. def _eval_real_imag(self, real):
  1248. zero = False
  1249. t_not_re_im = None
  1250. for t in self.args:
  1251. if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False:
  1252. return False
  1253. elif t.is_imaginary: # I
  1254. real = not real
  1255. elif t.is_extended_real: # 2
  1256. if not zero:
  1257. z = t.is_zero
  1258. if not z and zero is False:
  1259. zero = z
  1260. elif z:
  1261. if all(a.is_finite for a in self.args):
  1262. return True
  1263. return
  1264. elif t.is_extended_real is False:
  1265. # symbolic or literal like `2 + I` or symbolic imaginary
  1266. if t_not_re_im:
  1267. return # complex terms might cancel
  1268. t_not_re_im = t
  1269. elif t.is_imaginary is False: # symbolic like `2` or `2 + I`
  1270. if t_not_re_im:
  1271. return # complex terms might cancel
  1272. t_not_re_im = t
  1273. else:
  1274. return
  1275. if t_not_re_im:
  1276. if t_not_re_im.is_extended_real is False:
  1277. if real: # like 3
  1278. return zero # 3*(smthng like 2 + I or i) is not real
  1279. if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I
  1280. if not real: # like I
  1281. return zero # I*(smthng like 2 or 2 + I) is not real
  1282. elif zero is False:
  1283. return real # can't be trumped by 0
  1284. elif real:
  1285. return real # doesn't matter what zero is
  1286. def _eval_is_imaginary(self):
  1287. z = self.is_zero
  1288. if z:
  1289. return False
  1290. if self.is_finite is False:
  1291. return False
  1292. elif z is False and self.is_finite is True:
  1293. return self._eval_real_imag(False)
  1294. def _eval_is_hermitian(self):
  1295. return self._eval_herm_antiherm(True)
  1296. def _eval_herm_antiherm(self, real):
  1297. one_nc = zero = one_neither = False
  1298. for t in self.args:
  1299. if not t.is_commutative:
  1300. if one_nc:
  1301. return
  1302. one_nc = True
  1303. if t.is_antihermitian:
  1304. real = not real
  1305. elif t.is_hermitian:
  1306. if not zero:
  1307. z = t.is_zero
  1308. if not z and zero is False:
  1309. zero = z
  1310. elif z:
  1311. if all(a.is_finite for a in self.args):
  1312. return True
  1313. return
  1314. elif t.is_hermitian is False:
  1315. if one_neither:
  1316. return
  1317. one_neither = True
  1318. else:
  1319. return
  1320. if one_neither:
  1321. if real:
  1322. return zero
  1323. elif zero is False or real:
  1324. return real
  1325. def _eval_is_antihermitian(self):
  1326. z = self.is_zero
  1327. if z:
  1328. return False
  1329. elif z is False:
  1330. return self._eval_herm_antiherm(False)
  1331. def _eval_is_irrational(self):
  1332. for t in self.args:
  1333. a = t.is_irrational
  1334. if a:
  1335. others = list(self.args)
  1336. others.remove(t)
  1337. if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others):
  1338. return True
  1339. return
  1340. if a is None:
  1341. return
  1342. if all(x.is_real for x in self.args):
  1343. return False
  1344. def _eval_is_extended_positive(self):
  1345. """Return True if self is positive, False if not, and None if it
  1346. cannot be determined.
  1347. Explanation
  1348. ===========
  1349. This algorithm is non-recursive and works by keeping track of the
  1350. sign which changes when a negative or nonpositive is encountered.
  1351. Whether a nonpositive or nonnegative is seen is also tracked since
  1352. the presence of these makes it impossible to return True, but
  1353. possible to return False if the end result is nonpositive. e.g.
  1354. pos * neg * nonpositive -> pos or zero -> None is returned
  1355. pos * neg * nonnegative -> neg or zero -> False is returned
  1356. """
  1357. return self._eval_pos_neg(1)
  1358. def _eval_pos_neg(self, sign):
  1359. saw_NON = saw_NOT = False
  1360. for t in self.args:
  1361. if t.is_extended_positive:
  1362. continue
  1363. elif t.is_extended_negative:
  1364. sign = -sign
  1365. elif t.is_zero:
  1366. if all(a.is_finite for a in self.args):
  1367. return False
  1368. return
  1369. elif t.is_extended_nonpositive:
  1370. sign = -sign
  1371. saw_NON = True
  1372. elif t.is_extended_nonnegative:
  1373. saw_NON = True
  1374. # FIXME: is_positive/is_negative is False doesn't take account of
  1375. # Symbol('x', infinite=True, extended_real=True) which has
  1376. # e.g. is_positive is False but has uncertain sign.
  1377. elif t.is_positive is False:
  1378. sign = -sign
  1379. if saw_NOT:
  1380. return
  1381. saw_NOT = True
  1382. elif t.is_negative is False:
  1383. if saw_NOT:
  1384. return
  1385. saw_NOT = True
  1386. else:
  1387. return
  1388. if sign == 1 and saw_NON is False and saw_NOT is False:
  1389. return True
  1390. if sign < 0:
  1391. return False
  1392. def _eval_is_extended_negative(self):
  1393. return self._eval_pos_neg(-1)
  1394. def _eval_is_odd(self):
  1395. is_integer = self.is_integer
  1396. if is_integer:
  1397. if self.is_zero:
  1398. return False
  1399. from sympy.simplify.radsimp import fraction
  1400. n, d = fraction(self)
  1401. if d.is_Integer and d.is_even:
  1402. from sympy.ntheory.factor_ import trailing
  1403. # if minimal power of 2 in num vs den is
  1404. # positive then we have an even number
  1405. if (Add(*[i.as_base_exp()[1] for i in
  1406. Mul.make_args(n) if i.is_even]) - trailing(d.p)
  1407. ).is_positive:
  1408. return False
  1409. return
  1410. r, acc = True, 1
  1411. for t in self.args:
  1412. if abs(t) is S.One:
  1413. continue
  1414. assert t.is_integer
  1415. if t.is_even:
  1416. return False
  1417. if r is False:
  1418. pass
  1419. elif acc != 1 and (acc + t).is_odd:
  1420. r = False
  1421. elif t.is_even is None:
  1422. r = None
  1423. acc = t
  1424. return r
  1425. return is_integer # !integer -> !odd
  1426. def _eval_is_even(self):
  1427. is_integer = self.is_integer
  1428. if is_integer:
  1429. return fuzzy_not(self.is_odd)
  1430. from sympy.simplify.radsimp import fraction
  1431. n, d = fraction(self)
  1432. if n.is_Integer and n.is_even:
  1433. # if minimal power of 2 in den vs num is not
  1434. # negative then this is not an integer and
  1435. # can't be even
  1436. from sympy.ntheory.factor_ import trailing
  1437. if (Add(*[i.as_base_exp()[1] for i in
  1438. Mul.make_args(d) if i.is_even]) - trailing(n.p)
  1439. ).is_nonnegative:
  1440. return False
  1441. return is_integer
  1442. def _eval_is_composite(self):
  1443. """
  1444. Here we count the number of arguments that have a minimum value
  1445. greater than two.
  1446. If there are more than one of such a symbol then the result is composite.
  1447. Else, the result cannot be determined.
  1448. """
  1449. number_of_args = 0 # count of symbols with minimum value greater than one
  1450. for arg in self.args:
  1451. if not (arg.is_integer and arg.is_positive):
  1452. return None
  1453. if (arg-1).is_positive:
  1454. number_of_args += 1
  1455. if number_of_args > 1:
  1456. return True
  1457. def _eval_subs(self, old, new):
  1458. from sympy.functions.elementary.complexes import sign
  1459. from sympy.ntheory.factor_ import multiplicity
  1460. from sympy.simplify.powsimp import powdenest
  1461. from sympy.simplify.radsimp import fraction
  1462. if not old.is_Mul:
  1463. return None
  1464. # try keep replacement literal so -2*x doesn't replace 4*x
  1465. if old.args[0].is_Number and old.args[0] < 0:
  1466. if self.args[0].is_Number:
  1467. if self.args[0] < 0:
  1468. return self._subs(-old, -new)
  1469. return None
  1470. def base_exp(a):
  1471. # if I and -1 are in a Mul, they get both end up with
  1472. # a -1 base (see issue 6421); all we want here are the
  1473. # true Pow or exp separated into base and exponent
  1474. from sympy.functions.elementary.exponential import exp
  1475. if a.is_Pow or isinstance(a, exp):
  1476. return a.as_base_exp()
  1477. return a, S.One
  1478. def breakup(eq):
  1479. """break up powers of eq when treated as a Mul:
  1480. b**(Rational*e) -> b**e, Rational
  1481. commutatives come back as a dictionary {b**e: Rational}
  1482. noncommutatives come back as a list [(b**e, Rational)]
  1483. """
  1484. (c, nc) = (defaultdict(int), list())
  1485. for a in Mul.make_args(eq):
  1486. a = powdenest(a)
  1487. (b, e) = base_exp(a)
  1488. if e is not S.One:
  1489. (co, _) = e.as_coeff_mul()
  1490. b = Pow(b, e/co)
  1491. e = co
  1492. if a.is_commutative:
  1493. c[b] += e
  1494. else:
  1495. nc.append([b, e])
  1496. return (c, nc)
  1497. def rejoin(b, co):
  1498. """
  1499. Put rational back with exponent; in general this is not ok, but
  1500. since we took it from the exponent for analysis, it's ok to put
  1501. it back.
  1502. """
  1503. (b, e) = base_exp(b)
  1504. return Pow(b, e*co)
  1505. def ndiv(a, b):
  1506. """if b divides a in an extractive way (like 1/4 divides 1/2
  1507. but not vice versa, and 2/5 does not divide 1/3) then return
  1508. the integer number of times it divides, else return 0.
  1509. """
  1510. if not b.q % a.q or not a.q % b.q:
  1511. return int(a/b)
  1512. return 0
  1513. # give Muls in the denominator a chance to be changed (see issue 5651)
  1514. # rv will be the default return value
  1515. rv = None
  1516. n, d = fraction(self)
  1517. self2 = self
  1518. if d is not S.One:
  1519. self2 = n._subs(old, new)/d._subs(old, new)
  1520. if not self2.is_Mul:
  1521. return self2._subs(old, new)
  1522. if self2 != self:
  1523. rv = self2
  1524. # Now continue with regular substitution.
  1525. # handle the leading coefficient and use it to decide if anything
  1526. # should even be started; we always know where to find the Rational
  1527. # so it's a quick test
  1528. co_self = self2.args[0]
  1529. co_old = old.args[0]
  1530. co_xmul = None
  1531. if co_old.is_Rational and co_self.is_Rational:
  1532. # if coeffs are the same there will be no updating to do
  1533. # below after breakup() step; so skip (and keep co_xmul=None)
  1534. if co_old != co_self:
  1535. co_xmul = co_self.extract_multiplicatively(co_old)
  1536. elif co_old.is_Rational:
  1537. return rv
  1538. # break self and old into factors
  1539. (c, nc) = breakup(self2)
  1540. (old_c, old_nc) = breakup(old)
  1541. # update the coefficients if we had an extraction
  1542. # e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5
  1543. # then co_self in c is replaced by (3/5)**2 and co_residual
  1544. # is 2*(1/7)**2
  1545. if co_xmul and co_xmul.is_Rational and abs(co_old) != 1:
  1546. mult = S(multiplicity(abs(co_old), co_self))
  1547. c.pop(co_self)
  1548. if co_old in c:
  1549. c[co_old] += mult
  1550. else:
  1551. c[co_old] = mult
  1552. co_residual = co_self/co_old**mult
  1553. else:
  1554. co_residual = 1
  1555. # do quick tests to see if we can't succeed
  1556. ok = True
  1557. if len(old_nc) > len(nc):
  1558. # more non-commutative terms
  1559. ok = False
  1560. elif len(old_c) > len(c):
  1561. # more commutative terms
  1562. ok = False
  1563. elif {i[0] for i in old_nc}.difference({i[0] for i in nc}):
  1564. # unmatched non-commutative bases
  1565. ok = False
  1566. elif set(old_c).difference(set(c)):
  1567. # unmatched commutative terms
  1568. ok = False
  1569. elif any(sign(c[b]) != sign(old_c[b]) for b in old_c):
  1570. # differences in sign
  1571. ok = False
  1572. if not ok:
  1573. return rv
  1574. if not old_c:
  1575. cdid = None
  1576. else:
  1577. rat = []
  1578. for (b, old_e) in old_c.items():
  1579. c_e = c[b]
  1580. rat.append(ndiv(c_e, old_e))
  1581. if not rat[-1]:
  1582. return rv
  1583. cdid = min(rat)
  1584. if not old_nc:
  1585. ncdid = None
  1586. for i in range(len(nc)):
  1587. nc[i] = rejoin(*nc[i])
  1588. else:
  1589. ncdid = 0 # number of nc replacements we did
  1590. take = len(old_nc) # how much to look at each time
  1591. limit = cdid or S.Infinity # max number that we can take
  1592. failed = [] # failed terms will need subs if other terms pass
  1593. i = 0
  1594. while limit and i + take <= len(nc):
  1595. hit = False
  1596. # the bases must be equivalent in succession, and
  1597. # the powers must be extractively compatible on the
  1598. # first and last factor but equal in between.
  1599. rat = []
  1600. for j in range(take):
  1601. if nc[i + j][0] != old_nc[j][0]:
  1602. break
  1603. elif j == 0:
  1604. rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
  1605. elif j == take - 1:
  1606. rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
  1607. elif nc[i + j][1] != old_nc[j][1]:
  1608. break
  1609. else:
  1610. rat.append(1)
  1611. j += 1
  1612. else:
  1613. ndo = min(rat)
  1614. if ndo:
  1615. if take == 1:
  1616. if cdid:
  1617. ndo = min(cdid, ndo)
  1618. nc[i] = Pow(new, ndo)*rejoin(nc[i][0],
  1619. nc[i][1] - ndo*old_nc[0][1])
  1620. else:
  1621. ndo = 1
  1622. # the left residual
  1623. l = rejoin(nc[i][0], nc[i][1] - ndo*
  1624. old_nc[0][1])
  1625. # eliminate all middle terms
  1626. mid = new
  1627. # the right residual (which may be the same as the middle if take == 2)
  1628. ir = i + take - 1
  1629. r = (nc[ir][0], nc[ir][1] - ndo*
  1630. old_nc[-1][1])
  1631. if r[1]:
  1632. if i + take < len(nc):
  1633. nc[i:i + take] = [l*mid, r]
  1634. else:
  1635. r = rejoin(*r)
  1636. nc[i:i + take] = [l*mid*r]
  1637. else:
  1638. # there was nothing left on the right
  1639. nc[i:i + take] = [l*mid]
  1640. limit -= ndo
  1641. ncdid += ndo
  1642. hit = True
  1643. if not hit:
  1644. # do the subs on this failing factor
  1645. failed.append(i)
  1646. i += 1
  1647. else:
  1648. if not ncdid:
  1649. return rv
  1650. # although we didn't fail, certain nc terms may have
  1651. # failed so we rebuild them after attempting a partial
  1652. # subs on them
  1653. failed.extend(range(i, len(nc)))
  1654. for i in failed:
  1655. nc[i] = rejoin(*nc[i]).subs(old, new)
  1656. # rebuild the expression
  1657. if cdid is None:
  1658. do = ncdid
  1659. elif ncdid is None:
  1660. do = cdid
  1661. else:
  1662. do = min(ncdid, cdid)
  1663. margs = []
  1664. for b in c:
  1665. if b in old_c:
  1666. # calculate the new exponent
  1667. e = c[b] - old_c[b]*do
  1668. margs.append(rejoin(b, e))
  1669. else:
  1670. margs.append(rejoin(b.subs(old, new), c[b]))
  1671. if cdid and not ncdid:
  1672. # in case we are replacing commutative with non-commutative,
  1673. # we want the new term to come at the front just like the
  1674. # rest of this routine
  1675. margs = [Pow(new, cdid)] + margs
  1676. return co_residual*self2.func(*margs)*self2.func(*nc)
  1677. def _eval_nseries(self, x, n, logx, cdir=0):
  1678. from .function import PoleError
  1679. from sympy.functions.elementary.integers import ceiling
  1680. from sympy.series.order import Order
  1681. def coeff_exp(term, x):
  1682. lt = term.as_coeff_exponent(x)
  1683. if lt[0].has(x):
  1684. try:
  1685. lt = term.leadterm(x)
  1686. except ValueError:
  1687. return term, S.Zero
  1688. return lt
  1689. ords = []
  1690. try:
  1691. for t in self.args:
  1692. coeff, exp = t.leadterm(x, logx=logx)
  1693. if not coeff.has(x):
  1694. ords.append((t, exp))
  1695. else:
  1696. raise ValueError
  1697. n0 = sum(t[1] for t in ords if t[1].is_number)
  1698. facs = []
  1699. for t, m in ords:
  1700. n1 = ceiling(n - n0 + (m if m.is_number else 0))
  1701. s = t.nseries(x, n=n1, logx=logx, cdir=cdir)
  1702. ns = s.getn()
  1703. if ns is not None:
  1704. if ns < n1: # less than expected
  1705. n -= n1 - ns # reduce n
  1706. facs.append(s)
  1707. except (ValueError, NotImplementedError, TypeError, AttributeError, PoleError):
  1708. n0 = sympify(sum(t[1] for t in ords if t[1].is_number))
  1709. if n0.is_nonnegative:
  1710. n0 = S.Zero
  1711. facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args]
  1712. from sympy.simplify.powsimp import powsimp
  1713. res = powsimp(self.func(*facs).expand(), combine='exp', deep=True)
  1714. if res.has(Order):
  1715. res += Order(x**n, x)
  1716. return res
  1717. res = S.Zero
  1718. ords2 = [Add.make_args(factor) for factor in facs]
  1719. for fac in product(*ords2):
  1720. ords3 = [coeff_exp(term, x) for term in fac]
  1721. coeffs, powers = zip(*ords3)
  1722. power = sum(powers)
  1723. if (power - n).is_negative:
  1724. res += Mul(*coeffs)*(x**power)
  1725. def max_degree(e, x):
  1726. if e is x:
  1727. return S.One
  1728. if e.is_Atom:
  1729. return S.Zero
  1730. if e.is_Add:
  1731. return max(max_degree(a, x) for a in e.args)
  1732. if e.is_Mul:
  1733. return Add(*[max_degree(a, x) for a in e.args])
  1734. if e.is_Pow:
  1735. return max_degree(e.base, x)*e.exp
  1736. return S.Zero
  1737. if self.is_polynomial(x):
  1738. from sympy.polys.polyerrors import PolynomialError
  1739. from sympy.polys.polytools import degree
  1740. try:
  1741. if max_degree(self, x) >= n or degree(self, x) != degree(res, x):
  1742. res += Order(x**n, x)
  1743. except PolynomialError:
  1744. pass
  1745. else:
  1746. return res
  1747. if res != self:
  1748. res += Order(x**n, x)
  1749. return res
  1750. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  1751. return self.func(*[t.as_leading_term(x, logx=logx, cdir=cdir) for t in self.args])
  1752. def _eval_conjugate(self):
  1753. return self.func(*[t.conjugate() for t in self.args])
  1754. def _eval_transpose(self):
  1755. return self.func(*[t.transpose() for t in self.args[::-1]])
  1756. def _eval_adjoint(self):
  1757. return self.func(*[t.adjoint() for t in self.args[::-1]])
  1758. def as_content_primitive(self, radical=False, clear=True):
  1759. """Return the tuple (R, self/R) where R is the positive Rational
  1760. extracted from self.
  1761. Examples
  1762. ========
  1763. >>> from sympy import sqrt
  1764. >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
  1765. (6, -sqrt(2)*(1 - sqrt(2)))
  1766. See docstring of Expr.as_content_primitive for more examples.
  1767. """
  1768. coef = S.One
  1769. args = []
  1770. for a in self.args:
  1771. c, p = a.as_content_primitive(radical=radical, clear=clear)
  1772. coef *= c
  1773. if p is not S.One:
  1774. args.append(p)
  1775. # don't use self._from_args here to reconstruct args
  1776. # since there may be identical args now that should be combined
  1777. # e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x))
  1778. return coef, self.func(*args)
  1779. def as_ordered_factors(self, order=None):
  1780. """Transform an expression into an ordered list of factors.
  1781. Examples
  1782. ========
  1783. >>> from sympy import sin, cos
  1784. >>> from sympy.abc import x, y
  1785. >>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
  1786. [2, x, y, sin(x), cos(x)]
  1787. """
  1788. cpart, ncpart = self.args_cnc()
  1789. cpart.sort(key=lambda expr: expr.sort_key(order=order))
  1790. return cpart + ncpart
  1791. @property
  1792. def _sorted_args(self):
  1793. return tuple(self.as_ordered_factors())
  1794. mul = AssocOpDispatcher('mul')
  1795. def prod(a, start=1):
  1796. """Return product of elements of a. Start with int 1 so if only
  1797. ints are included then an int result is returned.
  1798. Examples
  1799. ========
  1800. >>> from sympy import prod, S
  1801. >>> prod(range(3))
  1802. 0
  1803. >>> type(_) is int
  1804. True
  1805. >>> prod([S(2), 3])
  1806. 6
  1807. >>> _.is_Integer
  1808. True
  1809. You can start the product at something other than 1:
  1810. >>> prod([1, 2], 3)
  1811. 6
  1812. """
  1813. return reduce(operator.mul, a, start)
  1814. def _keep_coeff(coeff, factors, clear=True, sign=False):
  1815. """Return ``coeff*factors`` unevaluated if necessary.
  1816. If ``clear`` is False, do not keep the coefficient as a factor
  1817. if it can be distributed on a single factor such that one or
  1818. more terms will still have integer coefficients.
  1819. If ``sign`` is True, allow a coefficient of -1 to remain factored out.
  1820. Examples
  1821. ========
  1822. >>> from sympy.core.mul import _keep_coeff
  1823. >>> from sympy.abc import x, y
  1824. >>> from sympy import S
  1825. >>> _keep_coeff(S.Half, x + 2)
  1826. (x + 2)/2
  1827. >>> _keep_coeff(S.Half, x + 2, clear=False)
  1828. x/2 + 1
  1829. >>> _keep_coeff(S.Half, (x + 2)*y, clear=False)
  1830. y*(x + 2)/2
  1831. >>> _keep_coeff(S(-1), x + y)
  1832. -x - y
  1833. >>> _keep_coeff(S(-1), x + y, sign=True)
  1834. -(x + y)
  1835. """
  1836. if not coeff.is_Number:
  1837. if factors.is_Number:
  1838. factors, coeff = coeff, factors
  1839. else:
  1840. return coeff*factors
  1841. if factors is S.One:
  1842. return coeff
  1843. if coeff is S.One:
  1844. return factors
  1845. elif coeff is S.NegativeOne and not sign:
  1846. return -factors
  1847. elif factors.is_Add:
  1848. if not clear and coeff.is_Rational and coeff.q != 1:
  1849. args = [i.as_coeff_Mul() for i in factors.args]
  1850. args = [(_keep_coeff(c, coeff), m) for c, m in args]
  1851. if any(c.is_Integer for c, _ in args):
  1852. return Add._from_args([Mul._from_args(
  1853. i[1:] if i[0] == 1 else i) for i in args])
  1854. return Mul(coeff, factors, evaluate=False)
  1855. elif factors.is_Mul:
  1856. margs = list(factors.args)
  1857. if margs[0].is_Number:
  1858. margs[0] *= coeff
  1859. if margs[0] == 1:
  1860. margs.pop(0)
  1861. else:
  1862. margs.insert(0, coeff)
  1863. return Mul._from_args(margs)
  1864. else:
  1865. m = coeff*factors
  1866. if m.is_Number and not factors.is_Number:
  1867. m = Mul._from_args((coeff, factors))
  1868. return m
  1869. def expand_2arg(e):
  1870. def do(e):
  1871. if e.is_Mul:
  1872. c, r = e.as_coeff_Mul()
  1873. if c.is_Number and r.is_Add:
  1874. return _unevaluated_Add(*[c*ri for ri in r.args])
  1875. return e
  1876. return bottom_up(e, do)
  1877. from .numbers import Rational
  1878. from .power import Pow
  1879. from .add import Add, _unevaluated_Add