Skip to content

Commit

Permalink
resolved issues raised by ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
ClaasRostock committed Nov 5, 2024
1 parent c1983a5 commit ee70e90
Show file tree
Hide file tree
Showing 14 changed files with 55 additions and 45 deletions.
9 changes: 4 additions & 5 deletions src/component_model/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@
from pythonfmu.enums import Fmi2Causality as Causality # type: ignore
from pythonfmu.enums import Fmi2Variability as Variability # type: ignore
from pythonfmu.fmi2slave import FMI2_MODEL_OPTIONS # type: ignore

from component_model.caus_var_ini import Initial

from src.component_model.utils.logger import get_module_logger
from src.component_model.variable import Variable

from component_model.caus_var_ini import Initial

logger = get_module_logger(__name__, level=0)
Value: TypeAlias = str | int | float | bool | Enum

Expand Down Expand Up @@ -649,7 +648,7 @@ def _get(self, vrs: list, typ: type) -> list:
"""
values = list()
for var, sub in self._var_iter(vrs):
check = var.typ == typ or (typ == int and issubclass(var.typ, Enum))
check = var.typ == typ or (typ is int and issubclass(var.typ, Enum))
assert check, f"Invalid type in 'get_{typ}'. Found variable {var.name} with type {var.typ}"
val = var.getter()
if var is not None and len(var) > 1:
Expand Down Expand Up @@ -680,7 +679,7 @@ def _set(self, vrs: list, values: list, typ: type):
"""
idx = 0
for var, sub in self._var_iter(vrs):
check = var.typ == typ or (typ == int and issubclass(var.typ, Enum))
check = var.typ == typ or (typ is int and issubclass(var.typ, Enum))
assert check, f"Invalid type in 'set_{typ}'. Found variable {var.name} with type {var.typ}"
if var is not None and len(var) > 1:
if sub is None: # set the whole vector
Expand Down
2 changes: 2 additions & 0 deletions src/component_model/utils/fmu.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from pathlib import Path
from typing import Any

from component_model.utils.xml import read_xml, xml_to_python_val


