Repository: DHI/mikeio
Pull request #778 (2025-01-20 15:50:41)

Fix keepdims


Patch:
diff --git a/mikeio/__init__.py b/mikeio/__init__.py
index 2c694975..499d93df 100644
--- a/mikeio/__init__.py
+++ b/mikeio/__init__.py
@@ -121,7 +121,7 @@ def read(
     ext = Path(filename).suffix.lower()
 
     if "dfs" not in ext:
-        raise ValueError("mikeio.read() is only supported for Dfs files")
+        raise ValueError("mikeio.read() is only supported for dfs files")
 
     dfs = open(filename)
     if isinstance(dfs, Mesh):
diff --git a/mikeio/dfs/_dfs.py b/mikeio/dfs/_dfs.py
index 174627f4..f7263438 100644
--- a/mikeio/dfs/_dfs.py
+++ b/mikeio/dfs/_dfs.py
@@ -19,7 +19,7 @@ from mikecore.DfsFileFactory import DfsFileFactory
 from mikecore.Projections import Cartography
 
 from ..dataset import Dataset
-from ..eum import EUMType, EUMUnit, ItemInfo, ItemInfoList
+from ..eum import ItemInfo, ItemInfoList
 from ..exceptions import ItemsError
 from .._time import DateTimeSelector
 
@@ -391,10 +391,15 @@ class _Dfs123:
         elif self._ndim == 2:
             shape = (nt, self.ny, self.nx)  # type: ignore
         else:
+            # TODO this is not used, since Dfs3 has a separate .read method
             shape = (nt, self.nz, self.ny, self.nx)  # type: ignore
 
+        dims = self.geometry.default_dims
+
         if single_time_selected and not keepdims:
             shape = shape[1:]
+        else:
+            dims = ["time"] + list(dims)
 
         data_list: list[np.ndarray] = [
             np.ndarray(shape=shape, dtype=dtype) for _ in range(n_items)
@@ -406,8 +411,8 @@ class _Dfs123:
             for item in range(n_items):
                 itemdata = self._dfs.ReadItemTimeStep(item_numbers[item] + 1, int(it))
 
-                src = itemdata.Data
-                d = src
+                d = itemdata.Data
+                assert d.ndim == 1
 
                 d[d == self.deletevalue] = np.nan
 
@@ -415,7 +420,7 @@ class _Dfs123:
                     d = d.reshape(self.ny, self.nx)  # type: ignore
 
                 if single_time_selected:
-                    data_list[item] = d
+                    data_list[item] = np.atleast_2d(d) if keepdims else d
                 else:
                     data_list[item][i] = d
 
@@ -426,10 +431,12 @@ class _Dfs123:
         items = _get_item_info(self._dfs.ItemInfo, item_numbers)
 
         self._dfs.Close()
+
         return Dataset(
-            data_list,
-            time,
-            items,
+            data=data_list,
+            time=time,
+            items=items,
+            dims=tuple(dims),
             geometry=self.geometry,
             validate=False,
             dt=self._timestep,
@@ -451,17 +458,9 @@ class _Dfs123:
         list[Iteminfo]
 
         """
-        items = []
-        for item in item_numbers:
-            name = self._dfs.ItemInfo[item].Name
-            eumItem = self._dfs.ItemInfo[item].Quantity.Item
-            eumUnit = self._dfs.ItemInfo[item].Quantity.Unit
-            itemtype = EUMType(eumItem)
-            unit = EUMUnit(eumUnit)
-            data_value_type = self._dfs.ItemInfo[item].ValueType
-            item_info = ItemInfo(name, itemtype, unit, data_value_type)
-            items.append(item_info)
-        return items
+        infos = self._dfs.ItemInfo
+        nos = item_numbers
+        return [ItemInfo.from_mikecore_dynamic_item_info(infos[i]) for i in nos]
 
     @property
     def geometry(self) -> Any:


Test patch:
diff --git a/tests/test_consistency.py b/tests/test_consistency.py
index ce1c9e7d..5626194c 100644
--- a/tests/test_consistency.py
+++ b/tests/test_consistency.py
@@ -574,3 +574,38 @@ def test_concat_dfsu3d_single_timesteps_generic_vs_dataset(tmp_path):
     assert ds3.end_time == ds4.end_time
     assert ds3.n_items == ds4.n_items
     assert ds3.n_timesteps == ds4.n_timesteps
+
+
+def test_keepdims_removes_singleton_dimension() -> None:
+    ds1 = mikeio.read(
+        filename="tests/testdata/consistency/oresundHD.dfs1", time=0, keepdims=False
+    )
+    assert ds1.dims == ("x",)
+
+    ds2 = mikeio.read(
+        filename="tests/testdata/consistency/oresundHD.dfs1", time=0, keepdims=True
+    )
+    assert ds2.dims == ("time", "x")
+
+    ds3 = mikeio.read(
+        filename="tests/testdata/consistency/oresundHD.dfs2", time=0, keepdims=False
+    )
+    assert ds3.dims == (
+        "y",
+        "x",
+    )
+
+    ds4 = mikeio.read(
+        filename="tests/testdata/consistency/oresundHD.dfs2", time=0, keepdims=True
+    )
+    assert ds4.dims == ("time", "y", "x")
+
+    ds5 = mikeio.read(
+        filename="tests/testdata/consistency/oresundHD.dfsu", time=0, keepdims=False
+    )
+    assert ds5.dims == ("element",)
+
+    ds6 = mikeio.read(
+        filename="tests/testdata/consistency/oresundHD.dfsu", time=0, keepdims=True
+    )
+    assert ds6.dims == ("time", "element")