mul.py 77 KB

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