diff --git a/CHANGELOG.md b/CHANGELOG.md index f5110c3d..09676afc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ - When setting active periods on a Port, the `set_active_periods_from_array` method now accepts a list of booleans in addition to a list of 0's and 1's. - The `get_port` method on Node now returns None rather than raising a ValueError, if no such port with that name can be found. - `verify_node` now called when adding nodes to models and `verify_node` modified to now verify not only check the node but also verify (via call to `verify_port`) any ports attached to the node. +- Fix: BoundedLoads call `nonnegative_load` validator instead of incorrect `nonnegative_costs` validator. ## Releases diff --git a/src/echo/models/agnostic/__init__.py b/src/echo/models/agnostic/__init__.py index 9989e138..d1c11a85 100644 --- a/src/echo/models/agnostic/__init__.py +++ b/src/echo/models/agnostic/__init__.py @@ -2,7 +2,6 @@ from echo.models.agnostic.base import ( Demand, FixedPort, - OffOrConstrainedPort, Sink, Source, ) @@ -12,7 +11,7 @@ ControlledLoad, ControlledLoadOrGen, ) -from echo.models.agnostic.flex import FlexPort, FlexSink, FlexSource +from echo.models.agnostic.flex import FlexPort, FlexSink, FlexSource, OffOrConstrainedPort from echo.models.agnostic.input_output import InputOutputNode from echo.models.agnostic.storage import MobileStorage, Storage from echo.models.agnostic.tellegen import ( diff --git a/src/echo/models/agnostic/base.py b/src/echo/models/agnostic/base.py index b5f64cd6..12499ce1 100644 --- a/src/echo/models/agnostic/base.py +++ b/src/echo/models/agnostic/base.py @@ -1,18 +1,12 @@ import numpy as np -import pandas as pd -import pyomo.environ as en -from pydantic import root_validator, validator -from pyomo.core.expr import InequalityExpression +from pydantic import validator from echo.configuration import FlowConstraint, Flows, OptimisationType -from echo.models.agnostic.flex import FlexPort from echo.models.base import Port -from echo.models.scenario import EchoConcreteModel from echo.utils import ( TimeExpandableType, ) from echo.validators import ( - check_bound_order, nonnegative_load, nonpositive_generation, ) @@ -88,30 +82,3 @@ def add_demand_profile_from_array( time_periods: int | None = None, ) -> None: self.set_initial_value_from_array(array=demand, expansion_periods=expansion_periods, time_periods=time_periods) - - -class OffOrConstrainedPort(FlexPort): - """A port that is either off (0) or on, and when it is on it is constrained between a min and max value.""" - - lower_bound: float - upper_bound: float - - bounds_check = root_validator(allow_reuse=True)(check_bound_order) # checks that lower bound < upper bound - - @property - def active(self) -> str: - return "active_" + self.port_name - - def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: - super().add_port_to_model(model, profile) - setattr(model, self.active, en.Var(model.Expansion, model.Time, initialize=0, domain=en.Binary)) - - # Apply constraints such that if active=1, the port is bounded, and if active=0, the port is 0. - def on_off_constraint1(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression: - return getattr(model, self.port_name)[p, t] >= getattr(model, self.active)[p, t] * self.lower_bound - - def on_off_constraint2(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression: - return getattr(model, self.port_name)[p, t] <= getattr(model, self.active)[p, t] * self.upper_bound - - setattr(model, "on_off1_" + self.port_name, en.Constraint(model.Expansion, model.Time, rule=on_off_constraint1)) - setattr(model, "on_off2_" + self.port_name, en.Constraint(model.Expansion, model.Time, rule=on_off_constraint2)) diff --git a/src/echo/models/agnostic/bounded.py b/src/echo/models/agnostic/bounded.py index 2b2b10be..50981f67 100644 --- a/src/echo/models/agnostic/bounded.py +++ b/src/echo/models/agnostic/bounded.py @@ -11,7 +11,7 @@ from echo.validators import ( ArrayType, check_bound_order, - nonnegative_costs, + nonnegative_load, ) @@ -37,8 +37,8 @@ class BoundedLoad(BoundedPort): import_constraint = FlowConstraint.NoConstraint # Do additional validation to make sure both bounds are >= 0 - upper_bound_check = validator("upper_bound", allow_reuse=True)(nonnegative_costs) - lower_bound_check = validator("lower_bound", allow_reuse=True)(nonnegative_costs) + upper_bound_check = validator("upper_bound", allow_reuse=True)(nonnegative_load) + lower_bound_check = validator("lower_bound", allow_reuse=True)(nonnegative_load) def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: super().add_port_to_model(model, profile) diff --git a/src/echo/models/agnostic/flex.py b/src/echo/models/agnostic/flex.py index 6d0d43d8..2671a613 100644 --- a/src/echo/models/agnostic/flex.py +++ b/src/echo/models/agnostic/flex.py @@ -1,5 +1,14 @@ +import pandas as pd +import pyomo.environ as en +from pydantic import root_validator +from pyomo.core.expr import InequalityExpression + from echo.configuration import FlowConstraint, Flows, OptimisationType from echo.models.base import Port +from echo.models.scenario import EchoConcreteModel +from echo.validators import ( + check_bound_order, +) class FlexPort(Port): @@ -21,3 +30,30 @@ class FlexSource(FlexPort): """Flexible ports, exports only""" flows = Flows.Export + + +class OffOrConstrainedPort(FlexPort): + """A port that is either off (0) or on, and when it is on it is constrained between a min and max value.""" + + lower_bound: float + upper_bound: float + + bounds_check = root_validator(allow_reuse=True)(check_bound_order) # checks that lower bound < upper bound + + @property + def active(self) -> str: + return "active_" + self.port_name + + def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: + super().add_port_to_model(model, profile) + setattr(model, self.active, en.Var(model.Expansion, model.Time, initialize=0, domain=en.Binary)) + + # Apply constraints such that if active=1, the port is bounded, and if active=0, the port is 0. + def on_off_constraint1(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression: + return getattr(model, self.port_name)[p, t] >= getattr(model, self.active)[p, t] * self.lower_bound + + def on_off_constraint2(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression: + return getattr(model, self.port_name)[p, t] <= getattr(model, self.active)[p, t] * self.upper_bound + + setattr(model, "on_off1_" + self.port_name, en.Constraint(model.Expansion, model.Time, rule=on_off_constraint1)) + setattr(model, "on_off2_" + self.port_name, en.Constraint(model.Expansion, model.Time, rule=on_off_constraint2)) diff --git a/src/echo/validators.py b/src/echo/validators.py index 3e28e6b3..888cf9b1 100644 --- a/src/echo/validators.py +++ b/src/echo/validators.py @@ -1,4 +1,5 @@ from collections.abc import Generator +from numbers import Number from typing import Any import numpy as np @@ -32,38 +33,45 @@ def var_in_range(var1: float, range_min: float, range_max: float) -> ValueError return ValueError() -def is_non_negative(v: FloatData, err_msg: str) -> FloatData: - if v is not None: - if hasattr(v, "__iter__"): - if isinstance(v, dict): - for i in v.values(): - if i < 0: - raise ValueError(err_msg) - else: - for i in v: - if i < 0: - raise ValueError(err_msg) - else: - if v < 0: - raise ValueError(err_msg) +def is_non_negative(v: FloatData | None, err_msg: str) -> FloatData | None: + """Tests is a 'v' is non negative + + A value of 0 is considered non-negative (i.e. doesn't raise a ValueError) for the purposes of this test + """ + if v is None: + return v + + if isinstance(v, Number): + values = [v] + elif isinstance(v, dict): + values = v.values() + else: + values = v # v is list, set or numpy array + + if any([i < 0 for i in values]): + raise ValueError(err_msg) return v -def is_non_positive(v: FloatData, err_msg: str) -> FloatData: - if v is not None: - if hasattr(v, "__iter__"): - if type(v) is dict: - for i in v.values(): - if i > 0: - raise ValueError(err_msg) - else: - for i in v: - if i > 0: - raise ValueError(err_msg) - else: - if v > 0: - raise ValueError(err_msg) +def is_non_positive(v: FloatData | None, err_msg: str) -> FloatData | None: + """Tests is a 'v' is non positive + + A value of 0 is considered non-positive (i.e. doesn't raise a ValueError) for the purposes of this test + """ + if v is None: + return v + + if isinstance(v, Number): + values = [v] + elif isinstance(v, dict): + values = v.values() + else: + values = v # v is list, set or numpy array + + if any([i > 0 for i in values]): + raise ValueError(err_msg) + return v diff --git a/tests/unit/models/agnostic/test_base.py b/tests/unit/models/agnostic/test_base.py new file mode 100644 index 00000000..f0aa0d31 --- /dev/null +++ b/tests/unit/models/agnostic/test_base.py @@ -0,0 +1,96 @@ +import pytest +from pydantic import ValidationError + +from echo.models.agnostic.base import Sink, Source + + +@pytest.mark.parametrize( + "initial_value, expected_error", + [ + ([-5.0], None), + ([-0.0001], None), + ([-42.0, -12.0], None), + ([-15], None), + ([0.0], None), + ([5.0], ValidationError), + ([42.0, -12.0], ValidationError), + ([15], ValidationError), + ], +) +def test_source_port_validation(initial_value, expected_error): + initial_values_as_dict = {(0, i): v for i, v in enumerate(initial_value)} + if expected_error: + with pytest.raises(expected_error): + Source(initial_value=initial_values_as_dict) + else: + Source(initial_value=initial_values_as_dict) + + +@pytest.mark.parametrize( + "initial_value, expected_error", + [ + ([-5.0], None), + ([-0.0001], None), + ([-42.0, -12.0], None), + ([-15], None), + ([0.0], None), + ([5.0], ValidationError), + ([42.0, -12.0], ValidationError), + ([15], ValidationError), + ], +) +def test_source_port_process_initial_value_performs_validation(initial_value, expected_error): + if expected_error: + with pytest.raises(expected_error): + port = Source() + port.process_initial_value(initial_value, time_periods=len(initial_value)) + + else: + port = Source() + port.process_initial_value(initial_value, time_periods=len(initial_value)) + + +@pytest.mark.parametrize( + "initial_value, expected_error", + [ + ([5.0], None), + ([0.0001], None), + ([42.0, 12.0], None), + ([15], None), + ([0.0], None), + ([-5.0], ValidationError), + ([-42.0, 12.0], ValidationError), + ([-15], ValidationError), + ], +) +def test_sink_port_validation(initial_value, expected_error): + initial_values_as_dict = {(0, i): v for i, v in enumerate(initial_value)} + if expected_error: + with pytest.raises(expected_error): + Sink(initial_value=initial_values_as_dict) + else: + Sink(initial_value=initial_values_as_dict) + + +@pytest.mark.parametrize( + "initial_value, expected_error", + [ + ([5.0], None), + ([0.0001], None), + ([42.0, 12.0], None), + ([15], None), + ([0.0], None), + ([-5.0], ValidationError), + ([-42.0, 12.0], ValidationError), + ([-15], ValidationError), + ], +) +def test_sink_port_process_initial_value_performs_validation(initial_value, expected_error): + if expected_error: + with pytest.raises(expected_error): + port = Sink() + port.process_initial_value(initial_value, time_periods=len(initial_value)) + + else: + port = Sink() + port.process_initial_value(initial_value, time_periods=len(initial_value)) diff --git a/tests/unit/models/agnostic/test_bounded.py b/tests/unit/models/agnostic/test_bounded.py new file mode 100644 index 00000000..dc117c75 --- /dev/null +++ b/tests/unit/models/agnostic/test_bounded.py @@ -0,0 +1,40 @@ +import pytest +from pydantic import ValidationError + +from echo.models.agnostic.bounded import BoundedLoad, BoundedPort + + +@pytest.mark.parametrize( + "lower_bound,upper_bound,expected_error", + [ + (0, 100, None), + (0.1, 0.2, None), + (100, 0, ValidationError), # lower bound > upper bound + (50, 50, ValidationError), # lower bound == upper bound + ], +) +def test_boundedport_validation(lower_bound: float, upper_bound: float, expected_error): + if expected_error: + with pytest.raises(expected_error): + BoundedPort(lower_bound=lower_bound, upper_bound=upper_bound) + else: + BoundedPort(lower_bound=lower_bound, upper_bound=upper_bound) + + +@pytest.mark.parametrize( + "lower_bound,upper_bound,expected_error", + [ + (0, 100, None), + (0.1, 0.2, None), + (100, 0, ValidationError), # lower bound > upper bound + (50, 50, ValidationError), # lower bound == upper bound + (-100, 100, ValidationError), # lower bound -ve + (-100, -50, ValidationError), # both bounds -ve + ], +) +def test_boundedload_validation(lower_bound: float, upper_bound: float, expected_error): + if expected_error: + with pytest.raises(expected_error): + BoundedLoad(lower_bound=lower_bound, upper_bound=upper_bound) + else: + BoundedLoad(lower_bound=lower_bound, upper_bound=upper_bound) diff --git a/tests/unit/models/agnostic/test_controlled.py b/tests/unit/models/agnostic/test_controlled.py new file mode 100644 index 00000000..bea1a84d --- /dev/null +++ b/tests/unit/models/agnostic/test_controlled.py @@ -0,0 +1,40 @@ +import pytest +from pydantic import ValidationError + +from echo.models.agnostic.controlled import ControlledGen, ControlledLoad + + +@pytest.mark.parametrize( + "min_power,max_power,expected_error", + [ + (0, 0, None), + (0, 100, None), + (100, 0, None), + (-85, 0, ValidationError), # min_power -ve + (0, -15, ValidationError), # max_power -ve + ], +) +def test_controlledload_validation(min_power: float, max_power: float, expected_error): + if expected_error: + with pytest.raises(expected_error): + ControlledLoad(min_power=min_power, max_power=max_power) + else: + ControlledLoad(min_power=min_power, max_power=max_power) + + +@pytest.mark.parametrize( + "min_power,max_power,expected_error", + [ + (0, 0, None), + (0, -100, None), + (-100, 0, None), + (85, 0, ValidationError), # min_power +ve + (0, 15, ValidationError), # max_power +ve + ], +) +def test_controlledgen_validation(min_power: float, max_power: float, expected_error): + if expected_error: + with pytest.raises(expected_error): + ControlledGen(min_power=min_power, max_power=max_power) + else: + ControlledGen(min_power=min_power, max_power=max_power) diff --git a/tests/unit/models/agnostic/test_flex.py b/tests/unit/models/agnostic/test_flex.py new file mode 100644 index 00000000..bca51565 --- /dev/null +++ b/tests/unit/models/agnostic/test_flex.py @@ -0,0 +1,21 @@ +import pytest +from pydantic import ValidationError + +from echo.models.agnostic.flex import OffOrConstrainedPort + + +@pytest.mark.parametrize( + "lower_bound,upper_bound,expected_error", + [ + (0, 100, None), + (0.1, 0.2, None), + (100, 0, ValidationError), # lower bound > upper bound + (50, 50, ValidationError), # lower bound == upper bound + ], +) +def test_offorconstrainedport_validation(lower_bound: float, upper_bound: float, expected_error): + if expected_error: + with pytest.raises(expected_error): + OffOrConstrainedPort(lower_bound=lower_bound, upper_bound=upper_bound) + else: + OffOrConstrainedPort(lower_bound=lower_bound, upper_bound=upper_bound) diff --git a/tests/unit/models/agnostic/test_storage.py b/tests/unit/models/agnostic/test_storage.py new file mode 100644 index 00000000..5fec6077 --- /dev/null +++ b/tests/unit/models/agnostic/test_storage.py @@ -0,0 +1,102 @@ +import pytest +from pydantic import ValidationError + +from echo.exceptions import ConfigurationError +from echo.models.agnostic.storage import MobileStorage, Storage + + +@pytest.mark.parametrize( + "storage_params", + [ + {"max_capacity": 0, "charging_power_limit": 0}, # missing discharging_power_limit + {"max_capacity": 0, "discharging_power_limit": 0}, # missing charging_power_limit + {"charging_power_limit": 0, "discharging_power_limit": 0}, # missing max_capacity + ], +) +def test_storage_validation_missing_fields(storage_params): + with pytest.raises(ValidationError): + Storage(**storage_params) + + +@pytest.mark.parametrize( + "storage_capacity_cost, expected_error", + [ + (5.0, None), + (0.0, ValidationError), # 0 is not a pydantic PositiveFloat + (-7.0, ValidationError), # not a PostiveFloat + ], +) +def test_storage_validation_storage_capactity_cost( + storage_capacity_cost: float, expected_error: ValidationError | None +): + storage_params = {"max_capacity": 0, "charging_power_limit": 0, "discharging_power_limit": 0} + if expected_error: + with pytest.raises(ValidationError): + Storage(storage_capacity_cost=storage_capacity_cost, **storage_params) + else: + Storage(storage_capacity_cost=storage_capacity_cost, **storage_params) + + +@pytest.mark.parametrize( + "storage_params, expected_error", + [ + ({"depth_of_discharge_limit": 0.5}, None), + ({"depth_of_discharge_limit": -0.5}, ValidationError), # Dod can't be negative + ({"depth_of_discharge_limit": 110}, ValidationError), # DoD can't be > 100% + ], +) +def test_storage_validation_depth_of_discharge_check(storage_params, expected_error): + common_storage_params = {"max_capacity": 0, "charging_power_limit": 0, "discharging_power_limit": 0} + if expected_error: + with pytest.raises(ValidationError): + Storage(**common_storage_params, **storage_params) + else: + Storage(**common_storage_params, **storage_params) + + +# NOTE: This test is fails due to a bug that needs to be resolved. +# Details on the bug can be found here: https://github.com/bsgip/echo/issues/124 +# +# @pytest.mark.parametrize( +# "initial_state_of_charge, expected_error", +# [ +# (50, None), # initial soc = min soc +# (75, None), # min soc < initial soc < max capacity +# (100, None), # initital soc = max capacity +# (0, ValidationError), # initial soc < min soc +# (25, ValidationError), # initial soc < min soc +# (101, ValidationError), # initial soc > max capacity +# ], +# ) +# def test_storage_validation_initial_state_of_charge_check(initial_state_of_charge, expected_error): +# # min_capacity = max_capacity * depth_of_discharge_limit = 50 +# storage_params = { +# "max_capacity": 100, +# "depth_of_discharge_limit": 0.5, +# "charging_power_limit": 0, +# "discharging_power_limit": 0, +# # (see function dod_checks) +# } +# if expected_error: +# with pytest.raises(ValidationError): +# Storage(initial_state_of_charge=initial_state_of_charge, **storage_params) +# else: +# Storage(initial_state_of_charge=initial_state_of_charge, **storage_params) + + +@pytest.mark.parametrize( + "conserv_params, expected_error", + [ + ({"soc_conserv": None}, None), # when soc_conserv is None no validation is triggered + ({"soc_conserv": 0, "soc_conserv_cost": None, "available": []}, ConfigurationError), # soc_conserv_cost is None + ({"soc_conserv": 0, "soc_conserv_cost": 0, "available": None}, ConfigurationError), # available is None + ], +) +def test_mobile_storage_validation(conserv_params, expected_error): + storage_params = {"max_capacity": 0, "charging_power_limit": 0, "discharging_power_limit": 0} + + if expected_error: + with pytest.raises(expected_error): + MobileStorage(**conserv_params, **storage_params) + else: + MobileStorage(**conserv_params, **storage_params) diff --git a/tests/unit/models/base/test_port.py b/tests/unit/models/base/test_port.py index 08854dbc..f8020909 100644 --- a/tests/unit/models/base/test_port.py +++ b/tests/unit/models/base/test_port.py @@ -107,7 +107,7 @@ def test_port_raises_configuration_error(port_params: dict): (np.array([1.0, 2.0, 3.0]), {(0, 0): 1.0, (0, 1): 2.0, (0, 2): 3.0}), # np array of floats ], ) -def test_port_proccess_initial_value(raw_initial_val: list, expected_initial_val: dict): +def test_port_process_initial_value(raw_initial_val: list, expected_initial_val: dict): port = Port(port_name="port_name") assert port.initial_value is None diff --git a/tests/unit/test_validators.py b/tests/unit/test_validators.py new file mode 100644 index 00000000..d64f905c --- /dev/null +++ b/tests/unit/test_validators.py @@ -0,0 +1,58 @@ +import numpy as np +import pytest + +from echo.validators import is_non_negative, is_non_positive + + +@pytest.mark.parametrize( + "value,should_raise_value_error", + [ + (-1.0, True), # floats + (0.0, False), + (1.0, False), + ([1, 2, 49], False), # lists + ([1, 2, -49], True), + ([-1, -2, -49], True), + ({0, 1.5, 2.7, 150.3}, False), # sets + ({0, 1.5, 2.7, -150.3}, True), + ({0, -1.5, -2.7, -150.3}, True), + ({0: 0, 1: 1, 2: 2}, False), # dicts + ({0: 0, 1: -1, 2: -2}, True), + (np.array([1, 2, 49]), False), # numpy arrays + (np.array([1, 2, -49]), True), + (np.array([-1, -2, -49]), True), + ], +) +def test_is_non_negative(value, should_raise_value_error): + if should_raise_value_error: + with pytest.raises(ValueError): + is_non_negative(value, "") + else: + is_non_negative(value, "") + + +@pytest.mark.parametrize( + "value,should_raise_value_error", + [ + (-1.0, False), # floats + (0.0, False), + (1.0, True), + ([-1, -2, -49], False), # lists + ([-1, -2, 49], True), + ([1, 2, 49], True), + ({0, -1.5, -2.7, -150.3}, False), # sets + ({0, -1.5, -2.7, 150.3}, True), + ({0, 1.5, 2.7, 150.3}, True), + ({0: 0, 1: -1, 2: -2}, False), # dicts + ({0: 0, 1: 1, 2: 2}, True), + (np.array([-1, -2, -49]), False), # numpy arrays + (np.array([-1, -2, 49]), True), + (np.array([1, 2, 49]), True), + ], +) +def test_is_non_positive(value, should_raise_value_error): + if should_raise_value_error: + with pytest.raises(ValueError): + is_non_positive(value, "") + else: + is_non_positive(value, "")