From a97c29fb398a04b2e23a889627a5b30102782f3d Mon Sep 17 00:00:00 2001 From: Saurabh Misra Date: Mon, 16 Dec 2024 18:33:37 -0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=20=E2=9A=A1=EF=B8=8F=20Speed=20up?= =?UTF-8?q?=20function=20`find=5Fcycle=5Fvertices`=20by=20324%=20(#5262)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/backend/base/langflow/graph/graph/utils.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/backend/base/langflow/graph/graph/utils.py b/src/backend/base/langflow/graph/graph/utils.py index b0c3a746b..12f0cd502 100644 --- a/src/backend/base/langflow/graph/graph/utils.py +++ b/src/backend/base/langflow/graph/graph/utils.py @@ -435,13 +435,14 @@ def should_continue(yielded_counts: dict[str, int], max_iterations: int | None) def find_cycle_vertices(edges): - # Create a directed graph from the edges graph = nx.DiGraph(edges) - # Find all simple cycles in the graph - cycles = list(nx.simple_cycles(graph)) + # Initialize a set to collect vertices part of any cycle + cycle_vertices = set() - # Flatten the list of cycles and remove duplicates - cycle_vertices = {vertex for cycle in cycles for vertex in cycle} + # Utilize the strong component feature in NetworkX to find cycles + for component in nx.strongly_connected_components(graph): + if len(component) > 1 or graph.has_edge(tuple(component)[0], tuple(component)[0]): # noqa: RUF015 + cycle_vertices.update(component) return sorted(cycle_vertices)