Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(kg): correct calculate_pagerank return type and documentation (#1953)
Thomas Lina28b1ba4c728
diff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.pyindex 37e691a0..4356052c 100644--- a/semantica/kg/centrality_calculator.py+++ b/semantica/kg/centrality_calculator.py@@ -36,7 +36,7 @@ Example Usage:>>> calculator = CentralityCalculator()>>> centrality = calculator.calculate_degree_centrality(graph)>>> all_centrality = calculator.calculate_all_centrality(graph)- >>> pagerank_scores = calculator.calculate_pagerank(graph, damping_factor=0.85)+ >>> pagerank_result = calculator.calculate_pagerank(graph, damping_factor=0.85)>>> top_nodes = calculator.get_top_nodes(centrality, top_k=10)Author: Semantica Contributors@@ -598,7 +598,7 @@ class CentralityCalculator:# Aliases used by some callersalpha: Optional[float] = None,max_iter: Optional[int] = None,- ) -> Dict[str, float]:+ ) -> Dict[str, Any]:"""Calculate PageRank scores for nodes in the graph.@@ -622,7 +622,9 @@ class CentralityCalculator:tolerance: Convergence tolerance for PageRank valuesReturns:- Dictionary mapping node IDs to PageRank scores+ Dictionary containing:+ - centrality: Mapping of node IDs to PageRank scores+ - rankings: List of ``(node_id, score)`` tuples sorted highest firstRaises:ValueError: If graph is empty or parameters are invaliddiff --git a/semantica/kg/kg_usage.md b/semantica/kg/kg_usage.mdindex 7695d89d..d3c6637e 100644--- a/semantica/kg/kg_usage.md+++ b/semantica/kg/kg_usage.md@@ -820,7 +820,7 @@ pagerank_scores = centrality_calc.calculate_pagerank()print("PageRank scores:")-for node_id, score in sorted(pagerank_scores.items(), key=lambda x: x[1], reverse=True)[:10]:+for node_id, score in pagerank_scores["rankings"][:10]:print(f" {node_id}: {score:.4f}")```@@ -846,11 +846,11 @@ low_damping = centrality_calc.calculate_pagerank()print("High damping factor top nodes:")-for node_id, score in sorted(high_damping.items(), key=lambda x: x[1], reverse=True)[:5]:+for node_id, score in high_damping["rankings"][:5]:print(f" {node_id}: {score:.4f}")print("Low damping factor top nodes:")-for node_id, score in sorted(low_damping.items(), key=lambda x: x[1], reverse=True)[:5]:+for node_id, score in low_damping["rankings"][:5]:print(f" {node_id}: {score:.4f}")```@@ -893,7 +893,7 @@ pagerank_filtered = centrality_calc.calculate_pagerank()print("PageRank for People and Organizations:")-for node_id, score in sorted(pagerank_filtered.items(), key=lambda x: x[1], reverse=True)[:10]:+for node_id, score in pagerank_filtered["rankings"][:10]:print(f" {node_id}: {score:.4f}")```@@ -1586,7 +1586,7 @@ pagerank_scores = calculate_pagerank(max_iterations=100,damping_factor=0.85)-print(f"PageRank calculated for {len(pagerank_scores)} nodes")+print(f"PageRank calculated for {len(pagerank_scores['centrality'])} nodes")# Label Propagation community detectioncommunities = detect_communities_label_propagation(@@ -1846,7 +1846,7 @@ for ranking in degree_centrality["rankings"][:5]:# 6. Calculate PageRank centralitypagerank_scores = centrality_calc.calculate_pagerank(kg, max_iterations=100, damping_factor=0.85)print("Top 5 nodes by PageRank:")-for node_id, score in sorted(pagerank_scores.items(), key=lambda x: x[1], reverse=True)[:5]:+for node_id, score in pagerank_scores["rankings"][:5]:print(f" {node_id}: {score:.4f}")# 7. Detect traditional communities@@ -1982,7 +1982,7 @@ from semantica.kg import (centrality_calc = CentralityCalculator()pagerank_scores = centrality_calc.calculate_pagerank(kg, max_iterations=100)-influential_entities = sorted(pagerank_scores.items(), key=lambda x: x[1], reverse=True)[:10]+influential_entities = pagerank_scores["rankings"][:10]print("Top 10 most influential entities:")for entity_id, score in influential_entities:print(f" {entity_id}: {score:.4f}")@@ -2040,4 +2040,3 @@ for source, target, length in sorted(optimal_paths, key=lambda x: x[2])[:10]:```This comprehensive guide demonstrates how to use all the graph algorithms in the knowledge graph module, from basic usage to advanced real-world applications. Each algorithm is designed to work with the existing KG infrastructure and can be combined for powerful analytics workflows.-diff --git a/semantica/kg/methods.py b/semantica/kg/methods.pyindex c5d28976..854ef2d8 100644--- a/semantica/kg/methods.py+++ b/semantica/kg/methods.py@@ -803,7 +803,7 @@ def calculate_pagerank(max_iterations: int = 100,damping_factor: float = 0.85,**kwargs-) -> Dict[str, float]:+) -> Dict[str, Any]:"""Calculate PageRank scores for nodes.@@ -822,7 +822,9 @@ def calculate_pagerank(**kwargs: Additional parameters for PageRank calculationReturns:- Dictionary mapping node IDs to PageRank scores+ Dictionary containing:+ - centrality: Mapping of node IDs to PageRank scores+ - rankings: List of ``(node_id, score)`` tuples sorted highest firstRaises:ValueError: If graph is empty or parameters are invalid@@ -830,11 +832,12 @@ def calculate_pagerank(Examples:>>> from semantica.kg.methods import calculate_pagerank- >>> scores = calculate_pagerank(+ >>> result = calculate_pagerank(... graph,... node_labels=["Entity"],... max_iterations=30... )+ >>> result["rankings"][:3]"""try:pass # CentralityCalculator imported at module leveldiff --git a/tests/kg/test_methods.py b/tests/kg/test_methods.pyindex 006e2aa2..348a6c7d 100644--- a/tests/kg/test_methods.py+++ b/tests/kg/test_methods.py@@ -350,7 +350,8 @@ class TestCalculatePageRank:"""Test calculate_pagerank with default parameters."""mock_calculator = Mock()mock_calculator.calculate_pagerank.return_value = {- "A": 0.25, "B": 0.25, "C": 0.25, "D": 0.25+ "centrality": {"A": 0.25, "B": 0.25, "C": 0.25, "D": 0.25},+ "rankings": [("A", 0.25), ("B", 0.25), ("C", 0.25), ("D", 0.25)],}mock_calculator_class.return_value = mock_calculator@@ -358,14 +359,18 @@ class TestCalculatePageRank:mock_calculator_class.assert_called_once()mock_calculator.calculate_pagerank.assert_called_once()- assert result == {"A": 0.25, "B": 0.25, "C": 0.25, "D": 0.25}+ assert result == {+ "centrality": {"A": 0.25, "B": 0.25, "C": 0.25, "D": 0.25},+ "rankings": [("A", 0.25), ("B", 0.25), ("C", 0.25), ("D", 0.25)],+ }@patch('semantica.kg.methods.CentralityCalculator')def test_calculate_pagerank_custom_params(self, mock_calculator_class):"""Test calculate_pagerank with custom parameters."""mock_calculator = Mock()mock_calculator.calculate_pagerank.return_value = {- "A": 0.4, "B": 0.3, "C": 0.2, "D": 0.1+ "centrality": {"A": 0.4, "B": 0.3, "C": 0.2, "D": 0.1},+ "rankings": [("A", 0.4), ("B", 0.3), ("C", 0.2), ("D", 0.1)],}mock_calculator_class.return_value = mock_calculator@@ -384,7 +389,10 @@ class TestCalculatePageRank:max_iterations=30,damping_factor=0.9)- assert result == {"A": 0.4, "B": 0.3, "C": 0.2, "D": 0.1}+ assert result == {+ "centrality": {"A": 0.4, "B": 0.3, "C": 0.2, "D": 0.1},+ "rankings": [("A", 0.4), ("B", 0.3), ("C", 0.2), ("D", 0.1)],+ }@patch('semantica.kg.methods.CentralityCalculator')def test_calculate_pagerank_error(self, mock_calculator_class):@@ -595,7 +603,8 @@ class TestMethodsIntegration:# Mock PageRank calculationmock_calculator = Mock()mock_calculator.calculate_pagerank.return_value = {- "A": 0.4, "B": 0.3, "C": 0.2, "D": 0.1+ "centrality": {"A": 0.4, "B": 0.3, "C": 0.2, "D": 0.1},+ "rankings": [("A", 0.4), ("B", 0.3), ("C", 0.2), ("D", 0.1)],}mock_calculator_class.return_value = mock_calculator@@ -608,8 +617,8 @@ class TestMethodsIntegration:mock_detector_class.return_value = mock_detector# Calculate PageRank- pagerank_scores = calculate_pagerank(self.mock_graph)- assert len(pagerank_scores) == 4+ pagerank_result = calculate_pagerank(self.mock_graph)+ assert len(pagerank_result["centrality"]) == 4# Detect communitiescommunities = detect_communities_label_propagation(self.mock_graph)diff --git a/tests/test_mcp_server_community_count.py b/tests/test_mcp_server_community_count.pyindex fe3cbe6b..519ad50a 100644--- a/tests/test_mcp_server_community_count.py+++ b/tests/test_mcp_server_community_count.py@@ -5,12 +5,10 @@ result. That result is a wrapper dict (`communities`, `node_assignments`,`modularity`, `algorithm`), so the tool reported the key count — 4 for everygraph and every algorithm — instead of the number of communities.-The line is unreachable through the real calculator on `main`: the sort feeding-`top_nodes_by_pagerank` raises first on a ContextGraph (issue #1747). Before-#1744 the failure happened one step earlier, inside `calculate_pagerank` itself-(issue #1721). These tests stub PageRank with a flat mapping, which both the old-sort and the #1747 ranking helper accept, so the handler reaches the community-line however those two fixes land.+These tests stub PageRank so the handler reaches the community-count path+without making that test depend on PageRank calculation details. The stub+matches the current structured PageRank return contract: `centrality` contains+the node-to-score mapping and `rankings` contains ordered `(node, score)` pairs."""import unittest@@ -20,7 +18,10 @@ from semantica import mcp_serverfrom semantica.context import ContextGraphfrom semantica.kg import CentralityCalculator, CommunityDetector-PAGERANK_STUB = {"alice": 0.5, "bob": 0.3, "acme": 0.2}+PAGERANK_STUB = {+ "centrality": {"alice": 0.5, "bob": 0.3, "acme": 0.2},+ "rankings": [("alice", 0.5), ("bob", 0.3), ("acme", 0.2)],+}def _one_cluster() -> ContextGraph: