Skip to content

Commit

Permalink
Accept array-like input vars with no dimension labels (#126)
Browse files Browse the repository at this point in the history
* infer dimension labels + clean-up

* add test

* update release notes

* black
  • Loading branch information
benbovy committed Apr 10, 2020
1 parent b603d58 commit efad842
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
4 changes: 4 additions & 0 deletions doc/whats_new.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ Enhancements
~~~~~~~~~~~~

- Added :attr:`xsimlab.Model.cache` public property (:issue:`125`).
- Parameter ``input_vars`` of :func:`~xsimlab.create_setup` and
:func:`xarray.Dataset.xsimlab.update_vars` now accepts array-like values
with no explicit dimension label(s), in this case those labels are inferred
from model variables' metadata (:issue:`126`).

Bug fixes
~~~~~~~~~
Expand Down
7 changes: 7 additions & 0 deletions xsimlab/tests/test_xr_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,12 +196,19 @@ def test_set_input_vars(self, model, in_dataset):
xr.testing.assert_equal(ds[vname], in_dataset[vname])
assert ds[vname].attrs == in_dataset[vname].attrs

# test errors
in_vars[("not_an", "input_var")] = None

with pytest.raises(KeyError) as excinfo:
ds.xsimlab._set_input_vars(model, in_vars)
assert "not valid key(s)" in str(excinfo.value)

# test implicit dimension label
in_vars = {("add", "offset"): [1, 2, 3, 4, 5]}
ds.xsimlab._set_input_vars(model, in_vars)

assert ds["add__offset"].dims == ("x",)

def test_update_clocks(self, model):
ds = xr.Dataset()
with pytest.raises(ValueError) as excinfo:
Expand Down
27 changes: 19 additions & 8 deletions xsimlab/xr_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,16 +296,24 @@ def _set_input_vars(self, model, input_vars):
+ f" is/are not valid key(s) for input variables in model {model}",
)

for (p_name, var_name), data in input_vars.items():
p_obj = model[p_name]
var = variables_dict(type(p_obj))[var_name]
for var_key, data in input_vars.items():
var_metadata = model.cache[var_key]["metadata"]
xr_var_name = model.cache[var_key]["name"]

xr_var_name = p_name + "__" + var_name
xr_var = as_variable(data)
try:
xr_var = as_variable(data)
except TypeError:
# try retrieve dimension labels from model variable's
# dimension labels that match the number of dimensions
ndims = len(np.shape(data))
dim_labels = {len(d): d for d in var_metadata["dims"]}
dims = dim_labels[ndims]

xr_var = as_variable((dims, data))

if var.metadata["description"]:
xr_var.attrs["description"] = var.metadata["description"]
xr_var.attrs.update(var.metadata["attrs"])
if var_metadata["description"]:
xr_var.attrs["description"] = var_metadata["description"]
xr_var.attrs.update(var_metadata["attrs"])

# maybe delete first to avoid merge conflicts
# (we just want to replace here)
Expand Down Expand Up @@ -851,6 +859,9 @@ def create_setup(
Values are anything that can be easily converted to
:class:`xarray.Variable` objects, e.g., single values, array-like,
``(dims, data, attrs)`` tuples or xarray objects.
For array-like values with no dimension labels, xarray-simlab will look
in ``model`` variables metadata for labels matching the number
of dimensions of those arrays.
output_vars : dict, optional
Dictionary with model variable names to save as simulation output
(time-dependent or time-independent). Entries of the dictionary look
Expand Down

0 comments on commit efad842

Please sign in to comment.