Debian Codegraph @

django/contrib/gis/gdal/geometries.py

raw
1 """
2 The OGRGeometry is a wrapper for using the OGR Geometry class
3 (see https://gdal.org/api/ogrgeometry_cpp.html#_CPPv411OGRGeometry).
4 OGRGeometry may be instantiated when reading geometries from OGR Data Sources
5 (e.g. SHP files), or when given OGC WKT (a string).
6
7 While the 'full' API is not present yet, the API is "pythonic" unlike
8 the traditional and "next-generation" OGR Python bindings. One major
9 advantage OGR Geometries have over their GEOS counterparts is support
10 for spatial reference systems and their transformation.
11
12 Example:
13 >>> from django.contrib.gis.gdal import OGRGeometry, OGRGeomType, SpatialReference
14 >>> wkt1, wkt2 = 'POINT(-90 30)', 'POLYGON((0 0, 5 0, 5 5, 0 5)'
15 >>> pnt = OGRGeometry(wkt1)
16 >>> print(pnt)
17 POINT (-90 30)
18 >>> mpnt = OGRGeometry(OGRGeomType('MultiPoint'), SpatialReference('WGS84'))
19 >>> mpnt.add(wkt1)
20 >>> mpnt.add(wkt1)
21 >>> print(mpnt)
22 MULTIPOINT (-90 30,-90 30)
23 >>> print(mpnt.srs.name)
24 WGS 84
25 >>> print(mpnt.srs.proj)
26 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
27 >>> mpnt.transform(SpatialReference('NAD27'))
28 >>> print(mpnt.proj)
29 +proj=longlat +ellps=clrk66 +datum=NAD27 +no_defs
30 >>> print(mpnt)
31 MULTIPOINT (-89.99993037860248 29.99979788655764,-89.99993037860248 29.99979788655764)
32
33 The OGRGeomType class is to make it easy to specify an OGR geometry type:
34 >>> from django.contrib.gis.gdal import OGRGeomType
35 >>> gt1 = OGRGeomType(3) # Using an integer for the type
36 >>> gt2 = OGRGeomType('Polygon') # Using a string
37 >>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive
38 >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
39 True True
40 """
41
42 import sys
43 import warnings
44 from binascii import b2a_hex
45 from ctypes import byref, c_char_p, c_double, c_ubyte, c_void_p, string_at
46
47 from django.contrib.gis.gdal.base import GDALBase
48 from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
49 from django.contrib.gis.gdal.error import GDALException, SRSException
50 from django.contrib.gis.gdal.geomtype import OGRGeomType
51 from django.contrib.gis.gdal.prototypes import geom as capi
52 from django.contrib.gis.gdal.prototypes import srs as srs_api
53 from django.contrib.gis.gdal.srs import CoordTransform, SpatialReference
54 from django.contrib.gis.geometry import hex_regex, json_regex, wkt_regex
55 from django.utils.deprecation import RemovedInDjango60Warning
56 from django.utils.encoding import force_bytes
57
58
59 # For more information, see the OGR C API source code:
60 # https://gdal.org/api/vector_c_api.html
61 #
62 # The OGR_G_* routines are relevant here.
63 class OGRGeometry(GDALBase):
64 """Encapsulate an OGR geometry."""
65
66 destructor = capi.destroy_geom
67 geos_support = True
68
69 def __init__(self, geom_input, srs=None):
70 """Initialize Geometry on either WKT or an OGR pointer as input."""
71 str_instance = isinstance(geom_input, str)
72
73 # If HEX, unpack input to a binary buffer.
74 if str_instance and hex_regex.match(geom_input):
75 geom_input = memoryview(bytes.fromhex(geom_input))
76 str_instance = False
77
78 # Constructing the geometry,
79 if str_instance:
80 wkt_m = wkt_regex.match(geom_input)
81 json_m = json_regex.match(geom_input)
82 if wkt_m:
83 if wkt_m["srid"]:
84 # If there's EWKT, set the SRS w/value of the SRID.
85 srs = int(wkt_m["srid"])
86 if wkt_m["type"].upper() == "LINEARRING":
87 # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT.
88 # See https://trac.osgeo.org/gdal/ticket/1992.
89 g = capi.create_geom(OGRGeomType(wkt_m["type"]).num)
90 capi.import_wkt(g, byref(c_char_p(wkt_m["wkt"].encode())))
91 else:
92 g = capi.from_wkt(
93 byref(c_char_p(wkt_m["wkt"].encode())), None, byref(c_void_p())
94 )
95 elif json_m:
96 g = self._from_json(geom_input.encode())
97 else:
98 # Seeing if the input is a valid short-hand string
99 # (e.g., 'Point', 'POLYGON').
100 OGRGeomType(geom_input)
101 g = capi.create_geom(OGRGeomType(geom_input).num)
102 elif isinstance(geom_input, memoryview):
103 # WKB was passed in
104 g = self._from_wkb(geom_input)
105 elif isinstance(geom_input, OGRGeomType):
106 # OGRGeomType was passed in, an empty geometry will be created.
107 g = capi.create_geom(geom_input.num)
108 elif isinstance(geom_input, self.ptr_type):
109 # OGR pointer (c_void_p) was the input.
110 g = geom_input
111 else:
112 raise GDALException(
113 "Invalid input type for OGR Geometry construction: %s"
114 % type(geom_input)
115 )
116
117 # Now checking the Geometry pointer before finishing initialization
118 # by setting the pointer for the object.
119 if not g:
120 raise GDALException(
121 "Cannot create OGR Geometry from input: %s" % geom_input
122 )
123 self.ptr = g
124
125 # Assigning the SpatialReference object to the geometry, if valid.
126 if srs:
127 self.srs = srs
128
129 # Setting the class depending upon the OGR Geometry Type
130 if (geo_class := GEO_CLASSES.get(self.geom_type.num)) is None:
131 raise TypeError(f"Unsupported geometry type: {self.geom_type}")
132 self.__class__ = geo_class
133
134 # Pickle routines
135 def __getstate__(self):
136 srs = self.srs
137 if srs:
138 srs = srs.wkt
139 else:
140 srs = None
141 return bytes(self.wkb), srs
142
143 def __setstate__(self, state):
144 wkb, srs = state
145 ptr = capi.from_wkb(wkb, None, byref(c_void_p()), len(wkb))
146 if not ptr:
147 raise GDALException("Invalid OGRGeometry loaded from pickled state.")
148 self.ptr = ptr
149 self.srs = srs
150
151 @classmethod
152 def _from_wkb(cls, geom_input):
153 return capi.from_wkb(
154 bytes(geom_input), None, byref(c_void_p()), len(geom_input)
155 )
156
157 @staticmethod
158 def _from_json(geom_input):
159 return capi.from_json(geom_input)
160
161 @classmethod
162 def from_bbox(cls, bbox):
163 "Construct a Polygon from a bounding box (4-tuple)."
164 x0, y0, x1, y1 = bbox
165 return OGRGeometry(
166 "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))"
167 % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0)
168 )
169
170 @staticmethod
171 def from_json(geom_input):
172 return OGRGeometry(OGRGeometry._from_json(force_bytes(geom_input)))
173
174 @classmethod
175 def from_gml(cls, gml_string):
176 return cls(capi.from_gml(force_bytes(gml_string)))
177
178 # ### Geometry set-like operations ###
179 # g = g1 | g2
180 def __or__(self, other):
181 "Return the union of the two geometries."
182 return self.union(other)
183
184 # g = g1 & g2
185 def __and__(self, other):
186 "Return the intersection of this Geometry and the other."
187 return self.intersection(other)
188
189 # g = g1 - g2
190 def __sub__(self, other):
191 "Return the difference this Geometry and the other."
192 return self.difference(other)
193
194 # g = g1 ^ g2
195 def __xor__(self, other):
196 "Return the symmetric difference of this Geometry and the other."
197 return self.sym_difference(other)
198
199 def __eq__(self, other):
200 "Is this Geometry equal to the other?"
201 return isinstance(other, OGRGeometry) and self.equals(other)
202
203 def __str__(self):
204 "WKT is used for the string representation."
205 return self.wkt
206
207 # #### Geometry Properties ####
208 @property
209 def dimension(self):
210 "Return 0 for points, 1 for lines, and 2 for surfaces."
211 return capi.get_dims(self.ptr)
212
213 @property
214 def coord_dim(self):
215 "Return the coordinate dimension of the Geometry."
216 return capi.get_coord_dim(self.ptr)
217
218 # RemovedInDjango60Warning
219 @coord_dim.setter
220 def coord_dim(self, dim):
221 "Set the coordinate dimension of this Geometry."
222 msg = "coord_dim setter is deprecated. Use set_3d() instead."
223 warnings.warn(msg, RemovedInDjango60Warning, stacklevel=2)
224 if dim not in (2, 3):
225 raise ValueError("Geometry dimension must be either 2 or 3")
226 capi.set_coord_dim(self.ptr, dim)
227
228 @property
229 def geom_count(self):
230 "Return the number of elements in this Geometry."
231 return capi.get_geom_count(self.ptr)
232
233 @property
234 def point_count(self):
235 "Return the number of Points in this Geometry."
236 return capi.get_point_count(self.ptr)
237
238 @property
239 def num_points(self):
240 "Alias for `point_count` (same name method in GEOS API.)"
241 return self.point_count
242
243 @property
244 def num_coords(self):
245 "Alias for `point_count`."
246 return self.point_count
247
248 @property
249 def geom_type(self):
250 "Return the Type for this Geometry."
251 return OGRGeomType(capi.get_geom_type(self.ptr))
252
253 @property
254 def geom_name(self):
255 "Return the Name of this Geometry."
256 return capi.get_geom_name(self.ptr)
257
258 @property
259 def area(self):
260 "Return the area for a LinearRing, Polygon, or MultiPolygon; 0 otherwise."
261 return capi.get_area(self.ptr)
262
263 @property
264 def envelope(self):
265 "Return the envelope for this Geometry."
266 # TODO: Fix Envelope() for Point geometries.
267 return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope())))
268
269 @property
270 def empty(self):
271 return capi.is_empty(self.ptr)
272
273 @property
274 def extent(self):
275 "Return the envelope as a 4-tuple, instead of as an Envelope object."
276 return self.envelope.tuple
277
278 @property
279 def is_3d(self):
280 """Return True if the geometry has Z coordinates."""
281 return capi.is_3d(self.ptr)
282
283 def set_3d(self, value):
284 """Set if this geometry has Z coordinates."""
285 if value is True:
286 capi.set_3d(self.ptr, 1)
287 elif value is False:
288 capi.set_3d(self.ptr, 0)
289 else:
290 raise ValueError(f"Input to 'set_3d' must be a boolean, got '{value!r}'.")
291
292 @property
293 def is_measured(self):
294 """Return True if the geometry has M coordinates."""
295 return capi.is_measured(self.ptr)
296
297 def set_measured(self, value):
298 """Set if this geometry has M coordinates."""
299 if value is True:
300 capi.set_measured(self.ptr, 1)
301 elif value is False:
302 capi.set_measured(self.ptr, 0)
303 else:
304 raise ValueError(
305 f"Input to 'set_measured' must be a boolean, got '{value!r}'."
306 )
307
308 @property
309 def has_curve(self):
310 """Return True if the geometry is or has curve geometry."""
311 return capi.has_curve_geom(self.ptr, 0)
312
313 def get_linear_geometry(self):
314 """Return a linear version of this geometry."""
315 return OGRGeometry(capi.get_linear_geom(self.ptr, 0, None))
316
317 def get_curve_geometry(self):
318 """Return a curve version of this geometry."""
319 return OGRGeometry(capi.get_curve_geom(self.ptr, None))
320
321 # #### SpatialReference-related Properties ####
322
323 # The SRS property
324 def _get_srs(self):
325 "Return the Spatial Reference for this Geometry."
326 try:
327 srs_ptr = capi.get_geom_srs(self.ptr)
328 return SpatialReference(srs_api.clone_srs(srs_ptr))
329 except SRSException:
330 return None
331
332 def _set_srs(self, srs):
333 "Set the SpatialReference for this geometry."
334 # Do not have to clone the `SpatialReference` object pointer because
335 # when it is assigned to this `OGRGeometry` it's internal OGR
336 # reference count is incremented, and will likewise be released
337 # (decremented) when this geometry's destructor is called.
338 if isinstance(srs, SpatialReference):
339 srs_ptr = srs.ptr
340 elif isinstance(srs, (int, str)):
341 sr = SpatialReference(srs)
342 srs_ptr = sr.ptr
343 elif srs is None:
344 srs_ptr = None
345 else:
346 raise TypeError(
347 "Cannot assign spatial reference with object of type: %s" % type(srs)
348 )
349 capi.assign_srs(self.ptr, srs_ptr)
350
351 srs = property(_get_srs, _set_srs)
352
353 # The SRID property
354 def _get_srid(self):
355 srs = self.srs
356 if srs:
357 return srs.srid
358 return None
359
360 def _set_srid(self, srid):
361 if isinstance(srid, int) or srid is None:
362 self.srs = srid
363 else:
364 raise TypeError("SRID must be set with an integer.")
365
366 srid = property(_get_srid, _set_srid)
367
368 # #### Output Methods ####
369 def _geos_ptr(self):
370 from django.contrib.gis.geos import GEOSGeometry
371
372 return GEOSGeometry._from_wkb(self.wkb)
373
374 @property
375 def geos(self):
376 "Return a GEOSGeometry object from this OGRGeometry."
377 if self.geos_support:
378 from django.contrib.gis.geos import GEOSGeometry
379
380 return GEOSGeometry(self._geos_ptr(), self.srid)
381 else:
382 from django.contrib.gis.geos import GEOSException
383
384 raise GEOSException(f"GEOS does not support {self.__class__.__qualname__}.")
385
386 @property
387 def gml(self):
388 "Return the GML representation of the Geometry."
389 return capi.to_gml(self.ptr)
390
391 @property
392 def hex(self):
393 "Return the hexadecimal representation of the WKB (a string)."
394 return b2a_hex(self.wkb).upper()
395
396 @property
397 def json(self):
398 """
399 Return the GeoJSON representation of this Geometry.
400 """
401 return capi.to_json(self.ptr)
402
403 geojson = json
404
405 @property
406 def kml(self):
407 "Return the KML representation of the Geometry."
408 return capi.to_kml(self.ptr, None)
409
410 @property
411 def wkb_size(self):
412 "Return the size of the WKB buffer."
413 return capi.get_wkbsize(self.ptr)
414
415 @property
416 def wkb(self):
417 "Return the WKB representation of the Geometry."
418 if sys.byteorder == "little":
419 byteorder = 1 # wkbNDR (from ogr_core.h)
420 else:
421 byteorder = 0 # wkbXDR
422 sz = self.wkb_size
423 # Creating the unsigned character buffer, and passing it in by reference.
424 buf = (c_ubyte * sz)()
425 # For backward compatibility, export old-style 99-402 extended
426 # dimension types when geometry does not have an M dimension.
427 # https://gdal.org/api/vector_c_api.html#_CPPv417OGR_G_ExportToWkb12OGRGeometryH15OGRwkbByteOrderPh
428 to_wkb = capi.to_iso_wkb if self.is_measured else capi.to_wkb
429 to_wkb(self.ptr, byteorder, byref(buf))
430 # Returning a buffer of the string at the pointer.
431 return memoryview(string_at(buf, sz))
432
433 @property
434 def wkt(self):
435 "Return the WKT representation of the Geometry."
436 # For backward compatibility, export old-style 99-402 extended
437 # dimension types when geometry does not have an M dimension.
438 # https://gdal.org/api/vector_c_api.html#_CPPv417OGR_G_ExportToWkt12OGRGeometryHPPc
439 to_wkt = capi.to_iso_wkt if self.is_measured else capi.to_wkt
440 return to_wkt(self.ptr, byref(c_char_p()))
441
442 @property
443 def ewkt(self):
444 "Return the EWKT representation of the Geometry."
445 srs = self.srs
446 if srs and srs.srid:
447 return "SRID=%s;%s" % (srs.srid, self.wkt)
448 else:
449 return self.wkt
450
451 # #### Geometry Methods ####
452 def clone(self):
453 "Clone this OGR Geometry."
454 return OGRGeometry(capi.clone_geom(self.ptr), self.srs)
455
456 def close_rings(self):
457 """
458 If there are any rings within this geometry that have not been
459 closed, this routine will do so by adding the starting point at the
460 end.
461 """
462 # Closing the open rings.
463 capi.geom_close_rings(self.ptr)
464
465 def transform(self, coord_trans, clone=False):
466 """
467 Transform this geometry to a different spatial reference system.
468 May take a CoordTransform object, a SpatialReference object, string
469 WKT or PROJ, and/or an integer SRID. By default, return nothing
470 and transform the geometry in-place. However, if the `clone` keyword is
471 set, return a transformed clone of this geometry.
472 """
473 if clone:
474 klone = self.clone()
475 klone.transform(coord_trans)
476 return klone
477
478 # Depending on the input type, use the appropriate OGR routine
479 # to perform the transformation.
480 if isinstance(coord_trans, CoordTransform):
481 capi.geom_transform(self.ptr, coord_trans.ptr)
482 elif isinstance(coord_trans, SpatialReference):
483 capi.geom_transform_to(self.ptr, coord_trans.ptr)
484 elif isinstance(coord_trans, (int, str)):
485 sr = SpatialReference(coord_trans)
486 capi.geom_transform_to(self.ptr, sr.ptr)
487 else:
488 raise TypeError(
489 "Transform only accepts CoordTransform, "
490 "SpatialReference, string, and integer objects."
491 )
492
493 # #### Topology Methods ####
494 def _topology(self, func, other):
495 """A generalized function for topology operations, takes a GDAL function and
496 the other geometry to perform the operation on."""
497 if not isinstance(other, OGRGeometry):
498 raise TypeError(
499 "Must use another OGRGeometry object for topology operations!"
500 )
501
502 # Returning the output of the given function with the other geometry's
503 # pointer.
504 return func(self.ptr, other.ptr)
505
506 def intersects(self, other):
507 "Return True if this geometry intersects with the other."
508 return self._topology(capi.ogr_intersects, other)
509
510 def equals(self, other):
511 "Return True if this geometry is equivalent to the other."
512 return self._topology(capi.ogr_equals, other)
513
514 def disjoint(self, other):
515 "Return True if this geometry and the other are spatially disjoint."
516 return self._topology(capi.ogr_disjoint, other)
517
518 def touches(self, other):
519 "Return True if this geometry touches the other."
520 return self._topology(capi.ogr_touches, other)
521
522 def crosses(self, other):
523 "Return True if this geometry crosses the other."
524 return self._topology(capi.ogr_crosses, other)
525
526 def within(self, other):
527 "Return True if this geometry is within the other."
528 return self._topology(capi.ogr_within, other)
529
530 def contains(self, other):
531 "Return True if this geometry contains the other."
532 return self._topology(capi.ogr_contains, other)
533
534 def overlaps(self, other):
535 "Return True if this geometry overlaps the other."
536 return self._topology(capi.ogr_overlaps, other)
537
538 # #### Geometry-generation Methods ####
539 def _geomgen(self, gen_func, other=None):
540 "A helper routine for the OGR routines that generate geometries."
541 if isinstance(other, OGRGeometry):
542 return OGRGeometry(gen_func(self.ptr, other.ptr), self.srs)
543 else:
544 return OGRGeometry(gen_func(self.ptr), self.srs)
545
546 @property
547 def boundary(self):
548 "Return the boundary of this geometry."
549 return self._geomgen(capi.get_boundary)
550
551 @property
552 def convex_hull(self):
553 """
554 Return the smallest convex Polygon that contains all the points in
555 this Geometry.
556 """
557 return self._geomgen(capi.geom_convex_hull)
558
559 def difference(self, other):
560 """
561 Return a new geometry consisting of the region which is the difference
562 of this geometry and the other.
563 """
564 return self._geomgen(capi.geom_diff, other)
565
566 def intersection(self, other):
567 """
568 Return a new geometry consisting of the region of intersection of this
569 geometry and the other.
570 """
571 return self._geomgen(capi.geom_intersection, other)
572
573 def sym_difference(self, other):
574 """
575 Return a new geometry which is the symmetric difference of this
576 geometry and the other.
577 """
578 return self._geomgen(capi.geom_sym_diff, other)
579
580 def union(self, other):
581 """
582 Return a new geometry consisting of the region which is the union of
583 this geometry and the other.
584 """
585 return self._geomgen(capi.geom_union, other)
586
587 @property
588 def centroid(self):
589 """Return the centroid (a Point) of this Polygon."""
590 # The centroid is a Point, create a geometry for this.
591 p = OGRGeometry(OGRGeomType("Point"))
592 capi.get_centroid(self.ptr, p.ptr)
593 return p
594
595
596 # The subclasses for OGR Geometry.
597 class Point(OGRGeometry):
598 def _geos_ptr(self):
599 from django.contrib.gis import geos
600
601 return geos.Point._create_empty() if self.empty else super()._geos_ptr()
602
603 @classmethod
604 def _create_empty(cls):
605 return capi.create_geom(OGRGeomType("point").num)
606
607 @property
608 def x(self):
609 "Return the X coordinate for this Point."
610 return capi.getx(self.ptr, 0)
611
612 @property
613 def y(self):
614 "Return the Y coordinate for this Point."
615 return capi.gety(self.ptr, 0)
616
617 @property
618 def z(self):
619 "Return the Z coordinate for this Point."
620 if self.is_3d:
621 return capi.getz(self.ptr, 0)
622
623 @property
624 def m(self):
625 """Return the M coordinate for this Point."""
626 if self.is_measured:
627 return capi.getm(self.ptr, 0)
628
629 @property
630 def tuple(self):
631 "Return the tuple of this point."
632 if self.is_3d and self.is_measured:
633 return self.x, self.y, self.z, self.m
634 if self.is_3d:
635 return self.x, self.y, self.z
636 if self.is_measured:
637 return self.x, self.y, self.m
638 return self.x, self.y
639
640 coords = tuple
641
642
643 class LineString(OGRGeometry):
644 def __getitem__(self, index):
645 "Return the Point at the given index."
646 if 0 <= index < self.point_count:
647 x, y, z, m = c_double(), c_double(), c_double(), c_double()
648 capi.get_point(self.ptr, index, byref(x), byref(y), byref(z), byref(m))
649 if self.is_3d and self.is_measured:
650 return x.value, y.value, z.value, m.value
651 if self.is_3d:
652 return x.value, y.value, z.value
653 if self.is_measured:
654 return x.value, y.value, m.value
655 dim = self.coord_dim
656 if dim == 1:
657 return (x.value,)
658 elif dim == 2:
659 return (x.value, y.value)
660 else:
661 raise IndexError(
662 "Index out of range when accessing points of a line string: %s." % index
663 )
664
665 def __len__(self):
666 "Return the number of points in the LineString."
667 return self.point_count
668
669 @property
670 def tuple(self):
671 "Return the tuple representation of this LineString."
672 return tuple(self[i] for i in range(len(self)))
673
674 coords = tuple
675
676 def _listarr(self, func):
677 """
678 Internal routine that returns a sequence (list) corresponding with
679 the given function.
680 """
681 return [func(self.ptr, i) for i in range(len(self))]
682
683 @property
684 def x(self):
685 "Return the X coordinates in a list."
686 return self._listarr(capi.getx)
687
688 @property
689 def y(self):
690 "Return the Y coordinates in a list."
691 return self._listarr(capi.gety)
692
693 @property
694 def z(self):
695 "Return the Z coordinates in a list."
696 if self.is_3d:
697 return self._listarr(capi.getz)
698
699 @property
700 def m(self):
701 """Return the M coordinates in a list."""
702 if self.is_measured:
703 return self._listarr(capi.getm)
704
705
706 # LinearRings are used in Polygons.
707 class LinearRing(LineString):
708 pass
709
710
711 class Polygon(OGRGeometry):
712 def __len__(self):
713 "Return the number of interior rings in this Polygon."
714 return self.geom_count
715
716 def __getitem__(self, index):
717 "Get the ring at the specified index."
718 if 0 <= index < self.geom_count:
719 return OGRGeometry(
720 capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs
721 )
722 else:
723 raise IndexError(
724 "Index out of range when accessing rings of a polygon: %s." % index
725 )
726
727 # Polygon Properties
728 @property
729 def shell(self):
730 "Return the shell of this Polygon."
731 return self[0] # First ring is the shell
732
733 exterior_ring = shell
734
735 @property
736 def tuple(self):
737 "Return a tuple of LinearRing coordinate tuples."
738 return tuple(self[i].tuple for i in range(self.geom_count))
739
740 coords = tuple
741
742 @property
743 def point_count(self):
744 "Return the number of Points in this Polygon."
745 # Summing up the number of points in each ring of the Polygon.
746 return sum(self[i].point_count for i in range(self.geom_count))
747
748
749 class CircularString(LineString):
750 geos_support = False
751
752
753 class CurvePolygon(Polygon):
754 geos_support = False
755
756
757 class CompoundCurve(OGRGeometry):
758 geos_support = False
759
760
761 # Geometry Collection base class.
762 class GeometryCollection(OGRGeometry):
763 "The Geometry Collection class."
764
765 def __getitem__(self, index):
766 "Get the Geometry at the specified index."
767 if 0 <= index < self.geom_count:
768 return OGRGeometry(
769 capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs
770 )
771 else:
772 raise IndexError(
773 "Index out of range when accessing geometry in a collection: %s."
774 % index
775 )
776
777 def __len__(self):
778 "Return the number of geometries in this Geometry Collection."
779 return self.geom_count
780
781 def add(self, geom):
782 "Add the geometry to this Geometry Collection."
783 if isinstance(geom, OGRGeometry):
784 if isinstance(geom, self.__class__):
785 for g in geom:
786 capi.add_geom(self.ptr, g.ptr)
787 else:
788 capi.add_geom(self.ptr, geom.ptr)
789 elif isinstance(geom, str):
790 tmp = OGRGeometry(geom)
791 capi.add_geom(self.ptr, tmp.ptr)
792 else:
793 raise GDALException("Must add an OGRGeometry.")
794
795 @property
796 def point_count(self):
797 "Return the number of Points in this Geometry Collection."
798 # Summing up the number of points in each geometry in this collection
799 return sum(self[i].point_count for i in range(self.geom_count))
800
801 @property
802 def tuple(self):
803 "Return a tuple representation of this Geometry Collection."
804 return tuple(self[i].tuple for i in range(self.geom_count))
805
806 coords = tuple
807
808
809 # Multiple Geometry types.
810 class MultiPoint(GeometryCollection):
811 pass
812
813
814 class MultiLineString(GeometryCollection):
815 pass
816
817
818 class MultiPolygon(GeometryCollection):
819 pass
820
821
822 class MultiSurface(GeometryCollection):
823 geos_support = False
824
825
826 class MultiCurve(GeometryCollection):
827 geos_support = False
828
829
830 # Class mapping dictionary (using the OGRwkbGeometryType as the key)
831 GEO_CLASSES = {
832 1: Point,
833 2: LineString,
834 3: Polygon,
835 4: MultiPoint,
836 5: MultiLineString,
837 6: MultiPolygon,
838 7: GeometryCollection,
839 8: CircularString,
840 9: CompoundCurve,
841 10: CurvePolygon,
842 11: MultiCurve,
843 12: MultiSurface,
844 101: LinearRing,
845 1008: CircularString, # CIRCULARSTRING Z
846 1009: CompoundCurve, # COMPOUNDCURVE Z
847 1010: CurvePolygon, # CURVEPOLYGON Z
848 1011: MultiCurve, # MULTICURVE Z
849 1012: MultiSurface, # MULTICURVE Z
850 2001: Point, # POINT M
851 2002: LineString, # LINESTRING M
852 2003: Polygon, # POLYGON M
853 2004: MultiPoint, # MULTIPOINT M
854 2005: MultiLineString, # MULTILINESTRING M
855 2006: MultiPolygon, # MULTIPOLYGON M
856 2007: GeometryCollection, # GEOMETRYCOLLECTION M
857 2008: CircularString, # CIRCULARSTRING M
858 2009: CompoundCurve, # COMPOUNDCURVE M
859 2010: CurvePolygon, # CURVEPOLYGON M
860 2011: MultiCurve, # MULTICURVE M
861 2012: MultiSurface, # MULTICURVE M
862 3001: Point, # POINT ZM
863 3002: LineString, # LINESTRING ZM
864 3003: Polygon, # POLYGON ZM
865 3004: MultiPoint, # MULTIPOINT ZM
866 3005: MultiLineString, # MULTILINESTRING ZM
867 3006: MultiPolygon, # MULTIPOLYGON ZM
868 3007: GeometryCollection, # GEOMETRYCOLLECTION ZM
869 3008: CircularString, # CIRCULARSTRING ZM
870 3009: CompoundCurve, # COMPOUNDCURVE ZM
871 3010: CurvePolygon, # CURVEPOLYGON ZM
872 3011: MultiCurve, # MULTICURVE ZM
873 3012: MultiSurface, # MULTISURFACE ZM
874 1 + OGRGeomType.wkb25bit: Point, # POINT Z
875 2 + OGRGeomType.wkb25bit: LineString, # LINESTRING Z
876 3 + OGRGeomType.wkb25bit: Polygon, # POLYGON Z
877 4 + OGRGeomType.wkb25bit: MultiPoint, # MULTIPOINT Z
878 5 + OGRGeomType.wkb25bit: MultiLineString, # MULTILINESTRING Z
879 6 + OGRGeomType.wkb25bit: MultiPolygon, # MULTIPOLYGON Z
880 7 + OGRGeomType.wkb25bit: GeometryCollection, # GEOMETRYCOLLECTION Z
881 }