util.py 20 KB

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