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,546 @@
1
+ from __future__ import annotations # Deprecating in python 3.15 in favour of lazy annotations (PEP 649 and 749)
2
+
3
+ import os
4
+ import warnings
5
+ from collections.abc import Iterable
6
+ from typing import cast
7
+
8
+ import matplotlib
9
+ import networkx as nx
10
+ import pyomo.environ as en
11
+ from attrs import define, field
12
+ from deprecated import deprecated
13
+ from pyomo.core.expr.relational_expr import EqualityExpression, InequalityExpression
14
+
15
+ from echo.configuration import Units
16
+ from echo.exceptions import ConfigurationError, validate
17
+ from echo.models.base.edge import Edge
18
+ from echo.models.base.node import Node
19
+ from echo.models.base.path import Path
20
+ from echo.models.base.port import Port
21
+ from echo.models.scenario import EchoConcreteModel
22
+ from echo.validators import ArrayType
23
+
24
+
25
+ @define
26
+ class OptimisationGraph:
27
+ nodes: dict[str, Node] = field(factory=dict) # Nodes keyed by their node_name
28
+ edges: dict[tuple[str, str], Edge] = field(factory=dict)
29
+ paths: dict[tuple, Path] = field(factory=dict)
30
+
31
+ @property
32
+ @deprecated
33
+ def node_obj(self) -> dict[str, Node]:
34
+ return self.nodes
35
+
36
+ @property
37
+ @deprecated
38
+ def edge_obj(self) -> dict[tuple[str, str], Edge]:
39
+ return self.edges
40
+
41
+ def node_name_list(self) -> list[str]:
42
+ return list(self.nodes.keys())
43
+
44
+ def edge_list(self) -> list[str]:
45
+ return [e.edge_name for e in self.edges.values()]
46
+
47
+ def convert_to_nx(self) -> nx.Graph:
48
+ """Converts the OptimisationGraph to a networkx graph, where nx nodes are echo node names and nx edges are
49
+ nx node pairs"""
50
+ g = nx.Graph()
51
+ g.add_nodes_from(self.nodes.keys())
52
+ g.add_edges_from(self.edges.keys())
53
+ return g
54
+
55
+ # This method should be made private and the public method deprecated
56
+ def add_node(self, node: Node) -> None:
57
+ self.nodes[node.node_name] = node
58
+
59
+ def add_nodes(self, nodes: Node | Iterable[Node]) -> None:
60
+ """Adds either a single node or list of nodes to graph"""
61
+ if isinstance(nodes, Node):
62
+ self.add_node(nodes)
63
+ return
64
+
65
+ for node in nodes:
66
+ self.add_node(node)
67
+
68
+ @deprecated(version="2.3.0")
69
+ def delete_node(self, node_name: str) -> None:
70
+ if self.get_node(node_name) is not None:
71
+ del self.nodes[node_name]
72
+ else:
73
+ print(f"Node {node_name} not found.")
74
+
75
+ @deprecated(version="2.3.0")
76
+ def delete_edge(self, edge_nodes: tuple[str, str]) -> None:
77
+ if self.get_edge(edge_nodes) is not None:
78
+ del self.edges[edge_nodes]
79
+ else:
80
+ print(f"Edge {edge_nodes} not found.")
81
+
82
+ @deprecated(version="2.3.0", reason="Use add_nodes method instead.")
83
+ def add_node_obj(self, node: list | Node) -> None:
84
+ """Adds either a single node or list of nodes to graph"""
85
+ # todo phase out this method
86
+ if isinstance(node, list):
87
+ for n in node:
88
+ self.add_node(n)
89
+ else:
90
+ self.add_node(node)
91
+
92
+ @deprecated(version="2.3.0", reason="Use add_nodes method instead.")
93
+ def add_nodes_from(self, nodes: list[Node]) -> None:
94
+ """Adds a list of nodes to the graph."""
95
+ for n in nodes:
96
+ self.add_node(n)
97
+
98
+ def get_node(self, node_name: str) -> Node | None:
99
+ """Returns node object given node name"""
100
+ return self.nodes.get(node_name)
101
+
102
+ def get_edge(self, nodes: tuple[str, str]) -> Edge | None:
103
+ """Retrieves the edge that connects a tuple of nodes, if an edge exists."""
104
+ if nodes in self.edges:
105
+ return self.edges.get(nodes)
106
+
107
+ reversed_nodes = (nodes[1], nodes[0])
108
+ if reversed_nodes in self.edges:
109
+ return self.edges.get(reversed_nodes)
110
+
111
+ return None
112
+
113
+ def add_edge(self, edge: Edge, nodes: tuple[str, str] | None = None) -> None:
114
+ port1 = edge.vertices[0]
115
+ port2 = edge.vertices[1]
116
+ validate(
117
+ port1.units == port2.units,
118
+ f"Ports on edge must have matching units. {port1.units} != {port2.units}",
119
+ )
120
+ if nodes is None:
121
+ # Want to avoid doing this lookup - very slow
122
+ node1_name = self.lookup_node_names_from_port(port1)
123
+ node2_name = self.lookup_node_names_from_port(port2)
124
+ else:
125
+ node1_name = nodes[0]
126
+ node2_name = nodes[1]
127
+ # Need to check whether an edge already exists between these two nodes
128
+ if self.get_edge(nodes=(node1_name, node2_name)) is not None:
129
+ raise ValueError("An edge between these nodes already exists")
130
+
131
+ self.edges[(node1_name, node2_name)] = edge
132
+
133
+ @deprecated(version="2.3.0", reason="Use add_edge method instead.")
134
+ def add_edge_obj(self, edge: list[Edge] | Edge) -> None:
135
+ # todo phase out this method
136
+ if isinstance(edge, list):
137
+ for e in edge:
138
+ self.add_edge(e)
139
+ else:
140
+ self.add_edge(edge)
141
+
142
+ @deprecated(version="2.3.0", reason="Use add_edge method instead.")
143
+ def add_edges_from(self, edge: list[Edge]) -> None:
144
+ for e in edge:
145
+ self.add_edge(e)
146
+
147
+ # @deprecated
148
+ # Ideally this should be deprecated and users should use `add_edge` as the main
149
+ # way off adding edges to the optimisation graph.
150
+ def connect_ports_and_create_edge(
151
+ self,
152
+ port1: Port,
153
+ port2: Port,
154
+ edge_name: str | None = None,
155
+ ) -> None:
156
+ """Creates an edge between port1 and port2 and adds it to the graph"""
157
+ edge = Edge(vertices=(port1, port2), edge_name=edge_name) if edge_name else Edge(vertices=(port1, port2))
158
+ self.add_edge(edge)
159
+
160
+ @deprecated(
161
+ version="2.3.0",
162
+ reason="No longer needed after migration to attrs",
163
+ )
164
+ def rebuild_all_edges(self) -> None:
165
+ """Deletes and rebuilds all edges. Deprecated and replaced with a `pass` (i.e. no operation)
166
+
167
+ To be used after stateful data has been injected into ports. Injecting stateful data into ports alters the
168
+ port. The new altered port correctly remains associated with the node, but does not remain associated with
169
+ any edges this port may be associated with. This method builds new edges for each old edge based on the port
170
+ name associated with each end of the edge. The original edge is deleted.
171
+
172
+ Returns:
173
+ None
174
+ """
175
+ pass
176
+
177
+ def lookup_node_names_from_port(self, port: Port) -> str:
178
+ """Returns node name of the node that a specified port belongs to, if the port belongs to a node."""
179
+ for node_name, node in self.nodes.items():
180
+ for p in node.ports.values():
181
+ if port == p:
182
+ return node_name
183
+ raise ConfigurationError(f"Port {port.port_name} is not part of any node, or node has not been added to graph.")
184
+
185
+ def get_ports_on_edge_from_nodes(self, node1: str, node2: str) -> tuple[Port, Port] | None:
186
+ """Returns the ports that are on the edge from node1 to node2."""
187
+ connecting_edge = self.edges.get((node1, node2))
188
+ if connecting_edge:
189
+ node1_port = connecting_edge.vertices[0]
190
+ node2_port = connecting_edge.vertices[1]
191
+ return node1_port, node2_port
192
+ else:
193
+ connecting_edge = self.edges.get((node2, node1))
194
+ if connecting_edge:
195
+ node1_port = connecting_edge.vertices[1]
196
+ node2_port = connecting_edge.vertices[0]
197
+ return node1_port, node2_port
198
+
199
+ return None
200
+
201
+ def get_sources_and_sinks(self) -> set[Node]:
202
+ """Returns a set that contains all source and sink nodes."""
203
+ validate(
204
+ bool(self.paths) is True,
205
+ "Create paths before retrieving sources and sinks.",
206
+ )
207
+ sources_or_sinks = set()
208
+ for path in self.paths.values():
209
+ sources_or_sinks.add(path.vertices[0])
210
+ sources_or_sinks.add(path.vertices[-1])
211
+ return sources_or_sinks
212
+
213
+ def get_path(self, path_vertices: list[Node] | list[str]) -> Path:
214
+ """Looks up a path using a list of path vertices (nodes, or node names)."""
215
+ if isinstance(path_vertices[0], Node):
216
+ name_key = [cast(Node, node).node_name for node in path_vertices]
217
+ return self.paths[tuple(name_key)]
218
+ else:
219
+ if self.paths.get(tuple(path_vertices)) is not None:
220
+ return self.paths[tuple(path_vertices)]
221
+ else:
222
+ raise ValueError(f"No path with vertices {path_vertices} is defined.")
223
+
224
+ def verify_paths(self) -> None:
225
+ """Verifies that our paths meet the assumptions required to correctly do flow tracing."""
226
+ all_nodes = self.get_sources_and_sinks()
227
+ for node in all_nodes:
228
+ for path in self.paths.values():
229
+ if node in path.vertices[1:-1]:
230
+ # if the source/sink node appears in the middle of another path, the optimiser will fail
231
+ # A node can't be both a tellegen node and a source/sink node
232
+ raise ConfigurationError("Source/sink node is being treated as a tellegen node.")
233
+
234
+ def create_path_objects(
235
+ self,
236
+ sources: list[Node] | list[str],
237
+ sinks: list[Node] | list[str],
238
+ path_unit: Units = Units.KW,
239
+ regularise: bool = False,
240
+ ) -> None:
241
+ """Creates path objects according to source/sink lists provided."""
242
+
243
+ if os.environ["ECHO_DISABLE_EXPERIMENTAL_PATH_WARNING"] != "1":
244
+ warnings.warn(
245
+ "Path tracing is still experimental. If you are generating paths to use path tariffs, please consider "
246
+ + "whether you can convert these tariffs to point/port tariffs.",
247
+ stacklevel=1,
248
+ )
249
+
250
+ all_paths = {}
251
+ graph = self.convert_to_nx()
252
+
253
+ if isinstance(sources[0], Node):
254
+ sources = [cast(Node, i).node_name for i in sources]
255
+
256
+ if isinstance(sinks[0], Node):
257
+ sinks = [cast(Node, i).node_name for i in sinks]
258
+
259
+ tellegen_node_set = set() # create a set to store list of nodes that are treated as tellegen nodes
260
+ source_sink_set = set(sources + sinks) # create a set of nodes that are treated as sinks/sources
261
+
262
+ for source_node in sources:
263
+ for sink_node in sinks:
264
+ if source_node is not sink_node:
265
+ # Find all the paths, just using the node names
266
+ simple_paths = nx.all_simple_paths(graph, source_node, sink_node)
267
+ simple_edges = nx.all_simple_edge_paths(graph, source_node, sink_node)
268
+ for vertex_list, edge_list in zip(simple_paths, simple_edges, strict=True):
269
+ tellegen_node_set.update(vertex_list[1:-1]) # update set of tellegen nodes
270
+ p = self._create_path_object(vertex_list, edge_list, regularise, path_unit) # create path
271
+ all_paths[tuple(vertex_list)] = p
272
+
273
+ intersection = source_sink_set.intersection(tellegen_node_set) # check overlap of tellegen and src/sink nodes
274
+
275
+ validate(
276
+ len(intersection) == 0,
277
+ f"Nodes '{intersection}' are being treated as both tellegen and source/sink.",
278
+ )
279
+
280
+ self.paths = all_paths
281
+
282
+ def _create_path_object(self, vertex_list: list, edge_list: list, regularise: bool, path_unit: Units) -> Path:
283
+ """Creates a path object"""
284
+ p = Path(vertices=vertex_list, regularise=regularise, units=path_unit) # Create path object
285
+ for edge in edge_list:
286
+ edge_ports = self.get_ports_on_edge_from_nodes(edge[0], edge[1])
287
+ validate(
288
+ edge_ports is not None,
289
+ f"get_ports_on_edge_from_nodes return None for edges {edge[0]}, {edge[1]}",
290
+ )
291
+ p.edge_ports.append(edge_ports)
292
+ return p
293
+
294
+ def apply_path_constraints(self, model: EchoConcreteModel) -> None:
295
+ """Applies path tracing constraints to model"""
296
+
297
+ def path_flow_rule(model: EchoConcreteModel, p: int, t: int) -> EqualityExpression:
298
+ a = 0
299
+ for path in self.paths.values(): # Iterate through all paths in the model
300
+ if path.vertices[0] is current_node_name: # If the path starts at the current node
301
+ a += getattr(model, path.flow_value)[p, t] # Add the flow value
302
+ if path.vertices[-1] is current_node_name: # If the path ends at the current node
303
+ a -= getattr(model, path.flow_value)[p, t] # Subtract the flow value
304
+ return a == getattr(model, current_port.port_name)[p, t] * -1 # Flows out - flows in = -1 * port
305
+
306
+ def only_inflow_or_outflow1(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
307
+ a = 0
308
+ for path in self.paths.values():
309
+ if path.vertices[-1] is current_node_name: # If the path ends at the current node
310
+ a += getattr(model, path.flow_value)[p, t] # Add the flow value
311
+ return (
312
+ a <= getattr(model, current_node.inflow)[p, t] * model.big_m
313
+ ) # Incoming paths can only be non-zero if inflow=1
314
+
315
+ def only_inflow_or_outflow2(model: EchoConcreteModel, p: int, t: int) -> InequalityExpression:
316
+ a = 0
317
+ for path in self.paths.values():
318
+ if path.vertices[0] is current_node_name: # If the path starts at the node
319
+ a += getattr(model, path.flow_value)[p, t] # Add the flow value
320
+ return (
321
+ a <= (1 - getattr(model, current_node.inflow)[p, t]) * model.big_m
322
+ ) # Outgoing paths can only be non-zero if inflow=0
323
+
324
+ sources_and_sinks = self.get_sources_and_sinks() # returns concatenated list of all source/sink nodes
325
+ for current_node_name in sources_and_sinks: # Iterate through the source/sink nodes
326
+ current_node = self.nodes[current_node_name] # get the node obj
327
+ for (
328
+ path_vertices,
329
+ path_obj,
330
+ ) in self.paths.items(): # Iterate through all paths
331
+ if current_node_name is path_vertices[0]: # If the path starts at the current node
332
+ current_port = path_obj.edge_ports[0][0] # Pick up the first port on the path
333
+ elif current_node_name is path_vertices[-1]: # If the path ends at the current node
334
+ current_port = path_obj.edge_ports[-1][-1] # Pick up the last port on the path
335
+
336
+ setattr(
337
+ model,
338
+ f"path_flow_con1_{current_node_name}",
339
+ en.Constraint(model.Expansion, model.Time, rule=path_flow_rule),
340
+ )
341
+
342
+ # Create an indicator var for when there are flows into a node
343
+ setattr(
344
+ model,
345
+ current_node.inflow,
346
+ en.Var(model.Expansion, model.Time, initialize=0, domain=en.Binary),
347
+ )
348
+
349
+ setattr(
350
+ model,
351
+ f"path_flow_con2_{current_node_name}",
352
+ en.Constraint(model.Expansion, model.Time, rule=only_inflow_or_outflow1),
353
+ )
354
+
355
+ setattr(
356
+ model,
357
+ f"path_flow_con3_{current_node_name}",
358
+ en.Constraint(model.Expansion, model.Time, rule=only_inflow_or_outflow2),
359
+ )
360
+
361
+ def draw_on_axes(
362
+ self,
363
+ axes: matplotlib.axes.Axes,
364
+ with_labels: bool = False,
365
+ labels: dict[str, str] | None = None,
366
+ **kwargs,
367
+ ) -> None:
368
+ """Draws the network on a matplotlib plot
369
+
370
+ Args:
371
+ axes (matplotlib.axes.Axes): The (sub-)plot on which to draw the network
372
+ with_labels (bool): Set to True to draw labels on the nodes. Defaults to False.
373
+ Uses the node's names as the label.
374
+ labels (dict): Optional way of supplying node labels as a dictionary of labels (strings) keyed by node.
375
+ Default = None.
376
+ **kwargs: Optional keyword arguments for customising the drawing of the network. See
377
+ networkx.drawing.nx_pylab.draw_networkx documentation for more information.
378
+
379
+ Examples:
380
+ The following example shows how to draw an already created OptimisationGraph with the name `network`
381
+
382
+ >>> import matplotlib.pyplot as plt
383
+ >>> network_figure = plt.figure()
384
+ >>> network_axes = network_figure.add_subplot()
385
+ >>> network.draw_on_axes(axes=network_axes, with_labels=True)
386
+ >>> plt.show()
387
+ """
388
+ nx.draw_networkx(
389
+ self.convert_to_nx(),
390
+ ax=axes,
391
+ with_labels=with_labels,
392
+ labels=labels,
393
+ **kwargs,
394
+ )
395
+
396
+ def to_cytoscape_json(self) -> str:
397
+ """Converts the optimisation graph to json that can be read by cytoscape (https://js.cytoscape.org/)"""
398
+ import json
399
+
400
+ graph = self.convert_to_nx()
401
+ nodes = []
402
+ for node in graph.nodes():
403
+ nodes.append({"data": {"id": node}})
404
+ for n1, n2 in graph.edges():
405
+ nodes.append({"data": {"id": f"{n1}_{n2}", "source": n1, "target": n2}})
406
+
407
+ return json.dumps(nodes)
408
+
409
+ @deprecated(version="2.3.0")
410
+ def print_port_names(self) -> None:
411
+ """Prints port name-uid pairs, useful for debugging infeasible optimisation"""
412
+ for n in self.nodes.values():
413
+ for pn, p in n.ports.items():
414
+ print(pn, ", ", p.port_name)
415
+
416
+ def _get_port_names_from_nodes(self, skip_dangling_ports: bool = False) -> set[str]:
417
+ output = set()
418
+ for n in self.nodes.values():
419
+ for p in n.ports.values():
420
+ if skip_dangling_ports and not p.allow_dangling_port:
421
+ output.add(p.port_name)
422
+ return output
423
+
424
+ @deprecated(version="2.3.0")
425
+ def get_port_names_from_nodes(self, skip_dangling_ports: bool = False) -> set[str]:
426
+ return self._get_port_names_from_nodes(skip_dangling_ports=skip_dangling_ports)
427
+
428
+ def _get_port_names_from_edges(self) -> set[str]:
429
+ output = set()
430
+ for e in self.edges.values():
431
+ output.add(e.vertices[0].port_name)
432
+ output.add(e.vertices[1].port_name)
433
+ return output
434
+
435
+ @deprecated(version="2.3.0")
436
+ def get_port_names_from_edges(self) -> set[str]:
437
+ return self._get_port_names_from_edges()
438
+
439
+ def verify_graph(self) -> None:
440
+ """Checks that the graph is connected (all nodes have at least one edge), and warns if there
441
+ are unconnected ports"""
442
+ validate(nx.is_connected(self.convert_to_nx()) is True, "Graph is not connected.")
443
+ # Check graph for ports that are not connected
444
+ ports_on_edges = self._get_port_names_from_nodes(skip_dangling_ports=True)
445
+ ports_on_nodes = self._get_port_names_from_edges()
446
+ diff = ports_on_edges - ports_on_nodes # check overlap
447
+ if len(diff) != 0:
448
+ warnings.warn(
449
+ f"Ports {diff} are defined on nodes but are not part of an edge. "
450
+ "This may cause erroneous optimisation results.",
451
+ stacklevel=1,
452
+ )
453
+
454
+ def split_graph_on_edge(self, node1: str, node2: str) -> tuple[OptimisationGraph, OptimisationGraph]:
455
+ """Splits a graph between node1 and node 2, and returns two echo optimisation graphs.
456
+ The ports on the split edge are kept in the two new graphs."""
457
+ system = self.convert_to_nx()
458
+ # Find the edge that connects these nodes
459
+ if system.has_edge(node1, node2):
460
+ system.remove_edge(node1, node2)
461
+ else:
462
+ raise ValueError(f'No edge exists between nodes "{node1}" and "{node2}"')
463
+
464
+ # Get a list of the two sets of nodes
465
+ y = nx.connected_components(system)
466
+ g1_nodes = next(y)
467
+ g2_nodes = next(y)
468
+
469
+ g1_subgraph = system.subgraph(g1_nodes)
470
+ g2_subgraph = system.subgraph(g2_nodes)
471
+
472
+ def create_new_graph(nodes: list[str], edges: list) -> OptimisationGraph:
473
+ """Creates a new graph from a list of node names and edge names"""
474
+ new_graph = OptimisationGraph()
475
+ for n in nodes:
476
+ new_graph.add_nodes(self.nodes[n])
477
+ for ed in edges:
478
+ if self.edges.get(ed) is not None:
479
+ new_graph.add_edge(self.edges[ed])
480
+ else:
481
+ new_graph.add_edge(self.edges[(ed[1], ed[0])])
482
+
483
+ return new_graph
484
+
485
+ graph1 = create_new_graph(g1_subgraph.nodes, g1_subgraph.edges)
486
+ graph2 = create_new_graph(g2_subgraph.nodes, g2_subgraph.edges)
487
+
488
+ return graph1, graph2
489
+
490
+ @deprecated(
491
+ version="2.3.0",
492
+ reason="No longer needed after migration to attrs. Modify nodes directly.",
493
+ )
494
+ def update_node(self, node_name: str, **kwargs) -> None:
495
+ # Originally this method was necessary because pydantic created clones of objects upon mutation
496
+ # and the edges that made up the optimisation graph
497
+
498
+ # The user should no longer need this function since they can either modifify nodes directly.
499
+
500
+ # Inject stateful data
501
+ # If the node has a set_stateful_attrs() function, use that function.
502
+ # If it is not, use node.update()
503
+ if node := self.nodes.get(node_name):
504
+ if hasattr(node, "set_stateful_attrs"):
505
+ node.set_stateful_attrs(**kwargs)
506
+ else:
507
+ node.update(**kwargs)
508
+
509
+ @deprecated(
510
+ version="2.3.0",
511
+ reason="No longer needed after migration to attrs. Modify EV nodes directly.",
512
+ )
513
+ def inject_data_into_ev(
514
+ self,
515
+ node_name: str,
516
+ available: ArrayType | list | str | None = None,
517
+ usage: ArrayType | list | str | None = None,
518
+ initial_state_of_charge: float | None = None,
519
+ interval_duration: int | None = None,
520
+ ) -> None:
521
+ """Injects stateful data into an EV node in an OptimisationGraph.
522
+
523
+ This is a convenience method to be used for networks constructed by MESNetwork.to_echo(). It will update
524
+ all data in the relevant node and edges through re-initialisation of nodes, and delete and recreated of
525
+ the edge.
526
+
527
+ Args:
528
+ node_name: The node_name of the EV to have stateful data injected.
529
+ available: The avability data of the EV to be injected.
530
+ usage: The usage data of the EV to be injected.
531
+ initial_state_of_charge: The initial state of charge of the EV to be injected.
532
+ interval_duration: The interval duration of the EV to be injected.
533
+
534
+ Returns:
535
+ None
536
+
537
+ """
538
+
539
+ node_attributes = {
540
+ "available": available,
541
+ "usage": usage,
542
+ "initial_state_of_charge": initial_state_of_charge,
543
+ "interval_duration": interval_duration,
544
+ }
545
+
546
+ self.update_node(node_name=node_name, **node_attributes)
@@ -0,0 +1,66 @@
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
+
7
+ from echo.configuration import Units
8
+ from echo.models.base.port import Port
9
+ from echo.models.scenario import EchoConcreteModel
10
+
11
+
12
+ @define
13
+ class Path:
14
+ """A path is a sequence of distinct vertices (nodes)."""
15
+
16
+ vertices: list # list of node names
17
+
18
+ edge_ports: list[tuple[Port, Port]] = field(factory=list) # list of edge name tuples
19
+ units: Units = Units.KW
20
+ regularise: bool = False
21
+ objective: en.numeric_expr.NumericExpression | float = 0
22
+
23
+ contingency_neg: str | None = None
24
+ contingency_pos: str | None = None
25
+ path_tariff: str | None = None
26
+ slack: str | None = None
27
+
28
+ uid: str = field(factory=shortuuid.uuid)
29
+ path_name: str = field()
30
+
31
+ @path_name.default
32
+ def _set_path_name_default(self) -> str:
33
+ return "path_" + str(self.uid)
34
+
35
+ flow_value: str = field()
36
+
37
+ @flow_value.default
38
+ def _set_flow_value_default(self) -> str:
39
+ return "flow_value_" + self.path_name
40
+
41
+ def add_vertices(self, vertex_list: list) -> None:
42
+ if hasattr(vertex_list[0], "node_name"):
43
+ vertex_list = [i.node_name for i in vertex_list]
44
+ self.vertices = vertex_list
45
+
46
+ def add_path_to_model(self, model: EchoConcreteModel) -> None:
47
+ setattr(
48
+ model,
49
+ self.flow_value,
50
+ en.Var(model.Expansion, model.Time, initialize=0, domain=en.NonNegativeReals),
51
+ )
52
+
53
+ def add_objective(self, model: EchoConcreteModel) -> None:
54
+ total = 0
55
+
56
+ if self.regularise is True:
57
+ total += (
58
+ sum(
59
+ getattr(model, self.flow_value)[p, t] * getattr(model, self.flow_value)[p, t]
60
+ for p in model.Expansion
61
+ for t in model.Time
62
+ )
63
+ * 0.0000001
64
+ )
65
+
66
+ self.objective += total