base.py 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. """Base geometry class and utilities.
  2. Note: a third, z, coordinate value may be used when constructing
  3. geometry objects, but has no effect on geometric analysis. All
  4. operations are performed in the x-y plane. Thus, geometries with
  5. different z values may intersect or be equal.
  6. """
  7. import re
  8. from warnings import warn
  9. import numpy as np
  10. import shapely
  11. from shapely._geometry_helpers import _geom_factory
  12. from shapely.constructive import BufferCapStyle, BufferJoinStyle
  13. from shapely.coords import CoordinateSequence
  14. from shapely.decorators import deprecate_positional
  15. from shapely.errors import GeometryTypeError, GEOSException, ShapelyDeprecationWarning
  16. GEOMETRY_TYPES = [
  17. "Point",
  18. "LineString",
  19. "LinearRing",
  20. "Polygon",
  21. "MultiPoint",
  22. "MultiLineString",
  23. "MultiPolygon",
  24. "GeometryCollection",
  25. ]
  26. _geos_ge_312 = shapely.geos_version >= (3, 12, 0)
  27. def geom_factory(g, parent=None):
  28. """Create a Shapely geometry instance from a pointer to a GEOS geometry.
  29. .. warning::
  30. The GEOS library used to create the the GEOS geometry pointer
  31. and the GEOS library used by Shapely must be exactly the same, or
  32. unexpected results or segfaults may occur.
  33. .. deprecated:: 2.0
  34. Deprecated in Shapely 2.0, and will be removed in a future version.
  35. """
  36. warn(
  37. "The 'geom_factory' function is deprecated in Shapely 2.0, and will be "
  38. "removed in a future version",
  39. FutureWarning,
  40. stacklevel=2,
  41. )
  42. return _geom_factory(g)
  43. def dump_coords(geom):
  44. """Dump coordinates of a geometry in the same order as data packing."""
  45. if not isinstance(geom, BaseGeometry):
  46. raise ValueError(
  47. "Must be instance of a geometry class; found " + geom.__class__.__name__
  48. )
  49. elif geom.geom_type in ("Point", "LineString", "LinearRing"):
  50. return geom.coords[:]
  51. elif geom.geom_type == "Polygon":
  52. return geom.exterior.coords[:] + [i.coords[:] for i in geom.interiors]
  53. elif geom.geom_type.startswith("Multi") or geom.geom_type == "GeometryCollection":
  54. # Recursive call
  55. return [dump_coords(part) for part in geom.geoms]
  56. else:
  57. raise GeometryTypeError("Unhandled geometry type: " + repr(geom.geom_type))
  58. def _maybe_unpack(result):
  59. if result.ndim == 0:
  60. # convert numpy 0-d array / scalar to python scalar
  61. return result.item()
  62. else:
  63. # >=1 dim array
  64. return result
  65. class CAP_STYLE:
  66. """Buffer cap styles."""
  67. round = BufferCapStyle.round
  68. flat = BufferCapStyle.flat
  69. square = BufferCapStyle.square
  70. class JOIN_STYLE:
  71. """Buffer join styles."""
  72. round = BufferJoinStyle.round
  73. mitre = BufferJoinStyle.mitre
  74. bevel = BufferJoinStyle.bevel
  75. class BaseGeometry(shapely.Geometry):
  76. """Provides GEOS spatial predicates and topological operations."""
  77. __slots__ = []
  78. def __new__(self):
  79. """Directly calling the base class 'BaseGeometry()' is deprecated.
  80. This will raise an error in the future. To create an empty geometry,
  81. use one of the subclasses instead, for example 'GeometryCollection()'
  82. """
  83. warn(
  84. "Directly calling the base class 'BaseGeometry()' is deprecated, and "
  85. "will raise an error in the future. To create an empty geometry, "
  86. "use one of the subclasses instead, for example 'GeometryCollection()'.",
  87. ShapelyDeprecationWarning,
  88. stacklevel=2,
  89. )
  90. return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY")
  91. @property
  92. def _ndim(self):
  93. return shapely.get_coordinate_dimension(self)
  94. def __bool__(self):
  95. """Return True if the geometry is not empty, else False."""
  96. return self.is_empty is False
  97. def __nonzero__(self):
  98. """Return True if the geometry is not empty, else False."""
  99. return self.__bool__()
  100. def __format__(self, format_spec):
  101. """Format a geometry using a format specification."""
  102. # bypass regexp for simple cases
  103. if format_spec == "":
  104. return shapely.to_wkt(self, rounding_precision=-1)
  105. elif format_spec == "x":
  106. return shapely.to_wkb(self, hex=True).lower()
  107. elif format_spec == "X":
  108. return shapely.to_wkb(self, hex=True)
  109. # fmt: off
  110. format_spec_regexp = (
  111. "(?:0?\\.(?P<prec>[0-9]+))?"
  112. "(?P<fmt_code>[fFgGxX]?)"
  113. )
  114. # fmt: on
  115. match = re.fullmatch(format_spec_regexp, format_spec)
  116. if match is None:
  117. raise ValueError(f"invalid format specifier: {format_spec}")
  118. prec, fmt_code = match.groups()
  119. if prec:
  120. prec = int(prec)
  121. else:
  122. # GEOS has a default rounding_precision -1
  123. prec = -1
  124. if not fmt_code:
  125. fmt_code = "g"
  126. if fmt_code in ("g", "G"):
  127. res = shapely.to_wkt(self, rounding_precision=prec, trim=True)
  128. elif fmt_code in ("f", "F"):
  129. res = shapely.to_wkt(self, rounding_precision=prec, trim=False)
  130. elif fmt_code in ("x", "X"):
  131. raise ValueError("hex representation does not specify precision")
  132. else:
  133. raise NotImplementedError(f"unhandled fmt_code: {fmt_code}")
  134. if fmt_code.isupper():
  135. return res.upper()
  136. else:
  137. return res
  138. def __repr__(self):
  139. """Return a string representation of the geometry."""
  140. try:
  141. wkt = super().__str__()
  142. except (GEOSException, ValueError):
  143. # we never want a repr() to fail; that can be very confusing
  144. return f"<shapely.{self.__class__.__name__} Exception in WKT writer>"
  145. # the total length is limited to 80 characters including brackets
  146. max_length = 78
  147. if len(wkt) > max_length:
  148. return f"<{wkt[: max_length - 3]}...>"
  149. return f"<{wkt}>"
  150. def __str__(self):
  151. """Return a string representation of the geometry."""
  152. return self.wkt
  153. def __reduce__(self):
  154. """Pickle support."""
  155. return (shapely.from_wkb, (shapely.to_wkb(self, include_srid=True),))
  156. # Operators
  157. # ---------
  158. def __and__(self, other):
  159. """Return the intersection of the geometries."""
  160. return self.intersection(other)
  161. def __or__(self, other):
  162. """Return the union of the geometries."""
  163. return self.union(other)
  164. def __sub__(self, other):
  165. """Return the difference of the geometries."""
  166. return self.difference(other)
  167. def __xor__(self, other):
  168. """Return the symmetric difference of the geometries."""
  169. return self.symmetric_difference(other)
  170. # Coordinate access
  171. # -----------------
  172. @property
  173. def coords(self):
  174. """Access to geometry's coordinates (CoordinateSequence)."""
  175. has_z = self.has_z
  176. has_m = self.has_m if _geos_ge_312 else False
  177. coords_array = shapely.get_coordinates(self, include_z=has_z, include_m=has_m)
  178. return CoordinateSequence(coords_array)
  179. @property
  180. def xy(self):
  181. """Separate arrays of X and Y coordinate values."""
  182. raise NotImplementedError
  183. # Python feature protocol
  184. @property
  185. def __geo_interface__(self):
  186. """Dictionary representation of the geometry."""
  187. raise NotImplementedError
  188. # Type of geometry and its representations
  189. # ----------------------------------------
  190. def geometryType(self):
  191. """Get the geometry type (deprecated).
  192. .. deprecated:: 2.0
  193. Use the :py:attr:`geom_type` attribute instead.
  194. """
  195. warn(
  196. "The 'GeometryType()' method is deprecated, and will be removed in "
  197. "the future. You can use the 'geom_type' attribute instead.",
  198. ShapelyDeprecationWarning,
  199. stacklevel=2,
  200. )
  201. return self.geom_type
  202. @property
  203. def type(self):
  204. """Get the geometry type (deprecated).
  205. .. deprecated:: 2.0
  206. Use the :py:attr:`geom_type` attribute instead.
  207. """
  208. warn(
  209. "The 'type' attribute is deprecated, and will be removed in "
  210. "the future. You can use the 'geom_type' attribute instead.",
  211. ShapelyDeprecationWarning,
  212. stacklevel=2,
  213. )
  214. return self.geom_type
  215. @property
  216. def wkt(self):
  217. """WKT representation of the geometry."""
  218. # TODO(shapely-2.0) keep default of not trimming?
  219. return shapely.to_wkt(self, rounding_precision=-1)
  220. @property
  221. def wkb(self):
  222. """WKB representation of the geometry."""
  223. return shapely.to_wkb(self)
  224. @property
  225. def wkb_hex(self):
  226. """WKB hex representation of the geometry."""
  227. return shapely.to_wkb(self, hex=True)
  228. def svg(self, scale_factor=1.0, **kwargs):
  229. """Raise NotImplementedError."""
  230. raise NotImplementedError
  231. def _repr_svg_(self):
  232. """SVG representation for iPython notebook."""
  233. svg_top = (
  234. '<svg xmlns="http://www.w3.org/2000/svg" '
  235. 'xmlns:xlink="http://www.w3.org/1999/xlink" '
  236. )
  237. if self.is_empty:
  238. return svg_top + "/>"
  239. else:
  240. # Establish SVG canvas that will fit all the data + small space
  241. xmin, ymin, xmax, ymax = self.bounds
  242. if xmin == xmax and ymin == ymax:
  243. # This is a point; buffer using an arbitrary size
  244. xmin, ymin, xmax, ymax = self.buffer(1).bounds
  245. else:
  246. # Expand bounds by a fraction of the data ranges
  247. expand = 0.04 # or 4%, same as R plots
  248. widest_part = max([xmax - xmin, ymax - ymin])
  249. expand_amount = widest_part * expand
  250. xmin -= expand_amount
  251. ymin -= expand_amount
  252. xmax += expand_amount
  253. ymax += expand_amount
  254. dx = xmax - xmin
  255. dy = ymax - ymin
  256. width = min([max([100.0, dx]), 300])
  257. height = min([max([100.0, dy]), 300])
  258. try:
  259. scale_factor = max([dx, dy]) / max([width, height])
  260. except ZeroDivisionError:
  261. scale_factor = 1.0
  262. view_box = f"{xmin} {ymin} {dx} {dy}"
  263. transform = f"matrix(1,0,0,-1,0,{ymax + ymin})"
  264. return (
  265. f'{svg_top}width="{width}" height="{height}" viewBox="{view_box}" '
  266. 'preserveAspectRatio="xMinYMin meet">'
  267. f'<g transform="{transform}">{self.svg(scale_factor)}</g></svg>'
  268. )
  269. @property
  270. def geom_type(self):
  271. """Name of the geometry's type, such as 'Point'."""
  272. return GEOMETRY_TYPES[shapely.get_type_id(self)]
  273. # Real-valued properties and methods
  274. # ----------------------------------
  275. @property
  276. def area(self):
  277. """Unitless area of the geometry (float)."""
  278. return float(shapely.area(self))
  279. def distance(self, other):
  280. """Unitless distance to other geometry (float)."""
  281. return _maybe_unpack(shapely.distance(self, other))
  282. def hausdorff_distance(self, other):
  283. """Unitless hausdorff distance to other geometry (float)."""
  284. return _maybe_unpack(shapely.hausdorff_distance(self, other))
  285. @property
  286. def length(self):
  287. """Unitless length of the geometry (float)."""
  288. return float(shapely.length(self))
  289. @property
  290. def minimum_clearance(self):
  291. """Unitless distance a node can be moved to produce an invalid geometry (float).""" # noqa: E501
  292. return float(shapely.minimum_clearance(self))
  293. # Topological properties
  294. # ----------------------
  295. @property
  296. def boundary(self):
  297. """Return a lower dimension geometry that bounds the object.
  298. The boundary of a polygon is a line, the boundary of a line is a
  299. collection of points. The boundary of a point is an empty (null)
  300. collection.
  301. """
  302. return shapely.boundary(self)
  303. @property
  304. def bounds(self):
  305. """Return minimum bounding region (minx, miny, maxx, maxy)."""
  306. return tuple(shapely.bounds(self).tolist())
  307. @property
  308. def centroid(self):
  309. """Return the geometric center of the object."""
  310. return shapely.centroid(self)
  311. def point_on_surface(self):
  312. """Return a point guaranteed to be within the object, cheaply.
  313. Alias of `representative_point`.
  314. """
  315. return shapely.point_on_surface(self)
  316. def representative_point(self):
  317. """Return a point guaranteed to be within the object, cheaply.
  318. Alias of `point_on_surface`.
  319. """
  320. return shapely.point_on_surface(self)
  321. @property
  322. def convex_hull(self):
  323. """Return the convex hull of the geometry.
  324. Imagine an elastic band stretched around the geometry: that's a convex
  325. hull, more or less.
  326. The convex hull of a three member multipoint, for example, is a
  327. triangular polygon.
  328. """
  329. return shapely.convex_hull(self)
  330. @property
  331. def envelope(self):
  332. """A figure that envelopes the geometry."""
  333. return shapely.envelope(self)
  334. @property
  335. def oriented_envelope(self):
  336. """Return the oriented envelope (minimum rotated rectangle) of a geometry.
  337. The oriented envelope encloses an input geometry, such that the resulting
  338. rectangle has minimum area.
  339. Unlike envelope this rectangle is not constrained to be parallel to the
  340. coordinate axes. If the convex hull of the object is a degenerate (line
  341. or point) this degenerate is returned.
  342. The starting point of the rectangle is not fixed. You can use
  343. :func:`~shapely.normalize` to reorganize the rectangle to
  344. :ref:`strict canonical form <canonical-form>` so the starting point is
  345. always the lower left point.
  346. Alias of `minimum_rotated_rectangle`.
  347. """
  348. return shapely.oriented_envelope(self)
  349. @property
  350. def minimum_rotated_rectangle(self):
  351. """Return the oriented envelope (minimum rotated rectangle) of the geometry.
  352. The oriented envelope encloses an input geometry, such that the resulting
  353. rectangle has minimum area.
  354. Unlike `envelope` this rectangle is not constrained to be parallel to the
  355. coordinate axes. If the convex hull of the object is a degenerate (line
  356. or point) this degenerate is returned.
  357. The starting point of the rectangle is not fixed. You can use
  358. :func:`~shapely.normalize` to reorganize the rectangle to
  359. :ref:`strict canonical form <canonical-form>` so the starting point is
  360. always the lower left point.
  361. Alias of `oriented_envelope`.
  362. """
  363. return shapely.oriented_envelope(self)
  364. # Note: future plan is to change this signature over a few releases:
  365. # shapely 2.0:
  366. # buffer(self, geometry, distance, quad_segs=16, cap_style="round", ...)
  367. # shapely 2.1: shows deprecation warning about positional 'cap_style', etc.
  368. # same signature as 2.0
  369. # shapely 2.2(?): enforce keyword-only arguments after 'quad_segs'
  370. # buffer(self, geometry, distance, quad_segs=16, *, cap_style="round", ...)
  371. @deprecate_positional(
  372. ["cap_style", "join_style", "mitre_limit", "single_sided"],
  373. category=DeprecationWarning,
  374. )
  375. def buffer(
  376. self,
  377. distance,
  378. quad_segs=16,
  379. cap_style="round",
  380. join_style="round",
  381. mitre_limit=5.0,
  382. single_sided=False,
  383. **kwargs,
  384. ):
  385. """Get a geometry that represents all points within a distance of this geometry.
  386. A positive distance produces a dilation, a negative distance an
  387. erosion. A very small or zero distance may sometimes be used to
  388. "tidy" a polygon.
  389. Parameters
  390. ----------
  391. distance : float
  392. The distance to buffer around the object.
  393. quad_segs : int, optional
  394. Sets the number of line segments used to approximate an
  395. angle fillet.
  396. cap_style : shapely.BufferCapStyle or {'round', 'square', 'flat'}, default 'round'
  397. Specifies the shape of buffered line endings. BufferCapStyle.round
  398. ('round') results in circular line endings (see ``quad_segs``). Both
  399. BufferCapStyle.square ('square') and BufferCapStyle.flat ('flat')
  400. result in rectangular line endings, only BufferCapStyle.flat
  401. ('flat') will end at the original vertex, while
  402. BufferCapStyle.square ('square') involves adding the buffer width.
  403. join_style : shapely.BufferJoinStyle or {'round', 'mitre', 'bevel'}, default 'round'
  404. Specifies the shape of buffered line midpoints.
  405. BufferJoinStyle.ROUND ('round') results in rounded shapes.
  406. BufferJoinStyle.bevel ('bevel') results in a beveled edge that
  407. touches the original vertex. BufferJoinStyle.mitre ('mitre') results
  408. in a single vertex that is beveled depending on the ``mitre_limit``
  409. parameter.
  410. mitre_limit : float, optional
  411. The mitre limit ratio is used for very sharp corners. The
  412. mitre ratio is the ratio of the distance from the corner to
  413. the end of the mitred offset corner. When two line segments
  414. meet at a sharp angle, a miter join will extend the original
  415. geometry. To prevent unreasonable geometry, the mitre limit
  416. allows controlling the maximum length of the join corner.
  417. Corners with a ratio which exceed the limit will be beveled.
  418. single_sided : bool, optional
  419. The side used is determined by the sign of the buffer
  420. distance:
  421. a positive distance indicates the left-hand side
  422. a negative distance indicates the right-hand side
  423. The single-sided buffer of point geometries is the same as
  424. the regular buffer. The End Cap Style for single-sided
  425. buffers is always ignored, and forced to the equivalent of
  426. CAP_FLAT.
  427. quadsegs, resolution : int, optional
  428. Deprecated aliases for `quad_segs`.
  429. **kwargs : dict, optional
  430. For backwards compatibility of renamed parameters. If an unsupported
  431. kwarg is passed, a `ValueError` will be raised.
  432. Returns
  433. -------
  434. Geometry
  435. Notes
  436. -----
  437. The return value is a strictly two-dimensional geometry. All
  438. Z coordinates of the original geometry will be ignored.
  439. .. deprecated:: 2.1.0
  440. A deprecation warning is shown if ``quad_segs``, ``cap_style``,
  441. ``join_style``, ``mitre_limit`` or ``single_sided`` are
  442. specified as positional arguments. In a future release, these will
  443. need to be specified as keyword arguments.
  444. Examples
  445. --------
  446. >>> from shapely import BufferCapStyle
  447. >>> from shapely.wkt import loads
  448. >>> g = loads('POINT (0.0 0.0)')
  449. 16-gon approx of a unit radius circle:
  450. >>> g.buffer(1.0).area
  451. 3.1365484905459398
  452. 128-gon approximation:
  453. >>> g.buffer(1.0, 128).area
  454. 3.1415138011443013
  455. triangle approximation:
  456. >>> g.buffer(1.0, 3).area
  457. 3.0
  458. >>> list(g.buffer(1.0, cap_style=BufferCapStyle.square).exterior.coords)
  459. [(1.0, 1.0), (1.0, -1.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)]
  460. >>> g.buffer(1.0, cap_style=BufferCapStyle.square).area
  461. 4.0
  462. """ # noqa: E501
  463. quadsegs = kwargs.pop("quadsegs", None)
  464. if quadsegs is not None:
  465. warn(
  466. "The `quadsegs` argument is deprecated. Use `quad_segs` instead.",
  467. FutureWarning,
  468. stacklevel=2,
  469. )
  470. quad_segs = quadsegs
  471. resolution = kwargs.pop("resolution", None)
  472. if resolution is not None:
  473. warn(
  474. "The 'resolution' argument is deprecated. Use 'quad_segs' instead",
  475. DeprecationWarning,
  476. stacklevel=2,
  477. )
  478. quad_segs = resolution
  479. if kwargs:
  480. kwarg = list(kwargs.keys())[0] # noqa
  481. raise TypeError(f"buffer() got an unexpected keyword argument '{kwarg}'")
  482. if mitre_limit == 0.0:
  483. raise ValueError("Cannot compute offset from zero-length line segment")
  484. elif not np.isfinite(distance).all():
  485. raise ValueError("buffer distance must be finite")
  486. return shapely.buffer(
  487. self,
  488. distance,
  489. quad_segs=quad_segs,
  490. cap_style=cap_style,
  491. join_style=join_style,
  492. mitre_limit=mitre_limit,
  493. single_sided=single_sided,
  494. )
  495. # Note: future plan is to change this signature over a few releases:
  496. # shapely 2.0:
  497. # simplify(self, tolerance, preserve_topology=True)
  498. # shapely 2.1: shows deprecation warning about positional 'preserve_topology'
  499. # same signature as 2.0
  500. # shapely 2.2(?): enforce keyword-only arguments after 'tolerance'
  501. # simplify(self, tolerance, *, preserve_topology=True)
  502. @deprecate_positional(["preserve_topology"], category=DeprecationWarning)
  503. def simplify(self, tolerance, preserve_topology=True):
  504. """Return a simplified geometry produced by the Douglas-Peucker algorithm.
  505. Coordinates of the simplified geometry will be no more than the
  506. tolerance distance from the original. Unless the topology preserving
  507. option is used, the algorithm may produce self-intersecting or
  508. otherwise invalid geometries.
  509. """
  510. return shapely.simplify(self, tolerance, preserve_topology=preserve_topology)
  511. def normalize(self):
  512. """Convert geometry to normal form (or canonical form).
  513. This method orders the coordinates, rings of a polygon and parts of
  514. multi geometries consistently. Typically useful for testing purposes
  515. (for example in combination with `equals_exact`).
  516. Examples
  517. --------
  518. >>> from shapely import MultiLineString
  519. >>> line = MultiLineString([[(0, 0), (1, 1)], [(3, 3), (2, 2)]])
  520. >>> line.normalize()
  521. <MULTILINESTRING ((2 2, 3 3), (0 0, 1 1))>
  522. """
  523. return shapely.normalize(self)
  524. # Overlay operations
  525. # ---------------------------
  526. # Note: future plan is to change this signature over a few releases:
  527. # shapely 2.0:
  528. # difference(self, other, grid_size=None)
  529. # shapely 2.1: shows deprecation warning about positional 'grid_size' arg
  530. # same signature as 2.0
  531. # shapely 2.2(?): enforce keyword-only arguments after 'other'
  532. # difference(self, other, *, grid_size=None)
  533. @deprecate_positional(["grid_size"], category=DeprecationWarning)
  534. def difference(self, other, grid_size=None):
  535. """Return the difference of the geometries.
  536. Refer to `shapely.difference` for full documentation.
  537. """
  538. return shapely.difference(self, other, grid_size=grid_size)
  539. # Note: future plan is to change this signature over a few releases:
  540. # shapely 2.0:
  541. # intersection(self, other, grid_size=None)
  542. # shapely 2.1: shows deprecation warning about positional 'grid_size' arg
  543. # same signature as 2.0
  544. # shapely 2.2(?): enforce keyword-only arguments after 'other'
  545. # intersection(self, other, *, grid_size=None)
  546. @deprecate_positional(["grid_size"], category=DeprecationWarning)
  547. def intersection(self, other, grid_size=None):
  548. """Return the intersection of the geometries.
  549. Refer to `shapely.intersection` for full documentation.
  550. """
  551. return shapely.intersection(self, other, grid_size=grid_size)
  552. # Note: future plan is to change this signature over a few releases:
  553. # shapely 2.0:
  554. # symmetric_difference(self, other, grid_size=None)
  555. # shapely 2.1: shows deprecation warning about positional 'grid_size' arg
  556. # same signature as 2.0
  557. # shapely 2.2(?): enforce keyword-only arguments after 'other'
  558. # symmetric_difference(self, other, *, grid_size=None)
  559. @deprecate_positional(["grid_size"], category=DeprecationWarning)
  560. def symmetric_difference(self, other, grid_size=None):
  561. """Return the symmetric difference of the geometries.
  562. Refer to `shapely.symmetric_difference` for full documentation.
  563. """
  564. return shapely.symmetric_difference(self, other, grid_size=grid_size)
  565. # Note: future plan is to change this signature over a few releases:
  566. # shapely 2.0:
  567. # union(self, other, grid_size=None)
  568. # shapely 2.1: shows deprecation warning about positional 'grid_size' arg
  569. # same signature as 2.0
  570. # shapely 2.2(?): enforce keyword-only arguments after 'other'
  571. # union(self, other, *, grid_size=None)
  572. @deprecate_positional(["grid_size"], category=DeprecationWarning)
  573. def union(self, other, grid_size=None):
  574. """Return the union of the geometries.
  575. Refer to `shapely.union` for full documentation.
  576. """
  577. return shapely.union(self, other, grid_size=grid_size)
  578. # Unary predicates
  579. # ----------------
  580. @property
  581. def has_z(self):
  582. """True if the geometry's coordinate sequence(s) have z values."""
  583. return bool(shapely.has_z(self))
  584. @property
  585. def has_m(self):
  586. """True if the geometry's coordinate sequence(s) have m values."""
  587. return bool(shapely.has_m(self))
  588. @property
  589. def is_empty(self):
  590. """True if the set of points in this geometry is empty, else False."""
  591. return bool(shapely.is_empty(self))
  592. @property
  593. def is_ring(self):
  594. """True if the geometry is a closed ring, else False."""
  595. return bool(shapely.is_ring(self))
  596. @property
  597. def is_closed(self):
  598. """True if the geometry is closed, else False.
  599. Applicable only to linear geometries.
  600. """
  601. if self.geom_type == "LinearRing":
  602. return True
  603. return bool(shapely.is_closed(self))
  604. @property
  605. def is_simple(self):
  606. """True if the geometry is simple.
  607. Simple means that any self-intersections are only at boundary points.
  608. """
  609. return bool(shapely.is_simple(self))
  610. @property
  611. def is_valid(self):
  612. """True if the geometry is valid.
  613. The definition depends on sub-class.
  614. """
  615. return bool(shapely.is_valid(self))
  616. # Binary predicates
  617. # -----------------
  618. def relate(self, other):
  619. """Return the DE-9IM intersection matrix for the two geometries (string)."""
  620. return shapely.relate(self, other)
  621. def covers(self, other):
  622. """Return True if the geometry covers the other, else False."""
  623. return _maybe_unpack(shapely.covers(self, other))
  624. def covered_by(self, other):
  625. """Return True if the geometry is covered by the other, else False."""
  626. return _maybe_unpack(shapely.covered_by(self, other))
  627. def contains(self, other):
  628. """Return True if the geometry contains the other, else False."""
  629. return _maybe_unpack(shapely.contains(self, other))
  630. def contains_properly(self, other):
  631. """Return True if the geometry completely contains the other.
  632. There should be no common boundary points.
  633. Refer to `shapely.contains_properly` for full documentation.
  634. """
  635. return _maybe_unpack(shapely.contains_properly(self, other))
  636. def crosses(self, other):
  637. """Return True if the geometries cross, else False."""
  638. return _maybe_unpack(shapely.crosses(self, other))
  639. def disjoint(self, other):
  640. """Return True if geometries are disjoint, else False."""
  641. return _maybe_unpack(shapely.disjoint(self, other))
  642. def equals(self, other):
  643. """Return True if geometries are equal, else False.
  644. This method considers point-set equality (or topological
  645. equality), and is equivalent to (self.within(other) &
  646. self.contains(other)).
  647. Examples
  648. --------
  649. >>> from shapely import LineString
  650. >>> LineString(
  651. ... [(0, 0), (2, 2)]
  652. ... ).equals(
  653. ... LineString([(0, 0), (1, 1), (2, 2)])
  654. ... )
  655. True
  656. Returns
  657. -------
  658. bool
  659. """
  660. return _maybe_unpack(shapely.equals(self, other))
  661. def intersects(self, other):
  662. """Return True if geometries intersect, else False."""
  663. return _maybe_unpack(shapely.intersects(self, other))
  664. def overlaps(self, other):
  665. """Return True if geometries overlap, else False."""
  666. return _maybe_unpack(shapely.overlaps(self, other))
  667. def touches(self, other):
  668. """Return True if geometries touch, else False."""
  669. return _maybe_unpack(shapely.touches(self, other))
  670. def within(self, other):
  671. """Return True if geometry is within the other, else False."""
  672. return _maybe_unpack(shapely.within(self, other))
  673. def dwithin(self, other, distance):
  674. """Return True if geometry is within a given distance from the other.
  675. Refer to `shapely.dwithin` for full documentation.
  676. """
  677. return _maybe_unpack(shapely.dwithin(self, other, distance))
  678. def equals_exact(self, other, tolerance=0.0, *, normalize=False):
  679. """Return True if the geometries are equivalent within the tolerance.
  680. Refer to :func:`~shapely.equals_exact` for full documentation.
  681. Parameters
  682. ----------
  683. other : BaseGeometry
  684. The other geometry object in this comparison.
  685. tolerance : float, optional (default: 0.)
  686. Absolute tolerance in the same units as coordinates.
  687. normalize : bool, optional (default: False)
  688. If True, normalize the two geometries so that the coordinates are
  689. in the same order.
  690. .. versionadded:: 2.1.0
  691. Examples
  692. --------
  693. >>> from shapely import LineString
  694. >>> LineString(
  695. ... [(0, 0), (2, 2)]
  696. ... ).equals_exact(
  697. ... LineString([(0, 0), (1, 1), (2, 2)]),
  698. ... 1e-6
  699. ... )
  700. False
  701. Returns
  702. -------
  703. bool
  704. """
  705. return _maybe_unpack(
  706. shapely.equals_exact(self, other, tolerance, normalize=normalize)
  707. )
  708. def relate_pattern(self, other, pattern):
  709. """Return True if the DE-9IM relationship code satisfies the pattern."""
  710. return _maybe_unpack(shapely.relate_pattern(self, other, pattern))
  711. # Linear referencing
  712. # ------------------
  713. # Note: future plan is to change this signature over a few releases:
  714. # shapely 2.0:
  715. # line_locate_point(self, other, normalized=False)
  716. # shapely 2.1: shows deprecation warning about positional 'normalized'
  717. # same signature as 2.0
  718. # shapely 2.2(?): enforce keyword-only arguments after 'other'
  719. # line_locate_point(self, other, *, normalized=False)
  720. @deprecate_positional(["normalized"], category=DeprecationWarning)
  721. def line_locate_point(self, other, normalized=False):
  722. """Return the distance of this geometry to a point nearest the specified point.
  723. If the normalized arg is True, return the distance normalized to the
  724. length of the linear geometry.
  725. Alias of `project`.
  726. """
  727. return _maybe_unpack(
  728. shapely.line_locate_point(self, other, normalized=normalized)
  729. )
  730. # Note: future plan is to change this signature over a few releases:
  731. # shapely 2.0:
  732. # project(self, other, normalized=False)
  733. # shapely 2.1: shows deprecation warning about positional 'normalized'
  734. # same signature as 2.0
  735. # shapely 2.2(?): enforce keyword-only arguments after 'other'
  736. # project(self, other, *, normalized=False)
  737. @deprecate_positional(["normalized"], category=DeprecationWarning)
  738. def project(self, other, normalized=False):
  739. """Return the distance of geometry to a point nearest the specified point.
  740. If the normalized arg is True, return the distance normalized to the
  741. length of the linear geometry.
  742. Alias of `line_locate_point`.
  743. """
  744. return _maybe_unpack(
  745. shapely.line_locate_point(self, other, normalized=normalized)
  746. )
  747. # Note: future plan is to change this signature over a few releases:
  748. # shapely 2.0:
  749. # line_interpolate_point(self, distance, normalized=False)
  750. # shapely 2.1: shows deprecation warning about positional 'normalized'
  751. # same signature as 2.0
  752. # shapely 2.2(?): enforce keyword-only arguments after 'distance'
  753. # line_interpolate_point(self, distance, *, normalized=False)
  754. @deprecate_positional(["normalized"], category=DeprecationWarning)
  755. def line_interpolate_point(self, distance, normalized=False):
  756. """Return a point at the specified distance along a linear geometry.
  757. Negative length values are taken as measured in the reverse
  758. direction from the end of the geometry. Out-of-range index
  759. values are handled by clamping them to the valid range of values.
  760. If the normalized arg is True, the distance will be interpreted as a
  761. fraction of the geometry's length.
  762. Alias of `interpolate`.
  763. """
  764. return shapely.line_interpolate_point(self, distance, normalized=normalized)
  765. # Note: future plan is to change this signature over a few releases:
  766. # shapely 2.0:
  767. # interpolate(self, distance, normalized=False)
  768. # shapely 2.1: shows deprecation warning about positional 'normalized'
  769. # same signature as 2.0
  770. # shapely 2.2(?): enforce keyword-only arguments after 'distance'
  771. # interpolate(self, distance, *, normalized=False)
  772. @deprecate_positional(["normalized"], category=DeprecationWarning)
  773. def interpolate(self, distance, normalized=False):
  774. """Return a point at the specified distance along a linear geometry.
  775. Negative length values are taken as measured in the reverse
  776. direction from the end of the geometry. Out-of-range index
  777. values are handled by clamping them to the valid range of values.
  778. If the normalized arg is True, the distance will be interpreted as a
  779. fraction of the geometry's length.
  780. Alias of `line_interpolate_point`.
  781. """
  782. return shapely.line_interpolate_point(self, distance, normalized=normalized)
  783. def segmentize(self, max_segment_length):
  784. """Add vertices to line segments based on maximum segment length.
  785. Additional vertices will be added to every line segment in an input geometry
  786. so that segments are no longer than the provided maximum segment length. New
  787. vertices will evenly subdivide each segment.
  788. Only linear components of input geometries are densified; other geometries
  789. are returned unmodified.
  790. Parameters
  791. ----------
  792. max_segment_length : float or array_like
  793. Additional vertices will be added so that all line segments are no
  794. longer this value. Must be greater than 0.
  795. Examples
  796. --------
  797. >>> from shapely import LineString, Polygon
  798. >>> LineString([(0, 0), (0, 10)]).segmentize(max_segment_length=5)
  799. <LINESTRING (0 0, 0 5, 0 10)>
  800. >>> Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]).segmentize(max_segment_length=5)
  801. <POLYGON ((0 0, 5 0, 10 0, 10 5, 10 10, 5 10, 0 10, 0 5, 0 0))>
  802. """ # noqa: E501
  803. return shapely.segmentize(self, max_segment_length)
  804. def reverse(self):
  805. """Return a copy of this geometry with the order of coordinates reversed.
  806. If the geometry is a polygon with interior rings, the interior rings are also
  807. reversed.
  808. Points are unchanged.
  809. See Also
  810. --------
  811. is_ccw : Checks if a geometry is clockwise.
  812. Examples
  813. --------
  814. >>> from shapely import LineString, Polygon
  815. >>> LineString([(0, 0), (1, 2)]).reverse()
  816. <LINESTRING (1 2, 0 0)>
  817. >>> Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]).reverse()
  818. <POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))>
  819. """
  820. return shapely.reverse(self)
  821. class BaseMultipartGeometry(BaseGeometry):
  822. """Base class for collections of multiple geometries."""
  823. __slots__ = []
  824. @property
  825. def coords(self):
  826. """Not implemented.
  827. Sub-geometries may have coordinate sequences, but multi-part geometries
  828. do not.
  829. """
  830. raise NotImplementedError(
  831. "Sub-geometries may have coordinate sequences, "
  832. "but multi-part geometries do not"
  833. )
  834. @property
  835. def geoms(self):
  836. """Access to the contained geometries."""
  837. return GeometrySequence(self)
  838. def __bool__(self):
  839. """Return True if the geometry is not empty, else False."""
  840. return self.is_empty is False
  841. def __eq__(self, other):
  842. """Return True if geometries are equal, else False."""
  843. if not isinstance(other, BaseGeometry):
  844. return NotImplemented
  845. return (
  846. type(other) is type(self)
  847. and len(self.geoms) == len(other.geoms)
  848. and all(a == b for a, b in zip(self.geoms, other.geoms))
  849. )
  850. def __hash__(self):
  851. """Return the hash value of the geometry."""
  852. return super().__hash__()
  853. def svg(self, scale_factor=1.0, color=None):
  854. """Return a group of SVG elements for the multipart geometry.
  855. Parameters
  856. ----------
  857. scale_factor : float
  858. Multiplication factor for the SVG stroke-width. Default is 1.
  859. color : str, optional
  860. Hex string for stroke or fill color. Default is to use "#66cc99"
  861. if geometry is valid, and "#ff3333" if invalid.
  862. """
  863. if self.is_empty:
  864. return "<g />"
  865. if color is None:
  866. color = "#66cc99" if self.is_valid else "#ff3333"
  867. return "<g>" + "".join(p.svg(scale_factor, color) for p in self.geoms) + "</g>"
  868. class GeometrySequence:
  869. """Iterative access to members of a homogeneous multipart geometry."""
  870. # Attributes
  871. # ----------
  872. # _parent : object
  873. # Parent (Shapely) geometry
  874. _parent = None
  875. def __init__(self, parent):
  876. """Initialize the sequence with a parent geometry."""
  877. self._parent = parent
  878. def _get_geom_item(self, i):
  879. return shapely.get_geometry(self._parent, i)
  880. def __iter__(self):
  881. """Iterate over the geometries in the sequence."""
  882. for i in range(self.__len__()):
  883. yield self._get_geom_item(i)
  884. def __len__(self):
  885. """Return the number of geometries in the sequence."""
  886. return shapely.get_num_geometries(self._parent)
  887. def __getitem__(self, key):
  888. """Access a geometry in the sequence by index or slice."""
  889. m = self.__len__()
  890. if isinstance(key, (int, np.integer)):
  891. if key + m < 0 or key >= m:
  892. raise IndexError("index out of range")
  893. if key < 0:
  894. i = m + key
  895. else:
  896. i = key
  897. return self._get_geom_item(i)
  898. elif isinstance(key, slice):
  899. res = []
  900. start, stop, stride = key.indices(m)
  901. for i in range(start, stop, stride):
  902. res.append(self._get_geom_item(i))
  903. return type(self._parent)(res or None)
  904. else:
  905. raise TypeError("key must be an index or slice")
  906. class EmptyGeometry(BaseGeometry):
  907. """An empty geometry."""
  908. def __new__(self):
  909. """Create an empty geometry."""
  910. warn(
  911. "The 'EmptyGeometry()' constructor to create an empty geometry is "
  912. "deprecated, and will raise an error in the future. Use one of the "
  913. "geometry subclasses instead, for example 'GeometryCollection()'.",
  914. ShapelyDeprecationWarning,
  915. stacklevel=2,
  916. )
  917. return shapely.from_wkt("GEOMETRYCOLLECTION EMPTY")