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.
 
 
 
 

676 lines
23 KiB

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