mul.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195
  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.extend([o1, o])
  373. # We do want a combined exponent if it would not be an Add, such as
  374. # y 2y 3y
  375. # x * x -> x
  376. # We determine if two exponents have the same term by using
  377. # as_coeff_Mul.
  378. #
  379. # Unfortunately, this isn't smart enough to consider combining into
  380. # exponents that might already be adds, so things like:
  381. # z - y y
  382. # x * x will be left alone. This is because checking every possible
  383. # combination can slow things down.
  384. # gather exponents of common bases...
  385. def _gather(c_powers):
  386. common_b = {} # b:e
  387. for b, e in c_powers:
  388. co = e.as_coeff_Mul()
  389. common_b.setdefault(b, {}).setdefault(
  390. co[1], []).append(co[0])
  391. for b, d in common_b.items():
  392. for di, li in d.items():
  393. d[di] = Add(*li)
  394. new_c_powers = []
  395. for b, e in common_b.items():
  396. new_c_powers.extend([(b, c*t) for t, c in e.items()])
  397. return new_c_powers
  398. # in c_powers
  399. c_powers = _gather(c_powers)
  400. # and in num_exp
  401. num_exp = _gather(num_exp)
  402. # --- PART 2 ---
  403. #
  404. # o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow)
  405. # o combine collected powers (2**x * 3**x -> 6**x)
  406. # with numeric base
  407. # ................................
  408. # now we have:
  409. # - coeff:
  410. # - c_powers: (b, e)
  411. # - num_exp: (2, e)
  412. # - pnum_rat: {(1/3, [1/3, 2/3, 1/4])}
  413. # 0 1
  414. # x -> 1 x -> x
  415. # this should only need to run twice; if it fails because
  416. # it needs to be run more times, perhaps this should be
  417. # changed to a "while True" loop -- the only reason it
  418. # isn't such now is to allow a less-than-perfect result to
  419. # be obtained rather than raising an error or entering an
  420. # infinite loop
  421. for i in range(2):
  422. new_c_powers = []
  423. changed = False
  424. for b, e in c_powers:
  425. if e.is_zero:
  426. # canceling out infinities yields NaN
  427. if (b.is_Add or b.is_Mul) and any(infty in b.args
  428. for infty in (S.ComplexInfinity, S.Infinity,
  429. S.NegativeInfinity)):
  430. return [S.NaN], [], None
  431. continue
  432. if e is S.One:
  433. if b.is_Number:
  434. coeff *= b
  435. continue
  436. p = b
  437. if e is not S.One:
  438. p = Pow(b, e)
  439. # check to make sure that the base doesn't change
  440. # after exponentiation; to allow for unevaluated
  441. # Pow, we only do so if b is not already a Pow
  442. if p.is_Pow and not b.is_Pow:
  443. bi = b
  444. b, e = p.as_base_exp()
  445. if b != bi:
  446. changed = True
  447. c_part.append(p)
  448. new_c_powers.append((b, e))
  449. # there might have been a change, but unless the base
  450. # matches some other base, there is nothing to do
  451. if changed and len({
  452. b for b, e in new_c_powers}) != len(new_c_powers):
  453. # start over again
  454. c_part = []
  455. c_powers = _gather(new_c_powers)
  456. else:
  457. break
  458. # x x x
  459. # 2 * 3 -> 6
  460. inv_exp_dict = {} # exp:Mul(num-bases) x x
  461. # e.g. x:6 for ... * 2 * 3 * ...
  462. for b, e in num_exp:
  463. inv_exp_dict.setdefault(e, []).append(b)
  464. for e, b in inv_exp_dict.items():
  465. inv_exp_dict[e] = cls(*b)
  466. c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e])
  467. # b, e -> e' = sum(e), b
  468. # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])}
  469. comb_e = {}
  470. for b, e in pnum_rat.items():
  471. comb_e.setdefault(Add(*e), []).append(b)
  472. del pnum_rat
  473. # process them, reducing exponents to values less than 1
  474. # and updating coeff if necessary else adding them to
  475. # num_rat for further processing
  476. num_rat = []
  477. for e, b in comb_e.items():
  478. b = cls(*b)
  479. if e.q == 1:
  480. coeff *= Pow(b, e)
  481. continue
  482. if e.p > e.q:
  483. e_i, ep = divmod(e.p, e.q)
  484. coeff *= Pow(b, e_i)
  485. e = Rational(ep, e.q)
  486. num_rat.append((b, e))
  487. del comb_e
  488. # extract gcd of bases in num_rat
  489. # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4)
  490. pnew = defaultdict(list)
  491. i = 0 # steps through num_rat which may grow
  492. while i < len(num_rat):
  493. bi, ei = num_rat[i]
  494. grow = []
  495. for j in range(i + 1, len(num_rat)):
  496. bj, ej = num_rat[j]
  497. g = bi.gcd(bj)
  498. if g is not S.One:
  499. # 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2
  500. # this might have a gcd with something else
  501. e = ei + ej
  502. if e.q == 1:
  503. coeff *= Pow(g, e)
  504. else:
  505. if e.p > e.q:
  506. e_i, ep = divmod(e.p, e.q) # change e in place
  507. coeff *= Pow(g, e_i)
  508. e = Rational(ep, e.q)
  509. grow.append((g, e))
  510. # update the jth item
  511. num_rat[j] = (bj/g, ej)
  512. # update bi that we are checking with
  513. bi = bi/g
  514. if bi is S.One:
  515. break
  516. if bi is not S.One:
  517. obj = Pow(bi, ei)
  518. if obj.is_Number:
  519. coeff *= obj
  520. else:
  521. # changes like sqrt(12) -> 2*sqrt(3)
  522. for obj in Mul.make_args(obj):
  523. if obj.is_Number:
  524. coeff *= obj
  525. else:
  526. assert obj.is_Pow
  527. bi, ei = obj.args
  528. pnew[ei].append(bi)
  529. num_rat.extend(grow)
  530. i += 1
  531. # combine bases of the new powers
  532. for e, b in pnew.items():
  533. pnew[e] = cls(*b)
  534. # handle -1 and I
  535. if neg1e:
  536. # treat I as (-1)**(1/2) and compute -1's total exponent
  537. p, q = neg1e.as_numer_denom()
  538. # if the integer part is odd, extract -1
  539. n, p = divmod(p, q)
  540. if n % 2:
  541. coeff = -coeff
  542. # if it's a multiple of 1/2 extract I
  543. if q == 2:
  544. c_part.append(S.ImaginaryUnit)
  545. elif p:
  546. # see if there is any positive base this power of
  547. # -1 can join
  548. neg1e = Rational(p, q)
  549. for e, b in pnew.items():
  550. if e == neg1e and b.is_positive:
  551. pnew[e] = -b
  552. break
  553. else:
  554. # keep it separate; we've already evaluated it as
  555. # much as possible so evaluate=False
  556. c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False))
  557. # add all the pnew powers
  558. c_part.extend([Pow(b, e) for e, b in pnew.items()])
  559. # oo, -oo
  560. if coeff in (S.Infinity, S.NegativeInfinity):
  561. def _handle_for_oo(c_part, coeff_sign):
  562. new_c_part = []
  563. for t in c_part:
  564. if t.is_extended_positive:
  565. continue
  566. if t.is_extended_negative:
  567. coeff_sign *= -1
  568. continue
  569. new_c_part.append(t)
  570. return new_c_part, coeff_sign
  571. c_part, coeff_sign = _handle_for_oo(c_part, 1)
  572. nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign)
  573. coeff *= coeff_sign
  574. # zoo
  575. if coeff is S.ComplexInfinity:
  576. # zoo might be
  577. # infinite_real + bounded_im
  578. # bounded_real + infinite_im
  579. # infinite_real + infinite_im
  580. # and non-zero real or imaginary will not change that status.
  581. c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and
  582. c.is_extended_real is not None)]
  583. nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and
  584. c.is_extended_real is not None)]
  585. # 0
  586. elif coeff.is_zero:
  587. # we know for sure the result will be 0 except the multiplicand
  588. # is infinity or a matrix
  589. if any(isinstance(c, MatrixExpr) for c in nc_part):
  590. return [coeff], nc_part, order_symbols
  591. if any(c.is_finite == False for c in c_part):
  592. return [S.NaN], [], order_symbols
  593. return [coeff], [], order_symbols
  594. # check for straggling Numbers that were produced
  595. _new = []
  596. for i in c_part:
  597. if i.is_Number:
  598. coeff *= i
  599. else:
  600. _new.append(i)
  601. c_part = _new
  602. # order commutative part canonically
  603. _mulsort(c_part)
  604. # current code expects coeff to be always in slot-0
  605. if coeff is not S.One:
  606. c_part.insert(0, coeff)
  607. # we are done
  608. if (global_parameters.distribute and not nc_part and len(c_part) == 2 and
  609. c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add):
  610. # 2*(1+a) -> 2 + 2 * a
  611. coeff = c_part[0]
  612. c_part = [Add(*[coeff*f for f in c_part[1].args])]
  613. return c_part, nc_part, order_symbols
  614. def _eval_power(self, e):
  615. # don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B
  616. cargs, nc = self.args_cnc(split_1=False)
  617. if e.is_Integer:
  618. return Mul(*[Pow(b, e, evaluate=False) for b in cargs]) * \
  619. Pow(Mul._from_args(nc), e, evaluate=False)
  620. if e.is_Rational and e.q == 2:
  621. if self.is_imaginary:
  622. a = self.as_real_imag()[1]
  623. if a.is_Rational:
  624. from .power import integer_nthroot
  625. n, d = abs(a/2).as_numer_denom()
  626. n, t = integer_nthroot(n, 2)
  627. if t:
  628. d, t = integer_nthroot(d, 2)
  629. if t:
  630. from sympy.functions.elementary.complexes import sign
  631. r = sympify(n)/d
  632. return _unevaluated_Mul(r**e.p, (1 + sign(a)*S.ImaginaryUnit)**e.p)
  633. p = Pow(self, e, evaluate=False)
  634. if e.is_Rational or e.is_Float:
  635. return p._eval_expand_power_base()
  636. return p
  637. @classmethod
  638. def class_key(cls):
  639. return 3, 0, cls.__name__
  640. def _eval_evalf(self, prec):
  641. c, m = self.as_coeff_Mul()
  642. if c is S.NegativeOne:
  643. if m.is_Mul:
  644. rv = -AssocOp._eval_evalf(m, prec)
  645. else:
  646. mnew = m._eval_evalf(prec)
  647. if mnew is not None:
  648. m = mnew
  649. rv = -m
  650. else:
  651. rv = AssocOp._eval_evalf(self, prec)
  652. if rv.is_number:
  653. return rv.expand()
  654. return rv
  655. @property
  656. def _mpc_(self):
  657. """
  658. Convert self to an mpmath mpc if possible
  659. """
  660. from .numbers import Float
  661. im_part, imag_unit = self.as_coeff_Mul()
  662. if imag_unit is not S.ImaginaryUnit:
  663. # ValueError may seem more reasonable but since it's a @property,
  664. # we need to use AttributeError to keep from confusing things like
  665. # hasattr.
  666. raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I")
  667. return (Float(0)._mpf_, Float(im_part)._mpf_)
  668. @cacheit
  669. def as_two_terms(self):
  670. """Return head and tail of self.
  671. This is the most efficient way to get the head and tail of an
  672. expression.
  673. - if you want only the head, use self.args[0];
  674. - if you want to process the arguments of the tail then use
  675. self.as_coef_mul() which gives the head and a tuple containing
  676. the arguments of the tail when treated as a Mul.
  677. - if you want the coefficient when self is treated as an Add
  678. then use self.as_coeff_add()[0]
  679. Examples
  680. ========
  681. >>> from sympy.abc import x, y
  682. >>> (3*x*y).as_two_terms()
  683. (3, x*y)
  684. """
  685. args = self.args
  686. if len(args) == 1:
  687. return S.One, self
  688. elif len(args) == 2:
  689. return args
  690. else:
  691. return args[0], self._new_rawargs(*args[1:])
  692. @cacheit
  693. def as_coeff_mul(self, *deps, rational=True, **kwargs):
  694. if deps:
  695. l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True)
  696. return self._new_rawargs(*l2), tuple(l1)
  697. args = self.args
  698. if args[0].is_Number:
  699. if not rational or args[0].is_Rational:
  700. return args[0], args[1:]
  701. elif args[0].is_extended_negative:
  702. return S.NegativeOne, (-args[0],) + args[1:]
  703. return S.One, args
  704. def as_coeff_Mul(self, rational=False):
  705. """
  706. Efficiently extract the coefficient of a product.
  707. """
  708. coeff, args = self.args[0], self.args[1:]
  709. if coeff.is_Number:
  710. if not rational or coeff.is_Rational:
  711. if len(args) == 1:
  712. return coeff, args[0]
  713. else:
  714. return coeff, self._new_rawargs(*args)
  715. elif coeff.is_extended_negative:
  716. return S.NegativeOne, self._new_rawargs(*((-coeff,) + args))
  717. return S.One, self
  718. def as_real_imag(self, deep=True, **hints):
  719. from sympy.functions.elementary.complexes import Abs, im, re
  720. other = []
  721. coeffr = []
  722. coeffi = []
  723. addterms = S.One
  724. for a in self.args:
  725. r, i = a.as_real_imag()
  726. if i.is_zero:
  727. coeffr.append(r)
  728. elif r.is_zero:
  729. coeffi.append(i*S.ImaginaryUnit)
  730. elif a.is_commutative:
  731. aconj = a.conjugate() if other else None
  732. # search for complex conjugate pairs:
  733. for i, x in enumerate(other):
  734. if x == aconj:
  735. coeffr.append(Abs(x)**2)
  736. del other[i]
  737. break
  738. else:
  739. if a.is_Add:
  740. addterms *= a
  741. else:
  742. other.append(a)
  743. else:
  744. other.append(a)
  745. m = self.func(*other)
  746. if hints.get('ignore') == m:
  747. return
  748. if len(coeffi) % 2:
  749. imco = im(coeffi.pop(0))
  750. # all other pairs make a real factor; they will be
  751. # put into reco below
  752. else:
  753. imco = S.Zero
  754. reco = self.func(*(coeffr + coeffi))
  755. r, i = (reco*re(m), reco*im(m))
  756. if addterms == 1:
  757. if m == 1:
  758. if imco.is_zero:
  759. return (reco, S.Zero)
  760. else:
  761. return (S.Zero, reco*imco)
  762. if imco is S.Zero:
  763. return (r, i)
  764. return (-imco*i, imco*r)
  765. from .function import expand_mul
  766. addre, addim = expand_mul(addterms, deep=False).as_real_imag()
  767. if imco is S.Zero:
  768. return (r*addre - i*addim, i*addre + r*addim)
  769. else:
  770. r, i = -imco*i, imco*r
  771. return (r*addre - i*addim, r*addim + i*addre)
  772. @staticmethod
  773. def _expandsums(sums):
  774. """
  775. Helper function for _eval_expand_mul.
  776. sums must be a list of instances of Basic.
  777. """
  778. L = len(sums)
  779. if L == 1:
  780. return sums[0].args
  781. terms = []
  782. left = Mul._expandsums(sums[:L//2])
  783. right = Mul._expandsums(sums[L//2:])
  784. terms = [Mul(a, b) for a in left for b in right]
  785. added = Add(*terms)
  786. return Add.make_args(added) # it may have collapsed down to one term
  787. def _eval_expand_mul(self, **hints):
  788. from sympy.simplify.radsimp import fraction
  789. # Handle things like 1/(x*(x + 1)), which are automatically converted
  790. # to 1/x*1/(x + 1)
  791. expr = self
  792. n, d = fraction(expr)
  793. if d.is_Mul:
  794. n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i
  795. for i in (n, d)]
  796. expr = n/d
  797. if not expr.is_Mul:
  798. return expr
  799. plain, sums, rewrite = [], [], False
  800. for factor in expr.args:
  801. if factor.is_Add:
  802. sums.append(factor)
  803. rewrite = True
  804. else:
  805. if factor.is_commutative:
  806. plain.append(factor)
  807. else:
  808. sums.append(Basic(factor)) # Wrapper
  809. if not rewrite:
  810. return expr
  811. else:
  812. plain = self.func(*plain)
  813. if sums:
  814. deep = hints.get("deep", False)
  815. terms = self.func._expandsums(sums)
  816. args = []
  817. for term in terms:
  818. t = self.func(plain, term)
  819. if t.is_Mul and any(a.is_Add for a in t.args) and deep:
  820. t = t._eval_expand_mul()
  821. args.append(t)
  822. return Add(*args)
  823. else:
  824. return plain
  825. @cacheit
  826. def _eval_derivative(self, s):
  827. args = list(self.args)
  828. terms = []
  829. for i in range(len(args)):
  830. d = args[i].diff(s)
  831. if d:
  832. # Note: reduce is used in step of Mul as Mul is unable to
  833. # handle subtypes and operation priority:
  834. terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One))
  835. return Add.fromiter(terms)
  836. @cacheit
  837. def _eval_derivative_n_times(self, s, n):
  838. from .function import AppliedUndef
  839. from .symbol import Symbol, symbols, Dummy
  840. if not isinstance(s, (AppliedUndef, Symbol)):
  841. # other types of s may not be well behaved, e.g.
  842. # (cos(x)*sin(y)).diff([[x, y, z]])
  843. return super()._eval_derivative_n_times(s, n)
  844. from .numbers import Integer
  845. args = self.args
  846. m = len(args)
  847. if isinstance(n, (int, Integer)):
  848. # https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors
  849. terms = []
  850. from sympy.ntheory.multinomial import multinomial_coefficients_iterator
  851. for kvals, c in multinomial_coefficients_iterator(m, n):
  852. p = Mul(*[arg.diff((s, k)) for k, arg in zip(kvals, args)])
  853. terms.append(c * p)
  854. return Add(*terms)
  855. from sympy.concrete.summations import Sum
  856. from sympy.functions.combinatorial.factorials import factorial
  857. from sympy.functions.elementary.miscellaneous import Max
  858. kvals = symbols("k1:%i" % m, cls=Dummy)
  859. klast = n - sum(kvals)
  860. nfact = factorial(n)
  861. e, l = (# better to use the multinomial?
  862. nfact/prod(map(factorial, kvals))/factorial(klast)*\
  863. Mul(*[args[t].diff((s, kvals[t])) for t in range(m-1)])*\
  864. args[-1].diff((s, Max(0, klast))),
  865. [(k, 0, n) for k in kvals])
  866. return Sum(e, *l)
  867. def _eval_difference_delta(self, n, step):
  868. from sympy.series.limitseq import difference_delta as dd
  869. arg0 = self.args[0]
  870. rest = Mul(*self.args[1:])
  871. return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) *
  872. rest)
  873. def _matches_simple(self, expr, repl_dict):
  874. # handle (w*3).matches('x*5') -> {w: x*5/3}
  875. coeff, terms = self.as_coeff_Mul()
  876. terms = Mul.make_args(terms)
  877. if len(terms) == 1:
  878. newexpr = self.__class__._combine_inverse(expr, coeff)
  879. return terms[0].matches(newexpr, repl_dict)
  880. return
  881. def matches(self, expr, repl_dict=None, old=False):
  882. expr = sympify(expr)
  883. if self.is_commutative and expr.is_commutative:
  884. return self._matches_commutative(expr, repl_dict, old)
  885. elif self.is_commutative is not expr.is_commutative:
  886. return None
  887. # Proceed only if both both expressions are non-commutative
  888. c1, nc1 = self.args_cnc()
  889. c2, nc2 = expr.args_cnc()
  890. c1, c2 = [c or [1] for c in [c1, c2]]
  891. # TODO: Should these be self.func?
  892. comm_mul_self = Mul(*c1)
  893. comm_mul_expr = Mul(*c2)
  894. repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old)
  895. # If the commutative arguments didn't match and aren't equal, then
  896. # then the expression as a whole doesn't match
  897. if not repl_dict and c1 != c2:
  898. return None
  899. # Now match the non-commutative arguments, expanding powers to
  900. # multiplications
  901. nc1 = Mul._matches_expand_pows(nc1)
  902. nc2 = Mul._matches_expand_pows(nc2)
  903. repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict)
  904. return repl_dict or None
  905. @staticmethod
  906. def _matches_expand_pows(arg_list):
  907. new_args = []
  908. for arg in arg_list:
  909. if arg.is_Pow and arg.exp > 0:
  910. new_args.extend([arg.base] * arg.exp)
  911. else:
  912. new_args.append(arg)
  913. return new_args
  914. @staticmethod
  915. def _matches_noncomm(nodes, targets, repl_dict=None):
  916. """Non-commutative multiplication matcher.
  917. `nodes` is a list of symbols within the matcher multiplication
  918. expression, while `targets` is a list of arguments in the
  919. multiplication expression being matched against.
  920. """
  921. if repl_dict is None:
  922. repl_dict = {}
  923. else:
  924. repl_dict = repl_dict.copy()
  925. # List of possible future states to be considered
  926. agenda = []
  927. # The current matching state, storing index in nodes and targets
  928. state = (0, 0)
  929. node_ind, target_ind = state
  930. # Mapping between wildcard indices and the index ranges they match
  931. wildcard_dict = {}
  932. while target_ind < len(targets) and node_ind < len(nodes):
  933. node = nodes[node_ind]
  934. if node.is_Wild:
  935. Mul._matches_add_wildcard(wildcard_dict, state)
  936. states_matches = Mul._matches_new_states(wildcard_dict, state,
  937. nodes, targets)
  938. if states_matches:
  939. new_states, new_matches = states_matches
  940. agenda.extend(new_states)
  941. if new_matches:
  942. for match in new_matches:
  943. repl_dict[match] = new_matches[match]
  944. if not agenda:
  945. return None
  946. else:
  947. state = agenda.pop()
  948. node_ind, target_ind = state
  949. return repl_dict
  950. @staticmethod
  951. def _matches_add_wildcard(dictionary, state):
  952. node_ind, target_ind = state
  953. if node_ind in dictionary:
  954. begin, end = dictionary[node_ind]
  955. dictionary[node_ind] = (begin, target_ind)
  956. else:
  957. dictionary[node_ind] = (target_ind, target_ind)
  958. @staticmethod
  959. def _matches_new_states(dictionary, state, nodes, targets):
  960. node_ind, target_ind = state
  961. node = nodes[node_ind]
  962. target = targets[target_ind]
  963. # Don't advance at all if we've exhausted the targets but not the nodes
  964. if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1:
  965. return None
  966. if node.is_Wild:
  967. match_attempt = Mul._matches_match_wilds(dictionary, node_ind,
  968. nodes, targets)
  969. if match_attempt:
  970. # If the same node has been matched before, don't return
  971. # anything if the current match is diverging from the previous
  972. # match
  973. other_node_inds = Mul._matches_get_other_nodes(dictionary,
  974. nodes, node_ind)
  975. for ind in other_node_inds:
  976. other_begin, other_end = dictionary[ind]
  977. curr_begin, curr_end = dictionary[node_ind]
  978. other_targets = targets[other_begin:other_end + 1]
  979. current_targets = targets[curr_begin:curr_end + 1]
  980. for curr, other in zip(current_targets, other_targets):
  981. if curr != other:
  982. return None
  983. # A wildcard node can match more than one target, so only the
  984. # target index is advanced
  985. new_state = [(node_ind, target_ind + 1)]
  986. # Only move on to the next node if there is one
  987. if node_ind < len(nodes) - 1:
  988. new_state.append((node_ind + 1, target_ind + 1))
  989. return new_state, match_attempt
  990. else:
  991. # If we're not at a wildcard, then make sure we haven't exhausted
  992. # nodes but not targets, since in this case one node can only match
  993. # one target
  994. if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1:
  995. return None
  996. match_attempt = node.matches(target)
  997. if match_attempt:
  998. return [(node_ind + 1, target_ind + 1)], match_attempt
  999. elif node == target:
  1000. return [(node_ind + 1, target_ind + 1)], None
  1001. else:
  1002. return None
  1003. @staticmethod
  1004. def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets):
  1005. """Determine matches of a wildcard with sub-expression in `target`."""
  1006. wildcard = nodes[wildcard_ind]
  1007. begin, end = dictionary[wildcard_ind]
  1008. terms = targets[begin:end + 1]
  1009. # TODO: Should this be self.func?
  1010. mult = Mul(*terms) if len(terms) > 1 else terms[0]
  1011. return wildcard.matches(mult)
  1012. @staticmethod
  1013. def _matches_get_other_nodes(dictionary, nodes, node_ind):
  1014. """Find other wildcards that may have already been matched."""
  1015. ind_node = nodes[node_ind]
  1016. return [ind for ind in dictionary if nodes[ind] == ind_node]
  1017. @staticmethod
  1018. def _combine_inverse(lhs, rhs):
  1019. """
  1020. Returns lhs/rhs, but treats arguments like symbols, so things
  1021. like oo/oo return 1 (instead of a nan) and ``I`` behaves like
  1022. a symbol instead of sqrt(-1).
  1023. """
  1024. from sympy.simplify.simplify import signsimp
  1025. from .symbol import Dummy
  1026. if lhs == rhs:
  1027. return S.One
  1028. def check(l, r):
  1029. if l.is_Float and r.is_comparable:
  1030. # if both objects are added to 0 they will share the same "normalization"
  1031. # and are more likely to compare the same. Since Add(foo, 0) will not allow
  1032. # the 0 to pass, we use __add__ directly.
  1033. return l.__add__(0) == r.evalf().__add__(0)
  1034. return False
  1035. if check(lhs, rhs) or check(rhs, lhs):
  1036. return S.One
  1037. if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)):
  1038. # gruntz and limit wants a literal I to not combine
  1039. # with a power of -1
  1040. d = Dummy('I')
  1041. _i = {S.ImaginaryUnit: d}
  1042. i_ = {d: S.ImaginaryUnit}
  1043. a = lhs.xreplace(_i).as_powers_dict()
  1044. b = rhs.xreplace(_i).as_powers_dict()
  1045. blen = len(b)
  1046. for bi in tuple(b.keys()):
  1047. if bi in a:
  1048. a[bi] -= b.pop(bi)
  1049. if not a[bi]:
  1050. a.pop(bi)
  1051. if len(b) != blen:
  1052. lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_)
  1053. rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_)
  1054. rv = lhs/rhs
  1055. srv = signsimp(rv)
  1056. return srv if srv.is_Number else rv
  1057. def as_powers_dict(self):
  1058. d = defaultdict(int)
  1059. for term in self.args:
  1060. for b, e in term.as_powers_dict().items():
  1061. d[b] += e
  1062. return d
  1063. def as_numer_denom(self):
  1064. # don't use _from_args to rebuild the numerators and denominators
  1065. # as the order is not guaranteed to be the same once they have
  1066. # been separated from each other
  1067. numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args]))
  1068. return self.func(*numers), self.func(*denoms)
  1069. def as_base_exp(self):
  1070. e1 = None
  1071. bases = []
  1072. nc = 0
  1073. for m in self.args:
  1074. b, e = m.as_base_exp()
  1075. if not b.is_commutative:
  1076. nc += 1
  1077. if e1 is None:
  1078. e1 = e
  1079. elif e != e1 or nc > 1:
  1080. return self, S.One
  1081. bases.append(b)
  1082. return self.func(*bases), e1
  1083. def _eval_is_polynomial(self, syms):
  1084. return all(term._eval_is_polynomial(syms) for term in self.args)
  1085. def _eval_is_rational_function(self, syms):
  1086. return all(term._eval_is_rational_function(syms) for term in self.args)
  1087. def _eval_is_meromorphic(self, x, a):
  1088. return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args),
  1089. quick_exit=True)
  1090. def _eval_is_algebraic_expr(self, syms):
  1091. return all(term._eval_is_algebraic_expr(syms) for term in self.args)
  1092. _eval_is_commutative = lambda self: _fuzzy_group(
  1093. a.is_commutative for a in self.args)
  1094. def _eval_is_complex(self):
  1095. comp = _fuzzy_group(a.is_complex for a in self.args)
  1096. if comp is False:
  1097. if any(a.is_infinite for a in self.args):
  1098. if any(a.is_zero is not False for a in self.args):
  1099. return None
  1100. return False
  1101. return comp
  1102. def _eval_is_zero_infinite_helper(self):
  1103. #
  1104. # Helper used by _eval_is_zero and _eval_is_infinite.
  1105. #
  1106. # Three-valued logic is tricky so let us reason this carefully. It
  1107. # would be nice to say that we just check is_zero/is_infinite in all
  1108. # args but we need to be careful about the case that one arg is zero
  1109. # and another is infinite like Mul(0, oo) or more importantly a case
  1110. # where it is not known if the arguments are zero or infinite like
  1111. # Mul(y, 1/x). If either y or x could be zero then there is a
  1112. # *possibility* that we have Mul(0, oo) which should give None for both
  1113. # is_zero and is_infinite.
  1114. #
  1115. # We keep track of whether we have seen a zero or infinity but we also
  1116. # need to keep track of whether we have *possibly* seen one which
  1117. # would be indicated by None.
  1118. #
  1119. # For each argument there is the possibility that is_zero might give
  1120. # True, False or None and likewise that is_infinite might give True,
  1121. # False or None, giving 9 combinations. The True cases for is_zero and
  1122. # is_infinite are mutually exclusive though so there are 3 main cases:
  1123. #
  1124. # - is_zero = True
  1125. # - is_infinite = True
  1126. # - is_zero and is_infinite are both either False or None
  1127. #
  1128. # At the end seen_zero and seen_infinite can be any of 9 combinations
  1129. # of True/False/None. Unless one is False though we cannot return
  1130. # anything except None:
  1131. #
  1132. # - is_zero=True needs seen_zero=True and seen_infinite=False
  1133. # - is_zero=False needs seen_zero=False
  1134. # - is_infinite=True needs seen_infinite=True and seen_zero=False
  1135. # - is_infinite=False needs seen_infinite=False
  1136. # - anything else gives both is_zero=None and is_infinite=None
  1137. #
  1138. # The loop only sets the flags to True or None and never back to False.
  1139. # Hence as soon as neither flag is False we exit early returning None.
  1140. # In particular as soon as we encounter a single arg that has
  1141. # is_zero=is_infinite=None we exit. This is a common case since it is
  1142. # the default assumptions for a Symbol and also the case for most
  1143. # expressions containing such a symbol. The early exit gives a big
  1144. # speedup for something like Mul(*symbols('x:1000')).is_zero.
  1145. #
  1146. seen_zero = seen_infinite = False
  1147. for a in self.args:
  1148. if a.is_zero:
  1149. if seen_infinite is not False:
  1150. return None, None
  1151. seen_zero = True
  1152. elif a.is_infinite:
  1153. if seen_zero is not False:
  1154. return None, None
  1155. seen_infinite = True
  1156. else:
  1157. if seen_zero is False and a.is_zero is None:
  1158. if seen_infinite is not False:
  1159. return None, None
  1160. seen_zero = None
  1161. if seen_infinite is False and a.is_infinite is None:
  1162. if seen_zero is not False:
  1163. return None, None
  1164. seen_infinite = None
  1165. return seen_zero, seen_infinite
  1166. def _eval_is_zero(self):
  1167. # True iff any arg is zero and no arg is infinite but need to handle
  1168. # three valued logic carefully.
  1169. seen_zero, seen_infinite = self._eval_is_zero_infinite_helper()
  1170. if seen_zero is False:
  1171. return False
  1172. elif seen_zero is True and seen_infinite is False:
  1173. return True
  1174. else:
  1175. return None
  1176. def _eval_is_infinite(self):
  1177. # True iff any arg is infinite and no arg is zero but need to handle
  1178. # three valued logic carefully.
  1179. seen_zero, seen_infinite = self._eval_is_zero_infinite_helper()
  1180. if seen_infinite is True and seen_zero is False:
  1181. return True
  1182. elif seen_infinite is False:
  1183. return False
  1184. else:
  1185. return None
  1186. # We do not need to implement _eval_is_finite because the assumptions
  1187. # system can infer it from finite = not infinite.
  1188. def _eval_is_rational(self):
  1189. r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True)
  1190. if r:
  1191. return r
  1192. elif r is False:
  1193. # All args except one are rational
  1194. if all(a.is_zero is False for a in self.args):
  1195. return False
  1196. def _eval_is_algebraic(self):
  1197. r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True)
  1198. if r:
  1199. return r
  1200. elif r is False:
  1201. # All args except one are algebraic
  1202. if all(a.is_zero is False for a in self.args):
  1203. return False
  1204. # without involving odd/even checks this code would suffice:
  1205. #_eval_is_integer = lambda self: _fuzzy_group(
  1206. # (a.is_integer for a in self.args), quick_exit=True)
  1207. def _eval_is_integer(self):
  1208. from sympy.ntheory.factor_ import trailing
  1209. is_rational = self._eval_is_rational()
  1210. if is_rational is False:
  1211. return False
  1212. numerators = []
  1213. denominators = []
  1214. unknown = False
  1215. for a in self.args:
  1216. hit = False
  1217. if a.is_integer:
  1218. if abs(a) is not S.One:
  1219. numerators.append(a)
  1220. elif a.is_Rational:
  1221. n, d = a.as_numer_denom()
  1222. if abs(n) is not S.One:
  1223. numerators.append(n)
  1224. if d is not S.One:
  1225. denominators.append(d)
  1226. elif a.is_Pow:
  1227. b, e = a.as_base_exp()
  1228. if not b.is_integer or not e.is_integer:
  1229. hit = unknown = True
  1230. if e.is_negative:
  1231. denominators.append(2 if a is S.Half else
  1232. Pow(a, S.NegativeOne))
  1233. elif not hit:
  1234. # int b and pos int e: a = b**e is integer
  1235. assert not e.is_positive
  1236. # for rational self and e equal to zero: a = b**e is 1
  1237. assert not e.is_zero
  1238. return # sign of e unknown -> self.is_integer unknown
  1239. else:
  1240. # x**2, 2**x, or x**y with x and y int-unknown -> unknown
  1241. return
  1242. else:
  1243. return
  1244. if not denominators and not unknown:
  1245. return True
  1246. allodd = lambda x: all(i.is_odd for i in x)
  1247. alleven = lambda x: all(i.is_even for i in x)
  1248. anyeven = lambda x: any(i.is_even for i in x)
  1249. from .relational import is_gt
  1250. if not numerators and denominators and all(
  1251. is_gt(_, S.One) for _ in denominators):
  1252. return False
  1253. elif unknown:
  1254. return
  1255. elif allodd(numerators) and anyeven(denominators):
  1256. return False
  1257. elif anyeven(numerators) and denominators == [2]:
  1258. return True
  1259. elif alleven(numerators) and allodd(denominators
  1260. ) and (Mul(*denominators, evaluate=False) - 1
  1261. ).is_positive:
  1262. return False
  1263. if len(denominators) == 1:
  1264. d = denominators[0]
  1265. if d.is_Integer and d.is_even:
  1266. # if minimal power of 2 in num vs den is not
  1267. # negative then we have an integer
  1268. if (Add(*[i.as_base_exp()[1] for i in
  1269. numerators if i.is_even]) - trailing(d.p)
  1270. ).is_nonnegative:
  1271. return True
  1272. if len(numerators) == 1:
  1273. n = numerators[0]
  1274. if n.is_Integer and n.is_even:
  1275. # if minimal power of 2 in den vs num is positive
  1276. # then we have have a non-integer
  1277. if (Add(*[i.as_base_exp()[1] for i in
  1278. denominators if i.is_even]) - trailing(n.p)
  1279. ).is_positive:
  1280. return False
  1281. def _eval_is_polar(self):
  1282. has_polar = any(arg.is_polar for arg in self.args)
  1283. return has_polar and \
  1284. all(arg.is_polar or arg.is_positive for arg in self.args)
  1285. def _eval_is_extended_real(self):
  1286. return self._eval_real_imag(True)
  1287. def _eval_real_imag(self, real):
  1288. zero = False
  1289. t_not_re_im = None
  1290. for t in self.args:
  1291. if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False:
  1292. return False
  1293. elif t.is_imaginary: # I
  1294. real = not real
  1295. elif t.is_extended_real: # 2
  1296. if not zero:
  1297. z = t.is_zero
  1298. if not z and zero is False:
  1299. zero = z
  1300. elif z:
  1301. if all(a.is_finite for a in self.args):
  1302. return True
  1303. return
  1304. elif t.is_extended_real is False:
  1305. # symbolic or literal like `2 + I` or symbolic imaginary
  1306. if t_not_re_im:
  1307. return # complex terms might cancel
  1308. t_not_re_im = t
  1309. elif t.is_imaginary is False: # symbolic like `2` or `2 + I`
  1310. if t_not_re_im:
  1311. return # complex terms might cancel
  1312. t_not_re_im = t
  1313. else:
  1314. return
  1315. if t_not_re_im:
  1316. if t_not_re_im.is_extended_real is False:
  1317. if real: # like 3
  1318. return zero # 3*(smthng like 2 + I or i) is not real
  1319. if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I
  1320. if not real: # like I
  1321. return zero # I*(smthng like 2 or 2 + I) is not real
  1322. elif zero is False:
  1323. return real # can't be trumped by 0
  1324. elif real:
  1325. return real # doesn't matter what zero is
  1326. def _eval_is_imaginary(self):
  1327. if all(a.is_zero is False and a.is_finite for a in self.args):
  1328. return self._eval_real_imag(False)
  1329. def _eval_is_hermitian(self):
  1330. return self._eval_herm_antiherm(True)
  1331. def _eval_is_antihermitian(self):
  1332. return self._eval_herm_antiherm(False)
  1333. def _eval_herm_antiherm(self, herm):
  1334. for t in self.args:
  1335. if t.is_hermitian is None or t.is_antihermitian is None:
  1336. return
  1337. if t.is_hermitian:
  1338. continue
  1339. elif t.is_antihermitian:
  1340. herm = not herm
  1341. else:
  1342. return
  1343. if herm is not False:
  1344. return herm
  1345. is_zero = self._eval_is_zero()
  1346. if is_zero:
  1347. return True
  1348. elif is_zero is False:
  1349. return herm
  1350. def _eval_is_irrational(self):
  1351. for t in self.args:
  1352. a = t.is_irrational
  1353. if a:
  1354. others = list(self.args)
  1355. others.remove(t)
  1356. if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others):
  1357. return True
  1358. return
  1359. if a is None:
  1360. return
  1361. if all(x.is_real for x in self.args):
  1362. return False
  1363. def _eval_is_extended_positive(self):
  1364. """Return True if self is positive, False if not, and None if it
  1365. cannot be determined.
  1366. Explanation
  1367. ===========
  1368. This algorithm is non-recursive and works by keeping track of the
  1369. sign which changes when a negative or nonpositive is encountered.
  1370. Whether a nonpositive or nonnegative is seen is also tracked since
  1371. the presence of these makes it impossible to return True, but
  1372. possible to return False if the end result is nonpositive. e.g.
  1373. pos * neg * nonpositive -> pos or zero -> None is returned
  1374. pos * neg * nonnegative -> neg or zero -> False is returned
  1375. """
  1376. return self._eval_pos_neg(1)
  1377. def _eval_pos_neg(self, sign):
  1378. saw_NON = saw_NOT = False
  1379. for t in self.args:
  1380. if t.is_extended_positive:
  1381. continue
  1382. elif t.is_extended_negative:
  1383. sign = -sign
  1384. elif t.is_zero:
  1385. if all(a.is_finite for a in self.args):
  1386. return False
  1387. return
  1388. elif t.is_extended_nonpositive:
  1389. sign = -sign
  1390. saw_NON = True
  1391. elif t.is_extended_nonnegative:
  1392. saw_NON = True
  1393. # FIXME: is_positive/is_negative is False doesn't take account of
  1394. # Symbol('x', infinite=True, extended_real=True) which has
  1395. # e.g. is_positive is False but has uncertain sign.
  1396. elif t.is_positive is False:
  1397. sign = -sign
  1398. if saw_NOT:
  1399. return
  1400. saw_NOT = True
  1401. elif t.is_negative is False:
  1402. if saw_NOT:
  1403. return
  1404. saw_NOT = True
  1405. else:
  1406. return
  1407. if sign == 1 and saw_NON is False and saw_NOT is False:
  1408. return True
  1409. if sign < 0:
  1410. return False
  1411. def _eval_is_extended_negative(self):
  1412. return self._eval_pos_neg(-1)
  1413. def _eval_is_odd(self):
  1414. is_integer = self._eval_is_integer()
  1415. if is_integer is not True:
  1416. return is_integer
  1417. from sympy.simplify.radsimp import fraction
  1418. n, d = fraction(self)
  1419. if d.is_Integer and d.is_even:
  1420. from sympy.ntheory.factor_ import trailing
  1421. # if minimal power of 2 in num vs den is
  1422. # positive then we have an even number
  1423. if (Add(*[i.as_base_exp()[1] for i in
  1424. Mul.make_args(n) if i.is_even]) - trailing(d.p)
  1425. ).is_positive:
  1426. return False
  1427. return
  1428. r, acc = True, 1
  1429. for t in self.args:
  1430. if abs(t) is S.One:
  1431. continue
  1432. if t.is_even:
  1433. return False
  1434. if r is False:
  1435. pass
  1436. elif acc != 1 and (acc + t).is_odd:
  1437. r = False
  1438. elif t.is_even is None:
  1439. r = None
  1440. acc = t
  1441. return r
  1442. def _eval_is_even(self):
  1443. from sympy.simplify.radsimp import fraction
  1444. n, d = fraction(self)
  1445. if n.is_Integer and n.is_even:
  1446. # if minimal power of 2 in den vs num is not
  1447. # negative then this is not an integer and
  1448. # can't be even
  1449. from sympy.ntheory.factor_ import trailing
  1450. if (Add(*[i.as_base_exp()[1] for i in
  1451. Mul.make_args(d) if i.is_even]) - trailing(n.p)
  1452. ).is_nonnegative:
  1453. return False
  1454. def _eval_is_composite(self):
  1455. """
  1456. Here we count the number of arguments that have a minimum value
  1457. greater than two.
  1458. If there are more than one of such a symbol then the result is composite.
  1459. Else, the result cannot be determined.
  1460. """
  1461. number_of_args = 0 # count of symbols with minimum value greater than one
  1462. for arg in self.args:
  1463. if not (arg.is_integer and arg.is_positive):
  1464. return None
  1465. if (arg-1).is_positive:
  1466. number_of_args += 1
  1467. if number_of_args > 1:
  1468. return True
  1469. def _eval_subs(self, old, new):
  1470. from sympy.functions.elementary.complexes import sign
  1471. from sympy.ntheory.factor_ import multiplicity
  1472. from sympy.simplify.powsimp import powdenest
  1473. from sympy.simplify.radsimp import fraction
  1474. if not old.is_Mul:
  1475. return None
  1476. # try keep replacement literal so -2*x doesn't replace 4*x
  1477. if old.args[0].is_Number and old.args[0] < 0:
  1478. if self.args[0].is_Number:
  1479. if self.args[0] < 0:
  1480. return self._subs(-old, -new)
  1481. return None
  1482. def base_exp(a):
  1483. # if I and -1 are in a Mul, they get both end up with
  1484. # a -1 base (see issue 6421); all we want here are the
  1485. # true Pow or exp separated into base and exponent
  1486. from sympy.functions.elementary.exponential import exp
  1487. if a.is_Pow or isinstance(a, exp):
  1488. return a.as_base_exp()
  1489. return a, S.One
  1490. def breakup(eq):
  1491. """break up powers of eq when treated as a Mul:
  1492. b**(Rational*e) -> b**e, Rational
  1493. commutatives come back as a dictionary {b**e: Rational}
  1494. noncommutatives come back as a list [(b**e, Rational)]
  1495. """
  1496. (c, nc) = (defaultdict(int), [])
  1497. for a in Mul.make_args(eq):
  1498. a = powdenest(a)
  1499. (b, e) = base_exp(a)
  1500. if e is not S.One:
  1501. (co, _) = e.as_coeff_mul()
  1502. b = Pow(b, e/co)
  1503. e = co
  1504. if a.is_commutative:
  1505. c[b] += e
  1506. else:
  1507. nc.append([b, e])
  1508. return (c, nc)
  1509. def rejoin(b, co):
  1510. """
  1511. Put rational back with exponent; in general this is not ok, but
  1512. since we took it from the exponent for analysis, it's ok to put
  1513. it back.
  1514. """
  1515. (b, e) = base_exp(b)
  1516. return Pow(b, e*co)
  1517. def ndiv(a, b):
  1518. """if b divides a in an extractive way (like 1/4 divides 1/2
  1519. but not vice versa, and 2/5 does not divide 1/3) then return
  1520. the integer number of times it divides, else return 0.
  1521. """
  1522. if not b.q % a.q or not a.q % b.q:
  1523. return int(a/b)
  1524. return 0
  1525. # give Muls in the denominator a chance to be changed (see issue 5651)
  1526. # rv will be the default return value
  1527. rv = None
  1528. n, d = fraction(self)
  1529. self2 = self
  1530. if d is not S.One:
  1531. self2 = n._subs(old, new)/d._subs(old, new)
  1532. if not self2.is_Mul:
  1533. return self2._subs(old, new)
  1534. if self2 != self:
  1535. rv = self2
  1536. # Now continue with regular substitution.
  1537. # handle the leading coefficient and use it to decide if anything
  1538. # should even be started; we always know where to find the Rational
  1539. # so it's a quick test
  1540. co_self = self2.args[0]
  1541. co_old = old.args[0]
  1542. co_xmul = None
  1543. if co_old.is_Rational and co_self.is_Rational:
  1544. # if coeffs are the same there will be no updating to do
  1545. # below after breakup() step; so skip (and keep co_xmul=None)
  1546. if co_old != co_self:
  1547. co_xmul = co_self.extract_multiplicatively(co_old)
  1548. elif co_old.is_Rational:
  1549. return rv
  1550. # break self and old into factors
  1551. (c, nc) = breakup(self2)
  1552. (old_c, old_nc) = breakup(old)
  1553. # update the coefficients if we had an extraction
  1554. # e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5
  1555. # then co_self in c is replaced by (3/5)**2 and co_residual
  1556. # is 2*(1/7)**2
  1557. if co_xmul and co_xmul.is_Rational and abs(co_old) != 1:
  1558. mult = S(multiplicity(abs(co_old), co_self))
  1559. c.pop(co_self)
  1560. if co_old in c:
  1561. c[co_old] += mult
  1562. else:
  1563. c[co_old] = mult
  1564. co_residual = co_self/co_old**mult
  1565. else:
  1566. co_residual = 1
  1567. # do quick tests to see if we can't succeed
  1568. ok = True
  1569. if len(old_nc) > len(nc):
  1570. # more non-commutative terms
  1571. ok = False
  1572. elif len(old_c) > len(c):
  1573. # more commutative terms
  1574. ok = False
  1575. elif {i[0] for i in old_nc}.difference({i[0] for i in nc}):
  1576. # unmatched non-commutative bases
  1577. ok = False
  1578. elif set(old_c).difference(set(c)):
  1579. # unmatched commutative terms
  1580. ok = False
  1581. elif any(sign(c[b]) != sign(old_c[b]) for b in old_c):
  1582. # differences in sign
  1583. ok = False
  1584. if not ok:
  1585. return rv
  1586. if not old_c:
  1587. cdid = None
  1588. else:
  1589. rat = []
  1590. for (b, old_e) in old_c.items():
  1591. c_e = c[b]
  1592. rat.append(ndiv(c_e, old_e))
  1593. if not rat[-1]:
  1594. return rv
  1595. cdid = min(rat)
  1596. if not old_nc:
  1597. ncdid = None
  1598. for i in range(len(nc)):
  1599. nc[i] = rejoin(*nc[i])
  1600. else:
  1601. ncdid = 0 # number of nc replacements we did
  1602. take = len(old_nc) # how much to look at each time
  1603. limit = cdid or S.Infinity # max number that we can take
  1604. failed = [] # failed terms will need subs if other terms pass
  1605. i = 0
  1606. while limit and i + take <= len(nc):
  1607. hit = False
  1608. # the bases must be equivalent in succession, and
  1609. # the powers must be extractively compatible on the
  1610. # first and last factor but equal in between.
  1611. rat = []
  1612. for j in range(take):
  1613. if nc[i + j][0] != old_nc[j][0]:
  1614. break
  1615. elif j == 0:
  1616. rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
  1617. elif j == take - 1:
  1618. rat.append(ndiv(nc[i + j][1], old_nc[j][1]))
  1619. elif nc[i + j][1] != old_nc[j][1]:
  1620. break
  1621. else:
  1622. rat.append(1)
  1623. j += 1
  1624. else:
  1625. ndo = min(rat)
  1626. if ndo:
  1627. if take == 1:
  1628. if cdid:
  1629. ndo = min(cdid, ndo)
  1630. nc[i] = Pow(new, ndo)*rejoin(nc[i][0],
  1631. nc[i][1] - ndo*old_nc[0][1])
  1632. else:
  1633. ndo = 1
  1634. # the left residual
  1635. l = rejoin(nc[i][0], nc[i][1] - ndo*
  1636. old_nc[0][1])
  1637. # eliminate all middle terms
  1638. mid = new
  1639. # the right residual (which may be the same as the middle if take == 2)
  1640. ir = i + take - 1
  1641. r = (nc[ir][0], nc[ir][1] - ndo*
  1642. old_nc[-1][1])
  1643. if r[1]:
  1644. if i + take < len(nc):
  1645. nc[i:i + take] = [l*mid, r]
  1646. else:
  1647. r = rejoin(*r)
  1648. nc[i:i + take] = [l*mid*r]
  1649. else:
  1650. # there was nothing left on the right
  1651. nc[i:i + take] = [l*mid]
  1652. limit -= ndo
  1653. ncdid += ndo
  1654. hit = True
  1655. if not hit:
  1656. # do the subs on this failing factor
  1657. failed.append(i)
  1658. i += 1
  1659. else:
  1660. if not ncdid:
  1661. return rv
  1662. # although we didn't fail, certain nc terms may have
  1663. # failed so we rebuild them after attempting a partial
  1664. # subs on them
  1665. failed.extend(range(i, len(nc)))
  1666. for i in failed:
  1667. nc[i] = rejoin(*nc[i]).subs(old, new)
  1668. # rebuild the expression
  1669. if cdid is None:
  1670. do = ncdid
  1671. elif ncdid is None:
  1672. do = cdid
  1673. else:
  1674. do = min(ncdid, cdid)
  1675. margs = []
  1676. for b in c:
  1677. if b in old_c:
  1678. # calculate the new exponent
  1679. e = c[b] - old_c[b]*do
  1680. margs.append(rejoin(b, e))
  1681. else:
  1682. margs.append(rejoin(b.subs(old, new), c[b]))
  1683. if cdid and not ncdid:
  1684. # in case we are replacing commutative with non-commutative,
  1685. # we want the new term to come at the front just like the
  1686. # rest of this routine
  1687. margs = [Pow(new, cdid)] + margs
  1688. return co_residual*self2.func(*margs)*self2.func(*nc)
  1689. def _eval_nseries(self, x, n, logx, cdir=0):
  1690. from .function import PoleError
  1691. from sympy.functions.elementary.integers import ceiling
  1692. from sympy.series.order import Order
  1693. def coeff_exp(term, x):
  1694. lt = term.as_coeff_exponent(x)
  1695. if lt[0].has(x):
  1696. try:
  1697. lt = term.leadterm(x)
  1698. except ValueError:
  1699. return term, S.Zero
  1700. return lt
  1701. ords = []
  1702. try:
  1703. for t in self.args:
  1704. coeff, exp = t.leadterm(x)
  1705. if not coeff.has(x):
  1706. ords.append((t, exp))
  1707. else:
  1708. raise ValueError
  1709. n0 = sum(t[1] for t in ords if t[1].is_number)
  1710. facs = []
  1711. for t, m in ords:
  1712. n1 = ceiling(n - n0 + (m if m.is_number else 0))
  1713. s = t.nseries(x, n=n1, logx=logx, cdir=cdir)
  1714. ns = s.getn()
  1715. if ns is not None:
  1716. if ns < n1: # less than expected
  1717. n -= n1 - ns # reduce n
  1718. facs.append(s)
  1719. except (ValueError, NotImplementedError, TypeError, AttributeError, PoleError):
  1720. n0 = sympify(sum(t[1] for t in ords if t[1].is_number))
  1721. if n0.is_nonnegative:
  1722. n0 = S.Zero
  1723. facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args]
  1724. from sympy.simplify.powsimp import powsimp
  1725. res = powsimp(self.func(*facs).expand(), combine='exp', deep=True)
  1726. if res.has(Order):
  1727. res += Order(x**n, x)
  1728. return res
  1729. res = S.Zero
  1730. ords2 = [Add.make_args(factor) for factor in facs]
  1731. for fac in product(*ords2):
  1732. ords3 = [coeff_exp(term, x) for term in fac]
  1733. coeffs, powers = zip(*ords3)
  1734. power = sum(powers)
  1735. if (power - n).is_negative:
  1736. res += Mul(*coeffs)*(x**power)
  1737. def max_degree(e, x):
  1738. if e is x:
  1739. return S.One
  1740. if e.is_Atom:
  1741. return S.Zero
  1742. if e.is_Add:
  1743. return max(max_degree(a, x) for a in e.args)
  1744. if e.is_Mul:
  1745. return Add(*[max_degree(a, x) for a in e.args])
  1746. if e.is_Pow:
  1747. return max_degree(e.base, x)*e.exp
  1748. return S.Zero
  1749. if self.is_polynomial(x):
  1750. from sympy.polys.polyerrors import PolynomialError
  1751. from sympy.polys.polytools import degree
  1752. try:
  1753. if max_degree(self, x) >= n or degree(self, x) != degree(res, x):
  1754. res += Order(x**n, x)
  1755. except PolynomialError:
  1756. pass
  1757. else:
  1758. return res
  1759. if res != self:
  1760. if (self - res).subs(x, 0) == S.Zero and n > 0:
  1761. lt = self._eval_as_leading_term(x, logx=logx, cdir=cdir)
  1762. if lt == S.Zero:
  1763. return res
  1764. res += Order(x**n, x)
  1765. return res
  1766. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  1767. return self.func(*[t.as_leading_term(x, logx=logx, cdir=cdir) for t in self.args])
  1768. def _eval_conjugate(self):
  1769. return self.func(*[t.conjugate() for t in self.args])
  1770. def _eval_transpose(self):
  1771. return self.func(*[t.transpose() for t in self.args[::-1]])
  1772. def _eval_adjoint(self):
  1773. return self.func(*[t.adjoint() for t in self.args[::-1]])
  1774. def as_content_primitive(self, radical=False, clear=True):
  1775. """Return the tuple (R, self/R) where R is the positive Rational
  1776. extracted from self.
  1777. Examples
  1778. ========
  1779. >>> from sympy import sqrt
  1780. >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive()
  1781. (6, -sqrt(2)*(1 - sqrt(2)))
  1782. See docstring of Expr.as_content_primitive for more examples.
  1783. """
  1784. coef = S.One
  1785. args = []
  1786. for a in self.args:
  1787. c, p = a.as_content_primitive(radical=radical, clear=clear)
  1788. coef *= c
  1789. if p is not S.One:
  1790. args.append(p)
  1791. # don't use self._from_args here to reconstruct args
  1792. # since there may be identical args now that should be combined
  1793. # e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x))
  1794. return coef, self.func(*args)
  1795. def as_ordered_factors(self, order=None):
  1796. """Transform an expression into an ordered list of factors.
  1797. Examples
  1798. ========
  1799. >>> from sympy import sin, cos
  1800. >>> from sympy.abc import x, y
  1801. >>> (2*x*y*sin(x)*cos(x)).as_ordered_factors()
  1802. [2, x, y, sin(x), cos(x)]
  1803. """
  1804. cpart, ncpart = self.args_cnc()
  1805. cpart.sort(key=lambda expr: expr.sort_key(order=order))
  1806. return cpart + ncpart
  1807. @property
  1808. def _sorted_args(self):
  1809. return tuple(self.as_ordered_factors())
  1810. mul = AssocOpDispatcher('mul')
  1811. def prod(a, start=1):
  1812. """Return product of elements of a. Start with int 1 so if only
  1813. ints are included then an int result is returned.
  1814. Examples
  1815. ========
  1816. >>> from sympy import prod, S
  1817. >>> prod(range(3))
  1818. 0
  1819. >>> type(_) is int
  1820. True
  1821. >>> prod([S(2), 3])
  1822. 6
  1823. >>> _.is_Integer
  1824. True
  1825. You can start the product at something other than 1:
  1826. >>> prod([1, 2], 3)
  1827. 6
  1828. """
  1829. return reduce(operator.mul, a, start)
  1830. def _keep_coeff(coeff, factors, clear=True, sign=False):
  1831. """Return ``coeff*factors`` unevaluated if necessary.
  1832. If ``clear`` is False, do not keep the coefficient as a factor
  1833. if it can be distributed on a single factor such that one or
  1834. more terms will still have integer coefficients.
  1835. If ``sign`` is True, allow a coefficient of -1 to remain factored out.
  1836. Examples
  1837. ========
  1838. >>> from sympy.core.mul import _keep_coeff
  1839. >>> from sympy.abc import x, y
  1840. >>> from sympy import S
  1841. >>> _keep_coeff(S.Half, x + 2)
  1842. (x + 2)/2
  1843. >>> _keep_coeff(S.Half, x + 2, clear=False)
  1844. x/2 + 1
  1845. >>> _keep_coeff(S.Half, (x + 2)*y, clear=False)
  1846. y*(x + 2)/2
  1847. >>> _keep_coeff(S(-1), x + y)
  1848. -x - y
  1849. >>> _keep_coeff(S(-1), x + y, sign=True)
  1850. -(x + y)
  1851. """
  1852. if not coeff.is_Number:
  1853. if factors.is_Number:
  1854. factors, coeff = coeff, factors
  1855. else:
  1856. return coeff*factors
  1857. if factors is S.One:
  1858. return coeff
  1859. if coeff is S.One:
  1860. return factors
  1861. elif coeff is S.NegativeOne and not sign:
  1862. return -factors
  1863. elif factors.is_Add:
  1864. if not clear and coeff.is_Rational and coeff.q != 1:
  1865. args = [i.as_coeff_Mul() for i in factors.args]
  1866. args = [(_keep_coeff(c, coeff), m) for c, m in args]
  1867. if any(c.is_Integer for c, _ in args):
  1868. return Add._from_args([Mul._from_args(
  1869. i[1:] if i[0] == 1 else i) for i in args])
  1870. return Mul(coeff, factors, evaluate=False)
  1871. elif factors.is_Mul:
  1872. margs = list(factors.args)
  1873. if margs[0].is_Number:
  1874. margs[0] *= coeff
  1875. if margs[0] == 1:
  1876. margs.pop(0)
  1877. else:
  1878. margs.insert(0, coeff)
  1879. return Mul._from_args(margs)
  1880. else:
  1881. m = coeff*factors
  1882. if m.is_Number and not factors.is_Number:
  1883. m = Mul._from_args((coeff, factors))
  1884. return m
  1885. def expand_2arg(e):
  1886. def do(e):
  1887. if e.is_Mul:
  1888. c, r = e.as_coeff_Mul()
  1889. if c.is_Number and r.is_Add:
  1890. return _unevaluated_Add(*[c*ri for ri in r.args])
  1891. return e
  1892. return bottom_up(e, do)
  1893. from .numbers import Rational
  1894. from .power import Pow
  1895. from .add import Add, _unevaluated_Add