Deltares / xugrid

Xarray and unstructured grids
https://deltares.github.io/xugrid/
MIT License
61 stars 8 forks source link

Regridder fails when no dx/dy is available in a structured grid #275

Closed Huite closed 1 month ago

Huite commented 1 month ago

The snippet below fails because a dx and dy coordinate is generated as a numpy array internally. Then it tries to assign it via assign_coords to the regridded result, but is missing the dx dim. It should be marked as dependent on x: coord = ("x", dx)

import xugrid as xu
import numpy as np
import xarray as xr
# %%

uda = xu.data.elevation_nl()
xmin, ymin, xmax, ymax = uda.grid.bounds
# %%
x = np.arange(xmin, xmax, 1000.0)
y = np.arange(xmin, xmax, 1000.0)
da = xr.DataArray(
    data=np.zeros((y.size, x.size)),
    coords={"y": y, "x": x},
    dims=["y", "x"]
)
# %%

regridder = xu.OverlapRegridder(source=uda, target=da, method="mean")
# %%
result = regridder.regrid(uda)
Huite commented 1 month ago

Fix is more or less this in StructuredGrid1d:

    @property
    def coords(self) -> dict:
        coords = {self.name: self.index}
        if isinstance(self.dvalue, np.ndarray):
            coords[self.dname] = (self.name, self.dvalue)
        else:
            coords[self.dname] = self.dvalue
        return coords
Huite commented 1 month ago

In fact, a non-scalar for dvalue always fails regardless of origin:

x = np.arange(xmin, xmax, 1000.0)
y = np.arange(xmin, xmax, 1000.0)
da = xr.DataArray(
    data=np.zeros((y.size, x.size)),
    coords={"y": y, "x": x, "dx": ("x", np.full(x.size, 1000.0)), "dy": ("y", np.full(y.size, 1000.0))},
    dims=["y", "x"]
)