entity.py 20 KB

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