|
| 1 | +import copy |
| 2 | +import logging |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | +import geopandas as gpd |
| 6 | +import numpy as np |
| 7 | +import shapely |
| 8 | +import xarray as xr |
| 9 | +import xvec |
| 10 | + |
| 11 | +from openeo_processes_dask.process_implementations.data_model import VectorCube |
| 12 | +from openeo_processes_dask.process_implementations.exceptions import ( |
| 13 | + DimensionNotAvailable, |
| 14 | + UnitMismatch, |
| 15 | +) |
| 16 | + |
| 17 | +__all__ = ["load_geojson", "vector_buffer", "vector_reproject"] |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +def load_geojson(data: dict, properties: Optional[list[str]] = []) -> VectorCube: |
| 23 | + DEFAULT_CRS = "epsg:4326" |
| 24 | + |
| 25 | + if isinstance(data, dict): |
| 26 | + # Get crs from geometries |
| 27 | + if "features" in data: |
| 28 | + for feature in data["features"]: |
| 29 | + if "properties" not in feature: |
| 30 | + feature["properties"] = {} |
| 31 | + elif feature["properties"] is None: |
| 32 | + feature["properties"] = {} |
| 33 | + if isinstance(data.get("crs", {}), dict): |
| 34 | + DEFAULT_CRS = ( |
| 35 | + data.get("crs", {}).get("properties", {}).get("name", DEFAULT_CRS) |
| 36 | + ) |
| 37 | + else: |
| 38 | + DEFAULT_CRS = int(data.get("crs", {})) |
| 39 | + logger.info(f"CRS in geometries: {DEFAULT_CRS}.") |
| 40 | + |
| 41 | + if "type" in data and data["type"] == "FeatureCollection": |
| 42 | + gdf = gpd.GeoDataFrame.from_features(data, crs=DEFAULT_CRS) |
| 43 | + elif "type" in data and data["type"] in ["Polygon"]: |
| 44 | + polygon = shapely.geometry.Polygon(data["coordinates"][0]) |
| 45 | + gdf = gpd.GeoDataFrame(geometry=[polygon]) |
| 46 | + gdf.crs = DEFAULT_CRS |
| 47 | + |
| 48 | + dimensions = ["geometry"] |
| 49 | + coordinates = {"geometry": gdf.geometry} |
| 50 | + |
| 51 | + if len(properties) == 0: |
| 52 | + if "features" in data: |
| 53 | + feature = data["features"][0] |
| 54 | + if "properties" in feature: |
| 55 | + property = feature["properties"] |
| 56 | + if len(property) == 1: |
| 57 | + key = list(property.keys())[0] |
| 58 | + value = list(property.values()) |
| 59 | + dimensions.append("properties") |
| 60 | + if isinstance(value, list) and len(value) > 1: |
| 61 | + values = np.zeros((len(gdf.geometry), len(value))) |
| 62 | + coordinates["properties"] = np.arange(len(value)) |
| 63 | + elif isinstance(value, list) and len(value) == 1: |
| 64 | + values = np.zeros((len(gdf.geometry), 1)) |
| 65 | + coordinates["properties"] = np.array([key]) |
| 66 | + else: |
| 67 | + values = np.zeros((len(gdf.geometry), 1)) |
| 68 | + coordinates["properties"] = np.array([key]) |
| 69 | + |
| 70 | + for i, feature in enumerate(data["features"]): |
| 71 | + value = feature.get("properties", {}).get(key, None) |
| 72 | + values[i, :] = value |
| 73 | + elif len(property) > 1: |
| 74 | + dimensions.append("properties") |
| 75 | + keys = list(property.keys()) |
| 76 | + coordinates["properties"] = keys |
| 77 | + values = np.zeros((len(gdf.geometry), len(keys))) |
| 78 | + for i, feature in enumerate(data["features"]): |
| 79 | + for j, key in enumerate(keys): |
| 80 | + value = feature.get("properties", {}).get(key, None) |
| 81 | + values[i, j] = value |
| 82 | + |
| 83 | + elif len(properties) == 1: |
| 84 | + property = properties[0] |
| 85 | + if "features" in data: |
| 86 | + feature = data["features"][0] |
| 87 | + if "properties" in feature: |
| 88 | + if property in feature["properties"]: |
| 89 | + value = feature["properties"][property] |
| 90 | + dimensions.append("properties") |
| 91 | + if isinstance(value, list) and len(value) > 0: |
| 92 | + values = np.zeros((len(gdf.geometry), len(value))) |
| 93 | + coordinates["properties"] = np.arange(len(value)) |
| 94 | + elif isinstance(value, list) and len(value) == 1: |
| 95 | + values = np.zeros((len(gdf.geometry), 1)) |
| 96 | + coordinates["properties"] = np.array([property]) |
| 97 | + else: |
| 98 | + values = np.zeros((len(gdf.geometry), 1)) |
| 99 | + coordinates["properties"] = np.array([property]) |
| 100 | + |
| 101 | + for i, feature in enumerate(data["features"]): |
| 102 | + value = feature.get("properties", {}).get(property, None) |
| 103 | + values[i, :] = value |
| 104 | + else: |
| 105 | + if "features" in data: |
| 106 | + dimensions.append("properties") |
| 107 | + coordinates["properties"] = properties |
| 108 | + values = np.zeros((len(gdf.geometry), len(properties))) |
| 109 | + for i, feature in enumerate(data["features"]): |
| 110 | + for j, key in enumerate(properties): |
| 111 | + value = feature.get("properties", {}).get(key, None) |
| 112 | + values[i, j] = value |
| 113 | + |
| 114 | + output_vector_cube = xr.DataArray(values, coords=coordinates, dims=dimensions) |
| 115 | + output_vector_cube = output_vector_cube.xvec.set_geom_indexes( |
| 116 | + "geometry", crs=gdf.crs |
| 117 | + ) |
| 118 | + return output_vector_cube |
| 119 | + |
| 120 | + |
| 121 | +def vector_buffer(geometries: VectorCube, distance: float) -> VectorCube: |
| 122 | + from shapely import buffer |
| 123 | + |
| 124 | + geometries_copy = copy.deepcopy(geometries) |
| 125 | + |
| 126 | + if isinstance(geometries_copy, xr.DataArray) and "geometry" in geometries_copy.dims: |
| 127 | + if hasattr(geometries_copy, "xvec") and hasattr( |
| 128 | + geometries_copy["geometry"], "crs" |
| 129 | + ): |
| 130 | + if geometries_copy["geometry"].crs.is_geographic: |
| 131 | + raise UnitMismatch( |
| 132 | + "The unit of the spatial reference system is not meters, but the given distance is in meters." |
| 133 | + ) |
| 134 | + |
| 135 | + geometry = geometries_copy["geometry"].values.tolist() |
| 136 | + |
| 137 | + new_geometry = [buffer(geom, distance) for geom in geometry] |
| 138 | + |
| 139 | + geometries_copy["geometry"] = new_geometry |
| 140 | + |
| 141 | + return geometries_copy |
| 142 | + |
| 143 | + else: |
| 144 | + raise DimensionNotAvailable(f"No geometry dimension found in {geometries}") |
| 145 | + |
| 146 | + |
| 147 | +def vector_reproject( |
| 148 | + data: VectorCube, projection, dimension: Optional[str] = None |
| 149 | +) -> VectorCube: |
| 150 | + DEFAULT_CRS = "epsg:4326" |
| 151 | + |
| 152 | + data_copy = copy.deepcopy(data) |
| 153 | + |
| 154 | + if not dimension: |
| 155 | + dimension = "geometry" |
| 156 | + |
| 157 | + if isinstance(data, xr.DataArray) and dimension in data.dims: |
| 158 | + if hasattr(data, "xvec") and hasattr(data[dimension], "crs"): |
| 159 | + data_copy = data_copy.xvec.to_crs({dimension: projection}) |
| 160 | + |
| 161 | + return data_copy |
| 162 | + else: |
| 163 | + data_copy = data_copy.xvec.set_geom_indexes(dimension, crs=DEFAULT_CRS) |
| 164 | + data_copy = data_copy.xvec.to_crs({dimension: projection}) |
| 165 | + |
| 166 | + return data_copy |
| 167 | + else: |
| 168 | + raise DimensionNotAvailable(f"No geometry dimension found in {data}") |
0 commit comments