Development of an internal social media platform with personalised dashboards for students
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

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