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

Implement set_value_as_xarray #185

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all 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
34 changes: 34 additions & 0 deletions ewatercycle/models/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,40 @@ def get_value_as_xarray(self, name: str) -> xr.DataArray:

"""

def set_value_as_xarray(self, name: str, value: xr.DataArray) -> None:
"""Specify a new value for a model variable by passing in an xarray.DataArray.

The DataArray should have the same grid as the model.

Args:
name: Name of variable
value: xarray.DataArray with values for the specified variable.

"""
model_grid = self.bmi.get_var_grid(name)
model_shape = self.bmi.get_grid_shape(model_grid)
if model_shape == value.shape:
self.bmi.set_value(name, value.data.flatten())
elif model_shape == value.T.shape:
self.bmi.set_value(name, value.T.data.flatten())
else:
raise ValueError(
f"Shape mismatch. Model has shape {model_shape}, but"
f"input has shape {value.shape}."
)
# TODO: what if data is NaN? Model-specific back-conversion? Don't convert to NaN in getters?
# TODO: wflow not settable (rank mismatch, should be 2???!)
# TODO: pcrglob discharge not settable (but works for temperature)
# TODO: add tests like so:
"""
name = 'temperature'
da = model.get_value_as_xarray(name)
orig = model.get_value(name)
model.set_value_as_xarray(name, da)
new = model.get_value(name)
assert all(orig == new)
"""

@property
@abstractmethod
def parameters(self) -> Iterable[Tuple[str, Any]]:
Expand Down