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