Debian Codegraph @

django/contrib/gis/geos/polygon.py

raw
1 from django.contrib.gis.geos import prototypes as capi
2 from django.contrib.gis.geos.geometry import GEOSGeometry
3 from django.contrib.gis.geos.libgeos import GEOM_PTR
4 from django.contrib.gis.geos.linestring import LinearRing
5
6
7 class Polygon(GEOSGeometry):
8 _minlength = 1
9
10 def __init__(self, *args, **kwargs):
11 """
12 Initialize on an exterior ring and a sequence of holes (both
13 instances may be either LinearRing instances, or a tuple/list
14 that may be constructed into a LinearRing).
15
16 Examples of initialization, where shell, hole1, and hole2 are
17 valid LinearRing geometries:
18 >>> from django.contrib.gis.geos import LinearRing, Polygon
19 >>> shell = hole1 = hole2 = LinearRing()
20 >>> poly = Polygon(shell, hole1, hole2)
21 >>> poly = Polygon(shell, (hole1, hole2))
22
23 >>> # Example where a tuple parameters are used:
24 >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0)),
25 ... ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))
26 """
27 if not args:
28 super().__init__(self._create_polygon(0, None), **kwargs)
29 return
30
31 # Getting the ext_ring and init_holes parameters from the argument list
32 ext_ring, *init_holes = args
33 n_holes = len(init_holes)
34
35 # If initialized as Polygon(shell, (LinearRing, LinearRing))
36 # [for backward-compatibility]
37 if n_holes == 1 and isinstance(init_holes[0], (tuple, list)):
38 if not init_holes[0]:
39 init_holes = ()
40 n_holes = 0
41 elif isinstance(init_holes[0][0], LinearRing):
42 init_holes = init_holes[0]
43 n_holes = len(init_holes)
44
45 polygon = self._create_polygon(n_holes + 1, [ext_ring, *init_holes])
46 super().__init__(polygon, **kwargs)
47
48 def __iter__(self):
49 "Iterate over each ring in the polygon."
50 for i in range(len(self)):
51 yield self[i]
52
53 def __len__(self):
54 "Return the number of rings in this Polygon."
55 return self.num_interior_rings + 1
56
57 @classmethod
58 def from_bbox(cls, bbox):
59 "Construct a Polygon from a bounding box (4-tuple)."
60 x0, y0, x1, y1 = bbox
61 for z in bbox:
62 if not isinstance(z, (float, int)):
63 return GEOSGeometry(
64 "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))"
65 % (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0)
66 )
67 return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))
68
69 # ### These routines are needed for list-like operation w/ListMixin ###
70 def _create_polygon(self, length, items):
71 # Instantiate LinearRing objects if necessary, but don't clone them yet
72 # _construct_ring will throw a TypeError if a parameter isn't a valid ring
73 # If we cloned the pointers here, we wouldn't be able to clean up
74 # in case of error.
75 if not length:
76 return capi.create_empty_polygon()
77
78 rings = []
79 for r in items:
80 if isinstance(r, GEOM_PTR):
81 rings.append(r)
82 else:
83 rings.append(self._construct_ring(r))
84
85 shell = self._clone(rings.pop(0))
86
87 n_holes = length - 1
88 if n_holes:
89 holes_param = (GEOM_PTR * n_holes)(*[self._clone(r) for r in rings])
90 else:
91 holes_param = None
92
93 return capi.create_polygon(shell, holes_param, n_holes)
94
95 def _clone(self, g):
96 if isinstance(g, GEOM_PTR):
97 return capi.geom_clone(g)
98 else:
99 return capi.geom_clone(g.ptr)
100
101 def _construct_ring(
102 self,
103 param,
104 msg=(
105 "Parameter must be a sequence of LinearRings or objects that can "
106 "initialize to LinearRings"
107 ),
108 ):
109 "Try to construct a ring from the given parameter."
110 if isinstance(param, LinearRing):
111 return param
112 try:
113 return LinearRing(param)
114 except TypeError:
115 raise TypeError(msg)
116
117 def _set_list(self, length, items):
118 # Getting the current pointer, replacing with the newly constructed
119 # geometry, and destroying the old geometry.
120 prev_ptr = self.ptr
121 srid = self.srid
122 self.ptr = self._create_polygon(length, items)
123 if srid:
124 self.srid = srid
125 capi.destroy_geom(prev_ptr)
126
127 def _get_single_internal(self, index):
128 """
129 Return the ring at the specified index. The first index, 0, will
130 always return the exterior ring. Indices > 0 will return the
131 interior ring at the given index (e.g., poly[1] and poly[2] would
132 return the first and second interior ring, respectively).
133
134 CAREFUL: Internal/External are not the same as Interior/Exterior!
135 Return a pointer from the existing geometries for use internally by the
136 object's methods. _get_single_external() returns a clone of the same
137 geometry for use by external code.
138 """
139 if index == 0:
140 return capi.get_extring(self.ptr)
141 else:
142 # Getting the interior ring, have to subtract 1 from the index.
143 return capi.get_intring(self.ptr, index - 1)
144
145 def _get_single_external(self, index):
146 return GEOSGeometry(
147 capi.geom_clone(self._get_single_internal(index)), srid=self.srid
148 )
149
150 _set_single = GEOSGeometry._set_single_rebuild
151 _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild
152
153 # #### Polygon Properties ####
154 @property
155 def num_interior_rings(self):
156 "Return the number of interior rings."
157 # Getting the number of rings
158 return capi.get_nrings(self.ptr)
159
160 def _get_ext_ring(self):
161 "Get the exterior ring of the Polygon."
162 return self[0]
163
164 def _set_ext_ring(self, ring):
165 "Set the exterior ring of the Polygon."
166 self[0] = ring
167
168 # Properties for the exterior ring/shell.
169 exterior_ring = property(_get_ext_ring, _set_ext_ring)
170 shell = exterior_ring
171
172 @property
173 def tuple(self):
174 "Get the tuple for each ring in this Polygon."
175 return tuple(self[i].tuple for i in range(len(self)))
176
177 coords = tuple
178
179 @property
180 def kml(self):
181 "Return the KML representation of this Polygon."
182 inner_kml = "".join(
183 "<innerBoundaryIs>%s</innerBoundaryIs>" % self[i + 1].kml
184 for i in range(self.num_interior_rings)
185 )
186 return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (
187 self[0].kml,
188 inner_kml,
189 )