Coverage for src/geodense/lib.py: 95%
341 statements
« prev ^ index » next coverage.py v7.6.1, created at 2026-10-24 20:04 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2026-10-24 20:04 +0000
1import json
2import logging
3import math
4import os
5import sys
6import tempfile
7from collections.abc import Callable, Iterable, Sequence
8from enum import Enum
9from functools import partial
10from typing import Literal, TextIO, cast
12from geojson_pydantic import (
13 Feature,
14 GeometryCollection,
15 LineString,
16 MultiLineString,
17 MultiPoint,
18 MultiPolygon,
19 Point,
20 Polygon,
21)
22from geojson_pydantic.geometries import Geometry
23from geojson_pydantic.types import LineStringCoords, Position, Position2D, Position3D
24from pydantic import BaseModel
25from pyproj import CRS
26from shapely import LineString as ShpLineString
27from shapely import Point as ShpPoint
29from geodense.geojson import CrsFeatureCollection
30from geodense.models import DEFAULT_PRECISION_METERS, DenseConfig, GeodenseError
31from geodense.types import (
32 GeojsonCoordinates,
33 GeojsonGeomNoGeomCollection,
34 GeojsonObject,
35 Nested,
36 ReportLineString,
37 T,
38)
40TWO_DIMENSIONAL = 2
41THREE_DIMENSIONAL = 3
42DEFAULT_CRS_2D = "OGC:CRS84"
43DEFAULT_CRS_3D = "OGC:CRS84h"
44SUPPORTED_FILE_FORMATS = {
45 "GeoJSON": [".geojson", ".json"],
46}
48logger = logging.getLogger("geodense")
51class InfValCoordinateError(Exception):
52 pass
55def densify_geojson_object(densify_config: DenseConfig, geojson_obj: GeojsonObject) -> GeojsonObject:
56 """Mutates the input in place and returns it; copy the object first if you need to retain the original."""
57 validate_geom_type(geojson_obj, "densify")
58 _densify_geometry = partial(densify_geometry, densify_config)
59 return traverse_geojson_geometries(geojson_obj, _densify_geometry)
62def densify_geometry(densify_config: DenseConfig, geometry: GeojsonGeomNoGeomCollection) -> None:
63 _densify_line_segment = partial(densify_line_segment, densify_config)
64 result: GeojsonCoordinates = traverse_linestrings_in_coordinates(geometry.coordinates, _densify_line_segment)
65 geometry.coordinates = result
68def densify_line_segment(
69 densify_config: DenseConfig,
70 coords: GeojsonCoordinates,
71) -> None:
72 linestring = cast(LineStringCoords, coords)
73 added_nodes = 0
74 stop = len(linestring) - 1
75 for i, _ in enumerate(linestring[:stop]):
76 added_nodes += _add_vertices_to_line_segment(linestring, i + added_nodes, densify_config)
79def check_density_geojson_object(densify_config: DenseConfig, geojson_obj: GeojsonObject) -> CrsFeatureCollection:
80 validate_geom_type(geojson_obj, "density-check")
81 _check_density_geometry = partial(check_density_geometry, densify_config)
82 result: Nested[ReportLineString] | None = transform_geojson_geometries(geojson_obj, _check_density_geometry)
83 if result is None:
84 raise ValueError("_check_density_geometry returned None")
86 flat_result: list[ReportLineString] = (
87 list( # filter out None values, these occur when point geometries are part of input
88 filter(lambda x: x is not None, _flatten(result))
89 )
90 )
91 report_fc = _report_line_string_to_geojson(flat_result, ":".join(densify_config.src_crs.to_authority()))
92 return report_fc
95def check_density_geometry(
96 densify_config: DenseConfig,
97 geometry: GeojsonGeomNoGeomCollection,
98) -> Nested[ReportLineString] | None:
99 _check_density_linestring = partial(check_density_linestring, densify_config)
100 return transform_linestrings_in_coordinates(geometry.coordinates, _check_density_linestring)
103def check_density_linestring(
104 densify_config: DenseConfig,
105 linestring: LineStringCoords,
106) -> list[ReportLineString]:
107 result = []
109 for k in range(0, len(linestring) - 1):
110 a: Position = linestring[k]
111 b: Position = linestring[k + 1]
113 a_2d = cast(Position2D, a[0:2])
114 b_2d = cast(Position2D, b[0:2])
116 if densify_config.in_projection:
117 linesegment_dist = _cartesian_distance(a_2d, b_2d)
118 else:
119 if densify_config.is_projected: # only convert to basegeographic crs if src_proj is projected
120 transformer = densify_config.transformer
121 if transformer is None:
122 raise GeodenseError("transformer cannot be None when src_crs.is_projected=True")
123 a_t = transformer.transform(*a_2d)
124 b_t = transformer.transform(*b_2d)
125 else: # src_crs is geographic do not transform
126 a_t, b_t = (a_2d, b_2d)
127 g = densify_config.geod
129 _, _, geod_dist = g.inv(*a_t, *b_t, return_back_azimuth=True)
130 if math.isnan(geod_dist):
131 raise GeodenseError(
132 f"unable to calculate geodesic distance, output calculation geodesic distance: {geod_dist}, expected: floating-point number"
133 )
134 linesegment_dist = geod_dist
135 if linesegment_dist > (densify_config.max_segment_length + 0.001):
136 result.append((linesegment_dist, (a, b)))
137 return result
140def _validate_dependent_file_args(
141 input_file_path: str,
142 output_file_path: str | None = None,
143 overwrite: bool = False,
144) -> None:
145 if output_file_path is not None and (input_file_path == output_file_path and input_file_path != "-"):
146 raise GeodenseError(
147 f"input_file and output_file arguments must be different, input_file: {input_file_path}, output_file: {output_file_path}"
148 )
149 if output_file_path is not None and output_file_path != "-":
150 if os.path.exists(output_file_path) and not overwrite:
151 raise GeodenseError(f"output_file {output_file_path} already exists")
152 elif os.path.exists(output_file_path) and overwrite:
153 os.remove(output_file_path)
156def check_density_file( # noqa: PLR0913
157 input_file_path: str,
158 max_segment_length: float,
159 density_check_report_path: str | None = None,
160 src_crs: str | None = None,
161 in_projection: bool = False,
162 overwrite: bool = False,
163) -> tuple[bool, str, int]:
164 if density_check_report_path is None:
165 density_check_report_path = os.path.join(tempfile.mkdtemp(), "check-density-report.json")
167 _validate_dependent_file_args(input_file_path, density_check_report_path, overwrite)
169 with open(input_file_path) if input_file_path != "-" else sys.stdin as src:
170 geojson_obj = textio_to_geojson(src)
171 validate_geom_type(geojson_obj, "check-density")
172 has_3d_coords: Has3D = _has_3d_coordinates(geojson_obj)
173 geojson_src_crs = _get_crs_geojson(geojson_obj, input_file_path, src_crs, has_3d_coords)
174 config = DenseConfig(
175 CRS.from_authority(*geojson_src_crs.split(":")),
176 max_segment_length,
177 in_projection=in_projection,
178 )
179 report_fc = check_density_geojson_object(config, geojson_obj)
181 failed_segment_count = len(report_fc.features)
182 check_status = failed_segment_count == 0
184 if not check_status:
185 with open(density_check_report_path, "w") as f:
186 f.write(report_fc.model_dump_json(indent=4, exclude_none=True))
187 return (check_status, density_check_report_path, len(report_fc.features))
190def _report_line_string_to_geojson(
191 report: list[ReportLineString], src_crs_auth_code: str | None
192) -> CrsFeatureCollection:
193 features: list[Feature] = [
194 Feature(
195 type="Feature",
196 properties={"segment_length": x[0]},
197 geometry=LineString(type="LineString", coordinates=list(x[1])),
198 )
199 for x in report
200 ]
201 result = CrsFeatureCollection(features=features, type="FeatureCollection", name="density-check-report")
202 if src_crs_auth_code is not None:
203 result.set_crs_auth_code(src_crs_auth_code)
204 return result
207def densify_file( # noqa: PLR0913
208 input_file_path: str,
209 output_file_path: str,
210 overwrite: bool = False,
211 max_segment_length: float | None = None,
212 densify_in_projection: bool = False,
213 src_crs: str | None = None,
214) -> None:
215 """_summary_
217 Arguments:
218 input_file_path: assumes file exists otherwise raises FileNotFoundError
219 output_file_path: assumes directory of output_file_path exists
221 Keyword Arguments:
222 layer -- layer name, when no specified and multilayer file, first layer will be used (default: {None})
223 max_segment_length -- max segment length to use for densification (default: {None})
224 densify_in_projection -- user src projection for densification (default: {False})
225 src_crs -- override src crs of input file (default: {None})
227 Raises:
228 ValueError: application errors
229 pyproj.exceptions.CRSError: when crs cannot be found by pyproj
231 """
232 _validate_dependent_file_args(input_file_path, output_file_path, overwrite)
233 src: TextIO
234 with open(input_file_path) if input_file_path != "-" else sys.stdin as src:
235 geojson_obj = textio_to_geojson(src)
236 has_3d_coords: Has3D = _has_3d_coordinates(geojson_obj)
237 geojson_src_crs = _get_crs_geojson(geojson_obj, input_file_path, src_crs, has_3d_coords)
238 config = DenseConfig(
239 CRS.from_authority(*geojson_src_crs.split(":")),
240 max_segment_length,
241 densify_in_projection,
242 )
243 densify_geojson_object(config, geojson_obj)
244 if src_crs is not None and isinstance(geojson_obj, CrsFeatureCollection):
245 geojson_obj.set_crs_auth_code(src_crs)
246 with open(output_file_path, "w") if output_file_path != "-" else sys.stdout as out_f:
247 geojson_obj_model: BaseModel = cast(BaseModel, geojson_obj)
249 out_f.write(geojson_obj_model.model_dump_json(indent=1, exclude_none=True))
252def transform_linestrings_in_coordinates(
253 coordinates: GeojsonCoordinates,
254 callback: Callable[[GeojsonCoordinates], T],
255) -> Nested | T | None:
256 # when point geometry return None, since we only want to operate on linestring-like coordinates sequences
257 if isinstance(coordinates, tuple):
258 return None
259 elif not _is_linestring_geom(coordinates):
260 _self = partial(transform_linestrings_in_coordinates, callback=callback)
261 return list(
262 map(
263 _self,
264 coordinates,
265 )
266 )
267 else:
268 return callback(coordinates)
271def traverse_linestrings_in_coordinates(
272 coordinates: GeojsonCoordinates,
273 callback: Callable[[GeojsonCoordinates], None],
274) -> GeojsonCoordinates:
275 """Differs from transform_linestrings_in_coordinates in that it does not transform the type of coordinates, so coordinates in > coordinates out. transform_linestrings_in_coordinates expects a callback that transforms the linestring coordinates to generic type T."""
276 # maybe do perform mutations on copy
277 if isinstance(coordinates, tuple):
278 return coordinates
279 elif not _is_linestring_geom(coordinates):
280 _self = partial(traverse_linestrings_in_coordinates, callback=callback)
281 list(
282 map(
283 _self,
284 coordinates,
285 )
286 )
287 else:
288 callback(coordinates)
289 return coordinates
292def traverse_geojson_geometries(
293 geojson: Feature | CrsFeatureCollection | Geometry,
294 geometry_callback: Callable[[Geometry], None] | None = None,
295 node_callback: Callable | None = None,
296) -> Feature | CrsFeatureCollection | Geometry:
297 """Mutates the input in place and returns it; copy the object first if you need to retain the original."""
298 _self: Callable[
299 [Feature | CrsFeatureCollection | Geometry],
300 Feature | CrsFeatureCollection | Geometry,
301 ] = partial(
302 traverse_geojson_geometries,
303 geometry_callback=geometry_callback,
304 node_callback=node_callback,
305 )
307 if isinstance(geojson, Feature):
308 feature = cast(Feature, geojson)
309 geom = cast(GeojsonGeomNoGeomCollection, feature.geometry)
310 try:
311 feature.geometry = _self(geom)
312 except InfValCoordinateError as _:
313 feature.geometry = None
315 elif isinstance(geojson, CrsFeatureCollection):
316 feature_collection = cast(CrsFeatureCollection, geojson)
317 feature_collection.features = list(map(_self, feature_collection.features))
318 elif isinstance(geojson, GeometryCollection):
319 geometry_collection = cast(GeometryCollection, geojson)
320 __self = cast(Callable[[Geometry], Geometry], _self)
321 geometry_collection.geometries = list(map(__self, geometry_collection.geometries))
322 elif isinstance(
323 geojson,
324 Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon,
325 ):
326 if geometry_callback is not None:
327 geometry_callback(cast(GeojsonGeomNoGeomCollection, geojson))
329 if node_callback:
330 node_callback(geojson)
332 return geojson
335def transform_geojson_geometries(
336 geojson: (Feature | CrsFeatureCollection | GeojsonGeomNoGeomCollection | GeometryCollection),
337 geometry_callback: Callable[[GeojsonGeomNoGeomCollection], T],
338) -> Nested | T:
339 _self = partial(transform_geojson_geometries, geometry_callback=geometry_callback)
341 if isinstance(geojson, Feature):
342 feature = cast(Feature, geojson)
343 geom = cast(GeojsonGeomNoGeomCollection, feature.geometry)
344 return _self(geom)
346 elif isinstance(geojson, CrsFeatureCollection):
347 feature_collection: CrsFeatureCollection = cast(CrsFeatureCollection, geojson)
348 return list(map(_self, feature_collection.features))
349 elif isinstance(geojson, GeometryCollection):
350 geometry_collection = cast(GeometryCollection, geojson)
351 return list(map(_self, geometry_collection.geometries))
352 else:
353 # isinstance(
354 # geojson,
355 # Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon,
356 # ):
357 geom = cast(GeojsonGeomNoGeomCollection, geojson)
358 return geometry_callback(geom)
361def interpolate_geodesic(a: Position, b: Position, densify_config: DenseConfig) -> LineStringCoords:
362 """geodesic interpolate intermediate points between points a and b, with segment_length < max_segment_length. Only returns intermediate points."""
364 three_dimensional_points = len(a) == THREE_DIMENSIONAL and len(b) == THREE_DIMENSIONAL
365 a_2d = Position2D(longitude=a.longitude, latitude=a.latitude)
366 b_2d = Position2D(longitude=b.longitude, latitude=b.latitude)
368 transformer = densify_config.transformer
370 if densify_config.is_projected: # only convert to basegeographic crs if src_proj is projected
371 if transformer is None:
372 raise GeodenseError("transformer cannot be None when src_crs.is_projected=True")
373 # technically the following transform call is a converion and not a transformation, since crs->base-crs will be a conversion in most cases
374 a_t: tuple[float, float] = transformer.transform(*a_2d)
375 b_t: tuple[float, float] = transformer.transform(*b_2d)
376 else: # src_crs is geographic do not transform
377 a_t, b_t = (a_2d, b_2d)
379 g = densify_config.geod
381 az12, _, geod_dist = g.inv(*a_t, *b_t, return_back_azimuth=True)
382 if math.isnan(geod_dist):
383 raise GeodenseError(
384 f"unable to calculate geodesic distance, output calculation geodesic distance: {geod_dist}, expected: floating-point number"
385 )
387 if geod_dist <= densify_config.max_segment_length:
388 return []
389 else:
390 (
391 nr_points,
392 new_max_segment_length,
393 ) = _get_intermediate_nr_points_and_segment_length(geod_dist, densify_config.max_segment_length)
394 r = g.fwd_intermediate(
395 *a_t,
396 az12,
397 npts=nr_points,
398 del_s=new_max_segment_length,
399 return_back_azimuth=True,
400 )
402 def optional_back_transform(lon: float, lat: float) -> Position2D:
403 """technically should be named optional_back_convert, since crs->base crs is (mostly) a conversion and not a transformation"""
404 if densify_config.is_projected:
405 if densify_config.back_transformer is None:
406 raise GeodenseError("back_transformer cannot be None when src_crs.is_projected=True")
407 _result = densify_config.back_transformer.transform(lon, lat)
408 return Position2D(longitude=_result[0], latitude=_result[1])
409 return Position2D(longitude=lon, latitude=lat)
411 if three_dimensional_points:
412 # interpolate height for three_dimensional_points
413 a_3d = cast(Position3D, a)
414 b_3d = cast(Position3D, b)
415 height_a = a_3d[2:][0]
416 height_b = b_3d[2:][0]
417 delta_height_b_a = height_b - height_a
418 delta_height_per_point = delta_height_b_a * (new_max_segment_length / geod_dist)
419 return [
420 Position3D(
421 *optional_back_transform(lon, lat),
422 altitude=round(
423 (height_a + ((i + 1) * delta_height_per_point)),
424 DEFAULT_PRECISION_METERS,
425 ),
426 )
427 for i, (lon, lat) in enumerate(zip(r.lons, r.lats, strict=True))
428 ]
429 else:
430 return [optional_back_transform(lon, lat) for lon, lat in zip(r.lons, r.lats, strict=True)]
433def _cartesian_distance(a: Position, b: Position) -> float:
434 return math.sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) # pythagoras
437def interpolate_src_proj(a: Position, b: Position, densify_config: DenseConfig) -> LineStringCoords:
438 """Interpolate intermediate points between points a and b, with segment_length < max_segment_length. Only returns intermediate points."""
440 all_three_dimensional = len(a) == THREE_DIMENSIONAL and len(b) == THREE_DIMENSIONAL
441 # when mixed 2D/3D reduce to 2D, shapely cannot do interpolation on points with mixed dimensionality
442 if not all_three_dimensional:
443 a = Position2D(longitude=a.longitude, latitude=a.latitude)
444 b = Position2D(longitude=b.longitude, latitude=b.latitude)
446 dist = _cartesian_distance(a, b)
447 if dist <= densify_config.max_segment_length:
448 return []
449 else:
450 new_points: list[Position] = []
452 (
453 nr_points,
454 new_max_segment_length,
455 ) = _get_intermediate_nr_points_and_segment_length(dist, densify_config.max_segment_length)
457 for i in range(0, nr_points):
458 p_point: ShpPoint = ShpLineString([a, b]).interpolate(new_max_segment_length * (i + 1))
459 p_2d = Position2D(longitude=p_point.coords[0][0], latitude=p_point.coords[0][1])
460 if len(p_point.coords[0]) == THREE_DIMENSIONAL:
461 p: Position = Position3D(*p_2d, altitude=p_point.coords[0][2]) # type: ignore
462 else:
463 p = p_2d
464 new_points.append(p)
465 return [
466 *new_points,
467 ]
470def textio_to_geojson(src: TextIO) -> GeojsonObject:
471 src_json = json.loads(src.read())
472 type_map = {
473 "Feature": Feature,
474 "GeometryCollection": GeometryCollection,
475 "FeatureCollection": CrsFeatureCollection,
476 "Point": Point,
477 "MultiPoint": MultiPoint,
478 "Polygon": Polygon,
479 "MultiPolygon": MultiPolygon,
480 "LineString": LineString,
481 "MultiLineString": MultiLineString,
482 }
483 try:
484 geojson_type = src_json["type"]
485 constructor = type_map[geojson_type]
486 except KeyError as e:
487 message = f'received invalid GeoJSON file, loc: `.type`, value: `{src_json["type"]}`, expected one of: {", ".join(list(type_map.keys()))}'
488 raise GeodenseError(message) from e
489 geojson_obj: GeojsonObject = constructor(**src_json)
490 return geojson_obj
493class Has3D(Enum):
494 all: Literal["all"] = "all"
495 some: Literal["some"] = "some"
496 none: Literal["none"] = "none"
499def _get_crs_geojson(
500 geojson_object: GeojsonObject,
501 input_file_path: str,
502 src_crs: str | None,
503 has_3d_coords: Has3D,
504) -> str:
505 result_crs: str | None = None
507 is_fc = False
508 if isinstance(geojson_object, CrsFeatureCollection):
509 result_crs = geojson_object.get_crs_auth_code()
510 is_fc = True
512 # case to set default CRS if src_crs not specified and not available in GeoJSON
513 if (
514 result_crs is None and src_crs is None
515 ): # set default crs if not in geojson object and not overridden with src_crs
516 default_crs = DEFAULT_CRS_2D
517 if has_3d_coords in [Has3D.some, Has3D.all]:
518 default_crs = DEFAULT_CRS_3D
519 message = f"unable to determine source CRS for file {input_file_path}, assumed CRS is {default_crs}"
520 logger.warning(message)
521 result_crs = default_crs
522 if is_fc:
523 fc: CrsFeatureCollection = cast(CrsFeatureCollection, geojson_object)
524 fc.set_crs_auth_code(result_crs)
526 # is src_crs is set use src_crs
527 elif src_crs is not None:
528 src_crs_crs: CRS = CRS.from_authority(*src_crs.split(":"))
529 if has_3d_coords == Has3D.all and not src_crs_crs.is_vertical:
530 logger.warning("src_crs is 2D while input data contains geometries with 3D coordinates")
531 result_crs = src_crs if src_crs is not None else result_crs # override json_crs with src_crs if defined
533 elif result_crs is None:
534 raise GeodenseError("could not determine CRS from GeoJSON object")
536 return result_crs
539def _flatten(container: Nested) -> Iterable:
540 if isinstance(container, tuple | str):
541 raise ValueError("var container should not be of type tuple or str")
543 for item in container:
544 if isinstance(item, Sequence) and not isinstance(item, tuple) and not isinstance(item, str):
545 yield from _flatten(item)
546 else:
547 yield item
550def _is_linestring_geom(geometry_coordinates: GeojsonCoordinates) -> bool:
551 """Check if coordinates are of linestring geometry type.
553 - Fiona linestring coordinates are of type: list[tuple[float,float,...]])
554 - GeoJSON linestring coordinates are of type: list[list[float]]
556 Args:
557 geometry_coordinates (list): Fiona or GeoJSON coordinates sequence
559 Returns:
560 bool: if geometry_coordinates is linestring return True else False
561 """
563 return (
564 len(geometry_coordinates) > 0
565 and isinstance(geometry_coordinates[0], Sequence)
566 and all(isinstance(x, float | int) for x in geometry_coordinates[0])
567 ) # also test for int just in case...
570def _transform_positions_in_coordinates(
571 coordinates: GeojsonCoordinates,
572 callback: Callable[[GeojsonCoordinates], T],
573) -> Nested | T:
574 if not isinstance(coordinates, tuple):
575 return list(map(lambda x: _transform_positions_in_coordinates(x, callback), coordinates))
576 return callback(coordinates)
579def _get_intermediate_nr_points_and_segment_length(dist: float, max_segment_length: float) -> tuple[int, float]:
580 if dist <= max_segment_length:
581 raise GeodenseError(f"max_segment_length ({max_segment_length}) cannot be bigger or equal than dist ({dist})")
582 remainder = dist % max_segment_length
583 nr_segments = int(dist // max_segment_length)
584 if remainder > 0:
585 nr_segments += 1
586 new_max_segment_length = dist / nr_segments # space segments evenly over delta(a,b)
587 nr_points = nr_segments - 1 # convert nr of segments to nr of intermediate points, should be at least 1
588 return nr_points, new_max_segment_length
591def _add_vertices_to_line_segment(linestring: LineStringCoords, coord_index: int, densify_config: DenseConfig) -> int:
592 """Adds vertices to linestring in place, and returns number of vertices added to linestring.
594 Args:
595 ft_linesegment (_type_): line segment to add vertices
596 coord_index (int): coordinate index of line segment to add vertices for
597 transformer (Transformer): pyproj transformer
598 max_segment_length (float): max segment length, if exceeded vertices will be added
599 densify_in_projection (bool): whether to use source projection to densify (not use great-circle distance)
601 Returns:
602 int: number of added vertices
603 """
605 a = linestring[coord_index]
606 b = linestring[coord_index + 1]
608 prec = densify_config.coord_precision
610 if not densify_config.in_projection:
611 linestring_coords = interpolate_geodesic(a, b, densify_config)
612 else:
613 linestring_coords = interpolate_src_proj(a, b, densify_config)
615 p = list(map(lambda x: _round_coordinates(x, prec), linestring_coords))
617 linestring[coord_index] = _round_coordinates(linestring[coord_index], prec)
618 linestring[coord_index + 1] = _round_coordinates(linestring[coord_index + 1], prec)
619 linestring[coord_index + 1 : coord_index + 1] = p
620 return len(p)
623def _round_coordinates(position: Position, precision: int) -> Position:
624 if len(position) == THREE_DIMENSIONAL:
625 p3 = cast(Position3D, position)
626 return Position3D(round(p3[0], precision), round(p3[1], precision), round(p3[2], DEFAULT_PRECISION_METERS))
627 return Position2D(round(position[0], precision), round(position[1], precision))
630def _get_geometry_type(
631 geometry: GeojsonGeomNoGeomCollection,
632) -> str:
633 return cast(str, geometry.type)
636def _geom_has_3d_coords(
637 geometry: GeojsonGeomNoGeomCollection,
638) -> Nested[bool] | bool:
639 def _position_is_3d(position: GeojsonCoordinates) -> bool:
640 return len(position) == THREE_DIMENSIONAL
642 return _transform_positions_in_coordinates(geometry.coordinates, _position_is_3d)
645def _has_3d_coordinates(geojson_obj: GeojsonObject, silent: bool | None = False) -> Has3D:
646 has_3d_coords: Nested[bool] | bool = transform_geojson_geometries(geojson_obj, _geom_has_3d_coords)
648 # in case only value returned from transform_geojson_geometries
649 if isinstance(has_3d_coords, bool): # noqa: SIM108
650 has_3d_coords_flat = [has_3d_coords]
651 else:
652 has_3d_coords_flat = list(_flatten(has_3d_coords))
654 if not all(has_3d_coords_flat) and any(has_3d_coords_flat): # some 3d
655 if not silent:
656 warning_message = "geometries with mixed 2D and 3D vertices found"
657 logger.warning(warning_message)
658 return Has3D.some
659 elif all(not x for x in has_3d_coords_flat): # none 3d
660 return Has3D.none
661 return Has3D.all
664def validate_geom_type(geojson_obj: GeojsonObject, command: str = "") -> None:
665 geom_types: Nested[str] | str = transform_geojson_geometries(geojson_obj, _get_geometry_type)
666 geom_types = [geom_types] if isinstance(geom_types, str) else geom_types
667 geom_types_flat = list(_flatten(geom_types))
668 if all(g_t in ("Point", "MultiPoint") for g_t in geom_types_flat):
669 # situation: all geoms point -> error
670 if command:
671 error_message = f"cannot run {command} on GeoJSON that only contains (Multi)Point geometries"
672 else:
673 error_message = "GeoJSON contains only (Multi)Point geometries"
674 raise GeodenseError(error_message)
675 elif any(gt in ["Point", "MultiPoint"] for gt in geom_types_flat):
676 # sitation: some geoms point -> warning
677 warning_message = "GeoJSON contains (Multi)Point geometries"
678 if command:
679 warning_message = f"{warning_message}, cannot run {command} on (Multi)Point geometries"
681 logger.warning(warning_message)
682 else:
683 # situation: no geoms point -> ok
684 pass