You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

geometry.py 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. """
  2. This module contains the 'base' GEOSGeometry object -- all GEOS Geometries
  3. inherit from this object.
  4. """
  5. import re
  6. from ctypes import addressof, byref, c_double
  7. from django.contrib.gis import gdal
  8. from django.contrib.gis.geometry import hex_regex, json_regex, wkt_regex
  9. from django.contrib.gis.geos import prototypes as capi
  10. from django.contrib.gis.geos.base import GEOSBase
  11. from django.contrib.gis.geos.coordseq import GEOSCoordSeq
  12. from django.contrib.gis.geos.error import GEOSException
  13. from django.contrib.gis.geos.libgeos import GEOM_PTR
  14. from django.contrib.gis.geos.mutable_list import ListMixin
  15. from django.contrib.gis.geos.prepared import PreparedGeometry
  16. from django.contrib.gis.geos.prototypes.io import (
  17. ewkb_w, wkb_r, wkb_w, wkt_r, wkt_w,
  18. )
  19. from django.utils.deconstruct import deconstructible
  20. from django.utils.encoding import force_bytes, force_text
  21. class GEOSGeometryBase(GEOSBase):
  22. _GEOS_CLASSES = None
  23. ptr_type = GEOM_PTR
  24. destructor = capi.destroy_geom
  25. has_cs = False # Only Point, LineString, LinearRing have coordinate sequences
  26. def __init__(self, ptr, cls):
  27. self._ptr = ptr
  28. # Setting the class type (e.g., Point, Polygon, etc.)
  29. if type(self) in (GEOSGeometryBase, GEOSGeometry):
  30. if cls is None:
  31. if GEOSGeometryBase._GEOS_CLASSES is None:
  32. # Inner imports avoid import conflicts with GEOSGeometry.
  33. from .linestring import LineString, LinearRing
  34. from .point import Point
  35. from .polygon import Polygon
  36. from .collections import (
  37. GeometryCollection, MultiPoint, MultiLineString, MultiPolygon,
  38. )
  39. GEOSGeometryBase._GEOS_CLASSES = {
  40. 0: Point,
  41. 1: LineString,
  42. 2: LinearRing,
  43. 3: Polygon,
  44. 4: MultiPoint,
  45. 5: MultiLineString,
  46. 6: MultiPolygon,
  47. 7: GeometryCollection,
  48. }
  49. cls = GEOSGeometryBase._GEOS_CLASSES[self.geom_typeid]
  50. self.__class__ = cls
  51. self._post_init()
  52. def _post_init(self):
  53. "Perform post-initialization setup."
  54. # Setting the coordinate sequence for the geometry (will be None on
  55. # geometries that do not have coordinate sequences)
  56. self._cs = GEOSCoordSeq(capi.get_cs(self.ptr), self.hasz) if self.has_cs else None
  57. def __copy__(self):
  58. """
  59. Return a clone because the copy of a GEOSGeometry may contain an
  60. invalid pointer location if the original is garbage collected.
  61. """
  62. return self.clone()
  63. def __deepcopy__(self, memodict):
  64. """
  65. The `deepcopy` routine is used by the `Node` class of django.utils.tree;
  66. thus, the protocol routine needs to be implemented to return correct
  67. copies (clones) of these GEOS objects, which use C pointers.
  68. """
  69. return self.clone()
  70. def __str__(self):
  71. "EWKT is used for the string representation."
  72. return self.ewkt
  73. def __repr__(self):
  74. "Short-hand representation because WKT may be very large."
  75. return '<%s object at %s>' % (self.geom_type, hex(addressof(self.ptr)))
  76. # Pickling support
  77. def _to_pickle_wkb(self):
  78. return bytes(self.wkb)
  79. def _from_pickle_wkb(self, wkb):
  80. return wkb_r().read(memoryview(wkb))
  81. def __getstate__(self):
  82. # The pickled state is simply a tuple of the WKB (in string form)
  83. # and the SRID.
  84. return self._to_pickle_wkb(), self.srid
  85. def __setstate__(self, state):
  86. # Instantiating from the tuple state that was pickled.
  87. wkb, srid = state
  88. ptr = self._from_pickle_wkb(wkb)
  89. if not ptr:
  90. raise GEOSException('Invalid Geometry loaded from pickled state.')
  91. self.ptr = ptr
  92. self._post_init()
  93. self.srid = srid
  94. @classmethod
  95. def _from_wkb(cls, wkb):
  96. return wkb_r().read(wkb)
  97. @staticmethod
  98. def from_ewkt(ewkt):
  99. ewkt = force_bytes(ewkt)
  100. srid = None
  101. parts = ewkt.split(b';', 1)
  102. if len(parts) == 2:
  103. srid_part, wkt = parts
  104. match = re.match(br'SRID=(?P<srid>\-?\d+)', srid_part)
  105. if not match:
  106. raise ValueError('EWKT has invalid SRID part.')
  107. srid = int(match.group('srid'))
  108. else:
  109. wkt = ewkt
  110. if not wkt:
  111. raise ValueError('Expected WKT but got an empty string.')
  112. return GEOSGeometry(GEOSGeometry._from_wkt(wkt), srid=srid)
  113. @staticmethod
  114. def _from_wkt(wkt):
  115. return wkt_r().read(wkt)
  116. @classmethod
  117. def from_gml(cls, gml_string):
  118. return gdal.OGRGeometry.from_gml(gml_string).geos
  119. # Comparison operators
  120. def __eq__(self, other):
  121. """
  122. Equivalence testing, a Geometry may be compared with another Geometry
  123. or an EWKT representation.
  124. """
  125. if isinstance(other, str):
  126. try:
  127. other = GEOSGeometry.from_ewkt(other)
  128. except (ValueError, GEOSException):
  129. return False
  130. return isinstance(other, GEOSGeometry) and self.srid == other.srid and self.equals_exact(other)
  131. def __hash__(self):
  132. return hash((self.srid, self.wkt))
  133. # ### Geometry set-like operations ###
  134. # Thanks to Sean Gillies for inspiration:
  135. # http://lists.gispython.org/pipermail/community/2007-July/001034.html
  136. # g = g1 | g2
  137. def __or__(self, other):
  138. "Return the union of this Geometry and the other."
  139. return self.union(other)
  140. # g = g1 & g2
  141. def __and__(self, other):
  142. "Return the intersection of this Geometry and the other."
  143. return self.intersection(other)
  144. # g = g1 - g2
  145. def __sub__(self, other):
  146. "Return the difference this Geometry and the other."
  147. return self.difference(other)
  148. # g = g1 ^ g2
  149. def __xor__(self, other):
  150. "Return the symmetric difference of this Geometry and the other."
  151. return self.sym_difference(other)
  152. # #### Coordinate Sequence Routines ####
  153. @property
  154. def coord_seq(self):
  155. "Return a clone of the coordinate sequence for this Geometry."
  156. if self.has_cs:
  157. return self._cs.clone()
  158. # #### Geometry Info ####
  159. @property
  160. def geom_type(self):
  161. "Return a string representing the Geometry type, e.g. 'Polygon'"
  162. return capi.geos_type(self.ptr).decode()
  163. @property
  164. def geom_typeid(self):
  165. "Return an integer representing the Geometry type."
  166. return capi.geos_typeid(self.ptr)
  167. @property
  168. def num_geom(self):
  169. "Return the number of geometries in the Geometry."
  170. return capi.get_num_geoms(self.ptr)
  171. @property
  172. def num_coords(self):
  173. "Return the number of coordinates in the Geometry."
  174. return capi.get_num_coords(self.ptr)
  175. @property
  176. def num_points(self):
  177. "Return the number points, or coordinates, in the Geometry."
  178. return self.num_coords
  179. @property
  180. def dims(self):
  181. "Return the dimension of this Geometry (0=point, 1=line, 2=surface)."
  182. return capi.get_dims(self.ptr)
  183. def normalize(self):
  184. "Convert this Geometry to normal form (or canonical form)."
  185. capi.geos_normalize(self.ptr)
  186. # #### Unary predicates ####
  187. @property
  188. def empty(self):
  189. """
  190. Return a boolean indicating whether the set of points in this Geometry
  191. are empty.
  192. """
  193. return capi.geos_isempty(self.ptr)
  194. @property
  195. def hasz(self):
  196. "Return whether the geometry has a 3D dimension."
  197. return capi.geos_hasz(self.ptr)
  198. @property
  199. def ring(self):
  200. "Return whether or not the geometry is a ring."
  201. return capi.geos_isring(self.ptr)
  202. @property
  203. def simple(self):
  204. "Return false if the Geometry isn't simple."
  205. return capi.geos_issimple(self.ptr)
  206. @property
  207. def valid(self):
  208. "Test the validity of this Geometry."
  209. return capi.geos_isvalid(self.ptr)
  210. @property
  211. def valid_reason(self):
  212. """
  213. Return a string containing the reason for any invalidity.
  214. """
  215. return capi.geos_isvalidreason(self.ptr).decode()
  216. # #### Binary predicates. ####
  217. def contains(self, other):
  218. "Return true if other.within(this) returns true."
  219. return capi.geos_contains(self.ptr, other.ptr)
  220. def covers(self, other):
  221. """
  222. Return True if the DE-9IM Intersection Matrix for the two geometries is
  223. T*****FF*, *T****FF*, ***T**FF*, or ****T*FF*. If either geometry is
  224. empty, return False.
  225. """
  226. return capi.geos_covers(self.ptr, other.ptr)
  227. def crosses(self, other):
  228. """
  229. Return true if the DE-9IM intersection matrix for the two Geometries
  230. is T*T****** (for a point and a curve,a point and an area or a line and
  231. an area) 0******** (for two curves).
  232. """
  233. return capi.geos_crosses(self.ptr, other.ptr)
  234. def disjoint(self, other):
  235. """
  236. Return true if the DE-9IM intersection matrix for the two Geometries
  237. is FF*FF****.
  238. """
  239. return capi.geos_disjoint(self.ptr, other.ptr)
  240. def equals(self, other):
  241. """
  242. Return true if the DE-9IM intersection matrix for the two Geometries
  243. is T*F**FFF*.
  244. """
  245. return capi.geos_equals(self.ptr, other.ptr)
  246. def equals_exact(self, other, tolerance=0):
  247. """
  248. Return true if the two Geometries are exactly equal, up to a
  249. specified tolerance.
  250. """
  251. return capi.geos_equalsexact(self.ptr, other.ptr, float(tolerance))
  252. def intersects(self, other):
  253. "Return true if disjoint return false."
  254. return capi.geos_intersects(self.ptr, other.ptr)
  255. def overlaps(self, other):
  256. """
  257. Return true if the DE-9IM intersection matrix for the two Geometries
  258. is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves).
  259. """
  260. return capi.geos_overlaps(self.ptr, other.ptr)
  261. def relate_pattern(self, other, pattern):
  262. """
  263. Return true if the elements in the DE-9IM intersection matrix for the
  264. two Geometries match the elements in pattern.
  265. """
  266. if not isinstance(pattern, str) or len(pattern) > 9:
  267. raise GEOSException('invalid intersection matrix pattern')
  268. return capi.geos_relatepattern(self.ptr, other.ptr, force_bytes(pattern))
  269. def touches(self, other):
  270. """
  271. Return true if the DE-9IM intersection matrix for the two Geometries
  272. is FT*******, F**T***** or F***T****.
  273. """
  274. return capi.geos_touches(self.ptr, other.ptr)
  275. def within(self, other):
  276. """
  277. Return true if the DE-9IM intersection matrix for the two Geometries
  278. is T*F**F***.
  279. """
  280. return capi.geos_within(self.ptr, other.ptr)
  281. # #### SRID Routines ####
  282. @property
  283. def srid(self):
  284. "Get the SRID for the geometry. Return None if no SRID is set."
  285. s = capi.geos_get_srid(self.ptr)
  286. if s == 0:
  287. return None
  288. else:
  289. return s
  290. @srid.setter
  291. def srid(self, srid):
  292. "Set the SRID for the geometry."
  293. capi.geos_set_srid(self.ptr, 0 if srid is None else srid)
  294. # #### Output Routines ####
  295. @property
  296. def ewkt(self):
  297. """
  298. Return the EWKT (SRID + WKT) of the Geometry.
  299. """
  300. srid = self.srid
  301. return 'SRID=%s;%s' % (srid, self.wkt) if srid else self.wkt
  302. @property
  303. def wkt(self):
  304. "Return the WKT (Well-Known Text) representation of this Geometry."
  305. return wkt_w(dim=3 if self.hasz else 2, trim=True).write(self).decode()
  306. @property
  307. def hex(self):
  308. """
  309. Return the WKB of this Geometry in hexadecimal form. Please note
  310. that the SRID is not included in this representation because it is not
  311. a part of the OGC specification (use the `hexewkb` property instead).
  312. """
  313. # A possible faster, all-python, implementation:
  314. # str(self.wkb).encode('hex')
  315. return wkb_w(dim=3 if self.hasz else 2).write_hex(self)
  316. @property
  317. def hexewkb(self):
  318. """
  319. Return the EWKB of this Geometry in hexadecimal form. This is an
  320. extension of the WKB specification that includes SRID value that are
  321. a part of this geometry.
  322. """
  323. return ewkb_w(dim=3 if self.hasz else 2).write_hex(self)
  324. @property
  325. def json(self):
  326. """
  327. Return GeoJSON representation of this Geometry.
  328. """
  329. return self.ogr.json
  330. geojson = json
  331. @property
  332. def wkb(self):
  333. """
  334. Return the WKB (Well-Known Binary) representation of this Geometry
  335. as a Python buffer. SRID and Z values are not included, use the
  336. `ewkb` property instead.
  337. """
  338. return wkb_w(3 if self.hasz else 2).write(self)
  339. @property
  340. def ewkb(self):
  341. """
  342. Return the EWKB representation of this Geometry as a Python buffer.
  343. This is an extension of the WKB specification that includes any SRID
  344. value that are a part of this geometry.
  345. """
  346. return ewkb_w(3 if self.hasz else 2).write(self)
  347. @property
  348. def kml(self):
  349. "Return the KML representation of this Geometry."
  350. gtype = self.geom_type
  351. return '<%s>%s</%s>' % (gtype, self.coord_seq.kml, gtype)
  352. @property
  353. def prepared(self):
  354. """
  355. Return a PreparedGeometry corresponding to this geometry -- it is
  356. optimized for the contains, intersects, and covers operations.
  357. """
  358. return PreparedGeometry(self)
  359. # #### GDAL-specific output routines ####
  360. def _ogr_ptr(self):
  361. return gdal.OGRGeometry._from_wkb(self.wkb)
  362. @property
  363. def ogr(self):
  364. "Return the OGR Geometry for this Geometry."
  365. return gdal.OGRGeometry(self._ogr_ptr(), self.srs)
  366. @property
  367. def srs(self):
  368. "Return the OSR SpatialReference for SRID of this Geometry."
  369. if self.srid:
  370. try:
  371. return gdal.SpatialReference(self.srid)
  372. except gdal.SRSException:
  373. pass
  374. return None
  375. @property
  376. def crs(self):
  377. "Alias for `srs` property."
  378. return self.srs
  379. def transform(self, ct, clone=False):
  380. """
  381. Requires GDAL. Transform the geometry according to the given
  382. transformation object, which may be an integer SRID, and WKT or
  383. PROJ.4 string. By default, transform the geometry in-place and return
  384. nothing. However if the `clone` keyword is set, don't modify the
  385. geometry and return a transformed clone instead.
  386. """
  387. srid = self.srid
  388. if ct == srid:
  389. # short-circuit where source & dest SRIDs match
  390. if clone:
  391. return self.clone()
  392. else:
  393. return
  394. if isinstance(ct, gdal.CoordTransform):
  395. # We don't care about SRID because CoordTransform presupposes
  396. # source SRS.
  397. srid = None
  398. elif srid is None or srid < 0:
  399. raise GEOSException("Calling transform() with no SRID set is not supported")
  400. # Creating an OGR Geometry, which is then transformed.
  401. g = gdal.OGRGeometry(self._ogr_ptr(), srid)
  402. g.transform(ct)
  403. # Getting a new GEOS pointer
  404. ptr = g._geos_ptr()
  405. if clone:
  406. # User wants a cloned transformed geometry returned.
  407. return GEOSGeometry(ptr, srid=g.srid)
  408. if ptr:
  409. # Reassigning pointer, and performing post-initialization setup
  410. # again due to the reassignment.
  411. capi.destroy_geom(self.ptr)
  412. self.ptr = ptr
  413. self._post_init()
  414. self.srid = g.srid
  415. else:
  416. raise GEOSException('Transformed WKB was invalid.')
  417. # #### Topology Routines ####
  418. def _topology(self, gptr):
  419. "Return Geometry from the given pointer."
  420. return GEOSGeometry(gptr, srid=self.srid)
  421. @property
  422. def boundary(self):
  423. "Return the boundary as a newly allocated Geometry object."
  424. return self._topology(capi.geos_boundary(self.ptr))
  425. def buffer(self, width, quadsegs=8):
  426. """
  427. Return a geometry that represents all points whose distance from this
  428. Geometry is less than or equal to distance. Calculations are in the
  429. Spatial Reference System of this Geometry. The optional third parameter sets
  430. the number of segment used to approximate a quarter circle (defaults to 8).
  431. (Text from PostGIS documentation at ch. 6.1.3)
  432. """
  433. return self._topology(capi.geos_buffer(self.ptr, width, quadsegs))
  434. def buffer_with_style(self, width, quadsegs=8, end_cap_style=1, join_style=1, mitre_limit=5.0):
  435. """
  436. Same as buffer() but allows customizing the style of the buffer.
  437. End cap style can be round (1), flat (2), or square (3).
  438. Join style can be round (1), mitre (2), or bevel (3).
  439. Mitre ratio limit only affects mitered join style.
  440. """
  441. return self._topology(
  442. capi.geos_bufferwithstyle(self.ptr, width, quadsegs, end_cap_style, join_style, mitre_limit),
  443. )
  444. @property
  445. def centroid(self):
  446. """
  447. The centroid is equal to the centroid of the set of component Geometries
  448. of highest dimension (since the lower-dimension geometries contribute zero
  449. "weight" to the centroid).
  450. """
  451. return self._topology(capi.geos_centroid(self.ptr))
  452. @property
  453. def convex_hull(self):
  454. """
  455. Return the smallest convex Polygon that contains all the points
  456. in the Geometry.
  457. """
  458. return self._topology(capi.geos_convexhull(self.ptr))
  459. def difference(self, other):
  460. """
  461. Return a Geometry representing the points making up this Geometry
  462. that do not make up other.
  463. """
  464. return self._topology(capi.geos_difference(self.ptr, other.ptr))
  465. @property
  466. def envelope(self):
  467. "Return the envelope for this geometry (a polygon)."
  468. return self._topology(capi.geos_envelope(self.ptr))
  469. def intersection(self, other):
  470. "Return a Geometry representing the points shared by this Geometry and other."
  471. return self._topology(capi.geos_intersection(self.ptr, other.ptr))
  472. @property
  473. def point_on_surface(self):
  474. "Compute an interior point of this Geometry."
  475. return self._topology(capi.geos_pointonsurface(self.ptr))
  476. def relate(self, other):
  477. "Return the DE-9IM intersection matrix for this Geometry and the other."
  478. return capi.geos_relate(self.ptr, other.ptr).decode()
  479. def simplify(self, tolerance=0.0, preserve_topology=False):
  480. """
  481. Return the Geometry, simplified using the Douglas-Peucker algorithm
  482. to the specified tolerance (higher tolerance => less points). If no
  483. tolerance provided, defaults to 0.
  484. By default, don't preserve topology - e.g. polygons can be split,
  485. collapse to lines or disappear holes can be created or disappear, and
  486. lines can cross. By specifying preserve_topology=True, the result will
  487. have the same dimension and number of components as the input. This is
  488. significantly slower.
  489. """
  490. if preserve_topology:
  491. return self._topology(capi.geos_preservesimplify(self.ptr, tolerance))
  492. else:
  493. return self._topology(capi.geos_simplify(self.ptr, tolerance))
  494. def sym_difference(self, other):
  495. """
  496. Return a set combining the points in this Geometry not in other,
  497. and the points in other not in this Geometry.
  498. """
  499. return self._topology(capi.geos_symdifference(self.ptr, other.ptr))
  500. @property
  501. def unary_union(self):
  502. "Return the union of all the elements of this geometry."
  503. return self._topology(capi.geos_unary_union(self.ptr))
  504. def union(self, other):
  505. "Return a Geometry representing all the points in this Geometry and other."
  506. return self._topology(capi.geos_union(self.ptr, other.ptr))
  507. # #### Other Routines ####
  508. @property
  509. def area(self):
  510. "Return the area of the Geometry."
  511. return capi.geos_area(self.ptr, byref(c_double()))
  512. def distance(self, other):
  513. """
  514. Return the distance between the closest points on this Geometry
  515. and the other. Units will be in those of the coordinate system of
  516. the Geometry.
  517. """
  518. if not isinstance(other, GEOSGeometry):
  519. raise TypeError('distance() works only on other GEOS Geometries.')
  520. return capi.geos_distance(self.ptr, other.ptr, byref(c_double()))
  521. @property
  522. def extent(self):
  523. """
  524. Return the extent of this geometry as a 4-tuple, consisting of
  525. (xmin, ymin, xmax, ymax).
  526. """
  527. from .point import Point
  528. env = self.envelope
  529. if isinstance(env, Point):
  530. xmin, ymin = env.tuple
  531. xmax, ymax = xmin, ymin
  532. else:
  533. xmin, ymin = env[0][0]
  534. xmax, ymax = env[0][2]
  535. return (xmin, ymin, xmax, ymax)
  536. @property
  537. def length(self):
  538. """
  539. Return the length of this Geometry (e.g., 0 for point, or the
  540. circumference of a Polygon).
  541. """
  542. return capi.geos_length(self.ptr, byref(c_double()))
  543. def clone(self):
  544. "Clone this Geometry."
  545. return GEOSGeometry(capi.geom_clone(self.ptr))
  546. class LinearGeometryMixin:
  547. """
  548. Used for LineString and MultiLineString.
  549. """
  550. def interpolate(self, distance):
  551. return self._topology(capi.geos_interpolate(self.ptr, distance))
  552. def interpolate_normalized(self, distance):
  553. return self._topology(capi.geos_interpolate_normalized(self.ptr, distance))
  554. def project(self, point):
  555. from .point import Point
  556. if not isinstance(point, Point):
  557. raise TypeError('locate_point argument must be a Point')
  558. return capi.geos_project(self.ptr, point.ptr)
  559. def project_normalized(self, point):
  560. from .point import Point
  561. if not isinstance(point, Point):
  562. raise TypeError('locate_point argument must be a Point')
  563. return capi.geos_project_normalized(self.ptr, point.ptr)
  564. @property
  565. def merged(self):
  566. """
  567. Return the line merge of this Geometry.
  568. """
  569. return self._topology(capi.geos_linemerge(self.ptr))
  570. @property
  571. def closed(self):
  572. """
  573. Return whether or not this Geometry is closed.
  574. """
  575. return capi.geos_isclosed(self.ptr)
  576. @deconstructible
  577. class GEOSGeometry(GEOSGeometryBase, ListMixin):
  578. "A class that, generally, encapsulates a GEOS geometry."
  579. def __init__(self, geo_input, srid=None):
  580. """
  581. The base constructor for GEOS geometry objects. It may take the
  582. following inputs:
  583. * strings:
  584. - WKT
  585. - HEXEWKB (a PostGIS-specific canonical form)
  586. - GeoJSON (requires GDAL)
  587. * buffer:
  588. - WKB
  589. The `srid` keyword specifies the Source Reference Identifier (SRID)
  590. number for this Geometry. If not provided, it defaults to None.
  591. """
  592. input_srid = None
  593. if isinstance(geo_input, bytes):
  594. geo_input = force_text(geo_input)
  595. if isinstance(geo_input, str):
  596. wkt_m = wkt_regex.match(geo_input)
  597. if wkt_m:
  598. # Handle WKT input.
  599. if wkt_m.group('srid'):
  600. input_srid = int(wkt_m.group('srid'))
  601. g = self._from_wkt(force_bytes(wkt_m.group('wkt')))
  602. elif hex_regex.match(geo_input):
  603. # Handle HEXEWKB input.
  604. g = wkb_r().read(force_bytes(geo_input))
  605. elif json_regex.match(geo_input):
  606. # Handle GeoJSON input.
  607. ogr = gdal.OGRGeometry.from_json(geo_input)
  608. g = ogr._geos_ptr()
  609. input_srid = ogr.srid
  610. else:
  611. raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.')
  612. elif isinstance(geo_input, GEOM_PTR):
  613. # When the input is a pointer to a geometry (GEOM_PTR).
  614. g = geo_input
  615. elif isinstance(geo_input, memoryview):
  616. # When the input is a buffer (WKB).
  617. g = wkb_r().read(geo_input)
  618. elif isinstance(geo_input, GEOSGeometry):
  619. g = capi.geom_clone(geo_input.ptr)
  620. else:
  621. raise TypeError('Improper geometry input type: %s' % type(geo_input))
  622. if not g:
  623. raise GEOSException('Could not initialize GEOS Geometry with given input.')
  624. input_srid = input_srid or capi.geos_get_srid(g) or None
  625. if input_srid and srid and input_srid != srid:
  626. raise ValueError('Input geometry already has SRID: %d.' % input_srid)
  627. super().__init__(g, None)
  628. # Set the SRID, if given.
  629. srid = input_srid or srid
  630. if srid and isinstance(srid, int):
  631. self.srid = srid