Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a method to compute overlaps between grid cells and polygons #234

Open
Huite opened this issue Apr 23, 2024 · 0 comments
Open

Add a method to compute overlaps between grid cells and polygons #234

Huite opened this issue Apr 23, 2024 · 0 comments

Comments

@Huite
Copy link
Collaborator

Huite commented Apr 23, 2024

We can triangulate the polygons using earcut, build a grid, and use an OverlapRegridder to get statistics:

This is the basic idea:

vertices, index = shapely.get_coordinates(gdf.geometry.to_numpy(), return_index=True)

split_at = np.flatnonzero(np.diff(index)) + 1
polygon_verts = np.split(vertices, split_at)


result = []
increment = 0
for i, ring in enumerate(polygon_verts):
    print(i)
    connectivity = earcut.triangulate_float64(ring, [len(ring)])
    result.append(connectivity + increment)    
    increment += len(ring)
out = np.concatenate(result).reshape((-1, 3))
grid = xu.Ugrid2d(*vertices.T, -1, out)

xmin, ymin, xmax, ymax = grid.bounds
lhm_grid = imod.util.empty_2d(xmin=xmin, xmax=xmax, dx=250.0, ymin=ymin, ymax=ymax, dy=-250.0)
regridder = xu.OverlapRegridder(source=grid, target=lhm_grid)

# %%

ds = regridder.to_dataset()
i = ds["__regrid_indptr"]
j = ds["__regrid_indices"]
v = ds["__regrid_data"].to_numpy()

from scipy import sparse

matrix = sparse.csr_matrix((v, j, i), shape=(ds["__regrid_n"].item(), ds["__regrid_m"].item()))
total_area = np.asarray(matrix.sum(axis=1)).ravel()
out = lhm_grid.copy(data=total_area.reshape(lhm_grid.shape)[::-1, :])

It appears quite performant; I did run into two easily fixable issues:
#233
Deltares/numba_celltree#13

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant