Skip to content

Commit 1b6c74b

Browse files
Add dfs component search to component graph
The search continues to go into depth until the condition is fulfilled. The condition has to be provided as a lambda. Signed-off-by: Matthias Wende <[email protected]>
1 parent d3f7fdf commit 1b6c74b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/frequenz/sdk/microgrid/_graph.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,29 @@ def is_chp_chain(self, component: Component) -> bool:
266266
Whether the specified component is part of a CHP chain.
267267
"""
268268

269+
@abstractmethod
270+
def dfs(
271+
self,
272+
current_node: Component,
273+
visited: Set[Component],
274+
condition: Callable[[Component], bool],
275+
) -> Set[Component]:
276+
"""
277+
Search for components that fulfill the condition in the Graph.
278+
279+
DFS is used for searching the graph. The graph travarsal is stopped
280+
once a component fulfills the condition.
281+
282+
Args:
283+
current_node: The current node to search from.
284+
visited: The set of visited nodes.
285+
condition: The condition function to check for.
286+
287+
Returns:
288+
A set of component ids where the coresponding components fulfill
289+
the condition function.
290+
"""
291+
269292

270293
class _MicrogridComponentGraph(ComponentGraph):
271294
"""ComponentGraph implementation designed to work with the microgrid API.
@@ -688,6 +711,42 @@ def is_chp_chain(self, component: Component) -> bool:
688711
"""
689712
return self.is_chp(component) or self.is_chp_meter(component)
690713

714+
def dfs(
715+
self,
716+
current_node: Component,
717+
visited: Set[Component],
718+
condition: Callable[[Component], bool],
719+
) -> Set[Component]:
720+
"""
721+
Search for components that fulfill the condition in the Graph.
722+
723+
DFS is used for searching the graph. The graph travarsal is stopped
724+
once a component fulfills the condition.
725+
726+
Args:
727+
current_node: The current node to search from.
728+
visited: The set of visited nodes.
729+
condition: The condition function to check for.
730+
731+
Returns:
732+
A set of component ids where the coresponding components fulfill
733+
the condition function.
734+
"""
735+
if current_node in visited:
736+
return set()
737+
738+
visited.add(current_node)
739+
740+
if condition(current_node):
741+
return {current_node}
742+
743+
component: Set[Component] = set()
744+
745+
for successor in self.successors(current_node.component_id):
746+
component.update(self.dfs(successor, visited, condition))
747+
748+
return component
749+
691750
def _validate_graph(self) -> None:
692751
"""Check that the underlying graph data is valid.
693752

0 commit comments

Comments
 (0)