-
Notifications
You must be signed in to change notification settings - Fork 35
/
geometries.py
353 lines (266 loc) · 10.5 KB
/
geometries.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""pydantic models for GeoJSON Geometry objects."""
from __future__ import annotations
import abc
import warnings
from typing import Any, Iterator, List, Literal, Union
from pydantic import Field, field_validator
from typing_extensions import Annotated
from geojson_pydantic.base import _GeoJsonBase
from geojson_pydantic.types import (
LinearRing,
LineStringCoords,
MultiLineStringCoords,
MultiPointCoords,
MultiPolygonCoords,
PolygonCoords,
Position,
)
def _position_wkt_coordinates(coordinates: Position, force_z: bool = False) -> str:
"""Converts a Position to WKT Coordinates."""
wkt_coordinates = " ".join(str(number) for number in coordinates)
if force_z and len(coordinates) < 3:
wkt_coordinates += " 0.0"
return wkt_coordinates
def _position_has_z(position: Position) -> bool:
return len(position) == 3
def _position_list_wkt_coordinates(
coordinates: List[Position], force_z: bool = False
) -> str:
"""Converts a list of Positions to WKT Coordinates."""
return ", ".join(
_position_wkt_coordinates(position, force_z) for position in coordinates
)
def _position_list_has_z(positions: List[Position]) -> bool:
"""Checks if any position in a list has a Z."""
return any(_position_has_z(position) for position in positions)
def _lines_wtk_coordinates(
coordinates: List[LineStringCoords], force_z: bool = False
) -> str:
"""Converts lines to WKT Coordinates."""
return ", ".join(
f"({_position_list_wkt_coordinates(line, force_z)})" for line in coordinates
)
def _lines_has_z(lines: List[LineStringCoords]) -> bool:
"""Checks if any position in a list has a Z."""
return any(
_position_has_z(position) for positions in lines for position in positions
)
def _polygons_wkt_coordinates(
coordinates: List[PolygonCoords], force_z: bool = False
) -> str:
return ", ".join(
f"({_lines_wtk_coordinates(polygon, force_z)})" for polygon in coordinates
)
class _GeometryBase(_GeoJsonBase, abc.ABC):
"""Base class for geometry models"""
type: str
coordinates: Any
@abc.abstractmethod
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
...
@property
@abc.abstractmethod
def has_z(self) -> bool:
"""Checks if any coordinate has a Z value."""
...
@property
def wkt(self) -> str:
"""Return the Well Known Text representation."""
# Start with the WKT Type
wkt = self.type.upper()
has_z = self.has_z
if self.coordinates:
# If any of the coordinates have a Z add a "Z" to the WKT
wkt += " Z " if has_z else " "
# Add the rest of the WKT inside parentheses
wkt += f"({self.__wkt_coordinates__(self.coordinates, force_z=has_z)})"
else:
# Otherwise it will be "EMPTY"
wkt += " EMPTY"
return wkt
class Point(_GeometryBase):
"""Point Model"""
type: Literal["Point"]
coordinates: Position
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
return _position_wkt_coordinates(coordinates, force_z)
@property
def has_z(self) -> bool:
"""Checks if any coordinate has a Z value."""
return _position_has_z(self.coordinates)
class MultiPoint(_GeometryBase):
"""MultiPoint Model"""
type: Literal["MultiPoint"]
coordinates: MultiPointCoords
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
return ", ".join(
f"({_position_wkt_coordinates(position, force_z)})"
for position in coordinates
)
@property
def has_z(self) -> bool:
"""Checks if any coordinate has a Z value."""
return _position_list_has_z(self.coordinates)
class LineString(_GeometryBase):
"""LineString Model"""
type: Literal["LineString"]
coordinates: LineStringCoords
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
return _position_list_wkt_coordinates(coordinates, force_z)
@property
def has_z(self) -> bool:
"""Checks if any coordinate has a Z value."""
return _position_list_has_z(self.coordinates)
class MultiLineString(_GeometryBase):
"""MultiLineString Model"""
type: Literal["MultiLineString"]
coordinates: MultiLineStringCoords
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
return _lines_wtk_coordinates(coordinates, force_z)
@property
def has_z(self) -> bool:
"""Checks if any coordinate has a Z value."""
return _lines_has_z(self.coordinates)
class Polygon(_GeometryBase):
"""Polygon Model"""
type: Literal["Polygon"]
coordinates: PolygonCoords
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
return _lines_wtk_coordinates(coordinates, force_z)
@field_validator("coordinates")
def check_closure(cls, coordinates: List) -> List:
"""Validate that Polygon is closed (first and last coordinate are the same)."""
if any(ring[-1] != ring[0] for ring in coordinates):
raise ValueError("All linear rings have the same start and end coordinates")
return coordinates
@property
def exterior(self) -> Union[LinearRing, None]:
"""Return the exterior Linear Ring of the polygon."""
return self.coordinates[0] if self.coordinates else None
@property
def interiors(self) -> Iterator[LinearRing]:
"""Interiors (Holes) of the polygon."""
yield from (
interior for interior in self.coordinates[1:] if len(self.coordinates) > 1
)
@property
def has_z(self) -> bool:
"""Checks if any coordinates have a Z value."""
return _lines_has_z(self.coordinates)
@classmethod
def from_bounds(
cls, xmin: float, ymin: float, xmax: float, ymax: float
) -> "Polygon":
"""Create a Polygon geometry from a boundingbox."""
return cls(
type="Polygon",
coordinates=[
[(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax), (xmin, ymin)]
],
)
class MultiPolygon(_GeometryBase):
"""MultiPolygon Model"""
type: Literal["MultiPolygon"]
coordinates: MultiPolygonCoords
def __wkt_coordinates__(self, coordinates: Any, force_z: bool) -> str:
"""return WKT coordinates."""
return _polygons_wkt_coordinates(coordinates, force_z)
@property
def has_z(self) -> bool:
"""Checks if any coordinates have a Z value."""
return any(_lines_has_z(polygon) for polygon in self.coordinates)
@field_validator("coordinates")
def check_closure(cls, coordinates: List) -> List:
"""Validate that Polygon is closed (first and last coordinate are the same)."""
if any(ring[-1] != ring[0] for polygon in coordinates for ring in polygon):
raise ValueError("All linear rings have the same start and end coordinates")
return coordinates
class GeometryCollection(_GeoJsonBase):
"""GeometryCollection Model"""
type: Literal["GeometryCollection"]
geometries: List[Geometry]
def __iter__(self) -> Iterator[Geometry]: # type: ignore [override]
"""iterate over geometries"""
return iter(self.geometries)
def __len__(self) -> int:
"""return geometries length"""
return len(self.geometries)
def __getitem__(self, index: int) -> Geometry:
"""get geometry at a given index"""
return self.geometries[index]
@property
def wkt(self) -> str:
"""Return the Well Known Text representation."""
# Each geometry will check its own coordinates for Z and include "Z" in the wkt
# if necessary. Rather than looking at the coordinates for each of the geometries
# again, we can just get the wkt from each of them and check if there is a Z
# anywhere in the text.
# Get the wkt from each of the geometries in the collection
geometries = (
f'({", ".join(geom.wkt for geom in self.geometries)})'
if self.geometries
else "EMPTY"
)
# If any of them contain `Z` add Z to the output wkt
z = " Z " if "Z" in geometries else " "
return f"{self.type.upper()}{z}{geometries}"
@field_validator("geometries")
def check_geometries(cls, geometries: List) -> List:
"""Add warnings for conditions the spec does not explicitly forbid."""
if len(geometries) == 1:
warnings.warn(
"GeometryCollection should not be used for single geometries.",
stacklevel=1,
)
if any(geom.type == "GeometryCollection" for geom in geometries):
warnings.warn(
"GeometryCollection should not be used for nested GeometryCollections.",
stacklevel=1,
)
if len({geom.type for geom in geometries}) == 1:
warnings.warn(
"GeometryCollection should not be used for homogeneous collections.",
stacklevel=1,
)
return geometries
Geometry = Annotated[
Union[
Point,
MultiPoint,
LineString,
MultiLineString,
Polygon,
MultiPolygon,
GeometryCollection,
],
Field(discriminator="type"),
]
GeometryCollection.model_rebuild()
def parse_geometry_obj(obj: Any) -> Geometry:
"""
`obj` is an object that is supposed to represent a GeoJSON geometry. This method returns the
reads the `"type"` field and returns the correct pydantic Geometry model.
"""
if "type" not in obj:
raise ValueError("Missing 'type' field in geometry")
if obj["type"] == "Point":
return Point.model_validate(obj)
elif obj["type"] == "MultiPoint":
return MultiPoint.model_validate(obj)
elif obj["type"] == "LineString":
return LineString.model_validate(obj)
elif obj["type"] == "MultiLineString":
return MultiLineString.model_validate(obj)
elif obj["type"] == "Polygon":
return Polygon.model_validate(obj)
elif obj["type"] == "MultiPolygon":
return MultiPolygon.model_validate(obj)
elif obj["type"] == "GeometryCollection":
return GeometryCollection.model_validate(obj)
raise ValueError(f"Unknown type: {obj['type']}")