Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(kg): make label propagation run on a ContextGraph (#1750)

Kevin4045ac8858ec
diff --git a/semantica/kg/community_detector.py b/semantica/kg/community_detector.py
index 01fa6064..9adab85d 100644
--- a/semantica/kg/community_detector.py
+++ b/semantica/kg/community_detector.py
@@ -844,23 +844,97 @@ class CommunityDetector:
def _filter_nodes_by_labels(self, graph: Any, node_labels: Optional[List[str]]) -> List[str]:
"""Filter nodes by specified labels."""
+ nodes = self._graph_node_ids(graph)
+
if node_labels is None:
- return list(graph.nodes()) if hasattr(graph, 'nodes') else []
-
+ return nodes
+
filtered_nodes = []
- for node in graph.nodes():
- if hasattr(graph, 'nodes'):
- node_data = graph.nodes[node]
- if isinstance(node_data, dict):
- node_label = node_data.get('label') or node_data.get('type')
- if node_label in node_labels:
- filtered_nodes.append(node)
- else:
- # Fallback - include all nodes if no label information
- filtered_nodes.append(node)
-
+ for node in nodes:
+ node_label = self._node_label(graph, node)
+ if node_label in node_labels:
+ filtered_nodes.append(node)
+
return filtered_nodes
-
+
+ @staticmethod
+ def _graph_node_ids(graph: Any) -> List[str]:
+ """Return node ids for any supported graph.
+
+ NetworkX exposes ``nodes`` as a callable view, while
+ :class:`~semantica.context.context_graph.ContextGraph` exposes it as a
+ mapping keyed by node id.
+ """
+ nodes = getattr(graph, "nodes", None)
+ if nodes is None:
+ return []
+ if callable(nodes):
+ return list(nodes())
+ return list(nodes)
+
+ @staticmethod
+ def _node_label(graph: Any, node: str) -> Optional[str]:
+ """Read a node's label from either a mapping or an object.
+
+ NetworkX stores node attributes in a dict, while ``ContextGraph``
+ stores a :class:`~semantica.context.context_graph.ContextNode` dataclass
+ whose label is ``node_type``.
+ """
+ node_data = graph.nodes[node]
+ if isinstance(node_data, dict):
+ return node_data.get("label") or node_data.get("type")
+ for attribute in ("node_type", "label", "type"):
+ label = getattr(node_data, attribute, None)
+ if label:
+ return label
+ return None
+
+ @staticmethod
+ def _edge_types_between(graph: Any, source: str, target: str) -> set:
+ """Collect the relationship types of every edge between two nodes.
+
+ ``ContextGraph`` keeps parallel edges and its ``get_edge_data()``
+ returns only the first one, so the edge list is the only view that
+ shows them all. NetworkX returns plain attributes for a simple graph
+ and a key-to-attributes mapping for a multigraph.
+ """
+ edges = getattr(graph, "edges", None)
+ if isinstance(edges, (list, tuple)) and any(
+ hasattr(edge, "source_id") for edge in edges
+ ):
+ types = set()
+ for edge in edges:
+ src = getattr(edge, "source_id", None)
+ dst = getattr(edge, "target_id", None)
+ if (src == source and dst == target) or (
+ src == target and dst == source
+ ):
+ edge_type = getattr(edge, "edge_type", None)
+ if edge_type:
+ types.add(edge_type)
+ return types
+
+ if hasattr(graph, "get_edge_data"):
+ data = graph.get_edge_data(source, target)
+ if not isinstance(data, dict) or not data:
+ return set()
+ is_multigraph = getattr(graph, "is_multigraph", None)
+ if callable(is_multigraph) and is_multigraph():
+ candidates = data.values()
+ else:
+ candidates = [data]
+ types = set()
+ for attributes in candidates:
+ if isinstance(attributes, dict):
+ edge_type = attributes.get("type") or attributes.get(
+ "relationship"
+ )
+ if edge_type:
+ types.add(edge_type)
+ return types
+
+ return set()
+
def _build_filtered_adjacency(
self,
graph: Any,
@@ -888,13 +962,11 @@ class CommunityDetector:
# Filter by relationship types if specified
if relationship_types is not None and hasattr(graph, 'get_edge_data'):
+ wanted = set(relationship_types)
for neighbor in all_neighbors:
if neighbor in nodes: # Only include filtered nodes
- edge_data = graph.get_edge_data(node, neighbor)
- if edge_data and isinstance(edge_data, dict):
- edge_type = edge_data.get('type') or edge_data.get('relationship')
- if edge_type in relationship_types:
- neighbors.append(neighbor)
+ if self._edge_types_between(graph, node, neighbor) & wanted:
+ neighbors.append(neighbor)
else:
# Include all neighbors that are in the filtered node set
neighbors = [neighbor for neighbor in all_neighbors if neighbor in nodes]
diff --git a/tests/kg/test_community_detector_label_propagation.py b/tests/kg/test_community_detector_label_propagation.py
new file mode 100644
index 00000000..ced1a82f
--- /dev/null
+++ b/tests/kg/test_community_detector_label_propagation.py
@@ -0,0 +1,108 @@
+"""Regression tests for CommunityDetector.detect_communities_label_propagation.
+
+Every call used to raise ``RuntimeError: Community detection failed: 'dict'
+object is not callable`` on a ContextGraph, because ``_filter_nodes_by_labels``
+took the graph's ``nodes`` mapping for a callable. Fixing that alone was not
+enough: the ``node_labels`` filter still returned every node, because a
+ContextGraph stores a ``ContextNode`` dataclass in ``nodes`` while the filter
+only understood plain dicts.
+"""
+
+import networkx as nx
+
+from semantica.context.context_graph import ContextGraph
+from semantica.kg.community_detector import CommunityDetector
+
+
+def _context_graph():
+ graph = ContextGraph()
+ graph.add_node("alice", "person", "Alice")
+ graph.add_node("bob", "org", "Bob")
+ graph.add_node("carol", "person", "Carol")
+ graph.add_edge("alice", "bob", "knows")
+ graph.add_edge("bob", "carol", "knows")
+ return graph
+
+
+def test_runs_on_a_context_graph():
+ result = CommunityDetector().detect_communities_label_propagation(_context_graph())
+
+ assert set(result) == {"communities", "node_assignments", "algorithm", "iterations"}
+ assert set(result["node_assignments"]) == {"alice", "bob", "carol"}
+ assert result["algorithm"] == "label_propagation"
+
+
+def test_filters_by_node_labels_on_a_context_graph():
+ detector = CommunityDetector()
+
+ people = detector.detect_communities_label_propagation(
+ _context_graph(), node_labels=["person"]
+ )
+ orgs = detector.detect_communities_label_propagation(
+ _context_graph(), node_labels=["org"]
+ )
+
+ assert set(people["node_assignments"]) == {"alice", "carol"}
+ assert set(orgs["node_assignments"]) == {"bob"}
+
+
+def test_keeps_networkx_node_labels_behaviour():
+ graph = nx.Graph()
+ graph.add_node("a", label="person")
+ graph.add_node("b", label="org")
+ graph.add_edge("a", "b")
+
+ detector = CommunityDetector()
+
+ assert set(
+ detector.detect_communities_label_propagation(graph)["node_assignments"]
+ ) == {"a", "b"}
+ filtered = detector.detect_communities_label_propagation(graph, node_labels=["org"])
+ assert set(filtered["node_assignments"]) == {"b"}
+
+
+def test_runs_on_a_context_graph_with_relationship_types():
+ result = CommunityDetector().detect_communities_label_propagation(
+ _context_graph(), relationship_types=["knows"]
+ )
+
+ assert set(result["node_assignments"]) == {"alice", "bob", "carol"}
+
+
+def test_relationship_filter_sees_parallel_edges_on_a_context_graph():
+ graph = ContextGraph()
+ graph.add_node("alice", "person", "Alice")
+ graph.add_node("bob", "person", "Bob")
+ graph.add_node("carol", "person", "Carol")
+ # alice - bob carries two edges. The first one does not match the filter,
+ # so a lookup that reads only the first stored edge drops the pair and
+ # leaves alice isolated.
+ graph.add_edge("alice", "bob", "knows")
+ graph.add_edge("alice", "bob", "mentors")
+ graph.add_edge("carol", "bob", "knows")
+
+ result = CommunityDetector().detect_communities_label_propagation(
+ graph, relationship_types=["mentors"]
+ )
+
+ assignments = result["node_assignments"]
+ assert assignments["alice"] == assignments["bob"]
+ assert assignments["carol"] != assignments["bob"]
+
+
+def test_relationship_filter_sees_parallel_edges_on_a_multigraph():
+ graph = nx.MultiGraph()
+ graph.add_node("a", label="person")
+ graph.add_node("b", label="person")
+ graph.add_node("c", label="person")
+ graph.add_edge("a", "b", type="knows")
+ graph.add_edge("a", "b", type="mentors")
+ graph.add_edge("c", "b", type="knows")
+
+ result = CommunityDetector().detect_communities_label_propagation(
+ graph, relationship_types=["mentors"]
+ )
+
+ assignments = result["node_assignments"]
+ assert assignments["a"] == assignments["b"]
+ assert assignments["c"] != assignments["b"]