Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
63 commits
Select commit Hold shift + click to select a range
7e44f50
Add attrs as dependency
mikejturner Sep 14, 2026
5aa528e
Convert port to attrs
mikejturner Sep 14, 2026
db4a8ee
Merge branch 'main' into switch-to-attrs
mikejturner Sep 16, 2026
e217df1
Migrate Ports and subclasses to attrs
mikejturner Sep 21, 2026
23c8d30
Merge branch 'main' into switch-to-attrs
mikejturner Sep 29, 2026
f864753
Migrate Node to attrs
mikejturner Sep 30, 2026
84873b7
Replace field with type annotation
mikejturner Sep 30, 2026
a61165a
Migrate TellegenNode to attrs
mikejturner Oct 1, 2026
198542b
Formatting
mikejturner Oct 1, 2026
7b94d8e
Migrate AggregationNode to attrs
mikejturner Oct 1, 2026
756ebf3
Migrate PartitionedMultiCommodityTellegenNode to attrs
mikejturner Oct 1, 2026
d27efe3
Migrate ThreeWayValveNode to attrs
mikejturner Oct 1, 2026
ca1108a
Migrate InputOutputNode to attrs
mikejturner Oct 1, 2026
7873d6c
Migrate TimeVaryingPiecewiseIONode to attrs
mikejturner Oct 1, 2026
1414c0d
Migrate GasBoilerFixedCOP to attrs
mikejturner Oct 1, 2026
51ee6fa
Migrate TempControlledBoiler to attrs
mikejturner Oct 1, 2026
6d72685
Migrate DieselGenerator to attrs
mikejturner Oct 1, 2026
c18ce85
Formatting
mikejturner Oct 1, 2026
bae4bae
Migrate TransformNode to attrs
mikejturner Oct 1, 2026
20a3abe
Migrate ParameterisedChiller to attrs
mikejturner Oct 1, 2026
b538919
Migrate ParameterisedHeatPump to attrs
mikejturner Oct 1, 2026
070775e
Migrate SimpleChiller and SimpleHeatPump to attrs
mikejturner Oct 1, 2026
915f9fe
Migrate SimpleHeatPumpDualOutput to attrs
mikejturner Oct 2, 2026
350f790
Migrate ThermalNode to attrs
mikejturner Oct 2, 2026
53d3a06
Migrate ThermalStorage to attrs
mikejturner Oct 2, 2026
3744550
Migrate Inverter to attrs
mikejturner Oct 2, 2026
7b7c066
Migrate EVBase to attrs
mikejturner Oct 2, 2026
8eb6e6b
Migrate EVWithProfile to attrs
mikejturner Oct 2, 2026
ec17853
Migrate EVV0G to attrs
mikejturner Oct 2, 2026
1f07886
Migrate EVV1G to attrs
mikejturner Oct 2, 2026
f7da6bc
Migrate EVV2G to attrs
mikejturner Oct 2, 2026
ee0aff7
Migrate deprecated EV to attrs
mikejturner Oct 2, 2026
5ba3877
Fix linting
mikejturner Oct 2, 2026
867b097
Correct validator parameter name
mikejturner Oct 2, 2026
77265ef
Migrate TimeDelayNode to attrs
mikejturner Oct 2, 2026
4474baa
Fix wrong slack attributes used in tests
mikejturner Oct 2, 2026
e4eafd8
Various fixes to get tests to pass
mikejturner Oct 2, 2026
9a08171
Migrate CarbonAggregation to attrs
mikejturner Oct 6, 2026
8e3806e
Migrate MultiCommodityTellegenNode to attrs
mikejturner Oct 6, 2026
b532964
Migrate Demand to attrs
mikejturner Oct 6, 2026
4497991
Tidy up the validators
mikejturner Oct 6, 2026
f0ed7d7
Rework root validators on ports
mikejturner Oct 6, 2026
b5ff282
Migrate Edge to attrs
mikejturner Oct 7, 2026
330d36e
Migrate TimePeriod and Windows to attrs
mikejturner Oct 7, 2026
cee3104
Migrate DemandCharge, ImportDemandCharge and ExportDemandCharge to attrs
mikejturner Oct 7, 2026
008cb6a
Migrate ObjectiveSet to attrs
mikejturner Oct 7, 2026
bf9a3b5
Migrate Objective and subclasses to attrs
mikejturner Oct 7, 2026
65a3fe9
Migrate Transform to attrs
mikejturner Oct 7, 2026
8307629
Migrate OptimisationGraph to attrs
mikejturner Oct 7, 2026
2ffce3c
Remove unused pydantic imports
mikejturner Oct 7, 2026
8ba6f42
Migrate Path to attrs
mikejturner Oct 8, 2026
a0d8407
Migrate Battery to attrs
mikejturner Oct 8, 2026
6587a26
Disable experimental paths warning when running pytest
mikejturner Oct 8, 2026
45fc025
Replace ArrayType class with a type alias
mikejturner Oct 8, 2026
521ec3b
Remove BaseModel
mikejturner Oct 8, 2026
763ca25
Removes pydantic dependency
mikejturner Oct 8, 2026
9c02d41
Add description of attrs migration
mikejturner Oct 9, 2026
a24ffe2
Update changelog
mikejturner Oct 9, 2026
7b78c34
Fix escaping in table
mikejturner Oct 11, 2026
1d763c5
Fix EV initialisation
mikejturner Oct 12, 2026
7319f66
Switch port default back to 0 (from None) for compatibility with nueva
mikejturner Oct 15, 2026
e514b7b
Removes commented out asserts
mikejturner Oct 15, 2026
23b2c71
Removed debug code
mikejturner Oct 15, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
177 changes: 177 additions & 0 deletions attrs-migration.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
14 changes: 9 additions & 5 deletions src/echo/models/agnostic/aggregation.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,30 @@
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.

This node has an additional variable, 'total', which equals the sum of all ports defined on the 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:
Expand Down
38 changes: 19 additions & 19 deletions src/echo/models/agnostic/base.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
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
from echo.utils import (
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)
Expand All @@ -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)
Expand All @@ -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)
Expand Down
21 changes: 10 additions & 11 deletions src/echo/models/agnostic/bounded.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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)
Expand All @@ -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)
Loading
Loading