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

Allow modification of unit #787

Merged
merged 2 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
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
6 changes: 5 additions & 1 deletion mikeio/dataset/_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,11 @@ def type(self) -> EUMType:
@property
def unit(self) -> EUMUnit:
"""EUMUnit."""
return self.item.unit
return self.item._unit

@unit.setter
def unit(self, value: EUMUnit) -> None:
self.item.unit = value

@property
def start_time(self) -> datetime:
Expand Down
20 changes: 17 additions & 3 deletions mikeio/eum/_eum.py
Original file line number Diff line number Diff line change
Expand Up @@ -1465,12 +1465,12 @@ def __init__(
raise ValueError(
"Invalid unit. Unit should be supplied as EUMUnit, e.g. ItemInfo('WL',EUMType.Water_Level, EUMUnit.meter)"
)
self.unit = unit
self._unit = unit
else:
if self.type == EUMType.Undefined:
self.unit = EUMUnit.undefined
self._unit = EUMUnit.undefined
else:
self.unit = self.type.units[0]
self._unit = self.type.units[0]

self.data_value_type = to_datatype(data_value_type)

Expand All @@ -1496,6 +1496,20 @@ def __repr__(self) -> str:
else:
return f"{self.name} <{self.type.display_name}> ({self.unit.display_name}) - {self.data_value_type}"

@property
def unit(self) -> EUMUnit:
"Item unit."
return self._unit

@unit.setter
def unit(self, value: EUMUnit) -> None:
"Set unit."
if value not in self.type.units:
raise ValueError(
f"{value} is not a correct unit for {self.type}. Use {self.type.units}"
)
self._unit = value

@staticmethod
def from_mikecore_dynamic_item_info(dfsItemInfo: DfsDynamicItemInfo) -> "ItemInfo":
"""Create ItemInfo from a mikecore.DfsDynamicItemInfo object."""
Expand Down
21 changes: 21 additions & 0 deletions tests/test_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -1376,3 +1376,24 @@ def test_set_by_mask():
mask = da < threshold
wl_capped = da.copy()
wl_capped[mask] = np.nan


def test_set_unit() -> None:
da = mikeio.DataArray(
data=np.array([0.0, 1.0]),
item=mikeio.ItemInfo("Water", mikeio.EUMType.Water_Level, mikeio.EUMUnit.meter),
)

da.unit = mikeio.EUMUnit.feet

assert da.unit == mikeio.EUMUnit.feet


def test_set_bad_unit_fails() -> None:
da = mikeio.DataArray(
data=np.array([0.0, 1.0]),
item=mikeio.ItemInfo("Water", mikeio.EUMType.Water_Level, mikeio.EUMUnit.meter),
)

with pytest.raises(ValueError, match="unit"):
da.unit = mikeio.EUMUnit.decibar