Debian Codegraph @

django/contrib/gis/geos/geometry.py

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