intersection.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. from sympy.core.function import Lambda, expand_complex
  2. from sympy.core.mul import Mul
  3. from sympy.core.numbers import ilcm
  4. from sympy.core.relational import Eq
  5. from sympy.core.singleton import S
  6. from sympy.core.symbol import (Dummy, symbols)
  7. from sympy.core.sorting import ordered
  8. from sympy.sets.fancysets import ComplexRegion
  9. from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
  10. from sympy.multipledispatch import Dispatcher
  11. from sympy.sets.conditionset import ConditionSet
  12. from sympy.sets.fancysets import (Integers, Naturals, Reals, Range,
  13. ImageSet, Rationals)
  14. from sympy.sets.sets import EmptySet, UniversalSet, imageset, ProductSet
  15. from sympy.simplify.radsimp import numer
  16. intersection_sets = Dispatcher('intersection_sets')
  17. @intersection_sets.register(ConditionSet, ConditionSet)
  18. def _(a, b):
  19. return None
  20. @intersection_sets.register(ConditionSet, Set)
  21. def _(a, b):
  22. return ConditionSet(a.sym, a.condition, Intersection(a.base_set, b))
  23. @intersection_sets.register(Naturals, Integers)
  24. def _(a, b):
  25. return a
  26. @intersection_sets.register(Naturals, Naturals)
  27. def _(a, b):
  28. return a if a is S.Naturals else b
  29. @intersection_sets.register(Interval, Naturals)
  30. def _(a, b):
  31. return intersection_sets(b, a)
  32. @intersection_sets.register(ComplexRegion, Set)
  33. def _(self, other):
  34. if other.is_ComplexRegion:
  35. # self in rectangular form
  36. if (not self.polar) and (not other.polar):
  37. return ComplexRegion(Intersection(self.sets, other.sets))
  38. # self in polar form
  39. elif self.polar and other.polar:
  40. r1, theta1 = self.a_interval, self.b_interval
  41. r2, theta2 = other.a_interval, other.b_interval
  42. new_r_interval = Intersection(r1, r2)
  43. new_theta_interval = Intersection(theta1, theta2)
  44. # 0 and 2*Pi means the same
  45. if ((2*S.Pi in theta1 and S.Zero in theta2) or
  46. (2*S.Pi in theta2 and S.Zero in theta1)):
  47. new_theta_interval = Union(new_theta_interval,
  48. FiniteSet(0))
  49. return ComplexRegion(new_r_interval*new_theta_interval,
  50. polar=True)
  51. if other.is_subset(S.Reals):
  52. new_interval = []
  53. x = symbols("x", cls=Dummy, real=True)
  54. # self in rectangular form
  55. if not self.polar:
  56. for element in self.psets:
  57. if S.Zero in element.args[1]:
  58. new_interval.append(element.args[0])
  59. new_interval = Union(*new_interval)
  60. return Intersection(new_interval, other)
  61. # self in polar form
  62. elif self.polar:
  63. for element in self.psets:
  64. if S.Zero in element.args[1]:
  65. new_interval.append(element.args[0])
  66. if S.Pi in element.args[1]:
  67. new_interval.append(ImageSet(Lambda(x, -x), element.args[0]))
  68. if S.Zero in element.args[0]:
  69. new_interval.append(FiniteSet(0))
  70. new_interval = Union(*new_interval)
  71. return Intersection(new_interval, other)
  72. @intersection_sets.register(Integers, Reals)
  73. def _(a, b):
  74. return a
  75. @intersection_sets.register(Range, Interval)
  76. def _(a, b):
  77. # Check that there are no symbolic arguments
  78. if not all(i.is_number for i in a.args + b.args[:2]):
  79. return
  80. # In case of null Range, return an EmptySet.
  81. if a.size == 0:
  82. return S.EmptySet
  83. from sympy.functions.elementary.integers import floor, ceiling
  84. # trim down to self's size, and represent
  85. # as a Range with step 1.
  86. start = ceiling(max(b.inf, a.inf))
  87. if start not in b:
  88. start += 1
  89. end = floor(min(b.sup, a.sup))
  90. if end not in b:
  91. end -= 1
  92. return intersection_sets(a, Range(start, end + 1))
  93. @intersection_sets.register(Range, Naturals)
  94. def _(a, b):
  95. return intersection_sets(a, Interval(b.inf, S.Infinity))
  96. @intersection_sets.register(Range, Range)
  97. def _(a, b):
  98. # Check that there are no symbolic range arguments
  99. if not all(all(v.is_number for v in r.args) for r in [a, b]):
  100. return None
  101. # non-overlap quick exits
  102. if not b:
  103. return S.EmptySet
  104. if not a:
  105. return S.EmptySet
  106. if b.sup < a.inf:
  107. return S.EmptySet
  108. if b.inf > a.sup:
  109. return S.EmptySet
  110. # work with finite end at the start
  111. r1 = a
  112. if r1.start.is_infinite:
  113. r1 = r1.reversed
  114. r2 = b
  115. if r2.start.is_infinite:
  116. r2 = r2.reversed
  117. # If both ends are infinite then it means that one Range is just the set
  118. # of all integers (the step must be 1).
  119. if r1.start.is_infinite:
  120. return b
  121. if r2.start.is_infinite:
  122. return a
  123. from sympy.solvers.diophantine.diophantine import diop_linear
  124. from sympy.functions.elementary.complexes import sign
  125. # this equation represents the values of the Range;
  126. # it's a linear equation
  127. eq = lambda r, i: r.start + i*r.step
  128. # we want to know when the two equations might
  129. # have integer solutions so we use the diophantine
  130. # solver
  131. va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b')))
  132. # check for no solution
  133. no_solution = va is None and vb is None
  134. if no_solution:
  135. return S.EmptySet
  136. # there is a solution
  137. # -------------------
  138. # find the coincident point, c
  139. a0 = va.as_coeff_Add()[0]
  140. c = eq(r1, a0)
  141. # find the first point, if possible, in each range
  142. # since c may not be that point
  143. def _first_finite_point(r1, c):
  144. if c == r1.start:
  145. return c
  146. # st is the signed step we need to take to
  147. # get from c to r1.start
  148. st = sign(r1.start - c)*step
  149. # use Range to calculate the first point:
  150. # we want to get as close as possible to
  151. # r1.start; the Range will not be null since
  152. # it will at least contain c
  153. s1 = Range(c, r1.start + st, st)[-1]
  154. if s1 == r1.start:
  155. pass
  156. else:
  157. # if we didn't hit r1.start then, if the
  158. # sign of st didn't match the sign of r1.step
  159. # we are off by one and s1 is not in r1
  160. if sign(r1.step) != sign(st):
  161. s1 -= st
  162. if s1 not in r1:
  163. return
  164. return s1
  165. # calculate the step size of the new Range
  166. step = abs(ilcm(r1.step, r2.step))
  167. s1 = _first_finite_point(r1, c)
  168. if s1 is None:
  169. return S.EmptySet
  170. s2 = _first_finite_point(r2, c)
  171. if s2 is None:
  172. return S.EmptySet
  173. # replace the corresponding start or stop in
  174. # the original Ranges with these points; the
  175. # result must have at least one point since
  176. # we know that s1 and s2 are in the Ranges
  177. def _updated_range(r, first):
  178. st = sign(r.step)*step
  179. if r.start.is_finite:
  180. rv = Range(first, r.stop, st)
  181. else:
  182. rv = Range(r.start, first + st, st)
  183. return rv
  184. r1 = _updated_range(a, s1)
  185. r2 = _updated_range(b, s2)
  186. # work with them both in the increasing direction
  187. if sign(r1.step) < 0:
  188. r1 = r1.reversed
  189. if sign(r2.step) < 0:
  190. r2 = r2.reversed
  191. # return clipped Range with positive step; it
  192. # can't be empty at this point
  193. start = max(r1.start, r2.start)
  194. stop = min(r1.stop, r2.stop)
  195. return Range(start, stop, step)
  196. @intersection_sets.register(Range, Integers)
  197. def _(a, b):
  198. return a
  199. @intersection_sets.register(ImageSet, Set)
  200. def _(self, other):
  201. from sympy.solvers.diophantine import diophantine
  202. # Only handle the straight-forward univariate case
  203. if (len(self.lamda.variables) > 1
  204. or self.lamda.signature != self.lamda.variables):
  205. return None
  206. base_set = self.base_sets[0]
  207. # Intersection between ImageSets with Integers as base set
  208. # For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the
  209. # diophantine equations f(n)=g(m).
  210. # If the solutions for n are {h(t) : t in Integers} then we return
  211. # {f(h(t)) : t in integers}.
  212. # If the solutions for n are {n_1, n_2, ..., n_k} then we return
  213. # {f(n_i) : 1 <= i <= k}.
  214. if base_set is S.Integers:
  215. gm = None
  216. if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):
  217. gm = other.lamda.expr
  218. var = other.lamda.variables[0]
  219. # Symbol of second ImageSet lambda must be distinct from first
  220. m = Dummy('m')
  221. gm = gm.subs(var, m)
  222. elif other is S.Integers:
  223. m = gm = Dummy('m')
  224. if gm is not None:
  225. fn = self.lamda.expr
  226. n = self.lamda.variables[0]
  227. try:
  228. solns = list(diophantine(fn - gm, syms=(n, m), permute=True))
  229. except (TypeError, NotImplementedError):
  230. # TypeError if equation not polynomial with rational coeff.
  231. # NotImplementedError if correct format but no solver.
  232. return
  233. # 3 cases are possible for solns:
  234. # - empty set,
  235. # - one or more parametric (infinite) solutions,
  236. # - a finite number of (non-parametric) solution couples.
  237. # Among those, there is one type of solution set that is
  238. # not helpful here: multiple parametric solutions.
  239. if len(solns) == 0:
  240. return S.EmptySet
  241. elif any(s.free_symbols for tupl in solns for s in tupl):
  242. if len(solns) == 1:
  243. soln, solm = solns[0]
  244. (t,) = soln.free_symbols
  245. expr = fn.subs(n, soln.subs(t, n)).expand()
  246. return imageset(Lambda(n, expr), S.Integers)
  247. else:
  248. return
  249. else:
  250. return FiniteSet(*(fn.subs(n, s[0]) for s in solns))
  251. if other == S.Reals:
  252. from sympy.solvers.solvers import denoms, solve_linear
  253. def _solution_union(exprs, sym):
  254. # return a union of linear solutions to i in expr;
  255. # if i cannot be solved, use a ConditionSet for solution
  256. sols = []
  257. for i in exprs:
  258. x, xis = solve_linear(i, 0, [sym])
  259. if x == sym:
  260. sols.append(FiniteSet(xis))
  261. else:
  262. sols.append(ConditionSet(sym, Eq(i, 0)))
  263. return Union(*sols)
  264. f = self.lamda.expr
  265. n = self.lamda.variables[0]
  266. n_ = Dummy(n.name, real=True)
  267. f_ = f.subs(n, n_)
  268. re, im = f_.as_real_imag()
  269. im = expand_complex(im)
  270. re = re.subs(n_, n)
  271. im = im.subs(n_, n)
  272. ifree = im.free_symbols
  273. lam = Lambda(n, re)
  274. if im.is_zero:
  275. # allow re-evaluation
  276. # of self in this case to make
  277. # the result canonical
  278. pass
  279. elif im.is_zero is False:
  280. return S.EmptySet
  281. elif ifree != {n}:
  282. return None
  283. else:
  284. # univarite imaginary part in same variable;
  285. # use numer instead of as_numer_denom to keep
  286. # this as fast as possible while still handling
  287. # simple cases
  288. base_set &= _solution_union(
  289. Mul.make_args(numer(im)), n)
  290. # exclude values that make denominators 0
  291. base_set -= _solution_union(denoms(f), n)
  292. return imageset(lam, base_set)
  293. elif isinstance(other, Interval):
  294. from sympy.solvers.solveset import (invert_real, invert_complex,
  295. solveset)
  296. f = self.lamda.expr
  297. n = self.lamda.variables[0]
  298. new_inf, new_sup = None, None
  299. new_lopen, new_ropen = other.left_open, other.right_open
  300. if f.is_real:
  301. inverter = invert_real
  302. else:
  303. inverter = invert_complex
  304. g1, h1 = inverter(f, other.inf, n)
  305. g2, h2 = inverter(f, other.sup, n)
  306. if all(isinstance(i, FiniteSet) for i in (h1, h2)):
  307. if g1 == n:
  308. if len(h1) == 1:
  309. new_inf = h1.args[0]
  310. if g2 == n:
  311. if len(h2) == 1:
  312. new_sup = h2.args[0]
  313. # TODO: Design a technique to handle multiple-inverse
  314. # functions
  315. # Any of the new boundary values cannot be determined
  316. if any(i is None for i in (new_sup, new_inf)):
  317. return
  318. range_set = S.EmptySet
  319. if all(i.is_real for i in (new_sup, new_inf)):
  320. # this assumes continuity of underlying function
  321. # however fixes the case when it is decreasing
  322. if new_inf > new_sup:
  323. new_inf, new_sup = new_sup, new_inf
  324. new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen)
  325. range_set = base_set.intersect(new_interval)
  326. else:
  327. if other.is_subset(S.Reals):
  328. solutions = solveset(f, n, S.Reals)
  329. if not isinstance(range_set, (ImageSet, ConditionSet)):
  330. range_set = solutions.intersect(other)
  331. else:
  332. return
  333. if range_set is S.EmptySet:
  334. return S.EmptySet
  335. elif isinstance(range_set, Range) and range_set.size is not S.Infinity:
  336. range_set = FiniteSet(*list(range_set))
  337. if range_set is not None:
  338. return imageset(Lambda(n, f), range_set)
  339. return
  340. else:
  341. return
  342. @intersection_sets.register(ProductSet, ProductSet)
  343. def _(a, b):
  344. if len(b.args) != len(a.args):
  345. return S.EmptySet
  346. return ProductSet(*(i.intersect(j) for i, j in zip(a.sets, b.sets)))
  347. @intersection_sets.register(Interval, Interval)
  348. def _(a, b):
  349. # handle (-oo, oo)
  350. infty = S.NegativeInfinity, S.Infinity
  351. if a == Interval(*infty):
  352. l, r = a.left, a.right
  353. if l.is_real or l in infty or r.is_real or r in infty:
  354. return b
  355. # We can't intersect [0,3] with [x,6] -- we don't know if x>0 or x<0
  356. if not a._is_comparable(b):
  357. return None
  358. empty = False
  359. if a.start <= b.end and b.start <= a.end:
  360. # Get topology right.
  361. if a.start < b.start:
  362. start = b.start
  363. left_open = b.left_open
  364. elif a.start > b.start:
  365. start = a.start
  366. left_open = a.left_open
  367. else:
  368. #this is to ensure that if Eq(a.start,b.start) but
  369. #type(a.start) != type(b.start) the order of a and b
  370. #does not matter for the result
  371. start = list(ordered([a,b]))[0].start
  372. left_open = a.left_open or b.left_open
  373. if a.end < b.end:
  374. end = a.end
  375. right_open = a.right_open
  376. elif a.end > b.end:
  377. end = b.end
  378. right_open = b.right_open
  379. else:
  380. end = list(ordered([a,b]))[0].end
  381. right_open = a.right_open or b.right_open
  382. if end - start == 0 and (left_open or right_open):
  383. empty = True
  384. else:
  385. empty = True
  386. if empty:
  387. return S.EmptySet
  388. return Interval(start, end, left_open, right_open)
  389. @intersection_sets.register(EmptySet, Set)
  390. def _(a, b):
  391. return S.EmptySet
  392. @intersection_sets.register(UniversalSet, Set)
  393. def _(a, b):
  394. return b
  395. @intersection_sets.register(FiniteSet, FiniteSet)
  396. def _(a, b):
  397. return FiniteSet(*(a._elements & b._elements))
  398. @intersection_sets.register(FiniteSet, Set)
  399. def _(a, b):
  400. try:
  401. return FiniteSet(*[el for el in a if el in b])
  402. except TypeError:
  403. return None # could not evaluate `el in b` due to symbolic ranges.
  404. @intersection_sets.register(Set, Set)
  405. def _(a, b):
  406. return None
  407. @intersection_sets.register(Integers, Rationals)
  408. def _(a, b):
  409. return a
  410. @intersection_sets.register(Naturals, Rationals)
  411. def _(a, b):
  412. return a
  413. @intersection_sets.register(Rationals, Reals)
  414. def _(a, b):
  415. return a
  416. def _intlike_interval(a, b):
  417. try:
  418. from sympy.functions.elementary.integers import floor, ceiling
  419. if b._inf is S.NegativeInfinity and b._sup is S.Infinity:
  420. return a
  421. s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1)
  422. return intersection_sets(s, b) # take out endpoints if open interval
  423. except ValueError:
  424. return None
  425. @intersection_sets.register(Integers, Interval)
  426. def _(a, b):
  427. return _intlike_interval(a, b)
  428. @intersection_sets.register(Naturals, Interval)
  429. def _(a, b):
  430. return _intlike_interval(a, b)