piecewise.py 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. from sympy.core import S, diff, Tuple, Dummy, Mul
  2. from sympy.core.basic import Basic, as_Basic
  3. from sympy.core.function import DefinedFunction
  4. from sympy.core.numbers import Rational, NumberSymbol, _illegal
  5. from sympy.core.parameters import global_parameters
  6. from sympy.core.relational import (Lt, Gt, Eq, Ne, Relational,
  7. _canonical, _canonical_coeff)
  8. from sympy.core.sorting import ordered
  9. from sympy.functions.elementary.miscellaneous import Max, Min
  10. from sympy.logic.boolalg import (And, Boolean, distribute_and_over_or, Not,
  11. true, false, Or, ITE, simplify_logic, to_cnf, distribute_or_over_and)
  12. from sympy.utilities.iterables import uniq, sift, common_prefix
  13. from sympy.utilities.misc import filldedent, func_name
  14. from itertools import product
  15. Undefined = S.NaN # Piecewise()
  16. class ExprCondPair(Tuple):
  17. """Represents an expression, condition pair."""
  18. def __new__(cls, expr, cond):
  19. expr = as_Basic(expr)
  20. if cond == True:
  21. return Tuple.__new__(cls, expr, true)
  22. elif cond == False:
  23. return Tuple.__new__(cls, expr, false)
  24. elif isinstance(cond, Basic) and cond.has(Piecewise):
  25. cond = piecewise_fold(cond)
  26. if isinstance(cond, Piecewise):
  27. cond = cond.rewrite(ITE)
  28. if not isinstance(cond, Boolean):
  29. raise TypeError(filldedent('''
  30. Second argument must be a Boolean,
  31. not `%s`''' % func_name(cond)))
  32. return Tuple.__new__(cls, expr, cond)
  33. @property
  34. def expr(self):
  35. """
  36. Returns the expression of this pair.
  37. """
  38. return self.args[0]
  39. @property
  40. def cond(self):
  41. """
  42. Returns the condition of this pair.
  43. """
  44. return self.args[1]
  45. @property
  46. def is_commutative(self):
  47. return self.expr.is_commutative
  48. def __iter__(self):
  49. yield self.expr
  50. yield self.cond
  51. def _eval_simplify(self, **kwargs):
  52. return self.func(*[a.simplify(**kwargs) for a in self.args])
  53. class Piecewise(DefinedFunction):
  54. """
  55. Represents a piecewise function.
  56. Usage:
  57. Piecewise( (expr,cond), (expr,cond), ... )
  58. - Each argument is a 2-tuple defining an expression and condition
  59. - The conds are evaluated in turn returning the first that is True.
  60. If any of the evaluated conds are not explicitly False,
  61. e.g. ``x < 1``, the function is returned in symbolic form.
  62. - If the function is evaluated at a place where all conditions are False,
  63. nan will be returned.
  64. - Pairs where the cond is explicitly False, will be removed and no pair
  65. appearing after a True condition will ever be retained. If a single
  66. pair with a True condition remains, it will be returned, even when
  67. evaluation is False.
  68. Examples
  69. ========
  70. >>> from sympy import Piecewise, log, piecewise_fold
  71. >>> from sympy.abc import x, y
  72. >>> f = x**2
  73. >>> g = log(x)
  74. >>> p = Piecewise((0, x < -1), (f, x <= 1), (g, True))
  75. >>> p.subs(x,1)
  76. 1
  77. >>> p.subs(x,5)
  78. log(5)
  79. Booleans can contain Piecewise elements:
  80. >>> cond = (x < y).subs(x, Piecewise((2, x < 0), (3, True))); cond
  81. Piecewise((2, x < 0), (3, True)) < y
  82. The folded version of this results in a Piecewise whose
  83. expressions are Booleans:
  84. >>> folded_cond = piecewise_fold(cond); folded_cond
  85. Piecewise((2 < y, x < 0), (3 < y, True))
  86. When a Boolean containing Piecewise (like cond) or a Piecewise
  87. with Boolean expressions (like folded_cond) is used as a condition,
  88. it is converted to an equivalent :class:`~.ITE` object:
  89. >>> Piecewise((1, folded_cond))
  90. Piecewise((1, ITE(x < 0, y > 2, y > 3)))
  91. When a condition is an ``ITE``, it will be converted to a simplified
  92. Boolean expression:
  93. >>> piecewise_fold(_)
  94. Piecewise((1, ((x >= 0) | (y > 2)) & ((y > 3) | (x < 0))))
  95. See Also
  96. ========
  97. piecewise_fold
  98. piecewise_exclusive
  99. ITE
  100. """
  101. nargs = None
  102. is_Piecewise = True
  103. def __new__(cls, *args, **options):
  104. if len(args) == 0:
  105. raise TypeError("At least one (expr, cond) pair expected.")
  106. # (Try to) sympify args first
  107. newargs = []
  108. for ec in args:
  109. # ec could be a ExprCondPair or a tuple
  110. pair = ExprCondPair(*getattr(ec, 'args', ec))
  111. cond = pair.cond
  112. if cond is false:
  113. continue
  114. newargs.append(pair)
  115. if cond is true:
  116. break
  117. eval = options.pop('evaluate', global_parameters.evaluate)
  118. if eval:
  119. r = cls.eval(*newargs)
  120. if r is not None:
  121. return r
  122. elif len(newargs) == 1 and newargs[0].cond == True:
  123. return newargs[0].expr
  124. return Basic.__new__(cls, *newargs, **options)
  125. @classmethod
  126. def eval(cls, *_args):
  127. """Either return a modified version of the args or, if no
  128. modifications were made, return None.
  129. Modifications that are made here:
  130. 1. relationals are made canonical
  131. 2. any False conditions are dropped
  132. 3. any repeat of a previous condition is ignored
  133. 4. any args past one with a true condition are dropped
  134. If there are no args left, nan will be returned.
  135. If there is a single arg with a True condition, its
  136. corresponding expression will be returned.
  137. EXAMPLES
  138. ========
  139. >>> from sympy import Piecewise
  140. >>> from sympy.abc import x
  141. >>> cond = -x < -1
  142. >>> args = [(1, cond), (4, cond), (3, False), (2, True), (5, x < 1)]
  143. >>> Piecewise(*args, evaluate=False)
  144. Piecewise((1, -x < -1), (4, -x < -1), (2, True))
  145. >>> Piecewise(*args)
  146. Piecewise((1, x > 1), (2, True))
  147. """
  148. if not _args:
  149. return Undefined
  150. if len(_args) == 1 and _args[0][-1] == True:
  151. return _args[0][0]
  152. newargs = _piecewise_collapse_arguments(_args)
  153. # some conditions may have been redundant
  154. missing = len(newargs) != len(_args)
  155. # some conditions may have changed
  156. same = all(a == b for a, b in zip(newargs, _args))
  157. # if either change happened we return the expr with the
  158. # updated args
  159. if not newargs:
  160. raise ValueError(filldedent('''
  161. There are no conditions (or none that
  162. are not trivially false) to define an
  163. expression.'''))
  164. if missing or not same:
  165. return cls(*newargs)
  166. def doit(self, **hints):
  167. """
  168. Evaluate this piecewise function.
  169. """
  170. newargs = []
  171. for e, c in self.args:
  172. if hints.get('deep', True):
  173. if isinstance(e, Basic):
  174. newe = e.doit(**hints)
  175. if newe != self:
  176. e = newe
  177. if isinstance(c, Basic):
  178. c = c.doit(**hints)
  179. newargs.append((e, c))
  180. return self.func(*newargs)
  181. def _eval_simplify(self, **kwargs):
  182. return piecewise_simplify(self, **kwargs)
  183. def _eval_as_leading_term(self, x, logx, cdir):
  184. for e, c in self.args:
  185. if c == True or c.subs(x, 0) == True:
  186. return e.as_leading_term(x)
  187. def _eval_adjoint(self):
  188. return self.func(*[(e.adjoint(), c) for e, c in self.args])
  189. def _eval_conjugate(self):
  190. return self.func(*[(e.conjugate(), c) for e, c in self.args])
  191. def _eval_derivative(self, x):
  192. return self.func(*[(diff(e, x), c) for e, c in self.args])
  193. def _eval_evalf(self, prec):
  194. return self.func(*[(e._evalf(prec), c) for e, c in self.args])
  195. def _eval_is_meromorphic(self, x, a):
  196. # Conditions often implicitly assume that the argument is real.
  197. # Hence, there needs to be some check for as_set.
  198. if not a.is_real:
  199. return None
  200. # Then, scan ExprCondPairs in the given order to find a piece that would contain a,
  201. # possibly as a boundary point.
  202. for e, c in self.args:
  203. cond = c.subs(x, a)
  204. if cond.is_Relational:
  205. return None
  206. if a in c.as_set().boundary:
  207. return None
  208. # Apply expression if a is an interior point of the domain of e.
  209. if cond:
  210. return e._eval_is_meromorphic(x, a)
  211. def piecewise_integrate(self, x, **kwargs):
  212. """Return the Piecewise with each expression being
  213. replaced with its antiderivative. To obtain a continuous
  214. antiderivative, use the :func:`~.integrate` function or method.
  215. Examples
  216. ========
  217. >>> from sympy import Piecewise
  218. >>> from sympy.abc import x
  219. >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
  220. >>> p.piecewise_integrate(x)
  221. Piecewise((0, x < 0), (x, x < 1), (2*x, True))
  222. Note that this does not give a continuous function, e.g.
  223. at x = 1 the 3rd condition applies and the antiderivative
  224. there is 2*x so the value of the antiderivative is 2:
  225. >>> anti = _
  226. >>> anti.subs(x, 1)
  227. 2
  228. The continuous derivative accounts for the integral *up to*
  229. the point of interest, however:
  230. >>> p.integrate(x)
  231. Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
  232. >>> _.subs(x, 1)
  233. 1
  234. See Also
  235. ========
  236. Piecewise._eval_integral
  237. """
  238. from sympy.integrals import integrate
  239. return self.func(*[(integrate(e, x, **kwargs), c) for e, c in self.args])
  240. def _handle_irel(self, x, handler):
  241. """Return either None (if the conditions of self depend only on x) else
  242. a Piecewise expression whose expressions (handled by the handler that
  243. was passed) are paired with the governing x-independent relationals,
  244. e.g. Piecewise((A, a(x) & b(y)), (B, c(x) | c(y)) ->
  245. Piecewise(
  246. (handler(Piecewise((A, a(x) & True), (B, c(x) | True)), b(y) & c(y)),
  247. (handler(Piecewise((A, a(x) & True), (B, c(x) | False)), b(y)),
  248. (handler(Piecewise((A, a(x) & False), (B, c(x) | True)), c(y)),
  249. (handler(Piecewise((A, a(x) & False), (B, c(x) | False)), True))
  250. """
  251. # identify governing relationals
  252. rel = self.atoms(Relational)
  253. irel = list(ordered([r for r in rel if x not in r.free_symbols
  254. and r not in (S.true, S.false)]))
  255. if irel:
  256. args = {}
  257. exprinorder = []
  258. for truth in product((1, 0), repeat=len(irel)):
  259. reps = dict(zip(irel, truth))
  260. # only store the true conditions since the false are implied
  261. # when they appear lower in the Piecewise args
  262. if 1 not in truth:
  263. cond = None # flag this one so it doesn't get combined
  264. else:
  265. andargs = Tuple(*[i for i in reps if reps[i]])
  266. free = list(andargs.free_symbols)
  267. if len(free) == 1:
  268. from sympy.solvers.inequalities import (
  269. reduce_inequalities, _solve_inequality)
  270. try:
  271. t = reduce_inequalities(andargs, free[0])
  272. # ValueError when there are potentially
  273. # nonvanishing imaginary parts
  274. except (ValueError, NotImplementedError):
  275. # at least isolate free symbol on left
  276. t = And(*[_solve_inequality(
  277. a, free[0], linear=True)
  278. for a in andargs])
  279. else:
  280. t = And(*andargs)
  281. if t is S.false:
  282. continue # an impossible combination
  283. cond = t
  284. expr = handler(self.xreplace(reps))
  285. if isinstance(expr, self.func) and len(expr.args) == 1:
  286. expr, econd = expr.args[0]
  287. cond = And(econd, True if cond is None else cond)
  288. # the ec pairs are being collected since all possibilities
  289. # are being enumerated, but don't put the last one in since
  290. # its expr might match a previous expression and it
  291. # must appear last in the args
  292. if cond is not None:
  293. args.setdefault(expr, []).append(cond)
  294. # but since we only store the true conditions we must maintain
  295. # the order so that the expression with the most true values
  296. # comes first
  297. exprinorder.append(expr)
  298. # convert collected conditions as args of Or
  299. for k in args:
  300. args[k] = Or(*args[k])
  301. # take them in the order obtained
  302. args = [(e, args[e]) for e in uniq(exprinorder)]
  303. # add in the last arg
  304. args.append((expr, True))
  305. return Piecewise(*args)
  306. def _eval_integral(self, x, _first=True, **kwargs):
  307. """Return the indefinite integral of the
  308. Piecewise such that subsequent substitution of x with a
  309. value will give the value of the integral (not including
  310. the constant of integration) up to that point. To only
  311. integrate the individual parts of Piecewise, use the
  312. ``piecewise_integrate`` method.
  313. Examples
  314. ========
  315. >>> from sympy import Piecewise
  316. >>> from sympy.abc import x
  317. >>> p = Piecewise((0, x < 0), (1, x < 1), (2, True))
  318. >>> p.integrate(x)
  319. Piecewise((0, x < 0), (x, x < 1), (2*x - 1, True))
  320. >>> p.piecewise_integrate(x)
  321. Piecewise((0, x < 0), (x, x < 1), (2*x, True))
  322. See Also
  323. ========
  324. Piecewise.piecewise_integrate
  325. """
  326. from sympy.integrals.integrals import integrate
  327. if _first:
  328. def handler(ipw):
  329. if isinstance(ipw, self.func):
  330. return ipw._eval_integral(x, _first=False, **kwargs)
  331. else:
  332. return ipw.integrate(x, **kwargs)
  333. irv = self._handle_irel(x, handler)
  334. if irv is not None:
  335. return irv
  336. # handle a Piecewise from -oo to oo with and no x-independent relationals
  337. # -----------------------------------------------------------------------
  338. ok, abei = self._intervals(x)
  339. if not ok:
  340. from sympy.integrals.integrals import Integral
  341. return Integral(self, x) # unevaluated
  342. pieces = [(a, b) for a, b, _, _ in abei]
  343. oo = S.Infinity
  344. done = [(-oo, oo, -1)]
  345. for k, p in enumerate(pieces):
  346. if p == (-oo, oo):
  347. # all undone intervals will get this key
  348. for j, (a, b, i) in enumerate(done):
  349. if i == -1:
  350. done[j] = a, b, k
  351. break # nothing else to consider
  352. N = len(done) - 1
  353. for j, (a, b, i) in enumerate(reversed(done)):
  354. if i == -1:
  355. j = N - j
  356. done[j: j + 1] = _clip(p, (a, b), k)
  357. done = [(a, b, i) for a, b, i in done if a != b]
  358. # append an arg if there is a hole so a reference to
  359. # argument -1 will give Undefined
  360. if any(i == -1 for (a, b, i) in done):
  361. abei.append((-oo, oo, Undefined, -1))
  362. # return the sum of the intervals
  363. args = []
  364. sum = None
  365. for a, b, i in done:
  366. anti = integrate(abei[i][-2], x, **kwargs)
  367. if sum is None:
  368. sum = anti
  369. else:
  370. sum = sum.subs(x, a)
  371. e = anti._eval_interval(x, a, x)
  372. if sum.has(*_illegal) or e.has(*_illegal):
  373. sum = anti
  374. else:
  375. sum += e
  376. # see if we know whether b is contained in original
  377. # condition
  378. if b is S.Infinity:
  379. cond = True
  380. elif self.args[abei[i][-1]].cond.subs(x, b) == False:
  381. cond = (x < b)
  382. else:
  383. cond = (x <= b)
  384. args.append((sum, cond))
  385. return Piecewise(*args)
  386. def _eval_interval(self, sym, a, b, _first=True):
  387. """Evaluates the function along the sym in a given interval [a, b]"""
  388. # FIXME: Currently complex intervals are not supported. A possible
  389. # replacement algorithm, discussed in issue 5227, can be found in the
  390. # following papers;
  391. # http://portal.acm.org/citation.cfm?id=281649
  392. # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.70.4127&rep=rep1&type=pdf
  393. if a is None or b is None:
  394. # In this case, it is just simple substitution
  395. return super()._eval_interval(sym, a, b)
  396. else:
  397. x, lo, hi = map(as_Basic, (sym, a, b))
  398. if _first: # get only x-dependent relationals
  399. def handler(ipw):
  400. if isinstance(ipw, self.func):
  401. return ipw._eval_interval(x, lo, hi, _first=None)
  402. else:
  403. return ipw._eval_interval(x, lo, hi)
  404. irv = self._handle_irel(x, handler)
  405. if irv is not None:
  406. return irv
  407. if (lo < hi) is S.false or (
  408. lo is S.Infinity or hi is S.NegativeInfinity):
  409. rv = self._eval_interval(x, hi, lo, _first=False)
  410. if isinstance(rv, Piecewise):
  411. rv = Piecewise(*[(-e, c) for e, c in rv.args])
  412. else:
  413. rv = -rv
  414. return rv
  415. if (lo < hi) is S.true or (
  416. hi is S.Infinity or lo is S.NegativeInfinity):
  417. pass
  418. else:
  419. _a = Dummy('lo')
  420. _b = Dummy('hi')
  421. a = lo if lo.is_comparable else _a
  422. b = hi if hi.is_comparable else _b
  423. pos = self._eval_interval(x, a, b, _first=False)
  424. if a == _a and b == _b:
  425. # it's purely symbolic so just swap lo and hi and
  426. # change the sign to get the value for when lo > hi
  427. neg, pos = (-pos.xreplace({_a: hi, _b: lo}),
  428. pos.xreplace({_a: lo, _b: hi}))
  429. else:
  430. # at least one of the bounds was comparable, so allow
  431. # _eval_interval to use that information when computing
  432. # the interval with lo and hi reversed
  433. neg, pos = (-self._eval_interval(x, hi, lo, _first=False),
  434. pos.xreplace({_a: lo, _b: hi}))
  435. # allow simplification based on ordering of lo and hi
  436. p = Dummy('', positive=True)
  437. if lo.is_Symbol:
  438. pos = pos.xreplace({lo: hi - p}).xreplace({p: hi - lo})
  439. neg = neg.xreplace({lo: hi + p}).xreplace({p: lo - hi})
  440. elif hi.is_Symbol:
  441. pos = pos.xreplace({hi: lo + p}).xreplace({p: hi - lo})
  442. neg = neg.xreplace({hi: lo - p}).xreplace({p: lo - hi})
  443. # evaluate limits that may have unevaluate Min/Max
  444. touch = lambda _: _.replace(
  445. lambda x: isinstance(x, (Min, Max)),
  446. lambda x: x.func(*x.args))
  447. neg = touch(neg)
  448. pos = touch(pos)
  449. # assemble return expression; make the first condition be Lt
  450. # b/c then the first expression will look the same whether
  451. # the lo or hi limit is symbolic
  452. if a == _a: # the lower limit was symbolic
  453. rv = Piecewise(
  454. (pos,
  455. lo < hi),
  456. (neg,
  457. True))
  458. else:
  459. rv = Piecewise(
  460. (neg,
  461. hi < lo),
  462. (pos,
  463. True))
  464. if rv == Undefined:
  465. raise ValueError("Can't integrate across undefined region.")
  466. if any(isinstance(i, Piecewise) for i in (pos, neg)):
  467. rv = piecewise_fold(rv)
  468. return rv
  469. # handle a Piecewise with lo <= hi and no x-independent relationals
  470. # -----------------------------------------------------------------
  471. ok, abei = self._intervals(x)
  472. if not ok:
  473. from sympy.integrals.integrals import Integral
  474. # not being able to do the interval of f(x) can
  475. # be stated as not being able to do the integral
  476. # of f'(x) over the same range
  477. return Integral(self.diff(x), (x, lo, hi)) # unevaluated
  478. pieces = [(a, b) for a, b, _, _ in abei]
  479. done = [(lo, hi, -1)]
  480. oo = S.Infinity
  481. for k, p in enumerate(pieces):
  482. if p[:2] == (-oo, oo):
  483. # all undone intervals will get this key
  484. for j, (a, b, i) in enumerate(done):
  485. if i == -1:
  486. done[j] = a, b, k
  487. break # nothing else to consider
  488. N = len(done) - 1
  489. for j, (a, b, i) in enumerate(reversed(done)):
  490. if i == -1:
  491. j = N - j
  492. done[j: j + 1] = _clip(p, (a, b), k)
  493. done = [(a, b, i) for a, b, i in done if a != b]
  494. # return the sum of the intervals
  495. sum = S.Zero
  496. upto = None
  497. for a, b, i in done:
  498. if i == -1:
  499. if upto is None:
  500. return Undefined
  501. # TODO simplify hi <= upto
  502. return Piecewise((sum, hi <= upto), (Undefined, True))
  503. sum += abei[i][-2]._eval_interval(x, a, b)
  504. upto = b
  505. return sum
  506. def _intervals(self, sym, err_on_Eq=False):
  507. r"""Return a bool and a message (when bool is False), else a
  508. list of unique tuples, (a, b, e, i), where a and b
  509. are the lower and upper bounds in which the expression e of
  510. argument i in self is defined and $a < b$ (when involving
  511. numbers) or $a \le b$ when involving symbols.
  512. If there are any relationals not involving sym, or any
  513. relational cannot be solved for sym, the bool will be False
  514. a message be given as the second return value. The calling
  515. routine should have removed such relationals before calling
  516. this routine.
  517. The evaluated conditions will be returned as ranges.
  518. Discontinuous ranges will be returned separately with
  519. identical expressions. The first condition that evaluates to
  520. True will be returned as the last tuple with a, b = -oo, oo.
  521. """
  522. from sympy.solvers.inequalities import _solve_inequality
  523. assert isinstance(self, Piecewise)
  524. def nonsymfail(cond):
  525. return False, filldedent('''
  526. A condition not involving
  527. %s appeared: %s''' % (sym, cond))
  528. def _solve_relational(r):
  529. if sym not in r.free_symbols:
  530. return nonsymfail(r)
  531. try:
  532. rv = _solve_inequality(r, sym)
  533. except NotImplementedError:
  534. return False, 'Unable to solve relational %s for %s.' % (r, sym)
  535. if isinstance(rv, Relational):
  536. free = rv.args[1].free_symbols
  537. if rv.args[0] != sym or sym in free:
  538. return False, 'Unable to solve relational %s for %s.' % (r, sym)
  539. if rv.rel_op == '==':
  540. # this equality has been affirmed to have the form
  541. # Eq(sym, rhs) where rhs is sym-free; it represents
  542. # a zero-width interval which will be ignored
  543. # whether it is an isolated condition or contained
  544. # within an And or an Or
  545. rv = S.false
  546. elif rv.rel_op == '!=':
  547. try:
  548. rv = Or(sym < rv.rhs, sym > rv.rhs)
  549. except TypeError:
  550. # e.g. x != I ==> all real x satisfy
  551. rv = S.true
  552. elif rv == (S.NegativeInfinity < sym) & (sym < S.Infinity):
  553. rv = S.true
  554. return True, rv
  555. args = list(self.args)
  556. # make self canonical wrt Relationals
  557. keys = self.atoms(Relational)
  558. reps = {}
  559. for r in keys:
  560. ok, s = _solve_relational(r)
  561. if ok != True:
  562. return False, ok
  563. reps[r] = s
  564. # process args individually so if any evaluate, their position
  565. # in the original Piecewise will be known
  566. args = [i.xreplace(reps) for i in self.args]
  567. # precondition args
  568. expr_cond = []
  569. default = idefault = None
  570. for i, (expr, cond) in enumerate(args):
  571. if cond is S.false:
  572. continue
  573. if cond is S.true:
  574. default = expr
  575. idefault = i
  576. break
  577. if isinstance(cond, Eq):
  578. # unanticipated condition, but it is here in case a
  579. # replacement caused an Eq to appear
  580. if err_on_Eq:
  581. return False, 'encountered Eq condition: %s' % cond
  582. continue # zero width interval
  583. cond = to_cnf(cond)
  584. if isinstance(cond, And):
  585. cond = distribute_or_over_and(cond)
  586. if isinstance(cond, Or):
  587. expr_cond.extend(
  588. [(i, expr, o) for o in cond.args
  589. if not isinstance(o, Eq)])
  590. elif cond is not S.false:
  591. expr_cond.append((i, expr, cond))
  592. elif cond is S.true:
  593. default = expr
  594. idefault = i
  595. break
  596. # determine intervals represented by conditions
  597. int_expr = []
  598. for iarg, expr, cond in expr_cond:
  599. if isinstance(cond, And):
  600. lower = S.NegativeInfinity
  601. upper = S.Infinity
  602. exclude = []
  603. for cond2 in cond.args:
  604. if not isinstance(cond2, Relational):
  605. return False, 'expecting only Relationals'
  606. if isinstance(cond2, Eq):
  607. lower = upper # ignore
  608. if err_on_Eq:
  609. return False, 'encountered secondary Eq condition'
  610. break
  611. elif isinstance(cond2, Ne):
  612. l, r = cond2.args
  613. if l == sym:
  614. exclude.append(r)
  615. elif r == sym:
  616. exclude.append(l)
  617. else:
  618. return nonsymfail(cond2)
  619. continue
  620. elif cond2.lts == sym:
  621. upper = Min(cond2.gts, upper)
  622. elif cond2.gts == sym:
  623. lower = Max(cond2.lts, lower)
  624. else:
  625. return nonsymfail(cond2) # should never get here
  626. if exclude:
  627. exclude = list(ordered(exclude))
  628. newcond = []
  629. for i, e in enumerate(exclude):
  630. if e < lower == True or e > upper == True:
  631. continue
  632. if not newcond:
  633. newcond.append((None, lower)) # add a primer
  634. newcond.append((newcond[-1][1], e))
  635. newcond.append((newcond[-1][1], upper))
  636. newcond.pop(0) # remove the primer
  637. expr_cond.extend([(iarg, expr, And(i[0] < sym, sym < i[1])) for i in newcond])
  638. continue
  639. elif isinstance(cond, Relational) and cond.rel_op != '!=':
  640. lower, upper = cond.lts, cond.gts # part 1: initialize with givens
  641. if cond.lts == sym: # part 1a: expand the side ...
  642. lower = S.NegativeInfinity # e.g. x <= 0 ---> -oo <= 0
  643. elif cond.gts == sym: # part 1a: ... that can be expanded
  644. upper = S.Infinity # e.g. x >= 0 ---> oo >= 0
  645. else:
  646. return nonsymfail(cond)
  647. else:
  648. return False, 'unrecognized condition: %s' % cond
  649. upper = Max(lower, upper)
  650. if err_on_Eq and lower == upper:
  651. return False, 'encountered Eq condition'
  652. if (lower >= upper) is not S.true:
  653. int_expr.append((lower, upper, expr, iarg))
  654. if default is not None:
  655. int_expr.append(
  656. (S.NegativeInfinity, S.Infinity, default, idefault))
  657. return True, list(uniq(int_expr))
  658. def _eval_nseries(self, x, n, logx, cdir=0):
  659. args = [(ec.expr._eval_nseries(x, n, logx), ec.cond) for ec in self.args]
  660. return self.func(*args)
  661. def _eval_power(self, s):
  662. return self.func(*[(e**s, c) for e, c in self.args])
  663. def _eval_subs(self, old, new):
  664. # this is strictly not necessary, but we can keep track
  665. # of whether True or False conditions arise and be
  666. # somewhat more efficient by avoiding other substitutions
  667. # and avoiding invalid conditions that appear after a
  668. # True condition
  669. args = list(self.args)
  670. args_exist = False
  671. for i, (e, c) in enumerate(args):
  672. c = c._subs(old, new)
  673. if c != False:
  674. args_exist = True
  675. e = e._subs(old, new)
  676. args[i] = (e, c)
  677. if c == True:
  678. break
  679. if not args_exist:
  680. args = ((Undefined, True),)
  681. return self.func(*args)
  682. def _eval_transpose(self):
  683. return self.func(*[(e.transpose(), c) for e, c in self.args])
  684. def _eval_template_is_attr(self, is_attr):
  685. b = None
  686. for expr, _ in self.args:
  687. a = getattr(expr, is_attr)
  688. if a is None:
  689. return
  690. if b is None:
  691. b = a
  692. elif b is not a:
  693. return
  694. return b
  695. _eval_is_finite = lambda self: self._eval_template_is_attr(
  696. 'is_finite')
  697. _eval_is_complex = lambda self: self._eval_template_is_attr('is_complex')
  698. _eval_is_even = lambda self: self._eval_template_is_attr('is_even')
  699. _eval_is_imaginary = lambda self: self._eval_template_is_attr(
  700. 'is_imaginary')
  701. _eval_is_integer = lambda self: self._eval_template_is_attr('is_integer')
  702. _eval_is_irrational = lambda self: self._eval_template_is_attr(
  703. 'is_irrational')
  704. _eval_is_negative = lambda self: self._eval_template_is_attr('is_negative')
  705. _eval_is_nonnegative = lambda self: self._eval_template_is_attr(
  706. 'is_nonnegative')
  707. _eval_is_nonpositive = lambda self: self._eval_template_is_attr(
  708. 'is_nonpositive')
  709. _eval_is_nonzero = lambda self: self._eval_template_is_attr(
  710. 'is_nonzero')
  711. _eval_is_odd = lambda self: self._eval_template_is_attr('is_odd')
  712. _eval_is_polar = lambda self: self._eval_template_is_attr('is_polar')
  713. _eval_is_positive = lambda self: self._eval_template_is_attr('is_positive')
  714. _eval_is_extended_real = lambda self: self._eval_template_is_attr(
  715. 'is_extended_real')
  716. _eval_is_extended_positive = lambda self: self._eval_template_is_attr(
  717. 'is_extended_positive')
  718. _eval_is_extended_negative = lambda self: self._eval_template_is_attr(
  719. 'is_extended_negative')
  720. _eval_is_extended_nonzero = lambda self: self._eval_template_is_attr(
  721. 'is_extended_nonzero')
  722. _eval_is_extended_nonpositive = lambda self: self._eval_template_is_attr(
  723. 'is_extended_nonpositive')
  724. _eval_is_extended_nonnegative = lambda self: self._eval_template_is_attr(
  725. 'is_extended_nonnegative')
  726. _eval_is_real = lambda self: self._eval_template_is_attr('is_real')
  727. _eval_is_zero = lambda self: self._eval_template_is_attr(
  728. 'is_zero')
  729. @classmethod
  730. def __eval_cond(cls, cond):
  731. """Return the truth value of the condition."""
  732. if cond == True:
  733. return True
  734. if isinstance(cond, Eq):
  735. try:
  736. diff = cond.lhs - cond.rhs
  737. if diff.is_commutative:
  738. return diff.is_zero
  739. except TypeError:
  740. pass
  741. def as_expr_set_pairs(self, domain=None):
  742. """Return tuples for each argument of self that give
  743. the expression and the interval in which it is valid
  744. which is contained within the given domain.
  745. If a condition cannot be converted to a set, an error
  746. will be raised. The variable of the conditions is
  747. assumed to be real; sets of real values are returned.
  748. Examples
  749. ========
  750. >>> from sympy import Piecewise, Interval
  751. >>> from sympy.abc import x
  752. >>> p = Piecewise(
  753. ... (1, x < 2),
  754. ... (2,(x > 0) & (x < 4)),
  755. ... (3, True))
  756. >>> p.as_expr_set_pairs()
  757. [(1, Interval.open(-oo, 2)),
  758. (2, Interval.Ropen(2, 4)),
  759. (3, Interval(4, oo))]
  760. >>> p.as_expr_set_pairs(Interval(0, 3))
  761. [(1, Interval.Ropen(0, 2)),
  762. (2, Interval(2, 3))]
  763. """
  764. if domain is None:
  765. domain = S.Reals
  766. exp_sets = []
  767. U = domain
  768. complex = not domain.is_subset(S.Reals)
  769. cond_free = set()
  770. for expr, cond in self.args:
  771. cond_free |= cond.free_symbols
  772. if len(cond_free) > 1:
  773. raise NotImplementedError(filldedent('''
  774. multivariate conditions are not handled.'''))
  775. if complex:
  776. for i in cond.atoms(Relational):
  777. if not isinstance(i, (Eq, Ne)):
  778. raise ValueError(filldedent('''
  779. Inequalities in the complex domain are
  780. not supported. Try the real domain by
  781. setting domain=S.Reals'''))
  782. cond_int = U.intersect(cond.as_set())
  783. U = U - cond_int
  784. if cond_int != S.EmptySet:
  785. exp_sets.append((expr, cond_int))
  786. return exp_sets
  787. def _eval_rewrite_as_ITE(self, *args, **kwargs):
  788. byfree = {}
  789. args = list(args)
  790. default = any(c == True for b, c in args)
  791. for i, (b, c) in enumerate(args):
  792. if not isinstance(b, Boolean) and b != True:
  793. raise TypeError(filldedent('''
  794. Expecting Boolean or bool but got `%s`
  795. ''' % func_name(b)))
  796. if c == True:
  797. break
  798. # loop over independent conditions for this b
  799. for c in c.args if isinstance(c, Or) else [c]:
  800. free = c.free_symbols
  801. x = free.pop()
  802. try:
  803. byfree[x] = byfree.setdefault(
  804. x, S.EmptySet).union(c.as_set())
  805. except NotImplementedError:
  806. if not default:
  807. raise NotImplementedError(filldedent('''
  808. A method to determine whether a multivariate
  809. conditional is consistent with a complete coverage
  810. of all variables has not been implemented so the
  811. rewrite is being stopped after encountering `%s`.
  812. This error would not occur if a default expression
  813. like `(foo, True)` were given.
  814. ''' % c))
  815. if byfree[x] in (S.UniversalSet, S.Reals):
  816. # collapse the ith condition to True and break
  817. args[i] = list(args[i])
  818. c = args[i][1] = True
  819. break
  820. if c == True:
  821. break
  822. if c != True:
  823. raise ValueError(filldedent('''
  824. Conditions must cover all reals or a final default
  825. condition `(foo, True)` must be given.
  826. '''))
  827. last, _ = args[i] # ignore all past ith arg
  828. for a, c in reversed(args[:i]):
  829. last = ITE(c, a, last)
  830. return _canonical(last)
  831. def _eval_rewrite_as_KroneckerDelta(self, *args, **kwargs):
  832. from sympy.functions.special.tensor_functions import KroneckerDelta
  833. rules = {
  834. And: [False, False],
  835. Or: [True, True],
  836. Not: [True, False],
  837. Eq: [None, None],
  838. Ne: [None, None]
  839. }
  840. class UnrecognizedCondition(Exception):
  841. pass
  842. def rewrite(cond):
  843. if isinstance(cond, Eq):
  844. return KroneckerDelta(*cond.args)
  845. if isinstance(cond, Ne):
  846. return 1 - KroneckerDelta(*cond.args)
  847. cls, args = type(cond), cond.args
  848. if cls not in rules:
  849. raise UnrecognizedCondition(cls)
  850. b1, b2 = rules[cls]
  851. k = Mul(*[1 - rewrite(c) for c in args]) if b1 else Mul(*[rewrite(c) for c in args])
  852. if b2:
  853. return 1 - k
  854. return k
  855. conditions = []
  856. true_value = None
  857. for value, cond in args:
  858. if type(cond) in rules:
  859. conditions.append((value, cond))
  860. elif cond is S.true:
  861. if true_value is None:
  862. true_value = value
  863. else:
  864. return
  865. if true_value is not None:
  866. result = true_value
  867. for value, cond in conditions[::-1]:
  868. try:
  869. k = rewrite(cond)
  870. result = k * value + (1 - k) * result
  871. except UnrecognizedCondition:
  872. return
  873. return result
  874. def piecewise_fold(expr, evaluate=True):
  875. """
  876. Takes an expression containing a piecewise function and returns the
  877. expression in piecewise form. In addition, any ITE conditions are
  878. rewritten in negation normal form and simplified.
  879. The final Piecewise is evaluated (default) but if the raw form
  880. is desired, send ``evaluate=False``; if trivial evaluation is
  881. desired, send ``evaluate=None`` and duplicate conditions and
  882. processing of True and False will be handled.
  883. Examples
  884. ========
  885. >>> from sympy import Piecewise, piecewise_fold, S
  886. >>> from sympy.abc import x
  887. >>> p = Piecewise((x, x < 1), (1, S(1) <= x))
  888. >>> piecewise_fold(x*p)
  889. Piecewise((x**2, x < 1), (x, True))
  890. See Also
  891. ========
  892. Piecewise
  893. piecewise_exclusive
  894. """
  895. if not isinstance(expr, Basic) or not expr.has(Piecewise):
  896. return expr
  897. new_args = []
  898. if isinstance(expr, (ExprCondPair, Piecewise)):
  899. for e, c in expr.args:
  900. if not isinstance(e, Piecewise):
  901. e = piecewise_fold(e)
  902. # we don't keep Piecewise in condition because
  903. # it has to be checked to see that it's complete
  904. # and we convert it to ITE at that time
  905. assert not c.has(Piecewise) # pragma: no cover
  906. if isinstance(c, ITE):
  907. c = c.to_nnf()
  908. c = simplify_logic(c, form='cnf')
  909. if isinstance(e, Piecewise):
  910. new_args.extend([(piecewise_fold(ei), And(ci, c))
  911. for ei, ci in e.args])
  912. else:
  913. new_args.append((e, c))
  914. else:
  915. # Given
  916. # P1 = Piecewise((e11, c1), (e12, c2), A)
  917. # P2 = Piecewise((e21, c1), (e22, c2), B)
  918. # ...
  919. # the folding of f(P1, P2) is trivially
  920. # Piecewise(
  921. # (f(e11, e21), c1),
  922. # (f(e12, e22), c2),
  923. # (f(Piecewise(A), Piecewise(B)), True))
  924. # Certain objects end up rewriting themselves as thus, so
  925. # we do that grouping before the more generic folding.
  926. # The following applies this idea when f = Add or f = Mul
  927. # (and the expression is commutative).
  928. if expr.is_Add or expr.is_Mul and expr.is_commutative:
  929. p, args = sift(expr.args, lambda x: x.is_Piecewise, binary=True)
  930. pc = sift(p, lambda x: tuple([c for e,c in x.args]))
  931. for c in list(ordered(pc)):
  932. if len(pc[c]) > 1:
  933. pargs = [list(i.args) for i in pc[c]]
  934. # the first one is the same; there may be more
  935. com = common_prefix(*[
  936. [i.cond for i in j] for j in pargs])
  937. n = len(com)
  938. collected = []
  939. for i in range(n):
  940. collected.append((
  941. expr.func(*[ai[i].expr for ai in pargs]),
  942. com[i]))
  943. remains = []
  944. for a in pargs:
  945. if n == len(a): # no more args
  946. continue
  947. if a[n].cond == True: # no longer Piecewise
  948. remains.append(a[n].expr)
  949. else: # restore the remaining Piecewise
  950. remains.append(
  951. Piecewise(*a[n:], evaluate=False))
  952. if remains:
  953. collected.append((expr.func(*remains), True))
  954. args.append(Piecewise(*collected, evaluate=False))
  955. continue
  956. args.extend(pc[c])
  957. else:
  958. args = expr.args
  959. # fold
  960. folded = list(map(piecewise_fold, args))
  961. for ec in product(*[
  962. (i.args if isinstance(i, Piecewise) else
  963. [(i, true)]) for i in folded]):
  964. e, c = zip(*ec)
  965. new_args.append((expr.func(*e), And(*c)))
  966. if evaluate is None:
  967. # don't return duplicate conditions, otherwise don't evaluate
  968. new_args = list(reversed([(e, c) for c, e in {
  969. c: e for e, c in reversed(new_args)}.items()]))
  970. rv = Piecewise(*new_args, evaluate=evaluate)
  971. if evaluate is None and len(rv.args) == 1 and rv.args[0].cond == True:
  972. return rv.args[0].expr
  973. if any(s.expr.has(Piecewise) for p in rv.atoms(Piecewise) for s in p.args):
  974. return piecewise_fold(rv)
  975. return rv
  976. def _clip(A, B, k):
  977. """Return interval B as intervals that are covered by A (keyed
  978. to k) and all other intervals of B not covered by A keyed to -1.
  979. The reference point of each interval is the rhs; if the lhs is
  980. greater than the rhs then an interval of zero width interval will
  981. result, e.g. (4, 1) is treated like (1, 1).
  982. Examples
  983. ========
  984. >>> from sympy.functions.elementary.piecewise import _clip
  985. >>> from sympy import Tuple
  986. >>> A = Tuple(1, 3)
  987. >>> B = Tuple(2, 4)
  988. >>> _clip(A, B, 0)
  989. [(2, 3, 0), (3, 4, -1)]
  990. Interpretation: interval portion (2, 3) of interval (2, 4) is
  991. covered by interval (1, 3) and is keyed to 0 as requested;
  992. interval (3, 4) was not covered by (1, 3) and is keyed to -1.
  993. """
  994. a, b = B
  995. c, d = A
  996. c, d = Min(Max(c, a), b), Min(Max(d, a), b)
  997. a = Min(a, b)
  998. p = []
  999. if a != c:
  1000. p.append((a, c, -1))
  1001. else:
  1002. pass
  1003. if c != d:
  1004. p.append((c, d, k))
  1005. else:
  1006. pass
  1007. if b != d:
  1008. if d == c and p and p[-1][-1] == -1:
  1009. p[-1] = p[-1][0], b, -1
  1010. else:
  1011. p.append((d, b, -1))
  1012. else:
  1013. pass
  1014. return p
  1015. def piecewise_simplify_arguments(expr, **kwargs):
  1016. from sympy.simplify.simplify import simplify
  1017. # simplify conditions
  1018. f1 = expr.args[0].cond.free_symbols
  1019. args = None
  1020. if len(f1) == 1 and not expr.atoms(Eq):
  1021. x = f1.pop()
  1022. # this won't return intervals involving Eq
  1023. # and it won't handle symbols treated as
  1024. # booleans
  1025. ok, abe_ = expr._intervals(x, err_on_Eq=True)
  1026. def include(c, x, a):
  1027. "return True if c.subs(x, a) is True, else False"
  1028. try:
  1029. return c.subs(x, a) == True
  1030. except TypeError:
  1031. return False
  1032. if ok:
  1033. args = []
  1034. covered = S.EmptySet
  1035. from sympy.sets.sets import Interval
  1036. for a, b, e, i in abe_:
  1037. c = expr.args[i].cond
  1038. incl_a = include(c, x, a)
  1039. incl_b = include(c, x, b)
  1040. iv = Interval(a, b, not incl_a, not incl_b)
  1041. cset = iv - covered
  1042. if not cset:
  1043. continue
  1044. try:
  1045. a = cset.inf
  1046. except NotImplementedError:
  1047. pass # continue with the given `a`
  1048. else:
  1049. incl_a = include(c, x, a)
  1050. if incl_a and incl_b:
  1051. if a.is_infinite and b.is_infinite:
  1052. c = S.true
  1053. elif b.is_infinite:
  1054. c = (x > a) if a in covered else (x >= a)
  1055. elif a.is_infinite:
  1056. c = (x <= b)
  1057. elif a in covered:
  1058. c = And(a < x, x <= b)
  1059. else:
  1060. c = And(a <= x, x <= b)
  1061. elif incl_a:
  1062. if a.is_infinite:
  1063. c = (x < b)
  1064. elif a in covered:
  1065. c = And(a < x, x < b)
  1066. else:
  1067. c = And(a <= x, x < b)
  1068. elif incl_b:
  1069. if b.is_infinite:
  1070. c = (x > a)
  1071. else:
  1072. c = And(a < x, x <= b)
  1073. else:
  1074. if a in covered:
  1075. c = (x < b)
  1076. else:
  1077. c = And(a < x, x < b)
  1078. covered |= iv
  1079. if a is S.NegativeInfinity and incl_a:
  1080. covered |= {S.NegativeInfinity}
  1081. if b is S.Infinity and incl_b:
  1082. covered |= {S.Infinity}
  1083. args.append((e, c))
  1084. if not S.Reals.is_subset(covered):
  1085. args.append((Undefined, True))
  1086. if args is None:
  1087. args = list(expr.args)
  1088. for i in range(len(args)):
  1089. e, c = args[i]
  1090. if isinstance(c, Basic):
  1091. c = simplify(c, **kwargs)
  1092. args[i] = (e, c)
  1093. # simplify expressions
  1094. doit = kwargs.pop('doit', None)
  1095. for i in range(len(args)):
  1096. e, c = args[i]
  1097. if isinstance(e, Basic):
  1098. # Skip doit to avoid growth at every call for some integrals
  1099. # and sums, see sympy/sympy#17165
  1100. newe = simplify(e, doit=False, **kwargs)
  1101. if newe != e:
  1102. e = newe
  1103. args[i] = (e, c)
  1104. # restore kwargs flag
  1105. if doit is not None:
  1106. kwargs['doit'] = doit
  1107. return Piecewise(*args)
  1108. def _piecewise_collapse_arguments(_args):
  1109. newargs = [] # the unevaluated conditions
  1110. current_cond = set() # the conditions up to a given e, c pair
  1111. for expr, cond in _args:
  1112. cond = cond.replace(
  1113. lambda _: _.is_Relational, _canonical_coeff)
  1114. # Check here if expr is a Piecewise and collapse if one of
  1115. # the conds in expr matches cond. This allows the collapsing
  1116. # of Piecewise((Piecewise((x,x<0)),x<0)) to Piecewise((x,x<0)).
  1117. # This is important when using piecewise_fold to simplify
  1118. # multiple Piecewise instances having the same conds.
  1119. # Eventually, this code should be able to collapse Piecewise's
  1120. # having different intervals, but this will probably require
  1121. # using the new assumptions.
  1122. if isinstance(expr, Piecewise):
  1123. unmatching = []
  1124. for i, (e, c) in enumerate(expr.args):
  1125. if c in current_cond:
  1126. # this would already have triggered
  1127. continue
  1128. if c == cond:
  1129. if c != True:
  1130. # nothing past this condition will ever
  1131. # trigger and only those args before this
  1132. # that didn't match a previous condition
  1133. # could possibly trigger
  1134. if unmatching:
  1135. expr = Piecewise(*(
  1136. unmatching + [(e, c)]))
  1137. else:
  1138. expr = e
  1139. break
  1140. else:
  1141. unmatching.append((e, c))
  1142. # check for condition repeats
  1143. got = False
  1144. # -- if an And contains a condition that was
  1145. # already encountered, then the And will be
  1146. # False: if the previous condition was False
  1147. # then the And will be False and if the previous
  1148. # condition is True then then we wouldn't get to
  1149. # this point. In either case, we can skip this condition.
  1150. for i in ([cond] +
  1151. (list(cond.args) if isinstance(cond, And) else
  1152. [])):
  1153. if i in current_cond:
  1154. got = True
  1155. break
  1156. if got:
  1157. continue
  1158. # -- if not(c) is already in current_cond then c is
  1159. # a redundant condition in an And. This does not
  1160. # apply to Or, however: (e1, c), (e2, Or(~c, d))
  1161. # is not (e1, c), (e2, d) because if c and d are
  1162. # both False this would give no results when the
  1163. # true answer should be (e2, True)
  1164. if isinstance(cond, And):
  1165. nonredundant = []
  1166. for c in cond.args:
  1167. if isinstance(c, Relational):
  1168. if c.negated.canonical in current_cond:
  1169. continue
  1170. # if a strict inequality appears after
  1171. # a non-strict one, then the condition is
  1172. # redundant
  1173. if isinstance(c, (Lt, Gt)) and (
  1174. c.weak in current_cond):
  1175. cond = False
  1176. break
  1177. nonredundant.append(c)
  1178. else:
  1179. cond = cond.func(*nonredundant)
  1180. elif isinstance(cond, Relational):
  1181. if cond.negated.canonical in current_cond:
  1182. cond = S.true
  1183. current_cond.add(cond)
  1184. # collect successive e,c pairs when exprs or cond match
  1185. if newargs:
  1186. if newargs[-1].expr == expr:
  1187. orcond = Or(cond, newargs[-1].cond)
  1188. if isinstance(orcond, (And, Or)):
  1189. orcond = distribute_and_over_or(orcond)
  1190. newargs[-1] = ExprCondPair(expr, orcond)
  1191. continue
  1192. elif newargs[-1].cond == cond:
  1193. continue
  1194. newargs.append(ExprCondPair(expr, cond))
  1195. return newargs
  1196. _blessed = lambda e: getattr(e.lhs, '_diff_wrt', False) and (
  1197. getattr(e.rhs, '_diff_wrt', None) or
  1198. isinstance(e.rhs, (Rational, NumberSymbol)))
  1199. def piecewise_simplify(expr, **kwargs):
  1200. expr = piecewise_simplify_arguments(expr, **kwargs)
  1201. if not isinstance(expr, Piecewise):
  1202. return expr
  1203. args = list(expr.args)
  1204. args = _piecewise_simplify_eq_and(args)
  1205. args = _piecewise_simplify_equal_to_next_segment(args)
  1206. return Piecewise(*args)
  1207. def _piecewise_simplify_equal_to_next_segment(args):
  1208. """
  1209. See if expressions valid for an Equal expression happens to evaluate
  1210. to the same function as in the next piecewise segment, see:
  1211. https://github.com/sympy/sympy/issues/8458
  1212. """
  1213. prevexpr = None
  1214. for i, (expr, cond) in reversed(list(enumerate(args))):
  1215. if prevexpr is not None:
  1216. if isinstance(cond, And):
  1217. eqs, other = sift(cond.args,
  1218. lambda i: isinstance(i, Eq), binary=True)
  1219. elif isinstance(cond, Eq):
  1220. eqs, other = [cond], []
  1221. else:
  1222. eqs = other = []
  1223. _prevexpr = prevexpr
  1224. _expr = expr
  1225. if eqs and not other:
  1226. eqs = list(ordered(eqs))
  1227. for e in eqs:
  1228. # allow 2 args to collapse into 1 for any e
  1229. # otherwise limit simplification to only simple-arg
  1230. # Eq instances
  1231. if len(args) == 2 or _blessed(e):
  1232. _prevexpr = _prevexpr.subs(*e.args)
  1233. _expr = _expr.subs(*e.args)
  1234. # Did it evaluate to the same?
  1235. if _prevexpr == _expr:
  1236. # Set the expression for the Not equal section to the same
  1237. # as the next. These will be merged when creating the new
  1238. # Piecewise
  1239. args[i] = args[i].func(args[i + 1][0], cond)
  1240. else:
  1241. # Update the expression that we compare against
  1242. prevexpr = expr
  1243. else:
  1244. prevexpr = expr
  1245. return args
  1246. def _piecewise_simplify_eq_and(args):
  1247. """
  1248. Try to simplify conditions and the expression for
  1249. equalities that are part of the condition, e.g.
  1250. Piecewise((n, And(Eq(n,0), Eq(n + m, 0))), (1, True))
  1251. -> Piecewise((0, And(Eq(n, 0), Eq(m, 0))), (1, True))
  1252. """
  1253. for i, (expr, cond) in enumerate(args):
  1254. if isinstance(cond, And):
  1255. eqs, other = sift(cond.args,
  1256. lambda i: isinstance(i, Eq), binary=True)
  1257. elif isinstance(cond, Eq):
  1258. eqs, other = [cond], []
  1259. else:
  1260. eqs = other = []
  1261. if eqs:
  1262. eqs = list(ordered(eqs))
  1263. for j, e in enumerate(eqs):
  1264. # these blessed lhs objects behave like Symbols
  1265. # and the rhs are simple replacements for the "symbols"
  1266. if _blessed(e):
  1267. expr = expr.subs(*e.args)
  1268. eqs[j + 1:] = [ei.subs(*e.args) for ei in eqs[j + 1:]]
  1269. other = [ei.subs(*e.args) for ei in other]
  1270. cond = And(*(eqs + other))
  1271. args[i] = args[i].func(expr, cond)
  1272. return args
  1273. def piecewise_exclusive(expr, *, skip_nan=False, deep=True):
  1274. """
  1275. Rewrite :class:`Piecewise` with mutually exclusive conditions.
  1276. Explanation
  1277. ===========
  1278. SymPy represents the conditions of a :class:`Piecewise` in an
  1279. "if-elif"-fashion, allowing more than one condition to be simultaneously
  1280. True. The interpretation is that the first condition that is True is the
  1281. case that holds. While this is a useful representation computationally it
  1282. is not how a piecewise formula is typically shown in a mathematical text.
  1283. The :func:`piecewise_exclusive` function can be used to rewrite any
  1284. :class:`Piecewise` with more typical mutually exclusive conditions.
  1285. Note that further manipulation of the resulting :class:`Piecewise`, e.g.
  1286. simplifying it, will most likely make it non-exclusive. Hence, this is
  1287. primarily a function to be used in conjunction with printing the Piecewise
  1288. or if one would like to reorder the expression-condition pairs.
  1289. If it is not possible to determine that all possibilities are covered by
  1290. the different cases of the :class:`Piecewise` then a final
  1291. :class:`~sympy.core.numbers.NaN` case will be included explicitly. This
  1292. can be prevented by passing ``skip_nan=True``.
  1293. Examples
  1294. ========
  1295. >>> from sympy import piecewise_exclusive, Symbol, Piecewise, S
  1296. >>> x = Symbol('x', real=True)
  1297. >>> p = Piecewise((0, x < 0), (S.Half, x <= 0), (1, True))
  1298. >>> piecewise_exclusive(p)
  1299. Piecewise((0, x < 0), (1/2, Eq(x, 0)), (1, x > 0))
  1300. >>> piecewise_exclusive(Piecewise((2, x > 1)))
  1301. Piecewise((2, x > 1), (nan, x <= 1))
  1302. >>> piecewise_exclusive(Piecewise((2, x > 1)), skip_nan=True)
  1303. Piecewise((2, x > 1))
  1304. Parameters
  1305. ==========
  1306. expr: a SymPy expression.
  1307. Any :class:`Piecewise` in the expression will be rewritten.
  1308. skip_nan: ``bool`` (default ``False``)
  1309. If ``skip_nan`` is set to ``True`` then a final
  1310. :class:`~sympy.core.numbers.NaN` case will not be included.
  1311. deep: ``bool`` (default ``True``)
  1312. If ``deep`` is ``True`` then :func:`piecewise_exclusive` will rewrite
  1313. any :class:`Piecewise` subexpressions in ``expr`` rather than just
  1314. rewriting ``expr`` itself.
  1315. Returns
  1316. =======
  1317. An expression equivalent to ``expr`` but where all :class:`Piecewise` have
  1318. been rewritten with mutually exclusive conditions.
  1319. See Also
  1320. ========
  1321. Piecewise
  1322. piecewise_fold
  1323. """
  1324. def make_exclusive(*pwargs):
  1325. cumcond = false
  1326. newargs = []
  1327. # Handle the first n-1 cases
  1328. for expr_i, cond_i in pwargs[:-1]:
  1329. cancond = And(cond_i, Not(cumcond)).simplify()
  1330. cumcond = Or(cond_i, cumcond).simplify()
  1331. newargs.append((expr_i, cancond))
  1332. # For the nth case defer simplification of cumcond
  1333. expr_n, cond_n = pwargs[-1]
  1334. cancond_n = And(cond_n, Not(cumcond)).simplify()
  1335. newargs.append((expr_n, cancond_n))
  1336. if not skip_nan:
  1337. cumcond = Or(cond_n, cumcond).simplify()
  1338. if cumcond is not true:
  1339. newargs.append((Undefined, Not(cumcond).simplify()))
  1340. return Piecewise(*newargs, evaluate=False)
  1341. if deep:
  1342. return expr.replace(Piecewise, make_exclusive)
  1343. elif isinstance(expr, Piecewise):
  1344. return make_exclusive(*expr.args)
  1345. else:
  1346. return expr