intersection.py 16 KB

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