eris-echo 2.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. echo/__init__.py +1 -0
  2. echo/configuration.py +178 -0
  3. echo/constants.py +8 -0
  4. echo/exceptions.py +16 -0
  5. echo/functional.py +83 -0
  6. echo/models/__init__.py +0 -0
  7. echo/models/agnostic/__init__.py +50 -0
  8. echo/models/agnostic/aggregation.py +64 -0
  9. echo/models/agnostic/base.py +84 -0
  10. echo/models/agnostic/bounded.py +43 -0
  11. echo/models/agnostic/controlled.py +97 -0
  12. echo/models/agnostic/flex.py +61 -0
  13. echo/models/agnostic/input_output.py +30 -0
  14. echo/models/agnostic/storage.py +307 -0
  15. echo/models/agnostic/tellegen/__init__.py +6 -0
  16. echo/models/agnostic/tellegen/base.py +62 -0
  17. echo/models/agnostic/tellegen/multi_commodity.py +50 -0
  18. echo/models/agnostic/tellegen/partitioned_multi_commodity.py +88 -0
  19. echo/models/agnostic/tellegen/three_way_valve.py +122 -0
  20. echo/models/agnostic/time_delay.py +34 -0
  21. echo/models/agnostic/time_varying.py +134 -0
  22. echo/models/base/__init__.py +21 -0
  23. echo/models/base/edge.py +128 -0
  24. echo/models/base/node.py +160 -0
  25. echo/models/base/optimisation_graph.py +546 -0
  26. echo/models/base/path.py +66 -0
  27. echo/models/base/port.py +564 -0
  28. echo/models/base/transform.py +186 -0
  29. echo/models/base/types.py +7 -0
  30. echo/models/carbon/__init__.py +4 -0
  31. echo/models/carbon/aggregation.py +33 -0
  32. echo/models/carbon/base.py +25 -0
  33. echo/models/electrical/__init__.py +35 -0
  34. echo/models/electrical/base.py +37 -0
  35. echo/models/electrical/ev/__init__.py +14 -0
  36. echo/models/electrical/ev/base.py +340 -0
  37. echo/models/electrical/ev/deprecated.py +273 -0
  38. echo/models/electrical/ev/ev_with_profile.py +137 -0
  39. echo/models/electrical/ev/v0g.py +264 -0
  40. echo/models/electrical/ev/v1g.py +85 -0
  41. echo/models/electrical/ev/v2g.py +84 -0
  42. echo/models/electrical/generation.py +49 -0
  43. echo/models/electrical/inverter.py +97 -0
  44. echo/models/gas/__init__.py +5 -0
  45. echo/models/gas/base.py +18 -0
  46. echo/models/gas/boiler_fixedcop.py +65 -0
  47. echo/models/gas/boiler_tempcontrolled.py +96 -0
  48. echo/models/prebuilt/__init__.py +17 -0
  49. echo/models/prebuilt/battery.py +36 -0
  50. echo/models/prebuilt/diesel_generator.py +57 -0
  51. echo/models/prebuilt/flex.py +36 -0
  52. echo/models/prebuilt/load.py +14 -0
  53. echo/models/prebuilt/scaled_solar.py +19 -0
  54. echo/models/prebuilt/solar.py +13 -0
  55. echo/models/scenario.py +63 -0
  56. echo/models/thermal/__init__.py +15 -0
  57. echo/models/thermal/base.py +117 -0
  58. echo/models/thermal/parameterised_chiller.py +228 -0
  59. echo/models/thermal/parameterised_heatpump.py +496 -0
  60. echo/models/thermal/simple_chiller.py +139 -0
  61. echo/models/thermal/simple_heatpump.py +291 -0
  62. echo/models/thermal/simple_heatpump_dualoutput.py +195 -0
  63. echo/models/thermal/storage.py +307 -0
  64. echo/objectives/__init__.py +0 -0
  65. echo/objectives/base.py +99 -0
  66. echo/objectives/contingency.py +158 -0
  67. echo/objectives/power.py +132 -0
  68. echo/objectives/tariff.py +694 -0
  69. echo/optimiser.py +460 -0
  70. echo/py.typed +0 -0
  71. echo/tracker.py +74 -0
  72. echo/utils.py +506 -0
  73. echo/validators.py +290 -0
  74. echo/visualization.py +229 -0
  75. eris_echo-2.3.0.dist-info/METADATA +127 -0
  76. eris_echo-2.3.0.dist-info/RECORD +79 -0
  77. eris_echo-2.3.0.dist-info/WHEEL +5 -0
  78. eris_echo-2.3.0.dist-info/licenses/LICENSE.txt +22 -0
  79. eris_echo-2.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,122 @@
