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 model.to_xugrid() #1314

Merged
merged 6 commits into from
Mar 26, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions python/ribasim/ribasim/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@
model_validator,
)

try:
import xugrid
except ImportError:
xugrid = None

Check warning on line 23 in python/ribasim/ribasim/model.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/model.py#L22-L23

Added lines #L22 - L23 were not covered by tests

import ribasim
from ribasim.config import (
Allocation,
Expand Down Expand Up @@ -342,3 +347,58 @@
ax.legend(handles, labels, loc="lower left", bbox_to_anchor=(1, 0.5))

return ax

def to_xugrid(self) -> xugrid.UgridDataset:
"""Convert the network to a xugrid.UgridDataset."""
node_df = self.node_table().df
visr marked this conversation as resolved.
Show resolved Hide resolved

# This will need to be adopted for locally unique node IDs,
# otherwise the `node_lookup` with `argsort` is not correct.
assert node_df.node_id.is_unique
visr marked this conversation as resolved.
Show resolved Hide resolved
node_df.sort_values("node_id", inplace=True)

edge_df = self.edge.df.copy()
# We assume only the flow network is of interest.
edge_df = edge_df[edge_df.edge_type == "flow"]

node_id = node_df.node_id.to_numpy(dtype="int32")
from_node_id = edge_df.from_node_id.to_numpy(dtype="int32")
to_node_id = edge_df.to_node_id.to_numpy(dtype="int32")

# from node_id to the node_dim index
node_lookup = pd.Series(
index=node_id,
data=node_id.argsort().astype("int32"),
name="node_index",
)

if node_df.crs is None:
# can be removed when CRS is required, #1254
visr marked this conversation as resolved.
Show resolved Hide resolved
projected = False
else:
projected = node_df.crs.is_projected

Check warning on line 379 in python/ribasim/ribasim/model.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/model.py#L379

Added line #L379 was not covered by tests

grid = xugrid.Ugrid1d(
node_x=node_df.geometry.x,
node_y=node_df.geometry.y,
fill_value=-1,
edge_node_connectivity=np.column_stack(
(
node_lookup[from_node_id],
node_lookup[to_node_id],
)
),
name="ribasim",
projected=projected,
crs=node_df.crs,
)

edge_dim = grid.edge_dimension
node_dim = grid.node_dimension

uds = xugrid.UgridDataset(None, grid)
uds = uds.assign_coords(node_id=(node_dim, node_id))
uds = uds.assign_coords(from_node_id=(edge_dim, from_node_id))
uds = uds.assign_coords(to_node_id=(edge_dim, to_node_id))

return uds
13 changes: 13 additions & 0 deletions python/ribasim/tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import numpy as np
import pandas as pd
import pytest
import xugrid
from pydantic import ValidationError
from ribasim.config import Solver
from ribasim.geometry.edge import NodeData
Expand Down Expand Up @@ -216,3 +217,15 @@ def test_indexing(basic):
match=re.escape("Cannot index into Basin / time: it contains no data."),
):
model.basin.time[1]


def test_xugrid(basic, tmp_path):
uds = basic.to_xugrid()
assert isinstance(uds, xugrid.UgridDataset)
assert uds.grid.edge_dimension == "ribasim_nEdges"
assert uds.grid.node_dimension == "ribasim_nNodes"
assert uds.grid.crs is None
assert uds.node_id.dtype == np.int32
uds.ugrid.to_netcdf(tmp_path / "ribasim.nc")
uds = xugrid.open_dataset(tmp_path / "ribasim.nc")
assert uds.attrs["Conventions"] == "CF-1.9 UGRID-1.0"
Loading