Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(kg): route label_propagation through the community dispatcher (#1755)

Kevin8e66e7c650ee
diff --git a/semantica/kg/_graph_view.py b/semantica/kg/_graph_view.py
index 675285b0..9c0c99e4 100644
--- a/semantica/kg/_graph_view.py
+++ b/semantica/kg/_graph_view.py
@@ -183,23 +183,77 @@ def _edge_type_of(edge: Any) -> Any:
)
-def _dict_edge_types(
- graph: Dict[str, Any], source: Any, target: Any, directed: bool
-) -> Set[Any]:
- """Collect the types of every declared edge between two nodes."""
- types: Set[Any] = set()
- for edge in _extract_edges(graph):
+@dataclass
+class EdgeTypeIndex:
+ """The declared edge types of a plain graph dictionary, read once.
+
+ ``typed`` records whether any edge record declares a type at all;
+ ``by_pair`` maps each ``(source, target)`` to the types declared from
+ ``source`` to ``target``; ``untyped`` holds every ``(source, target)``
+ joined by at least one edge that declares no type.
+ """
+
+ typed: bool
+ by_pair: Dict[Tuple[Any, Any], Set[Any]]
+ untyped: Set[Tuple[Any, Any]]
+
+
+def build_edge_type_index(graph: Dict[str, Any]) -> EdgeTypeIndex:
+ """Read a graph dictionary's edge records once for repeated type lookups.
+
+ A caller that classifies many links passes the result to
+ :func:`edge_types_between`, so the edge list is scanned once per graph
+ instead of once per link.
+ """
+ edges = _extract_edges(graph)
+ by_pair: Dict[Tuple[Any, Any], Set[Any]] = {}
+ untyped: Set[Tuple[Any, Any]] = set()
+ typed = False
+ for edge in edges:
+ edge_type = _edge_type_of(edge)
+ if edge_type:
+ typed = True
endpoints = _edge_endpoints(edge)
if endpoints is None:
continue
- src, dst = endpoints
- forwards = src == source and dst == target
- backwards = src == target and dst == source
- if not (forwards or (backwards and not directed)):
+ try:
+ if edge_type:
+ by_pair.setdefault(endpoints, set()).add(edge_type)
+ else:
+ untyped.add(endpoints)
+ except TypeError:
+ # An unhashable endpoint never equals a node id, which is always
+ # hashable, so it could not have matched a lookup anyway.
continue
- edge_type = _edge_type_of(edge)
- if edge_type:
- types.add(edge_type)
+ return EdgeTypeIndex(typed=typed, by_pair=by_pair, untyped=untyped)
+
+
+def _dict_edge_types(
+ graph: Dict[str, Any],
+ source: Any,
+ target: Any,
+ directed: bool,
+ index: Optional[EdgeTypeIndex] = None,
+) -> Optional[Set[Any]]:
+ """Collect the types of every declared edge between two nodes.
+
+ Returns ``None`` when an edge joining the pair declares no type, matching
+ :func:`edge_types_between`: a caller filtering on relationship types has
+ nothing to classify that link with and keeps it. The decision is made per
+ edge, so typed records elsewhere in the graph do not change it.
+ """
+ if index is None:
+ index = build_edge_type_index(graph)
+ if not index.typed:
+ return None
+ if (source, target) in index.untyped or (
+ not directed and (target, source) in index.untyped
+ ):
+ return None
+
+ types: Set[Any] = set(index.by_pair.get((source, target), ()))
+ if not directed:
+ types |= index.by_pair.get((target, source), set())
return types
@@ -291,15 +345,24 @@ def graph_node_label(graph: Any, node: Any) -> Optional[str]:
def edge_types_between(
- graph: Any, source: Any, target: Any, directed: bool = False
+ graph: Any,
+ source: Any,
+ target: Any,
+ directed: bool = False,
+ edge_types: Optional[EdgeTypeIndex] = None,
) -> Optional[Set[Any]]:
"""Collect the relationship types of every edge between two nodes.
Returns ``None`` when the graph exposes no edge types at all, because a
- caller cannot classify a link it has no metadata for. An empty set means the
- two nodes are joined by edges that declare no type. Callers keep the
- neighbour on ``None`` and apply the filter to a set. A plain graph
- dictionary is read through its ``relationships``/``edges`` entries.
+ caller cannot classify a link it has no metadata for. Callers keep the
+ neighbour on ``None`` and apply the filter to a set.
+
+ A plain graph dictionary is read through its ``relationships``/``edges``
+ entries and decides per edge: when an edge joining the pair declares no
+ type the result is ``None``, so that link is kept, while a pair joined only
+ by typed edges gets the set of their types. A ``ContextGraph`` or NetworkX
+ graph still answers for the pair as a whole: an empty set means the two
+ nodes are joined by edges that declare no type, and the filter drops them.
``directed`` narrows the edge-list lookup to edges that leave ``source`` and
enter ``target``. The default reads the pair as undirected, which is what a
@@ -312,9 +375,13 @@ def edge_types_between(
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.
+
+ ``edge_types`` is an optional :func:`build_edge_type_index` result for a
+ plain graph dictionary. A caller classifying many links builds it once, so
+ the lookup does not rescan the edge list for every pair.
"""
if isinstance(graph, dict):
- return _dict_edge_types(graph, source, target, directed)
+ return _dict_edge_types(graph, source, target, directed, edge_types)
edges = getattr(graph, "edges", None)
if isinstance(edges, (list, tuple)) and any(
diff --git a/semantica/kg/centrality_calculator.py b/semantica/kg/centrality_calculator.py
index 387195ca..37e691a0 100644
--- a/semantica/kg/centrality_calculator.py
+++ b/semantica/kg/centrality_calculator.py
@@ -52,7 +52,9 @@ from scipy import sparse
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from ._graph_view import (
+ EdgeTypeIndex,
build_adjacency,
+ build_edge_type_index,
build_graph_view,
edge_types_between,
graph_node_ids,
@@ -662,11 +664,22 @@ class CentralityCalculator:
if isinstance(graph, dict)
else None
)
+ # Its edge types are read once too, so the relationship filter
+ # costs O(E) rather than one edge-list scan per neighbour.
+ edge_types = (
+ build_edge_type_index(graph)
+ if relationship_types is not None and isinstance(graph, dict)
+ else None
+ )
for node in nodes:
source_idx = node_index[node]
neighbors = self._get_filtered_neighbors(
- graph, node, relationship_types, adjacency=adjacency
+ graph,
+ node,
+ relationship_types,
+ adjacency=adjacency,
+ edge_types=edge_types,
)
# Distribute PageRank equally among the neighbours that survive
@@ -750,11 +763,14 @@ class CentralityCalculator:
node: str,
relationship_types: Optional[List[str]],
adjacency: Optional[Dict[str, List[str]]] = None,
+ edge_types: Optional[EdgeTypeIndex] = None,
) -> List[str]:
"""Get neighbors filtered by relationship types.
``adjacency`` is an optional prebuilt outgoing adjacency for a plain
graph dictionary, so a caller looping over nodes builds it once.
+ ``edge_types`` is the matching prebuilt edge-type index, for the same
+ reason.
"""
if isinstance(graph, dict):
# A plain graph dictionary has no neighbour walk of its own, so the
@@ -788,7 +804,9 @@ class CentralityCalculator:
wanted = set(relationship_types)
filtered_neighbors = []
for neighbor in neighbors:
- types = edge_types_between(graph, node, neighbor, directed=True)
+ types = edge_types_between(
+ graph, node, neighbor, directed=True, edge_types=edge_types
+ )
if types is None or types & wanted:
filtered_neighbors.append(neighbor)
return filtered_neighbors
diff --git a/semantica/kg/community_detector.py b/semantica/kg/community_detector.py
index 92707e41..7d7fa153 100644
--- a/semantica/kg/community_detector.py
+++ b/semantica/kg/community_detector.py
@@ -51,6 +51,7 @@ from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
from ._graph_view import (
build_adjacency,
+ build_edge_type_index,
build_graph_view,
edge_types_between,
graph_node_ids,
@@ -475,8 +476,11 @@ class CommunityDetector:
Args:
graph: Input graph for community detection
- algorithm: Community detection algorithm to use
- (supported: "louvain", "leiden", "overlapping")
+ algorithm: Community detection algorithm to use. Supported values
+ are "louvain", "leiden", "overlapping" and
+ "label_propagation".
+ method: Alias for ``algorithm``. A value that is not supported is
+ ignored, which leaves ``algorithm`` in effect.
**options: Additional detection options (passed to algorithm-specific method)
Returns:
@@ -484,22 +488,39 @@ class CommunityDetector:
Raises:
ValueError: If algorithm is not supported
+ TypeError: If algorithm is not a string, or method is neither a
+ string nor None
"""
+ handlers = {
+ "louvain": self.detect_communities_louvain,
+ "leiden": self.detect_communities_leiden,
+ "overlapping": self.detect_overlapping_communities,
+ "label_propagation": self.detect_communities_label_propagation,
+ }
+
+ # The names are looked up in a dict, so a non-string would either be
+ # ignored or fail as "unhashable type"; name the real problem instead.
+ if method is not None and not isinstance(method, str):
+ raise TypeError(
+ f"method must be a string or None, got {type(method).__name__}"
+ )
+ if not isinstance(algorithm, str):
+ raise TypeError(
+ f"algorithm must be a string, got {type(algorithm).__name__}"
+ )
+
# 'method' is an alias for 'algorithm'
if method is not None:
- algorithm = method if method in ("louvain", "leiden", "overlapping") else "louvain"
+ algorithm = method if method in handlers else algorithm
self.logger.info(f"Detecting communities using {algorithm} algorithm")
- if algorithm == "louvain":
- return self.detect_communities_louvain(graph, **options)
- elif algorithm == "leiden":
- return self.detect_communities_leiden(graph, **options)
- elif algorithm == "overlapping":
- return self.detect_overlapping_communities(graph, **options)
- else:
+ handler = handlers.get(algorithm)
+ if handler is None:
raise ValueError(f"Unsupported algorithm: {algorithm}")
+ return handler(graph, **options)
+
def _build_adjacency(self, graph) -> Dict[str, List[str]]:
"""Build adjacency list from graph."""
return build_adjacency(graph)
@@ -641,7 +662,8 @@ class CommunityDetector:
relationship_types: Optional[List[str]] = None,
max_iterations: int = 100,
random_seed: Optional[int] = None,
- chunk_size: int = 1000
+ chunk_size: int = 1000,
+ **options
) -> Dict[str, Any]:
"""
Detect communities using Label Propagation algorithm.
@@ -657,7 +679,9 @@ class CommunityDetector:
max_iterations: Maximum number of iterations for convergence
random_seed: Random seed for reproducible results
chunk_size: Process nodes in chunks for memory efficiency
-
+ **options: Options meant for another algorithm, such as Louvain's
+ resolution or max_iter. They are ignored, with a warning.
+
Returns:
Dictionary containing:
- communities: List of communities (each as list of node IDs)
@@ -671,7 +695,15 @@ class CommunityDetector:
"""
try:
self.logger.info("Detecting communities using Label Propagation algorithm")
-
+
+ # The other algorithms accept options they do not use, so the
+ # dispatcher forwards one shared set; say which ones are ignored.
+ if options:
+ self.logger.warning(
+ "Label Propagation ignores unsupported options: "
+ + ", ".join(sorted(options))
+ )
+
# Set random seed if provided
if random_seed is not None:
import random
@@ -779,12 +811,11 @@ class CommunityDetector:
# Initialize labels for all nodes
labels = {node: i for i, node in enumerate(nodes)}
- # Build adjacency in chunks
- adjacency = {}
- for i in range(0, len(nodes), chunk_size):
- chunk_nodes = nodes[i:i + chunk_size]
- chunk_adjacency = self._build_filtered_adjacency(graph, chunk_nodes, relationship_types)
- adjacency.update(chunk_adjacency)
+ # Build the adjacency once, against the full node set, so an edge that
+ # crosses two chunks still counts. The chunks below only split the
+ # label updates; building it per chunk rebuilt the whole graph's
+ # adjacency every time and merged the same rows.
+ adjacency = self._build_filtered_adjacency(graph, nodes, relationship_types)
# Run label propagation with memory-efficient updates
for iteration in range(max_iterations):
@@ -841,7 +872,7 @@ class CommunityDetector:
result = {
"communities": communities,
"node_assignments": node_assignments,
- "algorithm": "label_propagation_chunked",
+ "algorithm": "label_propagation",
"iterations": iteration + 1 if 'iteration' in locals() else max_iterations
}
@@ -866,20 +897,43 @@ class CommunityDetector:
self,
graph: Any,
nodes: List[str],
- relationship_types: Optional[List[str]]
+ relationship_types: Optional[List[str]],
+ iterate: Optional[List[str]] = None
) -> Dict[str, List[str]]:
- """Build adjacency list filtered by nodes and relationship types."""
+ """Build adjacency list filtered by nodes and relationship types.
+
+ ``nodes`` is the set a neighbour has to belong to. ``iterate`` limits
+ which rows are built, so a caller can cover the graph in pieces without
+ losing the edges that run between the pieces.
+ """
adjacency = {}
-
- for node in nodes:
+ member = set(nodes)
+ rows = nodes if iterate is None else iterate
+
+ # A graph dictionary has no neighbour accessor, so build the whole
+ # map once, the way Louvain does through build_adjacency().
+ base_adjacency = (
+ {}
+ if hasattr(graph, "neighbors") or hasattr(graph, "get_neighbors")
+ else build_adjacency(graph)
+ )
+ # Its edge types are read once too, so the filter below costs O(E)
+ # rather than one edge-list scan per neighbour.
+ edge_types = (
+ build_edge_type_index(graph)
+ if relationship_types is not None and isinstance(graph, dict)
+ else None
+ )
+
+ for node in rows:
neighbors = []
-
+
if hasattr(graph, 'neighbors'):
all_neighbors = list(graph.neighbors(node))
elif hasattr(graph, 'get_neighbors'):
all_neighbors = graph.get_neighbors(node)
else:
- all_neighbors = []
+ all_neighbors = list(base_adjacency.get(node, []))
if all_neighbors and isinstance(all_neighbors[0], dict):
all_neighbors = [
@@ -887,19 +941,28 @@ class CommunityDetector:
if isinstance(n, dict) and n.get("id")
]
- # Filter by relationship types if specified. A graph whose edge
- # types cannot be read keeps its neighbours, so the filter never
- # turns an unclassifiable link into a silent removal.
- if relationship_types is not None and hasattr(graph, 'get_edge_data'):
+ # Filter by relationship types if specified. A graph dictionary has
+ # no get_edge_data, so the shared graph view answers from the edge
+ # records it declares; a graph whose edge types cannot be read keeps
+ # its neighbours, so the filter never turns an unclassifiable link
+ # into a silent removal.
+ if relationship_types is not None and (
+ hasattr(graph, 'get_edge_data') or isinstance(graph, dict)
+ ):
wanted = set(relationship_types)
for neighbor in all_neighbors:
- if neighbor in nodes: # Only include filtered nodes
- types = edge_types_between(graph, node, neighbor)
- if types is None or types & wanted:
- neighbors.append(neighbor)
+ if neighbor not in member: # Only include filtered nodes
+ continue
+ types = edge_types_between(
+ graph, node, neighbor, edge_types=edge_types
+ )
+ if types is None or types & 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]
+ neighbors = [
+ neighbor for neighbor in all_neighbors if neighbor in member
+ ]
adjacency[node] = neighbors
diff --git a/tests/kg/test_centrality_pagerank_adjacency_reuse.py b/tests/kg/test_centrality_pagerank_adjacency_reuse.py
index 5237912b..eab213cd 100644
--- a/tests/kg/test_centrality_pagerank_adjacency_reuse.py
+++ b/tests/kg/test_centrality_pagerank_adjacency_reuse.py
@@ -4,7 +4,7 @@
every node, so neighbour resolution cost O(N * (N + E)) instead of O(N + E).
"""
-from semantica.kg import CentralityCalculator, centrality_calculator
+from semantica.kg import CentralityCalculator, _graph_view, centrality_calculator
def _graph_dict(n=30):
@@ -32,6 +32,30 @@ def test_pagerank_builds_the_adjacency_once_for_a_graph_dict(monkeypatch):
assert len(calls) == 1
+def test_pagerank_reads_a_graph_dicts_edge_types_once(monkeypatch):
+ # The relationship filter used to rescan every edge record for every
+ # neighbour it classified, which made filtering O(E^2). The number of
+ # scans must not grow with the graph.
+ calls = []
+ real = _graph_view._extract_edges
+
+ def counting(graph):
+ calls.append(graph)
+ return real(graph)
+
+ monkeypatch.setattr(_graph_view, "_extract_edges", counting)
+
+ scans = []
+ for n in (10, 40):
+ calls.clear()
+ CentralityCalculator().calculate_pagerank(
+ _graph_dict(n), relationship_types=["next"]
+ )
+ scans.append(len(calls))
+
+ assert scans[0] == scans[1]
+
+
def test_pagerank_scores_are_unchanged_by_adjacency_reuse():
graph = _graph_dict(5)
graph["relationships"].append({"source": "n0", "target": "n2", "type": "skip"})
diff --git a/tests/kg/test_centrality_pagerank_node_labels.py b/tests/kg/test_centrality_pagerank_node_labels.py
index 9b668dad..823c1400 100644
--- a/tests/kg/test_centrality_pagerank_node_labels.py
+++ b/tests/kg/test_centrality_pagerank_node_labels.py
@@ -252,3 +252,50 @@ def test_relationship_types_filter_a_plain_graph_dict():
scores = ranked["centrality"]
assert scores["bob"] > scores["alice"]
assert scores["bob"] > scores["acme"]
+
+
+def test_relationship_types_keep_the_edges_of_an_untyped_graph_dict():
+ """A dictionary whose edges declare no type cannot answer the filter.
+
+ Its links are kept rather than all dropped, so the ranking matches the
+ unfiltered one instead of collapsing to a uniform score.
+ """
+ graph = {
+ "nodes": ["alice", "bob", "acme"],
+ "edges": [("alice", "bob"), ("bob", "acme")],
+ }
+ calculator = CentralityCalculator()
+
+ filtered = calculator.calculate_pagerank(graph, relationship_types=["knows"])
+ plain = calculator.calculate_pagerank(graph)
+
+ assert filtered["centrality"] == pytest.approx(plain["centrality"])
+ assert filtered["centrality"]["acme"] > filtered["centrality"]["alice"]
+
+
+def test_relationship_types_keep_an_untyped_edge_beside_typed_ones():
+ """Classifiability is decided per edge, not for the whole dictionary.
+
+ ``bob -> acme`` declares no type, so it is kept beside the typed
+ ``alice -> bob``; the ranking matches the graph where both edges match.
+ """
+ mixed = {
+ "nodes": ["alice", "bob", "acme"],
+ "edges": [
+ {"source": "alice", "target": "bob", "type": "knows"},
+ {"source": "bob", "target": "acme"},
+ ],
+ }
+ matching = {
+ "nodes": ["alice", "bob", "acme"],
+ "edges": [
+ {"source": "alice", "target": "bob", "type": "knows"},
+ {"source": "bob", "target": "acme", "type": "knows"},
+ ],
+ }
+ calculator = CentralityCalculator()
+
+ ranked = calculator.calculate_pagerank(mixed, relationship_types=["knows"])
+ expected = calculator.calculate_pagerank(matching, relationship_types=["knows"])
+
+ assert ranked["centrality"] == pytest.approx(expected["centrality"])
diff --git a/tests/kg/test_community_detector_dispatch.py b/tests/kg/test_community_detector_dispatch.py
new file mode 100644
index 00000000..b0551cb3
--- /dev/null
+++ b/tests/kg/test_community_detector_dispatch.py
@@ -0,0 +1,487 @@
+"""Regression tests for the CommunityDetector.detect_communities dispatcher.
+
+``label_propagation`` is implemented and reachable through
+``detect_communities_label_propagation()``, but the dispatcher never listed it.
+``algorithm="label_propagation"`` raised ``ValueError: Unsupported algorithm``,
+and ``method="label_propagation"`` matched none of the dispatched names and fell
+through to ``"louvain"``, so callers silently got Louvain results back.
+
+Routing it exposed a second problem. Existing callers pass a graph dictionary
+(``{"nodes": [...], "edges": [...]}``) and used to land on Louvain, which
+normalizes that shape through ``build_adjacency()``. Label propagation resolved
+node ids straight off ``graph.nodes``, found none, and the dispatched calls came
+back with ``No nodes found matching the specified criteria``.
+"""
+
+import logging
+
+import networkx as nx
+import pytest
+
+from semantica.context.context_graph import ContextGraph
+from semantica.kg import _graph_view, community_detector
+from semantica.kg.community_detector import CommunityDetector
+
+
+def _context_graph():
+ graph = ContextGraph()
+ for node in ("a", "b", "c", "d", "e", "f"):
+ graph.add_node(node, "person", node)
+ for source, target in (
+ ("a", "b"),
+ ("b", "c"),
+ ("c", "a"),
+ ("d", "e"),
+ ("e", "f"),
+ ("f", "d"),
+ ("c", "d"),
+ ):
+ graph.add_edge(source, target, "knows")
+ return graph
+
+
+def _graph_dict():
+ return {
+ "nodes": ["a", "b", "c", "d", "e", "f"],
+ "edges": [
+ ("a", "b"),
+ ("b", "c"),
+ ("c", "a"),
+ ("d", "e"),
+ ("e", "f"),
+ ("f", "d"),
+ ("c", "d"),
+ ],
+ }
+
+
+def _spy_on_label_propagation(monkeypatch):
+ """Return a detector whose label propagation method records its calls."""
+ detector = CommunityDetector()
+ calls = []
+ original = detector.detect_communities_label_propagation
+
+ def spy(graph, **options):
+ calls.append(options)
+ return original(graph, **options)
+
+ monkeypatch.setattr(detector, "detect_communities_label_propagation", spy)
+ return detector, calls
+
+
+def test_algorithm_name_reaches_label_propagation(monkeypatch):
+ detector, calls = _spy_on_label_propagation(monkeypatch)
+
+ result = detector.detect_communities(
+ _context_graph(), algorithm="label_propagation"
+ )
+
+ assert calls, "the dispatcher did not call detect_communities_label_propagation"
+ assert result["algorithm"] == "label_propagation"
+
+
+def test_method_alias_reaches_label_propagation(monkeypatch):
+ detector, calls = _spy_on_label_propagation(monkeypatch)
+
+ result = detector.detect_communities(_context_graph(), method="label_propagation")
+
+ assert calls, "the method alias fell back to another algorithm"
+ # The default algorithm="louvain" must not shadow the requested method.
+ assert result["algorithm"] == "label_propagation"
+ assert "modularity" not in result
+
+
+def test_result_is_not_louvain_output():
+ result = CommunityDetector().detect_communities(
+ _context_graph(), algorithm="label_propagation"
+ )
+
+ # Louvain reports modularity and has no iteration count.
+ assert set(result) == {"communities", "node_assignments", "algorithm", "iterations"}
+ assert "iterations" in result
+
+
+def test_graph_dict_reaches_label_propagation():
+ result = CommunityDetector().detect_communities(
+ _graph_dict(), method="label_propagation", random_seed=7
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(result["node_assignments"]) == ["a", "b", "c", "d", "e", "f"]
+
+
+def test_label_propagation_runs_on_a_context_graph():
+ result = CommunityDetector().detect_communities(
+ _context_graph(), method="label_propagation", random_seed=7
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(result["node_assignments"]) == ["a", "b", "c", "d", "e", "f"]
+
+
+def test_other_algorithms_keep_their_dispatch():
+ for name in ("louvain", "leiden", "overlapping"):
+ result = CommunityDetector().detect_communities(_graph_dict(), method=name)
+
+ assert result["algorithm"] == name
+
+
+def test_unknown_algorithm_still_raises():
+ with pytest.raises(ValueError, match="Unsupported algorithm: nope"):
+ CommunityDetector().detect_communities(_graph_dict(), algorithm="nope")
+
+
[email protected]("method", [["louvain"], {"k": 1}, 0, False, b"louvain"])
+def test_non_string_method_is_rejected(method):
+ # A non-string alias used to be ignored, or to raise "unhashable type"
+ # from the handler lookup. It now gets one clear error naming its type.
+ with pytest.raises(TypeError, match="method must be a string or None, got"):
+ CommunityDetector().detect_communities(_graph_dict(), method=method)
+
+
[email protected]("algorithm", [["louvain"], None, 0])
+def test_non_string_algorithm_is_rejected(algorithm):
+ with pytest.raises(TypeError, match="algorithm must be a string, got"):
+ CommunityDetector().detect_communities(_graph_dict(), algorithm=algorithm)
+
+
+def test_label_propagation_ignores_louvain_options_with_a_warning(caplog):
+ # Louvain, Leiden and overlapping accept options they do not use. Label
+ # propagation now does the same instead of raising "unexpected keyword
+ # argument", but says which options it ignored.
+ with caplog.at_level(logging.WARNING, logger="semantica.community_detector"):
+ result = CommunityDetector().detect_communities(
+ _graph_dict(),
+ method="label_propagation",
+ resolution=1.0,
+ max_iter=5,
+ random_seed=7,
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(sorted(c) for c in result["communities"]) == [
+ ["a", "b", "c"],
+ ["d", "e", "f"],
+ ]
+ assert any(
+ "ignores unsupported options: max_iter, resolution" in record.message
+ for record in caplog.records
+ )
+
+
+def test_label_propagation_options_raise_no_warning(caplog):
+ with caplog.at_level(logging.WARNING, logger="semantica.community_detector"):
+ CommunityDetector().detect_communities(
+ _graph_dict(),
+ method="label_propagation",
+ max_iterations=50,
+ random_seed=7,
+ )
+
+ assert not any(
+ "ignores unsupported options" in record.message for record in caplog.records
+ )
+
+
+def test_unknown_method_keeps_the_algorithm_argument():
+ # An unrecognised alias is ignored instead of being rewritten to Louvain.
+ result = CommunityDetector().detect_communities(
+ _graph_dict(), algorithm="leiden", method="nope"
+ )
+
+ assert result["algorithm"] == "leiden"
+
+
+def test_graph_dict_keeps_both_cliques_under_a_relationship_filter():
+ # A graph dictionary carries no edge types, and Louvain ignores the filter
+ # for that shape. Label propagation has to do the same instead of dropping
+ # every edge and returning one singleton per node.
+ result = CommunityDetector().detect_communities(
+ _graph_dict(),
+ method="label_propagation",
+ relationship_types=["knows"],
+ random_seed=7,
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(sorted(c) for c in result["communities"]) == [
+ ["a", "b", "c"],
+ ["d", "e", "f"],
+ ]
+
+
+def test_graph_dict_works_without_networkx():
+ # The graph-dictionary path goes through build_graph_view/build_adjacency
+ # rather than a NetworkX rebuild, so it must not need networkx.
+ detector = CommunityDetector()
+ detector.nx = None
+ detector.use_networkx = False
+
+ result = detector.detect_communities(
+ _graph_dict(), method="label_propagation", random_seed=7
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(sorted(c) for c in result["communities"]) == [
+ ["a", "b", "c"],
+ ["d", "e", "f"],
+ ]
+
+
+def test_graph_dict_honours_the_filter_when_its_edges_declare_types():
+ # A dictionary edge record may carry its own type. Those records can answer
+ # the filter, so the excluded "works_at" edge must not hold the two pairs
+ # together.
+ graph = {
+ "nodes": ["a", "b", "c", "d"],
+ "edges": [
+ {"source": "a", "target": "b", "type": "knows"},
+ {"source": "c", "target": "d", "type": "knows"},
+ {"source": "b", "target": "c", "type": "works_at"},
+ ],
+ }
+
+ result = CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ relationship_types=["knows"],
+ random_seed=7,
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(sorted(c) for c in result["communities"]) == [
+ ["a", "b"],
+ ["c", "d"],
+ ]
+
+
+def test_graph_dict_keeps_an_untyped_edge_beside_typed_ones():
+ # Whether an edge is classifiable is decided per edge. One typed record
+ # must not turn every untyped edge in the same graph into a dropped link.
+ graph = {
+ "nodes": ["a", "b", "c", "d", "e"],
+ "edges": [
+ {"source": "a", "target": "b", "type": "knows"},
+ {"source": "b", "target": "c", "type": "works_at"},
+ {"source": "c", "target": "d"},
+ {"source": "d", "target": "e"},
+ {"source": "e", "target": "c"},
+ ],
+ }
+
+ result = CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ relationship_types=["knows"],
+ random_seed=7,
+ )
+
+ assert sorted(sorted(c) for c in result["communities"]) == [
+ ["a", "b"],
+ ["c", "d", "e"],
+ ]
+
+
+def test_graph_dict_filter_reads_the_edge_types_once(monkeypatch):
+ # The relationship filter used to rescan every edge record for every
+ # neighbour it classified, which made filtering O(E^2). The number of
+ # scans must not grow with the graph.
+ calls = []
+ real = _graph_view._extract_edges
+
+ def counting(graph):
+ calls.append(graph)
+ return real(graph)
+
+ monkeypatch.setattr(_graph_view, "_extract_edges", counting)
+
+ scans = []
+ for n in (10, 40):
+ nodes = ["n%d" % i for i in range(n)]
+ graph = {
+ "nodes": nodes,
+ "edges": [
+ {"source": a, "target": b, "type": "next"}
+ for a, b in zip(nodes, nodes[1:])
+ ],
+ }
+ calls.clear()
+ CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ relationship_types=["next"],
+ random_seed=7,
+ )
+ scans.append(len(calls))
+
+ assert scans[0] == scans[1]
+
+
+def test_graph_dict_labels_filter_the_nodes():
+ # A graph dictionary carries its node labels on the node records. The
+ # filter used to read ``graph.nodes[node]``, an attribute a dict does not
+ # have, so every filtered call on a dictionary raised
+ # "Community detection failed: 'dict' object has no attribute 'nodes'"
+ # instead of matching the requested label.
+ graph = {
+ "nodes": [
+ {"id": "a", "label": "person"},
+ {"id": "b", "label": "person"},
+ {"id": "c", "label": "company"},
+ {"id": "d", "label": "company"},
+ ],
+ "edges": [("a", "b"), ("c", "d")],
+ }
+
+ result = CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ node_labels=["person"],
+ random_seed=7,
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(result["node_assignments"]) == ["a", "b"]
+
+
+def test_graph_dict_entities_are_read_through_the_shared_node_aliases():
+ # The same records may sit under "entities" and name their node through
+ # "node_id" while typing it through "type". The label lookup has to speak
+ # the aliases build_graph_view() already accepts, not just "id"/"label".
+ graph = {
+ "entities": [
+ {"node_id": "a", "type": "person"},
+ {"node_id": "b", "type": "person"},
+ {"node_id": "c", "type": "company"},
+ ],
+ "relationships": [("a", "b"), ("a", "c")],
+ }
+
+ result = CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ node_labels=["company"],
+ random_seed=7,
+ )
+
+ assert result["algorithm"] == "label_propagation"
+ assert sorted(result["node_assignments"]) == ["c"]
+
+
+def test_graph_dict_without_labels_still_reports_no_match():
+ # Labels are read from the records the dictionary declares. When none of
+ # them can be matched, the call keeps reporting the same "no match" it
+ # always did rather than failing on the missing ``nodes`` attribute.
+ graph = {
+ "nodes": ["a", "b"],
+ "edges": [("a", "b")],
+ }
+
+ with pytest.raises(
+ RuntimeError, match="No nodes found matching the specified criteria"
+ ):
+ CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ node_labels=["person"],
+ random_seed=7,
+ )
+
+
+def test_chunked_label_propagation_reports_the_requested_algorithm():
+ # Chunking is an execution detail. A caller that asked for label
+ # propagation must get that name back, whatever the graph size.
+ nodes = ["n%d" % i for i in range(6)]
+ graph = {
+ "nodes": nodes,
+ "edges": list(zip(nodes, nodes[1:])),
+ }
+
+ result = CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ chunk_size=2,
+ random_seed=7,
+ )
+
+ assert result["algorithm"] == "label_propagation"
+
+
+def _partition(result):
+ return sorted(sorted(community) for community in result["communities"])
+
+
+def test_chunked_label_propagation_keeps_the_edges_between_chunks():
+ # Chunking is an execution detail: an edge that joins two chunks has to
+ # still make its two endpoints neighbours. A complete graph is a single
+ # community whether it is walked whole or a few nodes at a time.
+ graph = nx.complete_graph(6)
+
+ whole = CommunityDetector().detect_communities(
+ graph, method="label_propagation", random_seed=7
+ )
+ chunked = CommunityDetector().detect_communities(
+ graph, method="label_propagation", chunk_size=3, random_seed=7
+ )
+
+ # Louvain also returns one community here and ignores chunk_size, so
+ # without this the test would pass even if the call never reached label
+ # propagation.
+ assert chunked["algorithm"] == "label_propagation"
+ assert _partition(whole) == [[0, 1, 2, 3, 4, 5]]
+ assert _partition(chunked) == _partition(whole)
+
+
+def test_chunked_label_propagation_builds_the_adjacency_once(monkeypatch):
+ # The chunks only split the label updates. Rebuilding the whole graph's
+ # adjacency and edge-type index for every chunk cost O(N / chunk_size)
+ # passes over the graph and produced the same rows.
+ adjacency_calls = []
+ index_calls = []
+ real_adjacency = community_detector.build_adjacency
+ real_index = community_detector.build_edge_type_index
+
+ def counting_adjacency(graph, directed=False):
+ adjacency_calls.append(graph)
+ return real_adjacency(graph, directed=directed)
+
+ def counting_index(graph):
+ index_calls.append(graph)
+ return real_index(graph)
+
+ monkeypatch.setattr(community_detector, "build_adjacency", counting_adjacency)
+ monkeypatch.setattr(community_detector, "build_edge_type_index", counting_index)
+
+ nodes = ["n%d" % i for i in range(6)]
+ graph = {
+ "nodes": nodes,
+ "edges": [
+ {"source": a, "target": b, "type": "next"}
+ for a, b in zip(nodes, nodes[1:])
+ ],
+ }
+
+ CommunityDetector().detect_communities(
+ graph,
+ method="label_propagation",
+ relationship_types=["next"],
+ chunk_size=2,
+ random_seed=7,
+ )
+
+ assert len(adjacency_calls) == 1
+ assert len(index_calls) == 1
+
+
+def test_chunked_adjacency_keeps_a_neighbour_from_another_chunk():
+ # A chunk's rows are built against the whole node set, so a neighbour
+ # that sits in the next chunk is still returned as a neighbour.
+ graph = nx.path_graph(4)
+ detector = CommunityDetector()
+
+ chunked = detector._build_filtered_adjacency(
+ graph, [0, 1, 2, 3], None, iterate=[0, 1]
+ )
+
+ assert sorted(chunked[0]) == [1]
+ assert sorted(chunked[1]) == [0, 2]