def model_from_fmu(fmu: str | Path, provideMsg: bool = False, sep=".") -> dict:
"""Generate a Model from an FMU (excluding the inner working functions like `do_step()`),
Expand Down
19 changes: 9 additions & 10 deletions src/component_model/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
from pythonfmu.enums import Fmi2Causality as Causality # type: ignore
from pythonfmu.enums import Fmi2Variability as Variability # type: ignore
from pythonfmu.variables import ScalarVariable # type: ignore

from src.component_model.caus_var_ini import Initial, check_causality_variability_initial, use_start
from src.component_model.utils.logger import get_module_logger

Expand Down Expand Up @@ -194,7 +193,7 @@ def __init__(
self._start: tuple
# First we check for str (since these are also iterable), then we can check for the presence of __getitem__
# Determine the (element) type (unique for all elements in compound variables)
if self._typ == str: # explicit free string
if self._typ is str: # explicit free string
self._len = 1
self.unit = "dimensionless"
self.display = None
Expand Down Expand Up @@ -453,7 +452,7 @@ def check_range(self, value: PyType | Compound | None, idx: int | None = None, d
if self._len == 1 and idx is None:
idx = 0
if isinstance(value, str): # no range checking on strings
return self._typ == str
return self._typ is str
elif self._len > 1 and idx is None: # check all components
assert isinstance(value, (tuple, list, np.ndarray)) and len(value) == self._len, f"{value} has no elements"
return all(self.check_range(value[i], i, disp) for i in range(self._len))
Expand All @@ -465,15 +464,15 @@ def check_range(self, value: PyType | Compound | None, idx: int | None = None, d
value = value[idx]
if value is None: # denotes unchanged values (of compound variables)
return True
if self._typ != type(value):
if self._typ is not type(value):
try:
value = self._typ(value) # try to cast the value
except Exception: # give up
return False
# special types (str checked above):
if self._typ == str: # no range checking on str
if self._typ is str: # no range checking on str
return True
elif self._typ == bool:
elif self._typ is bool:
return isinstance(value, bool)
elif isinstance(value, Enum):
return isinstance(value, self._typ)
Expand All @@ -489,7 +488,7 @@ def fmi_type_str(self, val: PyType) -> str:
"""Translate the provided type to a proper fmi type and return it as string.
See types defined in schema fmi2Unit.xsd.
"""
if self._typ == bool:
if self._typ is bool:
return "true" if val else "false"
else:
return str(val)
Expand Down Expand Up @@ -517,9 +516,9 @@ def auto_type(cls, val: PyType | Compound, allow_int: bool = False):
pass
elif issubclass(typ, t):
typ = t
elif typ == float and t == int: # we allow that, even if no subclass
elif typ is float and t is int: # we allow that, even if no subclass
pass
elif typ == int and t == float: # we allow that, even if no subclass
elif typ is int and t is float: # we allow that, even if no subclass
typ = float
else:
raise VariableInitError(f"Incompatible variable types {typ}, {t} in {val}") from None
Expand Down Expand Up @@ -593,7 +592,7 @@ def _disect_unit(self, quantity: PyType | Compound) -> tuple:
val, ub, display = (str(quantity), "", None) # type: ignore
else:
val, ub, display = (quantity, "dimensionless", None) # type: ignore
if self._typ is not None and type(val) != self._typ: # check variable type
if self._typ is not None and type(val) is not self._typ: # check variable type
try: # try to convert the magnitude to the correct type.
val = self._typ(val)
except Exception as err:
Expand Down
1 change: 1 addition & 0 deletions tests/examples/bouncing_ball_3d.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from math import sqrt

import numpy as np

from component_model.model import Model
from component_model.variable import Variable

Expand Down
1 change: 1 addition & 0 deletions tests/examples/bouncing_ball_xz.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from math import sqrt

import numpy as np

from component_model.model import Model
from component_model.variable import Variable

Expand Down
1 change: 1 addition & 0 deletions tests/examples/input_table.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import numpy as np

from component_model.model import Model
from component_model.variable import Variable

Expand Down
5 changes: 3 additions & 2 deletions tests/test_bouncing_ball_3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@

import matplotlib.pyplot as plt
import pytest
from component_model.model import Model # type: ignore
from component_model.utils import model_from_fmu
from fmpy import plot_result, simulate_fmu # type: ignore
from fmpy.util import fmu_info # type: ignore
from fmpy.validation import validate_fmu # type: ignore
Expand All @@ -17,6 +15,9 @@
from libcosimpy.CosimObserver import CosimObserver
from libcosimpy.CosimSlave import CosimLocalSlave

from component_model.model import Model # type: ignore
from component_model.utils import model_from_fmu


def _in_interval(x: float, x0: float, x1: float):
return x0 <= x <= x1 or x1 <= x <= x0
Expand Down
3 changes: 2 additions & 1 deletion tests/test_bouncing_ball_xz.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from pathlib import Path

import pytest
from component_model.model import Model # type: ignore
from fmpy import simulate_fmu # type: ignore
from libcosimpy.CosimEnums import CosimExecutionState
from libcosimpy.CosimExecution import CosimExecution
from libcosimpy.CosimSlave import CosimLocalSlave

from component_model.model import Model # type: ignore


@pytest.fixture(scope="session")
def bouncing_ball_fmu():
Expand Down
3 changes: 2 additions & 1 deletion tests/test_caus_var_ini.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import component_model.caus_var_ini as cvi # type: ignore
import pytest
from pythonfmu.enums import Fmi2Causality as Causality # type: ignore
from pythonfmu.enums import Fmi2Variability as Variability # type: ignore

import component_model.caus_var_ini as cvi # type: ignore


def test_combinations():
assert (len(cvi.combinations), len(cvi.combinations[0])) == (5, 6)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_make_simpletable.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

import numpy as np
import pytest
from component_model.model import Model # type: ignore
from component_model.utils import make_osp_system_structure
from fmpy import simulate_fmu # type: ignore
from fmpy.util import fmu_info # type: ignore
from fmpy.validation import validate_fmu # type: ignore
Expand All @@ -15,6 +13,8 @@
from libcosimpy.CosimObserver import CosimObserver # type: ignore
from libcosimpy.CosimSlave import CosimLocalSlave

from component_model.model import Model # type: ignore
from component_model.utils import make_osp_system_structure
from tests.examples.input_table import InputTable


Expand Down
1 change: 1 addition & 0 deletions tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pathlib import Path

import pytest

from component_model.logger import get_module_logger # type: ignore
from component_model.model import Model # type: ignore
from component_model.utils import model_from_fmu
Expand Down
3 changes: 2 additions & 1 deletion tests/test_pint.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@

import logging

from component_model.logger import get_module_logger # type: ignore
from pint import UnitRegistry

from component_model.logger import get_module_logger # type: ignore

logger = get_module_logger(__name__, level=logging.INFO)

_reg = UnitRegistry(system="SI", autoconvert_offset_to_baseunit=True) # , auto_reduce_dimensions=True)
Expand Down
7 changes: 4 additions & 3 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from pathlib import Path

import pytest

from component_model.model import Model
from component_model.utils import (
make_osp_system_structure,
Expand Down Expand Up @@ -43,9 +44,9 @@ def test_xml_to_python_val():
assert not xml_to_python_val("false")
assert xml_to_python_val("99") == 99, "Detect an int"
assert xml_to_python_val("99.99") == 99.99, "Detect a float"
assert xml_to_python_val("Real") == float, "Detect a type"
assert xml_to_python_val("String") == str, "Detect a type"
assert xml_to_python_val("Real") == float, "Detect a type"
assert xml_to_python_val("Real") is float, "Detect a type"
assert xml_to_python_val("String") is str, "Detect a type"
assert xml_to_python_val("Real") is float, "Detect a type"
assert xml_to_python_val("Hello World") == "Hello World", "Detect a literal string"


Expand Down
41 changes: 21 additions & 20 deletions tests/test_variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

import numpy as np
import pytest
from pythonfmu.enums import Fmi2Causality as Causality # type: ignore
from pythonfmu.enums import Fmi2Variability as Variability # type: ignore

from component_model.caus_var_ini import Initial
from component_model.logger import get_module_logger # type: ignore
from component_model.model import Model # type: ignore
Expand All @@ -16,8 +19,6 @@
cartesian_to_spherical,
spherical_to_cartesian,
)
from pythonfmu.enums import Fmi2Causality as Causality # type: ignore
from pythonfmu.enums import Fmi2Variability as Variability # type: ignore

logger = get_module_logger(__name__, level=logging.INFO)

Expand Down Expand Up @@ -72,17 +73,17 @@ def test_var_check():


def test_auto_type():
assert Variable.auto_type(1) == float, "int not allowed (default)"
assert Variable.auto_type(1, allow_int=True) == int, "int allowed"
assert Variable.auto_type(0.99, allow_int=True) == float
assert Variable.auto_type(0.99, allow_int=False) == float
assert Variable.auto_type((1, 2, 0.99), allow_int=False) == float
assert Variable.auto_type((1, 2, 0.99), allow_int=True) == float, "Ok by our rules"
assert Variable.auto_type((1, 2, 3), allow_int=True) == int
assert Variable.auto_type((True, False, 3), allow_int=True) == int
assert Variable.auto_type((True, False), allow_int=True) == bool
assert Variable.auto_type((True, False), allow_int=False) == bool
assert Variable.auto_type((True, 1, 9.9), allow_int=False) == bool
assert Variable.auto_type(1) is float, "int not allowed (default)"
assert Variable.auto_type(1, allow_int=True) is int, "int allowed"
assert Variable.auto_type(0.99, allow_int=True) is float
assert Variable.auto_type(0.99, allow_int=False) is float
assert Variable.auto_type((1, 2, 0.99), allow_int=False) is float
assert Variable.auto_type((1, 2, 0.99), allow_int=True) is float, "Ok by our rules"
assert Variable.auto_type((1, 2, 3), allow_int=True) is int
assert Variable.auto_type((True, False, 3), allow_int=True) is int
assert Variable.auto_type((True, False), allow_int=True) is bool
assert Variable.auto_type((True, False), allow_int=False) is bool
assert Variable.auto_type((True, 1, 9.9), allow_int=False) is bool
# with pytest.raises(VariableInitError) as err: # that goes too far
# assert Variable.auto_type( (True,1, 9.9), allow_int=False) == float
# assert str(err.value).startswith("Incompatible variable types")
Expand Down Expand Up @@ -203,7 +204,7 @@ def test_init():
myNP2,
myBool,
) = init_model_variables()
assert myInt.typ == int
assert myInt.typ is int
assert myInt.description == "A integer variable"
assert myInt.causality == Causality.parameter
assert myInt.variability == Variability.fixed
Expand All @@ -228,7 +229,7 @@ def test_init():
mod.set_integer(((mod.variable_by_name("myInt").value_reference),), (99,)) # simulate setting from outside
assert mod.get_integer(((mod.variable_by_name("myInt").value_reference),)) == [99]

assert myFloat.typ == float
assert myFloat.typ is float
assert myFloat.causality == Causality.input
assert myFloat.variability == Variability.continuous
assert myFloat.initial == Initial.none, f"initial: {myFloat.initial}"
Expand Down Expand Up @@ -276,7 +277,7 @@ def test_init():
mod.set_integer(((mod.variable_by_name("myEnum").value_reference),), (2,)) # simulate setting from outside
assert mod.get_integer(((mod.variable_by_name("myEnum").value_reference),)) == [2]

assert myBool.typ == bool
assert myBool.typ is bool
assert myBool.causality == Causality.parameter
assert myBool.variability == Variability.fixed
assert myBool.initial == Initial.exact
Expand All @@ -298,7 +299,7 @@ def test_init():
mod.set_boolean(((mod.variable_by_name("myBool").value_reference),), (True,)) # simulate setting from outside
assert mod.get_boolean(((mod.variable_by_name("myBool").value_reference),)) == [True]

assert myStr.typ == str
assert myStr.typ is str
assert myStr.causality == Causality.parameter
assert myStr.variability == Variability.fixed
assert myStr.initial == Initial.exact, f"initial: {myStr.initial}"
Expand All @@ -318,7 +319,7 @@ def test_init():
mod.set_string(((mod.variable_by_name("myStr").value_reference),), ("Hello",)) # simulate setting from outside
assert mod.get_string(((mod.variable_by_name("myStr").value_reference),)) == ["Hello"]

assert myNP.typ == float
assert myNP.typ is float
assert myNP == mod.variable_by_name("myNP")
assert myNP.description == "A NP variable"
assert mod.variable_by_name("myNP[1]") == mod.variable_by_name("myNP"), "Returns always the parent"
Expand Down Expand Up @@ -385,7 +386,7 @@ def test_init():
assert myEnum.range[0] == (0, 4)
assert myEnum.check_range(Causality.parameter)
assert myStr.range == (("", ""),), "Just a placeholder. Range of str is not checked"
assert myBool.typ == bool
assert myBool.typ is bool


def test_range():
Expand Down Expand Up @@ -426,7 +427,7 @@ def test_dirty():
on_set=lambda x: 0.5 * x,
rng=((0, "3m"), (0, float("inf")), (float("-inf"), "5rad")),
)
assert myNP.typ == float, f"Type {myNP.typ}"
assert myNP.typ is float, f"Type {myNP.typ}"
myNP.setter(np.array((2, 1, 4), float))
assert myNP not in mod.dirty, "Not dirty, because the whole variable was changed"
arrays_equal(mod.myNP, [0.5 * 2.0, 0.5 * math.radians(1), 0.5 * 4]) # ... and on_set has been run
Expand Down

0 comments on commit ee70e90

Please sign in to comment.