sets.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804
  1. from __future__ import annotations
  2. from typing import Any, Callable, TYPE_CHECKING, overload
  3. from functools import reduce
  4. from collections import defaultdict
  5. from collections.abc import Mapping, Iterable
  6. import inspect
  7. from sympy.core.kind import Kind, UndefinedKind, NumberKind
  8. from sympy.core.basic import Basic
  9. from sympy.core.containers import Tuple, TupleKind
  10. from sympy.core.decorators import sympify_method_args, sympify_return
  11. from sympy.core.evalf import EvalfMixin
  12. from sympy.core.expr import Expr
  13. from sympy.core.function import Lambda
  14. from sympy.core.logic import (FuzzyBool, fuzzy_bool, fuzzy_or, fuzzy_and,
  15. fuzzy_not)
  16. from sympy.core.numbers import Float, Integer
  17. from sympy.core.operations import LatticeOp
  18. from sympy.core.parameters import global_parameters
  19. from sympy.core.relational import Eq, Ne, is_lt
  20. from sympy.core.singleton import Singleton, S
  21. from sympy.core.sorting import ordered
  22. from sympy.core.symbol import symbols, Symbol, Dummy, uniquely_named_symbol
  23. from sympy.core.sympify import _sympify, sympify, _sympy_converter
  24. from sympy.functions.elementary.exponential import exp, log
  25. from sympy.functions.elementary.miscellaneous import Max, Min
  26. from sympy.logic.boolalg import And, Or, Not, Xor, true, false
  27. from sympy.utilities.decorator import deprecated
  28. from sympy.utilities.exceptions import sympy_deprecation_warning
  29. from sympy.utilities.iterables import (iproduct, sift, roundrobin, iterable,
  30. subsets)
  31. from sympy.utilities.misc import func_name, filldedent
  32. from mpmath import mpi, mpf
  33. from mpmath.libmp.libmpf import prec_to_dps
  34. tfn = defaultdict(lambda: None, {
  35. True: S.true,
  36. S.true: S.true,
  37. False: S.false,
  38. S.false: S.false})
  39. @sympify_method_args
  40. class Set(Basic, EvalfMixin):
  41. """
  42. The base class for any kind of set.
  43. Explanation
  44. ===========
  45. This is not meant to be used directly as a container of items. It does not
  46. behave like the builtin ``set``; see :class:`FiniteSet` for that.
  47. Real intervals are represented by the :class:`Interval` class and unions of
  48. sets by the :class:`Union` class. The empty set is represented by the
  49. :class:`EmptySet` class and available as a singleton as ``S.EmptySet``.
  50. """
  51. __slots__: tuple[()] = ()
  52. is_number = False
  53. is_iterable = False
  54. is_interval = False
  55. is_FiniteSet = False
  56. is_Interval = False
  57. is_ProductSet = False
  58. is_Union = False
  59. is_Intersection: FuzzyBool = None
  60. is_UniversalSet: FuzzyBool = None
  61. is_Complement: FuzzyBool = None
  62. is_ComplexRegion = False
  63. is_empty: FuzzyBool = None
  64. is_finite_set: FuzzyBool = None
  65. @property # type: ignore
  66. @deprecated(
  67. """
  68. The is_EmptySet attribute of Set objects is deprecated.
  69. Use 's is S.EmptySet" or 's.is_empty' instead.
  70. """,
  71. deprecated_since_version="1.5",
  72. active_deprecations_target="deprecated-is-emptyset",
  73. )
  74. def is_EmptySet(self):
  75. return None
  76. if TYPE_CHECKING:
  77. def __new__(cls, *args: Basic | complex) -> Set:
  78. ...
  79. @overload # type: ignore
  80. def subs(self, arg1: Mapping[Basic | complex, Set | complex], arg2: None=None) -> Set: ...
  81. @overload
  82. def subs(self, arg1: Iterable[tuple[Basic | complex, Set | complex]], arg2: None=None, **kwargs: Any) -> Set: ...
  83. @overload
  84. def subs(self, arg1: Set | complex, arg2: Set | complex) -> Set: ...
  85. @overload
  86. def subs(self, arg1: Mapping[Basic | complex, Basic | complex], arg2: None=None, **kwargs: Any) -> Basic: ...
  87. @overload
  88. def subs(self, arg1: Iterable[tuple[Basic | complex, Basic | complex]], arg2: None=None, **kwargs: Any) -> Basic: ...
  89. @overload
  90. def subs(self, arg1: Basic | complex, arg2: Basic | complex, **kwargs: Any) -> Basic: ...
  91. def subs(self, arg1: Mapping[Basic | complex, Basic | complex] | Basic | complex, # type: ignore
  92. arg2: Basic | complex | None = None, **kwargs: Any) -> Basic:
  93. ...
  94. def simplify(self, **kwargs) -> Set:
  95. assert False
  96. def evalf(self, n: int = 15, subs: dict[Basic, Basic | float] | None = None,
  97. maxn: int = 100, chop: bool = False, strict: bool = False,
  98. quad: str | None = None, verbose: bool = False) -> Set:
  99. ...
  100. n = evalf
  101. @staticmethod
  102. def _infimum_key(expr):
  103. """
  104. Return infimum (if possible) else S.Infinity.
  105. """
  106. try:
  107. infimum = expr.inf
  108. assert infimum.is_comparable
  109. infimum = infimum.evalf() # issue #18505
  110. except (NotImplementedError,
  111. AttributeError, AssertionError, ValueError):
  112. infimum = S.Infinity
  113. return infimum
  114. def union(self, other):
  115. """
  116. Returns the union of ``self`` and ``other``.
  117. Examples
  118. ========
  119. As a shortcut it is possible to use the ``+`` operator:
  120. >>> from sympy import Interval, FiniteSet
  121. >>> Interval(0, 1).union(Interval(2, 3))
  122. Union(Interval(0, 1), Interval(2, 3))
  123. >>> Interval(0, 1) + Interval(2, 3)
  124. Union(Interval(0, 1), Interval(2, 3))
  125. >>> Interval(1, 2, True, True) + FiniteSet(2, 3)
  126. Union({3}, Interval.Lopen(1, 2))
  127. Similarly it is possible to use the ``-`` operator for set differences:
  128. >>> Interval(0, 2) - Interval(0, 1)
  129. Interval.Lopen(1, 2)
  130. >>> Interval(1, 3) - FiniteSet(2)
  131. Union(Interval.Ropen(1, 2), Interval.Lopen(2, 3))
  132. """
  133. return Union(self, other)
  134. def intersect(self, other):
  135. """
  136. Returns the intersection of 'self' and 'other'.
  137. Examples
  138. ========
  139. >>> from sympy import Interval
  140. >>> Interval(1, 3).intersect(Interval(1, 2))
  141. Interval(1, 2)
  142. >>> from sympy import imageset, Lambda, symbols, S
  143. >>> n, m = symbols('n m')
  144. >>> a = imageset(Lambda(n, 2*n), S.Integers)
  145. >>> a.intersect(imageset(Lambda(m, 2*m + 1), S.Integers))
  146. EmptySet
  147. """
  148. return Intersection(self, other)
  149. def intersection(self, other):
  150. """
  151. Alias for :meth:`intersect()`
  152. """
  153. return self.intersect(other)
  154. def is_disjoint(self, other):
  155. """
  156. Returns True if ``self`` and ``other`` are disjoint.
  157. Examples
  158. ========
  159. >>> from sympy import Interval
  160. >>> Interval(0, 2).is_disjoint(Interval(1, 2))
  161. False
  162. >>> Interval(0, 2).is_disjoint(Interval(3, 4))
  163. True
  164. References
  165. ==========
  166. .. [1] https://en.wikipedia.org/wiki/Disjoint_sets
  167. """
  168. return self.intersect(other) == S.EmptySet
  169. def isdisjoint(self, other):
  170. """
  171. Alias for :meth:`is_disjoint()`
  172. """
  173. return self.is_disjoint(other)
  174. def complement(self, universe):
  175. r"""
  176. The complement of 'self' w.r.t the given universe.
  177. Examples
  178. ========
  179. >>> from sympy import Interval, S
  180. >>> Interval(0, 1).complement(S.Reals)
  181. Union(Interval.open(-oo, 0), Interval.open(1, oo))
  182. >>> Interval(0, 1).complement(S.UniversalSet)
  183. Complement(UniversalSet, Interval(0, 1))
  184. """
  185. return Complement(universe, self)
  186. def _complement(self, other):
  187. # this behaves as other - self
  188. if isinstance(self, ProductSet) and isinstance(other, ProductSet):
  189. # If self and other are disjoint then other - self == self
  190. if len(self.sets) != len(other.sets):
  191. return other
  192. # There can be other ways to represent this but this gives:
  193. # (A x B) - (C x D) = ((A - C) x B) U (A x (B - D))
  194. overlaps = []
  195. pairs = list(zip(self.sets, other.sets))
  196. for n in range(len(pairs)):
  197. sets = (o if i != n else o-s for i, (s, o) in enumerate(pairs))
  198. overlaps.append(ProductSet(*sets))
  199. return Union(*overlaps)
  200. elif isinstance(other, Interval):
  201. if isinstance(self, (Interval, FiniteSet)):
  202. return Intersection(other, self.complement(S.Reals))
  203. elif isinstance(other, Union):
  204. return Union(*(o - self for o in other.args))
  205. elif isinstance(other, Complement):
  206. return Complement(other.args[0], Union(other.args[1], self), evaluate=False)
  207. elif other is S.EmptySet:
  208. return S.EmptySet
  209. elif isinstance(other, FiniteSet):
  210. sifted = sift(other, lambda x: fuzzy_bool(self.contains(x)))
  211. # ignore those that are contained in self
  212. return Union(FiniteSet(*(sifted[False])),
  213. Complement(FiniteSet(*(sifted[None])), self, evaluate=False)
  214. if sifted[None] else S.EmptySet)
  215. def symmetric_difference(self, other):
  216. """
  217. Returns symmetric difference of ``self`` and ``other``.
  218. Examples
  219. ========
  220. >>> from sympy import Interval, S
  221. >>> Interval(1, 3).symmetric_difference(S.Reals)
  222. Union(Interval.open(-oo, 1), Interval.open(3, oo))
  223. >>> Interval(1, 10).symmetric_difference(S.Reals)
  224. Union(Interval.open(-oo, 1), Interval.open(10, oo))
  225. >>> from sympy import S, EmptySet
  226. >>> S.Reals.symmetric_difference(EmptySet)
  227. Reals
  228. References
  229. ==========
  230. .. [1] https://en.wikipedia.org/wiki/Symmetric_difference
  231. """
  232. return SymmetricDifference(self, other)
  233. def _symmetric_difference(self, other):
  234. return Union(Complement(self, other), Complement(other, self))
  235. @property
  236. def inf(self):
  237. """
  238. The infimum of ``self``.
  239. Examples
  240. ========
  241. >>> from sympy import Interval, Union
  242. >>> Interval(0, 1).inf
  243. 0
  244. >>> Union(Interval(0, 1), Interval(2, 3)).inf
  245. 0
  246. """
  247. return self._inf
  248. @property
  249. def _inf(self):
  250. raise NotImplementedError("(%s)._inf" % self)
  251. @property
  252. def sup(self):
  253. """
  254. The supremum of ``self``.
  255. Examples
  256. ========
  257. >>> from sympy import Interval, Union
  258. >>> Interval(0, 1).sup
  259. 1
  260. >>> Union(Interval(0, 1), Interval(2, 3)).sup
  261. 3
  262. """
  263. return self._sup
  264. @property
  265. def _sup(self):
  266. raise NotImplementedError("(%s)._sup" % self)
  267. def contains(self, other):
  268. """
  269. Returns a SymPy value indicating whether ``other`` is contained
  270. in ``self``: ``true`` if it is, ``false`` if it is not, else
  271. an unevaluated ``Contains`` expression (or, as in the case of
  272. ConditionSet and a union of FiniteSet/Intervals, an expression
  273. indicating the conditions for containment).
  274. Examples
  275. ========
  276. >>> from sympy import Interval, S
  277. >>> from sympy.abc import x
  278. >>> Interval(0, 1).contains(0.5)
  279. True
  280. As a shortcut it is possible to use the ``in`` operator, but that
  281. will raise an error unless an affirmative true or false is not
  282. obtained.
  283. >>> Interval(0, 1).contains(x)
  284. (0 <= x) & (x <= 1)
  285. >>> x in Interval(0, 1)
  286. Traceback (most recent call last):
  287. ...
  288. TypeError: did not evaluate to a bool: None
  289. The result of 'in' is a bool, not a SymPy value
  290. >>> 1 in Interval(0, 2)
  291. True
  292. >>> _ is S.true
  293. False
  294. """
  295. from .contains import Contains
  296. other = sympify(other, strict=True)
  297. c = self._contains(other)
  298. if isinstance(c, Contains):
  299. return c
  300. if c is None:
  301. return Contains(other, self, evaluate=False)
  302. b = tfn[c]
  303. if b is None:
  304. return c
  305. return b
  306. def _contains(self, other):
  307. """Test if ``other`` is an element of the set ``self``.
  308. This is an internal method that is expected to be overridden by
  309. subclasses of ``Set`` and will be called by the public
  310. :func:`Set.contains` method or the :class:`Contains` expression.
  311. Parameters
  312. ==========
  313. other: Sympified :class:`Basic` instance
  314. The object whose membership in ``self`` is to be tested.
  315. Returns
  316. =======
  317. Symbolic :class:`Boolean` or ``None``.
  318. A return value of ``None`` indicates that it is unknown whether
  319. ``other`` is contained in ``self``. Returning ``None`` from here
  320. ensures that ``self.contains(other)`` or ``Contains(self, other)`` will
  321. return an unevaluated :class:`Contains` expression.
  322. If not ``None`` then the returned value is a :class:`Boolean` that is
  323. logically equivalent to the statement that ``other`` is an element of
  324. ``self``. Usually this would be either ``S.true`` or ``S.false`` but
  325. not always.
  326. """
  327. raise NotImplementedError(f"{type(self).__name__}._contains")
  328. def is_subset(self, other):
  329. """
  330. Returns True if ``self`` is a subset of ``other``.
  331. Examples
  332. ========
  333. >>> from sympy import Interval
  334. >>> Interval(0, 0.5).is_subset(Interval(0, 1))
  335. True
  336. >>> Interval(0, 1).is_subset(Interval(0, 1, left_open=True))
  337. False
  338. """
  339. if not isinstance(other, Set):
  340. raise ValueError("Unknown argument '%s'" % other)
  341. # Handle the trivial cases
  342. if self == other:
  343. return True
  344. is_empty = self.is_empty
  345. if is_empty is True:
  346. return True
  347. elif fuzzy_not(is_empty) and other.is_empty:
  348. return False
  349. if self.is_finite_set is False and other.is_finite_set:
  350. return False
  351. # Dispatch on subclass rules
  352. ret = self._eval_is_subset(other)
  353. if ret is not None:
  354. return ret
  355. ret = other._eval_is_superset(self)
  356. if ret is not None:
  357. return ret
  358. # Use pairwise rules from multiple dispatch
  359. from sympy.sets.handlers.issubset import is_subset_sets
  360. ret = is_subset_sets(self, other)
  361. if ret is not None:
  362. return ret
  363. # Fall back on computing the intersection
  364. # XXX: We shouldn't do this. A query like this should be handled
  365. # without evaluating new Set objects. It should be the other way round
  366. # so that the intersect method uses is_subset for evaluation.
  367. if self.intersect(other) == self:
  368. return True
  369. def _eval_is_subset(self, other):
  370. '''Returns a fuzzy bool for whether self is a subset of other.'''
  371. return None
  372. def _eval_is_superset(self, other):
  373. '''Returns a fuzzy bool for whether self is a subset of other.'''
  374. return None
  375. # This should be deprecated:
  376. def issubset(self, other):
  377. """
  378. Alias for :meth:`is_subset()`
  379. """
  380. return self.is_subset(other)
  381. def is_proper_subset(self, other):
  382. """
  383. Returns True if ``self`` is a proper subset of ``other``.
  384. Examples
  385. ========
  386. >>> from sympy import Interval
  387. >>> Interval(0, 0.5).is_proper_subset(Interval(0, 1))
  388. True
  389. >>> Interval(0, 1).is_proper_subset(Interval(0, 1))
  390. False
  391. """
  392. if isinstance(other, Set):
  393. return self != other and self.is_subset(other)
  394. else:
  395. raise ValueError("Unknown argument '%s'" % other)
  396. def is_superset(self, other):
  397. """
  398. Returns True if ``self`` is a superset of ``other``.
  399. Examples
  400. ========
  401. >>> from sympy import Interval
  402. >>> Interval(0, 0.5).is_superset(Interval(0, 1))
  403. False
  404. >>> Interval(0, 1).is_superset(Interval(0, 1, left_open=True))
  405. True
  406. """
  407. if isinstance(other, Set):
  408. return other.is_subset(self)
  409. else:
  410. raise ValueError("Unknown argument '%s'" % other)
  411. # This should be deprecated:
  412. def issuperset(self, other):
  413. """
  414. Alias for :meth:`is_superset()`
  415. """
  416. return self.is_superset(other)
  417. def is_proper_superset(self, other):
  418. """
  419. Returns True if ``self`` is a proper superset of ``other``.
  420. Examples
  421. ========
  422. >>> from sympy import Interval
  423. >>> Interval(0, 1).is_proper_superset(Interval(0, 0.5))
  424. True
  425. >>> Interval(0, 1).is_proper_superset(Interval(0, 1))
  426. False
  427. """
  428. if isinstance(other, Set):
  429. return self != other and self.is_superset(other)
  430. else:
  431. raise ValueError("Unknown argument '%s'" % other)
  432. def _eval_powerset(self):
  433. from .powerset import PowerSet
  434. return PowerSet(self)
  435. def powerset(self):
  436. """
  437. Find the Power set of ``self``.
  438. Examples
  439. ========
  440. >>> from sympy import EmptySet, FiniteSet, Interval
  441. A power set of an empty set:
  442. >>> A = EmptySet
  443. >>> A.powerset()
  444. {EmptySet}
  445. A power set of a finite set:
  446. >>> A = FiniteSet(1, 2)
  447. >>> a, b, c = FiniteSet(1), FiniteSet(2), FiniteSet(1, 2)
  448. >>> A.powerset() == FiniteSet(a, b, c, EmptySet)
  449. True
  450. A power set of an interval:
  451. >>> Interval(1, 2).powerset()
  452. PowerSet(Interval(1, 2))
  453. References
  454. ==========
  455. .. [1] https://en.wikipedia.org/wiki/Power_set
  456. """
  457. return self._eval_powerset()
  458. @property
  459. def measure(self):
  460. """
  461. The (Lebesgue) measure of ``self``.
  462. Examples
  463. ========
  464. >>> from sympy import Interval, Union
  465. >>> Interval(0, 1).measure
  466. 1
  467. >>> Union(Interval(0, 1), Interval(2, 3)).measure
  468. 2
  469. """
  470. return self._measure
  471. @property
  472. def kind(self):
  473. """
  474. The kind of a Set
  475. Explanation
  476. ===========
  477. Any :class:`Set` will have kind :class:`SetKind` which is
  478. parametrised by the kind of the elements of the set. For example
  479. most sets are sets of numbers and will have kind
  480. ``SetKind(NumberKind)``. If elements of sets are different in kind than
  481. their kind will ``SetKind(UndefinedKind)``. See
  482. :class:`sympy.core.kind.Kind` for an explanation of the kind system.
  483. Examples
  484. ========
  485. >>> from sympy import Interval, Matrix, FiniteSet, EmptySet, ProductSet, PowerSet
  486. >>> FiniteSet(Matrix([1, 2])).kind
  487. SetKind(MatrixKind(NumberKind))
  488. >>> Interval(1, 2).kind
  489. SetKind(NumberKind)
  490. >>> EmptySet.kind
  491. SetKind()
  492. A :class:`sympy.sets.powerset.PowerSet` is a set of sets:
  493. >>> PowerSet({1, 2, 3}).kind
  494. SetKind(SetKind(NumberKind))
  495. A :class:`ProductSet` represents the set of tuples of elements of
  496. other sets. Its kind is :class:`sympy.core.containers.TupleKind`
  497. parametrised by the kinds of the elements of those sets:
  498. >>> p = ProductSet(FiniteSet(1, 2), FiniteSet(3, 4))
  499. >>> list(p)
  500. [(1, 3), (2, 3), (1, 4), (2, 4)]
  501. >>> p.kind
  502. SetKind(TupleKind(NumberKind, NumberKind))
  503. When all elements of the set do not have same kind, the kind
  504. will be returned as ``SetKind(UndefinedKind)``:
  505. >>> FiniteSet(0, Matrix([1, 2])).kind
  506. SetKind(UndefinedKind)
  507. The kind of the elements of a set are given by the ``element_kind``
  508. attribute of ``SetKind``:
  509. >>> Interval(1, 2).kind.element_kind
  510. NumberKind
  511. See Also
  512. ========
  513. NumberKind
  514. sympy.core.kind.UndefinedKind
  515. sympy.core.containers.TupleKind
  516. MatrixKind
  517. sympy.matrices.expressions.sets.MatrixSet
  518. sympy.sets.conditionset.ConditionSet
  519. Rationals
  520. Naturals
  521. Integers
  522. sympy.sets.fancysets.ImageSet
  523. sympy.sets.fancysets.Range
  524. sympy.sets.fancysets.ComplexRegion
  525. sympy.sets.powerset.PowerSet
  526. sympy.sets.sets.ProductSet
  527. sympy.sets.sets.Interval
  528. sympy.sets.sets.Union
  529. sympy.sets.sets.Intersection
  530. sympy.sets.sets.Complement
  531. sympy.sets.sets.EmptySet
  532. sympy.sets.sets.UniversalSet
  533. sympy.sets.sets.FiniteSet
  534. sympy.sets.sets.SymmetricDifference
  535. sympy.sets.sets.DisjointUnion
  536. """
  537. return self._kind()
  538. @property
  539. def boundary(self):
  540. """
  541. The boundary or frontier of a set.
  542. Explanation
  543. ===========
  544. A point x is on the boundary of a set S if
  545. 1. x is in the closure of S.
  546. I.e. Every neighborhood of x contains a point in S.
  547. 2. x is not in the interior of S.
  548. I.e. There does not exist an open set centered on x contained
  549. entirely within S.
  550. There are the points on the outer rim of S. If S is open then these
  551. points need not actually be contained within S.
  552. For example, the boundary of an interval is its start and end points.
  553. This is true regardless of whether or not the interval is open.
  554. Examples
  555. ========
  556. >>> from sympy import Interval
  557. >>> Interval(0, 1).boundary
  558. {0, 1}
  559. >>> Interval(0, 1, True, False).boundary
  560. {0, 1}
  561. """
  562. return self._boundary
  563. @property
  564. def is_open(self):
  565. """
  566. Property method to check whether a set is open.
  567. Explanation
  568. ===========
  569. A set is open if and only if it has an empty intersection with its
  570. boundary. In particular, a subset A of the reals is open if and only
  571. if each one of its points is contained in an open interval that is a
  572. subset of A.
  573. Examples
  574. ========
  575. >>> from sympy import S
  576. >>> S.Reals.is_open
  577. True
  578. >>> S.Rationals.is_open
  579. False
  580. """
  581. return Intersection(self, self.boundary).is_empty
  582. @property
  583. def is_closed(self):
  584. """
  585. A property method to check whether a set is closed.
  586. Explanation
  587. ===========
  588. A set is closed if its complement is an open set. The closedness of a
  589. subset of the reals is determined with respect to R and its standard
  590. topology.
  591. Examples
  592. ========
  593. >>> from sympy import Interval
  594. >>> Interval(0, 1).is_closed
  595. True
  596. """
  597. return self.boundary.is_subset(self)
  598. @property
  599. def closure(self):
  600. """
  601. Property method which returns the closure of a set.
  602. The closure is defined as the union of the set itself and its
  603. boundary.
  604. Examples
  605. ========
  606. >>> from sympy import S, Interval
  607. >>> S.Reals.closure
  608. Reals
  609. >>> Interval(0, 1).closure
  610. Interval(0, 1)
  611. """
  612. return self + self.boundary
  613. @property
  614. def interior(self):
  615. """
  616. Property method which returns the interior of a set.
  617. The interior of a set S consists all points of S that do not
  618. belong to the boundary of S.
  619. Examples
  620. ========
  621. >>> from sympy import Interval
  622. >>> Interval(0, 1).interior
  623. Interval.open(0, 1)
  624. >>> Interval(0, 1).boundary.interior
  625. EmptySet
  626. """
  627. return self - self.boundary
  628. @property
  629. def _boundary(self):
  630. raise NotImplementedError()
  631. @property
  632. def _measure(self):
  633. raise NotImplementedError("(%s)._measure" % self)
  634. def _kind(self):
  635. return SetKind(UndefinedKind)
  636. def _eval_evalf(self, prec):
  637. dps = prec_to_dps(prec)
  638. return self.func(*[arg.evalf(n=dps) for arg in self.args])
  639. @sympify_return([('other', 'Set')], NotImplemented)
  640. def __add__(self, other):
  641. return self.union(other)
  642. @sympify_return([('other', 'Set')], NotImplemented)
  643. def __or__(self, other):
  644. return self.union(other)
  645. @sympify_return([('other', 'Set')], NotImplemented)
  646. def __and__(self, other):
  647. return self.intersect(other)
  648. @sympify_return([('other', 'Set')], NotImplemented)
  649. def __mul__(self, other):
  650. return ProductSet(self, other)
  651. @sympify_return([('other', 'Set')], NotImplemented)
  652. def __xor__(self, other):
  653. return SymmetricDifference(self, other)
  654. @sympify_return([('exp', Expr)], NotImplemented)
  655. def __pow__(self, exp):
  656. if not (exp.is_Integer and exp >= 0):
  657. raise ValueError("%s: Exponent must be a positive Integer" % exp)
  658. return ProductSet(*[self]*exp)
  659. @sympify_return([('other', 'Set')], NotImplemented)
  660. def __sub__(self, other):
  661. return Complement(self, other)
  662. def __contains__(self, other):
  663. other = _sympify(other)
  664. c = self._contains(other)
  665. b = tfn[c]
  666. if b is None:
  667. # x in y must evaluate to T or F; to entertain a None
  668. # result with Set use y.contains(x)
  669. raise TypeError('did not evaluate to a bool: %r' % c)
  670. return b
  671. class ProductSet(Set):
  672. """
  673. Represents a Cartesian Product of Sets.
  674. Explanation
  675. ===========
  676. Returns a Cartesian product given several sets as either an iterable
  677. or individual arguments.
  678. Can use ``*`` operator on any sets for convenient shorthand.
  679. Examples
  680. ========
  681. >>> from sympy import Interval, FiniteSet, ProductSet
  682. >>> I = Interval(0, 5); S = FiniteSet(1, 2, 3)
  683. >>> ProductSet(I, S)
  684. ProductSet(Interval(0, 5), {1, 2, 3})
  685. >>> (2, 2) in ProductSet(I, S)
  686. True
  687. >>> Interval(0, 1) * Interval(0, 1) # The unit square
  688. ProductSet(Interval(0, 1), Interval(0, 1))
  689. >>> coin = FiniteSet('H', 'T')
  690. >>> set(coin**2)
  691. {(H, H), (H, T), (T, H), (T, T)}
  692. The Cartesian product is not commutative or associative e.g.:
  693. >>> I*S == S*I
  694. False
  695. >>> (I*I)*I == I*(I*I)
  696. False
  697. Notes
  698. =====
  699. - Passes most operations down to the argument sets
  700. References
  701. ==========
  702. .. [1] https://en.wikipedia.org/wiki/Cartesian_product
  703. """
  704. is_ProductSet = True
  705. def __new__(cls, *sets, **assumptions):
  706. if len(sets) == 1 and iterable(sets[0]) and not isinstance(sets[0], (Set, set)):
  707. sympy_deprecation_warning(
  708. """
  709. ProductSet(iterable) is deprecated. Use ProductSet(*iterable) instead.
  710. """,
  711. deprecated_since_version="1.5",
  712. active_deprecations_target="deprecated-productset-iterable",
  713. )
  714. sets = tuple(sets[0])
  715. sets = [sympify(s) for s in sets]
  716. if not all(isinstance(s, Set) for s in sets):
  717. raise TypeError("Arguments to ProductSet should be of type Set")
  718. # Nullary product of sets is *not* the empty set
  719. if len(sets) == 0:
  720. return FiniteSet(())
  721. if S.EmptySet in sets:
  722. return S.EmptySet
  723. return Basic.__new__(cls, *sets, **assumptions)
  724. @property
  725. def sets(self):
  726. return self.args
  727. def flatten(self):
  728. def _flatten(sets):
  729. for s in sets:
  730. if s.is_ProductSet:
  731. yield from _flatten(s.sets)
  732. else:
  733. yield s
  734. return ProductSet(*_flatten(self.sets))
  735. def _contains(self, element):
  736. """
  737. ``in`` operator for ProductSets.
  738. Examples
  739. ========
  740. >>> from sympy import Interval
  741. >>> (2, 3) in Interval(0, 5) * Interval(0, 5)
  742. True
  743. >>> (10, 10) in Interval(0, 5) * Interval(0, 5)
  744. False
  745. Passes operation on to constituent sets
  746. """
  747. if element.is_Symbol:
  748. return None
  749. if not isinstance(element, Tuple) or len(element) != len(self.sets):
  750. return S.false
  751. return And(*[s.contains(e) for s, e in zip(self.sets, element)])
  752. def as_relational(self, *symbols):
  753. symbols = [_sympify(s) for s in symbols]
  754. if len(symbols) != len(self.sets) or not all(
  755. i.is_Symbol for i in symbols):
  756. raise ValueError(
  757. 'number of symbols must match the number of sets')
  758. return And(*[s.as_relational(i) for s, i in zip(self.sets, symbols)])
  759. @property
  760. def _boundary(self):
  761. return Union(*(ProductSet(*(b + b.boundary if i != j else b.boundary
  762. for j, b in enumerate(self.sets)))
  763. for i, a in enumerate(self.sets)))
  764. @property
  765. def is_iterable(self):
  766. """
  767. A property method which tests whether a set is iterable or not.
  768. Returns True if set is iterable, otherwise returns False.
  769. Examples
  770. ========
  771. >>> from sympy import FiniteSet, Interval
  772. >>> I = Interval(0, 1)
  773. >>> A = FiniteSet(1, 2, 3, 4, 5)
  774. >>> I.is_iterable
  775. False
  776. >>> A.is_iterable
  777. True
  778. """
  779. return all(set.is_iterable for set in self.sets)
  780. def __iter__(self):
  781. """
  782. A method which implements is_iterable property method.
  783. If self.is_iterable returns True (both constituent sets are iterable),
  784. then return the Cartesian Product. Otherwise, raise TypeError.
  785. """
  786. return iproduct(*self.sets)
  787. @property
  788. def is_empty(self):
  789. return fuzzy_or(s.is_empty for s in self.sets)
  790. @property
  791. def is_finite_set(self):
  792. all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
  793. return fuzzy_or([self.is_empty, all_finite])
  794. @property
  795. def _measure(self):
  796. measure = 1
  797. for s in self.sets:
  798. measure *= s.measure
  799. return measure
  800. def _kind(self):
  801. return SetKind(TupleKind(*(i.kind.element_kind for i in self.args)))
  802. def __len__(self):
  803. return reduce(lambda a, b: a*b, (len(s) for s in self.args))
  804. def __bool__(self):
  805. return all(self.sets)
  806. class Interval(Set):
  807. """
  808. Represents a real interval as a Set.
  809. Usage:
  810. Returns an interval with end points ``start`` and ``end``.
  811. For ``left_open=True`` (default ``left_open`` is ``False``) the interval
  812. will be open on the left. Similarly, for ``right_open=True`` the interval
  813. will be open on the right.
  814. Examples
  815. ========
  816. >>> from sympy import Symbol, Interval
  817. >>> Interval(0, 1)
  818. Interval(0, 1)
  819. >>> Interval.Ropen(0, 1)
  820. Interval.Ropen(0, 1)
  821. >>> Interval.Ropen(0, 1)
  822. Interval.Ropen(0, 1)
  823. >>> Interval.Lopen(0, 1)
  824. Interval.Lopen(0, 1)
  825. >>> Interval.open(0, 1)
  826. Interval.open(0, 1)
  827. >>> a = Symbol('a', real=True)
  828. >>> Interval(0, a)
  829. Interval(0, a)
  830. Notes
  831. =====
  832. - Only real end points are supported
  833. - ``Interval(a, b)`` with $a > b$ will return the empty set
  834. - Use the ``evalf()`` method to turn an Interval into an mpmath
  835. ``mpi`` interval instance
  836. References
  837. ==========
  838. .. [1] https://en.wikipedia.org/wiki/Interval_%28mathematics%29
  839. """
  840. is_Interval = True
  841. def __new__(cls, start, end, left_open=False, right_open=False):
  842. start = _sympify(start)
  843. end = _sympify(end)
  844. left_open = _sympify(left_open)
  845. right_open = _sympify(right_open)
  846. if not all(isinstance(a, (type(true), type(false)))
  847. for a in [left_open, right_open]):
  848. raise NotImplementedError(
  849. "left_open and right_open can have only true/false values, "
  850. "got %s and %s" % (left_open, right_open))
  851. # Only allow real intervals
  852. if fuzzy_not(fuzzy_and(i.is_extended_real for i in (start, end, end-start))):
  853. raise ValueError("Non-real intervals are not supported")
  854. # evaluate if possible
  855. if is_lt(end, start):
  856. return S.EmptySet
  857. elif (end - start).is_negative:
  858. return S.EmptySet
  859. if end == start and (left_open or right_open):
  860. return S.EmptySet
  861. if end == start and not (left_open or right_open):
  862. if start is S.Infinity or start is S.NegativeInfinity:
  863. return S.EmptySet
  864. return FiniteSet(end)
  865. # Make sure infinite interval end points are open.
  866. if start is S.NegativeInfinity:
  867. left_open = true
  868. if end is S.Infinity:
  869. right_open = true
  870. if start == S.Infinity or end == S.NegativeInfinity:
  871. return S.EmptySet
  872. return Basic.__new__(cls, start, end, left_open, right_open)
  873. @property
  874. def start(self):
  875. """
  876. The left end point of the interval.
  877. This property takes the same value as the ``inf`` property.
  878. Examples
  879. ========
  880. >>> from sympy import Interval
  881. >>> Interval(0, 1).start
  882. 0
  883. """
  884. return self._args[0]
  885. @property
  886. def end(self):
  887. """
  888. The right end point of the interval.
  889. This property takes the same value as the ``sup`` property.
  890. Examples
  891. ========
  892. >>> from sympy import Interval
  893. >>> Interval(0, 1).end
  894. 1
  895. """
  896. return self._args[1]
  897. @property
  898. def left_open(self):
  899. """
  900. True if interval is left-open.
  901. Examples
  902. ========
  903. >>> from sympy import Interval
  904. >>> Interval(0, 1, left_open=True).left_open
  905. True
  906. >>> Interval(0, 1, left_open=False).left_open
  907. False
  908. """
  909. return self._args[2]
  910. @property
  911. def right_open(self):
  912. """
  913. True if interval is right-open.
  914. Examples
  915. ========
  916. >>> from sympy import Interval
  917. >>> Interval(0, 1, right_open=True).right_open
  918. True
  919. >>> Interval(0, 1, right_open=False).right_open
  920. False
  921. """
  922. return self._args[3]
  923. @classmethod
  924. def open(cls, a, b):
  925. """Return an interval including neither boundary."""
  926. return cls(a, b, True, True)
  927. @classmethod
  928. def Lopen(cls, a, b):
  929. """Return an interval not including the left boundary."""
  930. return cls(a, b, True, False)
  931. @classmethod
  932. def Ropen(cls, a, b):
  933. """Return an interval not including the right boundary."""
  934. return cls(a, b, False, True)
  935. @property
  936. def _inf(self):
  937. return self.start
  938. @property
  939. def _sup(self):
  940. return self.end
  941. @property
  942. def left(self):
  943. return self.start
  944. @property
  945. def right(self):
  946. return self.end
  947. @property
  948. def is_empty(self):
  949. if self.left_open or self.right_open:
  950. cond = self.start >= self.end # One/both bounds open
  951. else:
  952. cond = self.start > self.end # Both bounds closed
  953. return fuzzy_bool(cond)
  954. @property
  955. def is_finite_set(self):
  956. return self.measure.is_zero
  957. def _complement(self, other):
  958. if other == S.Reals:
  959. a = Interval(S.NegativeInfinity, self.start,
  960. True, not self.left_open)
  961. b = Interval(self.end, S.Infinity, not self.right_open, True)
  962. return Union(a, b)
  963. if isinstance(other, FiniteSet):
  964. nums = [m for m in other.args if m.is_number]
  965. if nums == []:
  966. return None
  967. return Set._complement(self, other)
  968. @property
  969. def _boundary(self):
  970. finite_points = [p for p in (self.start, self.end)
  971. if abs(p) != S.Infinity]
  972. return FiniteSet(*finite_points)
  973. def _contains(self, other):
  974. if (not isinstance(other, Expr) or other is S.NaN
  975. or other.is_real is False or other.has(S.ComplexInfinity)):
  976. # if an expression has zoo it will be zoo or nan
  977. # and neither of those is real
  978. return false
  979. if self.start is S.NegativeInfinity and self.end is S.Infinity:
  980. if other.is_real is not None:
  981. return tfn[other.is_real]
  982. d = Dummy()
  983. return self.as_relational(d).subs(d, other)
  984. def as_relational(self, x):
  985. """Rewrite an interval in terms of inequalities and logic operators."""
  986. x = sympify(x)
  987. if self.right_open:
  988. right = x < self.end
  989. else:
  990. right = x <= self.end
  991. if self.left_open:
  992. left = self.start < x
  993. else:
  994. left = self.start <= x
  995. return And(left, right)
  996. @property
  997. def _measure(self):
  998. return self.end - self.start
  999. def _kind(self):
  1000. return SetKind(NumberKind)
  1001. def to_mpi(self, prec=53):
  1002. return mpi(mpf(self.start._eval_evalf(prec)),
  1003. mpf(self.end._eval_evalf(prec)))
  1004. def _eval_evalf(self, prec):
  1005. return Interval(self.left._evalf(prec), self.right._evalf(prec),
  1006. left_open=self.left_open, right_open=self.right_open)
  1007. def _is_comparable(self, other):
  1008. is_comparable = self.start.is_comparable
  1009. is_comparable &= self.end.is_comparable
  1010. is_comparable &= other.start.is_comparable
  1011. is_comparable &= other.end.is_comparable
  1012. return is_comparable
  1013. @property
  1014. def is_left_unbounded(self):
  1015. """Return ``True`` if the left endpoint is negative infinity. """
  1016. return self.left is S.NegativeInfinity or self.left == Float("-inf")
  1017. @property
  1018. def is_right_unbounded(self):
  1019. """Return ``True`` if the right endpoint is positive infinity. """
  1020. return self.right is S.Infinity or self.right == Float("+inf")
  1021. def _eval_Eq(self, other):
  1022. if not isinstance(other, Interval):
  1023. if isinstance(other, FiniteSet):
  1024. return false
  1025. elif isinstance(other, Set):
  1026. return None
  1027. return false
  1028. class Union(Set, LatticeOp):
  1029. """
  1030. Represents a union of sets as a :class:`Set`.
  1031. Examples
  1032. ========
  1033. >>> from sympy import Union, Interval
  1034. >>> Union(Interval(1, 2), Interval(3, 4))
  1035. Union(Interval(1, 2), Interval(3, 4))
  1036. The Union constructor will always try to merge overlapping intervals,
  1037. if possible. For example:
  1038. >>> Union(Interval(1, 2), Interval(2, 3))
  1039. Interval(1, 3)
  1040. See Also
  1041. ========
  1042. Intersection
  1043. References
  1044. ==========
  1045. .. [1] https://en.wikipedia.org/wiki/Union_%28set_theory%29
  1046. """
  1047. is_Union = True
  1048. @property
  1049. def identity(self):
  1050. return S.EmptySet
  1051. @property
  1052. def zero(self):
  1053. return S.UniversalSet
  1054. def __new__(cls, *args, **kwargs):
  1055. evaluate = kwargs.get('evaluate', global_parameters.evaluate)
  1056. # flatten inputs to merge intersections and iterables
  1057. args = _sympify(args)
  1058. # Reduce sets using known rules
  1059. if evaluate:
  1060. args = list(cls._new_args_filter(args))
  1061. return simplify_union(args)
  1062. args = list(ordered(args, Set._infimum_key))
  1063. obj = Basic.__new__(cls, *args)
  1064. obj._argset = frozenset(args)
  1065. return obj
  1066. @property
  1067. def args(self):
  1068. return self._args
  1069. def _complement(self, universe):
  1070. # DeMorgan's Law
  1071. return Intersection(s.complement(universe) for s in self.args)
  1072. @property
  1073. def _inf(self):
  1074. # We use Min so that sup is meaningful in combination with symbolic
  1075. # interval end points.
  1076. return Min(*[set.inf for set in self.args])
  1077. @property
  1078. def _sup(self):
  1079. # We use Max so that sup is meaningful in combination with symbolic
  1080. # end points.
  1081. return Max(*[set.sup for set in self.args])
  1082. @property
  1083. def is_empty(self):
  1084. return fuzzy_and(set.is_empty for set in self.args)
  1085. @property
  1086. def is_finite_set(self):
  1087. return fuzzy_and(set.is_finite_set for set in self.args)
  1088. @property
  1089. def _measure(self):
  1090. # Measure of a union is the sum of the measures of the sets minus
  1091. # the sum of their pairwise intersections plus the sum of their
  1092. # triple-wise intersections minus ... etc...
  1093. # Sets is a collection of intersections and a set of elementary
  1094. # sets which made up those intersections (called "sos" for set of sets)
  1095. # An example element might of this list might be:
  1096. # ( {A,B,C}, A.intersect(B).intersect(C) )
  1097. # Start with just elementary sets ( ({A}, A), ({B}, B), ... )
  1098. # Then get and subtract ( ({A,B}, (A int B), ... ) while non-zero
  1099. sets = [(FiniteSet(s), s) for s in self.args]
  1100. measure = 0
  1101. parity = 1
  1102. while sets:
  1103. # Add up the measure of these sets and add or subtract it to total
  1104. measure += parity * sum(inter.measure for sos, inter in sets)
  1105. # For each intersection in sets, compute the intersection with every
  1106. # other set not already part of the intersection.
  1107. sets = ((sos + FiniteSet(newset), newset.intersect(intersection))
  1108. for sos, intersection in sets for newset in self.args
  1109. if newset not in sos)
  1110. # Clear out sets with no measure
  1111. sets = [(sos, inter) for sos, inter in sets if inter.measure != 0]
  1112. # Clear out duplicates
  1113. sos_list = []
  1114. sets_list = []
  1115. for _set in sets:
  1116. if _set[0] in sos_list:
  1117. continue
  1118. else:
  1119. sos_list.append(_set[0])
  1120. sets_list.append(_set)
  1121. sets = sets_list
  1122. # Flip Parity - next time subtract/add if we added/subtracted here
  1123. parity *= -1
  1124. return measure
  1125. def _kind(self):
  1126. kinds = tuple(arg.kind for arg in self.args if arg is not S.EmptySet)
  1127. if not kinds:
  1128. return SetKind()
  1129. elif all(i == kinds[0] for i in kinds):
  1130. return kinds[0]
  1131. else:
  1132. return SetKind(UndefinedKind)
  1133. @property
  1134. def _boundary(self):
  1135. def boundary_of_set(i):
  1136. """ The boundary of set i minus interior of all other sets """
  1137. b = self.args[i].boundary
  1138. for j, a in enumerate(self.args):
  1139. if j != i:
  1140. b = b - a.interior
  1141. return b
  1142. return Union(*map(boundary_of_set, range(len(self.args))))
  1143. def _contains(self, other):
  1144. return Or(*[s.contains(other) for s in self.args])
  1145. def is_subset(self, other):
  1146. return fuzzy_and(s.is_subset(other) for s in self.args)
  1147. def as_relational(self, symbol):
  1148. """Rewrite a Union in terms of equalities and logic operators. """
  1149. if (len(self.args) == 2 and
  1150. all(isinstance(i, Interval) for i in self.args)):
  1151. # optimization to give 3 args as (x > 1) & (x < 5) & Ne(x, 3)
  1152. # instead of as 4, ((1 <= x) & (x < 3)) | ((x <= 5) & (3 < x))
  1153. # XXX: This should be ideally be improved to handle any number of
  1154. # intervals and also not to assume that the intervals are in any
  1155. # particular sorted order.
  1156. a, b = self.args
  1157. if a.sup == b.inf and a.right_open and b.left_open:
  1158. mincond = symbol > a.inf if a.left_open else symbol >= a.inf
  1159. maxcond = symbol < b.sup if b.right_open else symbol <= b.sup
  1160. necond = Ne(symbol, a.sup)
  1161. return And(necond, mincond, maxcond)
  1162. return Or(*[i.as_relational(symbol) for i in self.args])
  1163. @property
  1164. def is_iterable(self):
  1165. return all(arg.is_iterable for arg in self.args)
  1166. def __iter__(self):
  1167. return roundrobin(*(iter(arg) for arg in self.args))
  1168. class Intersection(Set, LatticeOp):
  1169. """
  1170. Represents an intersection of sets as a :class:`Set`.
  1171. Examples
  1172. ========
  1173. >>> from sympy import Intersection, Interval
  1174. >>> Intersection(Interval(1, 3), Interval(2, 4))
  1175. Interval(2, 3)
  1176. We often use the .intersect method
  1177. >>> Interval(1,3).intersect(Interval(2,4))
  1178. Interval(2, 3)
  1179. See Also
  1180. ========
  1181. Union
  1182. References
  1183. ==========
  1184. .. [1] https://en.wikipedia.org/wiki/Intersection_%28set_theory%29
  1185. """
  1186. is_Intersection = True
  1187. @property
  1188. def identity(self):
  1189. return S.UniversalSet
  1190. @property
  1191. def zero(self):
  1192. return S.EmptySet
  1193. def __new__(cls, *args , evaluate=None):
  1194. if evaluate is None:
  1195. evaluate = global_parameters.evaluate
  1196. # flatten inputs to merge intersections and iterables
  1197. args = list(ordered(set(_sympify(args))))
  1198. # Reduce sets using known rules
  1199. if evaluate:
  1200. args = list(cls._new_args_filter(args))
  1201. return simplify_intersection(args)
  1202. args = list(ordered(args, Set._infimum_key))
  1203. obj = Basic.__new__(cls, *args)
  1204. obj._argset = frozenset(args)
  1205. return obj
  1206. @property
  1207. def args(self):
  1208. return self._args
  1209. @property
  1210. def is_iterable(self):
  1211. return any(arg.is_iterable for arg in self.args)
  1212. @property
  1213. def is_finite_set(self):
  1214. if fuzzy_or(arg.is_finite_set for arg in self.args):
  1215. return True
  1216. def _kind(self):
  1217. kinds = tuple(arg.kind for arg in self.args if arg is not S.UniversalSet)
  1218. if not kinds:
  1219. return SetKind(UndefinedKind)
  1220. elif all(i == kinds[0] for i in kinds):
  1221. return kinds[0]
  1222. else:
  1223. return SetKind()
  1224. @property
  1225. def _inf(self):
  1226. raise NotImplementedError()
  1227. @property
  1228. def _sup(self):
  1229. raise NotImplementedError()
  1230. def _contains(self, other):
  1231. return And(*[set.contains(other) for set in self.args])
  1232. def __iter__(self):
  1233. sets_sift = sift(self.args, lambda x: x.is_iterable)
  1234. completed = False
  1235. candidates = sets_sift[True] + sets_sift[None]
  1236. finite_candidates, others = [], []
  1237. for candidate in candidates:
  1238. length = None
  1239. try:
  1240. length = len(candidate)
  1241. except TypeError:
  1242. others.append(candidate)
  1243. if length is not None:
  1244. finite_candidates.append(candidate)
  1245. finite_candidates.sort(key=len)
  1246. for s in finite_candidates + others:
  1247. other_sets = set(self.args) - {s}
  1248. other = Intersection(*other_sets, evaluate=False)
  1249. completed = True
  1250. for x in s:
  1251. try:
  1252. if x in other:
  1253. yield x
  1254. except TypeError:
  1255. completed = False
  1256. if completed:
  1257. return
  1258. if not completed:
  1259. if not candidates:
  1260. raise TypeError("None of the constituent sets are iterable")
  1261. raise TypeError(
  1262. "The computation had not completed because of the "
  1263. "undecidable set membership is found in every candidates.")
  1264. @staticmethod
  1265. def _handle_finite_sets(args):
  1266. '''Simplify intersection of one or more FiniteSets and other sets'''
  1267. # First separate the FiniteSets from the others
  1268. fs_args, others = sift(args, lambda x: x.is_FiniteSet, binary=True)
  1269. # Let the caller handle intersection of non-FiniteSets
  1270. if not fs_args:
  1271. return
  1272. # Convert to Python sets and build the set of all elements
  1273. fs_sets = [set(fs) for fs in fs_args]
  1274. all_elements = reduce(lambda a, b: a | b, fs_sets, set())
  1275. # Extract elements that are definitely in or definitely not in the
  1276. # intersection. Here we check contains for all of args.
  1277. definite = set()
  1278. for e in all_elements:
  1279. inall = fuzzy_and(s.contains(e) for s in args)
  1280. if inall is True:
  1281. definite.add(e)
  1282. if inall is not None:
  1283. for s in fs_sets:
  1284. s.discard(e)
  1285. # At this point all elements in all of fs_sets are possibly in the
  1286. # intersection. In some cases this is because they are definitely in
  1287. # the intersection of the finite sets but it's not clear if they are
  1288. # members of others. We might have {m, n}, {m}, and Reals where we
  1289. # don't know if m or n is real. We want to remove n here but it is
  1290. # possibly in because it might be equal to m. So what we do now is
  1291. # extract the elements that are definitely in the remaining finite
  1292. # sets iteratively until we end up with {n}, {}. At that point if we
  1293. # get any empty set all remaining elements are discarded.
  1294. fs_elements = reduce(lambda a, b: a | b, fs_sets, set())
  1295. # Need fuzzy containment testing
  1296. fs_symsets = [FiniteSet(*s) for s in fs_sets]
  1297. while fs_elements:
  1298. for e in fs_elements:
  1299. infs = fuzzy_and(s.contains(e) for s in fs_symsets)
  1300. if infs is True:
  1301. definite.add(e)
  1302. if infs is not None:
  1303. for n, s in enumerate(fs_sets):
  1304. # Update Python set and FiniteSet
  1305. if e in s:
  1306. s.remove(e)
  1307. fs_symsets[n] = FiniteSet(*s)
  1308. fs_elements.remove(e)
  1309. break
  1310. # If we completed the for loop without removing anything we are
  1311. # done so quit the outer while loop
  1312. else:
  1313. break
  1314. # If any of the sets of remainder elements is empty then we discard
  1315. # all of them for the intersection.
  1316. if not all(fs_sets):
  1317. fs_sets = [set()]
  1318. # Here we fold back the definitely included elements into each fs.
  1319. # Since they are definitely included they must have been members of
  1320. # each FiniteSet to begin with. We could instead fold these in with a
  1321. # Union at the end to get e.g. {3}|({x}&{y}) rather than {3,x}&{3,y}.
  1322. if definite:
  1323. fs_sets = [fs | definite for fs in fs_sets]
  1324. if fs_sets == [set()]:
  1325. return S.EmptySet
  1326. sets = [FiniteSet(*s) for s in fs_sets]
  1327. # Any set in others is redundant if it contains all the elements that
  1328. # are in the finite sets so we don't need it in the Intersection
  1329. all_elements = reduce(lambda a, b: a | b, fs_sets, set())
  1330. is_redundant = lambda o: all(fuzzy_bool(o.contains(e)) for e in all_elements)
  1331. others = [o for o in others if not is_redundant(o)]
  1332. if others:
  1333. rest = Intersection(*others)
  1334. # XXX: Maybe this shortcut should be at the beginning. For large
  1335. # FiniteSets it could much more efficient to process the other
  1336. # sets first...
  1337. if rest is S.EmptySet:
  1338. return S.EmptySet
  1339. # Flatten the Intersection
  1340. if rest.is_Intersection:
  1341. sets.extend(rest.args)
  1342. else:
  1343. sets.append(rest)
  1344. if len(sets) == 1:
  1345. return sets[0]
  1346. else:
  1347. return Intersection(*sets, evaluate=False)
  1348. def as_relational(self, symbol):
  1349. """Rewrite an Intersection in terms of equalities and logic operators"""
  1350. return And(*[set.as_relational(symbol) for set in self.args])
  1351. class Complement(Set):
  1352. r"""Represents the set difference or relative complement of a set with
  1353. another set.
  1354. $$A - B = \{x \in A \mid x \notin B\}$$
  1355. Examples
  1356. ========
  1357. >>> from sympy import Complement, FiniteSet
  1358. >>> Complement(FiniteSet(0, 1, 2), FiniteSet(1))
  1359. {0, 2}
  1360. See Also
  1361. =========
  1362. Intersection, Union
  1363. References
  1364. ==========
  1365. .. [1] https://mathworld.wolfram.com/ComplementSet.html
  1366. """
  1367. is_Complement = True
  1368. def __new__(cls, a, b, evaluate=True):
  1369. a, b = map(_sympify, (a, b))
  1370. if evaluate:
  1371. return Complement.reduce(a, b)
  1372. return Basic.__new__(cls, a, b)
  1373. @staticmethod
  1374. def reduce(A, B):
  1375. """
  1376. Simplify a :class:`Complement`.
  1377. """
  1378. if B == S.UniversalSet or A.is_subset(B):
  1379. return S.EmptySet
  1380. if isinstance(B, Union):
  1381. return Intersection(*(s.complement(A) for s in B.args))
  1382. result = B._complement(A)
  1383. if result is not None:
  1384. return result
  1385. else:
  1386. return Complement(A, B, evaluate=False)
  1387. def _contains(self, other):
  1388. A = self.args[0]
  1389. B = self.args[1]
  1390. return And(A.contains(other), Not(B.contains(other)))
  1391. def as_relational(self, symbol):
  1392. """Rewrite a complement in terms of equalities and logic
  1393. operators"""
  1394. A, B = self.args
  1395. A_rel = A.as_relational(symbol)
  1396. B_rel = Not(B.as_relational(symbol))
  1397. return And(A_rel, B_rel)
  1398. def _kind(self):
  1399. return self.args[0].kind
  1400. @property
  1401. def is_iterable(self):
  1402. if self.args[0].is_iterable:
  1403. return True
  1404. @property
  1405. def is_finite_set(self):
  1406. A, B = self.args
  1407. a_finite = A.is_finite_set
  1408. if a_finite is True:
  1409. return True
  1410. elif a_finite is False and B.is_finite_set:
  1411. return False
  1412. def __iter__(self):
  1413. A, B = self.args
  1414. for a in A:
  1415. if a not in B:
  1416. yield a
  1417. else:
  1418. continue
  1419. class EmptySet(Set, metaclass=Singleton):
  1420. """
  1421. Represents the empty set. The empty set is available as a singleton
  1422. as ``S.EmptySet``.
  1423. Examples
  1424. ========
  1425. >>> from sympy import S, Interval
  1426. >>> S.EmptySet
  1427. EmptySet
  1428. >>> Interval(1, 2).intersect(S.EmptySet)
  1429. EmptySet
  1430. See Also
  1431. ========
  1432. UniversalSet
  1433. References
  1434. ==========
  1435. .. [1] https://en.wikipedia.org/wiki/Empty_set
  1436. """
  1437. is_empty = True
  1438. is_finite_set = True
  1439. is_FiniteSet = True
  1440. @property # type: ignore
  1441. @deprecated(
  1442. """
  1443. The is_EmptySet attribute of Set objects is deprecated.
  1444. Use 's is S.EmptySet" or 's.is_empty' instead.
  1445. """,
  1446. deprecated_since_version="1.5",
  1447. active_deprecations_target="deprecated-is-emptyset",
  1448. )
  1449. def is_EmptySet(self):
  1450. return True
  1451. @property
  1452. def _measure(self):
  1453. return 0
  1454. def _contains(self, other):
  1455. return false
  1456. def as_relational(self, symbol):
  1457. return false
  1458. def __len__(self):
  1459. return 0
  1460. def __iter__(self):
  1461. return iter([])
  1462. def _eval_powerset(self):
  1463. return FiniteSet(self)
  1464. @property
  1465. def _boundary(self):
  1466. return self
  1467. def _complement(self, other):
  1468. return other
  1469. def _kind(self):
  1470. return SetKind()
  1471. def _symmetric_difference(self, other):
  1472. return other
  1473. class UniversalSet(Set, metaclass=Singleton):
  1474. """
  1475. Represents the set of all things.
  1476. The universal set is available as a singleton as ``S.UniversalSet``.
  1477. Examples
  1478. ========
  1479. >>> from sympy import S, Interval
  1480. >>> S.UniversalSet
  1481. UniversalSet
  1482. >>> Interval(1, 2).intersect(S.UniversalSet)
  1483. Interval(1, 2)
  1484. See Also
  1485. ========
  1486. EmptySet
  1487. References
  1488. ==========
  1489. .. [1] https://en.wikipedia.org/wiki/Universal_set
  1490. """
  1491. is_UniversalSet = True
  1492. is_empty = False
  1493. is_finite_set = False
  1494. def _complement(self, other):
  1495. return S.EmptySet
  1496. def _symmetric_difference(self, other):
  1497. return other
  1498. @property
  1499. def _measure(self):
  1500. return S.Infinity
  1501. def _kind(self):
  1502. return SetKind(UndefinedKind)
  1503. def _contains(self, other):
  1504. return true
  1505. def as_relational(self, symbol):
  1506. return true
  1507. @property
  1508. def _boundary(self):
  1509. return S.EmptySet
  1510. class FiniteSet(Set):
  1511. """
  1512. Represents a finite set of Sympy expressions.
  1513. Examples
  1514. ========
  1515. >>> from sympy import FiniteSet, Symbol, Interval, Naturals0
  1516. >>> FiniteSet(1, 2, 3, 4)
  1517. {1, 2, 3, 4}
  1518. >>> 3 in FiniteSet(1, 2, 3, 4)
  1519. True
  1520. >>> FiniteSet(1, (1, 2), Symbol('x'))
  1521. {1, x, (1, 2)}
  1522. >>> FiniteSet(Interval(1, 2), Naturals0, {1, 2})
  1523. FiniteSet({1, 2}, Interval(1, 2), Naturals0)
  1524. >>> members = [1, 2, 3, 4]
  1525. >>> f = FiniteSet(*members)
  1526. >>> f
  1527. {1, 2, 3, 4}
  1528. >>> f - FiniteSet(2)
  1529. {1, 3, 4}
  1530. >>> f + FiniteSet(2, 5)
  1531. {1, 2, 3, 4, 5}
  1532. References
  1533. ==========
  1534. .. [1] https://en.wikipedia.org/wiki/Finite_set
  1535. """
  1536. is_FiniteSet = True
  1537. is_iterable = True
  1538. is_empty = False
  1539. is_finite_set = True
  1540. def __new__(cls, *args, **kwargs):
  1541. evaluate = kwargs.get('evaluate', global_parameters.evaluate)
  1542. if evaluate:
  1543. args = list(map(sympify, args))
  1544. if len(args) == 0:
  1545. return S.EmptySet
  1546. else:
  1547. args = list(map(sympify, args))
  1548. # keep the form of the first canonical arg
  1549. dargs = {}
  1550. for i in reversed(list(ordered(args))):
  1551. if i.is_Symbol:
  1552. dargs[i] = i
  1553. else:
  1554. try:
  1555. dargs[i.as_dummy()] = i
  1556. except TypeError:
  1557. # e.g. i = class without args like `Interval`
  1558. dargs[i] = i
  1559. _args_set = set(dargs.values())
  1560. args = list(ordered(_args_set, Set._infimum_key))
  1561. obj = Basic.__new__(cls, *args)
  1562. obj._args_set = _args_set
  1563. return obj
  1564. def __iter__(self):
  1565. return iter(self.args)
  1566. def _complement(self, other):
  1567. if isinstance(other, Interval):
  1568. # Splitting in sub-intervals is only done for S.Reals;
  1569. # other cases that need splitting will first pass through
  1570. # Set._complement().
  1571. nums, syms = [], []
  1572. for m in self.args:
  1573. if m.is_number and m.is_real:
  1574. nums.append(m)
  1575. elif m.is_real == False:
  1576. pass # drop non-reals
  1577. else:
  1578. syms.append(m) # various symbolic expressions
  1579. if other == S.Reals and nums != []:
  1580. nums.sort()
  1581. intervals = [] # Build up a list of intervals between the elements
  1582. intervals += [Interval(S.NegativeInfinity, nums[0], True, True)]
  1583. for a, b in zip(nums[:-1], nums[1:]):
  1584. intervals.append(Interval(a, b, True, True)) # both open
  1585. intervals.append(Interval(nums[-1], S.Infinity, True, True))
  1586. if syms != []:
  1587. return Complement(Union(*intervals, evaluate=False),
  1588. FiniteSet(*syms), evaluate=False)
  1589. else:
  1590. return Union(*intervals, evaluate=False)
  1591. elif nums == []: # no splitting necessary or possible:
  1592. if syms:
  1593. return Complement(other, FiniteSet(*syms), evaluate=False)
  1594. else:
  1595. return other
  1596. elif isinstance(other, FiniteSet):
  1597. unk = []
  1598. for i in self:
  1599. c = sympify(other.contains(i))
  1600. if c is not S.true and c is not S.false:
  1601. unk.append(i)
  1602. unk = FiniteSet(*unk)
  1603. if unk == self:
  1604. return
  1605. not_true = []
  1606. for i in other:
  1607. c = sympify(self.contains(i))
  1608. if c is not S.true:
  1609. not_true.append(i)
  1610. return Complement(FiniteSet(*not_true), unk)
  1611. return Set._complement(self, other)
  1612. def _contains(self, other):
  1613. """
  1614. Tests whether an element, other, is in the set.
  1615. Explanation
  1616. ===========
  1617. The actual test is for mathematical equality (as opposed to
  1618. syntactical equality). In the worst case all elements of the
  1619. set must be checked.
  1620. Examples
  1621. ========
  1622. >>> from sympy import FiniteSet
  1623. >>> 1 in FiniteSet(1, 2)
  1624. True
  1625. >>> 5 in FiniteSet(1, 2)
  1626. False
  1627. """
  1628. if other in self._args_set:
  1629. return S.true
  1630. else:
  1631. # evaluate=True is needed to override evaluate=False context;
  1632. # we need Eq to do the evaluation
  1633. return Or(*[Eq(e, other, evaluate=True) for e in self.args])
  1634. def _eval_is_subset(self, other):
  1635. return fuzzy_and(other._contains(e) for e in self.args)
  1636. @property
  1637. def _boundary(self):
  1638. return self
  1639. @property
  1640. def _inf(self):
  1641. return Min(*self)
  1642. @property
  1643. def _sup(self):
  1644. return Max(*self)
  1645. @property
  1646. def measure(self):
  1647. return 0
  1648. def _kind(self):
  1649. if not self.args:
  1650. return SetKind()
  1651. elif all(i.kind == self.args[0].kind for i in self.args):
  1652. return SetKind(self.args[0].kind)
  1653. else:
  1654. return SetKind(UndefinedKind)
  1655. def __len__(self):
  1656. return len(self.args)
  1657. def as_relational(self, symbol):
  1658. """Rewrite a FiniteSet in terms of equalities and logic operators. """
  1659. return Or(*[Eq(symbol, elem) for elem in self])
  1660. def compare(self, other):
  1661. return (hash(self) - hash(other))
  1662. def _eval_evalf(self, prec):
  1663. dps = prec_to_dps(prec)
  1664. return FiniteSet(*[elem.evalf(n=dps) for elem in self])
  1665. def _eval_simplify(self, **kwargs):
  1666. from sympy.simplify import simplify
  1667. return FiniteSet(*[simplify(elem, **kwargs) for elem in self])
  1668. @property
  1669. def _sorted_args(self):
  1670. return self.args
  1671. def _eval_powerset(self):
  1672. return self.func(*[self.func(*s) for s in subsets(self.args)])
  1673. def _eval_rewrite_as_PowerSet(self, *args, **kwargs):
  1674. """Rewriting method for a finite set to a power set."""
  1675. from .powerset import PowerSet
  1676. is2pow = lambda n: bool(n and not n & (n - 1))
  1677. if not is2pow(len(self)):
  1678. return None
  1679. fs_test = lambda arg: isinstance(arg, Set) and arg.is_FiniteSet
  1680. if not all(fs_test(arg) for arg in args):
  1681. return None
  1682. biggest = max(args, key=len)
  1683. for arg in subsets(biggest.args):
  1684. arg_set = FiniteSet(*arg)
  1685. if arg_set not in args:
  1686. return None
  1687. return PowerSet(biggest)
  1688. def __ge__(self, other):
  1689. if not isinstance(other, Set):
  1690. raise TypeError("Invalid comparison of set with %s" % func_name(other))
  1691. return other.is_subset(self)
  1692. def __gt__(self, other):
  1693. if not isinstance(other, Set):
  1694. raise TypeError("Invalid comparison of set with %s" % func_name(other))
  1695. return self.is_proper_superset(other)
  1696. def __le__(self, other):
  1697. if not isinstance(other, Set):
  1698. raise TypeError("Invalid comparison of set with %s" % func_name(other))
  1699. return self.is_subset(other)
  1700. def __lt__(self, other):
  1701. if not isinstance(other, Set):
  1702. raise TypeError("Invalid comparison of set with %s" % func_name(other))
  1703. return self.is_proper_subset(other)
  1704. def __eq__(self, other):
  1705. if isinstance(other, (set, frozenset)):
  1706. return self._args_set == other
  1707. return super().__eq__(other)
  1708. __hash__ : Callable[[Basic], Any] = Basic.__hash__
  1709. _sympy_converter[set] = lambda x: FiniteSet(*x)
  1710. _sympy_converter[frozenset] = lambda x: FiniteSet(*x)
  1711. class SymmetricDifference(Set):
  1712. """Represents the set of elements which are in either of the
  1713. sets and not in their intersection.
  1714. Examples
  1715. ========
  1716. >>> from sympy import SymmetricDifference, FiniteSet
  1717. >>> SymmetricDifference(FiniteSet(1, 2, 3), FiniteSet(3, 4, 5))
  1718. {1, 2, 4, 5}
  1719. See Also
  1720. ========
  1721. Complement, Union
  1722. References
  1723. ==========
  1724. .. [1] https://en.wikipedia.org/wiki/Symmetric_difference
  1725. """
  1726. is_SymmetricDifference = True
  1727. def __new__(cls, a, b, evaluate=True):
  1728. if evaluate:
  1729. return SymmetricDifference.reduce(a, b)
  1730. return Basic.__new__(cls, a, b)
  1731. @staticmethod
  1732. def reduce(A, B):
  1733. result = B._symmetric_difference(A)
  1734. if result is not None:
  1735. return result
  1736. else:
  1737. return SymmetricDifference(A, B, evaluate=False)
  1738. def as_relational(self, symbol):
  1739. """Rewrite a symmetric_difference in terms of equalities and
  1740. logic operators"""
  1741. A, B = self.args
  1742. A_rel = A.as_relational(symbol)
  1743. B_rel = B.as_relational(symbol)
  1744. return Xor(A_rel, B_rel)
  1745. @property
  1746. def is_iterable(self):
  1747. if all(arg.is_iterable for arg in self.args):
  1748. return True
  1749. def __iter__(self):
  1750. args = self.args
  1751. union = roundrobin(*(iter(arg) for arg in args))
  1752. for item in union:
  1753. count = 0
  1754. for s in args:
  1755. if item in s:
  1756. count += 1
  1757. if count % 2 == 1:
  1758. yield item
  1759. class DisjointUnion(Set):
  1760. """ Represents the disjoint union (also known as the external disjoint union)
  1761. of a finite number of sets.
  1762. Examples
  1763. ========
  1764. >>> from sympy import DisjointUnion, FiniteSet, Interval, Union, Symbol
  1765. >>> A = FiniteSet(1, 2, 3)
  1766. >>> B = Interval(0, 5)
  1767. >>> DisjointUnion(A, B)
  1768. DisjointUnion({1, 2, 3}, Interval(0, 5))
  1769. >>> DisjointUnion(A, B).rewrite(Union)
  1770. Union(ProductSet({1, 2, 3}, {0}), ProductSet(Interval(0, 5), {1}))
  1771. >>> C = FiniteSet(Symbol('x'), Symbol('y'), Symbol('z'))
  1772. >>> DisjointUnion(C, C)
  1773. DisjointUnion({x, y, z}, {x, y, z})
  1774. >>> DisjointUnion(C, C).rewrite(Union)
  1775. ProductSet({x, y, z}, {0, 1})
  1776. References
  1777. ==========
  1778. https://en.wikipedia.org/wiki/Disjoint_union
  1779. """
  1780. def __new__(cls, *sets):
  1781. dj_collection = []
  1782. for set_i in sets:
  1783. if isinstance(set_i, Set):
  1784. dj_collection.append(set_i)
  1785. else:
  1786. raise TypeError("Invalid input: '%s', input args \
  1787. to DisjointUnion must be Sets" % set_i)
  1788. obj = Basic.__new__(cls, *dj_collection)
  1789. return obj
  1790. @property
  1791. def sets(self):
  1792. return self.args
  1793. @property
  1794. def is_empty(self):
  1795. return fuzzy_and(s.is_empty for s in self.sets)
  1796. @property
  1797. def is_finite_set(self):
  1798. all_finite = fuzzy_and(s.is_finite_set for s in self.sets)
  1799. return fuzzy_or([self.is_empty, all_finite])
  1800. @property
  1801. def is_iterable(self):
  1802. if self.is_empty:
  1803. return False
  1804. iter_flag = True
  1805. for set_i in self.sets:
  1806. if not set_i.is_empty:
  1807. iter_flag = iter_flag and set_i.is_iterable
  1808. return iter_flag
  1809. def _eval_rewrite_as_Union(self, *sets, **kwargs):
  1810. """
  1811. Rewrites the disjoint union as the union of (``set`` x {``i``})
  1812. where ``set`` is the element in ``sets`` at index = ``i``
  1813. """
  1814. dj_union = S.EmptySet
  1815. index = 0
  1816. for set_i in sets:
  1817. if isinstance(set_i, Set):
  1818. cross = ProductSet(set_i, FiniteSet(index))
  1819. dj_union = Union(dj_union, cross)
  1820. index = index + 1
  1821. return dj_union
  1822. def _contains(self, element):
  1823. """
  1824. ``in`` operator for DisjointUnion
  1825. Examples
  1826. ========
  1827. >>> from sympy import Interval, DisjointUnion
  1828. >>> D = DisjointUnion(Interval(0, 1), Interval(0, 2))
  1829. >>> (0.5, 0) in D
  1830. True
  1831. >>> (0.5, 1) in D
  1832. True
  1833. >>> (1.5, 0) in D
  1834. False
  1835. >>> (1.5, 1) in D
  1836. True
  1837. Passes operation on to constituent sets
  1838. """
  1839. if not isinstance(element, Tuple) or len(element) != 2:
  1840. return S.false
  1841. if not element[1].is_Integer:
  1842. return S.false
  1843. if element[1] >= len(self.sets) or element[1] < 0:
  1844. return S.false
  1845. return self.sets[element[1]]._contains(element[0])
  1846. def _kind(self):
  1847. if not self.args:
  1848. return SetKind()
  1849. elif all(i.kind == self.args[0].kind for i in self.args):
  1850. return self.args[0].kind
  1851. else:
  1852. return SetKind(UndefinedKind)
  1853. def __iter__(self):
  1854. if self.is_iterable:
  1855. iters = []
  1856. for i, s in enumerate(self.sets):
  1857. iters.append(iproduct(s, {Integer(i)}))
  1858. return iter(roundrobin(*iters))
  1859. else:
  1860. raise ValueError("'%s' is not iterable." % self)
  1861. def __len__(self):
  1862. """
  1863. Returns the length of the disjoint union, i.e., the number of elements in the set.
  1864. Examples
  1865. ========
  1866. >>> from sympy import FiniteSet, DisjointUnion, EmptySet
  1867. >>> D1 = DisjointUnion(FiniteSet(1, 2, 3, 4), EmptySet, FiniteSet(3, 4, 5))
  1868. >>> len(D1)
  1869. 7
  1870. >>> D2 = DisjointUnion(FiniteSet(3, 5, 7), EmptySet, FiniteSet(3, 5, 7))
  1871. >>> len(D2)
  1872. 6
  1873. >>> D3 = DisjointUnion(EmptySet, EmptySet)
  1874. >>> len(D3)
  1875. 0
  1876. Adds up the lengths of the constituent sets.
  1877. """
  1878. if self.is_finite_set:
  1879. size = 0
  1880. for set in self.sets:
  1881. size += len(set)
  1882. return size
  1883. else:
  1884. raise ValueError("'%s' is not a finite set." % self)
  1885. def imageset(*args):
  1886. r"""
  1887. Return an image of the set under transformation ``f``.
  1888. Explanation
  1889. ===========
  1890. If this function cannot compute the image, it returns an
  1891. unevaluated ImageSet object.
  1892. .. math::
  1893. \{ f(x) \mid x \in \mathrm{self} \}
  1894. Examples
  1895. ========
  1896. >>> from sympy import S, Interval, imageset, sin, Lambda
  1897. >>> from sympy.abc import x
  1898. >>> imageset(x, 2*x, Interval(0, 2))
  1899. Interval(0, 4)
  1900. >>> imageset(lambda x: 2*x, Interval(0, 2))
  1901. Interval(0, 4)
  1902. >>> imageset(Lambda(x, sin(x)), Interval(-2, 1))
  1903. ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
  1904. >>> imageset(sin, Interval(-2, 1))
  1905. ImageSet(Lambda(x, sin(x)), Interval(-2, 1))
  1906. >>> imageset(lambda y: x + y, Interval(-2, 1))
  1907. ImageSet(Lambda(y, x + y), Interval(-2, 1))
  1908. Expressions applied to the set of Integers are simplified
  1909. to show as few negatives as possible and linear expressions
  1910. are converted to a canonical form. If this is not desirable
  1911. then the unevaluated ImageSet should be used.
  1912. >>> imageset(x, -2*x + 5, S.Integers)
  1913. ImageSet(Lambda(x, 2*x + 1), Integers)
  1914. See Also
  1915. ========
  1916. sympy.sets.fancysets.ImageSet
  1917. """
  1918. from .fancysets import ImageSet
  1919. from .setexpr import set_function
  1920. if len(args) < 2:
  1921. raise ValueError('imageset expects at least 2 args, got: %s' % len(args))
  1922. if isinstance(args[0], (Symbol, tuple)) and len(args) > 2:
  1923. f = Lambda(args[0], args[1])
  1924. set_list = args[2:]
  1925. else:
  1926. f = args[0]
  1927. set_list = args[1:]
  1928. if isinstance(f, Lambda):
  1929. pass
  1930. elif callable(f):
  1931. nargs = getattr(f, 'nargs', {})
  1932. if nargs:
  1933. if len(nargs) != 1:
  1934. raise NotImplementedError(filldedent('''
  1935. This function can take more than 1 arg
  1936. but the potentially complicated set input
  1937. has not been analyzed at this point to
  1938. know its dimensions. TODO
  1939. '''))
  1940. N = nargs.args[0]
  1941. if N == 1:
  1942. s = 'x'
  1943. else:
  1944. s = [Symbol('x%i' % i) for i in range(1, N + 1)]
  1945. else:
  1946. s = inspect.signature(f).parameters
  1947. dexpr = _sympify(f(*[Dummy() for i in s]))
  1948. var = tuple(uniquely_named_symbol(
  1949. Symbol(i), dexpr) for i in s)
  1950. f = Lambda(var, f(*var))
  1951. else:
  1952. raise TypeError(filldedent('''
  1953. expecting lambda, Lambda, or FunctionClass,
  1954. not \'%s\'.''' % func_name(f)))
  1955. if any(not isinstance(s, Set) for s in set_list):
  1956. name = [func_name(s) for s in set_list]
  1957. raise ValueError(
  1958. 'arguments after mapping should be sets, not %s' % name)
  1959. if len(set_list) == 1:
  1960. set = set_list[0]
  1961. try:
  1962. # TypeError if arg count != set dimensions
  1963. r = set_function(f, set)
  1964. if r is None:
  1965. raise TypeError
  1966. if not r:
  1967. return r
  1968. except TypeError:
  1969. r = ImageSet(f, set)
  1970. if isinstance(r, ImageSet):
  1971. f, set = r.args
  1972. if f.variables[0] == f.expr:
  1973. return set
  1974. if isinstance(set, ImageSet):
  1975. # XXX: Maybe this should just be:
  1976. # f2 = set.lambda
  1977. # fun = Lambda(f2.signature, f(*f2.expr))
  1978. # return imageset(fun, *set.base_sets)
  1979. if len(set.lamda.variables) == 1 and len(f.variables) == 1:
  1980. x = set.lamda.variables[0]
  1981. y = f.variables[0]
  1982. return imageset(
  1983. Lambda(x, f.expr.subs(y, set.lamda.expr)), *set.base_sets)
  1984. if r is not None:
  1985. return r
  1986. return ImageSet(f, *set_list)
  1987. def is_function_invertible_in_set(func, setv):
  1988. """
  1989. Checks whether function ``func`` is invertible when the domain is
  1990. restricted to set ``setv``.
  1991. """
  1992. # Functions known to always be invertible:
  1993. if func in (exp, log):
  1994. return True
  1995. u = Dummy("u")
  1996. fdiff = func(u).diff(u)
  1997. # monotonous functions:
  1998. # TODO: check subsets (`func` in `setv`)
  1999. if (fdiff > 0) == True or (fdiff < 0) == True:
  2000. return True
  2001. # TODO: support more
  2002. return None
  2003. def simplify_union(args):
  2004. """
  2005. Simplify a :class:`Union` using known rules.
  2006. Explanation
  2007. ===========
  2008. We first start with global rules like 'Merge all FiniteSets'
  2009. Then we iterate through all pairs and ask the constituent sets if they
  2010. can simplify themselves with any other constituent. This process depends
  2011. on ``union_sets(a, b)`` functions.
  2012. """
  2013. from sympy.sets.handlers.union import union_sets
  2014. # ===== Global Rules =====
  2015. if not args:
  2016. return S.EmptySet
  2017. for arg in args:
  2018. if not isinstance(arg, Set):
  2019. raise TypeError("Input args to Union must be Sets")
  2020. # Merge all finite sets
  2021. finite_sets = [x for x in args if x.is_FiniteSet]
  2022. if len(finite_sets) > 1:
  2023. a = (x for set in finite_sets for x in set)
  2024. finite_set = FiniteSet(*a)
  2025. args = [finite_set] + [x for x in args if not x.is_FiniteSet]
  2026. # ===== Pair-wise Rules =====
  2027. # Here we depend on rules built into the constituent sets
  2028. args = set(args)
  2029. new_args = True
  2030. while new_args:
  2031. for s in args:
  2032. new_args = False
  2033. for t in args - {s}:
  2034. new_set = union_sets(s, t)
  2035. # This returns None if s does not know how to intersect
  2036. # with t. Returns the newly intersected set otherwise
  2037. if new_set is not None:
  2038. if not isinstance(new_set, set):
  2039. new_set = {new_set}
  2040. new_args = (args - {s, t}).union(new_set)
  2041. break
  2042. if new_args:
  2043. args = new_args
  2044. break
  2045. if len(args) == 1:
  2046. return args.pop()
  2047. else:
  2048. return Union(*args, evaluate=False)
  2049. def simplify_intersection(args):
  2050. """
  2051. Simplify an intersection using known rules.
  2052. Explanation
  2053. ===========
  2054. We first start with global rules like
  2055. 'if any empty sets return empty set' and 'distribute any unions'
  2056. Then we iterate through all pairs and ask the constituent sets if they
  2057. can simplify themselves with any other constituent
  2058. """
  2059. # ===== Global Rules =====
  2060. if not args:
  2061. return S.UniversalSet
  2062. for arg in args:
  2063. if not isinstance(arg, Set):
  2064. raise TypeError("Input args to Union must be Sets")
  2065. # If any EmptySets return EmptySet
  2066. if S.EmptySet in args:
  2067. return S.EmptySet
  2068. # Handle Finite sets
  2069. rv = Intersection._handle_finite_sets(args)
  2070. if rv is not None:
  2071. return rv
  2072. # If any of the sets are unions, return a Union of Intersections
  2073. for s in args:
  2074. if s.is_Union:
  2075. other_sets = set(args) - {s}
  2076. if len(other_sets) > 0:
  2077. other = Intersection(*other_sets)
  2078. return Union(*(Intersection(arg, other) for arg in s.args))
  2079. else:
  2080. return Union(*s.args)
  2081. for s in args:
  2082. if s.is_Complement:
  2083. args.remove(s)
  2084. other_sets = args + [s.args[0]]
  2085. return Complement(Intersection(*other_sets), s.args[1])
  2086. from sympy.sets.handlers.intersection import intersection_sets
  2087. # At this stage we are guaranteed not to have any
  2088. # EmptySets, FiniteSets, or Unions in the intersection
  2089. # ===== Pair-wise Rules =====
  2090. # Here we depend on rules built into the constituent sets
  2091. args = set(args)
  2092. new_args = True
  2093. while new_args:
  2094. for s in args:
  2095. new_args = False
  2096. for t in args - {s}:
  2097. new_set = intersection_sets(s, t)
  2098. # This returns None if s does not know how to intersect
  2099. # with t. Returns the newly intersected set otherwise
  2100. if new_set is not None:
  2101. new_args = (args - {s, t}).union({new_set})
  2102. break
  2103. if new_args:
  2104. args = new_args
  2105. break
  2106. if len(args) == 1:
  2107. return args.pop()
  2108. else:
  2109. return Intersection(*args, evaluate=False)
  2110. def _handle_finite_sets(op, x, y, commutative):
  2111. # Handle finite sets:
  2112. fs_args, other = sift([x, y], lambda x: isinstance(x, FiniteSet), binary=True)
  2113. if len(fs_args) == 2:
  2114. return FiniteSet(*[op(i, j) for i in fs_args[0] for j in fs_args[1]])
  2115. elif len(fs_args) == 1:
  2116. sets = [_apply_operation(op, other[0], i, commutative) for i in fs_args[0]]
  2117. return Union(*sets)
  2118. else:
  2119. return None
  2120. def _apply_operation(op, x, y, commutative):
  2121. from .fancysets import ImageSet
  2122. d = Dummy('d')
  2123. out = _handle_finite_sets(op, x, y, commutative)
  2124. if out is None:
  2125. out = op(x, y)
  2126. if out is None and commutative:
  2127. out = op(y, x)
  2128. if out is None:
  2129. _x, _y = symbols("x y")
  2130. if isinstance(x, Set) and not isinstance(y, Set):
  2131. out = ImageSet(Lambda(d, op(d, y)), x).doit()
  2132. elif not isinstance(x, Set) and isinstance(y, Set):
  2133. out = ImageSet(Lambda(d, op(x, d)), y).doit()
  2134. else:
  2135. out = ImageSet(Lambda((_x, _y), op(_x, _y)), x, y)
  2136. return out
  2137. def set_add(x, y):
  2138. from sympy.sets.handlers.add import _set_add
  2139. return _apply_operation(_set_add, x, y, commutative=True)
  2140. def set_sub(x, y):
  2141. from sympy.sets.handlers.add import _set_sub
  2142. return _apply_operation(_set_sub, x, y, commutative=False)
  2143. def set_mul(x, y):
  2144. from sympy.sets.handlers.mul import _set_mul
  2145. return _apply_operation(_set_mul, x, y, commutative=True)
  2146. def set_div(x, y):
  2147. from sympy.sets.handlers.mul import _set_div
  2148. return _apply_operation(_set_div, x, y, commutative=False)
  2149. def set_pow(x, y):
  2150. from sympy.sets.handlers.power import _set_pow
  2151. return _apply_operation(_set_pow, x, y, commutative=False)
  2152. def set_function(f, x):
  2153. from sympy.sets.handlers.functions import _set_function
  2154. return _set_function(f, x)
  2155. class SetKind(Kind):
  2156. """
  2157. SetKind is kind for all Sets
  2158. Every instance of Set will have kind ``SetKind`` parametrised by the kind
  2159. of the elements of the ``Set``. The kind of the elements might be
  2160. ``NumberKind``, or ``TupleKind`` or something else. When not all elements
  2161. have the same kind then the kind of the elements will be given as
  2162. ``UndefinedKind``.
  2163. Parameters
  2164. ==========
  2165. element_kind: Kind (optional)
  2166. The kind of the elements of the set. In a well defined set all elements
  2167. will have the same kind. Otherwise the kind should
  2168. :class:`sympy.core.kind.UndefinedKind`. The ``element_kind`` argument is optional but
  2169. should only be omitted in the case of ``EmptySet`` whose kind is simply
  2170. ``SetKind()``
  2171. Examples
  2172. ========
  2173. >>> from sympy import Interval
  2174. >>> Interval(1, 2).kind
  2175. SetKind(NumberKind)
  2176. >>> Interval(1,2).kind.element_kind
  2177. NumberKind
  2178. See Also
  2179. ========
  2180. sympy.core.kind.NumberKind
  2181. sympy.matrices.kind.MatrixKind
  2182. sympy.core.containers.TupleKind
  2183. """
  2184. def __new__(cls, element_kind=None):
  2185. obj = super().__new__(cls, element_kind)
  2186. obj.element_kind = element_kind
  2187. return obj
  2188. def __repr__(self):
  2189. if not self.element_kind:
  2190. return "SetKind()"
  2191. else:
  2192. return "SetKind(%s)" % self.element_kind