From 2e842652be9f7890bfcc887d5086ec0fbc96f15d Mon Sep 17 00:00:00 2001 From: alekszievr <44192193+alekszievr@users.noreply.github.com> Date: Sat, 8 Feb 2025 00:15:26 +0100 Subject: [PATCH] Fix diameter and shortest path calculation in networkx adapter [COG-1201] (#507) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit …nnected graph ## Description ## DCO Affirmation I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin ## Summary by CodeRabbit - Bug Fixes - Enhanced reliability of graph metric calculations to gracefully handle unexpected inputs, ensuring smoother and uninterrupted graph analysis for end-users. --- .../databases/graph/networkx/adapter.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/cognee/infrastructure/databases/graph/networkx/adapter.py b/cognee/infrastructure/databases/graph/networkx/adapter.py index d6d009893..1d0c4c540 100644 --- a/cognee/infrastructure/databases/graph/networkx/adapter.py +++ b/cognee/infrastructure/databases/graph/networkx/adapter.py @@ -404,15 +404,17 @@ class NetworkXAdapter(GraphDBInterface): return edge_density def _get_diameter(graph): - if nx.is_strongly_connected(graph): - return nx.diameter(graph.to_undirected()) - else: + try: + return nx.diameter(nx.DiGraph(graph.to_undirected())) + except Exception as e: + logger.warning("Failed to calculate diameter: %s", e) return None def _get_avg_shortest_path_length(graph): - if nx.is_strongly_connected(graph): - return nx.average_shortest_path_length(graph) - else: + try: + return nx.average_shortest_path_length(nx.DiGraph(graph.to_undirected())) + except Exception as e: + logger.warning("Failed to calculate average shortest path length: %s", e) return None def _get_avg_clustering(graph):