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,61 @@
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 FlowConstraint, Flows, OptimisationType
7
+ from echo.models.base import Port
8
+ from echo.models.scenario import EchoConcreteModel
9
+ from echo.validators import (
10
+ bound_order_validator,
11
+ )
12
+
13
+
14
+ @define
15
+ class FlexPort(Port):
16
+ """Flexible variable port, which can import and export without constraints."""
17
+
18
+ flows: Flows = Flows.Both
19
+ import_constraint: FlowConstraint = FlowConstraint.NoConstraint
20
+ export_constraint: FlowConstraint = FlowConstraint.NoConstraint
21
+ flow_type: OptimisationType = OptimisationType.Variable
22
+
23
+
24
+ @define
25
+ class FlexSink(FlexPort):
26
+ """Flexible port, imports only"""
27
+
28
+ flows: Flows = Flows.Import
29
+
30
+
31
+ @define
32
+ class FlexSource(FlexPort):
33
+ """Flexible ports, exports only"""
34
+
35
+ flows: Flows = Flows.Export
36
+
37
+
38
+ @define
39
+ class OffOrConstrainedPort(FlexPort):
40
+ """A port that is either off (0) or on, and when it is on it is constrained between a min and max value."""
41
+
42
+ lower_bound: float = field(kw_only=True, validator=bound_order_validator)
43
+ upper_bound: float = field(kw_only=True, validator=bound_order_validator)
44
+
45
+ @property
46
+ def active(self) -> str:
47
+ return "active_" + self.port_name
48
+
49
+ def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None:
50
+ super().add_port_to_model(model, profile)
51
+ setattr(model, self.active, en.Var(model.Expansion, model.Time, initialize=0, domain=en.Binary))
52
+
53
+ # Apply constraints such that if active=1, the port is bounded, and if active=0, the port is 0.
54
+ def on_off_constraint1(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
55
+ return getattr(model, self.port_name)[p, t] >= getattr(model, self.active)[p, t] * self.lower_bound
56
+
57
+ def on_off_constraint2(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
58
+ return getattr(model, self.port_name)[p, t] <= getattr(model, self.active)[p, t] * self.upper_bound
59
+
60
+ setattr(model, "on_off1_" + self.port_name, en.Constraint(model.Expansion, model.Time, rule=on_off_constraint1))
61
+ setattr(model, "on_off2_" + self.port_name, en.Constraint(model.Expansion, model.Time, rule=on_off_constraint2))
@@ -0,0 +1,30 @@
1
+ from attrs import define, field
2
+
3
+ from echo.configuration import Units
4
+ from echo.models.agnostic.flex import FlexPort
5
+ from echo.models.base.node import Node
6
+
7
+
8
+ @define
9
+ class InputOutputNode(Node):
10
+ """
11
+ An input-output node has one input port and one output port.
12
+ A custom transformation can be defined between input and output.
13
+ """
14
+
15
+ # TODO: This Node does not do anything, unnecessary inheritance
16
+
17
+ input_port_unit: Units = field(kw_only=True)
18
+ output_port_unit: Units = field(kw_only=True)
19
+ # Optional parameters for controlling input/output port flows
20
+ max_output: float | None = None # output might be neg or pos, leave it open
21
+ min_output: float | None = None
22
+ max_input: float | None = None
23
+ min_input: float | None = None
24
+ input_port_ref: str = "input"
25
+ output_port_ref: str = "output"
26
+
27
+ def __attrs_post_init__(self) -> None:
28
+ # Create an input port and an output port with the correct units
29
+ self.ports[self.input_port_ref] = FlexPort(units=self.input_port_unit)
30
+ self.ports[self.output_port_ref] = FlexPort(units=self.output_port_unit)
@@ -0,0 +1,307 @@
1
+ from types import NoneType
2
+
3
+ import attrs
4
+ import pandas as pd
5
+ import pyomo.environ as en
6
+ from attrs import define, field
7
+ from pyomo.core.expr import EqualityExpression, InequalityExpression
8
+
9
+ from echo.configuration import FlowConstraint, Flows, OptimisationType
10
+ from echo.models.base import Port
11
+ from echo.models.scenario import EchoConcreteModel
12
+ from echo.utils import (
13
+ TimeExpandableType,
14
+ TimeSeriesData,
15
+ expand_as_array,
16
+ set_float_var_bounds,
17
+ )
18
+ from echo.validators import (
19
+ ArrayType,
20
+ depth_of_discharge_validator,
21
+ soc_conserv_validator,
22
+ update_constraint_values,
23
+ )
24
+
25
+
26
+ @define
27
+ class Storage(Port):
28
+ """Same as old storage but without all the EV attributes"""
29
+
30
+ flows: Flows = Flows.Both
31
+ flow_type: OptimisationType = OptimisationType.Variable
32
+ import_constraint: FlowConstraint = FlowConstraint.Fixed
33
+ export_constraint: FlowConstraint = FlowConstraint.Fixed
34
+ max_capacity: float = field(kw_only=True, validator=depth_of_discharge_validator)
35
+ depth_of_discharge_limit: float = field(
36
+ default=0, validator=depth_of_discharge_validator
37
+ ) # DoD limit is the percent soc to which you can discharge the storage
38
+ min_soc: float = field(default=0)
39
+ charging_power_limit: float = field(kw_only=True, validator=update_constraint_values)
40
+ discharging_power_limit: float = field(kw_only=True, validator=update_constraint_values)
41
+ charging_efficiency: float = field(default=1)
42
+ discharging_efficiency: float = field(default=1)
43
+ fixed_storage_capacity: bool = field(default=True)
44
+ storage_capacity_cost: float | None = field(
45
+ default=None, validator=attrs.validators.or_(attrs.validators.instance_of(NoneType), attrs.validators.gt(0))
46
+ )
47
+ regularise: bool = field(default=False)
48
+ initial_state_of_charge: float | None = field(default=None, kw_only=True)
49
+
50
+ @property
51
+ def soc_value(self) -> str:
52
+ return "storage_soc_" + self.port_name
53
+
54
+ @property
55
+ def optimised_capacity(self) -> str:
56
+ return "optimised_storage_capacity_" + self.port_name
57
+
58
+ @property
59
+ def soc_constraint(self) -> str:
60
+ return "soc_cons_" + self.port_name
61
+
62
+ def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None:
63
+ super().add_port_to_model(model, profile)
64
+ self.create_storage_variables(model)
65
+ self.apply_soc_constraints(model)
66
+
67
+ def create_storage_variables(self, model: EchoConcreteModel) -> None:
68
+ # Create soc variable and bound it
69
+ setattr(
70
+ model,
71
+ self.soc_value,
72
+ en.Var(
73
+ model.Expansion,
74
+ model.Time,
75
+ initialize=self.initial_state_of_charge,
76
+ bounds=(self.min_soc, self.max_capacity),
77
+ ),
78
+ )
79
+ # Apply charging constraints as bounds on port_name variable
80
+ set_float_var_bounds(model, self.port_name, ub=self.charging_power_limit, lb=self.discharging_power_limit)
81
+
82
+ if self.fixed_storage_capacity is False:
83
+ setattr(model, self.optimised_capacity, en.Var(initialize=0, domain=en.NonNegativeReals))
84
+
85
+ def cap_limit(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
86
+ # Ensure SOC is within max capacity
87
+ return getattr(model, self.soc_value)[p, t] <= getattr(model, self.optimised_capacity)
88
+
89
+ setattr(model, f"cap_lim_{self.port_name}", en.Constraint(model.Expansion, model.Time, rule=cap_limit))
90
+ else:
91
+ setattr(model, self.optimised_capacity, en.Param(initialize=self.max_capacity, domain=en.NonNegativeReals))
92
+
93
+ def apply_soc_constraints(self, model: EchoConcreteModel) -> None:
94
+ """Extract some variables to make constraints easier to write"""
95
+ max_t = len(model.Time) # maximum time interval t
96
+ kw_to_kwh = model.scenario_settings.interval_duration / 60 # conversion from kW to kWh
97
+ soc = getattr(model, self.soc_value)
98
+ power = getattr(model, self.port_name)
99
+
100
+ def soc_rule(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
101
+ if p == 0 and t == 0:
102
+ return (
103
+ soc[p, t]
104
+ == self.initial_state_of_charge
105
+ + pos[p, t] * kw_to_kwh * self.charging_efficiency
106
+ + neg[p, t] * kw_to_kwh / self.discharging_efficiency
107
+ )
108
+ elif t == 0:
109
+ return (
110
+ soc[p, t]
111
+ == soc[p - 1, max_t]
112
+ + pos[p, t] * kw_to_kwh * self.charging_efficiency
113
+ + neg[p, t] * kw_to_kwh / self.discharging_efficiency
114
+ )
115
+ else:
116
+ return (
117
+ soc[p, t]
118
+ == soc[p, t - 1]
119
+ + pos[p, t] * kw_to_kwh * self.charging_efficiency
120
+ + neg[p, t] * kw_to_kwh / self.discharging_efficiency
121
+ )
122
+
123
+ def soc_rule_perfect_efficiency(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
124
+ if p == 0 and t == 0:
125
+ return soc[p, t] == self.initial_state_of_charge + power[p, t] * kw_to_kwh
126
+ elif t == 0:
127
+ return soc[p, t] == soc[p - 1, max_t] + power[p, t] * kw_to_kwh
128
+ else:
129
+ return soc[p, t] == soc[p, t - 1] + power[p, t] * kw_to_kwh
130
+
131
+ if (self.charging_efficiency == 1) and (self.discharging_efficiency == 1):
132
+ setattr(
133
+ model, self.soc_constraint, en.Constraint(model.Expansion, model.Time, rule=soc_rule_perfect_efficiency)
134
+ )
135
+ else:
136
+ self.constrain_pos_neg(model)
137
+ pos = getattr(model, self.pos) # get pos variable for writing constraints
138
+ neg = getattr(model, self.neg) # get neg variable for writing constraints
139
+ setattr(model, self.soc_constraint, en.Constraint(model.Expansion, model.Time, rule=soc_rule))
140
+
141
+ def add_objective(self, model: EchoConcreteModel) -> None:
142
+ super().add_objective(model)
143
+ total = 0
144
+
145
+ # To get unique solution
146
+ if self.regularise is True:
147
+ total += (
148
+ sum(
149
+ getattr(model, self.pos)[p, t] * getattr(model, self.pos)[p, t]
150
+ + getattr(model, self.neg)[p, t] * getattr(model, self.neg)[p, t]
151
+ for p in model.Expansion
152
+ for t in model.Time
153
+ )
154
+ * 0.0000001
155
+ )
156
+
157
+ if self.storage_capacity_cost is not None:
158
+ total += getattr(model, self.optimised_capacity) * self.storage_capacity_cost
159
+
160
+ self.objective += total
161
+
162
+
163
+ @define
164
+ class MobileStorage(Storage):
165
+ """New Storage + EV attributes"""
166
+
167
+ # next variable is for allowing soc to go below min so as to avoid optimisation failing if there infeasible ev trips
168
+ enable_trip_slack: bool = field(default=False)
169
+ # next three variables are for having a 'conservative' ev user lower bound on the soc while it is plugged in
170
+ # soc_conserv: Union[ArrayType,list,float, None, dict] = None
171
+ soc_conserv: TimeExpandableType | None = field(default=None, validator=soc_conserv_validator)
172
+ soc_conserv_cost: float | None = field(default=None, validator=soc_conserv_validator)
173
+ # soc_conserve: scalarOrArray
174
+ available: ArrayType | list | None = field(default=None, validator=soc_conserv_validator)
175
+
176
+ @property
177
+ def cons_slack(self) -> str:
178
+ return "con_slack" + self.port_name
179
+
180
+ @property
181
+ def trip_slack(self) -> str:
182
+ return "trip_slack_" + self.port_name
183
+
184
+ def add_port_to_model(self, model: EchoConcreteModel, profile: pd.DataFrame) -> None:
185
+ super(Storage, self).add_port_to_model(model, profile)
186
+ self.create_storage_variables(model)
187
+ if self.enable_trip_slack:
188
+ self.apply_modified_soc_constraints(model)
189
+ else:
190
+ self.apply_soc_constraints(model)
191
+ self.apply_conserv_soc_constraints(model)
192
+
193
+ def apply_conserv_soc_constraints(self, model: EchoConcreteModel) -> None:
194
+ def soc_conservative_rule(
195
+ model: EchoConcreteModel,
196
+ p: int,
197
+ t: int,
198
+ ) -> InequalityExpression | type[en.Constraint.Skip]:
199
+ """A rule for enforcing conservativeness while plugged in"""
200
+ if expanded_soc_conserv and self.available is not None and self.available[t]:
201
+ return (
202
+ getattr(model, self.soc_value)[p, t]
203
+ + getattr(model, self.cons_slack)[p, t]
204
+ - expanded_soc_conserv[p, t]
205
+ >= 0
206
+ )
207
+ else:
208
+ return en.Constraint.Skip
209
+
210
+ if self.soc_conserv is not None:
211
+ expanded_soc_conserv = expand_as_array(
212
+ TimeSeriesData(
213
+ value=self.soc_conserv,
214
+ num_expansion_intervals=len(model.Expansion),
215
+ num_time_intervals=len(model.Time),
216
+ )
217
+ )
218
+ setattr(
219
+ model, self.cons_slack, en.Var(model.Expansion, model.Time, initialize=0, domain=en.NonNegativeReals)
220
+ )
221
+ setattr(
222
+ model,
223
+ f"cons_soc_{self.port_name}",
224
+ en.Constraint(model.Expansion, model.Time, rule=soc_conservative_rule),
225
+ )
226
+
227
+ def apply_modified_soc_constraints(self, model: EchoConcreteModel) -> None:
228
+ """Get some variables to make constraints easier to write"""
229
+ max_t = len(model.Time) # maximum time interval t
230
+ kw_to_kwh = model.scenario_settings.interval_duration / 60 # conversion from kW to kWh
231
+ soc = getattr(model, self.soc_value)
232
+ power = getattr(model, self.port_name)
233
+
234
+ def soc_rule_slack(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
235
+ if p == 0 and t == 0:
236
+ return (
237
+ soc[p, t]
238
+ == self.initial_state_of_charge
239
+ + pos[p, t] * kw_to_kwh * self.charging_efficiency
240
+ + neg[p, t] * kw_to_kwh / self.discharging_efficiency
241
+ + slack[p, t]
242
+ )
243
+ elif t == 0:
244
+ return (
245
+ soc[p, t]
246
+ == soc[p - 1, max_t]
247
+ + pos[p, t] * kw_to_kwh * self.charging_efficiency
248
+ + neg[p, t] * kw_to_kwh / self.discharging_efficiency
249
+ + slack[p, t]
250
+ )
251
+ else:
252
+ return (
253
+ soc[p, t]
254
+ == soc[p, t - 1]
255
+ + pos[p, t] * kw_to_kwh * self.charging_efficiency
256
+ + neg[p, t] * kw_to_kwh / self.discharging_efficiency
257
+ + slack[p, t]
258
+ )
259
+
260
+ def soc_rule_perfect_efficiency_slack(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
261
+ if p == 0 and t == 0:
262
+ return soc[p, t] == self.initial_state_of_charge + power[p, t] * kw_to_kwh + slack[p, t]
263
+ elif t == 0:
264
+ return soc[p, t] == soc[p, t - 1] + power[p - 1, max_t] * kw_to_kwh + slack[p, t]
265
+ else:
266
+ return soc[p, t] == soc[p, t - 1] + power[p, t] * kw_to_kwh + slack[p, t]
267
+
268
+ if self.enable_trip_slack is True:
269
+ """Create a slack variable"""
270
+ setattr(
271
+ model, self.trip_slack, en.Var(model.Expansion, model.Time, initialize=0, domain=en.NonNegativeReals)
272
+ )
273
+
274
+ # get slack variable for writing constraints
275
+ slack = getattr(model, self.trip_slack)
276
+
277
+ # Apply the modified soc constraint, which will overwrite the previously created one
278
+ if (self.charging_efficiency == 1) and (self.discharging_efficiency == 1):
279
+ setattr(
280
+ model,
281
+ self.soc_constraint,
282
+ en.Constraint(model.Expansion, model.Time, rule=soc_rule_perfect_efficiency_slack),
283
+ )
284
+ else:
285
+ self.constrain_pos_neg(model)
286
+ pos = getattr(model, self.pos) # get pos variable for writing constraints
287
+ neg = getattr(model, self.neg) # get neg variable for writing constraints
288
+ setattr(model, self.soc_constraint, en.Constraint(model.Expansion, model.Time, rule=soc_rule_slack))
289
+
290
+ def add_objective(self, model: EchoConcreteModel) -> None:
291
+ super().add_objective(model)
292
+ total = 0
293
+
294
+ if self.enable_trip_slack:
295
+ total += (
296
+ sum(getattr(model, self.trip_slack)[p, t] for p in model.Expansion for t in model.Time)
297
+ * model.big_m
298
+ * 20
299
+ ) # we want this to be more important than import/export constraints
300
+
301
+ if self.soc_conserv is not None:
302
+ total += (
303
+ sum(getattr(model, self.cons_slack)[p, t] for p in model.Expansion for t in model.Time)
304
+ * self.soc_conserv_cost
305
+ )
306
+
307
+ self.objective += total
@@ -0,0 +1,6 @@
1
+ from echo.models.agnostic.tellegen.base import TellegenNode
2
+ from echo.models.agnostic.tellegen.multi_commodity import MultiCommodityTellegenNode
3
+ from echo.models.agnostic.tellegen.partitioned_multi_commodity import PartitionedMultiCommodityTellegenNode
4
+ from echo.models.agnostic.tellegen.three_way_valve import ThreeWayValveNode
5
+
6
+ __all__ = ["MultiCommodityTellegenNode", "PartitionedMultiCommodityTellegenNode", "TellegenNode", "ThreeWayValveNode"]
@@ -0,0 +1,62 @@
1
+ import pyomo.environ as en
2
+ from attrs import define, field
3
+ from pyomo.core.expr import EqualityExpression
4
+
5
+ from echo.configuration import Flows, Units
6
+ from echo.exceptions import ConfigurationError, validate
7
+ from echo.models.base import Node, Port
8
+ from echo.models.scenario import EchoConcreteModel
9
+ from echo.validators import (
10
+ ports_have_same_units_validator,
11
+ )
12
+
13
+
14
+ @define
15
+ class TellegenNode(Node):
16
+ """A node that implements a Tellegen constraint requiring that port values sum to zero."""
17
+
18
+ ports: dict[str, Port] = field(factory=dict, validator=ports_have_same_units_validator)
19
+
20
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
21
+ def tellegen_node_rule(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
22
+ a = 0
23
+ for port in node_ports.values():
24
+ a += getattr(model, port.port_name)[p, t]
25
+ return a == 0
26
+
27
+ node_ports = self.ports
28
+ con_name = "reliability_con_" + self.node_name
29
+ setattr(model, con_name, en.Constraint(model.Expansion, model.Time, rule=tellegen_node_rule))
30
+
31
+ def verify_node(self) -> None:
32
+ super().verify_node()
33
+
34
+ validate(
35
+ len(self.ports) >= 2,
36
+ f"A TellegenNode(id={self.uid}, name={self.node_name}) must have at least two ports.",
37
+ )
38
+
39
+ # We can't have all import or all export ports on a tellegennode
40
+ flows = {port.flows for port in self.ports.values()}
41
+ validate(
42
+ flows != {Flows.Import} and flows != {Flows.Export},
43
+ f"TellgenNode(id={self.uid}, name={self.node_name}) must have a mixture "
44
+ f"of import and export ports. Got: {flows}",
45
+ )
46
+
47
+ @property
48
+ def units(self) -> Units | None:
49
+ if self.ports:
50
+ first_port = list(self.ports.values())[0]
51
+ return first_port.units
52
+ return None
53
+
54
+ # Override parent's 'add_port' method so we can perform checks necessary to tellegennodes.
55
+ def add_port(self, name: str, port: Port) -> None:
56
+ if self.units and self.units != port.units:
57
+ raise ConfigurationError(
58
+ f"Port with units '{port.units}' must match "
59
+ f"TellegenNode(id={self.uid}, name={self.node_name}) units, '{self.units}'."
60
+ )
61
+
62
+ super().add_port(name=name, port=port)
@@ -0,0 +1,50 @@
1
+ from collections.abc import Iterable
2
+ from functools import partial
3
+
4
+ import pyomo.environ as en
5
+ from attrs import define
6
+ from pyomo.core.expr import EqualityExpression
7
+
8
+ from echo.models.base import Node, Port
9
+ from echo.models.scenario import EchoConcreteModel
10
+
11
+
12
+ @define
13
+ class MultiCommodityTellegenNode(Node):
14
+ """
15
+ A node with ports that have multiple commodities.
16
+ A tellegen constraint is applied per commodity.
17
+ """
18
+
19
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
20
+ """Apply Tellegen constraint for same commodity ports."""
21
+
22
+ def tellegen_node_rule(
23
+ commodity_ports: Iterable[Port],
24
+ model: EchoConcreteModel,
25
+ p: int,
26
+ t: int,
27
+ ) -> EqualityExpression:
28
+ net_flow = 0
29
+ for port in commodity_ports:
30
+ port_flow = getattr(model, port.port_name)
31
+ net_flow += port_flow[p, t]
32
+ return net_flow == 0
33
+
34
+ commodities = dict()
35
+ for p in self.ports.values():
36
+ if commodities.get(p.units) is None:
37
+ commodities[p.units] = [p]
38
+ else:
39
+ commodities[p.units].append(p)
40
+
41
+ for commodity_type, commodity_ports in commodities.items():
42
+ setattr(
43
+ model,
44
+ "node_con_" + str(commodity_type) + self.node_name,
45
+ en.Constraint(
46
+ model.Expansion,
47
+ model.Time,
48
+ rule=partial(tellegen_node_rule, commodity_ports),
49
+ ),
50
+ )
@@ -0,0 +1,88 @@
1
+ from collections.abc import Iterable
2
+ from functools import partial
3
+
4
+ import pyomo.environ as en
5
+ from attrs import define, field
6
+ from pyomo.core.expr import EqualityExpression
7
+
8
+ from echo.exceptions import ConfigurationError
9
+ from echo.models.base import Node, Port
10
+ from echo.models.scenario import EchoConcreteModel
11
+ from echo.validators import partitions_port_validator
12
+
13
+
14
+ @define
15
+ class PartitionedMultiCommodityTellegenNode(Node):
16
+ """
17
+ A node with partitions of ports, ports in each partition may have multiple commodities.
18
+ A tellegen constraint is applied per partition per commodity.
19
+ """
20
+
21
+ partitions: dict[str, list[Port]] = field(factory=dict, validator=partitions_port_validator)
22
+ default_partition: str = "default_partition"
23
+
24
+ def __attrs_post_init__(self) -> None:
25
+ if len(self.ports):
26
+ if len(self.partitions):
27
+ raise ValueError(
28
+ "Expect user to define either ports dictionary or partitions dictionary, "
29
+ "but not both on an instance of PartitionedMultiCommodityTellegenNode."
30
+ f"Offending instance {self.node_name}"
31
+ )
32
+ else:
33
+ # If user defined ports but not partitions, assign all ports to a default partition
34
+ self.partitions = {self.default_partition: list(self.ports.values())}
35
+ else:
36
+ self.ports = {_p.port_name: _p for port_set in self.partitions.values() for _p in port_set}
37
+
38
+ def add_port(self, name: str, port: Port, partition: str | None = None) -> None:
39
+ """Override base add_port method, add addition argument which is partition name to which add the port.
40
+
41
+ If partition is not specified, adds to the default partition.
42
+ """
43
+ if partition is None:
44
+ partition = self.default_partition
45
+ if self.ports.get(name) is None:
46
+ self.ports[name] = port
47
+ if not self.partitions.get(partition):
48
+ """If partition with this name does not exist in the partition dictionary, add new item."""
49
+ self.partitions[partition] = [port]
50
+ else:
51
+ self.partitions[partition].append(port)
52
+ else:
53
+ raise ConfigurationError(f"Port with name {name} is already defined on node {self.node_name}")
54
+
55
+ def apply_node_constraints(self, model: EchoConcreteModel) -> None:
56
+ """Apply Tellegen constraint for same commodity ports within each partition."""
57
+
58
+ def tellegen_node_rule(
59
+ partition_ports: Iterable[Port],
60
+ model: EchoConcreteModel,
61
+ p: int,
62
+ t: int,
63
+ ) -> EqualityExpression:
64
+ net_flow = 0
65
+ for port in partition_ports:
66
+ port_flow = getattr(model, port.port_name)
67
+ net_flow += port_flow[p, t]
68
+ return net_flow == 0
69
+
70
+ partition_commodities = dict()
71
+ for _partition, _ports in self.partitions.items():
72
+ for p in _ports:
73
+ _key = (_partition, p.units)
74
+ if partition_commodities.get(_key) is None:
75
+ partition_commodities[_key] = [p]
76
+ else:
77
+ partition_commodities[_key].append(p)
78
+
79
+ for partition_commodity_type, partition_ports in partition_commodities.items():
80
+ setattr(
81
+ model,
82
+ "node_con_" + str(partition_commodity_type) + self.node_name,
83
+ en.Constraint(
84
+ model.Expansion,
85
+ model.Time,
86
+ rule=partial(tellegen_node_rule, partition_ports),
87
+ ),
88
+ )