util.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. """Utility functions for geometrical entities.
  2. Contains
  3. ========
  4. intersection
  5. convex_hull
  6. closest_points
  7. farthest_points
  8. are_coplanar
  9. are_similar
  10. """
  11. from collections import deque
  12. from math import sqrt as _sqrt
  13. from .entity import GeometryEntity
  14. from .exceptions import GeometryError
  15. from .point import Point, Point2D, Point3D
  16. from sympy.core.containers import OrderedSet
  17. from sympy.core.exprtools import factor_terms
  18. from sympy.core.function import Function, expand_mul
  19. from sympy.core.sorting import ordered
  20. from sympy.core.symbol import Symbol
  21. from sympy.core.singleton import S
  22. from sympy.polys.polytools import cancel
  23. from sympy.functions.elementary.miscellaneous import sqrt
  24. from sympy.utilities.iterables import is_sequence
  25. def find(x, equation):
  26. """
  27. Checks whether a Symbol matching ``x`` is present in ``equation``
  28. or not. If present, the matching symbol is returned, else a
  29. ValueError is raised. If ``x`` is a string the matching symbol
  30. will have the same name; if ``x`` is a Symbol then it will be
  31. returned if found.
  32. Examples
  33. ========
  34. >>> from sympy.geometry.util import find
  35. >>> from sympy import Dummy
  36. >>> from sympy.abc import x
  37. >>> find('x', x)
  38. x
  39. >>> find('x', Dummy('x'))
  40. _x
  41. The dummy symbol is returned since it has a matching name:
  42. >>> _.name == 'x'
  43. True
  44. >>> find(x, Dummy('x'))
  45. Traceback (most recent call last):
  46. ...
  47. ValueError: could not find x
  48. """
  49. free = equation.free_symbols
  50. xs = [i for i in free if (i.name if isinstance(x, str) else i) == x]
  51. if not xs:
  52. raise ValueError('could not find %s' % x)
  53. if len(xs) != 1:
  54. raise ValueError('ambiguous %s' % x)
  55. return xs[0]
  56. def _ordered_points(p):
  57. """Return the tuple of points sorted numerically according to args"""
  58. return tuple(sorted(p, key=lambda x: x.args))
  59. def are_coplanar(*e):
  60. """ Returns True if the given entities are coplanar otherwise False
  61. Parameters
  62. ==========
  63. e: entities to be checked for being coplanar
  64. Returns
  65. =======
  66. Boolean
  67. Examples
  68. ========
  69. >>> from sympy import Point3D, Line3D
  70. >>> from sympy.geometry.util import are_coplanar
  71. >>> a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1))
  72. >>> b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1))
  73. >>> c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9))
  74. >>> are_coplanar(a, b, c)
  75. False
  76. """
  77. from .line import LinearEntity3D
  78. from .plane import Plane
  79. # XXX update tests for coverage
  80. e = set(e)
  81. # first work with a Plane if present
  82. for i in list(e):
  83. if isinstance(i, Plane):
  84. e.remove(i)
  85. return all(p.is_coplanar(i) for p in e)
  86. if all(isinstance(i, Point3D) for i in e):
  87. if len(e) < 3:
  88. return False
  89. # remove pts that are collinear with 2 pts
  90. a, b = e.pop(), e.pop()
  91. for i in list(e):
  92. if Point3D.are_collinear(a, b, i):
  93. e.remove(i)
  94. if not e:
  95. return False
  96. else:
  97. # define a plane
  98. p = Plane(a, b, e.pop())
  99. for i in e:
  100. if i not in p:
  101. return False
  102. return True
  103. else:
  104. pt3d = []
  105. for i in e:
  106. if isinstance(i, Point3D):
  107. pt3d.append(i)
  108. elif isinstance(i, LinearEntity3D):
  109. pt3d.extend(i.args)
  110. elif isinstance(i, GeometryEntity): # XXX we should have a GeometryEntity3D class so we can tell the difference between 2D and 3D -- here we just want to deal with 2D objects; if new 3D objects are encountered that we didn't handle above, an error should be raised
  111. # all 2D objects have some Point that defines them; so convert those points to 3D pts by making z=0
  112. for p in i.args:
  113. if isinstance(p, Point):
  114. pt3d.append(Point3D(*(p.args + (0,))))
  115. return are_coplanar(*pt3d)
  116. def are_similar(e1, e2):
  117. """Are two geometrical entities similar.
  118. Can one geometrical entity be uniformly scaled to the other?
  119. Parameters
  120. ==========
  121. e1 : GeometryEntity
  122. e2 : GeometryEntity
  123. Returns
  124. =======
  125. are_similar : boolean
  126. Raises
  127. ======
  128. GeometryError
  129. When `e1` and `e2` cannot be compared.
  130. Notes
  131. =====
  132. If the two objects are equal then they are similar.
  133. See Also
  134. ========
  135. sympy.geometry.entity.GeometryEntity.is_similar
  136. Examples
  137. ========
  138. >>> from sympy import Point, Circle, Triangle, are_similar
  139. >>> c1, c2 = Circle(Point(0, 0), 4), Circle(Point(1, 4), 3)
  140. >>> t1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1))
  141. >>> t2 = Triangle(Point(0, 0), Point(2, 0), Point(0, 2))
  142. >>> t3 = Triangle(Point(0, 0), Point(3, 0), Point(0, 1))
  143. >>> are_similar(t1, t2)
  144. True
  145. >>> are_similar(t1, t3)
  146. False
  147. """
  148. if e1 == e2:
  149. return True
  150. is_similar1 = getattr(e1, 'is_similar', None)
  151. if is_similar1:
  152. return is_similar1(e2)
  153. is_similar2 = getattr(e2, 'is_similar', None)
  154. if is_similar2:
  155. return is_similar2(e1)
  156. n1 = e1.__class__.__name__
  157. n2 = e2.__class__.__name__
  158. raise GeometryError(
  159. "Cannot test similarity between %s and %s" % (n1, n2))
  160. def centroid(*args):
  161. """Find the centroid (center of mass) of the collection containing only Points,
  162. Segments or Polygons. The centroid is the weighted average of the individual centroid
  163. where the weights are the lengths (of segments) or areas (of polygons).
  164. Overlapping regions will add to the weight of that region.
  165. If there are no objects (or a mixture of objects) then None is returned.
  166. See Also
  167. ========
  168. sympy.geometry.point.Point, sympy.geometry.line.Segment,
  169. sympy.geometry.polygon.Polygon
  170. Examples
  171. ========
  172. >>> from sympy import Point, Segment, Polygon
  173. >>> from sympy.geometry.util import centroid
  174. >>> p = Polygon((0, 0), (10, 0), (10, 10))
  175. >>> q = p.translate(0, 20)
  176. >>> p.centroid, q.centroid
  177. (Point2D(20/3, 10/3), Point2D(20/3, 70/3))
  178. >>> centroid(p, q)
  179. Point2D(20/3, 40/3)
  180. >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
  181. >>> centroid(p, q)
  182. Point2D(1, 2 - sqrt(2))
  183. >>> centroid(Point(0, 0), Point(2, 0))
  184. Point2D(1, 0)
  185. Stacking 3 polygons on top of each other effectively triples the
  186. weight of that polygon:
  187. >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
  188. >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
  189. >>> centroid(p, q)
  190. Point2D(3/2, 1/2)
  191. >>> centroid(p, p, p, q) # centroid x-coord shifts left
  192. Point2D(11/10, 1/2)
  193. Stacking the squares vertically above and below p has the same
  194. effect:
  195. >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
  196. Point2D(11/10, 1/2)
  197. """
  198. from .line import Segment
  199. from .polygon import Polygon
  200. if args:
  201. if all(isinstance(g, Point) for g in args):
  202. c = Point(0, 0)
  203. for g in args:
  204. c += g
  205. den = len(args)
  206. elif all(isinstance(g, Segment) for g in args):
  207. c = Point(0, 0)
  208. L = 0
  209. for g in args:
  210. l = g.length
  211. c += g.midpoint*l
  212. L += l
  213. den = L
  214. elif all(isinstance(g, Polygon) for g in args):
  215. c = Point(0, 0)
  216. A = 0
  217. for g in args:
  218. a = g.area
  219. c += g.centroid*a
  220. A += a
  221. den = A
  222. c /= den
  223. return c.func(*[i.simplify() for i in c.args])
  224. def closest_points(*args):
  225. """Return the subset of points from a set of points that were
  226. the closest to each other in the 2D plane.
  227. Parameters
  228. ==========
  229. args
  230. A collection of Points on 2D plane.
  231. Notes
  232. =====
  233. This can only be performed on a set of points whose coordinates can
  234. be ordered on the number line. If there are no ties then a single
  235. pair of Points will be in the set.
  236. Examples
  237. ========
  238. >>> from sympy import closest_points, Triangle
  239. >>> Triangle(sss=(3, 4, 5)).args
  240. (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
  241. >>> closest_points(*_)
  242. {(Point2D(0, 0), Point2D(3, 0))}
  243. References
  244. ==========
  245. .. [1] https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html
  246. .. [2] Sweep line algorithm
  247. https://en.wikipedia.org/wiki/Sweep_line_algorithm
  248. """
  249. p = [Point2D(i) for i in set(args)]
  250. if len(p) < 2:
  251. raise ValueError('At least 2 distinct points must be given.')
  252. try:
  253. p.sort(key=lambda x: x.args)
  254. except TypeError:
  255. raise ValueError("The points could not be sorted.")
  256. if not all(i.is_Rational for j in p for i in j.args):
  257. def hypot(x, y):
  258. arg = x*x + y*y
  259. if arg.is_Rational:
  260. return _sqrt(arg)
  261. return sqrt(arg)
  262. else:
  263. from math import hypot
  264. rv = [(0, 1)]
  265. best_dist = hypot(p[1].x - p[0].x, p[1].y - p[0].y)
  266. i = 2
  267. left = 0
  268. box = deque([0, 1])
  269. while i < len(p):
  270. while left < i and p[i][0] - p[left][0] > best_dist:
  271. box.popleft()
  272. left += 1
  273. for j in box:
  274. d = hypot(p[i].x - p[j].x, p[i].y - p[j].y)
  275. if d < best_dist:
  276. rv = [(j, i)]
  277. elif d == best_dist:
  278. rv.append((j, i))
  279. else:
  280. continue
  281. best_dist = d
  282. box.append(i)
  283. i += 1
  284. return {tuple([p[i] for i in pair]) for pair in rv}
  285. def convex_hull(*args, polygon=True):
  286. """The convex hull surrounding the Points contained in the list of entities.
  287. Parameters
  288. ==========
  289. args : a collection of Points, Segments and/or Polygons
  290. Optional parameters
  291. ===================
  292. polygon : Boolean. If True, returns a Polygon, if false a tuple, see below.
  293. Default is True.
  294. Returns
  295. =======
  296. convex_hull : Polygon if ``polygon`` is True else as a tuple `(U, L)` where
  297. ``L`` and ``U`` are the lower and upper hulls, respectively.
  298. Notes
  299. =====
  300. This can only be performed on a set of points whose coordinates can
  301. be ordered on the number line.
  302. See Also
  303. ========
  304. sympy.geometry.point.Point, sympy.geometry.polygon.Polygon
  305. Examples
  306. ========
  307. >>> from sympy import convex_hull
  308. >>> points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)]
  309. >>> convex_hull(*points)
  310. Polygon(Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4))
  311. >>> convex_hull(*points, **dict(polygon=False))
  312. ([Point2D(-5, 2), Point2D(15, 4)],
  313. [Point2D(-5, 2), Point2D(1, 1), Point2D(3, 1), Point2D(15, 4)])
  314. References
  315. ==========
  316. .. [1] https://en.wikipedia.org/wiki/Graham_scan
  317. .. [2] Andrew's Monotone Chain Algorithm
  318. (A.M. Andrew,
  319. "Another Efficient Algorithm for Convex Hulls in Two Dimensions", 1979)
  320. https://web.archive.org/web/20210511015444/http://geomalgorithms.com/a10-_hull-1.html
  321. """
  322. from .line import Segment
  323. from .polygon import Polygon
  324. p = OrderedSet()
  325. for e in args:
  326. if not isinstance(e, GeometryEntity):
  327. try:
  328. e = Point(e)
  329. except NotImplementedError:
  330. raise ValueError('%s is not a GeometryEntity and cannot be made into Point' % str(e))
  331. if isinstance(e, Point):
  332. p.add(e)
  333. elif isinstance(e, Segment):
  334. p.update(e.points)
  335. elif isinstance(e, Polygon):
  336. p.update(e.vertices)
  337. else:
  338. raise NotImplementedError(
  339. 'Convex hull for %s not implemented.' % type(e))
  340. # make sure all our points are of the same dimension
  341. if any(len(x) != 2 for x in p):
  342. raise ValueError('Can only compute the convex hull in two dimensions')
  343. p = list(p)
  344. if len(p) == 1:
  345. return p[0] if polygon else (p[0], None)
  346. elif len(p) == 2:
  347. s = Segment(p[0], p[1])
  348. return s if polygon else (s, None)
  349. def _orientation(p, q, r):
  350. '''Return positive if p-q-r are clockwise, neg if ccw, zero if
  351. collinear.'''
  352. return (q.y - p.y)*(r.x - p.x) - (q.x - p.x)*(r.y - p.y)
  353. # scan to find upper and lower convex hulls of a set of 2d points.
  354. U = []
  355. L = []
  356. try:
  357. p.sort(key=lambda x: x.args)
  358. except TypeError:
  359. raise ValueError("The points could not be sorted.")
  360. for p_i in p:
  361. while len(U) > 1 and _orientation(U[-2], U[-1], p_i) <= 0:
  362. U.pop()
  363. while len(L) > 1 and _orientation(L[-2], L[-1], p_i) >= 0:
  364. L.pop()
  365. U.append(p_i)
  366. L.append(p_i)
  367. U.reverse()
  368. convexHull = tuple(L + U[1:-1])
  369. if len(convexHull) == 2:
  370. s = Segment(convexHull[0], convexHull[1])
  371. return s if polygon else (s, None)
  372. if polygon:
  373. return Polygon(*convexHull)
  374. else:
  375. U.reverse()
  376. return (U, L)
  377. def farthest_points(*args):
  378. """Return the subset of points from a set of points that were
  379. the furthest apart from each other in the 2D plane.
  380. Parameters
  381. ==========
  382. args
  383. A collection of Points on 2D plane.
  384. Notes
  385. =====
  386. This can only be performed on a set of points whose coordinates can
  387. be ordered on the number line. If there are no ties then a single
  388. pair of Points will be in the set.
  389. Examples
  390. ========
  391. >>> from sympy.geometry import farthest_points, Triangle
  392. >>> Triangle(sss=(3, 4, 5)).args
  393. (Point2D(0, 0), Point2D(3, 0), Point2D(3, 4))
  394. >>> farthest_points(*_)
  395. {(Point2D(0, 0), Point2D(3, 4))}
  396. References
  397. ==========
  398. .. [1] https://code.activestate.com/recipes/117225-convex-hull-and-diameter-of-2d-point-sets/
  399. .. [2] Rotating Callipers Technique
  400. https://en.wikipedia.org/wiki/Rotating_calipers
  401. """
  402. def rotatingCalipers(Points):
  403. U, L = convex_hull(*Points, **{"polygon": False})
  404. if L is None:
  405. if isinstance(U, Point):
  406. raise ValueError('At least two distinct points must be given.')
  407. yield U.args
  408. else:
  409. i = 0
  410. j = len(L) - 1
  411. while i < len(U) - 1 or j > 0:
  412. yield U[i], L[j]
  413. # if all the way through one side of hull, advance the other side
  414. if i == len(U) - 1:
  415. j -= 1
  416. elif j == 0:
  417. i += 1
  418. # still points left on both lists, compare slopes of next hull edges
  419. # being careful to avoid divide-by-zero in slope calculation
  420. elif (U[i+1].y - U[i].y) * (L[j].x - L[j-1].x) > \
  421. (L[j].y - L[j-1].y) * (U[i+1].x - U[i].x):
  422. i += 1
  423. else:
  424. j -= 1
  425. p = [Point2D(i) for i in set(args)]
  426. if not all(i.is_Rational for j in p for i in j.args):
  427. def hypot(x, y):
  428. arg = x*x + y*y
  429. if arg.is_Rational:
  430. return _sqrt(arg)
  431. return sqrt(arg)
  432. else:
  433. from math import hypot
  434. rv = []
  435. diam = 0
  436. for pair in rotatingCalipers(args):
  437. h, q = _ordered_points(pair)
  438. d = hypot(h.x - q.x, h.y - q.y)
  439. if d > diam:
  440. rv = [(h, q)]
  441. elif d == diam:
  442. rv.append((h, q))
  443. else:
  444. continue
  445. diam = d
  446. return set(rv)
  447. def idiff(eq, y, x, n=1):
  448. """Return ``dy/dx`` assuming that ``eq == 0``.
  449. Parameters
  450. ==========
  451. y : the dependent variable or a list of dependent variables (with y first)
  452. x : the variable that the derivative is being taken with respect to
  453. n : the order of the derivative (default is 1)
  454. Examples
  455. ========
  456. >>> from sympy.abc import x, y, a
  457. >>> from sympy.geometry.util import idiff
  458. >>> circ = x**2 + y**2 - 4
  459. >>> idiff(circ, y, x)
  460. -x/y
  461. >>> idiff(circ, y, x, 2).simplify()
  462. (-x**2 - y**2)/y**3
  463. Here, ``a`` is assumed to be independent of ``x``:
  464. >>> idiff(x + a + y, y, x)
  465. -1
  466. Now the x-dependence of ``a`` is made explicit by listing ``a`` after
  467. ``y`` in a list.
  468. >>> idiff(x + a + y, [y, a], x)
  469. -Derivative(a, x) - 1
  470. See Also
  471. ========
  472. sympy.core.function.Derivative: represents unevaluated derivatives
  473. sympy.core.function.diff: explicitly differentiates wrt symbols
  474. """
  475. if is_sequence(y):
  476. dep = set(y)
  477. y = y[0]
  478. elif isinstance(y, Symbol):
  479. dep = {y}
  480. elif isinstance(y, Function):
  481. pass
  482. else:
  483. raise ValueError("expecting x-dependent symbol(s) or function(s) but got: %s" % y)
  484. f = {s: Function(s.name)(x) for s in eq.free_symbols
  485. if s != x and s in dep}
  486. if isinstance(y, Symbol):
  487. dydx = Function(y.name)(x).diff(x)
  488. else:
  489. dydx = y.diff(x)
  490. eq = eq.subs(f)
  491. derivs = {}
  492. for i in range(n):
  493. # equation will be linear in dydx, a*dydx + b, so dydx = -b/a
  494. deq = eq.diff(x)
  495. b = deq.xreplace({dydx: S.Zero})
  496. a = (deq - b).xreplace({dydx: S.One})
  497. yp = factor_terms(expand_mul(cancel((-b/a).subs(derivs)), deep=False))
  498. if i == n - 1:
  499. return yp.subs([(v, k) for k, v in f.items()])
  500. derivs[dydx] = yp
  501. eq = dydx - yp
  502. dydx = dydx.diff(x)
  503. def intersection(*entities, pairwise=False, **kwargs):
  504. """The intersection of a collection of GeometryEntity instances.
  505. Parameters
  506. ==========
  507. entities : sequence of GeometryEntity
  508. pairwise (keyword argument) : Can be either True or False
  509. Returns
  510. =======
  511. intersection : list of GeometryEntity
  512. Raises
  513. ======
  514. NotImplementedError
  515. When unable to calculate intersection.
  516. Notes
  517. =====
  518. The intersection of any geometrical entity with itself should return
  519. a list with one item: the entity in question.
  520. An intersection requires two or more entities. If only a single
  521. entity is given then the function will return an empty list.
  522. It is possible for `intersection` to miss intersections that one
  523. knows exists because the required quantities were not fully
  524. simplified internally.
  525. Reals should be converted to Rationals, e.g. Rational(str(real_num))
  526. or else failures due to floating point issues may result.
  527. Case 1: When the keyword argument 'pairwise' is False (default value):
  528. In this case, the function returns a list of intersections common to
  529. all entities.
  530. Case 2: When the keyword argument 'pairwise' is True:
  531. In this case, the functions returns a list intersections that occur
  532. between any pair of entities.
  533. See Also
  534. ========
  535. sympy.geometry.entity.GeometryEntity.intersection
  536. Examples
  537. ========
  538. >>> from sympy import Ray, Circle, intersection
  539. >>> c = Circle((0, 1), 1)
  540. >>> intersection(c, c.center)
  541. []
  542. >>> right = Ray((0, 0), (1, 0))
  543. >>> up = Ray((0, 0), (0, 1))
  544. >>> intersection(c, right, up)
  545. [Point2D(0, 0)]
  546. >>> intersection(c, right, up, pairwise=True)
  547. [Point2D(0, 0), Point2D(0, 2)]
  548. >>> left = Ray((1, 0), (0, 0))
  549. >>> intersection(right, left)
  550. [Segment2D(Point2D(0, 0), Point2D(1, 0))]
  551. """
  552. if len(entities) <= 1:
  553. return []
  554. # entities may be an immutable tuple
  555. entities = list(entities)
  556. for i, e in enumerate(entities):
  557. if not isinstance(e, GeometryEntity):
  558. entities[i] = Point(e)
  559. if not pairwise:
  560. # find the intersection common to all objects
  561. res = entities[0].intersection(entities[1])
  562. for entity in entities[2:]:
  563. newres = []
  564. for x in res:
  565. newres.extend(x.intersection(entity))
  566. res = newres
  567. return res
  568. # find all pairwise intersections
  569. ans = []
  570. for j in range(len(entities)):
  571. for k in range(j + 1, len(entities)):
  572. ans.extend(intersection(entities[j], entities[k]))
  573. return list(ordered(set(ans)))