From 7bdf43d54b94d039f5beaddd621c9f3f9085c0b3 Mon Sep 17 00:00:00 2001 From: Lukas Kluft Date: Mon, 3 Nov 2025 14:18:41 +0100 Subject: [PATCH 1/2] Fix writing of uninitialised data arrays Fixes #230 --- konrad/component.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/konrad/component.py b/konrad/component.py index 5bce6e7..ee2190e 100644 --- a/konrad/component.py +++ b/konrad/component.py @@ -152,7 +152,16 @@ def to_dataset(self): self.coords["time"] = [0] return xr.Dataset( coords=self.coords, - data_vars=self.data_vars, + # Convert `None` to ndarrays filled with np.nan + data_vars={ + k: ( + dim, + np.full([len(self.coords[d]) for d in dim], fill_value=np.nan), + ) + if val is None + else (dim, val) + for k, (dim, val) in self.data_vars.items() + }, attrs=self.attrs, ) From 1f0b19c908c33d1b44e7b1ae8ea0eeced07208f2 Mon Sep 17 00:00:00 2001 From: Lukas Kluft Date: Mon, 3 Nov 2025 14:47:36 +0100 Subject: [PATCH 2/2] Add test for Component class --- konrad/test/test_component.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 konrad/test/test_component.py diff --git a/konrad/test/test_component.py b/konrad/test/test_component.py new file mode 100644 index 0000000..4d578e3 --- /dev/null +++ b/konrad/test/test_component.py @@ -0,0 +1,29 @@ +import numpy as np + +from konrad.component import Component + + +class TestComponent: + def test_to_dataset(self): + """Test conversion to Xarray dataset.""" + c = Component() + + c.coords = {"dim": np.arange(10)} + c._data_vars = {"var": (("dim",), np.arange(10))} + c._attrs = {"title": "Dummy component"} + + ds = c.to_dataset() + + assert ds.title == "Dummy component" + assert ds["var"][5] == 5 + + def test_to_dataset_uninitialized(self): + """Test conversion to Xarray dataset with uninitialized data.""" + c = Component() + + c.coords = {"dim": np.arange(10)} + c._data_vars = {"var": (("dim",), None)} + + ds = c.to_dataset() + + assert np.all(np.isnan(ds["var"]))