From 9ebd02e331052549135ab7698bb6a70b342e89c0 Mon Sep 17 00:00:00 2001 From: Gabriel Luiz Freitas Almeida Date: Mon, 12 Jun 2023 07:49:35 -0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=80=20feat(base.py):=20add=20topologic?= =?UTF-8?q?al=5Fsort=20method=20to=20perform=20a=20topological=20sort=20of?= =?UTF-8?q?=20the=20vertices=20in=20the=20graph=20=F0=9F=9A=80=20feat(base?= =?UTF-8?q?.py):=20add=20generator=5Fbuild=20method=20to=20build=20each=20?= =?UTF-8?q?node=20in=20the=20graph=20and=20yield=20it=20The=20topological?= =?UTF-8?q?=5Fsort=20method=20performs=20a=20topological=20sort=20of=20the?= =?UTF-8?q?=20vertices=20in=20the=20graph,=20returning=20a=20list=20of=20v?= =?UTF-8?q?ertices=20in=20topological=20order.=20The=20generator=5Fbuild?= =?UTF-8?q?=20method=20builds=20each=20node=20in=20the=20graph=20and=20yie?= =?UTF-8?q?lds=20it.=20These=20methods=20are=20useful=20for=20building=20t?= =?UTF-8?q?he=20graph=20in=20a=20specific=20order,=20which=20is=20importan?= =?UTF-8?q?t=20for=20certain=20algorithms=20that=20rely=20on=20the=20order?= =?UTF-8?q?=20of=20the=20nodes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/backend/langflow/graph/graph/base.py | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/backend/langflow/graph/graph/base.py b/src/backend/langflow/graph/graph/base.py index 1e9d1f10f..dba948693 100644 --- a/src/backend/langflow/graph/graph/base.py +++ b/src/backend/langflow/graph/graph/base.py @@ -107,6 +107,48 @@ class Graph: raise ValueError("No root node found") return root_node.build() + def topological_sort(self) -> List[Vertex]: + """ + Performs a topological sort of the vertices in the graph. + + Returns: + List[Vertex]: A list of vertices in topological order. + + Raises: + ValueError: If the graph contains a cycle. + """ + # States: 0 = unvisited, 1 = visiting, 2 = visited + state = {node: 0 for node in self.nodes} + sorted_vertices = [] + + def dfs(node): + if state[node] == 1: + # We have a cycle + raise ValueError( + "Graph contains a cycle, cannot perform topological sort" + ) + if state[node] == 0: + state[node] = 1 + for edge in node.edges: + if edge.source == node: + dfs(edge.target) + state[node] = 2 + sorted_vertices.append(node) + + # Visit each node + for node in self.nodes: + if state[node] == 0: + dfs(node) + + return list(reversed(sorted_vertices)) + + def generator_build(self) -> List[Vertex]: + """Builds each + node in the graph and yields it.""" + sorted_vertices = self.topological_sort() + for node in sorted_vertices: + yield node.build() + def get_node_neighbors(self, node: Vertex) -> Dict[Vertex, int]: """Returns the neighbors of a node.""" neighbors: Dict[Vertex, int] = {}