From 1a25a1c1ae42f6c3143fe5a26d960e1d6ae0d19d Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Mon, 14 Sep 2026 11:07:11 +0800 Subject: [PATCH 1/9] Move OffOrConstrainedPort to flex module --- src/echo/models/agnostic/__init__.py | 3 +-- src/echo/models/agnostic/base.py | 35 +-------------------------- src/echo/models/agnostic/flex.py | 36 ++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 36 deletions(-) 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/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)) From dfdfb623732b50bba529995c84f0b857575c093a Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Mon, 14 Sep 2026 13:48:20 +0800 Subject: [PATCH 2/9] Fix typo --- tests/unit/models/base/test_port.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 6516a94fae1a42a365f29bf2ba49eb7c31a254f0 Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Mon, 14 Sep 2026 13:54:19 +0800 Subject: [PATCH 3/9] Add some tests for a couple of the validators --- tests/unit/test_validators.py | 56 +++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 tests/unit/test_validators.py diff --git a/tests/unit/test_validators.py b/tests/unit/test_validators.py new file mode 100644 index 00000000..67d1f817 --- /dev/null +++ b/tests/unit/test_validators.py @@ -0,0 +1,56 @@ +import pytest +import numpy as np + +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]), True), # numpy arrays + (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]), True), # numpy arrays + (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, "") From ec063577fbd90ef5fad26a0c09237bd4fcbe72dc Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Mon, 14 Sep 2026 13:54:42 +0800 Subject: [PATCH 4/9] Refactor two validation functions --- src/echo/validators.py | 64 ++++++++++++++++++++++++------------------ 1 file changed, 36 insertions(+), 28 deletions(-) diff --git a/src/echo/validators.py b/src/echo/validators.py index 3e28e6b3..ace29535 100644 --- a/src/echo/validators.py +++ b/src/echo/validators.py @@ -1,5 +1,6 @@ from collections.abc import Generator from typing import Any +from numbers import Number import numpy as np from pydantic import Field @@ -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 From 7d8034642758632ddf72d7140db1fc93792e2822 Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Mon, 14 Sep 2026 14:36:54 +0800 Subject: [PATCH 5/9] Add tests for Source initial value validation --- tests/unit/models/agnostic/test_base.py | 50 +++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 tests/unit/models/agnostic/test_base.py diff --git a/tests/unit/models/agnostic/test_base.py b/tests/unit/models/agnostic/test_base.py new file mode 100644 index 00000000..83a996a7 --- /dev/null +++ b/tests/unit/models/agnostic/test_base.py @@ -0,0 +1,50 @@ +import pytest +from pydantic import ValidationError + +from echo.models.agnostic.base import 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)) From 4d02ad57d18558e49979abcdb7f28db0333ea4f4 Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Mon, 14 Sep 2026 14:40:07 +0800 Subject: [PATCH 6/9] Add tests for Sink initial value validation --- tests/unit/models/agnostic/test_base.py | 48 ++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/tests/unit/models/agnostic/test_base.py b/tests/unit/models/agnostic/test_base.py index 83a996a7..f17469c1 100644 --- a/tests/unit/models/agnostic/test_base.py +++ b/tests/unit/models/agnostic/test_base.py @@ -1,7 +1,7 @@ import pytest from pydantic import ValidationError -from echo.models.agnostic.base import Source +from echo.models.agnostic.base import Source, Sink @pytest.mark.parametrize( @@ -48,3 +48,49 @@ def test_source_port_process_initial_value_performs_validation(initial_value, ex 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)) From 3a4c642b13f2d48903e5ff2a4b62d2d1f2db3b28 Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Tue, 15 Sep 2026 14:27:49 +0800 Subject: [PATCH 7/9] Add unit tests exercising pydantic validation of Port subclasses --- src/echo/validators.py | 2 +- tests/unit/models/agnostic/test_base.py | 2 +- tests/unit/models/agnostic/test_bounded.py | 40 +++++++ tests/unit/models/agnostic/test_controlled.py | 40 +++++++ tests/unit/models/agnostic/test_flex.py | 21 ++++ tests/unit/models/agnostic/test_storage.py | 102 ++++++++++++++++++ tests/unit/test_validators.py | 2 +- 7 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 tests/unit/models/agnostic/test_bounded.py create mode 100644 tests/unit/models/agnostic/test_controlled.py create mode 100644 tests/unit/models/agnostic/test_flex.py create mode 100644 tests/unit/models/agnostic/test_storage.py diff --git a/src/echo/validators.py b/src/echo/validators.py index ace29535..888cf9b1 100644 --- a/src/echo/validators.py +++ b/src/echo/validators.py @@ -1,6 +1,6 @@ from collections.abc import Generator -from typing import Any from numbers import Number +from typing import Any import numpy as np from pydantic import Field diff --git a/tests/unit/models/agnostic/test_base.py b/tests/unit/models/agnostic/test_base.py index f17469c1..f0aa0d31 100644 --- a/tests/unit/models/agnostic/test_base.py +++ b/tests/unit/models/agnostic/test_base.py @@ -1,7 +1,7 @@ import pytest from pydantic import ValidationError -from echo.models.agnostic.base import Source, Sink +from echo.models.agnostic.base import Sink, Source @pytest.mark.parametrize( 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/test_validators.py b/tests/unit/test_validators.py index 67d1f817..6ad04de3 100644 --- a/tests/unit/test_validators.py +++ b/tests/unit/test_validators.py @@ -1,5 +1,5 @@ -import pytest import numpy as np +import pytest from echo.validators import is_non_negative, is_non_positive From afd03b5c518f8fa299b96528a7bbb81e29d0fdb8 Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Tue, 15 Sep 2026 14:28:54 +0800 Subject: [PATCH 8/9] Fix: BoundedLoad uses correct validator --- CHANGELOG.md | 1 + src/echo/models/agnostic/bounded.py | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) 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/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) From ffea416ca2ac5656cb370783d8348b03bcf950bd Mon Sep 17 00:00:00 2001 From: Mike Turner Date: Wed, 16 Sep 2026 10:25:58 +0800 Subject: [PATCH 9/9] Adds a couple of extra test cases --- tests/unit/test_validators.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_validators.py b/tests/unit/test_validators.py index 6ad04de3..d64f905c 100644 --- a/tests/unit/test_validators.py +++ b/tests/unit/test_validators.py @@ -18,7 +18,8 @@ ({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]), True), # numpy arrays + (np.array([1, 2, 49]), False), # numpy arrays + (np.array([1, 2, -49]), True), (np.array([-1, -2, -49]), True), ], ) @@ -44,7 +45,8 @@ def test_is_non_negative(value, should_raise_value_error): ({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]), True), # numpy arrays + (np.array([-1, -2, -49]), False), # numpy arrays + (np.array([-1, -2, 49]), True), (np.array([1, 2, 49]), True), ], )