diff --git a/CHANGELOG.md b/CHANGELOG.md index 09676afc..3ce49693 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ #### Adds - Adds support for unconnected (dangling) ports by setting `all_dangling_port` to True. +- Adds support for `ECHO_DISABLE_PATH_WARNING` environment variable. This is enabled by default when running pytest. +- Adds [attrs](https://www.attrs.org/en/stable/index.html) as a project dependency. #### Changes @@ -16,6 +18,12 @@ - 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. +- Major: Migrated the codebase from pydantic V1 to [attrs](https://www.attrs.org/en/stable/index.html). See [Attrs Migration Guide](https://github.com/bsgip/echo/blob/main/attrs-migration.md) for more details. +- The ArrayType Class is replaced by a type alias (this was necessary for the migration from pydantic to attrs) + +#### Removes + +- Pydantic project dependency. ## Releases diff --git a/attrs-migration.md b/attrs-migration.md new file mode 100644 index 00000000..836d652c --- /dev/null +++ b/attrs-migration.md @@ -0,0 +1,177 @@ +# Attrs Migration + +This document covers what you need to know about migrating from [pydantic V1](https://pydantic.dev/docs/validation/1.10/overview/) to [attrs](https://www.attrs.org/en/stable/) and some hints about working productively with attrs going forward. + +## Justification + +Attrs is a much simpler way to do validation for `echo` without all the funny business/magic that pydantic introduces. + +- There is no copying of objects behind your back when you mutate an object. +- Attrs uses a decorator on the class and creates the initialiser (`__init__`) for you. It also adds `__repr__` and `__eq__` for you. It gives you a few hooks for e.g. `__attrs_post_init__` that allow you to customize the process if required. +- There is no messing with class hierarchy. Attrs doesn't use inheritance for this reason. It uses a decorator instead. That means the only inheritance in your classes is the one you put there. + +## How to migrate from Pydantic to Attrs + +The following list is a brief description of how `echo` was migrated from pydantic to attrs. This is only meant to illustrative. Reading the echo code and seeing the changes made is the best way to understand migration. + +- Remove all inheritance from pydantics `BaseModel`. Use attrs `@define` decorator on each class instead. +- Replace `Field` with `field` (attrs field helper) + - If using factories for default values, replace `default_factory` with `factory`. +- Make sure all attributes have type annotations (See [Gotcha 1](#attrs-gotchas)). +- Replace attribute default values with one of the following ways of doing defaults in attrs: + - directly on the instance variable `a: int = 1` (this is the same as pydantic) + - using the field helper with a default `a: int = field(default=1)` + - using the field helper with a factory `a: int = field(factory=list)` + - using a separate declaration `@a.default...`. Example: `@port_name.default` on `Port` class. These can be particularly useful when the attributes default value depends on other attributes. +- Replace pydantic validating type annotations (PositiveInt, NonNegativeFloat etc.) with attrs built-in validators. + - For example `a: NonNegativeFloat` becomes `a: int = field(..., validator=validators.ge(0))`. This is one of the most common changes made in `echo`. The following table shows the relationship between pydantic type annotations (that trigger validation) and attrs equivalent validators: + +| pydantic type annotation | attrs equivalent validator | +| --- | --- | +| `PositiveFloat` | `validators.gt(0)` | +| `NegativeFloat` | `validators.lt(0)` | +| `NonPositiveFloat` | `validators.le(0)` | +| `NonNegativeFloat` | `validators.ge(0)` | +| `PositiveFloat\|None` | `validators.optional(validators.gt(0))` | +| `NegativeFloat\|None` | `validators.optional(validators.lt(0))` | +| `NonPositiveFloat\|None` | `validators.optional(validators.le(0))` | +| `NonNegativeFloat\|None` | `validators.optional(validators.ge(0))` | + +- Replace pydantic `@validator`s + - use the field helper `b: int = field(..., validator=my_custom_validator)` or decorator `@a.validator...`. Example: `@time_periods.validator` on `Window` class. +- ~~Replace root validators with calls the validator in `__attrs_post_init__`.~~ This will only validate on instance creation and not each time the attribute is set. See below for a better approach. +- Replace root validators with validators on each of the attributes involved in the relationship. Example: `reset_periods_validator` and `import_or_export_demand_set_validator` on `DemandCharge` class. + +In addition to the above changes, it was also necessary to replace all references to pydantic's `ValidationError` with python's `ValueError` across the unit tests. + +## Attrs Gotchas + +Pydantic does a lot of magic behind the scenes to make your life "easier". Attrs is much simpler but this means you are often required to do a few things manually or be a bit more thoughtful/careful when using it. Here a few attrs gotchas to be aware of. + +### Gotcha 1: Forgetting to add type annotations to attributes + +Always use type annotations on *all* attributes. Don't forgot to use type annotations on attributes that a defined with attr's `field` specifier. + +The short explanation is that type annotations indicate to attrs that an attribute is an instance variable (rather than a class variable). This might seem strange at first but is in fact how [dataclasses](https://docs.python.org/3/library/dataclasses.html) work. + +### Gotcha 2: Forgetting to add type annotations when overriding attributes in subclasses + +Any time we want to change the behaviour of an attribute in a subclass (whether that is setting a new default as above, or adding a validator etc.) we need to remember all the full attribute definition. + +The reasons for this is the same reason as gotcha 1. + +Let's say we want to override the default value of attribute `b` in a subclass, + +```python +@define +class ParentClass(): + b: int = 2 + +@define +class ChildClass(ParentClass): + b = 999 +``` + +In attrs this code won't work how you expect. In fact the `b = 999` which have no effect at all! + +Instead we need the full attribute definition in the subclass (i.e. with the type annotation), + +```python +@define +class ParentClass(): + b: int = 2 + +@define +class ChildClass(ParentClass): + b: int = 999 +``` + +### Gotcha 3: Forgetting to add `@define` to subclasses + +In general you always want to decorate subclasses with `@define`. + +This is a must if the subclass adds new attributes or overrides the behaviour of attributes (See gotchas 1 and 2). + +In the following example, `b` will have a default value of 2 even with instances of `ChildClass`. + +```python +@define +class ParentClass(): + b: int = 2 + +# ChildClass missing @define +class ChildClass(ParentClass): + b: int = 999 +``` + +Technically this doesn't seem to be necessary on subclasses that only add new methods or override methods. In this case it's still preferable to used `@define`. Some else could subclass your class and without the decorator any attributes they define would get ignored. + +### Gotcha 4: Error messages about attribute ordering/default values + +When working with attrs it is common is see the following warning message in your IDE: + +> Fields without default values cannot appear after fields with default values + +To understand what happening let's look at an example, + +```python +@define +class Parent: + a: int + b: bool = True + +@define +class Child(Parent): + c: str +``` + +Here we have a two classes with a `Child` inheriting from `Parent`. Let's recreate the `__init__` method for `Child` that attrs will make for us, + +```python +def __init__(a: int, b: bool = True, c: str): + ... +``` + +Here `a`, `b` and `c` are all positional arguments. + +Now we can see the problem. Argument `c` comes after `b` which has a default value. Positional arguments are not allowed to come after arguments with defaults in python. + +There are two ways to fix this: + +1. Supply a default value for the attribute or, +2. Make the attribute keyword only. + +Applying these solutions to our example gives us: + +```python +@define +class Child(Parent): + c: str = "default-value" + # c: str | None = None # this is another approach +``` + +or, + +```python +@define +class Child(Parent): + c: str = field(kw_only=True) +``` + +### Gotcha 5: Extra attributes + +Pydantic allows extra attributes to be attached to instances when the appropriate configuration is used, + +```py +class BaseModel(PydanticBaseModel): + """Create a modified base model with the config we want.""" + + class Config: + validate_assignment = True + extra = "ignore" # <- this attribute allows extra attributes on any model + arbitrary_types_allowed = True +``` + +Here `extra` configuration option allows this behaviour. + +attrs doesn't have an equivalent and is more pythonic: if you want attributes, then you need to specify explictly on a class. diff --git a/pyproject.toml b/pyproject.toml index 073fdb0c..5b87e636 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,13 +29,13 @@ dependencies = [ "orjson>=3.9,<4", "pandas>=2.1,<3", "plotly>=5.22,<6", - "pydantic>=1.10,<2", "pyomo>=6.6,<7", "scikit-learn>=1.3,<2", "seaborn>=0.12,<1", "shortuuid>=1.0.11,<2", "typing-extensions>=4.7,<5", "scipy>=1.14.1,<2", + "attrs>=26.1.0", ] requires-python = ">= 3.11" authors = [ diff --git a/src/echo/models/agnostic/aggregation.py b/src/echo/models/agnostic/aggregation.py index ab67e87c..8cba3b19 100644 --- a/src/echo/models/agnostic/aggregation.py +++ b/src/echo/models/agnostic/aggregation.py @@ -1,16 +1,17 @@ import pandas as pd import pyomo.environ as en -from pydantic import root_validator +from attrs import define, field from pyomo.core.expr import EqualityExpression from echo.configuration import Units from echo.exceptions import ConfigurationError from echo.models.agnostic.flex import FlexSink -from echo.models.base import Node +from echo.models.base import Node, Port from echo.models.scenario import EchoConcreteModel -from echo.validators import node_unit_validator +from echo.validators import ports_have_same_units_validator, ports_match_nominal_units_validator +@define class AggregationNode(Node): """Arbitrary commodity aggregation node. @@ -18,9 +19,12 @@ class AggregationNode(Node): port_units attribute is used for validation, all ports must be the same commodity. """ - port_units: Units + port_units: Units = field(kw_only=True) + ports: dict[str, Port] = field( + factory=dict, validator=[ports_have_same_units_validator, ports_match_nominal_units_validator] + ) - aggregator_unit_check = root_validator(allow_reuse=True)(node_unit_validator) + # aggregator_unit_check = root_validator(allow_reuse=True)(node_unit_validator) @property def total(self) -> None: diff --git a/src/echo/models/agnostic/base.py b/src/echo/models/agnostic/base.py index 12499ce1..a049b6c8 100644 --- a/src/echo/models/agnostic/base.py +++ b/src/echo/models/agnostic/base.py @@ -1,5 +1,5 @@ import numpy as np -from pydantic import validator +from attrs import define, field from echo.configuration import FlowConstraint, Flows, OptimisationType from echo.models.base import Port @@ -7,29 +7,29 @@ TimeExpandableType, ) from echo.validators import ( - nonnegative_load, - nonpositive_generation, + nonnegative_load_validator, + nonpositive_generation_validator, ) +@define class FixedPort(Port): """Fixed port (parameter), can either import or export.""" - flows = Flows.Both - import_constraint = FlowConstraint.NoConstraint - export_constraint = FlowConstraint.NoConstraint - flow_type = OptimisationType.Parameter + flows: Flows = Flows.Both + import_constraint: FlowConstraint = FlowConstraint.NoConstraint + export_constraint: FlowConstraint = FlowConstraint.NoConstraint + flow_type: OptimisationType = OptimisationType.Parameter +@define class Source(Port): """A fixed source of a commodity.""" - flows = Flows.Export - export_constraint = FlowConstraint.NoConstraint - flow_type = OptimisationType.Parameter - - # Source should have non positive initial values - non_pos_check = validator("initial_value", allow_reuse=True)(nonpositive_generation) + flows: Flows = Flows.Export + export_constraint: FlowConstraint = FlowConstraint.NoConstraint + flow_type: OptimisationType = OptimisationType.Parameter + initial_value: dict[tuple[int, int], float] | float = field(default=0, validator=nonpositive_generation_validator) def add_source_profile(self, source_values: dict) -> None: self.set_initial_value(source_values) @@ -45,16 +45,15 @@ def add_source_profile_from_array( ) +@define class Sink(Port): """A fixed sink for a commodity.""" - flows = Flows.Import - import_constraint = FlowConstraint.NoConstraint - flow_type = OptimisationType.Parameter + flows: Flows = Flows.Import + import_constraint: FlowConstraint = FlowConstraint.NoConstraint + flow_type: OptimisationType = OptimisationType.Parameter - non_neg_check = validator("initial_value", allow_reuse=True)( - nonnegative_load - ) # Sink should have non negative initial values + initial_value: dict[tuple[int, int], float] | float = field(default=0, validator=nonnegative_load_validator) def add_sink_profile(self, sink_values: dict[tuple[int, int], float]) -> None: self.set_initial_value(sink_values) @@ -71,6 +70,7 @@ def add_sink_profile_from_array( ) +@define class Demand(Sink): def add_demand_profile(self, demand: dict) -> None: self.set_initial_value(demand) diff --git a/src/echo/models/agnostic/bounded.py b/src/echo/models/agnostic/bounded.py index 50981f67..0142e46e 100644 --- a/src/echo/models/agnostic/bounded.py +++ b/src/echo/models/agnostic/bounded.py @@ -1,5 +1,5 @@ import pandas as pd -from pydantic import root_validator, validator +from attrs import define, field from echo.configuration import FlowConstraint from echo.models.agnostic.flex import FlexPort @@ -10,18 +10,17 @@ ) from echo.validators import ( ArrayType, - check_bound_order, - nonnegative_load, + bound_order_validator, + nonnegative_load_validator, ) +@define class BoundedPort(FlexPort): """A flex port with an upper and lower bound""" - upper_bound: ArrayType | float - lower_bound: ArrayType | float - - bound_check = root_validator(allow_reuse=True)(check_bound_order) # check lower bound < upper bound + upper_bound: ArrayType | float = field(kw_only=True, validator=bound_order_validator) + lower_bound: ArrayType | float = field(kw_only=True, validator=bound_order_validator) def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: super().add_port_to_model(model, profile) @@ -31,14 +30,14 @@ def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> set_var_bounds_from_dict(model=model, var_name=self.port_name, ub=ub_dict, lb=lb_dict) +@define class BoundedLoad(BoundedPort): """A port where the load has to be within a max and min value which is specified at each timestep.""" - import_constraint = FlowConstraint.NoConstraint + import_constraint: FlowConstraint = FlowConstraint.NoConstraint - # Do additional validation to make sure both bounds are >= 0 - upper_bound_check = validator("upper_bound", allow_reuse=True)(nonnegative_load) - lower_bound_check = validator("lower_bound", allow_reuse=True)(nonnegative_load) + upper_bound: ArrayType | float = field(kw_only=True, validator=[nonnegative_load_validator, bound_order_validator]) + lower_bound: ArrayType | float = field(kw_only=True, validator=[nonnegative_load_validator, bound_order_validator]) 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/controlled.py b/src/echo/models/agnostic/controlled.py index 45c0fca4..211f9f73 100644 --- a/src/echo/models/agnostic/controlled.py +++ b/src/echo/models/agnostic/controlled.py @@ -1,6 +1,7 @@ +import attrs import pandas as pd import pyomo.environ as en -from pydantic import Field +from attrs import define, field from pyomo.core.expr import InequalityExpression from echo.configuration import Flows, Units @@ -11,6 +12,7 @@ ) +@define class ControlledLoadOrGen(FlexPort): """ A controlled load or generation has a max/min power, as well as a max/min utilisation. @@ -20,11 +22,11 @@ class ControlledLoadOrGen(FlexPort): and the maximum energy that could be consumed/generated if the load operated at max power. """ - min_utilisation: float | None = None - max_utilisation: float | None = None - max_power: float | None = None - min_power: float | None = None - units: Units = Units.KW + min_utilisation: float | None = field(default=None) + max_utilisation: float | None = field(default=None) + max_power: float | None = field(default=None) + min_power: float | None = field(default=None) + units: Units = field(default=Units.KW) def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: super().add_port_to_model(model, profile) @@ -81,13 +83,15 @@ def sum_of_energy_must_be_less_than_max(model: EchoConcreteModel) -> InequalityE ) +@define class ControlledLoad(ControlledLoadOrGen): - max_power: float = Field(ge=0) - min_power: float = Field(ge=0) + max_power: float = field(kw_only=True, validator=attrs.validators.ge(0)) + min_power: float = field(kw_only=True, validator=attrs.validators.ge(0)) flows = Flows.Import +@define class ControlledGen(ControlledLoadOrGen): - max_power: float = Field(le=0) - min_power: float = Field(le=0) + max_power: float = field(kw_only=True, validator=attrs.validators.le(0)) + min_power: float = field(kw_only=True, validator=attrs.validators.le(0)) flows = Flows.Export diff --git a/src/echo/models/agnostic/flex.py b/src/echo/models/agnostic/flex.py index 2671a613..994a9cf9 100644 --- a/src/echo/models/agnostic/flex.py +++ b/src/echo/models/agnostic/flex.py @@ -1,44 +1,46 @@ import pandas as pd import pyomo.environ as en -from pydantic import root_validator +from attrs import define, field 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, + bound_order_validator, ) +@define class FlexPort(Port): """Flexible variable port, which can import and export without constraints.""" - flows = Flows.Both - import_constraint = FlowConstraint.NoConstraint - export_constraint = FlowConstraint.NoConstraint - flow_type = OptimisationType.Variable + flows: Flows = Flows.Both + import_constraint: FlowConstraint = FlowConstraint.NoConstraint + export_constraint: FlowConstraint = FlowConstraint.NoConstraint + flow_type: OptimisationType = OptimisationType.Variable +@define class FlexSink(FlexPort): """Flexible port, imports only""" - flows = Flows.Import + flows: Flows = Flows.Import +@define class FlexSource(FlexPort): """Flexible ports, exports only""" - flows = Flows.Export + flows: Flows = Flows.Export +@define 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 + lower_bound: float = field(kw_only=True, validator=bound_order_validator) + upper_bound: float = field(kw_only=True, validator=bound_order_validator) @property def active(self) -> str: diff --git a/src/echo/models/agnostic/input_output.py b/src/echo/models/agnostic/input_output.py index 34029cb7..e63fd221 100644 --- a/src/echo/models/agnostic/input_output.py +++ b/src/echo/models/agnostic/input_output.py @@ -1,8 +1,11 @@ +from attrs import define, field + from echo.configuration import Units from echo.models.agnostic.flex import FlexPort from echo.models.base.node import Node +@define class InputOutputNode(Node): """ An input-output node has one input port and one output port. @@ -11,18 +14,17 @@ class InputOutputNode(Node): # TODO: This Node does not do anything, unnecessary inheritance - input_port_unit: Units - output_port_unit: Units + input_port_unit: Units = field(kw_only=True) + output_port_unit: Units = field(kw_only=True) # Optional parameters for controlling input/output port flows - max_output: float | None # output might be neg or pos, leave it open - min_output: float | None - max_input: float | None - min_input: float | None + max_output: float | None = None # output might be neg or pos, leave it open + min_output: float | None = None + max_input: float | None = None + min_input: float | None = None input_port_ref: str = "input" output_port_ref: str = "output" - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: # Create an input port and an output port with the correct units self.ports[self.input_port_ref] = FlexPort(units=self.input_port_unit) self.ports[self.output_port_ref] = FlexPort(units=self.output_port_unit) diff --git a/src/echo/models/agnostic/storage.py b/src/echo/models/agnostic/storage.py index 7bb6a1a1..cc9c91d5 100644 --- a/src/echo/models/agnostic/storage.py +++ b/src/echo/models/agnostic/storage.py @@ -1,10 +1,12 @@ +from types import NoneType + +import attrs import pandas as pd import pyomo.environ as en -from pydantic import PositiveFloat, root_validator +from attrs import define, field from pyomo.core.expr import EqualityExpression, InequalityExpression from echo.configuration import FlowConstraint, Flows, OptimisationType -from echo.exceptions import validate from echo.models.base import Port from echo.models.scenario import EchoConcreteModel from echo.utils import ( @@ -15,30 +17,35 @@ ) from echo.validators import ( ArrayType, - dod_checks, + depth_of_discharge_validator, + soc_conserv_validator, + update_constraint_values, ) +@define class Storage(Port): """Same as old storage but without all the EV attributes""" - flows = Flows.Both - flow_type = OptimisationType.Variable - import_constraint = FlowConstraint.Fixed - export_constraint = FlowConstraint.Fixed - max_capacity: float - depth_of_discharge_limit: float = 0 # DoD limit is the percent soc to which you can discharge the storage - min_soc: float = 0 - charging_power_limit: float - discharging_power_limit: float - charging_efficiency: float = 1 - discharging_efficiency: float = 1 - fixed_storage_capacity: bool = True - storage_capacity_cost: PositiveFloat | None = None - regularise: bool = False - initial_state_of_charge: float | None - - dod_check = root_validator(allow_reuse=True)(dod_checks) + flows: Flows = Flows.Both + flow_type: OptimisationType = OptimisationType.Variable + import_constraint: FlowConstraint = FlowConstraint.Fixed + export_constraint: FlowConstraint = FlowConstraint.Fixed + max_capacity: float = field(kw_only=True, validator=depth_of_discharge_validator) + depth_of_discharge_limit: float = field( + default=0, validator=depth_of_discharge_validator + ) # DoD limit is the percent soc to which you can discharge the storage + min_soc: float = field(default=0) + charging_power_limit: float = field(kw_only=True, validator=update_constraint_values) + discharging_power_limit: float = field(kw_only=True, validator=update_constraint_values) + charging_efficiency: float = field(default=1) + discharging_efficiency: float = field(default=1) + fixed_storage_capacity: bool = field(default=True) + storage_capacity_cost: float | None = field( + default=None, validator=attrs.validators.or_(attrs.validators.instance_of(NoneType), attrs.validators.gt(0)) + ) + regularise: bool = field(default=False) + initial_state_of_charge: float | None = field(default=None, kw_only=True) @property def soc_value(self) -> str: @@ -52,11 +59,6 @@ def optimised_capacity(self) -> str: def soc_constraint(self) -> str: return "soc_cons_" + self.port_name - def __init__(self, **data) -> None: - super().__init__(**data) - self.import_constraint_value = self.charging_power_limit - self.export_constraint_value = self.discharging_power_limit - def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: super().add_port_to_model(model, profile) self.create_storage_variables(model) @@ -158,17 +160,18 @@ def add_objective(self, model: EchoConcreteModel) -> None: self.objective += total +@define class MobileStorage(Storage): """New Storage + EV attributes""" # next variable is for allowing soc to go below min so as to avoid optimisation failing if there infeasible ev trips - enable_trip_slack: bool = False + enable_trip_slack: bool = field(default=False) # next three variables are for having a 'conservative' ev user lower bound on the soc while it is plugged in # soc_conserv: Union[ArrayType,list,float, None, dict] = None - soc_conserv: TimeExpandableType | None = None - soc_conserv_cost: float | None = None + soc_conserv: TimeExpandableType | None = field(default=None, validator=soc_conserv_validator) + soc_conserv_cost: float | None = field(default=None, validator=soc_conserv_validator) # soc_conserve: scalarOrArray - available: ArrayType | list | None = None + available: ArrayType | list | None = field(default=None, validator=soc_conserv_validator) @property def cons_slack(self) -> str: @@ -178,16 +181,6 @@ def cons_slack(self) -> str: def trip_slack(self) -> str: return "trip_slack_" + self.port_name - @root_validator - def check_soc_conserv_has_cost(cls, values: dict) -> dict: - soc_conserv = values.get("soc_conserv") - soc_conserv_cost = values.get("soc_conserv_cost") - available = values.get("available") - if soc_conserv is not None: - validate(soc_conserv_cost is not None, "soc_conserv requires soc_conserv_cost") - validate(available is not None, "soc_conserve requires available") - return values - def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None: super(Storage, self).add_port_to_model(model, profile) self.create_storage_variables(model) diff --git a/src/echo/models/agnostic/tellegen/base.py b/src/echo/models/agnostic/tellegen/base.py index 774ea75f..d643571b 100644 --- a/src/echo/models/agnostic/tellegen/base.py +++ b/src/echo/models/agnostic/tellegen/base.py @@ -1,19 +1,20 @@ import pyomo.environ as en -from pydantic import root_validator +from attrs import define, field from pyomo.core.expr import EqualityExpression from echo.exceptions import validate -from echo.models.base import Node +from echo.models.base import Node, Port from echo.models.scenario import EchoConcreteModel from echo.validators import ( - node_unit_validator, + ports_have_same_units_validator, ) +@define class TellegenNode(Node): """A node that implements a Tellegen constraint requiring that port values sum to zero.""" - tellegen_unit_check = root_validator(allow_reuse=True)(node_unit_validator) + ports: dict[str, Port] = field(factory=dict, validator=ports_have_same_units_validator) def apply_node_constraints(self, model: EchoConcreteModel) -> None: def tellegen_node_rule(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression: diff --git a/src/echo/models/agnostic/tellegen/multi_commodity.py b/src/echo/models/agnostic/tellegen/multi_commodity.py index 8abfd00e..f72cf920 100644 --- a/src/echo/models/agnostic/tellegen/multi_commodity.py +++ b/src/echo/models/agnostic/tellegen/multi_commodity.py @@ -2,12 +2,14 @@ from functools import partial import pyomo.environ as en +from attrs import define from pyomo.core.expr import EqualityExpression from echo.models.base import Node, Port from echo.models.scenario import EchoConcreteModel +@define class MultiCommodityTellegenNode(Node): """ A node with ports that have multiple commodities. diff --git a/src/echo/models/agnostic/tellegen/partitioned_multi_commodity.py b/src/echo/models/agnostic/tellegen/partitioned_multi_commodity.py index decba63d..04d9302b 100644 --- a/src/echo/models/agnostic/tellegen/partitioned_multi_commodity.py +++ b/src/echo/models/agnostic/tellegen/partitioned_multi_commodity.py @@ -2,30 +2,26 @@ from functools import partial import pyomo.environ as en -from pydantic import Field, root_validator +from attrs import define, field from pyomo.core.expr import EqualityExpression from echo.exceptions import ConfigurationError from echo.models.base import Node, Port from echo.models.scenario import EchoConcreteModel -from echo.validators import ( - validate_partition_ports, -) +from echo.validators import partitions_port_validator +@define class PartitionedMultiCommodityTellegenNode(Node): """ A node with partitions of ports, ports in each partition may have multiple commodities. A tellegen constraint is applied per partition per commodity. """ - partitions: dict[str, list[Port]] = Field(default_factory=dict) + partitions: dict[str, list[Port]] = field(factory=dict, validator=partitions_port_validator) default_partition: str = "default_partition" - partition_port_uniqueness_check = root_validator(allow_reuse=True)(validate_partition_ports) - - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: if len(self.ports): if len(self.partitions): raise ValueError( diff --git a/src/echo/models/agnostic/tellegen/three_way_valve.py b/src/echo/models/agnostic/tellegen/three_way_valve.py index 594c00d4..cf0df235 100644 --- a/src/echo/models/agnostic/tellegen/three_way_valve.py +++ b/src/echo/models/agnostic/tellegen/three_way_valve.py @@ -1,5 +1,6 @@ import pandas as pd import pyomo.environ as en +from attrs import define, field from pyomo.core.expr import InequalityExpression from echo.configuration import Units @@ -8,6 +9,7 @@ from echo.models.scenario import EchoConcreteModel +@define class ThreeWayValveNode(TellegenNode): """A node that implements a Tellegen constraint requiring that port values sum to zero. @@ -16,7 +18,7 @@ class ThreeWayValveNode(TellegenNode): At each time the flow is allowed through only one output port. """ - units: Units + units: Units = field(kw_only=True) input_port_name: str = "input_port" output_port_name_1: str = "output_port_1" output_port_name_2: str = "output_port_2" @@ -24,6 +26,9 @@ class ThreeWayValveNode(TellegenNode): # Tuple of two port names on the Node, non-zero flow through only one of the port allowed at any time mutually_exclusive_port_flows: tuple[str, str] = None + def __attrs_post_init__(self) -> None: + self.create_ports() + @property def binary_variable_flow_through_mutually_exclusive_port_1(self) -> str: return f"binary_variable_flow_through_mutually_exclusive_{self.output_port_name_1}_{self.node_name}" @@ -44,10 +49,6 @@ def constraint_neg_flow_mutually_exclusive_port_2(self) -> str: def constraint_pos_flow_mutually_exclusive_port_2(self) -> str: return f"constraint_pos_flow_mutually_exclusive_port_{self.output_port_name_2}_{self.node_name}" - def __init__(self, **data) -> None: - super().__init__(**data) - self.create_ports() - def create_ports(self) -> None: # Create input and output ports self.ports[self.input_port_name] = FlexSink(units=self.units) diff --git a/src/echo/models/agnostic/time_delay.py b/src/echo/models/agnostic/time_delay.py index 00a4ff84..1761adac 100644 --- a/src/echo/models/agnostic/time_delay.py +++ b/src/echo/models/agnostic/time_delay.py @@ -1,4 +1,5 @@ import pyomo.environ as en +from attrs import define, field from pyomo.core.expr import InequalityExpression from echo.models.agnostic.flex import FlexSink, FlexSource @@ -6,13 +7,14 @@ from echo.models.scenario import EchoConcreteModel +@define class TimeDelayNode(InputOutputNode): """A time delay node is an input-output node that implements a fixed delay between input and output.""" - time_delay: int # number of time intervals delay between input and output + time_delay: int = field(kw_only=True) # number of time intervals delay between input and output - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() self.ports["input"] = FlexSink(units=self.input_port_unit) self.ports["output"] = FlexSource(units=self.output_port_unit) diff --git a/src/echo/models/agnostic/time_varying.py b/src/echo/models/agnostic/time_varying.py index 9adddb6d..4ccdf123 100644 --- a/src/echo/models/agnostic/time_varying.py +++ b/src/echo/models/agnostic/time_varying.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import root_validator +from attrs import define, field from echo.exceptions import validate from echo.models.agnostic.input_output import InputOutputNode @@ -10,11 +10,12 @@ set_float_var_bounds, ) from echo.validators import ( - set_bounds_from_piecewise_points, - validate_piecewise_arrays, + piecewise_arrays_validator, + set_bounds_from_piecewise_points_validator, ) +@define class TimeVaryingPiecewiseIONode(InputOutputNode): """A Node with an input and output and time varying piecewise relationship between input and output. @@ -23,15 +24,25 @@ class TimeVaryingPiecewiseIONode(InputOutputNode): Attributes input_port_unit and output_port_unit define node's commodity. """ - input_points: dict | None # dict where the keys are planning-time period tuple, and value is input pt array - output_points: dict | None # dict where the keys are planning-time period tuple, and value is output pt array - input_points_ref: str | None # Ref to profile dataframe column with input points array to be used across all times - output_points_ref: str | None # Ref to profile dataframe column with input points array to be used across all times + # dict where the keys are planning-time period tuple, and value is input pt array + input_points: dict | None = field( + default=None, validator=[piecewise_arrays_validator, set_bounds_from_piecewise_points_validator] + ) - piecewise_check = root_validator(allow_reuse=True)(validate_piecewise_arrays) # validate input/output points - populate_bounds = root_validator(allow_reuse=True)( - set_bounds_from_piecewise_points - ) # set attributes max_output, min_output, max_input, min_input from input points/output points + # dict where the keys are planning-time period tuple, and value is output pt array + output_points: dict | None = field( + default=None, validator=[piecewise_arrays_validator, set_bounds_from_piecewise_points_validator] + ) + + input_points_ref: str | None = ( + None # Ref to profile dataframe column with input points array to be used across all times + ) + output_points_ref: str | None = ( + None # Ref to profile dataframe column with input points array to be used across all times + ) + + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() def verify_points_values(self) -> None: validate(self.input_points is not None, "No input points defined") diff --git a/src/echo/models/base/__init__.py b/src/echo/models/base/__init__.py index 4362103c..9dadf1b5 100644 --- a/src/echo/models/base/__init__.py +++ b/src/echo/models/base/__init__.py @@ -1,4 +1,3 @@ -from echo.models.base.base_model import BaseModel from echo.models.base.edge import Edge from echo.models.base.node import Node from echo.models.base.optimisation_graph import OptimisationGraph @@ -8,7 +7,6 @@ from echo.models.base.types import ConstraintValueType, InitialValue, InitialValueInput __all__ = [ - "BaseModel", "Edge", "Node", "OptimisationGraph", diff --git a/src/echo/models/base/base_model.py b/src/echo/models/base/base_model.py deleted file mode 100644 index 92874d6d..00000000 --- a/src/echo/models/base/base_model.py +++ /dev/null @@ -1,10 +0,0 @@ -from pydantic import BaseModel as PydanticBaseModel - - -class BaseModel(PydanticBaseModel): - """Create a modified base model with the config we want.""" - - class Config: - validate_assignment = True # Set to true so that we re-validate when we update a model field - extra = "ignore" # extra attributes are ignored - arbitrary_types_allowed = True diff --git a/src/echo/models/base/edge.py b/src/echo/models/base/edge.py index 8e63b47b..b62f26cf 100644 --- a/src/echo/models/base/edge.py +++ b/src/echo/models/base/edge.py @@ -2,33 +2,33 @@ import pyomo.environ as en import shortuuid -from pydantic import Field +from attrs import define, field from pyomo.core.expr.relational_expr import EqualityExpression from echo.configuration import Flows from echo.exceptions import ConfigurationError -from echo.models.base import BaseModel from echo.models.base.port import Port from echo.models.base.types import ConstraintValueType from echo.models.scenario import EchoConcreteModel -class Edge(BaseModel): +@define +class Edge: """ Edges are used to connect nodes. For an edge (x, y) where x and y are nodes, the edge value is equal to the flow from x->y plus the flow from y->x. """ - uid: str = Field(default_factory=shortuuid.uuid) - edge_name: str | None = None vertices: tuple[Port, Port] - nodes: tuple[str, str] | None # tuple of node names - todo make this required - tariff: list | None | None + nodes: tuple[str, str] | None = None # tuple of node names - todo make this required + tariff: list | None = None - def __init__(self, **data) -> None: - super().__init__(**data) - if self.edge_name is None: - self.edge_name = "edge_" + str(self.uid) + uid: str = field(factory=shortuuid.uuid) + edge_name: str = field() + + @edge_name.default + def _set_edge_name_default(self) -> str: + return "edge_" + str(self.uid) def add_vertices(self, obj1: Port, obj2: Port) -> None: """Adds edge vertices (which are ports on nodes) diff --git a/src/echo/models/base/node.py b/src/echo/models/base/node.py index 85333be9..f645cda2 100644 --- a/src/echo/models/base/node.py +++ b/src/echo/models/base/node.py @@ -5,34 +5,34 @@ import pandas as pd import pyomo.environ as en import shortuuid -from pydantic import Field +from attrs import define, field from echo.exceptions import ConfigurationError -from echo.models.base import BaseModel from echo.models.base.port import Port from echo.models.scenario import EchoConcreteModel -class Node(BaseModel): +@define +class Node: """ Nodes are collections of one or more ports that can include non-trivial relationships between the ports, this allows transformations to be implemented. """ - node_name: str = "" - uid: str = Field(default_factory=shortuuid.uuid) - ports: dict[str, Port] = {} - objective: en.numeric_expr.NumericExpression | float = 0 # For adding any node objectives + uid: str = field(factory=shortuuid.uuid) + node_name: str = field() + + @node_name.default + def _set_node_name_default(self) -> str: + return "node_" + str(self.uid) + + ports: dict[str, Port] = field(factory=dict) + objective: en.numeric_expr.NumericExpression | float = field(default=0) # For adding any node objectives @property def inflow(self) -> str: return f"inflow_{self.node_name}" - def __init__(self, **data) -> None: - super().__init__(**data) - if not self.node_name: - self.node_name = "node_" + str(self.uid) - def add_port(self, name: str, port: Port) -> None: if self.ports.get(name) is None: self.ports[name] = port diff --git a/src/echo/models/base/optimisation_graph.py b/src/echo/models/base/optimisation_graph.py index 6991889d..569cd4e8 100644 --- a/src/echo/models/base/optimisation_graph.py +++ b/src/echo/models/base/optimisation_graph.py @@ -1,17 +1,18 @@ from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749) import copy +import os import warnings from typing import cast import matplotlib import networkx as nx import pyomo.environ as en +from attrs import define, field from pyomo.core.expr.relational_expr import EqualityExpression, InequalityExpression from echo.configuration import Units from echo.exceptions import ConfigurationError, validate -from echo.models.base import BaseModel from echo.models.base.edge import Edge from echo.models.base.node import Node from echo.models.base.path import Path @@ -20,13 +21,11 @@ from echo.validators import ArrayType -class OptimisationGraph(BaseModel): - node_obj: dict[str, Node] = {} # Nodes keyed by their node_name - edge_obj: dict[tuple[str, str], Edge] = {} - paths: dict[tuple, Path] = {} - - def __init__(self, **data) -> None: - super().__init__(**data) +@define +class OptimisationGraph: + node_obj: dict[str, Node] = field(factory=dict) # Nodes keyed by their node_name + edge_obj: dict[tuple[str, str], Edge] = field(factory=dict) + paths: dict[tuple, Path] = field(factory=dict) def node_name_list(self) -> list[str]: return list(self.node_obj.keys()) @@ -239,11 +238,12 @@ def create_path_objects( ) -> None: """Creates path objects according to source/sink lists provided.""" - warnings.warn( - "Path tracing is still experimental. If you are generating paths to use path tariffs, please consider " - + "whether you can convert these tariffs to point/port tariffs.", - stacklevel=1, - ) + if os.environ["ECHO_DISABLE_EXPERIMENTAL_PATH_WARNING"] != "1": + warnings.warn( + "Path tracing is still experimental. If you are generating paths to use path tariffs, please consider " + + "whether you can convert these tariffs to point/port tariffs.", + stacklevel=1, + ) all_paths = {} graph = self.convert_to_nx() diff --git a/src/echo/models/base/path.py b/src/echo/models/base/path.py index ce9f7ea9..1895f658 100644 --- a/src/echo/models/base/path.py +++ b/src/echo/models/base/path.py @@ -2,36 +2,41 @@ import pyomo.environ as en import shortuuid -from pydantic import Field +from attrs import define, field from echo.configuration import Units -from echo.models.base import BaseModel from echo.models.base.port import Port from echo.models.scenario import EchoConcreteModel -class Path(BaseModel): +@define +class Path: """A path is a sequence of distinct vertices (nodes).""" - edge_ports: list[tuple[Port, Port]] = [] # list of edge name tuples vertices: list # list of node names - uid: str = Field(default_factory=shortuuid.uuid) - path_name: str | None = None - units = Units.KW + + edge_ports: list[tuple[Port, Port]] = field(factory=list) # list of edge name tuples + units: Units = Units.KW regularise: bool = False objective: en.numeric_expr.NumericExpression | float = 0 - flow_value: str = "" - contingency_neg: str | None - contingency_pos: str | None - path_tariff: str | None - slack: str | None - - def __init__(self, **data) -> None: - super().__init__(**data) - if self.path_name is None: - self.path_name = "path_" + str(self.uid) - self.flow_value = "flow_value_" + self.path_name + contingency_neg: str | None = None + contingency_pos: str | None = None + path_tariff: str | None = None + slack: str | None = None + + uid: str = field(factory=shortuuid.uuid) + path_name: str = field() + + @path_name.default + def _set_path_name_default(self) -> str: + return "path_" + str(self.uid) + + flow_value: str = field() + + @flow_value.default + def _set_flow_value_default(self) -> str: + return "flow_value_" + self.path_name def add_vertices(self, vertex_list: list) -> None: if hasattr(vertex_list[0], "node_name"): diff --git a/src/echo/models/base/port.py b/src/echo/models/base/port.py index 5c19532c..7c2e0bfc 100644 --- a/src/echo/models/base/port.py +++ b/src/echo/models/base/port.py @@ -7,14 +7,13 @@ import pandas as pd import pyomo.environ as en import shortuuid -from pydantic import Field, validator +from attrs import define, field, validators from pyomo.core import RangeSet from pyomo.core.expr.relational_expr import EqualityExpression, InequalityExpression from echo.configuration import FlowConstraint, Flows, OptimisationType, Units from echo.constants import negative_variable_component, positive_variable_component from echo.exceptions import ConfigurationError -from echo.models.base import BaseModel from echo.models.base.types import ConstraintValueType, InitialValue, InitialValueInput from echo.models.scenario import EchoConcreteModel from echo.utils import ( @@ -25,35 +24,46 @@ set_var_bounds_from_dict, to_initial_values, ) -from echo.validators import export_cons_check, import_cons_check +from echo.validators import ( + export_constraint_validator, + import_constraint_validator, +) + +@define +class Port: + uid: str = field(factory=shortuuid.uuid) + port_name: str = field() -class Port(BaseModel): - # Pydantic attribute declaration follows this format: - # attribute_name: type = default_value + @port_name.default + def _set_port_name_default(self) -> str: + return "port_" + str(self.uid) units: Units = Units.NA # Used to ensure that common units are being optimised over at points of interconnection - initial_value: dict[tuple[int, int], float] | None = None + + initial_value: dict[tuple[int, int], float] | float = field(default=0) + initial_value_ref: str | None = None # string ref to df column initial_value_scaling: int | None = None # scaling factor for initial values flow_type: OptimisationType = OptimisationType.NA - uid: str | None = Field(default_factory=shortuuid.uuid) - port_name: str = "" + flows: Flows = Flows.NA # What flow directions are possible (import, export, both) # Used to define the nature of import / export directions and constraints import_constraint: FlowConstraint = FlowConstraint.NA - import_constraint_value: ConstraintValueType | None = None + import_constraint_value: ConstraintValueType | None = field( + default=None, validator=[validators.instance_of(ConstraintValueType | None), import_constraint_validator] + ) + export_constraint: FlowConstraint = FlowConstraint.NA - export_constraint_value: ConstraintValueType | None = None + export_constraint_value: ConstraintValueType | None = field( + default=None, validator=[validators.instance_of(ConstraintValueType | None), export_constraint_validator] + ) + active_periods: dict[tuple[int, int], Any] | None = None slack: bool = False objective: en.numeric_expr.NumericExpression | float = 0 # this will eventually be a pyomo expression allow_dangling_port: bool = False - # Validators for import/export constraint values - import_con_sign = validator("import_constraint_value", allow_reuse=True)(import_cons_check) - export_con_sign = validator("export_constraint_value", allow_reuse=True)(export_cons_check) - @property def pos(self) -> str: return positive_variable_component + self.port_name @@ -90,11 +100,6 @@ def export_slack(self) -> str: def export_slack_max(self) -> str: return f"export_slack_max_{self.port_name}" - def __init__(self, **data) -> None: - super().__init__(**data) - if not self.port_name: # if no name is provided, give it a default name using the uid - self.port_name = "port_" + str(self.uid) - def set_flow_constraints( self, max_import: ConstraintValueType | None, diff --git a/src/echo/models/base/transform.py b/src/echo/models/base/transform.py index 6d04fcce..752a2c08 100644 --- a/src/echo/models/base/transform.py +++ b/src/echo/models/base/transform.py @@ -4,12 +4,11 @@ import pyomo.environ as en import shortuuid -from pydantic import Field +from attrs import define, field from pyomo.core.expr.relational_expr import EqualityExpression from echo.configuration import TransformRule from echo.exceptions import ConfigurationError -from echo.models.base import BaseModel from echo.models.base.node import Node from echo.models.base.port import Port from echo.models.scenario import EchoConcreteModel @@ -27,17 +26,18 @@ class TransformTerm: weight: TimeExpandableType -class Transform(BaseModel): +@define +class Transform: """An object for carrying a generic linear node transformation.""" - uid: str = Field(default_factory=shortuuid.uuid) - lhs: list[TransformTerm] = [] - rhs = 0 + uid: str = field(factory=shortuuid.uuid) + lhs_terms: list[TransformTerm] = field(factory=list) + rhs: en.numeric_expr.NumericExpression | float = 0 - def __init__(self, lhs_terms: list[TransformTerm], **data) -> None: - super().__init__(**data) - if lhs_terms: - self.lhs = lhs_terms + @property + def lhs(self) -> list[TransformTerm]: + """lhs is an alias for lhs_terms""" + return self.lhs_terms @property def transform_name(self) -> str: @@ -51,10 +51,11 @@ def _add_transform_to_model(self, model: EchoConcreteModel) -> None: var.constrain_pos_neg(model) +@define class TransformNode(Node): """Implements node constraints using Transforms""" - transformations: dict[str, Transform] = {} + transformations: dict[str, Transform] = field(factory=dict) def add_transformation(self, transformation_obj: Transform) -> None: """Adds a transformation object to a node. diff --git a/src/echo/models/base/types.py b/src/echo/models/base/types.py index 7b7213fd..3b5efc12 100644 --- a/src/echo/models/base/types.py +++ b/src/echo/models/base/types.py @@ -2,6 +2,6 @@ from echo.validators import ArrayType -ConstraintValueType = ArrayType | float +ConstraintValueType = ArrayType | list | float | int InitialValue = dict[tuple[int, int], int | float] InitialValueInput = InitialValue | list[int | float] | np.ndarray diff --git a/src/echo/models/carbon/aggregation.py b/src/echo/models/carbon/aggregation.py index ea9bfb40..db7b72a3 100644 --- a/src/echo/models/carbon/aggregation.py +++ b/src/echo/models/carbon/aggregation.py @@ -1,11 +1,13 @@ import pandas as pd import pyomo.environ as en +from attrs import define from pyomo.core.expr import EqualityExpression from echo.models.base import Node from echo.models.scenario import EchoConcreteModel +@define class CarbonAggregation(Node): """This node has an additional variable, 'total', which equals the sum of all ports defined on the node.""" diff --git a/src/echo/models/carbon/base.py b/src/echo/models/carbon/base.py index 03b4cdc4..e908f8f4 100644 --- a/src/echo/models/carbon/base.py +++ b/src/echo/models/carbon/base.py @@ -1,20 +1,25 @@ +from attrs import define + from echo.configuration import Flows, Units from echo.models.agnostic import FlexPort +@define class CarbonPort(FlexPort): """A flexible carbon port""" - units = Units.CO2 + units: Units = Units.CO2 +@define class CarbonSource(CarbonPort): """A variable source of CO2""" - flows = Flows.Export + flows: Flows = Flows.Export +@define class CarbonSink(CarbonPort): """A variable sink of CO2""" - flows = Flows.Import + flows: Flows = Flows.Import diff --git a/src/echo/models/electrical/base.py b/src/echo/models/electrical/base.py index cb11775e..832f80a8 100644 --- a/src/echo/models/electrical/base.py +++ b/src/echo/models/electrical/base.py @@ -1,30 +1,37 @@ +from attrs import define + from echo.configuration import ( Units, ) from echo.models.agnostic import BoundedLoad, Demand, FixedPort, FlexPort, Storage +@define class ElectricalDemand(Demand): """Fixed electrical demand.""" - units = Units.KW + units: Units = Units.KW +@define class ElectricalPort(FlexPort): """Flexible electrical port""" - units = Units.KW + units: Units = Units.KW +@define class FixedElectricalPort(FixedPort): """An electrical port with fixed values (parameters). No constraints on whether the port is importing/exporting.""" - units = Units.KW + units: Units = Units.KW +@define class ElectricalStorage(Storage): - units = Units.KW + units: Units = Units.KW +@define class BoundedElectricalLoad(BoundedLoad): - units = Units.KW + units: Units = Units.KW diff --git a/src/echo/models/electrical/ev/base.py b/src/echo/models/electrical/ev/base.py index 2373768c..bafcafc0 100644 --- a/src/echo/models/electrical/ev/base.py +++ b/src/echo/models/electrical/ev/base.py @@ -1,4 +1,5 @@ import numpy as np +from attrs import define, field from echo.configuration import ( EVChargeMode, @@ -16,10 +17,12 @@ from echo.validators import ArrayType +@define class MobileElectricalStorage(MobileStorage): - units = Units.KW + units: Units = Units.KW +@define class EVBase(TransformNode): """Base class for EVV0G, EVV1G and EVV2G. @@ -86,35 +89,33 @@ class EVBase(TransformNode): charge_mode: EVChargeMode | None = None connection_port_name: str = "cp" - ports: dict[str, ElectricalDemand | ElectricalPort | MobileElectricalStorage] = {} + ports: dict[str, ElectricalDemand | ElectricalPort | MobileElectricalStorage] = field(factory=dict) # Battery attributes charging_efficiency: float = 1 - charging_power_limit: float + charging_power_limit: float = field(kw_only=True) depth_of_discharge_limit: float = 0 discharging_efficiency: float = 1 - discharging_power_limit: float + discharging_power_limit: float = field(kw_only=True) enable_trip_slack: bool = False - max_capacity: float + max_capacity: float = field(kw_only=True) soc_conserv: TimeExpandableType | None = None soc_conserv_cost: float | None = None usage_power_limit: float | None = None # Stateful attributes - available: ArrayType | list | None - initial_state_of_charge: float | None - interval_duration: int | None + available: ArrayType | list | None = None + initial_state_of_charge: float | None = None + interval_duration: int | None = None set_stateful_attrs_at_init: bool = True - tod_charging: ArrayType | list | str | None + tod_charging: ArrayType | list | str | None = None usage: ArrayType | list | None = None # Helpful mappings for port names and uids port_dict_name_to_port_name_map: dict[str, str] | None = None port_dict_name_to_port_uid_map: dict[str, str] | None = None - def __init__(self, **data) -> None: - super().__init__(**data) - + def __attrs_post_init__(self) -> None: # If usage_power_limit isn't specified, set it to discharging_power_limit. This is for backwards compatability if self.usage_power_limit is None: self.usage_power_limit = self.discharging_power_limit diff --git a/src/echo/models/electrical/ev/deprecated.py b/src/echo/models/electrical/ev/deprecated.py index b378ec03..4747bfb3 100644 --- a/src/echo/models/electrical/ev/deprecated.py +++ b/src/echo/models/electrical/ev/deprecated.py @@ -2,13 +2,10 @@ import numpy as np import pandas as pd +from attrs import define, field from deprecated import deprecated -from echo.configuration import ( - EVChargeMode, - EVChargeStatus, - TransformRule, -) +from echo.configuration import EVChargeMode, EVChargeStatus, TransformRule from echo.exceptions import validate from echo.models.base import Transform, TransformNode, TransformTerm from echo.models.electrical.base import ElectricalDemand, ElectricalPort @@ -22,21 +19,22 @@ version="2.1.14", reason="Supeseded by EVV0G, EVV1G, EVV2G, EVWithProfile and EVBase classes", ) +@define class EV(TransformNode): charge_mode: EVChargeMode | None = None - available: ArrayType | list | str - usage: ArrayType | list + available: ArrayType | list | str = field(kw_only=True) + usage: ArrayType | list = field(kw_only=True) connection_port_name: str = "cp" tod_charging: ArrayType | list | str | None = None - interval_duration: int + interval_duration: int = field(kw_only=True) # Battery attributes - max_capacity: float + max_capacity: float = field(kw_only=True) depth_of_discharge_limit: float = 0 - charging_power_limit: float - discharging_power_limit: float + charging_power_limit: float = field(kw_only=True) + discharging_power_limit: float = field(kw_only=True) charging_efficiency: float = 1 discharging_efficiency: float = 1 - initial_state_of_charge: float + initial_state_of_charge: float = field(kw_only=True) # next variable is for allowing soc to go below min so as to avoid optimisation failing if there infeasible ev trips trip_slack: bool = False # todo call this 'enable_trip_slack' so we can give it straight to port @@ -44,17 +42,15 @@ class EV(TransformNode): soc_conserv: TimeExpandableType | None = None soc_conserv_cost: float | None = None - V0G_delta: ArrayType | list | None - V0G_SOC: ArrayType | list | None - V0G_trip_infeasibility: ArrayType | list | None - charge_status: EVChargeStatus | None + V0G_delta: ArrayType | list | None = None + V0G_SOC: ArrayType | list | None = None + V0G_trip_infeasibility: ArrayType | list | None = None + charge_status: EVChargeStatus | None = None port_dict_name_to_port_uid_map: dict[str, str] | None = None port_dict_name_to_port_name_map: dict[str, str] | None = None - def __init__(self, **data) -> None: - super().__init__(**data) - + def __attrs_post_init__(self) -> None: # Check that usage is always <= max discharge of battery, otherwise the problem will be infeasible. for i in self.usage: if i > self.discharging_power_limit * -1: @@ -70,15 +66,25 @@ def __init__(self, **data) -> None: if self.port_dict_name_to_port_name_map is None: self.port_dict_name_to_port_name_map = {} - # Preserve uid and port_name if present on port + battery_attributes = [ + "max_capacity", + "depth_of_discharge_limit", + "charging_power_limit", + "discharging_power_limit", + "charging_efficiency", + "discharging_efficiency", + "initial_state_of_charge", + ] + battery_params = {k: getattr(self, k) for k in battery_attributes} if "vehicle" in self.port_dict_name_to_port_uid_map.keys(): + # Preserve uid and port_name if present on port vehicle = MobileElectricalStorage( uid=self.port_dict_name_to_port_uid_map["vehicle"], port_name=self.port_dict_name_to_port_name_map["vehicle"], - **{k: v for k, v in data.items() if k not in ["uid", "port_name"]}, + **battery_params, ) else: - vehicle = MobileElectricalStorage(**data) + vehicle = MobileElectricalStorage(**battery_params) vehicle.enable_trip_slack = self.trip_slack # Apply trip slack self.ports["vehicle"] = vehicle # EV always has a storage port @@ -88,7 +94,6 @@ def __init__(self, **data) -> None: usage_port = ElectricalDemand( uid=self.port_dict_name_to_port_uid_map["usage"], port_name=self.port_dict_name_to_port_name_map["usage"], - **{k: v for k, v in data.items() if k not in ["uid", "port_name"]}, ) else: usage_port = ElectricalDemand() @@ -104,7 +109,6 @@ def __init__(self, **data) -> None: electrical_demand = ElectricalDemand( uid=self.port_dict_name_to_port_uid_map[self.connection_port_name], port_name=self.port_dict_name_to_port_name_map[self.connection_port_name], - **{k: v for k, v in data.items() if k not in ["uid", "port_name"]}, ) else: diff --git a/src/echo/models/electrical/ev/ev_with_profile.py b/src/echo/models/electrical/ev/ev_with_profile.py index ca2a2c22..c03e55cb 100644 --- a/src/echo/models/electrical/ev/ev_with_profile.py +++ b/src/echo/models/electrical/ev/ev_with_profile.py @@ -1,6 +1,6 @@ import numpy as np import shortuuid -from pydantic import Field, NonNegativeFloat +from attrs import define, field, validators from echo.configuration import ( EVChargeMode, @@ -11,6 +11,7 @@ from echo.validators import ArrayType +@define class EVWithProfile(Node): """An EV defined through a timeseries profile of demand. @@ -27,16 +28,15 @@ class EVWithProfile(Node): """ charge_mode: EVChargeMode = EVChargeMode.DemandProfile - port_name: str | None = "demand" - port_uid: str | None = Field(default_factory=shortuuid.uuid) - charging_power_limit: NonNegativeFloat | None + port_name: str = "demand" + port_uid: str = field(factory=shortuuid.uuid) + charging_power_limit: float = field(default=None, validator=validators.optional(validators.ge(0))) # Stateful attributes set_stateful_attrs_at_init: bool = True - demand: dict | ArrayType | list | None + demand: dict | ArrayType | list | None = None - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: # Set the EV charge mode self.charge_mode: EVChargeMode = EVChargeMode.DemandProfile diff --git a/src/echo/models/electrical/ev/v0g.py b/src/echo/models/electrical/ev/v0g.py index a778f045..6ec3ad59 100644 --- a/src/echo/models/electrical/ev/v0g.py +++ b/src/echo/models/electrical/ev/v0g.py @@ -2,6 +2,7 @@ import numpy as np import pandas as pd +from attrs import define from echo.configuration import ( EVChargeMode, @@ -15,6 +16,7 @@ from echo.validators import ArrayType, check_initial_state_of_charge_within_bounds +@define class EVV0G(EVBase): """This EV object takes an available and usage dataset to precalculate a demand profile. @@ -23,13 +25,13 @@ class EVV0G(EVBase): """ # Initialise attributes - V0G_delta: ArrayType | list | None - V0G_SOC: ArrayType | list | None - V0G_trip_infeasibility: ArrayType | list | None - charge_status: EVChargeStatus | None + V0G_delta: ArrayType | list | None = None + V0G_SOC: ArrayType | list | None = None + V0G_trip_infeasibility: ArrayType | list | None = None + charge_status: EVChargeStatus | None = None - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() # Set the charge_mode self.charge_mode = EVChargeMode.V0G diff --git a/src/echo/models/electrical/ev/v1g.py b/src/echo/models/electrical/ev/v1g.py index 8f1e07c2..cf49b3ec 100644 --- a/src/echo/models/electrical/ev/v1g.py +++ b/src/echo/models/electrical/ev/v1g.py @@ -1,3 +1,5 @@ +from attrs import define + from echo.configuration import ( EVChargeMode, ) @@ -5,11 +7,12 @@ from echo.validators import ArrayType, check_initial_state_of_charge_within_bounds +@define class EVV1G(EVBase): """An EV with demand managed charging.""" - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() # Set the charge_mode self.charge_mode = EVChargeMode.V1G diff --git a/src/echo/models/electrical/ev/v2g.py b/src/echo/models/electrical/ev/v2g.py index 738c0370..6602ae12 100644 --- a/src/echo/models/electrical/ev/v2g.py +++ b/src/echo/models/electrical/ev/v2g.py @@ -1,3 +1,5 @@ +from attrs import define + from echo.configuration import ( EVChargeMode, ) @@ -5,13 +7,14 @@ from echo.validators import ArrayType, check_initial_state_of_charge_within_bounds +@define class EVV2G(EVBase): """An EV with demand managed charging and generation managed discharging for purposes of providing energy to an electrical network. """ - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() # Set the charge_mode self.charge_mode = EVChargeMode.V2G diff --git a/src/echo/models/electrical/generation.py b/src/echo/models/electrical/generation.py index 1bf03801..7a74ee82 100644 --- a/src/echo/models/electrical/generation.py +++ b/src/echo/models/electrical/generation.py @@ -1,4 +1,5 @@ import pandas as pd +from attrs import define, field from echo.configuration import ( OptimisationType, @@ -10,11 +11,12 @@ from echo.validators import ArrayType +@define class ElectricalGeneration(Source): """Electrical generation which can be fixed (non-curtailable) or variable (curtailable)""" - units = Units.KW - curtailable: bool = False + units: Units = Units.KW + curtailable: bool = field(default=False) def add_generation_profile(self, generation: dict) -> None: self.set_initial_value(generation) diff --git a/src/echo/models/electrical/inverter.py b/src/echo/models/electrical/inverter.py index ebe60590..ec4c2e44 100644 --- a/src/echo/models/electrical/inverter.py +++ b/src/echo/models/electrical/inverter.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import Field +from attrs import define, field, validators from pyomo.core.expr.relational_expr import EqualityExpression from echo.exceptions import validate @@ -9,6 +9,7 @@ from echo.models.scenario import EchoConcreteModel +@define class Inverter(Node): """An inverter is a node with one AC port and at least one DC port. Flows from AC to DC, and DC to AC, are subject to conversion efficiencies. @@ -21,18 +22,16 @@ class Inverter(Node): of specifying uids for the ports then use the `add_ac_port` and `add_dc_ports` remembering to supply `uid` values. """ - max_import: float | None - max_export: float | None - dc_ac_efficiency: float = Field(default=1.0, ge=0, le=1) - ac_dc_efficiency: float = Field(default=1.0, ge=0, le=1) + max_import: float | None = None + max_export: float | None = None + dc_ac_efficiency: float = field(default=1.0, validator=[validators.ge(0), validators.le(1)]) + ac_dc_efficiency: float = field(default=1.0, validator=[validators.ge(0), validators.le(1)]) ac_port_name: str | None = None - dc_port_names: list[str] = Field(default_factory=list) + dc_port_names: list[str] = field(factory=list) - def __init__( + def __attrs_post_init__( self, - **kwargs, ) -> None: - super().__init__(**kwargs) if self.ac_port_name: self._add_ac_port(port_name=self.ac_port_name) for port_name in self.dc_port_names: diff --git a/src/echo/models/gas/base.py b/src/echo/models/gas/base.py index ff65bbd3..1f9b751e 100644 --- a/src/echo/models/gas/base.py +++ b/src/echo/models/gas/base.py @@ -1,14 +1,18 @@ +from attrs import define + from echo.configuration import Units from echo.models.agnostic import FixedPort, FlexPort +@define class FlexGasPort(FlexPort): """A flexible port with flow units of Joules/second""" - units = Units.JPS + units: Units = Units.JPS +@define class FixedGasPort(FixedPort): """A Fixed port with flow units of Joules/second""" - units = Units.JPS + units: Units = Units.JPS diff --git a/src/echo/models/gas/boiler_fixedcop.py b/src/echo/models/gas/boiler_fixedcop.py index 9f82f33a..715ba4e1 100644 --- a/src/echo/models/gas/boiler_fixedcop.py +++ b/src/echo/models/gas/boiler_fixedcop.py @@ -1,30 +1,37 @@ import pyomo.environ as en -from pydantic import NonNegativeFloat, root_validator +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression from echo.configuration import Units from echo.models.agnostic import FlexPort, InputOutputNode, OffOrConstrainedPort from echo.models.scenario import EchoConcreteModel from echo.validators import ( - set_output_bounds_from_input_bounds_and_cop_and_startup_cop, - validate_startup_efficiency, + set_output_bounds_validator, + startup_efficiency_validator, ) +@define class GasBoilerFixedCOP(InputOutputNode): """ A gas boiler converts gas to heat at a fixed coefficient of performance (COP) where COP = output/input.""" - cop: NonNegativeFloat - input_port_unit = Units.JPS - output_port_unit = Units.KWT - startup_cop: NonNegativeFloat # efficiency in startup period + input_port_unit: Units = Units.JPS + output_port_unit: Units = Units.KWT - check_cop = root_validator(allow_reuse=True)(validate_startup_efficiency) - set_bounds = root_validator(allow_reuse=True)(set_output_bounds_from_input_bounds_and_cop_and_startup_cop) + min_input: float | None = field(default=None, validator=set_output_bounds_validator) + + cop: float = field( + default=1, validator=[validators.ge(0), startup_efficiency_validator, set_output_bounds_validator] + ) + + startup_cop: float = field( + default=1, validator=[validators.ge(0), startup_efficiency_validator, set_output_bounds_validator] + ) # efficiency in startup period + + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() - def __init__(self, **data) -> None: - super().__init__(**data) # Add an input and output node, and create the appropriate transformation object self.ports[self.input_port_ref] = OffOrConstrainedPort( upper_bound=self.max_input, lower_bound=self.min_input, units=self.input_port_unit diff --git a/src/echo/models/gas/boiler_tempcontrolled.py b/src/echo/models/gas/boiler_tempcontrolled.py index cef886c4..f5a2ff3d 100644 --- a/src/echo/models/gas/boiler_tempcontrolled.py +++ b/src/echo/models/gas/boiler_tempcontrolled.py @@ -1,43 +1,50 @@ import pandas as pd import pyomo.environ as en -from pydantic import root_validator +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression from echo.configuration import Units from echo.models.agnostic import InputOutputNode, OffOrConstrainedPort from echo.models.scenario import EchoConcreteModel from echo.validators import ( - set_output_bounds_from_input_bounds_and_cop_and_startup_cop, - validate_startup_efficiency, + set_output_bounds_validator, + startup_efficiency_validator, ) +@define class TempControlledBoiler(InputOutputNode): """ A temp controlled boiler has an input and output port. It has two internal temperature variables, one for exiting water temp and one for returning water temp. """ - input_port_unit = Units.JPS - output_port_unit = Units.KWT - max_input: float - min_input: float + input_port_unit: Units = Units.JPS + output_port_unit: Units = Units.KWT exit_temp_bounds: tuple = (75, 80) return_temp_bounds: tuple = (50, 80) - deg_to_kw: float # factor for converting a temperature difference to kW required to achieve that delta T - cop: float # coefficient of performance - determines how much of the input energy is delivered as heating energy - startup_cop: float | None + + # factor for converting a temperature difference to kW required to achieve that delta T + deg_to_kw: float = field(kw_only=True) + + min_input: float | None = field(default=None, validator=set_output_bounds_validator) + + # coefficient of performance - determines how much of the input energy is delivered as heating energy + cop: float = field( + default=1, validator=[validators.ge(0), startup_efficiency_validator, set_output_bounds_validator] + ) + + startup_cop: float | None = field( + default=None, validator=[startup_efficiency_validator, set_output_bounds_validator] + ) # pyomo vars - is_on: str | None return_t: str = "" exit_t: str = "" - check_eta = root_validator(allow_reuse=True)(validate_startup_efficiency) - set_output_bounds = root_validator(allow_reuse=True)(set_output_bounds_from_input_bounds_and_cop_and_startup_cop) + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() - def __init__(self, **data) -> None: - super().__init__(**data) self.ports[self.input_port_ref] = OffOrConstrainedPort( units=self.input_port_unit, lower_bound=self.min_input, upper_bound=self.max_input ) diff --git a/src/echo/models/prebuilt/battery.py b/src/echo/models/prebuilt/battery.py index a247dc25..bae8698a 100644 --- a/src/echo/models/prebuilt/battery.py +++ b/src/echo/models/prebuilt/battery.py @@ -1,9 +1,10 @@ -from pydantic import PositiveFloat +from attrs import define, field, validators from echo.models.base.node import Node from echo.models.electrical import ElectricalStorage +@define class Battery(Node): def __init__( self, @@ -12,7 +13,7 @@ def __init__( initial_state_of_charge: float, charging_power_limit: float, discharging_power_limit: float, - storage_capacity_cost: PositiveFloat | None = None, + storage_capacity_cost: float | None = field(default=None, validator=validators.optional(validators.gt(0))), charging_efficiency: float = 1, discharging_efficiency: float = 1, depth_of_discharge_limit: float = 0, @@ -20,7 +21,7 @@ def __init__( regularise: bool = False, **data, ) -> None: - super().__init__(**data) + self.__attrs_init__(**data) self.ports[port_name] = ElectricalStorage( max_capacity=max_capacity, depth_of_discharge_limit=depth_of_discharge_limit, diff --git a/src/echo/models/prebuilt/diesel_generator.py b/src/echo/models/prebuilt/diesel_generator.py index 2ab329e8..db866faf 100644 --- a/src/echo/models/prebuilt/diesel_generator.py +++ b/src/echo/models/prebuilt/diesel_generator.py @@ -1,5 +1,5 @@ import pyomo.environ as en -from pydantic import NonNegativeFloat +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression from echo.configuration import Units @@ -8,22 +8,24 @@ from echo.models.scenario import EchoConcreteModel +@define class DieselGenerator(InputOutputNode): """ A diesel generator node. Converts diesel into electricity at a fixed rate of cop which is in units of kW/liters per second """ - input_port_unit = Units.LPS - output_port_unit = Units.KW - cop: NonNegativeFloat = 0.4 * 3600 # kW / litres per second - startup_efficiency: NonNegativeFloat = ( - 0.5 # ratio of efficiency in startup and shutdown period, # todo: ensure between 0-1 (confloat??) - ) - C02Intensity: NonNegativeFloat = 2.7 # emissions intensity kg per sec / litre per sec = kg/litre + input_port_unit: Units = Units.LPS + output_port_unit: Units = Units.KW + cop: float = field(default=0.4 * 3600, validator=validators.ge(0)) # kW / litres per second + # ratio of efficiency in startup and shutdown period, # todo: ensure between 0-1 (confloat??) + startup_efficiency: float = field(default=0.5, validator=validators.ge(0)) + # emissions intensity kg per sec / litre per sec = kg/litre + C02Intensity: float = field(default=2.7, validator=validators.ge(0)) + + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() - def __init__(self, **data) -> None: - super().__init__(**data) # add an input and output node, and create appropriate transformations self.ports["output"] = OffOrConstrainedPort( upper_bound=self.min_output, lower_bound=self.max_output, units=self.output_port_unit diff --git a/src/echo/models/thermal/base.py b/src/echo/models/thermal/base.py index eaa616b1..cdcd3541 100644 --- a/src/echo/models/thermal/base.py +++ b/src/echo/models/thermal/base.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import NonNegativeFloat, PositiveFloat +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression, InequalityExpression from echo.models.base import Node @@ -8,6 +8,7 @@ from echo.utils import set_var_bounds_from_dict +@define class ThermalNode(Node): """ A thermal node has an internal temperature variable, which can be bounded. @@ -15,12 +16,22 @@ class ThermalNode(Node): All the ports are related to temp by an energy balance constraint. """ - temp_ub: dict # Upper bound of acceptable temperature for each time interval: dict with expansion-time keys - temp_lb: dict # Lower bound of acceptable temperature for each time interval: dict with expansion-time keys - external_temp: dict # External (ambient) temp, formatted as dict with expansion-time keys - loss_factor: NonNegativeFloat = 0 # Losses due to ambient temp being lower than internal temp - gain_factor: NonNegativeFloat = 0 # Free gains due to ambient temp being higher than internal temp - temp_to_energy_coef: PositiveFloat = 1 # Conversion factor * temp change = added energy + temp_ub: dict = field( + kw_only=True + ) # Upper bound of acceptable temperature for each time interval: dict with expansion-time keys + temp_lb: dict = field( + kw_only=True + ) # Lower bound of acceptable temperature for each time interval: dict with expansion-time keys + external_temp: dict = field(kw_only=True) # External (ambient) temp, formatted as dict with expansion-time keys + loss_factor: float = field( + default=0, validator=validators.ge(0) + ) # Losses due to ambient temp being lower than internal temp + gain_factor: float = field( + default=0, validator=validators.ge(0) + ) # Free gains due to ambient temp being higher than internal temp + temp_to_energy_coef: float = field( + default=1, validator=validators.gt(0) + ) # Conversion factor * temp change = added energy initial_internal_temp: float = 0 # initial internal temperature # Pyomo vars/params @@ -29,8 +40,7 @@ class ThermalNode(Node): losses: str = "" gains: str = "" - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: self.internal_temp = "internal_temp_" + self.node_name self.is_gain = "is_gain_" + self.node_name self.losses = "losses_" + self.node_name diff --git a/src/echo/models/thermal/parameterised_chiller.py b/src/echo/models/thermal/parameterised_chiller.py index 1d9a6b2f..8e0bf0bb 100644 --- a/src/echo/models/thermal/parameterised_chiller.py +++ b/src/echo/models/thermal/parameterised_chiller.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import PositiveFloat, root_validator +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression from scipy import interpolate @@ -13,9 +13,13 @@ expand_as_dict, to_initial_values, ) -from echo.validators import validate_partial_load_cop, validate_temperature_dependent_cop +from echo.validators import ( + partial_load_cop_validator, + temperature_dependent_cop_validator, +) +@define class ParameterisedChiller(TimeVaryingPiecewiseIONode): """A chiller has one electrical input port and one cooling output (thermal sink) port. @@ -24,41 +28,60 @@ class ParameterisedChiller(TimeVaryingPiecewiseIONode): for all time periods. """ - nominal_cop: PositiveFloat # Nominal coefficient of performance COP = output/input - max_cooling_capacity: PositiveFloat # Maximum cooling output in KWT (1RT ~ 3.5KWT) - partial_load_cop: dict = { - 0: 0, - 0.25: 0.8, - 0.5: 0.9, - 0.75: 1, - 1: 0.85, - } # Scaling factor for the nominal COP (coefficient of performance) depending on the partial load value - temperature_dependent_cop: dict = { - 0: 0.7, - 10: 1, - 20: 0.5, - 30: 0.35, - 45: 0.2, - } # Scaling factor for the nominal COP (coefficient of performance) depending on + nominal_cop: float = field( + kw_only=True, validator=validators.gt(0) + ) # Nominal coefficient of performance COP = output/input + + max_cooling_capacity: float = field( + kw_only=True, validator=validators.gt(0) + ) # Maximum cooling output in KWT (1RT ~ 3.5KWT) + partial_load_cop: dict = field( + default={ + 0: 0, + 0.25: 0.8, + 0.5: 0.9, + 0.75: 1, + 1: 0.85, + }, + validator=partial_load_cop_validator, + ) # Scaling factor for the nominal COP (coefficient of performance) depending on the partial load value + temperature_dependent_cop: dict = field( + default={ + 0: 0.7, + 10: 1, + 20: 0.5, + 30: 0.35, + 45: 0.2, + }, + validator=temperature_dependent_cop_validator, + ) # Scaling factor for the nominal COP (coefficient of performance) depending on \ # the ambient/condenser temperature value - ambient_temperature_dict: dict = ( - None # Condenser side temperature ambient air temperature or condenser - # water temperature for water cooled chiller - ) - ambient_temperature_ref: str = None # Ambient temperature array passed by string reference + ambient_temperature_dict: dict = field( + factory=dict + ) # Condenser side temperature ambient air temperature or condenser \ + # water temperature for water cooled chiller + ambient_temperature_ref: str | None = None # Ambient temperature array passed by string reference constant_ambient_temperature: float = 10 # Constant value for ambient temperature in degrees C, # when no array data is provided input_port_unit: Units = Units.KW # Input port units output_port_unit: Units = Units.KWT # Output port units TODO: implementation for output units JPS heat_rejection_port: bool = False # If True, add heat rejection port - heat_rejection_coefficient: PositiveFloat = 1 # Heat rejection coefficient cooling_delivered/heat_rejected - - partial_load_cop_check = root_validator(allow_reuse=True)(validate_partial_load_cop) - temperature_cop_check = root_validator(allow_reuse=True)(validate_temperature_dependent_cop) + heat_rejection_coefficient: float = field( + default=1, validator=validators.gt(0) + ) # Heat rejection coefficient cooling_delivered/heat_rejected # The input_port_ref and output_port_ref are defined on the parent class (TimeVaryingPiecewiseIONode) heat_rejection_port_ref: str = "heat_rejection" + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() + + # A chiller has one electrical input port and one cooling output (thermal sink) port + self.ports[self.input_port_ref] = FlexSink(units=self.input_port_unit) + self.ports[self.output_port_ref] = FlexSink(units=self.output_port_unit) + if self.heat_rejection_port: + self.ports[self.heat_rejection_port_ref] = FlexSource(units=self.output_port_unit) + @property def temperature_cop_param(self) -> str: return f"temperature_cop_factor_{self.node_name}" @@ -71,14 +94,6 @@ def electrical_input_port_ref(self) -> str: def thermal_output_port_ref(self) -> str: return self.output_port_ref - def __init__(self, **data) -> None: - super().__init__(**data) - # A chiller has one electrical input port and one cooling output (thermal sink) port - self.ports[self.input_port_ref] = FlexSink(units=self.input_port_unit) - self.ports[self.output_port_ref] = FlexSink(units=self.output_port_unit) - if self.heat_rejection_port: - self.ports[self.heat_rejection_port_ref] = FlexSource(units=self.output_port_unit) - def update(self, ambient_temperature_dict: dict[float, float]) -> None: self.ambient_temperature_dict = ambient_temperature_dict diff --git a/src/echo/models/thermal/parameterised_heatpump.py b/src/echo/models/thermal/parameterised_heatpump.py index a3da519a..3e4cd4fb 100644 --- a/src/echo/models/thermal/parameterised_heatpump.py +++ b/src/echo/models/thermal/parameterised_heatpump.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import PositiveFloat +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression, InequalityExpression from scipy import interpolate @@ -15,8 +15,10 @@ set_float_var_bounds, to_initial_values, ) +from echo.validators import partial_load_cop_validator, temperature_dependent_cop_validator +@define class ParameterisedHeatPump(Node): """A Parameterised heat pump model. @@ -31,65 +33,85 @@ class ParameterisedHeatPump(Node): performance (COP) at each time step. """ - nominal_heating_cop: PositiveFloat # Nominal coefficient of performance in heating mode COP = output/input - nominal_cooling_cop: PositiveFloat # Nominal coefficient of performance in cooling mode COP = output/input - max_heating_capacity: PositiveFloat # Maximum cooling output in KWT (1RT ~ 3.5KWT) - max_cooling_capacity: PositiveFloat # Maximum cooling output in KWT (1RT ~ 3.5KWT) - partial_load_cop_heating: dict = { - 0: 0, - 0.25: 0.8, - 0.5: 0.9, - 0.75: 1, - 1: 0.85, - } # Scaling factor for the nominal COP (coefficient of performance) depending on the partial load value - partial_load_cop_cooling: dict = { - 0: 0, - 0.25: 0.8, - 0.5: 0.9, - 0.75: 1, - 1: 0.85, - } # Scaling factor for the nominal COP (coefficient of performance) depending on the partial load value - temperature_dependent_cop_heating: dict = { - -10: 0.4, - 0: 0.6, - 10: 0.7, - 20: 0.9, - 30: 1, - 45: 1, - } # Scaling factor for the nominal heating COP depending on + nominal_heating_cop: float = field( + default=1, validator=validators.gt(0) + ) # Nominal coefficient of performance in heating mode COP = output/input + nominal_cooling_cop: float = field( + default=1, validator=validators.gt(0) + ) # Nominal coefficient of performance in cooling mode COP = output/input + max_heating_capacity: float = field( + kw_only=True, validator=validators.gt(0) + ) # Maximum cooling output in KWT (1RT ~ 3.5KWT) + max_cooling_capacity: float = field( + kw_only=True, validator=validators.gt(0) + ) # Maximum cooling output in KWT (1RT ~ 3.5KWT) + partial_load_cop_heating: dict = field( + default={ + 0: 0, + 0.25: 0.8, + 0.5: 0.9, + 0.75: 1, + 1: 0.85, + }, + validator=partial_load_cop_validator, + ) # Scaling factor for the nominal COP (coefficient of performance) depending on the partial load value + partial_load_cop_cooling: dict = field( + default={ + 0: 0, + 0.25: 0.8, + 0.5: 0.9, + 0.75: 1, + 1: 0.85, + }, + validator=partial_load_cop_validator, + ) # Scaling factor for the nominal COP (coefficient of performance) depending on the partial load value + temperature_dependent_cop_heating: dict = field( + default={ + -10: 0.4, + 0: 0.6, + 10: 0.7, + 20: 0.9, + 30: 1, + 45: 1, + }, + validator=temperature_dependent_cop_validator, + ) # Scaling factor for the nominal heating COP depending on # the ambient/condenser temperature value - temperature_dependent_cop_cooling: dict = { - 0: 0.7, - 10: 1, - 20: 0.5, - 30: 0.35, - 45: 0.2, - } # Scaling factor for the nominal cooling COP depending on + temperature_dependent_cop_cooling: dict = field( + default={ + 0: 0.7, + 10: 1, + 20: 0.5, + 30: 0.35, + 45: 0.2, + }, + validator=temperature_dependent_cop_validator, + ) # Scaling factor for the nominal cooling COP depending on # the ambient/condenser temperature value - ambient_temperature_dict: dict = ( - None # Condenser side temperature ambient air temperature or condenser - # water temperature for water cooled chiller - ) - ambient_temperature_ref: str = None # Ambient temperature array passed by string reference + ambient_temperature_dict: dict = field( + factory=dict + ) # Condenser side temperature ambient air temperature or condenser \ + # water temperature for water cooled chiller + ambient_temperature_ref: str | None = None # Ambient temperature array passed by string reference constant_ambient_temperature: float = 10 # Constant value for ambient temperature in degrees C, # when no array data is provided heat_intake_rejection_port: bool = False # If True, add heat intake_rejection port - heat_intake_rejection_coefficient: PositiveFloat = 1 + heat_intake_rejection_coefficient: float = field(default=1, validator=validators.gt(0)) # Heat intake coefficient = heating_delivered_to_load/heat_intake_from_source # Heat rejection coefficient = cooling_delivered_to_load/heat_rejected_to_source (environment) # TODO: We do not want user to ever provide these. Rewrite to be pyomo parameter - input_points_cooling: dict = None - output_points_cooling: dict = None - input_points_heating: dict = None - output_points_heating: dict = None + input_points_cooling: dict | None = None + output_points_cooling: dict | None = None + input_points_heating: dict | None = None + output_points_heating: dict | None = None electrical_input_port_ref: str = "input" thermal_output_port_ref: str = "output" heat_intake_rejection_port_ref: str = "heat_intake_rejection" - # partial_load_cop_check = root_validator(allow_reuse=True)(validate_partial_load_cop) - # temperature_cop_check = root_validator(allow_reuse=True)(validate_temperature_dependent_cop) + def __attrs_post_init__(self) -> None: + self.create_ports() @property def temperature_cop_heating_param(self) -> str: @@ -107,10 +129,6 @@ def power_to_heat(self) -> str: def power_to_cool(self) -> str: return "power_to_cool_" + self.node_name - def __init__(self, **data) -> None: - super().__init__(**data) - self.create_ports() - def update(self, ambient_temperature_dict: dict[float, float]) -> None: self.ambient_temperature_dict = ambient_temperature_dict diff --git a/src/echo/models/thermal/simple_chiller.py b/src/echo/models/thermal/simple_chiller.py index 0f31582d..f939241f 100644 --- a/src/echo/models/thermal/simple_chiller.py +++ b/src/echo/models/thermal/simple_chiller.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import PositiveFloat, validator +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression from echo.configuration import FlowConstraint, Units @@ -12,9 +12,10 @@ expand_as_dict, to_initial_values, ) -from echo.validators import non_negative_cop_check +from echo.validators import non_negative_cop_validator +@define class SimpleChiller(Node): """A simple chiller model that uses predefined COP (coefficient of performance) values for cooling. @@ -24,19 +25,22 @@ class SimpleChiller(Node): performance (COP) time series data. """ - max_cooling_capacity: PositiveFloat | None = None # Max cooling load that can be serviced in KWT + max_cooling_capacity: float | None = field( + default=None, validator=validators.optional(validators.gt(0)) + ) # Max cooling load that can be serviced in KWT # (if None, bounded by big_m value) - cooling_cop_time_series: dict | None # Formatted dict of cooling COPs (coefficients of performance) - cooling_cop_time_series_ref: str | None - cooling_cop_constant: PositiveFloat | None = 1 # Constant COP value to use across all optimisation intervals - - cooling_cop_check = validator("cooling_cop_time_series", allow_reuse=True)(non_negative_cop_check) + cooling_cop_time_series: dict | None = field( + default=None, validator=non_negative_cop_validator + ) # Formatted dict of cooling COPs (coefficients of performance) + cooling_cop_time_series_ref: str | None = None + cooling_cop_constant: float = field( + default=1, validator=validators.gt(0) + ) # Constant COP value to use across all optimisation intervals electrical_input_port_ref: str = "input" thermal_output_port_ref: str = "output" - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: # Constraint flow of the thermal port if self.max_cooling_capacity: thermal_import_constraint = FlowConstraint.Fixed diff --git a/src/echo/models/thermal/simple_heatpump.py b/src/echo/models/thermal/simple_heatpump.py index 7a081ae7..3e176a12 100644 --- a/src/echo/models/thermal/simple_heatpump.py +++ b/src/echo/models/thermal/simple_heatpump.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import PositiveFloat, validator +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression, InequalityExpression from echo.configuration import FlowConstraint, Units @@ -13,9 +13,10 @@ set_float_var_bounds, to_initial_values, ) -from echo.validators import non_negative_cop_check +from echo.validators import non_negative_cop_validator +@define class SimpleHeatPump(Node): """A simple heat pump model that uses predefined COP (coefficient of performance) values for heating and cooling. @@ -26,30 +27,34 @@ class SimpleHeatPump(Node): performance (COP) time series data. """ - max_cooling_capacity: PositiveFloat = ( - None # Max cooling load that can be serviced in KWT (if None, bounded by big_m value) - ) - max_heating_capacity: PositiveFloat = ( - None # Max heating load that can be serviced in KWT (if None, bounded by big_m value) - ) - heating_cop_time_series: dict | None # Formatted dict of heating COPs (coefficients of performance) + max_cooling_capacity: float | None = field( + default=None, validator=validators.optional(validators.gt(0)) + ) # Max cooling load that can be serviced in KWT (if None, bounded by big_m value) + max_heating_capacity: float | None = field( + default=None, validator=validators.optional(validators.gt(0)) + ) # Max heating load that can be serviced in KWT (if None, bounded by big_m value) + heating_cop_time_series: dict | None = field( + default=None, validator=non_negative_cop_validator + ) # Formatted dict of heating COPs (coefficients of performance) # per time period - cooling_cop_time_series: dict | None # Formatted dict of cooling COPs (coefficients of performance) + cooling_cop_time_series: dict | None = field( + default=None, validator=non_negative_cop_validator + ) # Formatted dict of cooling COPs (coefficients of performance) # per time period - heating_cop_time_series_ref: str | None - cooling_cop_time_series_ref: str | None + heating_cop_time_series_ref: str | None = None + cooling_cop_time_series_ref: str | None = None - cooling_cop_constant: PositiveFloat | None = 1 # Constant COP value to use across all optimisation intervals - heating_cop_constant: PositiveFloat | None = 1 # Constant COP value to use across all optimisation intervals - - heating_cop_check = validator("heating_cop_time_series", allow_reuse=True)(non_negative_cop_check) - cooling_cop_check = validator("cooling_cop_time_series", allow_reuse=True)(non_negative_cop_check) + cooling_cop_constant: float = field( + default=1, validator=validators.gt(0) + ) # Constant COP value to use across all optimisation intervals + heating_cop_constant: float = field( + default=1, validator=validators.gt(0) + ) # Constant COP value to use across all optimisation intervals electrical_input_port_ref: str = "input" thermal_output_port_ref: str = "output" - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: self.create_ports() def update(self, heating_cop_time_series: dict[float, float], cooling_cop_time_series: dict[float, float]) -> None: diff --git a/src/echo/models/thermal/simple_heatpump_dualoutput.py b/src/echo/models/thermal/simple_heatpump_dualoutput.py index 596690d4..11f09f5e 100644 --- a/src/echo/models/thermal/simple_heatpump_dualoutput.py +++ b/src/echo/models/thermal/simple_heatpump_dualoutput.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import NonNegativeFloat +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression, InequalityExpression from echo.configuration import Units @@ -12,6 +12,7 @@ ) +@define class SimpleHeatPumpDualOutput(SimpleHeatPump): """A simple dual output (four-pipe) heatpump model that uses predefined COP values for heating and cooling. @@ -24,13 +25,15 @@ class SimpleHeatPumpDualOutput(SimpleHeatPump): performance (COP) time series data. """ - waste_heat_recovery_coeff: NonNegativeFloat = 1 # Waste heat recovery coefficient from cooling to heating loop + waste_heat_recovery_coeff: float = field( + default=1, validator=validators.ge(0) + ) # Waste heat recovery coefficient from cooling to heating loop electrical_input_port_ref: str = "input" cooling_output_port_ref: str = "cooling_output" heating_output_port_ref: str = "heating_output" - def __init__(self, **data) -> None: - super().__init__(**data) + def __attrs_post_init__(self) -> None: + super().__attrs_post_init__() # Create input and output ports: electrical input port, cooling output port and heating output port self.create_ports() diff --git a/src/echo/models/thermal/storage.py b/src/echo/models/thermal/storage.py index 9ef2ad1b..2d09d3c8 100644 --- a/src/echo/models/thermal/storage.py +++ b/src/echo/models/thermal/storage.py @@ -1,6 +1,6 @@ import pandas as pd import pyomo.environ as en -from pydantic import NegativeFloat, NonNegativeFloat, PositiveFloat, root_validator, validator +from attrs import define, field, validators from pyomo.core.expr import EqualityExpression from echo.configuration import FlowConstraint, Units @@ -11,8 +11,10 @@ set_float_var_bounds, to_initial_values, ) +from echo.validators import temperature_range_validator, thermal_units_validator +@define class ThermalStorage(Node): """Model of sensible thermal storage with liquid or solid storage medium. @@ -20,37 +22,42 @@ class ThermalStorage(Node): storage volume. """ - max_temp: float # Maximum operational temperature in degrees Celsius - min_temp: float # Minimum operational temperature in degrees Celsius - storage_mass: PositiveFloat # Mass of storage medium in kg - specific_heat: PositiveFloat # Specific heat capacity in Joule/kg*C - charging_power_limit: PositiveFloat = ( - None # Maximum energy flow into the storage at each interval, in energy_flow_units - ) - discharging_power_limit: NegativeFloat = ( - None # Maximum energy flow out of the storage at each interval, in energy_flow_units - ) + max_temp: float = field( + kw_only=True, validator=temperature_range_validator + ) # Maximum operational temperature in degrees Celsius + min_temp: float = field( + kw_only=True, validator=temperature_range_validator + ) # Minimum operational temperature in degrees Celsius + storage_mass: float = field(kw_only=True, validator=validators.gt(0)) # Mass of storage medium in kg + specific_heat: float = field(kw_only=True, validator=validators.gt(0)) # Specific heat capacity in Joule/kg*C + charging_power_limit: float | None = field( + default=None, validator=validators.optional(validators.gt(0)) + ) # Maximum energy flow into the storage at each interval, in energy_flow_units + discharging_power_limit: float | None = field( + default=None, validator=validators.optional(validators.lt(0)) + ) # Maximum energy flow out of the storage at each interval, in energy_flow_units ambient_temp: dict | None = None # Ambient temp, formatted as dict with expansion-time keys - ambient_temp_ref: str | None # Ambient temp by column name reference in profile dataframe - ins_transmittance: NonNegativeFloat = ( - 0 # Thermal transmittance U-value of Thermal Energy Storage insulation in W/sqm*C - ) - surface_area: NonNegativeFloat = 0 # Surface area of Thermal Energy Storage in square meters, default value=0 - # means zero heat loss/gain - initial_temp: float = None # initial internal temperature in degrees Celsius + ambient_temp_ref: str | None = None # Ambient temp by column name reference in profile dataframe + ins_transmittance: float = field( + default=0, validator=validators.ge(0) + ) # Thermal transmittance U-value of Thermal Energy Storage insulation in W/sqm*C + surface_area: float = field( + default=0, validator=validators.ge(0) + ) # Surface area of Thermal Energy Storage in square meters, default value=0 means zero heat loss/gain + initial_temp: float | None = None # initial internal temperature in degrees Celsius optimised_capacity: bool = False # If True, set heat storage capacity (size of storage) to be optimisation variable enforce_end_temperature_value: bool = True # If True, the internal temperature value at the end of the # last optimisation interval is required to be equal initial value - energy_flow_units: Units = Units.KWT # Thermal energy flow units to use, expecting KW Thermal or JPS + energy_flow_units: Units = field( + default=Units.KWT, validator=thermal_units_validator + ) # Thermal energy flow units to use, expecting KW Thermal or JPS separate_in_out_ports: bool = False # Create two thermal ports charge and discharge, else 1 two-way port input_port_ref: str = "input" output_port_ref: str = "output" input_output_port_ref: str = "input_output" - def __init__(self, **data) -> None: - super().__init__(**data) - + def __attrs_post_init__(self) -> None: if self.separate_in_out_ports: self.ports[self.input_port_ref] = FlexSink(units=self.energy_flow_units) self.ports[self.output_port_ref] = FlexSource(units=self.energy_flow_units) @@ -116,24 +123,6 @@ def set_port(self, input_output_port: FlexPort) -> None: self.ports[self.input_output_port_ref].export_constraint = FlowConstraint.Fixed self.ports[self.input_output_port_ref].export_constraint_value = self.discharging_power_limit - @root_validator - def _non_zero_temp_range(cls, values: dict) -> dict: - """Temperature range must be non-zero and positive for Thermal Energy Storage to be operational""" - if "max_temp" in values and "min_temp" in values and values["max_temp"] - values["min_temp"] <= 0: - raise ValueError( - "Temperature range must be non-zero and positive for Thermal Energy Storage to be operational." - f"Was given max temperature {values['max_temp']} " - f"and min temperature {values['min_temp']}, " - f"resulting in range {values['max_temp'] - values['min_temp']}" - ) - return values - - @validator("energy_flow_units", allow_reuse=True) - def _units_are_allowed(cls, v: Units) -> Units: - if v and v not in {Units.JPS, Units.KWT}: - raise ValueError(f"Only allowed units are KW Thermal (KWT) and Joules per second (JPS). Received {v}") - return v - @property def internal_temp(self) -> str: return "internal_temp_" + self.node_name diff --git a/src/echo/objectives/base.py b/src/echo/objectives/base.py index af8787cb..8c52bc63 100644 --- a/src/echo/objectives/base.py +++ b/src/echo/objectives/base.py @@ -1,23 +1,22 @@ import pandas as pd import pyomo.environ as en import shortuuid -from pydantic import Field +from attrs import define, field -from echo.models.base import BaseModel as EchoBaseModel from echo.models.base import Path, Port from echo.models.scenario import EchoConcreteModel -class Objective(EchoBaseModel): - component: Port | Path | None - uid: str = Field(default_factory=shortuuid.uuid) - name: str = "" +@define +class Objective: + component: Port | Path | None = None weight: float = 1 + uid: str = field(factory=shortuuid.uuid) + name: str = field() - def __init__(self, **data) -> None: - super().__init__(**data) - if not self.name: - self.name = "obj_" + self.uid + @name.default + def _set_name_default(self) -> str: + return "obj_" + str(self.uid) def verify_objective(self, model: EchoConcreteModel, df: pd.DataFrame | None) -> None: pass @@ -39,10 +38,11 @@ def get_objective_total(self, model: EchoConcreteModel) -> float: return en.value(obj_expr) # Return the value of the summed expression -class ObjectiveSet(EchoBaseModel): +@define +class ObjectiveSet: """Objective Set is an object containing a list of defined objectives that can be passed to the echo optimiser""" - objective_list: list[Objective] + objective_list: list[Objective] = field(factory=list) def add_objectives_to_model(self, model: EchoConcreteModel, df: pd.DataFrame | None = None) -> None: for obj in self.objective_list: @@ -55,10 +55,11 @@ def get_objective_total(self, model: EchoConcreteModel) -> float: return sum([obj.objective_expr(model) * obj.weight for obj in self.objective_list]) +@define class TotalFlow(Objective): """Minimises flow at a specified port across all time periods/expansions.""" - component: Port + component: Port = field(kw_only=True) minimise: bool = True def objective_expr(self, model: EchoConcreteModel) -> float: @@ -66,10 +67,11 @@ def objective_expr(self, model: EchoConcreteModel) -> float: return sign * sum(getattr(model, self.component.port_name)[p, t] for p in model.Expansion for t in model.Time) +@define class TotalImportFlow(Objective): """Minimises import at a specified port across all time periods/expansions.""" - component: Port + component: Port = field(kw_only=True) minimise: bool = True def apply_constraints(self, model: EchoConcreteModel) -> None: @@ -81,10 +83,11 @@ def objective_expr(self, model: EchoConcreteModel) -> float: return sign * sum(getattr(model, self.component.pos)[p, t] for p in model.Expansion for t in model.Time) +@define class TotalExportFlow(Objective): """Minimises export at a specified port across all time periods/expansions.""" - component: Port + component: Port = field(kw_only=True) minimise: bool = True def apply_constraints(self, model: EchoConcreteModel) -> None: diff --git a/src/echo/objectives/contingency.py b/src/echo/objectives/contingency.py index 45dd5951..8b3ff54e 100644 --- a/src/echo/objectives/contingency.py +++ b/src/echo/objectives/contingency.py @@ -1,5 +1,5 @@ import pyomo.environ as en -from pydantic import PositiveFloat +from attrs import define, field, validators from pyomo.core.expr import InequalityExpression from echo.models.agnostic import Storage @@ -8,14 +8,18 @@ from echo.objectives.base import Objective +@define class Contingency(Objective): - component: Path + component: Path = field(kw_only=True) +@define class ContingencyNegative(Contingency): """FCAS Raise""" - duration: PositiveFloat # todo this should just be the interval duration ? + duration: float = field( + kw_only=True, validator=validators.gt(0) + ) # todo this should just be the interval duration ? @property def contingency_neg(self) -> str: @@ -80,10 +84,13 @@ def objective_expr(self, model: EchoConcreteModel) -> None: ) +@define class ContingencyPositive(Contingency): """FCAS Lower""" - duration: PositiveFloat + duration: float = field( + kw_only=True, validator=validators.gt(0) + ) # todo this should just be the interval duration ? @property def contingency_pos(self) -> None: diff --git a/src/echo/objectives/power.py b/src/echo/objectives/power.py index 46261f4f..c18d8d36 100644 --- a/src/echo/objectives/power.py +++ b/src/echo/objectives/power.py @@ -1,5 +1,5 @@ import pyomo.environ as en -from pydantic import PositiveFloat +from attrs import define, field, validators from pyomo.core.expr import InequalityExpression from echo.models.agnostic import Storage @@ -8,10 +8,11 @@ from echo.objectives.base import Objective +@define class PeakPositivePower(Objective): """The PeakPositivePower objective minimises the peak positive (imported) power at the specified port.""" - component: Port + component: Port = field(kw_only=True) @property def max_pos(self) -> str: @@ -37,10 +38,11 @@ def objective_expr(self, model: EchoConcreteModel) -> float: return getattr(model, self.max_pos) +@define class PeakNegativePower(Objective): """The PeakNegativePower objective minimises the peak negative (exported) power at the specified port.""" - component: Port + component: Port = field(kw_only=True) @property def max_neg(self) -> str: @@ -66,11 +68,12 @@ def objective_expr(self, model: EchoConcreteModel) -> float: return getattr(model, self.max_neg) * -1 +@define class FinalChargeObjective(Objective): """A cost on the final state of charge of a storage asset being below full.""" - component: Storage - rate: PositiveFloat + component: Storage = field(kw_only=True) + rate: float = field(kw_only=True, validator=validators.gt(0)) def apply_constraints(self, model: EchoConcreteModel) -> None: pass @@ -85,12 +88,13 @@ def objective_expr(self, model: EchoConcreteModel) -> float: return obj +@define class NotFullyChargedPenalty(Objective): """A penalty objective for penalising a storage asset for not being fulling charged.""" - component: Storage - rate: PositiveFloat | None - rate_array: list + component: Storage = field(kw_only=True) + rate: float | None = field(default=None, validator=validators.optional(validators.gt(0))) + rate_array: list = field(factory=list) def apply_constraints(self, model: EchoConcreteModel) -> None: if hasattr(model, self.component.pos) is False: @@ -109,10 +113,11 @@ def objective_expr(self, model: EchoConcreteModel) -> None: return obj +@define class QuadraticPower(Objective): """The QuadraticPower objective minimises flow^2 at a specified port.""" - component: Port + component: Port = field(kw_only=True) def apply_constraints(self, model: EchoConcreteModel) -> None: if hasattr(model, self.component.pos) is False: diff --git a/src/echo/objectives/tariff.py b/src/echo/objectives/tariff.py index d4c218e9..170a2daa 100644 --- a/src/echo/objectives/tariff.py +++ b/src/echo/objectives/tariff.py @@ -7,20 +7,25 @@ import pandas as pd import pyomo.environ as en import shortuuid -from pydantic import Field, NonNegativeFloat, NonPositiveFloat, PositiveFloat, PositiveInt, root_validator, validator +from attrs import define, field, validators from pyomo.core.expr import InequalityExpression from echo.exceptions import validate -from echo.models.base import BaseModel as EchoBaseModel from echo.models.base import Path, Port from echo.models.scenario import EchoConcreteModel from echo.objectives.base import Objective -from echo.validators import ArrayType +from echo.validators import ( + ArrayType, + block_rates_validator, + import_or_export_demand_set_validator, + reset_periods_validator, +) +@define class Tariff(Objective): - tariff_array: ArrayType | list # tariff array prices should always be positive - expansion_periods: PositiveInt | None = 1 + tariff_array: ArrayType | list = field(kw_only=True) # tariff array prices should always be positive + expansion_periods: int = field(default=1, validator=validators.gt(0)) @staticmethod def return_tariff_dict(array: list[float] | np.ndarray, expansion_periods: int) -> dict: @@ -30,20 +35,21 @@ def return_tariff_dict(array: list[float] | np.ndarray, expansion_periods: int) return vals +@define class ImportTariff(Tariff): """The ImportTariff objective applies a price per kWh of energy imported at a defined port.""" - component: Port - import_tariff_dict: dict | None + component: Port = field(kw_only=True) + import_tariff_dict: dict | None = field() + + @import_tariff_dict.default + def _import_tariff_dict_default(self) -> dict: + return self.return_tariff_dict(self.tariff_array, self.expansion_periods) @property def import_tariff(self) -> str: return "import_tariff_" + self.name - def __init__(self, **data) -> None: - super().__init__(**data) - self.import_tariff_dict = self.return_tariff_dict(self.tariff_array, self.expansion_periods) - def create_params(self, model: EchoConcreteModel, df: pd.DataFrame) -> None: setattr( model, @@ -67,21 +73,22 @@ def objective_expr(self, model: EchoConcreteModel) -> float: ) +@define class ExportTariff(Tariff): """The ExportTariff objective applies a tariff, defined as an array of prices, to the negative (exporting) component of the specified port.""" - component: Port - export_tariff_dict: dict | None + component: Port = field(kw_only=True) + export_tariff_dict: dict | None = field() + + @export_tariff_dict.default + def _export_tariff_dict_default(self) -> dict: + return self.return_tariff_dict(self.tariff_array, self.expansion_periods) @property def export_tariff(self) -> str: return "export_tariff_" + self.name - def __init__(self, **data) -> None: - super().__init__(**data) - self.export_tariff_dict = self.return_tariff_dict(self.tariff_array, self.expansion_periods) - def create_params(self, model: EchoConcreteModel, df: pd.DataFrame) -> None: setattr( model, @@ -105,37 +112,30 @@ def objective_expr(self, model: EchoConcreteModel) -> float: ) +@define class BlockTariff(Objective): """A block tariff, or step tariff, divides consumption over a time period into different blocks, and each block has a different price.""" - component: Port - blocks: list # list of consumption blocks/steps (cumulative) as tuple ranges - rates: list # list of rates per tuple - reset_periods: list = [] - reset_index: en.RangeSet + component: Port = field(kw_only=True) + blocks: list = field( + kw_only=True, validator=block_rates_validator + ) # list of consumption blocks/steps (cumulative) as tuple ranges + rates: list = field(kw_only=True, validator=block_rates_validator) # list of rates per tuple + reset_periods: list = field(factory=list) + reset_index: en.RangeSet = field(default=en.RangeSet(0, 0)) + + @reset_periods.validator + def _set_reset_index(self, attributes, value) -> None: # noqa ANN001 + if self.reset_periods is not None: + self.reset_index = en.RangeSet(0, len(self.reset_periods) - 1) + else: + self.reset_index = en.RangeSet(0, 0) @property def num_price_bands(self) -> int: return len(self.rates) - @root_validator - def check_block_rates(cls, values: dict) -> dict: - validate( - len(values.get("blocks")) + 1 == len(values.get("rates")), - "Enter one more rate than num blocks", - ) - return values - - @root_validator(pre=True) - def set_reset_index(cls, values: dict) -> dict: - rp = values.get("reset_periods") - if rp is not None: - values["reset_index"] = en.RangeSet(0, len(rp) - 1) - else: - values["reset_index"] = en.RangeSet(0, 0) - return values - def get_block_var_name(self, i: int) -> str: return "block_" + str(i) @@ -171,6 +171,7 @@ def _get_active_periods( return initial_window_val +@define class BlockImportTariff(BlockTariff): @property def window_active(self) -> str: @@ -218,20 +219,21 @@ def objective_expr(self, model: EchoConcreteModel) -> float: return total +@define class PathTariff(Tariff): """The PathTariff objective applies a cost per kW of power flow on a specified path.""" - component: Path - path_tariff_dict: dict | None + component: Path = field(kw_only=True) + path_tariff_dict: dict = field() + + @path_tariff_dict.default + def _path_tariff_dict_default(self) -> dict: + return self.return_tariff_dict(self.tariff_array, self.expansion_periods) @property def path_tariff(self) -> str: return "path_tariff_" + self.name - def __init__(self, **data) -> None: - super().__init__(**data) - self.path_tariff_dict = self.return_tariff_dict(self.tariff_array, self.expansion_periods) - def create_params(self, model: EchoConcreteModel, df: pd.DataFrame) -> None: setattr( model, @@ -252,11 +254,12 @@ def objective_expr(self, model: EchoConcreteModel) -> float: ) +@define class ThroughputCost(Objective): """A ThroughputCost objective applies a fixed rate to total throughput (i.e. import minus export) at a port.""" - component: Port - rate: PositiveFloat + component: Port = field(kw_only=True) + rate: float = field(kw_only=True, validator=validators.gt(0)) def apply_constraints(self, model: EchoConcreteModel) -> None: if hasattr(model, self.component.pos) is False: @@ -289,7 +292,8 @@ class Day(Enum): holiday = "holiday" -class TimePeriod(EchoBaseModel): +@define +class TimePeriod: start_time: time end_time: time day_type: list[Day] @@ -363,19 +367,19 @@ def overlaps(self, other: "TimePeriod") -> bool: return False -class Window(EchoBaseModel): +@define +class Window: """Class for specifying window over which a tariff is calculated using datetimes""" - time_periods: list[TimePeriod] + time_periods: list[TimePeriod] = field(factory=list) reset_periods: ResetPeriod | None = None - @validator("time_periods") - def non_overlapping_periods(cls, v: list[TimePeriod]) -> list[TimePeriod]: - for i in range(len(v)): - for j in range(i + 1, len(v)): - if v[i].overlaps(v[j]): - raise ValueError(f"TimePeriod {v[i]} overlaps with TimePeriod {v[j]}") - return v + @time_periods.validator + def _non_overlapping_periods(self, attributes, value) -> None: # noqa ANN001 + for i in range(len(value)): + for j in range(i + 1, len(value)): + if value[i].overlaps(value[j]): + raise ValueError(f"TimePeriod {value[i]} overlaps with TimePeriod {value[j]}") def to_bool_periods(self, df: pd.DataFrame) -> np.ndarray: """To convert a window to a bool array""" @@ -446,20 +450,28 @@ def perform_rollover_calc(diff_array: np.ndarray) -> list[int]: return _find_rollover(df, interval_duration) -class DemandCharge(EchoBaseModel): +@define +class DemandCharge: """A demand charge is a rate that applies to the maximum demand over one or many specified time windows.""" - uid: str = Field(default_factory=shortuuid.uuid) - name: str - rate: NonNegativeFloat + rate: float = field(kw_only=True, validator=validators.ge(0)) + window_array: ArrayType | list = field(kw_only=True, validator=reset_periods_validator) + reset_periods: ArrayType | list | None = field(default=None, validator=reset_periods_validator) + num_reset_periods: int = 0 + reset_index: en.RangeSet = en.RangeSet( + 0, 0 + ) # index for separating different reset periods (get set by 'reset_periods_validator'). + min_demand: float = 0.0 - window_array: ArrayType | list - reset_periods: ArrayType | list - import_demand: bool = False - export_demand: bool = False + import_demand: bool = field(default=False, validator=import_or_export_demand_set_validator) + export_demand: bool = field(default=False, validator=import_or_export_demand_set_validator) - num_reset_periods: int = 0 - reset_index: en.RangeSet # index for separating different reset periods + uid: str = field(factory=shortuuid.uuid) + name: str = field() + + @name.default + def _set_edge_name_default(self) -> str: + return "dc_" + str(self.uid) @property def max_demand_val(self) -> str: @@ -469,43 +481,6 @@ def max_demand_val(self) -> str: def window_active(self) -> str: return "window_active_" + self.name - @root_validator(pre=True) - def check_reset_periods(cls, values: dict) -> dict: - rp = values.get("reset_periods") - window_array = values.get("window_array") - if rp is not None: - validate( - sum(rp) == len(window_array), - f"Sum of reset period lengths ({sum(rp)}) is not equal to window array length ({len(window_array)}).", - ) - values["num_reset_periods"] = len(rp) - else: - values["reset_periods"] = [len(window_array)] - values["num_reset_periods"] = 1 - values["reset_index"] = en.RangeSet(0, values.get("num_reset_periods") - 1) - return values - - @root_validator - def check_import_or_export(cls, values: dict) -> dict: - validate( - values.get("import_demand") is True or values.get("export_demand") is True, - ( - "Please use ImportDemandCharge or ExportDemandCharge classes, or alternatively," - " set DemandCharge.import_demand or DemandCharge.export_demand as True before adding " - "the demand charge to the demand tariff objective." - ), - ) - return values - - @root_validator(pre=True) - def set_uid_and_name(cls, values: dict) -> dict: - if not values.get("uid"): - values["uid"] = shortuuid.uuid() - - if not values.get("name"): - values["name"] = "dc_" + str(values["uid"]) - return values - @staticmethod def _get_active_periods(window_bool: np.ndarray, reset_periods: list[int]) -> dict[tuple[int, int, int], float]: # todo only works for single expansion period @@ -577,24 +552,27 @@ def get_objective_total(self, model: EchoConcreteModel) -> float: return expr +@define class ImportDemandCharge(DemandCharge): - import_demand = True - export_demand = False - min_demand: NonNegativeFloat = 0.0 + import_demand: bool = True + export_demand: bool = False + min_demand: float = field(default=0.0, validator=validators.ge(0)) +@define class ExportDemandCharge(DemandCharge): - import_demand = False - export_demand = True - min_demand: NonPositiveFloat = 0.0 + import_demand: bool = False + export_demand: bool = True + min_demand: float = field(default=0.0, validator=validators.le(0)) +@define class DemandTariffObjective(Objective): """A demand tariff objective contains a set of one or more demand charges.""" - component: Port - demand_charges: list[DemandCharge | ImportDemandCharge | ExportDemandCharge] - expansion_periods: PositiveInt | None = 1 + component: Port = field(kw_only=True) + demand_charges: list[DemandCharge | ImportDemandCharge | ExportDemandCharge] = field(kw_only=True) + expansion_periods: int = field(default=1, validator=validators.gt(0)) def verify_objective(self, model: EchoConcreteModel, df: pd.DataFrame) -> None: def verify_non_overlapping() -> None: diff --git a/src/echo/validators.py b/src/echo/validators.py index 888cf9b1..a611b92a 100644 --- a/src/echo/validators.py +++ b/src/echo/validators.py @@ -1,36 +1,20 @@ -from collections.abc import Generator from numbers import Number from typing import Any +import attrs import numpy as np -from pydantic import Field +import pyomo.environ as en -from echo.exceptions import validate +from echo.configuration import Units +from echo.exceptions import ConfigurationError, validate FloatData = dict[Any, float] | list[float] | set[float] | float | np.ndarray - -class ArrayType(np.ndarray): - numpy_array: np.ndarray = Field(default_factory=lambda: np.zeros(10)) - - @classmethod - def __get_validators__(cls) -> Generator: - yield cls.validate - - # todo actually validate this type - @classmethod - def validate(cls, v: np.ndarray) -> np.ndarray: - if type(v) is str: - raise ValueError("Array Type cannot be a string.") - return v - - class Config: - arbitrary_types_allowed = True - - -def var_in_range(var1: float, range_min: float, range_max: float) -> ValueError | None: - if var1 < range_min or var1 > range_max: - return ValueError() +# ArrayType is a type alias for np.ndarray +# Originally ArrayType was a subclass of np.ndarray with added pydantic type validation +# This is not possible in attrs (type annotation have no runtime effects outside of pydantic +# and so can't "trigger" any validation) hence we replace the ArrayType class with a type alias. +ArrayType = np.ndarray def is_non_negative(v: FloatData | None, err_msg: str) -> FloatData | None: @@ -75,38 +59,33 @@ def is_non_positive(v: FloatData | None, err_msg: str) -> FloatData | None: return v -def import_cons_check(v: FloatData) -> FloatData: - v = is_non_negative(v, "Import constraint should be positive, following positive load convention") - return v +def import_constraint_validator(instance, attributes, value) -> None: # noqa ANN001 + is_non_negative(value, "Import constraint should be positive, following positive load convention") -def export_cons_check(v: FloatData) -> FloatData: - v = is_non_positive(v, "Export constraint should be negative following positive load convention.") - return v +def export_constraint_validator(instance, attributes, value) -> None: # noqa ANN001 + is_non_positive(value, "Export constraint should be negative following positive load convention.") -def nonnegative_load(v: FloatData) -> FloatData: - v = is_non_negative(v, "Load array entries should all be non negative.") - return v +def nonnegative_load_validator(instance, attributes, value) -> None: # noqa ANN001 + is_non_negative(value, "Load array entries should all be non negative.") -def nonpositive_generation(v: FloatData) -> FloatData: - v = is_non_positive(v, "Generation array entries should all be non positive.") - return v +def nonpositive_generation_validator(instance, attributes, value) -> None: # noqa ANN001 + is_non_positive(value, "Generation array entries should all be non positive.") -def nonnegative_costs(v: FloatData) -> FloatData: - v = is_non_negative(v, "Costs should be positive") - return v +def update_constraint_values(instance, attributes, value) -> None: # noqa ANN001 + # Keeps the charging/discharging power limits in sync the import/export constraint limits + instance.import_constraint_value = instance.charging_power_limit + instance.export_constraint_value = instance.discharging_power_limit -def dod_checks(cls, values: dict) -> dict: # noqa ANN001 +def depth_of_discharge_validator(instance, attributes, value) -> None: # noqa ANN001 """Validator for depth of discharge.""" # Check which dod representation we have - dod_lim = values.get("depth_of_discharge_limit") - max_cap = values.get("max_capacity") - init_soc = values.get("initial_state_of_charge") - set_stateful_attrs_at_init = values.get("set_stateful_attrs_at_init") + dod_lim = instance.depth_of_discharge_limit + max_cap = instance.max_capacity # Check dod representation if 0 <= dod_lim <= 1: @@ -118,15 +97,17 @@ def dod_checks(cls, values: dict) -> dict: # noqa ANN001 else: raise ValueError("DoD must be entered as decimal fraction or percentage of max capacity") - values["min_soc"] = min_soc + instance.min_soc = min_soc - # Check initial soc is within bounds - if set_stateful_attrs_at_init: - check_initial_state_of_charge_within_bounds( - initial_state_of_charge=init_soc, min_soc=min_soc, max_capacity=max_cap - ) - return values +def soc_conserv_validator(instance, attributes, value) -> None: # noqa ANN001 + """Check there is a converv cost and availability when soc conserv is enabled""" + soc_conserv = instance.soc_conserv + soc_conserv_cost = instance.soc_conserv_cost + available = instance.available + if soc_conserv is not None: + validate(soc_conserv_cost is not None, "soc_conserv requires soc_conserv_cost") + validate(available is not None, "soc_conserve requires available") def check_initial_state_of_charge_within_bounds( @@ -140,10 +121,10 @@ def check_initial_state_of_charge_within_bounds( ) -def check_bound_order(cls, values: dict) -> dict: # noqa ANN001 +def bound_order_validator(instance, attributes, value) -> None: # noqa ANN001 """Checks that lower bound is smaller than upper bound.""" - lb = values.get("lower_bound") - ub = values.get("upper_bound") + lb = instance.lower_bound + ub = instance.upper_bound if (lb is not None) and (ub is not None): if hasattr(lb, "__iter__"): validate(len(lb) == len(ub), "Lower bound and upper bound are mismatched lengths.") @@ -153,31 +134,27 @@ def check_bound_order(cls, values: dict) -> dict: # noqa ANN001 else: if lb >= ub: raise ValueError("Lower bound should be less than upper bound.") - return values - - -def node_unit_validator(cls, values: dict) -> dict: # noqa ANN001 - """Checks that a tellegen and aggregation nodes' ports all have the same units.""" - ports = values.get("ports") - u = None - nominal_units = values.get("port_units") - if ports is not None: - for port_key, p in ports.items(): - if u is not None: - validate(p.units == u, "Tellegen and Aggregation Node ports must have the same units.") - else: - u = p.units - if nominal_units is not None: + + +def ports_have_same_units_validator(instance, attributes, value) -> None: # noqa ANN001 + """Raises a ConfigurationError if the units of the ports are not the same""" + port_units = set([port.units for port in value.values()]) + validate(len(port_units) <= 1, "Tellegen and Aggregation Node ports must have the same units.") + + +def ports_match_nominal_units_validator(instance, attributes, value) -> None: # noqa ANN001 + if hasattr(instance, "nominal_units"): + if instance.nominal_units is not None: + for port_name, port in value.items(): validate( - p.units == nominal_units, f"Port {port_key} units do not match nominal node units {nominal_units}." + port.units == instance.nominal_units, + f"Port '{port_name}' units do not match nominal node units '{instance.nominal_units}'.", ) - return values - -def validate_piecewise_arrays(cls, values: dict) -> dict: # noqa ANN001 - input_points = values.get("input_points") - output_points = values.get("output_points") +def piecewise_arrays_validator(instance, attributes, value) -> None: # noqa ANN001 + input_points = instance.input_points if hasattr(instance, "input_points") else None + output_points = instance.output_points if hasattr(instance, "output_points") else None if input_points is not None and output_points is not None: validate(len(input_points) == len(output_points), "Mismatched indices for input and output dictionaries.") for k, _ in input_points.items(): @@ -186,44 +163,38 @@ def validate_piecewise_arrays(cls, values: dict) -> dict: # noqa ANN001 f"Input and output arrays are not equal lengths for index {k}", ) - return values +def set_bounds_from_piecewise_points_validator(instance, attributes, value) -> None: # noqa ANN001 + input_points = instance.input_points + output_points = instance.output_points + if input_points is not None: + instance.max_input = max(max(input_points.values())) + instance.min_input = min(min(input_points.values())) + if output_points is not None: + instance.max_output = max(max(output_points.values())) + instance.min_output = min(min(output_points.values())) -def set_bounds_from_piecewise_points(cls, values: dict) -> dict: # noqa ANN001 - input_points = values.get("input_points") - output_points = values.get("output_points") - if input_points is not None and output_points is not None: - values["max_input"] = max(max(input_points.values())) - values["min_input"] = min(min(input_points.values())) - values["max_output"] = max(max(output_points.values())) - values["min_output"] = min(min(output_points.values())) - return values - - -def set_output_bounds_from_input_bounds_and_cop_and_startup_cop(cls, values: dict) -> dict: # noqa ANN001 - cop = values.get("cop") - eta = values.get("startup_cop") - max_in = values.get("max_input") - min_in = values.get("min_input") - values["max_output"] = max_in * cop * -1 - if eta is not None: - values["min_output"] = min_in * eta * -1 + +def set_output_bounds_validator(instance, attributes, values) -> None: # noqa ANN001 + if instance.min_input is None: + raise ValueError("'min_input' must be set on GasBoilerFixedCOP.") + instance.max_output = instance.max_input * instance.cop * -1 + if instance.startup_cop is not None: + instance.min_output = instance.min_input * instance.startup_cop * -1 else: - values["min_output"] = min_in * cop * -1 - return values + instance.min_output = instance.min_input * instance.cop * -1 -def validate_startup_efficiency(cls, values: dict) -> dict: # noqa ANN001 - cop = values.get("cop") - eta = values.get("startup_cop") - if eta is not None: - validate(cop >= eta, "Startup efficiency should be less than coefficient of performance (cop)") - return values +def startup_efficiency_validator(instance, attributes, value) -> None: # noqa ANN001 + if instance.startup_cop is not None: + validate( + instance.cop >= instance.startup_cop, + "Startup efficiency should be less than coefficient of performance (cop)", + ) -def validate_partial_load_cop(cls, values: dict) -> dict: # noqa ANN001 - partial_load_cop = values.get("partial_load_cop") - for k, v in partial_load_cop.items(): +def partial_load_cop_validator(instance, attributes, value) -> None: # noqa ANN001 + for k, v in value.items(): validate( 0 <= k <= 1, f"All keys in partial load cop must be float values between 0 and 1, offending key {k}", @@ -232,13 +203,10 @@ def validate_partial_load_cop(cls, values: dict) -> dict: # noqa ANN001 0 <= v <= 1, f"All values in partial load cop must be float values between 0 and 1, offending value {v}", ) - return values -def validate_temperature_dependent_cop(cls, values: dict) -> dict: # noqa ANN001 - """Validate temperature dependent cop dictionary""" - temperature_cop_coeff = values.get("temperature_dependent_cop") - for k, v in temperature_cop_coeff.items(): +def temperature_dependent_cop_validator(instance, attributes, value) -> None: # noqa ANN001 + for k, v in value.items(): validate( -10 <= k <= 50, # TODO: reasonable value range is different between air cooled and water cooled chillers. @@ -250,27 +218,73 @@ def validate_temperature_dependent_cop(cls, values: dict) -> dict: # noqa ANN00 0 < v <= 1, f"All values in temperature dependent cop must be float values between 0 and 1, offending value {v}", ) - return values -def non_negative_cop_check(v: FloatData) -> FloatData: - v = is_non_negative(v, "Coefficient of performance for heating and cooling must be given as non_negative value") - return v +def non_negative_cop_validator(instance, attributes, value) -> None: # noqa ANN001 + is_non_negative(value, "Coefficient of performance for heating and cooling must be given as non_negative value") -def validate_partition_ports(cls, values: dict) -> dict: # noqa ANN001 +def partitions_port_validator(instance, attributes, value) -> None: # noqa ANN001 """Validate that set of ports defined across different partitions are unique""" - partitions = values.get("partitions") + partitions = value + node_name = instance.node_name if hasattr(instance, "node_name") else "unknown-node" port_name_list = [_port.port_name for v in partitions.values() for _port in v] port_uid_list = [_port.uid for v in partitions.values() for _port in v] validate( len(port_name_list) == len(set(port_name_list)), "All ports defined across partitions of PartitionedMultiCommodityTellegenNode must have unique names." - f"Offending node {values.get('node_name')}", + f"Offending node '{node_name}'", ) validate( len(port_uid_list) == len(set(port_uid_list)), "All ports defined across partitions of PartitionedMultiCommodityTellegenNode must have unique uids." - f"Offending node {values.get('node_name')}", + f"Offending node '{node_name}'", + ) + + +def thermal_units_validator(instance, attributes, value) -> None: # noqa ANN001 + allowable_thermal_units = {Units.JPS, Units.KWT} + if value not in allowable_thermal_units: + raise ValueError(f"Only allowed units are KW Thermal (KWT) and Joules per second (JPS). Received {value}") + + +def temperature_range_validator(instance, attributes, value) -> None: # noqa ANN001 + """Temperature range must be non-zero and positive""" + if instance.max_temp - instance.min_temp <= 0: + raise ValueError( + "Temperature range must be non-zero and positive." + f"Max temp ('{instance.max_temp}') <= min temp ('{instance.min_temp}')." + ) + + +def import_or_export_demand_set_validator(instance, attributes, value) -> None: # noqa ANN001 + if not instance.import_demand and not instance.export_demand: + raise ConfigurationError( + "Please use set either DemandCharge.import_demand or Demand.export_demand." + " Alternatively use instances of ImportDemandCharge or ExportDemandCharge." + ) + + +def reset_periods_validator(instance, attributes, value) -> None: # noqa ANN001 + if instance.reset_periods is not None: + validate( + sum(instance.reset_periods) == len(instance.window_array), + ( + f"Sum of reset period lengths ({sum(instance.reset_periods)}) is not equal" + f" to window array length ({len(instance.window_array)})." + ), + ) + else: + # Prevent attrs from retriggering this validator again when we set 'reset_periods' from within the validator + with attrs.validators.disabled(): + instance.reset_periods = [len(instance.window_array)] + + instance.num_reset_periods = len(instance.reset_periods) + instance.reset_index = en.RangeSet(0, instance.num_reset_periods - 1) + + +def block_rates_validator(instance, attributes, value) -> None: # noqa ANN001 + validate( + len(instance.blocks) + 1 == len(instance.rates), + "Enter one more rate than num blocks", ) - return values diff --git a/tests/conftest.py b/tests/conftest.py index 9913def1..58060134 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -5,6 +5,8 @@ from echo.models.scenario import EchoConcreteModel, ScenarioSettings, engine_settings_from_environment +os.environ["ECHO_DISABLE_EXPERIMENTAL_PATH_WARNING"] = "1" + @pytest.fixture def can_optimiser_do_non_linear_optimisation() -> bool: diff --git a/tests/integration/test_evs.py b/tests/integration/test_evs.py index 465ab1c8..4bc884de 100644 --- a/tests/integration/test_evs.py +++ b/tests/integration/test_evs.py @@ -3035,7 +3035,7 @@ def test_ev_demand_profile_set_stateful_attrs(): assert isinstance(ev.port_uid, str) # Inject some demand data into it - assert ev.ports["demand"].initial_value is None + assert ev.ports["demand"].initial_value == 0 ev.set_stateful_attrs(demand=[1, 2, 3, 4, 5]) assert isinstance(ev.ports["demand"].initial_value, dict) assert len(ev.ports["demand"].initial_value.keys()) == 5 @@ -3842,8 +3842,7 @@ def test_update_node_EVV0G(): # Assert that the ElectricalDemand port on the edge and on the EV node are identical, but not the same object. This # is where some of the pydantic fun occurs - pydantic will instantiate a new, and identical, instance of a port # when constructing the edges. - assert old_edge_port == old_ev_cp_port - assert id(old_edge_port) != id(old_ev_cp_port) + assert old_edge_port is old_ev_cp_port system.update_node( "ev", @@ -3865,14 +3864,12 @@ def test_update_node_EVV0G(): # Assert that the ElectricalDemand port on the edge and on the EV node are identical, but not the same object. This # is where some of the pydantic fun occurs - pydantic will instantiate a new, and identical, instance of a port # when constructing the edges. - assert new_edge_port == new_ev_cp_port - assert id(new_edge_port) != id(new_ev_cp_port) + assert new_edge_port is new_ev_cp_port # Assert that the ElectricalDemand port on the edge as well as the port on the EV node are the same object before # and after update_node is called. We need to also assert that the memory location is the same as all attribute # names could be potentially identical (if they've been copied into a new instance completely for example). - assert old_ev_cp_port == new_ev_cp_port - assert id(old_edge_port) == id(new_edge_port) + assert old_edge_port is new_edge_port # Test that the update EV node will still work in an optimisation problem. # Create objectives/tariffs @@ -3971,8 +3968,7 @@ def test_update_node_EVV1G(): # Assert that the ElectricalDemand port on the edge and on the EV node are identical, but not the same object. This # is where some of the pydantic fun occurs - pydantic will instantiate a new, and identical, instance of a port # when constructing the edges. - assert old_edge_port == old_ev_cp_port - assert id(old_edge_port) != id(old_ev_cp_port) + assert old_edge_port is old_ev_cp_port system.update_node( "ev", @@ -3994,14 +3990,12 @@ def test_update_node_EVV1G(): # Assert that the ElectricalDemand port on the edge and on the EV node are identical, but not the same object. This # is where some of the pydantic fun occurs - pydantic will instantiate a new, and identical, instance of a port # when constructing the edges. - assert new_edge_port == new_ev_cp_port - assert id(new_edge_port) != id(new_ev_cp_port) + assert new_edge_port is new_ev_cp_port # Assert that the ElectricalDemand port on the edge as well as the port on the EV node are the same object before # and after update_node is called. We need to also assert that the memory location is the same as all attribute # names could be potentially identical (if they've been copied into a new instance completely for example). - assert old_ev_cp_port == new_ev_cp_port - assert id(old_edge_port) == id(new_edge_port) + assert old_ev_cp_port is new_ev_cp_port # Test that the update EV node will still work in an optimisation problem. # Create objectives/tariffs @@ -4100,8 +4094,7 @@ def test_update_node_EVV2G(): # Assert that the ElectricalDemand port on the edge and on the EV node are identical, but not the same object. This # is where some of the pydantic fun occurs - pydantic will instantiate a new, and identical, instance of a port # when constructing the edges. - assert old_edge_port == old_ev_cp_port - assert id(old_edge_port) != id(old_ev_cp_port) + assert old_edge_port is old_ev_cp_port system.update_node( "ev", @@ -4123,14 +4116,12 @@ def test_update_node_EVV2G(): # Assert that the ElectricalDemand port on the edge and on the EV node are identical, but not the same object. This # is where some of the pydantic fun occurs - pydantic will instantiate a new, and identical, instance of a port # when constructing the edges. - assert new_edge_port == new_ev_cp_port - assert id(new_edge_port) != id(new_ev_cp_port) + assert new_edge_port is new_ev_cp_port # Assert that the ElectricalDemand port on the edge as well as the port on the EV node are the same object before # and after update_node is called. We need to also assert that the memory location is the same as all attribute # names could be potentially identical (if they've been copied into a new instance completely for example). - assert old_ev_cp_port == new_ev_cp_port - assert id(old_edge_port) == id(new_edge_port) + assert old_ev_cp_port is new_ev_cp_port # Test that the update EV node will still work in an optimisation problem. # Create objectives/tariffs @@ -4206,7 +4197,7 @@ def test_v0g_with_discharging_power_limit_and_usage_power_limit(): soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-10, ) @@ -4263,7 +4254,7 @@ def test_v0g_with_none_usage_power_limit_fails_if_discharge_power_limit_is_small soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=None, ) @@ -4291,7 +4282,7 @@ def test_v1g_with_discharging_power_limit_and_usage_power_limit_greater_than_usa soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-15, ) @@ -4321,7 +4312,7 @@ def test_v1g_with_usage_power_limit_less_than_usage(): soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-1, ) @@ -4350,7 +4341,7 @@ def test_v1g_with_discharging_power_limit_lt_usage_usage_power_limit_gt_usage(): soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-10, ) @@ -4380,7 +4371,7 @@ def test_v1g_with_discharging_power_limit_and_usage_power_limit_less_than_usage( soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-1, ) @@ -4410,7 +4401,7 @@ def test_v1g_with_none_usage_power_limit_fails_if_discharge_power_limit_is_small soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=None, ) @@ -4438,7 +4429,7 @@ def test_v2g_with_discharging_power_limit_and_usage_power_limit_greater_than_usa soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-15, ) @@ -4468,7 +4459,7 @@ def test_v2g_with_usage_power_limit_less_than_usage(): soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-1, ) @@ -4497,7 +4488,7 @@ def test_v2g_with_discharging_power_limit_lt_usage_usage_power_limit_gt_usage(): soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-10, ) @@ -4527,7 +4518,7 @@ def test_v2g_with_discharging_power_limit_and_usage_power_limit_less_than_usage( soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=-1, ) @@ -4557,6 +4548,6 @@ def test_v2g_with_none_usage_power_limit_fails_if_discharge_power_limit_is_small soc_conserv_cost=0.0, interval_duration=interval_duration, tod_charging=None, - trip_slack=False, + enable_trip_slack=False, usage_power_limit=None, ) diff --git a/tests/integration/test_rebuild_optimisation_graph.py b/tests/integration/test_rebuild_optimisation_graph.py index c8b0ce12..cf4e96ac 100644 --- a/tests/integration/test_rebuild_optimisation_graph.py +++ b/tests/integration/test_rebuild_optimisation_graph.py @@ -1,5 +1,3 @@ -import pytest - from echo.configuration import Units from echo.models.agnostic import FlexPort, TellegenNode from echo.models.base import Node, OptimisationGraph @@ -38,17 +36,17 @@ def test_port_reference_is_made_in_edge(): # Create edge objects and add to graph system.connect_ports_and_create_edge(grid.ports["grid_to_cp"], connection_point.ports["cp_to_grid"]) - with pytest.raises(Exception): - assert id(grid.ports["grid_to_cp"]) == id(system.get_edge(("grid", "cp")).vertices[0]) - assert id(connection_point.ports["cp_to_grid"]) == id(system.get_edge(("grid", "cp")).vertices[1]) + assert grid.ports["grid_to_cp"] is system.get_edge(("grid", "cp")).vertices[0] + assert connection_point.ports["cp_to_grid"] is system.get_edge(("grid", "cp")).vertices[1] def test_rebuild_all_edges(): """Tests the rebuild_all_edges function usage after stateful data has been injected.""" def assert_node_edge_port_values( - v0g_node_port_value: dict[tuple[int, int], float] | None, - v0g_edge_port_value: dict[tuple[int, int], float] | None, + ev: EVV0G | EVV1G | EVV2G, + v0g_node_port_value: dict[tuple[int, int], float] | float, + v0g_edge_port_value: dict[tuple[int, int], float] | float, v12g_node_value: dict[tuple[int, int], float] | None, v12g_edge_value: dict[tuple[int, int], float] | None, ): @@ -141,8 +139,9 @@ def assert_node_edge_port_values( pv.add_generation_profile_from_array(solar_data, expansion_periods) assert_node_edge_port_values( - v0g_node_port_value=None, - v0g_edge_port_value=None, + ev=ev, + v0g_node_port_value=0, + v0g_edge_port_value=0, v12g_node_value=None, v12g_edge_value=None, ) @@ -156,6 +155,7 @@ def assert_node_edge_port_values( ) assert_node_edge_port_values( + ev=ev, v0g_node_port_value={ (0, 0): 5.0, (0, 1): 5.0, @@ -191,9 +191,10 @@ def assert_node_edge_port_values( ) # Rebuild all the edges before optimisation - system.rebuild_all_edges() + # system.rebuild_all_edges() assert_node_edge_port_values( + ev=ev, v0g_node_port_value={ (0, 0): 5.0, (0, 1): 5.0, diff --git a/tests/unit/models/agnostic/test_agnostic_base.py b/tests/unit/models/agnostic/test_agnostic_base.py index f0aa0d31..167479bb 100644 --- a/tests/unit/models/agnostic/test_agnostic_base.py +++ b/tests/unit/models/agnostic/test_agnostic_base.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.agnostic.base import Sink, Source @@ -12,9 +11,9 @@ ([-42.0, -12.0], None), ([-15], None), ([0.0], None), - ([5.0], ValidationError), - ([42.0, -12.0], ValidationError), - ([15], ValidationError), + ([5.0], ValueError), + ([42.0, -12.0], ValueError), + ([15], ValueError), ], ) def test_source_port_validation(initial_value, expected_error): @@ -34,9 +33,9 @@ def test_source_port_validation(initial_value, expected_error): ([-42.0, -12.0], None), ([-15], None), ([0.0], None), - ([5.0], ValidationError), - ([42.0, -12.0], ValidationError), - ([15], ValidationError), + ([5.0], ValueError), + ([42.0, -12.0], ValueError), + ([15], ValueError), ], ) def test_source_port_process_initial_value_performs_validation(initial_value, expected_error): @@ -58,9 +57,9 @@ def test_source_port_process_initial_value_performs_validation(initial_value, ex ([42.0, 12.0], None), ([15], None), ([0.0], None), - ([-5.0], ValidationError), - ([-42.0, 12.0], ValidationError), - ([-15], ValidationError), + ([-5.0], ValueError), + ([-42.0, 12.0], ValueError), + ([-15], ValueError), ], ) def test_sink_port_validation(initial_value, expected_error): @@ -80,9 +79,9 @@ def test_sink_port_validation(initial_value, expected_error): ([42.0, 12.0], None), ([15], None), ([0.0], None), - ([-5.0], ValidationError), - ([-42.0, 12.0], ValidationError), - ([-15], ValidationError), + ([-5.0], ValueError), + ([-42.0, 12.0], ValueError), + ([-15], ValueError), ], ) def test_sink_port_process_initial_value_performs_validation(initial_value, expected_error): diff --git a/tests/unit/models/agnostic/test_bounded.py b/tests/unit/models/agnostic/test_bounded.py index dc117c75..8c628c4e 100644 --- a/tests/unit/models/agnostic/test_bounded.py +++ b/tests/unit/models/agnostic/test_bounded.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.agnostic.bounded import BoundedLoad, BoundedPort @@ -9,8 +8,8 @@ [ (0, 100, None), (0.1, 0.2, None), - (100, 0, ValidationError), # lower bound > upper bound - (50, 50, ValidationError), # lower bound == upper bound + (100, 0, ValueError), # lower bound > upper bound + (50, 50, ValueError), # lower bound == upper bound ], ) def test_boundedport_validation(lower_bound: float, upper_bound: float, expected_error): @@ -26,10 +25,10 @@ def test_boundedport_validation(lower_bound: float, upper_bound: float, expected [ (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 + (100, 0, ValueError), # lower bound > upper bound + (50, 50, ValueError), # lower bound == upper bound + (-100, 100, ValueError), # lower bound -ve + (-100, -50, ValueError), # both bounds -ve ], ) def test_boundedload_validation(lower_bound: float, upper_bound: float, expected_error): diff --git a/tests/unit/models/agnostic/test_controlled.py b/tests/unit/models/agnostic/test_controlled.py index bea1a84d..15168046 100644 --- a/tests/unit/models/agnostic/test_controlled.py +++ b/tests/unit/models/agnostic/test_controlled.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.agnostic.controlled import ControlledGen, ControlledLoad @@ -10,8 +9,8 @@ (0, 0, None), (0, 100, None), (100, 0, None), - (-85, 0, ValidationError), # min_power -ve - (0, -15, ValidationError), # max_power -ve + (-85, 0, ValueError), # min_power -ve + (0, -15, ValueError), # max_power -ve ], ) def test_controlledload_validation(min_power: float, max_power: float, expected_error): @@ -28,8 +27,8 @@ def test_controlledload_validation(min_power: float, max_power: float, expected_ (0, 0, None), (0, -100, None), (-100, 0, None), - (85, 0, ValidationError), # min_power +ve - (0, 15, ValidationError), # max_power +ve + (85, 0, ValueError), # min_power +ve + (0, 15, ValueError), # max_power +ve ], ) def test_controlledgen_validation(min_power: float, max_power: float, expected_error): diff --git a/tests/unit/models/agnostic/test_flex.py b/tests/unit/models/agnostic/test_flex.py index bca51565..394cbc36 100644 --- a/tests/unit/models/agnostic/test_flex.py +++ b/tests/unit/models/agnostic/test_flex.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.agnostic.flex import OffOrConstrainedPort @@ -9,8 +8,8 @@ [ (0, 100, None), (0.1, 0.2, None), - (100, 0, ValidationError), # lower bound > upper bound - (50, 50, ValidationError), # lower bound == upper bound + (100, 0, ValueError), # lower bound > upper bound + (50, 50, ValueError), # lower bound == upper bound ], ) def test_offorconstrainedport_validation(lower_bound: float, upper_bound: float, expected_error): diff --git a/tests/unit/models/agnostic/test_storage.py b/tests/unit/models/agnostic/test_storage.py index 5f3fe3a0..f9832009 100644 --- a/tests/unit/models/agnostic/test_storage.py +++ b/tests/unit/models/agnostic/test_storage.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.exceptions import ConfigurationError from echo.models.agnostic.storage import MobileStorage, Storage @@ -14,7 +13,7 @@ ], ) def test_storage_validation_missing_fields(storage_params): - with pytest.raises(ValidationError): + with pytest.raises(TypeError): Storage(**storage_params) @@ -22,13 +21,11 @@ def test_storage_validation_missing_fields(storage_params): "storage_capacity_cost, expected_error", [ (5.0, None), - (0.0, ValidationError), # 0 is not a pydantic PositiveFloat - (-7.0, ValidationError), # not a PostiveFloat + (0.0, ValueError), # 0 is not a pydantic PositiveFloat + (-7.0, ValueError), # not a PostiveFloat ], ) -def test_storage_validation_storage_capactity_cost( - storage_capacity_cost: float, expected_error: ValidationError | None -): +def test_storage_validation_storage_capacity_cost(storage_capacity_cost: float, expected_error): storage_params = {"max_capacity": 0, "charging_power_limit": 0, "discharging_power_limit": 0} if expected_error: with pytest.raises(expected_error): @@ -41,8 +38,8 @@ def test_storage_validation_storage_capactity_cost( "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% + ({"depth_of_discharge_limit": -0.5}, ValueError), # Dod can't be negative + ({"depth_of_discharge_limit": 110}, ValueError), # DoD can't be > 100% ], ) def test_storage_validation_depth_of_discharge_check(storage_params, expected_error): diff --git a/tests/unit/models/base/test_edge.py b/tests/unit/models/base/test_edge.py index 6873f74f..4a144b9a 100644 --- a/tests/unit/models/base/test_edge.py +++ b/tests/unit/models/base/test_edge.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.base.edge import Edge from echo.models.base.port import Port @@ -9,7 +8,7 @@ def test_edge_initialisation_missing_required_params(): # required parameters: vertices - with pytest.raises(ValidationError): + with pytest.raises(TypeError): Edge() @@ -17,8 +16,9 @@ def test_edge_initialisation_missing_required_params(): def test_edge_initialisation(edge_name): port_1 = Port() required_params = {"vertices": (port_1, port_1)} + params = {"edge_name": edge_name} if edge_name else {} - edge = Edge(edge_name=edge_name, **required_params) + edge = Edge(**params, **required_params) assert len(edge.uid) == SHORTUUID_LENGTH diff --git a/tests/unit/models/base/test_path.py b/tests/unit/models/base/test_path.py index 22abdd97..370b80ed 100644 --- a/tests/unit/models/base/test_path.py +++ b/tests/unit/models/base/test_path.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.base.path import Path @@ -8,15 +7,16 @@ def test_path_initialisation_missing_required_params(): # required parameters: vertices - with pytest.raises(ValidationError): + with pytest.raises(TypeError): Path() @pytest.mark.parametrize("path_name", [None, "path-name"]) def test_path_initialisation(path_name): required_params = {"vertices": []} + params = {"path_name": path_name} if path_name else {} - path = Path(path_name=path_name, **required_params) + path = Path(**params, **required_params) assert len(path.uid) == SHORTUUID_LENGTH @@ -25,3 +25,5 @@ def test_path_initialisation(path_name): assert path.path_name == path_name else: assert path.path_name.endswith(path.uid) + + assert path.flow_value == "flow_value_" + path.path_name diff --git a/tests/unit/models/base/test_port.py b/tests/unit/models/base/test_port.py index f8020909..a7ad06c7 100644 --- a/tests/unit/models/base/test_port.py +++ b/tests/unit/models/base/test_port.py @@ -4,7 +4,6 @@ import pandas as pd import pyomo as pyo import pytest -from pydantic import ValidationError from pyomo.core.base.var import IndexedVar from echo import constants @@ -15,6 +14,17 @@ from echo.utils import TimeSeriesData +def test_default_port_name_based_off_uid(): + port = Port() + assert port.port_name.endswith(port.uid) + + +def test_set_port_name(): + port_name = "my-port-name" + port = Port(port_name=port_name) + assert port.port_name == port_name + + @pytest.mark.parametrize( "port_params", [ @@ -110,22 +120,22 @@ def test_port_raises_configuration_error(port_params: 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 + assert port.initial_value == 0 port.process_initial_value(initial_val=raw_initial_val) assert port.initial_value == expected_initial_val @pytest.mark.parametrize( - "import_constraint_value,export_constraint_value", + "import_constraint_value,export_constraint_value,expected_exception", [ - ("NOT VALID", 1.0), # value must be float or array-like - (1.0, "NOT VALID"), # value must be float or array-like - (-1.0, -1.0), # import value cannot be negative - (1.0, 1.0), # Export value can't be + ("NOT VALID", 1.0, TypeError), # value must be float or array-like + (1.0, "NOT VALID", TypeError), # value must be float or array-like + (-1.0, -1.0, ValueError), # import value cannot be negative + (1.0, 1.0, ValueError), # Export value can't be positive ], ) -def test_validation(import_constraint_value, export_constraint_value): - with pytest.raises(ValidationError): +def test_validation(import_constraint_value, export_constraint_value, expected_exception): + with pytest.raises(expected_exception): Port( flows=Flows.Both, import_constraint=FlowConstraint.Fixed, diff --git a/tests/unit/models/electrical/ev/test_ev_with_profile.py b/tests/unit/models/electrical/ev/test_ev_with_profile.py index 08b94ea2..66affc80 100644 --- a/tests/unit/models/electrical/ev/test_ev_with_profile.py +++ b/tests/unit/models/electrical/ev/test_ev_with_profile.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.configuration import EVChargeMode from echo.models.electrical.base import ElectricalDemand @@ -12,8 +11,8 @@ (0, None), (1, None), (100, None), - (-85, ValidationError), # -ve - (-1, ValidationError), # -ve + (-85, ValueError), # -ve + (-1, ValueError), # -ve ], ) def test_ev_with_profile_validation_charging_power_limit(charging_power_limit, expected_error): diff --git a/tests/unit/models/electrical/test_inverter.py b/tests/unit/models/electrical/test_inverter.py index 69bf8011..c4af0688 100644 --- a/tests/unit/models/electrical/test_inverter.py +++ b/tests/unit/models/electrical/test_inverter.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.electrical import ElectricalPort from echo.models.electrical.inverter import Inverter @@ -11,8 +10,8 @@ (0.0, 0.0, None), (1.0, 1.0, None), (0.4, 0.7, None), - (-0.4, 0.7, ValidationError), # dc_ac_efficiency -ve - (0.4, -0.7, ValidationError), # ac_dc_efficiency -ve + (-0.4, 0.7, ValueError), # dc_ac_efficiency -ve + (0.4, -0.7, ValueError), # ac_dc_efficiency -ve ], ) def test_inverter_validation(dc_ac_efficiency, ac_dc_efficiency, expected_error): diff --git a/tests/unit/models/gas/test_boiler_fixedcop.py b/tests/unit/models/gas/test_boiler_fixedcop.py index 83a25c0f..5b871bb6 100644 --- a/tests/unit/models/gas/test_boiler_fixedcop.py +++ b/tests/unit/models/gas/test_boiler_fixedcop.py @@ -1,10 +1,9 @@ import pytest -from pydantic import ValidationError from echo.exceptions import ConfigurationError from echo.models.gas.boiler_fixedcop import GasBoilerFixedCOP -nonnegativefloat_values = [(1, None), (0, None), (-1, ValidationError)] +nonnegativefloat_values = [(1, None), (0, None), (-1, ValueError)] @pytest.mark.parametrize( @@ -12,8 +11,8 @@ [ ({"startup_cop": 0.5, "cop": 1}, None), ({"startup_cop": 0, "cop": 1}, None), - ({"startup_cop": -0.5, "cop": 1}, ValidationError), - ({"startup_cop": -0.5, "cop": -0.1}, ValidationError), + ({"startup_cop": -0.5, "cop": 1}, ValueError), + ({"startup_cop": -0.5, "cop": -0.1}, ValueError), ({"startup_cop": 1, "cop": 0.5}, ConfigurationError), ], ) diff --git a/tests/unit/models/gas/test_boiler_tempcontrolled.py b/tests/unit/models/gas/test_boiler_tempcontrolled.py index 87ffff64..729e144a 100644 --- a/tests/unit/models/gas/test_boiler_tempcontrolled.py +++ b/tests/unit/models/gas/test_boiler_tempcontrolled.py @@ -1,11 +1,8 @@ import pytest -from pydantic import ValidationError from echo.exceptions import ConfigurationError from echo.models.gas.boiler_tempcontrolled import TempControlledBoiler -nonnegativefloat_values = [(1, None), (0, None), (-1, ValidationError)] - @pytest.mark.parametrize( "override_params, expected_error", diff --git a/tests/unit/models/prebuilt/test_diesel_generator.py b/tests/unit/models/prebuilt/test_diesel_generator.py index ea863a90..c947d9b4 100644 --- a/tests/unit/models/prebuilt/test_diesel_generator.py +++ b/tests/unit/models/prebuilt/test_diesel_generator.py @@ -1,9 +1,8 @@ import pytest -from pydantic import ValidationError from echo.models.prebuilt.diesel_generator import DieselGenerator -nonnegativefloat_values = [(1, None), (0, None), (-1, ValidationError)] +nonnegativefloat_values = [(1, None), (0, None), (-1, ValueError)] nonnegativefloat_attributes = [ "cop", "startup_efficiency", diff --git a/tests/unit/models/thermal/test_parameterised_chiller.py b/tests/unit/models/thermal/test_parameterised_chiller.py index 19112fca..cf1bb18b 100644 --- a/tests/unit/models/thermal/test_parameterised_chiller.py +++ b/tests/unit/models/thermal/test_parameterised_chiller.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.thermal import ParameterisedChiller @@ -8,10 +7,10 @@ "nominal_cop, max_cooling_capacity, expected_error", [ (1, 1, None), - (0, 1, ValidationError), # nominal cop 0 - (1, 0, ValidationError), # max_cooling_capacity 0 - (-0.5, 1, ValidationError), # nominal cop -ve - (1, -0.5, ValidationError), # max_cooling_capacity -ve + (0, 1, ValueError), # nominal cop 0 + (1, 0, ValueError), # max_cooling_capacity 0 + (-0.5, 1, ValueError), # nominal cop -ve + (1, -0.5, ValueError), # max_cooling_capacity -ve ], ) def test_parameterisedchiller_validation(nominal_cop, max_cooling_capacity, expected_error): diff --git a/tests/unit/models/thermal/test_parameterised_heatpump.py b/tests/unit/models/thermal/test_parameterised_heatpump.py index 687a0839..3248d25f 100644 --- a/tests/unit/models/thermal/test_parameterised_heatpump.py +++ b/tests/unit/models/thermal/test_parameterised_heatpump.py @@ -1,11 +1,10 @@ import pytest -from pydantic import ValidationError from echo.configuration import Units from echo.models.agnostic.flex import FlexPort, FlexSink from echo.models.thermal.parameterised_heatpump import ParameterisedHeatPump -values = [(1, None), (0, ValidationError), (-1, ValidationError)] +values = [(1, None), (0, ValueError), (-1, ValueError)] positivefloat_attributes = [ "nominal_heating_cop", "nominal_cooling_cop", diff --git a/tests/unit/models/thermal/test_simple_chiller.py b/tests/unit/models/thermal/test_simple_chiller.py index aff4a7a6..3d0991d7 100644 --- a/tests/unit/models/thermal/test_simple_chiller.py +++ b/tests/unit/models/thermal/test_simple_chiller.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.configuration import FlowConstraint, Units from echo.models.agnostic.flex import FlexSink @@ -11,7 +10,7 @@ def test_simple_chiller(cooling_cop_dict): SimpleChiller(max_cooling_capacity=20, cooling_cop_time_series=cooling_cop_dict) -positivefloat_values = [(1, None), (0, ValidationError), (-1, ValidationError)] +positivefloat_values = [(1, None), (0, ValueError), (-1, ValueError)] positivefloat_attributes = [ "max_cooling_capacity", "cooling_cop_constant", diff --git a/tests/unit/models/thermal/test_simple_heatpump.py b/tests/unit/models/thermal/test_simple_heatpump.py index 5059e75c..fae2c463 100644 --- a/tests/unit/models/thermal/test_simple_heatpump.py +++ b/tests/unit/models/thermal/test_simple_heatpump.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.configuration import FlowConstraint, Units from echo.models.agnostic.flex import FlexPort, FlexSink @@ -15,7 +14,7 @@ def test_simple_heatpump(cooling_cop_dict, heating_cop_dict): assert len(hp.ports) == 2 -positivefloat_values = [(1, None), (0, ValidationError), (-1, ValidationError)] +positivefloat_values = [(1, None), (0, ValueError), (-1, ValueError)] positivefloat_attributes = [ "max_cooling_capacity", "max_heating_capacity", diff --git a/tests/unit/models/thermal/test_simple_heatpump_dualoutput.py b/tests/unit/models/thermal/test_simple_heatpump_dualoutput.py index 46cd7b81..09a762b1 100644 --- a/tests/unit/models/thermal/test_simple_heatpump_dualoutput.py +++ b/tests/unit/models/thermal/test_simple_heatpump_dualoutput.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.configuration import Units from echo.models.thermal import SimpleHeatPumpDualOutput @@ -10,13 +9,12 @@ def test_simple_heatpump_dual_output(cooling_cop_dict, heating_cop_dict): hp_dual_output = SimpleHeatPumpDualOutput( cooling_cop_time_series=cooling_cop_dict, heating_cop_time_series=heating_cop_dict, - dual_output=True, ) assert len(hp_dual_output.ports) == 3 assert len([p for p in hp_dual_output.ports.values() if p.units == Units.KWT]) == 2 -@pytest.mark.parametrize("waste_heat_recovery_coeff, expected_error", [(1, None), (0, None), (-1, ValidationError)]) +@pytest.mark.parametrize("waste_heat_recovery_coeff, expected_error", [(1, None), (0, None), (-1, ValueError)]) def test_simpleheatpump_dual_output_validation(waste_heat_recovery_coeff, expected_error): if expected_error: with pytest.raises(expected_error): diff --git a/tests/unit/models/thermal/test_thermal_base.py b/tests/unit/models/thermal/test_thermal_base.py index f19912c1..d4408ed4 100644 --- a/tests/unit/models/thermal/test_thermal_base.py +++ b/tests/unit/models/thermal/test_thermal_base.py @@ -1,16 +1,15 @@ import pytest -from pydantic import ValidationError from echo.models.thermal.base import ThermalNode -positivefloat_values = [(1, None), (0, ValidationError), (-1, ValidationError)] +positivefloat_values = [(1, None), (0, ValueError), (-1, ValueError)] positivefloat_attributes = ["temp_to_energy_coef"] positivefloat_data = [ ({attribute: value}, error) for attribute in positivefloat_attributes for value, error in positivefloat_values ] -nonnegativefloat_values = [(1, None), (0, None), (-1, ValidationError)] +nonnegativefloat_values = [(1, None), (0, None), (-1, ValueError)] nonnegativefloat_attributes = [ "loss_factor", "gain_factor", diff --git a/tests/unit/models/thermal/test_thermal_storage.py b/tests/unit/models/thermal/test_thermal_storage.py index 33b3263f..4bae5856 100644 --- a/tests/unit/models/thermal/test_thermal_storage.py +++ b/tests/unit/models/thermal/test_thermal_storage.py @@ -1,10 +1,9 @@ import pytest -from pydantic import ValidationError from echo.configuration import Units from echo.models.thermal.storage import ThermalStorage -positivefloat_values = [(1, None), (0, ValidationError), (-1, ValidationError)] +positivefloat_values = [(1, None), (0, ValueError), (-1, ValueError)] positivefloat_attributes = [ "storage_mass", "specific_heat", @@ -14,7 +13,7 @@ ({attribute: value}, error) for attribute in positivefloat_attributes for value, error in positivefloat_values ] -negativefloat_values = [(-1, None), (0, ValidationError), (1, ValidationError)] +negativefloat_values = [(-1, None), (0, ValueError), (1, ValueError)] negativefloat_attributes = [ "discharging_power_limit", ] @@ -22,7 +21,7 @@ ({attribute: value}, error) for attribute in negativefloat_attributes for value, error in negativefloat_values ] -nonnegativefloat_values = [(1, None), (0, None), (-1, ValidationError)] +nonnegativefloat_values = [(1, None), (0, None), (-1, ValueError)] nonnegativefloat_attributes = [ "ins_transmittance", "surface_area", @@ -53,16 +52,16 @@ def test_thermalstorage_validation_floats(param_to_override, expected_error): @pytest.mark.parametrize( "units, expected_error", [ - (Units.NA, ValidationError), - (Units.KW, ValidationError), - (Units.CO2, ValidationError), + (Units.NA, ValueError), + (Units.KW, ValueError), + (Units.CO2, ValueError), (Units.KWT, None), # thermal unit (Units.JPS, None), # thermal unit - (Units.KWh, ValidationError), - (Units.KVA, ValidationError), - (Units.KVAR, ValidationError), - (Units.LPS, ValidationError), - (Units.CMS, ValidationError), + (Units.KWh, ValueError), + (Units.KVA, ValueError), + (Units.KVAR, ValueError), + (Units.LPS, ValueError), + (Units.CMS, ValueError), ], ) def test_thermalstorage_validation_units(units, expected_error): @@ -84,9 +83,9 @@ def test_thermalstorage_validation_units(units, expected_error): [ (0, 1, None), (-1, 0, None), - (0, 0, ValidationError), # min_temp == max_temp - (1, 1, ValidationError), # min_temp == max_temp - (1, 0, ValidationError), # min_temp > max_temp + (0, 0, ValueError), # min_temp == max_temp + (1, 1, ValueError), # min_temp == max_temp + (1, 0, ValueError), # min_temp > max_temp ], ) def test_thermalstorage_validation_temp_range(min_temp, max_temp, expected_error): diff --git a/tests/unit/objectives/test_contingency.py b/tests/unit/objectives/test_contingency.py index 3b07e028..70ebe961 100644 --- a/tests/unit/objectives/test_contingency.py +++ b/tests/unit/objectives/test_contingency.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.base import Path from echo.objectives.contingency import ContingencyNegative, ContingencyPositive @@ -9,8 +8,8 @@ "duration, expected_error", [ (1.0, None), - (0.0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1.0, ValidationError), # not a PostiveFloat + (0.0, ValueError), # 0 is not a pydantic PositiveFloat + (-1.0, ValueError), # not a PostiveFloat ], ) def test_contingencypositive_validation(duration, expected_error): @@ -29,8 +28,8 @@ def test_contingencypositive_validation(duration, expected_error): "duration, expected_error", [ (1.0, None), - (0.0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1.0, ValidationError), # not a PostiveFloat + (0.0, ValueError), # 0 is not a pydantic PositiveFloat + (-1.0, ValueError), # not a PostiveFloat ], ) def test_contingencynegative_validation(duration, expected_error): diff --git a/tests/unit/objectives/test_power.py b/tests/unit/objectives/test_power.py index 12ec277d..daef4e08 100644 --- a/tests/unit/objectives/test_power.py +++ b/tests/unit/objectives/test_power.py @@ -1,5 +1,4 @@ import pytest -from pydantic import ValidationError from echo.models.agnostic.storage import Storage from echo.objectives.power import FinalChargeObjective, NotFullyChargedPenalty @@ -9,8 +8,8 @@ "rate, expected_error", [ (1.0, None), - (0.0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1.0, ValidationError), # not a PostiveFloat + (0.0, ValueError), # 0 is not a pydantic PositiveFloat + (-1.0, ValueError), # not a PostiveFloat ], ) def test_notfullychargepenalty_validation(rate, expected_error): @@ -30,8 +29,8 @@ def test_notfullychargepenalty_validation(rate, expected_error): "rate, expected_error", [ (1.0, None), - (0.0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1.0, ValidationError), # not a PostiveFloat + (0.0, ValueError), # 0 is not a pydantic PositiveFloat + (-1.0, ValueError), # not a PostiveFloat ], ) def test_finalchargeobjective_validation(rate, expected_error): diff --git a/tests/unit/objectives/test_tariff.py b/tests/unit/objectives/test_tariff.py index 6b1e4628..936fccb5 100644 --- a/tests/unit/objectives/test_tariff.py +++ b/tests/unit/objectives/test_tariff.py @@ -2,7 +2,6 @@ import pyomo.environ as en import pytest -from pydantic import ValidationError from echo.exceptions import ConfigurationError from echo.models.base.port import Port @@ -30,11 +29,11 @@ def test_demandcharge_initialisation_required_params(parameter_to_remove): } del required_params[parameter_to_remove] - with pytest.raises(ValidationError): + with pytest.raises(TypeError): DemandCharge(import_demand=True, **required_params) -@pytest.mark.parametrize("rate,expected_error", [(1, None), (0, None), (-1, ValidationError)]) +@pytest.mark.parametrize("rate,expected_error", [(1, None), (0, None), (-1, ValueError)]) def test_demandcharge_validation(rate, expected_error): required_params = { "window_array": [], @@ -117,7 +116,6 @@ def test_demandcharge_validation_check_import_or_export(import_demand, export_de ) def test_demandcharge_validation_set_uid_and_name(override_params, expected_uid, expected_name): required_params = { - "name": None, "rate": 1, "window_array": [], "import_demand": True, @@ -136,7 +134,7 @@ def test_demandcharge_validation_set_uid_and_name(override_params, expected_uid, assert dc.name.endswith(dc.uid) -@pytest.mark.parametrize("min_demand,expected_error", [(1, None), (0, None), (-1, ValidationError)]) +@pytest.mark.parametrize("min_demand,expected_error", [(1, None), (0, None), (-1, ValueError)]) def test_importdemandcharge_validation(min_demand, expected_error): required_params = { "rate": 1, @@ -150,7 +148,7 @@ def test_importdemandcharge_validation(min_demand, expected_error): ImportDemandCharge(min_demand=min_demand, **required_params) -@pytest.mark.parametrize("min_demand,expected_error", [(-1, None), (0, None), (1, ValidationError)]) +@pytest.mark.parametrize("min_demand,expected_error", [(-1, None), (0, None), (1, ValueError)]) def test_exportdemandcharge_validation(min_demand, expected_error): required_params = { "rate": 1, @@ -186,14 +184,14 @@ def test_exportdemandcharge_validation(min_demand, expected_error): TimePeriod(start_time=time(0, 0), end_time=time(19, 0), day_type=[Day.weekday]), TimePeriod(start_time=time(18, 0), end_time=time(23, 59), day_type=[Day.weekday]), ], - ValidationError, + ValueError, ), # 1 hour overlap ( [ TimePeriod(start_time=time(0, 0), end_time=time(19, 0), day_type=[Day.weekday, Day.holiday]), TimePeriod(start_time=time(18, 0), end_time=time(23, 59), day_type=[Day.holiday]), ], - ValidationError, + ValueError, ), # 1 hour overlap on holidays ], ) @@ -210,11 +208,11 @@ def test_window_validation_non_overlapping_periods(time_periods, expected_error) "expansion_periods, expected_error", [ (1, None), - (0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1, ValidationError), # not a PostiveFloat - (-1.0, ValidationError), # not an int - (0.0, ValidationError), # not an int - (-1.0, ValidationError), # not an int + (0, ValueError), # 0 is not a pydantic PositiveFloat + (-1, ValueError), # not a PostiveFloat + (-1.0, ValueError), # not an int + (0.0, ValueError), # not an int + (-1.0, ValueError), # not an int ], ) def test_demandtariffobjective_validation(expansion_periods, expected_error): @@ -231,12 +229,12 @@ def test_demandtariffobjective_validation(expansion_periods, expected_error): "rate, expected_error", [ (1.0, None), - (0.0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1.0, ValidationError), # not a PostiveFloat + (0.0, ValueError), # 0 is not a pydantic PositiveFloat + (-1.0, ValueError), # not a PostiveFloat ], ) def test_throughputcost_validation(rate, expected_error): - required_params = {"component": Port(), "demand_charges": []} + required_params = {"component": Port()} if expected_error: with pytest.raises(expected_error): @@ -249,11 +247,11 @@ def test_throughputcost_validation(rate, expected_error): "expansion_periods, expected_error", [ (1, None), - (0, ValidationError), # 0 is not a pydantic PositiveFloat - (-1, ValidationError), # not a PostiveFloat - (-1.0, ValidationError), # not an int - (0.0, ValidationError), # not an int - (-1.0, ValidationError), # not an int + (0, ValueError), # 0 is not a pydantic PositiveFloat + (-1, ValueError), # not a PostiveFloat + (-1.0, ValueError), # not an int + (0.0, ValueError), # not an int + (-1.0, ValueError), # not an int ], ) def test_tariff_validation(expansion_periods, expected_error): diff --git a/uv.lock b/uv.lock index 17338362..b3b4ded0 100644 --- a/uv.lock +++ b/uv.lock @@ -15,6 +15,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/b3/6b4067be973ae96ba0d615946e314c5ae35f9f993eca561b356540bb0c2b/alabaster-1.0.0-py3-none-any.whl", hash = "sha256:fc6786402dc3fcb2de3cabd5fe455a2db534b371124f1f21de8731783dec828b", size = 13929, upload-time = "2024-07-26T18:15:02.05Z" }, ] +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + [[package]] name = "babel" version = "2.18.0" @@ -375,6 +384,7 @@ wheels = [ name = "echo" source = { editable = "." } dependencies = [ + { name = "attrs" }, { name = "deprecated" }, { name = "matplotlib" }, { name = "networkx" }, @@ -382,7 +392,6 @@ dependencies = [ { name = "orjson" }, { name = "pandas" }, { name = "plotly" }, - { name = "pydantic" }, { name = "pyomo" }, { name = "scikit-learn" }, { name = "scipy" }, @@ -441,6 +450,7 @@ test = [ [package.metadata] requires-dist = [ + { name = "attrs", specifier = ">=26.1.0" }, { name = "deprecated", specifier = ">=1.3.1,<2" }, { name = "matplotlib", specifier = "==3.11.1" }, { name = "networkx", specifier = ">=3.1,<4" }, @@ -448,7 +458,6 @@ requires-dist = [ { name = "orjson", specifier = ">=3.9,<4" }, { name = "pandas", specifier = ">=2.1,<3" }, { name = "plotly", specifier = ">=5.22,<6" }, - { name = "pydantic", specifier = ">=1.10,<2" }, { name = "pyomo", specifier = ">=6.6,<7" }, { name = "scikit-learn", specifier = ">=1.3,<2" }, { name = "scipy", specifier = ">=1.14.1,<2" }, @@ -1173,38 +1182,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" }, ] -[[package]] -name = "pydantic" -version = "1.10.26" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/7b/da/fd89f987a376c807cd81ea0eff4589aade783bbb702637b4734ef2c743a2/pydantic-1.10.26.tar.gz", hash = "sha256:8c6aa39b494c5af092e690127c283d84f363ac36017106a9e66cb33a22ac412e", size = 357906, upload-time = "2025-12-18T15:47:46.557Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/c1/d521e64c8130e1ad9d22c270bed3fabcc0940c9539b076b639c88fd32a8d/pydantic-1.10.26-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:116233e53889bcc536f617e38c1b8337d7fa9c280f0fd7a4045947515a785637", size = 2428347, upload-time = "2025-12-18T15:46:39.41Z" }, - { url = "https://files.pythonhosted.org/packages/2c/08/f4b804a00c16e3ea994cb640a7c25c579b4f1fa674cde6a19fa0dfb0ae4f/pydantic-1.10.26-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c3cfdd361addb6eb64ccd26ac356ad6514cee06a61ab26b27e16b5ed53108f77", size = 2212605, upload-time = "2025-12-18T15:46:41.006Z" }, - { url = "https://files.pythonhosted.org/packages/5d/78/0df4b9efef29bbc5e39f247fcba99060d15946b4463d82a5589cf7923d71/pydantic-1.10.26-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e4451951a9a93bf9a90576f3e25240b47ee49ab5236adccb8eff6ac943adf0f", size = 2753560, upload-time = "2025-12-18T15:46:43.215Z" }, - { url = "https://files.pythonhosted.org/packages/68/66/6ab6c1d3a116d05d2508fce64f96e35242938fac07544d611e11d0d363a0/pydantic-1.10.26-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9858ed44c6bea5f29ffe95308db9e62060791c877766c67dd5f55d072c8612b5", size = 2859235, upload-time = "2025-12-18T15:46:45.112Z" }, - { url = "https://files.pythonhosted.org/packages/61/4e/f1676bb0fcdf6ed2ce4670d7d1fc1d6c3a06d84497644acfbe02649503f1/pydantic-1.10.26-cp311-cp311-win_amd64.whl", hash = "sha256:ac1089f723e2106ebde434377d31239e00870a7563245072968e5af5cc4d33df", size = 2066646, upload-time = "2025-12-18T15:46:46.816Z" }, - { url = "https://files.pythonhosted.org/packages/02/6c/cd97a5a776c4515e6ee2ae81c2f2c5be51376dda6c31f965d7746ce0019f/pydantic-1.10.26-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:468d5b9cacfcaadc76ed0a4645354ab6f263ec01a63fb6d05630ea1df6ae453f", size = 2433795, upload-time = "2025-12-18T15:46:49.321Z" }, - { url = "https://files.pythonhosted.org/packages/47/12/de20affa30dcef728fcf9cc98e13ff4438c7a630de8d2f90eb38eba0891c/pydantic-1.10.26-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2c1b0b914be31671000ca25cf7ea17fcaaa68cfeadf6924529c5c5aa24b7ab1f", size = 2227387, upload-time = "2025-12-18T15:46:50.877Z" }, - { url = "https://files.pythonhosted.org/packages/7b/1d/9d65dcc5b8c17ba590f1f9f486e9306346831902318b7ee93f63516f4003/pydantic-1.10.26-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:15b13b9f8ba8867095769e1156e0d7fbafa1f65b898dd40fd1c02e34430973cb", size = 2629594, upload-time = "2025-12-18T15:46:53.42Z" }, - { url = "https://files.pythonhosted.org/packages/3f/76/acb41409356789e23e1a7ef58f93821410c96409183ce314ddb58d97f23e/pydantic-1.10.26-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:ad7025ca324ae263d4313998e25078dcaec5f9ed0392c06dedb57e053cc8086b", size = 2745305, upload-time = "2025-12-18T15:46:55.987Z" }, - { url = "https://files.pythonhosted.org/packages/22/72/a98c0c5e527a66057d969fedd61675223c7975ade61acebbca9f1abd6dc0/pydantic-1.10.26-cp312-cp312-win_amd64.whl", hash = "sha256:4482b299874dabb88a6c3759e3d85c6557c407c3b586891f7d808d8a38b66b9c", size = 1937647, upload-time = "2025-12-18T15:46:57.905Z" }, - { url = "https://files.pythonhosted.org/packages/28/b9/17a5a5a421c23ac27486b977724a42c9d5f8b7f0f4aab054251066223900/pydantic-1.10.26-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ae7913bb40a96c87e3d3f6fe4e918ef53bf181583de4e71824360a9b11aef1c", size = 2494599, upload-time = "2025-12-18T15:47:00.209Z" }, - { url = "https://files.pythonhosted.org/packages/e6/8e/6e3bd4241076cf227b443d7577245dd5d181ecf40b3182fcb908bc8c197d/pydantic-1.10.26-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8154c13f58d4de5d3a856bb6c909c7370f41fb876a5952a503af6b975265f4ba", size = 2254391, upload-time = "2025-12-18T15:47:02.268Z" }, - { url = "https://files.pythonhosted.org/packages/a8/30/a1c4092eda2145ecbead6c92db489b223e101e1ba0da82576d0cf73dd422/pydantic-1.10.26-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f8af0507bf6118b054a9765fb2e402f18a8b70c964f420d95b525eb711122d62", size = 2609445, upload-time = "2025-12-18T15:47:04.909Z" }, - { url = "https://files.pythonhosted.org/packages/3a/2a/0491f1729ee4b7b6bc859ec22f69752f0c09bee1b66ac6f5f701136f34c3/pydantic-1.10.26-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dcb5a7318fb43189fde6af6f21ac7149c4bcbcfffc54bc87b5becddc46084847", size = 2732124, upload-time = "2025-12-18T15:47:07.464Z" }, - { url = "https://files.pythonhosted.org/packages/2a/56/b59f3b2f84e1df2b04ae768a1bb04d9f0288ff71b67cdcbb07683757b2c0/pydantic-1.10.26-cp313-cp313-win_amd64.whl", hash = "sha256:71cde228bc0600cf8619f0ee62db050d1880dcc477eba0e90b23011b4ee0f314", size = 1939888, upload-time = "2025-12-18T15:47:09.618Z" }, - { url = "https://files.pythonhosted.org/packages/d2/8b/0c3dc02d4b97790b0f199bf933f677c14e7be4a8d21307c5f2daae06aa41/pydantic-1.10.26-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:6b40730cc81d53d515dc0b8bb5c9b43fadb9bed46de4a3c03bd95e8571616dba", size = 2502689, upload-time = "2025-12-18T15:47:12.308Z" }, - { url = "https://files.pythonhosted.org/packages/d4/9d/d31aeea45542b2ae4b09ecba92b88aaba696b801c31919811aa979a1242d/pydantic-1.10.26-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c3bbb9c0eecdf599e4db9b372fa9cc55be12e80a0d9c6d307950a39050cb0e37", size = 2269494, upload-time = "2025-12-18T15:47:14.53Z" }, - { url = "https://files.pythonhosted.org/packages/78/c1/3a4d069593283ca4dd0006039ba33644e21e432cddc09da706ac50441610/pydantic-1.10.26-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cc2e3fe7bc4993626ef6b6fa855defafa1d6f8996aa1caef2deb83c5ac4d043a", size = 2620047, upload-time = "2025-12-18T15:47:17.089Z" }, - { url = "https://files.pythonhosted.org/packages/e0/0e/340c3d29197d99c15ab04093d43bb9c9d0fd17c2a34b80cb9d36ed732b09/pydantic-1.10.26-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:36d9e46b588aaeb1dcd2409fa4c467fe0b331f3cc9f227b03a7a00643704e962", size = 2747625, upload-time = "2025-12-18T15:47:19.21Z" }, - { url = "https://files.pythonhosted.org/packages/1e/58/f12ab3727339b172c830b32151919456b67787cdfe8808b2568b322fb15c/pydantic-1.10.26-cp314-cp314-win_amd64.whl", hash = "sha256:81ce3c8616d12a7be31b4aadfd3434f78f6b44b75adbfaec2fe1ad4f7f999b8c", size = 1976436, upload-time = "2025-12-18T15:47:21.384Z" }, - { url = "https://files.pythonhosted.org/packages/1f/98/556e82f00b98486def0b8af85da95e69d2be7e367cf2431408e108bc3095/pydantic-1.10.26-py3-none-any.whl", hash = "sha256:c43ad70dc3ce7787543d563792426a16fd7895e14be4b194b5665e36459dd917", size = 166975, upload-time = "2025-12-18T15:47:44.927Z" }, -] - [[package]] name = "pygments" version = "2.20.0"