Skip to content

Commit

Permalink
Init instance variables in __init__ (#600)
Browse files Browse the repository at this point in the history
  • Loading branch information
ecomodeller authored Nov 2, 2023
1 parent 376b706 commit 6ab5abf
Show file tree
Hide file tree
Showing 13 changed files with 171 additions and 196 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,6 @@ htmlcov

docs/_build
\tmp
.venv/
.venv/

.testmondata
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
LIB = mikeio

LIB = mikeio

Expand All @@ -19,6 +20,7 @@ coverage:
pytest --cov-report html --cov=$(LIB) tests/

doctest:
# only test a specific set of files for now
pytest mikeio/dfs/*.py mikeio/dfsu/*.py mikeio/eum/*.py mikeio/pfs/*.py mikeio/spatial/_grid_geometry.py --doctest-modules
rm -f *.dfs* # remove temporary files, created from doctests

Expand Down
5 changes: 2 additions & 3 deletions mikeio/dataset/_dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,6 @@ def _is_compatible(self, other, raise_error=False):
problems.append("Number of timesteps must be the same")
if self.start_time != other.start_time:
problems.append("start_time must be the same")
#if type(self.geometry) != type(other.geometry):
if not isinstance(self.geometry, other.geometry.__class__):
problems.append("The type of geometry must be the same")
if hasattr(self.geometry, "__eq__"):
Expand Down Expand Up @@ -344,12 +343,12 @@ def _set_spectral_attributes(self, geometry):
# ============= Basic properties/methods ===========

@property
def name(self) -> Optional[str]:
def name(self) -> str:
"""Name of this DataArray (=da.item.name)"""
return self.item.name

@name.setter
def name(self, value):
def name(self, value: str) -> None:
self.item.name = value

@property
Expand Down
53 changes: 18 additions & 35 deletions mikeio/dataset/_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
MutableMapping,
Any,
overload,
Hashable
Hashable,
Set

)


Expand Down Expand Up @@ -94,7 +96,8 @@ def __init__(
data = self._create_dataarrays(
data=data, time=time, items=items, geometry=geometry, zn=zn, dims=dims
) # type: ignore
self._init_from_DataArrays(data, validate=validate)
self._data_vars = self._init_from_DataArrays(data, validate=validate)
self.plot = _DatasetPlotter(self)

@staticmethod
def _is_DataArrays(data):
Expand Down Expand Up @@ -135,31 +138,23 @@ def _create_dataarrays(
)
return data_vars

def _init_from_DataArrays(self, data, validate=True):
def _init_from_DataArrays(self, data, validate=True) -> MutableMapping[str, DataArray]:
"""Initialize Dataset object with Iterable of DataArrays"""
self._data_vars = self._DataArrays_as_mapping(data)
data_vars = self._DataArrays_as_mapping(data)

if (len(self) > 1) and validate:
first = self[0]
for i in range(1, len(self)):
da = self[i]
if (len(data_vars) > 1) and validate:
first = list(data_vars.values())[0]
for da in data_vars.values():
first._is_compatible(da, raise_error=True)

self._check_all_different_ids(self._data_vars.values())
self._check_all_different_ids(data_vars.values())

self.__itemattr = []
for key, value in self._data_vars.items():
# TODO is it necessary to keep track of item names?
self.__itemattr: Set[str] = set()
for key, value in data_vars.items():
self._set_name_attr(key, value)

self.plot = _DatasetPlotter(self)

if len(self) > 0:
self._set_spectral_attributes(self.geometry)

# since Dataset is MutableMapping it has values and keys by default
# but we delete those to avoid confusion
# self.values = None
self.keys = None
return data_vars

@property
def values(self):
Expand Down Expand Up @@ -232,11 +227,7 @@ def _DataArrays_as_mapping(data):
data = [data]

item_names = Dataset._unique_item_names(data)

data_map = {}
for n, da in zip(item_names, data):
data_map[n] = da
return data_map
return {key: da for key, da in zip(item_names, data)}

@staticmethod
def _validate_item_names_and_keys(data_map: Mapping[str, DataArray]):
Expand All @@ -251,13 +242,12 @@ def _validate_item_names_and_keys(data_map: Mapping[str, DataArray]):
return data_map

@staticmethod
def _unique_item_names(das: Sequence[DataArray]):
def _unique_item_names(das: Sequence[DataArray]) -> List[str]:
item_names = [da.name for da in das]
if len(set(item_names)) != len(item_names):
raise ValueError(
f"Item names must be unique! ({item_names}). Please rename before constructing Dataset."
)
# TODO: make a list of unique items names
return item_names

@staticmethod
Expand Down Expand Up @@ -303,13 +293,6 @@ def _check_already_present(self, new_da):
for da in self:
self._id_of_DataArrays_equal(da, new_da)

def _set_spectral_attributes(self, geometry):
if hasattr(geometry, "frequencies") and hasattr(geometry, "directions"):
self.frequencies = geometry.frequencies
self.n_frequencies = geometry.n_frequencies
self.directions = geometry.directions
self.n_directions = geometry.n_directions

# ============ end of init =============

# ============= Basic properties/methods ===========
Expand Down Expand Up @@ -643,7 +626,7 @@ def rename(self, mapper: Mapping[str, str], inplace=False):
def _set_name_attr(self, name: str, value: DataArray):
name = _to_safe_name(name)
if name not in self.__itemattr:
self.__itemattr.append(name) # keep track of what we insert
self.__itemattr.add(name) # keep track of what we insert
setattr(self, name, value)

def _del_name_attr(self, name: str):
Expand Down
Loading

0 comments on commit 6ab5abf

Please sign in to comment.