frequenz_microgrid_component_graph/graph/
creation.rs1use petgraph::graph::DiGraph;
8
9use crate::{ComponentGraphConfig, Edge, Error, Node, component_category::CategoryPredicates};
10
11use super::{ComponentGraph, EdgeMap, NodeIndexMap};
12
13impl<N, E> ComponentGraph<N, E>
15where
16 N: Node,
17 E: Edge,
18{
19 pub fn try_new<NodeIterator: IntoIterator<Item = N>, EdgeIterator: IntoIterator<Item = E>>(
27 components: NodeIterator,
28 connections: EdgeIterator,
29 config: ComponentGraphConfig,
30 ) -> Result<Self, Error> {
31 let (graph, indices) = Self::create_graph(components, &config)?;
32 let root_id = Self::find_root(&graph)?.component_id();
33
34 let mut cg = Self {
35 graph,
36 node_indices: indices,
37 root_id,
38 edges: EdgeMap::new(),
39 config,
40 };
41 cg.add_connections(connections)?;
42
43 cg.validate()?;
44
45 for component in cg.components() {
50 if component.category().is_passthrough() {
51 tracing::warn!(
52 "Component {cid} ({category}) is a pass-through category and \
53 will be treated as transparent in validators and formula generators.",
54 cid = component.component_id(),
55 category = component.category(),
56 );
57 }
58 }
59
60 Ok(cg)
61 }
62
63 fn find_root(graph: &DiGraph<N, ()>) -> Result<&N, Error> {
64 let mut roots_iter = graph.raw_nodes().iter().filter(|n| n.weight.is_grid());
65
66 let root = roots_iter
67 .next()
68 .map(|n| &n.weight)
69 .ok_or_else(|| Error::invalid_graph("No grid component found."))?;
70
71 if roots_iter.next().is_some() {
72 return Err(Error::invalid_graph("Multiple grid components found."));
73 }
74
75 Ok(root)
76 }
77
78 fn create_graph(
79 components: impl IntoIterator<Item = N>,
80 config: &ComponentGraphConfig,
81 ) -> Result<(DiGraph<N, ()>, NodeIndexMap), Error> {
82 let mut graph = DiGraph::new();
83 let mut indices = NodeIndexMap::new();
84
85 for component in components {
86 let cid = component.component_id();
87
88 if component.is_unspecified_inverter(config) {
89 return Err(Error::invalid_component(format!(
90 "InverterType not specified for inverter: {cid}"
91 )));
92 }
93 if indices.contains_key(&cid) {
94 return Err(Error::invalid_graph(format!(
95 "Duplicate component ID found: {cid}"
96 )));
97 }
98
99 let idx = graph.add_node(component);
100 indices.insert(cid, idx);
101 }
102
103 Ok((graph, indices))
104 }
105
106 fn add_connections(&mut self, connections: impl IntoIterator<Item = E>) -> Result<(), Error> {
107 for connection in connections {
108 let sid = connection.source();
109 let did = connection.destination();
110
111 if sid == did {
112 return Err(Error::invalid_connection(format!(
113 "Connection:({sid}, {did}) Can't connect a component to itself."
114 )));
115 }
116 for cid in [sid, did] {
117 let Some(&idx) = self.node_indices.get(&cid) else {
118 return Err(Error::invalid_connection(format!(
119 "Connection:({sid}, {did}) Can't find a component with ID {cid}"
120 )));
121 };
122 if self.graph[idx].is_unspecified() {
125 return Err(Error::invalid_component(format!(
126 "ComponentCategory not specified for component: {cid}"
127 )));
128 }
129 }
130
131 let source_idx = self.node_indices[&connection.source()];
132 let dest_idx = self.node_indices[&connection.destination()];
133 self.edges.insert((source_idx, dest_idx), connection);
134 self.graph.update_edge(source_idx, dest_idx, ());
135 }
136
137 Ok(())
138 }
139}
140
141#[cfg(test)]
142mod tests {
143 use super::*;
144 use crate::ComponentCategory;
145 use crate::InverterType;
146 use crate::graph::test_utils::{ComponentGraphBuilder, ComponentHandle};
147
148 fn nodes_and_edges() -> (ComponentGraphBuilder, ComponentHandle) {
149 let mut builder = ComponentGraphBuilder::new();
150
151 let grid_meter = builder.meter();
152 let meter_bat_chain = builder.meter_bat_chain(1, 1);
153 builder.connect(grid_meter, meter_bat_chain);
154
155 let meter_bat_chain = builder.meter_bat_chain(1, 1);
156 builder.connect(grid_meter, meter_bat_chain);
157
158 (builder, grid_meter)
159 }
160
161 #[test]
162 fn test_component_validation() {
163 let (mut builder, grid_meter) = nodes_and_edges();
164
165 assert!(
166 builder
167 .build(None)
168 .is_err_and(|e| e == Error::invalid_graph("No grid component found.")),
169 );
170
171 let grid = builder.grid();
172 builder.connect(grid, grid_meter);
173
174 assert!(builder.build(None).is_ok());
175
176 builder.add_component_with_id(2, ComponentCategory::Meter);
177 assert!(
178 builder
179 .build(None)
180 .is_err_and(|e| e == Error::invalid_graph("Duplicate component ID found: 2"))
181 );
182
183 builder.pop_component();
184 let unspec_inv =
185 builder.add_component(ComponentCategory::Inverter(InverterType::Unspecified));
186 builder.connect(grid_meter, unspec_inv);
187
188 assert!(builder.build(None).is_err_and(
190 |e| e == Error::invalid_component("InverterType not specified for inverter: 8")
191 ));
192 let unspec_inv_config = ComponentGraphConfig::builder()
195 .allow_unspecified_inverters(true)
196 .build();
197
198 assert!(builder.build(Some(unspec_inv_config.clone())).is_ok());
199
200 assert!(
201 builder
202 .pop_component()
203 .unwrap()
204 .is_battery_inverter(&unspec_inv_config)
205 );
206 builder.pop_connection();
207 builder.add_component(ComponentCategory::GridConnectionPoint);
208 assert!(
209 builder
210 .build(None)
211 .is_err_and(|e| e == Error::invalid_graph("Multiple grid components found."))
212 );
213
214 builder.pop_component();
215 assert!(builder.build(None).is_ok());
216 }
217
218 #[test]
219 fn test_unspecified_component_connections() -> Result<(), Error> {
220 let (mut builder, grid_meter) = nodes_and_edges();
221 let grid = builder.grid();
222 builder.connect(grid, grid_meter);
223 let consumer_formula = builder.build(None)?.consumer_formula()?.to_string();
224
225 let unspecified = builder.add_component(ComponentCategory::Unspecified);
228 let graph = builder.build(None)?;
229 assert!(
230 graph
231 .components()
232 .any(|c| c.component_id() == unspecified.component_id())
233 );
234 assert_eq!(graph.consumer_formula()?.to_string(), consumer_formula);
235
236 for (source, destination) in [(grid_meter, unspecified), (unspecified, grid_meter)] {
238 builder.connect(source, destination);
239 assert!(builder.build(None).is_err_and(|e| e
240 == Error::invalid_component("ComponentCategory not specified for component: 8")));
241 builder.pop_connection();
242 }
243
244 Ok(())
245 }
246
247 #[test]
248 fn test_connection_validation() {
249 let (mut builder, grid_meter) = nodes_and_edges();
250
251 let grid = builder.grid();
252 builder.connect(grid, grid_meter);
253
254 builder.connect(grid, grid);
255 assert!(builder.build(None).is_err_and(|e| e
256 == Error::invalid_connection(
257 "Connection:(7, 7) Can't connect a component to itself."
258 )));
259 builder.pop_connection();
260
261 builder.connect(grid_meter, ComponentHandle::new(9));
262 assert!(builder.build(None).is_err_and(|e| e
263 == Error::invalid_connection("Connection:(0, 9) Can't find a component with ID 9")));
264
265 builder.pop_connection();
266 assert!(builder.build(None).is_ok());
267 }
268}