piecewise.py 52 KB

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