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): keep the PageRank vector normalised when nodes are dropped (#1770)
Kevindd9e575682fb
diff --git a/plugins/skills/visualize/SKILL.md b/plugins/skills/visualize/SKILL.mdindex 594fd04e..5af788b7 100644--- a/plugins/skills/visualize/SKILL.md+++ b/plugins/skills/visualize/SKILL.md@@ -71,7 +71,7 @@ elif centrality_type == "eigenvector":elif centrality_type == "pagerank":scores = calc.calculate_pagerank(graph=graph,- max_iterations=20,+ max_iterations=100,damping_factor=0.85,)```diff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.pyindex 39fbc049..a8e15569 100644--- a/semantica/kg/centrality_calculator.py+++ b/semantica/kg/centrality_calculator.py@@ -590,7 +590,7 @@ class CentralityCalculator:graph: Any,node_labels: Optional[List[str]] = None,relationship_types: Optional[List[str]] = None,- max_iterations: int = 20,+ max_iterations: int = 100,damping_factor: float = 0.85,tolerance: float = 1e-6,# Aliases used by some callers@@ -609,7 +609,13 @@ class CentralityCalculator:``{"entities": [...], "relationships": [...]}`` mapping)node_labels: List of node labels to include (None for all)relationship_types: List of relationship types to consider (None for all)- max_iterations: Maximum number of iterations for convergence+ max_iterations: Maximum power-iteration steps. 20 is enough for small+ undirected graphs, but a directed graph with sink nodes needs far+ more before the per-node values settle (at tolerance=1e-6 a+ 10-node directed chain needs ~33 steps and a 10-leaf directed+ star ~85). The default of 100 lets those graphs converge without+ the caller raising the cap. The scores always sum to 1 whether or+ not convergence was reached.damping_factor: Probability of continuing random walk (0.85 is typical)tolerance: Convergence tolerance for PageRank values@@ -647,20 +653,25 @@ class CentralityCalculator:row_indices = []col_indices = []data = []+ has_outgoing = np.zeros(n, dtype=bool)for node in nodes:source_idx = node_index[node]neighbors = self._get_filtered_neighbors(graph, node, relationship_types)- # Distribute PageRank equally among neighbors- if neighbors:- weight = 1.0 / len(neighbors)- for neighbor in neighbors:- if neighbor in node_index: # Only include filtered nodes- target_idx = node_index[neighbor]- row_indices.append(target_idx)- col_indices.append(source_idx)- data.append(weight)+ # Distribute PageRank equally among the neighbours that survive+ # the node filter. Counting the filtered-out ones too would send+ # part of the mass to nodes outside the matrix, where it vanishes+ # (issue #1759).+ retained = [n for n in neighbors if n in node_index]+ if retained:+ weight = 1.0 / len(retained)+ for neighbour in retained:+ target_idx = node_index[neighbour]+ row_indices.append(target_idx)+ col_indices.append(source_idx)+ data.append(weight)+ has_outgoing[source_idx] = True# Create sparse matrixadjacency = sparse.csr_matrix((data, (row_indices, col_indices)), shape=(n, n))@@ -672,8 +683,19 @@ class CentralityCalculator:for iteration in range(max_iterations):prev_pagerank = pagerank.copy()- # PageRank formula: PR = (1 - d) * 1/n + d * A * PR- pagerank = (1 - damping_factor) / n + damping_factor * adjacency.dot(prev_pagerank)+ # A node with no outgoing edge inside the current node set (a+ # leaf, or a node whose neighbours were filtered out) has an+ # empty column in the transition matrix, so its mass cannot+ # flow on. Redistribute it uniformly, as standard PageRank does,+ # otherwise the scores drift below 1 on a directed graph.+ dangling_mass = prev_pagerank[~has_outgoing].sum()++ # PageRank formula: PR = (1 - d) / n + d * A * PR + d * dangling / n+ pagerank = (+ (1 - damping_factor) / n+ + damping_factor * adjacency.dot(prev_pagerank)+ + damping_factor * dangling_mass / n+ )# Check convergencediff = np.linalg.norm(pagerank - prev_pagerank)diff --git a/semantica/kg/methods.py b/semantica/kg/methods.pyindex 35f36442..c5d28976 100644--- a/semantica/kg/methods.py+++ b/semantica/kg/methods.py@@ -800,7 +800,7 @@ def calculate_pagerank(graph: Any,node_labels: Optional[List[str]] = None,relationship_types: Optional[List[str]] = None,- max_iterations: int = 20,+ max_iterations: int = 100,damping_factor: float = 0.85,**kwargs) -> Dict[str, float]:@@ -811,7 +811,13 @@ def calculate_pagerank(graph: Graph object (NetworkX or similar)node_labels: List of node labels to includerelationship_types: List of relationship types to consider- max_iterations: Maximum number of iterations for convergence+ max_iterations: Maximum power-iteration steps. 20 is enough for small+ undirected graphs, but a directed graph with sink nodes needs far+ more before the per-node values settle (at tolerance=1e-6 a+ 10-node directed chain needs ~33 steps and a 10-leaf directed star+ ~85). The default of 100 lets those graphs converge without the+ caller raising the cap. The scores always sum to 1 whether or not+ convergence was reached.damping_factor: Probability of continuing random walk**kwargs: Additional parameters for PageRank calculationdiff --git a/tests/kg/test_centrality_pagerank_mass.py b/tests/kg/test_centrality_pagerank_mass.pynew file mode 100644index 00000000..c8cec879--- /dev/null+++ b/tests/kg/test_centrality_pagerank_mass.py@@ -0,0 +1,96 @@+"""PageRank is a probability distribution: the scores must sum to 1.++Regression tests for #1759. Part of the mass used to be dropped whenever a+column of the transition matrix was left empty, which happens when a node+filter removes every outgoing neighbour of a node, or when a node simply has+no outgoing edge inside the current node set. The scores then drift below 1+and are no longer comparable across runs.+"""++import networkx as nx+import pytest++from semantica.kg import CentralityCalculator+++def calculator():+ return CentralityCalculator()+++def _scores(result):+ return result["centrality"]+++def test_pagerank_sums_to_one_on_a_directed_graph(calculator):+ """A node with no outgoing edge must not swallow its share of the mass."""+ graph = nx.DiGraph([("alice", "acme"), ("bob", "acme"), ("alice", "bob")])++ scores = _scores(calculator.calculate_pagerank(graph))++ assert sum(scores.values()) == pytest.approx(1.0)+ assert scores == pytest.approx(nx.pagerank(graph))+++def test_pagerank_keeps_mass_when_node_filter_drops_a_neighbour(calculator):+ """The weight must be spread over the retained neighbours only (#1759)."""+ graph = nx.Graph()+ graph.add_node("alice", label="person")+ graph.add_node("bob", label="person")+ graph.add_node("acme", label="organization")+ graph.add_edge("alice", "bob")+ graph.add_edge("alice", "acme")++ scores = _scores(calculator.calculate_pagerank(graph, node_labels=["person"]))++ assert sum(scores.values()) == pytest.approx(1.0)+ # Dropping a node has to agree with never adding it (#1759, Expected).+ without = nx.Graph([("alice", "bob")])+ assert scores == pytest.approx(nx.pagerank(without))+++def test_pagerank_keeps_mass_when_relationship_filter_drops_edges(calculator):+ graph = nx.Graph()+ for name, label in (("alice", "person"), ("bob", "person"), ("acme", "org")):+ graph.add_node(name, label=label)+ graph.add_edge("alice", "acme", type="works_for")+ graph.add_edge("bob", "acme", type="works_for")+ graph.add_edge("alice", "bob", type="knows")++ scores = _scores(calculator.calculate_pagerank(graph, relationship_types=["knows"]))++ assert sum(scores.values()) == pytest.approx(1.0)+ # alice and bob stay symmetric and keep the only retained edge; acme is+ # dangling once the 'works_for' edges are filtered out. Fixed point for+ # the 3-node, d=0.85 walk: alice = bob = 0.4651, acme = 0.0698. Pinning the+ # values (not just the sum) is what catches a wrong-but-normalised result.+ assert scores["alice"] == pytest.approx(scores["bob"])+ assert scores["alice"] == pytest.approx(0.4651, abs=1e-3)+ assert scores["acme"] == pytest.approx(0.0698, abs=1e-3)++[email protected]("factory", [nx.Graph, nx.DiGraph])+def test_pagerank_matches_networkx(calculator, factory):+ graph = factory([("a", "b"), ("b", "c"), ("c", "a"), ("c", "d")])++ # The default cap is 100, but this graph is small and the comparison wants+ # a wide margin over the calculator's own 1e-6 convergence tolerance, so+ # spell the cap out here.+ scores = _scores(calculator.calculate_pagerank(graph, max_iterations=200))++ assert scores == pytest.approx(nx.pagerank(graph), abs=1e-5)+++def test_default_iterations_converge_on_a_directed_chain(calculator):+ """A directed graph must settle on the default cap, not just sum to 1.++ Every node but the last has a single successor, so a 10-node chain needs+ ~33 power steps at tolerance=1e-6 -- more than the old default of 20. The+ default is now 100, so the caller gets the fixed point without raising it.+ """+ graph = nx.DiGraph((str(i), str(i + 1)) for i in range(10))++ scores = _scores(calculator.calculate_pagerank(graph))++ assert sum(scores.values()) == pytest.approx(1.0)+ assert scores == pytest.approx(nx.pagerank(graph), abs=1e-5)