1
+ import pandas as pd
2
+ import pyomo.environ as en
3
+ from attrs import define, field
4
+ from pyomo.core.expr import InequalityExpression
5
+
6
+ from echo.configuration import Units
7
+ from echo.models.agnostic.flex import FlexSink, FlexSource
8
+ from echo.models.agnostic.tellegen.base import TellegenNode
9
+ from echo.models.scenario import EchoConcreteModel
10
+
11
+
12
+ @define
13
+ class ThreeWayValveNode(TellegenNode):
14
+ """A node that implements a Tellegen constraint requiring that port values sum to zero.
15
+
16
+ ThreeWayValveNode node implements additional constraints between ports,
17
+ there is one input (import) port and two output (export) ports.
18
+ At each time the flow is allowed through only one output port.
19
+ """
20
+
21
+ units: Units = field(kw_only=True)
22
+ input_port_name: str = "input_port"
23
+ output_port_name_1: str = "output_port_1"
24
+ output_port_name_2: str = "output_port_2"
25
+
26
+ # Tuple of two port names on the Node, non-zero flow through only one of the port allowed at any time
27
+ mutually_exclusive_port_flows: tuple[str, str] = None
28
+
29
+ def __attrs_post_init__(self) -> None:
30
+ self.create_ports()
31
+
32
+ @property
33
+ def binary_variable_flow_through_mutually_exclusive_port_1(self) -> str:
34
+ return f"binary_variable_flow_through_mutually_exclusive_{self.output_port_name_1}_{self.node_name}"
35
+
36
+ @property
37
+ def constraint_neg_flow_mutually_exclusive_port_1(self) -> str:
38
+ return f"constraint_neg_flow_mutually_exclusive_{self.output_port_name_1}_{self.node_name}"
39
+
40
+ @property
41
+ def constraint_pos_flow_mutually_exclusive_port_1(self) -> str:
42
+ return f"constraint_pos_flow_mutually_exclusive_{self.output_port_name_1}_{self.node_name}"
43
+
44
+ @property
45
+ def constraint_neg_flow_mutually_exclusive_port_2(self) -> str:
46
+ return f"constraint_neg_flow_mutually_exclusive_{self.output_port_name_2}_{self.node_name}"
47
+
48
+ @property
49
+ def constraint_pos_flow_mutually_exclusive_port_2(self) -> str:
50
+ return f"constraint_pos_flow_mutually_exclusive_port_{self.output_port_name_2}_{self.node_name}"
51
+
52
+ def create_ports(self) -> None:
53
+ # Create input and output ports
54
+ self.ports[self.input_port_name] = FlexSink(units=self.units)
55
+ self.ports[self.output_port_name_1] = FlexSource(units=self.units)
56
+ self.ports[self.output_port_name_2] = FlexSource(units=self.units)
57
+
58
+ def set_ports(
59
+ self,
60
+ input_port: FlexSink,
61
+ output_port_1: FlexSource,
62
+ output_port_2: FlexSource,
63
+ ) -> None:
64
+ # Discard existing ports
65
+ self.ports.clear()
66
+
67
+ # Update port references
68
+ self.input_port_name = input_port.port_name
69
+ self.output_port_name_1 = output_port_1.port_name
70
+ self.output_port_name_2 = output_port_2.port_name
71
+
72
+ # Add the new ports
73
+ self.ports[self.input_port_name] = input_port
74
+ self.ports[self.output_port_name_1] = output_port_1
75
+ self.ports[self.output_port_name_2] = output_port_2
76
+
77
+ def add_node_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None:
78
+ # Load coefficient of performance values from profile (if provided by reference)
79
+ setattr(
80
+ model,
81
+ self.binary_variable_flow_through_mutually_exclusive_port_1,
82
+ en.Var(model.Expansion, model.Time, initialize=0, domain=en.Binary),
83
+ )
84
+ super().add_node_to_model(model, profile)
85
+
86
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
87
+ super().apply_node_constraints(model)
88
+ self._apply_mutually_exclusive_port_flow_constraint(model)
89
+
90
+ def _apply_mutually_exclusive_port_flow_constraint(self, model: EchoConcreteModel) -> None:
91
+
92
+ _port_name_1 = self.ports.get(self.output_port_name_1).port_name
93
+ _port_name_2 = self.ports.get(self.output_port_name_2).port_name
94
+ _binary_var = getattr(model, self.binary_variable_flow_through_mutually_exclusive_port_1)
95
+
96
+ def mutual_exclusivity_rule_11(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
97
+ """When _binary_var is 0, flow through output port 1 is constrained to be zero"""
98
+ return _binary_var[p, t] * -1 * model.big_m <= getattr(model, _port_name_1)[p, t]
99
+
100
+ con_name = self.constraint_neg_flow_mutually_exclusive_port_1
101
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=mutual_exclusivity_rule_11))
102
+
103
+ def mutual_exclusivity_rule_12(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
104
+ """When _binary_var is 0, flow through output port 1 is constrained to be zero"""
105
+ return getattr(model, _port_name_1)[p, t] <= _binary_var[p, t] * model.big_m
106
+
107
+ con_name = self.constraint_pos_flow_mutually_exclusive_port_1
108
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=mutual_exclusivity_rule_12))
109
+
110
+ def mutual_exclusivity_rule_21(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
111
+ """When _binary_var is 1, flow through output port 2 is constrained to be zero"""
112
+ return (1 - _binary_var[p, t]) * -1 * model.big_m <= getattr(model, _port_name_2)[p, t]
113
+
114
+ con_name = self.constraint_neg_flow_mutually_exclusive_port_2
115
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=mutual_exclusivity_rule_21))
116
+
117
+ def mutual_exclusivity_rule_22(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
118
+ """When _binary_var is 1, flow through output port 2 is constrained to be zero"""
119
+ return getattr(model, _port_name_2)[p, t] <= (1 - _binary_var[p, t]) * model.big_m
120
+
121
+ con_name = self.constraint_pos_flow_mutually_exclusive_port_2
122
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=mutual_exclusivity_rule_22))
@@ -0,0 +1,34 @@
1
+ import pyomo.environ as en
2
+ from attrs import define, field
3
+ from pyomo.core.expr import InequalityExpression
4
+
5
+ from echo.models.agnostic.flex import FlexSink, FlexSource
6
+ from echo.models.agnostic.input_output import InputOutputNode
7
+ from echo.models.scenario import EchoConcreteModel
8
+
9
+
10
+ @define
11
+ class TimeDelayNode(InputOutputNode):
12
+ """A time delay node is an input-output node that implements a fixed delay between input and output."""
13
+
14
+ time_delay: int = field(kw_only=True) # number of time intervals delay between input and output
15
+
16
+ def __attrs_post_init__(self) -> None:
17
+ super().__attrs_post_init__()
18
+ self.ports["input"] = FlexSink(units=self.input_port_unit)
19
+ self.ports["output"] = FlexSource(units=self.output_port_unit)
20
+
21
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
22
+ def time_delay_rule(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
23
+ """This is a modified tellegen rule, where the sum=0 applies over staggered time periods according to the
24
+ time delay.
25
+ """
26
+ a = getattr(model, self.ports["input"].port_name)
27
+ b = getattr(model, self.ports["output"].port_name)
28
+ if t < self.time_delay:
29
+ return b[p, t] == 0
30
+ else:
31
+ return b[p, t] == a[p, int(t - self.time_delay)] * -1
32
+
33
+ con_name = "time_delay_con_" + self.node_name
34
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=time_delay_rule))
@@ -0,0 +1,134 @@
1
+ import pandas as pd
2
+ import pyomo.environ as en
3
+ from attrs import define, field
4
+
5
+ from echo.exceptions import validate
6
+ from echo.models.agnostic.input_output import InputOutputNode
7
+ from echo.models.scenario import EchoConcreteModel
8
+ from echo.utils import (
9
+ populate_values_across_time_and_expansion_indices,
10
+ set_float_var_bounds,
11
+ )
12
+ from echo.validators import (
13
+ piecewise_arrays_validator,
14
+ set_bounds_from_piecewise_points_validator,
15
+ )
16
+
17
+
18
+ @define
19
+ class TimeVaryingPiecewiseIONode(InputOutputNode):
20
+ """A Node with an input and output and time varying piecewise relationship between input and output.
21
+
22
+ The relationship between input and output is defined at each time interval by an array
23
+ of input-->output point pairs, which are used to construct a piecewise constraint.
24
+ Attributes input_port_unit and output_port_unit define node's commodity.
25
+ """
26
+
27
+ # dict where the keys are planning-time period tuple, and value is input pt array
28
+ input_points: dict | None = field(
29
+ default=None, validator=[piecewise_arrays_validator, set_bounds_from_piecewise_points_validator]
30
+ )
31
+
32
+ # dict where the keys are planning-time period tuple, and value is output pt array
33
+ output_points: dict | None = field(
34
+ default=None, validator=[piecewise_arrays_validator, set_bounds_from_piecewise_points_validator]
35
+ )
36
+
37
+ input_points_ref: str | None = (
38
+ None # Ref to profile dataframe column with input points array to be used across all times
39
+ )
40
+ output_points_ref: str | None = (
41
+ None # Ref to profile dataframe column with input points array to be used across all times
42
+ )
43
+
44
+ def __attrs_post_init__(self) -> None:
45
+ super().__attrs_post_init__()
46
+
47
+ def verify_points_values(self) -> None:
48
+ validate(self.input_points is not None, "No input points defined")
49
+ validate(self.output_points is not None, "No output points defined")
50
+ # Validate that dictionary keys match and length of each value array are the same
51
+ for k in self.input_points.keys():
52
+ validate(k in self.output_points.keys(), f"Key {k} not found in output_points dictionary")
53
+ validate(
54
+ len(self.input_points[k]) == len(self.output_points[k]),
55
+ "Number of break points in "
56
+ "input_points output_points must match."
57
+ f"Different length value arrays for key {k}",
58
+ )
59
+
60
+ def load_input_output_values_from_profile(self, model: EchoConcreteModel, profile_df: pd.DataFrame) -> None:
61
+ """If input/output point string references are provided, load values from profile.
62
+
63
+ input_points_ref/output_points_ref will override input_points/output_points values provided
64
+ in the instance's attributes (if any) with values from profile dataframe.
65
+ """
66
+ if self.input_points_ref:
67
+ """Load input points array from profile dataframe and set the same array across all time points"""
68
+ if self.input_points_ref not in profile_df.columns:
69
+ raise ValueError(f"Could not find reference column name {self.input_points_ref} in the profile.")
70
+ input_points_array = profile_df[self.input_points_ref].to_list()
71
+ self.add_constant_input_points(input_points_array, len(model.Time), len(model.Expansion))
72
+
73
+ if self.output_points_ref:
74
+ """Load input points array from profile dataframe and set the same array across all time points"""
75
+ if self.output_points_ref and self.output_points_ref not in profile_df.columns:
76
+ raise ValueError(f"Could not find reference column name {self.output_points_ref} in the profile.")
77
+ output_points_array = profile_df[self.output_points_ref].to_list()
78
+ self.add_constant_output_points(output_points_array, len(model.Time), len(model.Expansion))
79
+
80
+ def add_node_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None:
81
+ self.load_input_output_values_from_profile(model, profile)
82
+ super().add_node_to_model(model, profile)
83
+ # Bound input and output port variables, otherwise piecewise constraint will fail
84
+ self.verify_points_values()
85
+ set_float_var_bounds(
86
+ model=model, var_name=self.ports[self.output_port_ref].port_name, ub=self.max_output, lb=self.min_output
87
+ )
88
+ set_float_var_bounds(
89
+ model=model, var_name=self.ports[self.input_port_ref].port_name, ub=self.max_input, lb=self.min_input
90
+ )
91
+
92
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
93
+ xvar = getattr(model, self.ports[self.input_port_ref].port_name)
94
+ yvar = getattr(model, self.ports[self.output_port_ref].port_name)
95
+ xdata = self.input_points
96
+ ydata = self.output_points
97
+ con_name = "piecewise_con_" + self.node_name
98
+ setattr(
99
+ model,
100
+ con_name,
101
+ en.Piecewise(
102
+ model.Expansion,
103
+ model.Time,
104
+ yvar,
105
+ xvar,
106
+ pw_pts=xdata,
107
+ pw_constr_type="EQ",
108
+ f_rule=ydata,
109
+ pw_repn="SOS2",
110
+ warn_domain_coverage=False,
111
+ ),
112
+ )
113
+
114
+ def add_constant_input_points(
115
+ self,
116
+ input_points: float | int | list,
117
+ time_periods: int,
118
+ expansion_periods: int = 1,
119
+ ) -> None:
120
+ """Tiles constant input points array across time and expansion periods"""
121
+ self.input_points = populate_values_across_time_and_expansion_indices(
122
+ input_points, time_periods, expansion_periods
123
+ )
124
+
125
+ def add_constant_output_points(
126
+ self,
127
+ output_points: float | int | list,
128
+ time_periods: int,
129
+ expansion_periods: int = 1,
130
+ ) -> None:
131
+ """Tiles constant output points array across time and expansion periods."""
132
+ self.output_points = populate_values_across_time_and_expansion_indices(
133
+ output_points, time_periods, expansion_periods
134
+ )
@@ -0,0 +1,21 @@
1
+ from echo.models.base.edge import Edge
2
+ from echo.models.base.node import Node
3
+ from echo.models.base.optimisation_graph import OptimisationGraph
4
+ from echo.models.base.path import Path
5
+ from echo.models.base.port import Port
6
+ from echo.models.base.transform import Transform, TransformNode, TransformTerm
7
+ from echo.models.base.types import ConstraintValueType, InitialValue, InitialValueInput
8
+
9
+ __all__ = [
10
+ "Edge",
11
+ "Node",
12
+ "OptimisationGraph",
13
+ "Port",
14
+ "Path",
15
+ "Transform",
16
+ "TransformNode",
17
+ "TransformTerm",
18
+ "ConstraintValueType",
19
+ "InitialValue",
20
+ "InitialValueInput",
21
+ ]
@@ -0,0 +1,128 @@
1
+ from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749)
2
+
3
+ import pyomo.environ as en
4
+ import shortuuid
5
+ from attrs import define, field
6
+ from pyomo.core.expr.relational_expr import EqualityExpression
7
+
8
+ from echo.configuration import Flows
9
+ from echo.exceptions import ConfigurationError
10
+ from echo.models.base.port import Port
11
+ from echo.models.base.types import ConstraintValueType
12
+ from echo.models.scenario import EchoConcreteModel
13
+
14
+
15
+ @define
16
+ class Edge:
17
+ """
18
+ Edges are used to connect nodes. For an edge (x, y) where x and y are nodes,
19
+ the edge value is equal to the flow from x->y plus the flow from y->x.
20
+ """
21
+
22
+ vertices: tuple[Port, Port]
23
+ tariff: list | None = None
24
+
25
+ uid: str = field(factory=shortuuid.uuid)
26
+ edge_name: str = field()
27
+
28
+ @edge_name.default
29
+ def _set_edge_name_default(self) -> str:
30
+ return "edge_" + str(self.uid)
31
+
32
+ def add_vertices(self, obj1: Port, obj2: Port) -> None:
33
+ """Adds edge vertices (which are ports on nodes)
34
+
35
+ Args:
36
+ obj1: port object
37
+ obj2: port object
38
+
39
+ Returns:
40
+ None
41
+ """
42
+ self.vertices = (obj1, obj2)
43
+
44
+ def verify_edge(self) -> None:
45
+ """Verifies that flows on ports associated with either end of an edge are the same.
46
+
47
+ Returns:
48
+ None
49
+
50
+ Raises:
51
+ ConfigurationError: If the flows on the ports at either end of an edge are not the same.
52
+ """
53
+
54
+ port1 = self.vertices[0]
55
+ port2 = self.vertices[1]
56
+
57
+ if (port1.flows is Flows.Export) and (port2.flows is Flows.Export):
58
+ raise ConfigurationError("Port flow constraints do not allow any flow along the edge.")
59
+ if (port1.flows is Flows.Import) and (port2.flows is Flows.Import):
60
+ raise ConfigurationError("Port flow constraints do not allow any flow along the edge.")
61
+
62
+ def add_edge_to_model(self, model: EchoConcreteModel) -> None:
63
+ """Applies edge constraint: ``port1 = -1 *port2`` to a concrete model.
64
+
65
+ Args:
66
+ model: pyomo concrete model
67
+
68
+ Returns:
69
+ None
70
+ """
71
+
72
+ port1 = self.vertices[0]
73
+ port2 = self.vertices[1]
74
+
75
+ def edge_constraint_rule(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
76
+ """Generates the edge constraint rule.
77
+
78
+ Args:
79
+ model: The concrete model from which to draw data.
80
+ p: Index representing capacity expansion
81
+ t: Index representing time.
82
+
83
+ Returns:
84
+ EqualityExpression: The transform rule.
85
+
86
+ Raises:
87
+ Exception: If an improper TransformRule is used.
88
+ """
89
+
90
+ return getattr(model, port1.port_name)[p, t] + getattr(model, port2.port_name)[p, t] == 0
91
+
92
+ con_name = "edge_con_" + port1.port_name + "_" + port2.port_name
93
+ setattr(
94
+ model,
95
+ con_name,
96
+ en.Constraint(model.Expansion, model.Time, rule=edge_constraint_rule),
97
+ )
98
+
99
+ def get_max_flow_along_edge(self, forwards: bool = True) -> ConstraintValueType | None:
100
+ """Returns the max flow along an edge.
101
+
102
+ Args:
103
+ forwards: True is flow is from the 0th port to the 1st port in self.vertices. False if from 1st to the 0th.
104
+ Defaults to True.
105
+
106
+ Returns:
107
+ ConstraintValueType: The max flow across this edge.
108
+ """
109
+
110
+ max_flow = None
111
+
112
+ if forwards is True:
113
+ port1 = self.vertices[0]
114
+ port2 = self.vertices[1]
115
+ else:
116
+ port1 = self.vertices[1]
117
+ port2 = self.vertices[0]
118
+
119
+ if port1.export_constraint_value is not None:
120
+ max_flow = port1.export_constraint_value
121
+
122
+ if port2.import_constraint_value is not None:
123
+ if max_flow is not None:
124
+ max_flow = min(max_flow, port2.import_constraint_value)
125
+ else:
126
+ max_flow = port2.import_constraint_value
127
+
128
+ return max_flow
@@ -0,0 +1,160 @@
1
+ from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749)
2
+
3
+ from collections.abc import Iterable
4
+
5
+ import pandas as pd
6
+ import pyomo.environ as en
7
+ import shortuuid
8
+ from attrs import define, field
9
+
10
+ from echo.exceptions import ConfigurationError
11
+ from echo.models.base.port import Port
12
+ from echo.models.scenario import EchoConcreteModel
13
+
14
+
15
+ @define
16
+ class Node:
17
+ """
18
+ Nodes are collections of one or more ports that can include non-trivial relationships between the ports,
19
+ this allows transformations to be implemented.
20
+ """
21
+
22
+ uid: str = field(factory=shortuuid.uuid)
23
+ node_name: str = field()
24
+
25
+ @node_name.default
26
+ def _set_node_name_default(self) -> str:
27
+ return "node_" + str(self.uid)
28
+
29
+ ports: dict[str, Port] = field(factory=dict)
30
+ objective: en.numeric_expr.NumericExpression | float = field(default=0) # For adding any node objectives
31
+
32
+ @property
33
+ def inflow(self) -> str:
34
+ return f"inflow_{self.node_name}"
35
+
36
+ def add_port(self, name: str, port: Port) -> None:
37
+ if self.ports.get(name) is not None:
38
+ raise ConfigurationError(
39
+ f"Port with name '{name}' is already defined on TellegenNode(id={self.uid}, name={self.node_name})."
40
+ )
41
+
42
+ self.ports[name] = port
43
+
44
+ def add_ports_from_list(self, names: Iterable[str], port_type: type[Port], **kwargs) -> None:
45
+ """Creates a set of ports (using port_type) and adds them to this Node. The ports will be constructed
46
+ using port_type and the supplied kwargs"""
47
+
48
+ for name in names:
49
+ self.add_port(name, port_type(**kwargs))
50
+
51
+ def get_port(self, port_name: str) -> Port | None:
52
+ """Returns the Port object with the name port_name.
53
+
54
+ Args:
55
+ port_name: The name of the Port.
56
+
57
+ Returns:
58
+ Port: The port object with the name port_name, or None if the port isn't found
59
+ """
60
+
61
+ return self.ports.get(port_name)
62
+
63
+ def num_ports(self) -> int:
64
+ """Returns the number of ports associated with this node.
65
+
66
+ Returns:
67
+ The number of ports for this node.
68
+ """
69
+ return len(self.ports)
70
+
71
+ def verify_node(self) -> None:
72
+ """Checks there is at least one port associated with this node.
73
+
74
+ Raises:
75
+ ConfigurationError: If there are no ports present on this node.
76
+ """
77
+
78
+ if len(self.ports) < 1:
79
+ raise ConfigurationError("A node must have at least one port.")
80
+
81
+ for port in self.ports.values():
82
+ port.verify_port()
83
+
84
+ def add_node_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None:
85
+ """Add this node to a concrete model.
86
+
87
+ Args:
88
+ model: The concrete model to add the node to.
89
+ profile: The data associated with this node.
90
+ """
91
+
92
+ self.verify_node()
93
+ for port in self.ports.values():
94
+ port.add_port_to_model(model, profile)
95
+
96
+ # @abc.abstractmethod
97
+ def add_objective(self, model: EchoConcreteModel) -> None:
98
+ """Define objective/s and add to self.objective. To be overwritten.
99
+
100
+ Should be implemented as an expression that needs to be concatanated to self.objective. For example:
101
+
102
+ def add_objective(self, model: EchoConcreteModel) -> None:
103
+ total = 0
104
+
105
+ if self.regularise is True:
106
+ total += (
107
+ sum(
108
+ getattr(model, self.flow_value)[p, t] * getattr(model, self.flow_value)[p, t]
109
+ for p in model.Expansion
110
+ for t in model.Time
111
+ )
112
+ * 0.0000001
113
+ )
114
+
115
+ self.objective += total
116
+
117
+ Args:
118
+ model: The model to add the objective/s to.
119
+
120
+ Returns:
121
+ None
122
+ """
123
+ pass
124
+
125
+ # @abc.abstractmethod
126
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
127
+ """Apply constraints associated with this node to a concrete model.
128
+
129
+ Intended to be overridden in subclasses.
130
+
131
+ Define constraints as functions that returns a Constraint, EqualityExpression or InequalityExpression.
132
+
133
+ Define a subfunction of the form detailed in the example below, then apply with setattr. For example:
134
+
135
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
136
+ def tellegen_node_rule(model: EchoConcreteModel, p: int, t:int) -> EqualityExpression:
137
+ a = 0
138
+ for port in node_ports.values():
139
+ a += getattr(model, port.port_name)[p, t]
140
+ return a == 0
141
+
142
+ node_ports = self.ports
143
+ con_name = "reliability_con_" + self.node_name
144
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=tellegen_node_rule))
145
+
146
+ Args:
147
+ model: The model to add the constraints to.
148
+
149
+ Returns:
150
+ None
151
+ """
152
+ pass
153
+
154
+ def get_port_name_to_port_dict_name_map(self) -> dict[str, str]:
155
+ """Map the port name key in self.ports to the corresponding Port.port_name.
156
+
157
+ Returns:
158
+
159
+ """
160
+ return {port.port_name: port_dict_name for port_dict_name, port in self.ports.items()}