|
| 1 | +import numpy as np |
| 2 | +import xarray |
| 3 | + |
| 4 | +from openeo.metadata import CollectionMetadata |
| 5 | +from openeo.udf import XarrayDataCube |
| 6 | +from openeo.udf.debug import inspect |
| 7 | + |
| 8 | + |
| 9 | +def apply_metadata(input_metadata: CollectionMetadata, context: dict) -> CollectionMetadata: |
| 10 | + |
| 11 | + xstep = input_metadata.get("x", "step") |
| 12 | + ystep = input_metadata.get("y", "step") |
| 13 | + new_metadata = { |
| 14 | + "x": {"type": "spatial", "axis": "x", "step": xstep / 2.0, "reference_system": 4326}, |
| 15 | + "y": {"type": "spatial", "axis": "y", "step": ystep / 2.0, "reference_system": 4326}, |
| 16 | + "t": {"type": "temporal"}, |
| 17 | + } |
| 18 | + return CollectionMetadata(new_metadata) |
| 19 | + |
| 20 | + |
| 21 | +def fancy_upsample_function(array: np.array, factor: int = 2) -> np.array: |
| 22 | + assert array.ndim == 3 |
| 23 | + return array.repeat(factor, axis=-1).repeat(factor, axis=-2) |
| 24 | + |
| 25 | + |
| 26 | +def apply_datacube(cube: XarrayDataCube, context: dict) -> XarrayDataCube: |
| 27 | + array: xarray.DataArray = cube.get_array() |
| 28 | + |
| 29 | + cubearray: xarray.DataArray = cube.get_array().copy() + 60 |
| 30 | + |
| 31 | + # We make prediction and transform numpy array back to datacube |
| 32 | + |
| 33 | + # Pixel size of the original image |
| 34 | + init_pixel_size_x = cubearray.coords["x"][-1] - cubearray.coords["x"][-2] |
| 35 | + init_pixel_size_y = cubearray.coords["y"][-1] - cubearray.coords["y"][-2] |
| 36 | + |
| 37 | + if cubearray.data.ndim == 4 and cubearray.data.shape[0] == 1: |
| 38 | + cubearray = cubearray[0] |
| 39 | + predicted_array = fancy_upsample_function(cubearray.data, 2) |
| 40 | + inspect(predicted_array, "test message") |
| 41 | + coord_x = np.linspace( |
| 42 | + start=cube.get_array().coords["x"].min(), |
| 43 | + stop=cube.get_array().coords["x"].max() + init_pixel_size_x, |
| 44 | + num=predicted_array.shape[-2], |
| 45 | + endpoint=False, |
| 46 | + ) |
| 47 | + coord_y = np.linspace( |
| 48 | + start=cube.get_array().coords["y"].min(), |
| 49 | + stop=cube.get_array().coords["y"].max() + init_pixel_size_y, |
| 50 | + num=predicted_array.shape[-1], |
| 51 | + endpoint=False, |
| 52 | + ) |
| 53 | + predicted_cube = xarray.DataArray(predicted_array, dims=["bands", "x", "y"], coords=dict(x=coord_x, y=coord_y)) |
| 54 | + |
| 55 | + return XarrayDataCube(predicted_cube) |
0 commit comments