entity.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. """The definition of the base geometrical entity with attributes common to
  2. all derived geometrical entities.
  3. Contains
  4. ========
  5. GeometryEntity
  6. GeometricSet
  7. Notes
  8. =====
  9. A GeometryEntity is any object that has special geometric properties.
  10. A GeometrySet is a superclass of any GeometryEntity that can also
  11. be viewed as a sympy.sets.Set. In particular, points are the only
  12. GeometryEntity not considered a Set.
  13. Rn is a GeometrySet representing n-dimensional Euclidean space. R2 and
  14. R3 are currently the only ambient spaces implemented.
  15. """
  16. from __future__ import annotations
  17. from sympy.core.basic import Basic
  18. from sympy.core.containers import Tuple
  19. from sympy.core.evalf import EvalfMixin, N
  20. from sympy.core.numbers import oo
  21. from sympy.core.symbol import Dummy
  22. from sympy.core.sympify import sympify
  23. from sympy.functions.elementary.trigonometric import cos, sin, atan
  24. from sympy.matrices import eye
  25. from sympy.multipledispatch import dispatch
  26. from sympy.printing import sstr
  27. from sympy.sets import Set, Union, FiniteSet
  28. from sympy.sets.handlers.intersection import intersection_sets
  29. from sympy.sets.handlers.union import union_sets
  30. from sympy.solvers.solvers import solve
  31. from sympy.utilities.misc import func_name
  32. from sympy.utilities.iterables import is_sequence
  33. # How entities are ordered; used by __cmp__ in GeometryEntity
  34. ordering_of_classes = [
  35. "Point2D",
  36. "Point3D",
  37. "Point",
  38. "Segment2D",
  39. "Ray2D",
  40. "Line2D",
  41. "Segment3D",
  42. "Line3D",
  43. "Ray3D",
  44. "Segment",
  45. "Ray",
  46. "Line",
  47. "Plane",
  48. "Triangle",
  49. "RegularPolygon",
  50. "Polygon",
  51. "Circle",
  52. "Ellipse",
  53. "Curve",
  54. "Parabola"
  55. ]
  56. x, y = [Dummy('entity_dummy') for i in range(2)]
  57. T = Dummy('entity_dummy', real=True)
  58. class GeometryEntity(Basic, EvalfMixin):
  59. """The base class for all geometrical entities.
  60. This class does not represent any particular geometric entity, it only
  61. provides the implementation of some methods common to all subclasses.
  62. """
  63. __slots__: tuple[str, ...] = ()
  64. def __cmp__(self, other):
  65. """Comparison of two GeometryEntities."""
  66. n1 = self.__class__.__name__
  67. n2 = other.__class__.__name__
  68. c = (n1 > n2) - (n1 < n2)
  69. if not c:
  70. return 0
  71. i1 = -1
  72. for cls in self.__class__.__mro__:
  73. try:
  74. i1 = ordering_of_classes.index(cls.__name__)
  75. break
  76. except ValueError:
  77. i1 = -1
  78. if i1 == -1:
  79. return c
  80. i2 = -1
  81. for cls in other.__class__.__mro__:
  82. try:
  83. i2 = ordering_of_classes.index(cls.__name__)
  84. break
  85. except ValueError:
  86. i2 = -1
  87. if i2 == -1:
  88. return c
  89. return (i1 > i2) - (i1 < i2)
  90. def __contains__(self, other):
  91. """Subclasses should implement this method for anything more complex than equality."""
  92. if type(self) is type(other):
  93. return self == other
  94. raise NotImplementedError()
  95. def __getnewargs__(self):
  96. """Returns a tuple that will be passed to __new__ on unpickling."""
  97. return tuple(self.args)
  98. def __ne__(self, o):
  99. """Test inequality of two geometrical entities."""
  100. return not self == o
  101. def __new__(cls, *args, **kwargs):
  102. # Points are sequences, but they should not
  103. # be converted to Tuples, so use this detection function instead.
  104. def is_seq_and_not_point(a):
  105. # we cannot use isinstance(a, Point) since we cannot import Point
  106. if hasattr(a, 'is_Point') and a.is_Point:
  107. return False
  108. return is_sequence(a)
  109. args = [Tuple(*a) if is_seq_and_not_point(a) else sympify(a) for a in args]
  110. return Basic.__new__(cls, *args)
  111. def __radd__(self, a):
  112. """Implementation of reverse add method."""
  113. return a.__add__(self)
  114. def __rtruediv__(self, a):
  115. """Implementation of reverse division method."""
  116. return a.__truediv__(self)
  117. def __repr__(self):
  118. """String representation of a GeometryEntity that can be evaluated
  119. by sympy."""
  120. return type(self).__name__ + repr(self.args)
  121. def __rmul__(self, a):
  122. """Implementation of reverse multiplication method."""
  123. return a.__mul__(self)
  124. def __rsub__(self, a):
  125. """Implementation of reverse subtraction method."""
  126. return a.__sub__(self)
  127. def __str__(self):
  128. """String representation of a GeometryEntity."""
  129. return type(self).__name__ + sstr(self.args)
  130. def _eval_subs(self, old, new):
  131. from sympy.geometry.point import Point, Point3D
  132. if is_sequence(old) or is_sequence(new):
  133. if isinstance(self, Point3D):
  134. old = Point3D(old)
  135. new = Point3D(new)
  136. else:
  137. old = Point(old)
  138. new = Point(new)
  139. return self._subs(old, new)
  140. def _repr_svg_(self):
  141. """SVG representation of a GeometryEntity suitable for IPython"""
  142. try:
  143. bounds = self.bounds
  144. except (NotImplementedError, TypeError):
  145. # if we have no SVG representation, return None so IPython
  146. # will fall back to the next representation
  147. return None
  148. if not all(x.is_number and x.is_finite for x in bounds):
  149. return None
  150. svg_top = '''<svg xmlns="http://www.w3.org/2000/svg"
  151. xmlns:xlink="http://www.w3.org/1999/xlink"
  152. width="{1}" height="{2}" viewBox="{0}"
  153. preserveAspectRatio="xMinYMin meet">
  154. <defs>
  155. <marker id="markerCircle" markerWidth="8" markerHeight="8"
  156. refx="5" refy="5" markerUnits="strokeWidth">
  157. <circle cx="5" cy="5" r="1.5" style="stroke: none; fill:#000000;"/>
  158. </marker>
  159. <marker id="markerArrow" markerWidth="13" markerHeight="13" refx="2" refy="4"
  160. orient="auto" markerUnits="strokeWidth">
  161. <path d="M2,2 L2,6 L6,4" style="fill: #000000;" />
  162. </marker>
  163. <marker id="markerReverseArrow" markerWidth="13" markerHeight="13" refx="6" refy="4"
  164. orient="auto" markerUnits="strokeWidth">
  165. <path d="M6,2 L6,6 L2,4" style="fill: #000000;" />
  166. </marker>
  167. </defs>'''
  168. # Establish SVG canvas that will fit all the data + small space
  169. xmin, ymin, xmax, ymax = map(N, bounds)
  170. if xmin == xmax and ymin == ymax:
  171. # This is a point; buffer using an arbitrary size
  172. xmin, ymin, xmax, ymax = xmin - .5, ymin -.5, xmax + .5, ymax + .5
  173. else:
  174. # Expand bounds by a fraction of the data ranges
  175. expand = 0.1 # or 10%; this keeps arrowheads in view (R plots use 4%)
  176. widest_part = max([xmax - xmin, ymax - ymin])
  177. expand_amount = widest_part * expand
  178. xmin -= expand_amount
  179. ymin -= expand_amount
  180. xmax += expand_amount
  181. ymax += expand_amount
  182. dx = xmax - xmin
  183. dy = ymax - ymin
  184. width = min([max([100., dx]), 300])
  185. height = min([max([100., dy]), 300])
  186. scale_factor = 1. if max(width, height) == 0 else max(dx, dy) / max(width, height)
  187. try:
  188. svg = self._svg(scale_factor)
  189. except (NotImplementedError, TypeError):
  190. # if we have no SVG representation, return None so IPython
  191. # will fall back to the next representation
  192. return None
  193. view_box = "{} {} {} {}".format(xmin, ymin, dx, dy)
  194. transform = "matrix(1,0,0,-1,0,{})".format(ymax + ymin)
  195. svg_top = svg_top.format(view_box, width, height)
  196. return svg_top + (
  197. '<g transform="{}">{}</g></svg>'
  198. ).format(transform, svg)
  199. def _svg(self, scale_factor=1., fill_color="#66cc99"):
  200. """Returns SVG path element for the GeometryEntity.
  201. Parameters
  202. ==========
  203. scale_factor : float
  204. Multiplication factor for the SVG stroke-width. Default is 1.
  205. fill_color : str, optional
  206. Hex string for fill color. Default is "#66cc99".
  207. """
  208. raise NotImplementedError()
  209. def _sympy_(self):
  210. return self
  211. @property
  212. def ambient_dimension(self):
  213. """What is the dimension of the space that the object is contained in?"""
  214. raise NotImplementedError()
  215. @property
  216. def bounds(self):
  217. """Return a tuple (xmin, ymin, xmax, ymax) representing the bounding
  218. rectangle for the geometric figure.
  219. """
  220. raise NotImplementedError()
  221. def encloses(self, o):
  222. """
  223. Return True if o is inside (not on or outside) the boundaries of self.
  224. The object will be decomposed into Points and individual Entities need
  225. only define an encloses_point method for their class.
  226. See Also
  227. ========
  228. sympy.geometry.ellipse.Ellipse.encloses_point
  229. sympy.geometry.polygon.Polygon.encloses_point
  230. Examples
  231. ========
  232. >>> from sympy import RegularPolygon, Point, Polygon
  233. >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
  234. >>> t2 = Polygon(*RegularPolygon(Point(0, 0), 2, 3).vertices)
  235. >>> t2.encloses(t)
  236. True
  237. >>> t.encloses(t2)
  238. False
  239. """
  240. from sympy.geometry.point import Point
  241. from sympy.geometry.line import Segment, Ray, Line
  242. from sympy.geometry.ellipse import Ellipse
  243. from sympy.geometry.polygon import Polygon, RegularPolygon
  244. if isinstance(o, Point):
  245. return self.encloses_point(o)
  246. elif isinstance(o, Segment):
  247. return all(self.encloses_point(x) for x in o.points)
  248. elif isinstance(o, (Ray, Line)):
  249. return False
  250. elif isinstance(o, Ellipse):
  251. return self.encloses_point(o.center) and \
  252. self.encloses_point(
  253. Point(o.center.x + o.hradius, o.center.y)) and \
  254. not self.intersection(o)
  255. elif isinstance(o, Polygon):
  256. if isinstance(o, RegularPolygon):
  257. if not self.encloses_point(o.center):
  258. return False
  259. return all(self.encloses_point(v) for v in o.vertices)
  260. raise NotImplementedError()
  261. def equals(self, o):
  262. return self == o
  263. def intersection(self, o):
  264. """
  265. Returns a list of all of the intersections of self with o.
  266. Notes
  267. =====
  268. An entity is not required to implement this method.
  269. If two different types of entities can intersect, the item with
  270. higher index in ordering_of_classes should implement
  271. intersections with anything having a lower index.
  272. See Also
  273. ========
  274. sympy.geometry.util.intersection
  275. """
  276. raise NotImplementedError()
  277. def is_similar(self, other):
  278. """Is this geometrical entity similar to another geometrical entity?
  279. Two entities are similar if a uniform scaling (enlarging or
  280. shrinking) of one of the entities will allow one to obtain the other.
  281. Notes
  282. =====
  283. This method is not intended to be used directly but rather
  284. through the `are_similar` function found in util.py.
  285. An entity is not required to implement this method.
  286. If two different types of entities can be similar, it is only
  287. required that one of them be able to determine this.
  288. See Also
  289. ========
  290. scale
  291. """
  292. raise NotImplementedError()
  293. def reflect(self, line):
  294. """
  295. Reflects an object across a line.
  296. Parameters
  297. ==========
  298. line: Line
  299. Examples
  300. ========
  301. >>> from sympy import pi, sqrt, Line, RegularPolygon
  302. >>> l = Line((0, pi), slope=sqrt(2))
  303. >>> pent = RegularPolygon((1, 2), 1, 5)
  304. >>> rpent = pent.reflect(l)
  305. >>> rpent
  306. RegularPolygon(Point2D(-2*sqrt(2)*pi/3 - 1/3 + 4*sqrt(2)/3, 2/3 + 2*sqrt(2)/3 + 2*pi/3), -1, 5, -atan(2*sqrt(2)) + 3*pi/5)
  307. >>> from sympy import pi, Line, Circle, Point
  308. >>> l = Line((0, pi), slope=1)
  309. >>> circ = Circle(Point(0, 0), 5)
  310. >>> rcirc = circ.reflect(l)
  311. >>> rcirc
  312. Circle(Point2D(-pi, pi), -5)
  313. """
  314. from sympy.geometry.point import Point
  315. g = self
  316. l = line
  317. o = Point(0, 0)
  318. if l.slope.is_zero:
  319. v = l.args[0].y
  320. if not v: # x-axis
  321. return g.scale(y=-1)
  322. reps = [(p, p.translate(y=2*(v - p.y))) for p in g.atoms(Point)]
  323. elif l.slope is oo:
  324. v = l.args[0].x
  325. if not v: # y-axis
  326. return g.scale(x=-1)
  327. reps = [(p, p.translate(x=2*(v - p.x))) for p in g.atoms(Point)]
  328. else:
  329. if not hasattr(g, 'reflect') and not all(
  330. isinstance(arg, Point) for arg in g.args):
  331. raise NotImplementedError(
  332. 'reflect undefined or non-Point args in %s' % g)
  333. a = atan(l.slope)
  334. c = l.coefficients
  335. d = -c[-1]/c[1] # y-intercept
  336. # apply the transform to a single point
  337. xf = Point(x, y)
  338. xf = xf.translate(y=-d).rotate(-a, o).scale(y=-1
  339. ).rotate(a, o).translate(y=d)
  340. # replace every point using that transform
  341. reps = [(p, xf.xreplace({x: p.x, y: p.y})) for p in g.atoms(Point)]
  342. return g.xreplace(dict(reps))
  343. def rotate(self, angle, pt=None):
  344. """Rotate ``angle`` radians counterclockwise about Point ``pt``.
  345. The default pt is the origin, Point(0, 0)
  346. See Also
  347. ========
  348. scale, translate
  349. Examples
  350. ========
  351. >>> from sympy import Point, RegularPolygon, Polygon, pi
  352. >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
  353. >>> t # vertex on x axis
  354. Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
  355. >>> t.rotate(pi/2) # vertex on y axis now
  356. Triangle(Point2D(0, 1), Point2D(-sqrt(3)/2, -1/2), Point2D(sqrt(3)/2, -1/2))
  357. """
  358. newargs = []
  359. for a in self.args:
  360. if isinstance(a, GeometryEntity):
  361. newargs.append(a.rotate(angle, pt))
  362. else:
  363. newargs.append(a)
  364. return type(self)(*newargs)
  365. def scale(self, x=1, y=1, pt=None):
  366. """Scale the object by multiplying the x,y-coordinates by x and y.
  367. If pt is given, the scaling is done relative to that point; the
  368. object is shifted by -pt, scaled, and shifted by pt.
  369. See Also
  370. ========
  371. rotate, translate
  372. Examples
  373. ========
  374. >>> from sympy import RegularPolygon, Point, Polygon
  375. >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
  376. >>> t
  377. Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
  378. >>> t.scale(2)
  379. Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)/2), Point2D(-1, -sqrt(3)/2))
  380. >>> t.scale(2, 2)
  381. Triangle(Point2D(2, 0), Point2D(-1, sqrt(3)), Point2D(-1, -sqrt(3)))
  382. """
  383. from sympy.geometry.point import Point
  384. if pt:
  385. pt = Point(pt, dim=2)
  386. return self.translate(*(-pt).args).scale(x, y).translate(*pt.args)
  387. return type(self)(*[a.scale(x, y) for a in self.args]) # if this fails, override this class
  388. def translate(self, x=0, y=0):
  389. """Shift the object by adding to the x,y-coordinates the values x and y.
  390. See Also
  391. ========
  392. rotate, scale
  393. Examples
  394. ========
  395. >>> from sympy import RegularPolygon, Point, Polygon
  396. >>> t = Polygon(*RegularPolygon(Point(0, 0), 1, 3).vertices)
  397. >>> t
  398. Triangle(Point2D(1, 0), Point2D(-1/2, sqrt(3)/2), Point2D(-1/2, -sqrt(3)/2))
  399. >>> t.translate(2)
  400. Triangle(Point2D(3, 0), Point2D(3/2, sqrt(3)/2), Point2D(3/2, -sqrt(3)/2))
  401. >>> t.translate(2, 2)
  402. Triangle(Point2D(3, 2), Point2D(3/2, sqrt(3)/2 + 2), Point2D(3/2, 2 - sqrt(3)/2))
  403. """
  404. newargs = []
  405. for a in self.args:
  406. if isinstance(a, GeometryEntity):
  407. newargs.append(a.translate(x, y))
  408. else:
  409. newargs.append(a)
  410. return self.func(*newargs)
  411. def parameter_value(self, other, t):
  412. """Return the parameter corresponding to the given point.
  413. Evaluating an arbitrary point of the entity at this parameter
  414. value will return the given point.
  415. Examples
  416. ========
  417. >>> from sympy import Line, Point
  418. >>> from sympy.abc import t
  419. >>> a = Point(0, 0)
  420. >>> b = Point(2, 2)
  421. >>> Line(a, b).parameter_value((1, 1), t)
  422. {t: 1/2}
  423. >>> Line(a, b).arbitrary_point(t).subs(_)
  424. Point2D(1, 1)
  425. """
  426. from sympy.geometry.point import Point
  427. if not isinstance(other, GeometryEntity):
  428. other = Point(other, dim=self.ambient_dimension)
  429. if not isinstance(other, Point):
  430. raise ValueError("other must be a point")
  431. sol = solve(self.arbitrary_point(T) - other, T, dict=True)
  432. if not sol:
  433. raise ValueError("Given point is not on %s" % func_name(self))
  434. return {t: sol[0][T]}
  435. class GeometrySet(GeometryEntity, Set):
  436. """Parent class of all GeometryEntity that are also Sets
  437. (compatible with sympy.sets)
  438. """
  439. __slots__ = ()
  440. def _contains(self, other):
  441. """sympy.sets uses the _contains method, so include it for compatibility."""
  442. if isinstance(other, Set) and other.is_FiniteSet:
  443. return all(self.__contains__(i) for i in other)
  444. return self.__contains__(other)
  445. @dispatch(GeometrySet, Set) # type:ignore # noqa:F811
  446. def union_sets(self, o): # noqa:F811
  447. """ Returns the union of self and o
  448. for use with sympy.sets.Set, if possible. """
  449. # if its a FiniteSet, merge any points
  450. # we contain and return a union with the rest
  451. if o.is_FiniteSet:
  452. other_points = [p for p in o if not self._contains(p)]
  453. if len(other_points) == len(o):
  454. return None
  455. return Union(self, FiniteSet(*other_points))
  456. if self._contains(o):
  457. return self
  458. return None
  459. @dispatch(GeometrySet, Set) # type: ignore # noqa:F811
  460. def intersection_sets(self, o): # noqa:F811
  461. """ Returns a sympy.sets.Set of intersection objects,
  462. if possible. """
  463. from sympy.geometry.point import Point
  464. try:
  465. # if o is a FiniteSet, find the intersection directly
  466. # to avoid infinite recursion
  467. if o.is_FiniteSet:
  468. inter = FiniteSet(*(p for p in o if self.contains(p)))
  469. else:
  470. inter = self.intersection(o)
  471. except NotImplementedError:
  472. # sympy.sets.Set.reduce expects None if an object
  473. # doesn't know how to simplify
  474. return None
  475. # put the points in a FiniteSet
  476. points = FiniteSet(*[p for p in inter if isinstance(p, Point)])
  477. non_points = [p for p in inter if not isinstance(p, Point)]
  478. return Union(*(non_points + [points]))
  479. def translate(x, y):
  480. """Return the matrix to translate a 2-D point by x and y."""
  481. rv = eye(3)
  482. rv[2, 0] = x
  483. rv[2, 1] = y
  484. return rv
  485. def scale(x, y, pt=None):
  486. """Return the matrix to multiply a 2-D point's coordinates by x and y.
  487. If pt is given, the scaling is done relative to that point."""
  488. rv = eye(3)
  489. rv[0, 0] = x
  490. rv[1, 1] = y
  491. if pt:
  492. from sympy.geometry.point import Point
  493. pt = Point(pt, dim=2)
  494. tr1 = translate(*(-pt).args)
  495. tr2 = translate(*pt.args)
  496. return tr1*rv*tr2
  497. return rv
  498. def rotate(th):
  499. """Return the matrix to rotate a 2-D point about the origin by ``angle``.
  500. The angle is measured in radians. To Point a point about a point other
  501. then the origin, translate the Point, do the rotation, and
  502. translate it back:
  503. >>> from sympy.geometry.entity import rotate, translate
  504. >>> from sympy import Point, pi
  505. >>> rot_about_11 = translate(-1, -1)*rotate(pi/2)*translate(1, 1)
  506. >>> Point(1, 1).transform(rot_about_11)
  507. Point2D(1, 1)
  508. >>> Point(0, 0).transform(rot_about_11)
  509. Point2D(2, 0)
  510. """
  511. s = sin(th)
  512. rv = eye(3)*cos(th)
  513. rv[0, 1] = s
  514. rv[1, 0] = -s
  515. rv[2, 2] = 1
  516. return rv