Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Feat/pr 1548 hierarchical community (#1596)

Zohaib Hassnain247455d149c2
diff --git a/semantica/kg/__init__.py b/semantica/kg/__init__.py
index ceb505a5..b76868f7 100644
--- a/semantica/kg/__init__.py
+++ b/semantica/kg/__init__.py
@@ -107,6 +107,11 @@ License: MIT
from .centrality_calculator import CentralityCalculator
from .community_detector import CommunityDetector
+from .community_hierarchy import (
+ CommunityHierarchy,
+ CommunityHierarchyBuilder,
+ HierarchicalCommunity,
+)
from .config import KGConfig, kg_config
from .connectivity_analyzer import ConnectivityAnalyzer
from .entity_resolver import EntityResolver
@@ -114,6 +119,7 @@ from .graph_analyzer import GraphAnalyzer
from .graph_builder import GraphBuilder
from .graph_validator import GraphValidator
from .link_predictor import LinkPredictor
+from .methods import build_community_hierarchy
from .node_embeddings import NodeEmbedder
from .path_finder import PathFinder
from .kg_provenance import GraphBuilderWithProvenance, AlgorithmTrackerWithProvenance
@@ -134,6 +140,10 @@ from .temporal_query_rewriter import TemporalQueryRewriter, TemporalQueryResult
__all__ = [
# Core Classes
"KnowledgeGraph",
+ "HierarchicalCommunity",
+ "CommunityHierarchy",
+ "CommunityHierarchyBuilder",
+ "build_community_hierarchy",
"GraphBuilder",
"GraphBuilderWithProvenance",
"EntityResolver",
diff --git a/semantica/kg/community_hierarchy.py b/semantica/kg/community_hierarchy.py
new file mode 100644
index 00000000..fc5dc767
--- /dev/null
+++ b/semantica/kg/community_hierarchy.py
@@ -0,0 +1,1418 @@
+"""
+Hierarchical Community Structure and Multi-Level Graph Coarsening.
+
+This module provides data structures and algorithms for constructing,
+indexing, and querying hierarchical community structures across
+multiple levels of coarsening.
+"""
+
+from collections import Counter, defaultdict
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+import hashlib
+import json
+import math
+import random
+import traceback
+from typing import Any, Dict, List, Optional, Set, Tuple, Union
+
+import networkx as nx
+import networkx.algorithms.community as nx_comm
+
+from ..utils.logging import get_logger
+from .knowledge_graph import KnowledgeGraph
+
+logger = get_logger("community_hierarchy")
+
+
+def _clean_attr_val(val: Any) -> Any:
+ """Clean and normalize attribute value for canonical deterministic hashing."""
+ if isinstance(val, float):
+ return None if math.isnan(val) else float(val)
+ if isinstance(val, (int, str, bool)):
+ return val
+ if val is None:
+ return None
+ if isinstance(val, dict):
+ return {
+ str(k): _clean_attr_val(v)
+ for k, v in sorted(val.items(), key=lambda x: str(x[0]))
+ }
+ if isinstance(val, (list, tuple)):
+ return [_clean_attr_val(x) for x in val]
+ return str(val)
+
+
+def canonicalize_edges(
+ edges: Any,
+ directed: bool = False,
+) -> List[Dict[str, Any]]:
+ """Produce deterministic canonical representation of induced edges."""
+ if not edges:
+ return []
+
+ if hasattr(edges, "edges"):
+ is_dir = getattr(edges, "is_directed", lambda: directed)()
+ raw_edges = edges.edges(data=True)
+ elif isinstance(edges, (str, bytes)):
+ return []
+ elif isinstance(edges, Iterable):
+ is_dir = directed
+ raw_edges = edges
+ else:
+ return []
+
+ canonical = []
+ for item in raw_edges:
+ if isinstance(item, dict):
+ src = str(
+ item.get("source", item.get("source_id", item.get("src", "")))
+ )
+ tgt = str(
+ item.get("target", item.get("target_id", item.get("tgt", "")))
+ )
+ raw_attrs: Dict[str, Any] = {}
+ if "attributes" in item and isinstance(item["attributes"], dict):
+ raw_attrs.update(item["attributes"])
+ for k, v in item.items():
+ if k not in (
+ "source",
+ "source_id",
+ "src",
+ "target",
+ "target_id",
+ "tgt",
+ "attributes",
+ ):
+ raw_attrs[k] = v
+ attrs = raw_attrs
+ elif isinstance(item, (tuple, list)):
+ if len(item) == 2:
+ src, tgt = str(item[0]), str(item[1])
+ attrs = {}
+ elif len(item) >= 3:
+ src, tgt = str(item[0]), str(item[1])
+ data = item[2]
+ if isinstance(data, dict):
+ attrs = dict(data)
+ elif isinstance(data, (int, float)):
+ attrs = {"weight": float(data)}
+ else:
+ attrs = {"data": str(data)}
+ else:
+ continue
+ else:
+ continue
+
+ if not is_dir and src > tgt:
+ src, tgt = tgt, src
+
+ clean_attrs: Dict[str, Any] = {
+ str(k): _clean_attr_val(v)
+ for k, v in sorted(attrs.items(), key=lambda x: str(x[0]))
+ }
+
+ canonical.append(
+ {
+ "attributes": clean_attrs,
+ "source": src,
+ "target": tgt,
+ }
+ )
+
+ canonical.sort(
+ key=lambda e: (
+ e["source"],
+ e["target"],
+ json.dumps(e["attributes"], sort_keys=True, separators=(",", ":")),
+ )
+ )
+ return canonical
+
+
+def compute_community_hash(
+ level: int,
+ index: int,
+ entity_ids: List[str],
+ child_ids: Optional[List[str]] = None,
+ edges: Optional[Any] = None,
+ directed: bool = False,
+) -> str:
+ """Compute canonical deterministic SHA-256 hash for community content."""
+ payload = {
+ "level": level,
+ "index": index,
+ "entity_ids": sorted(set(str(e) for e in entity_ids)),
+ "child_ids": sorted(set(str(c) for c in (child_ids or []))),
+ "edges": canonicalize_edges(edges, directed=directed),
+ }
+ dumped = json.dumps(payload, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(dumped.encode("utf-8")).hexdigest()
+
+
+@dataclass
+class HierarchicalCommunity:
+ """Hierarchical community representation within a clustered graph."""
+
+ id: str
+ level: int
+ index: int
+ entity_ids: List[str]
+ child_ids: List[str] = field(default_factory=list)
+ parent_id: Optional[str] = None
+ size: int = 0
+ metrics: Dict[str, Any] = field(default_factory=dict)
+ content_hash: str = ""
+ edges: List[Dict[str, Any]] = field(default_factory=list)
+ directed: bool = False
+
+ def __post_init__(self) -> None:
+ if self.entity_ids:
+ self.entity_ids = sorted(set(str(e) for e in self.entity_ids))
+ else:
+ self.entity_ids = []
+
+ if self.child_ids:
+ self.child_ids = sorted(set(str(c) for c in self.child_ids))
+ else:
+ self.child_ids = []
+
+ if self.edges:
+ self.edges = canonicalize_edges(self.edges, directed=self.directed)
+ else:
+ self.edges = []
+
+ if not self.size:
+ self.size = len(self.entity_ids)
+
+ if not self.content_hash:
+ self.content_hash = compute_community_hash(
+ self.level,
+ self.index,
+ self.entity_ids,
+ self.child_ids,
+ edges=self.edges,
+ directed=self.directed,
+ )
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Serialize community to a dictionary."""
+ return {
+ "id": self.id,
+ "level": self.level,
+ "index": self.index,
+ "entity_ids": list(self.entity_ids),
+ "child_ids": list(self.child_ids),
+ "parent_id": self.parent_id,
+ "size": self.size,
+ "metrics": dict(self.metrics),
+ "content_hash": self.content_hash,
+ "edges": list(self.edges),
+ "directed": self.directed,
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "HierarchicalCommunity":
+ """Instantiate a community from a dictionary."""
+ raw_parent = data.get("parent_id")
+ parent_id = str(raw_parent) if raw_parent is not None else None
+ return cls(
+ id=str(data["id"]),
+ level=int(data["level"]),
+ index=int(data["index"]),
+ entity_ids=list(data.get("entity_ids", [])),
+ child_ids=list(data.get("child_ids", [])),
+ parent_id=parent_id,
+ size=int(data.get("size", len(data.get("entity_ids", [])))),
+ metrics=dict(data.get("metrics", {})),
+ content_hash=str(data.get("content_hash", "")),
+ edges=list(data.get("edges", [])),
+ directed=bool(data.get("directed", False)),
+ )
+
+
+class CommunityHierarchy:
+ """Container for hierarchical community structures and traversal."""
+
+ def __init__(
+ self,
+ communities: Optional[
+ Union[
+ Dict[str, HierarchicalCommunity],
+ List[HierarchicalCommunity],
+ ]
+ ] = None,
+ graph: Optional[Any] = None,
+ metadata: Optional[Dict[str, Any]] = None,
+ ) -> None:
+ self._graph = graph
+ self.metadata: Dict[str, Any] = dict(metadata or {})
+ if communities is None:
+ self._communities: Dict[str, HierarchicalCommunity] = {}
+ elif isinstance(communities, (list, tuple, set)):
+ self._communities = {c.id: c for c in communities}
+ elif isinstance(communities, dict):
+ self._communities = dict(communities)
+ else:
+ raise TypeError("communities must be a dict, list, or None")
+
+ self._node_to_community: Dict[Tuple[str, int], str] = {}
+ self._level_to_communities: Dict[int, List[str]] = {}
+ self._rebuild_index()
+
+ def _rebuild_index(self) -> None:
+ self._node_to_community.clear()
+ self._level_to_communities.clear()
+
+ for comm in self._communities.values():
+ level = comm.level
+ if level not in self._level_to_communities:
+ self._level_to_communities[level] = []
+ self._level_to_communities[level].append(comm.id)
+
+ for node_id in comm.entity_ids:
+ self._node_to_community[(str(node_id), level)] = comm.id
+
+ for level in self._level_to_communities:
+ self._level_to_communities[level].sort(
+ key=lambda cid: self._communities[cid].index
+ )
+
+ @property
+ def communities(self) -> Dict[str, HierarchicalCommunity]:
+ """Dictionary of community ID to HierarchicalCommunity object."""
+ return self._communities
+
+ @property
+ def levels(self) -> List[int]:
+ """Sorted list of unique levels present in the hierarchy."""
+ return sorted(self._level_to_communities.keys())
+
+ @property
+ def max_level(self) -> int:
+ """Maximum hierarchy level index, or -1 if empty."""
+ return max(self.levels) if self.levels else -1
+
+ @property
+ def is_empty(self) -> bool:
+ """Return True if hierarchy contains no communities."""
+ return len(self._communities) == 0
+
+ @property
+ def root_communities(self) -> List[HierarchicalCommunity]:
+ """Communities with no parent (top of the hierarchy)."""
+ roots = [c for c in self._communities.values() if c.parent_id is None]
+ roots.sort(key=lambda c: (c.level, c.index))
+ return roots
+
+ @property
+ def leaf_communities(self) -> List[HierarchicalCommunity]:
+ """Communities with no children (finest level)."""
+ leaves = [c for c in self._communities.values() if not c.child_ids]
+ leaves.sort(key=lambda c: (c.level, c.index))
+ return leaves
+
+ def get_community(
+ self, community_id: str
+ ) -> Optional[HierarchicalCommunity]:
+ """Retrieve community by ID."""
+ return self._communities.get(str(community_id))
+
+ def get_communities_at_level(
+ self, level: int
+ ) -> List[HierarchicalCommunity]:
+ """Retrieve all communities at a specific hierarchy level."""
+ cids = self._level_to_communities.get(level, [])
+ return [self._communities[cid] for cid in cids]
+
+ def get_children(
+ self, community_or_id: Union[str, HierarchicalCommunity]
+ ) -> List[HierarchicalCommunity]:
+ """Retrieve child communities for a given community or ID."""
+ if isinstance(community_or_id, HierarchicalCommunity):
+ comm = community_or_id
+ else:
+ comm = self.get_community(str(community_or_id))
+
+ if comm is None:
+ return []
+ return [
+ self._communities[cid]
+ for cid in comm.child_ids
+ if cid in self._communities
+ ]
+
+ def get_parent(
+ self, community_or_id: Union[str, HierarchicalCommunity]
+ ) -> Optional[HierarchicalCommunity]:
+ """Retrieve parent community for a given community or ID."""
+ if isinstance(community_or_id, HierarchicalCommunity):
+ comm = community_or_id
+ else:
+ comm = self.get_community(str(community_or_id))
+
+ if comm is None or comm.parent_id is None:
+ return None
+ return self.get_community(comm.parent_id)
+
+ def get_community_for_node(
+ self, node_id: str, level: Optional[int] = None
+ ) -> Optional[HierarchicalCommunity]:
+ """
+ Look up community containing a node at a given level in O(1) time.
+
+ If level is None, defaults to the lowest level available (usually 0).
+ """
+ if self.is_empty:
+ return None
+ target_level = min(self.levels) if level is None else level
+ comm_id = self._node_to_community.get((str(node_id), target_level))
+ if comm_id is None:
+ return None
+ return self._communities.get(comm_id)
+
+ def get_subgraph(
+ self,
+ community_or_id: Union[str, HierarchicalCommunity],
+ graph: Optional[Any] = None,
+ ) -> Any:
+ """Extract the subgraph induced by community entities."""
+ target_graph = graph if graph is not None else self._graph
+ if target_graph is None:
+ raise ValueError("A graph must be provided to extract a subgraph.")
+
+ if isinstance(community_or_id, HierarchicalCommunity):
+ comm = community_or_id
+ else:
+ comm = self.get_community(str(community_or_id))
+
+ if comm is None:
+ raise KeyError(
+ f"Community '{community_or_id}' not found in hierarchy."
+ )
+
+ node_set = set(comm.entity_ids)
+
+ if hasattr(target_graph, "subgraph"):
+ matching_nodes = [
+ n for n in target_graph.nodes
+ if str(n) in node_set or n in node_set
+ ]
+ return target_graph.subgraph(matching_nodes).copy()
+
+ if isinstance(target_graph, KnowledgeGraph):
+ sub_entities = [
+ e for e in target_graph.entities
+ if (
+ str(e.get("id", "")) if isinstance(e, dict) else str(e)
+ ) in node_set
+ ]
+ sub_relationships = [
+ r for r in target_graph.relationships
+ if (
+ str(r.get("source", r.get("source_id", "")))
+ if isinstance(r, dict)
+ else str(r[0])
+ ) in node_set
+ and (
+ str(r.get("target", r.get("target_id", "")))
+ if isinstance(r, dict)
+ else str(r[1])
+ ) in node_set
+ ]
+ return KnowledgeGraph(
+ entities=sub_entities,
+ relationships=sub_relationships,
+ metadata=dict(target_graph.metadata),
+ )
+
+ if isinstance(target_graph, dict):
+ if "entities" in target_graph or "relationships" in target_graph:
+ sub_entities = [
+ e for e in target_graph.get("entities", [])
+ if (
+ str(e.get("id", "")) if isinstance(e, dict) else str(e)
+ ) in node_set
+ ]
+ sub_relationships = [
+ r for r in target_graph.get("relationships", [])
+ if (
+ str(r.get("source", r.get("source_id", "")))
+ if isinstance(r, dict)
+ else str(r[0])
+ ) in node_set
+ and (
+ str(r.get("target", r.get("target_id", "")))
+ if isinstance(r, dict)
+ else str(r[1])
+ ) in node_set
+ ]
+ return {
+ "entities": sub_entities,
+ "relationships": sub_relationships,
+ "metadata": dict(target_graph.get("metadata", {})),
+ }
+ if "nodes" in target_graph or "edges" in target_graph:
+ sub_nodes = [
+ n for n in target_graph.get("nodes", [])
+ if (
+ str(n.get("id", "")) if isinstance(n, dict) else str(n)
+ ) in node_set
+ ]
+ sub_edges = [
+ e for e in target_graph.get("edges", [])
+ if (
+ str(e.get("source", e.get("source_id", "")))
+ if isinstance(e, dict)
+ else str(e[0])
+ ) in node_set
+ and (
+ str(e.get("target", e.get("target_id", "")))
+ if isinstance(e, dict)
+ else str(e[1])
+ ) in node_set
+ ]
+ return {"nodes": sub_nodes, "edges": sub_edges}
+
+ # Adjacency dict format: {node: [neighbors, ...]}
+ sub_adj: Dict[str, Any] = {}
+ for node, nbrs in target_graph.items():
+ node_str = str(node)
+ if node_str in node_set:
+ if isinstance(nbrs, (list, set, tuple)):
+ sub_adj[node_str] = [
+ str(nbr) for nbr in nbrs if str(nbr) in node_set
+ ]
+ else:
+ sub_adj[node_str] = nbrs
+ return sub_adj
+
+ raise TypeError(f"Unsupported graph type: {type(target_graph)}")
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Serialize hierarchy to a dictionary."""
+ sorted_comms = sorted(
+ self._communities.items(),
+ key=lambda kv: (kv[1].level, kv[1].index),
+ )
+ return {
+ "communities": {cid: c.to_dict() for cid, c in sorted_comms},
+ "levels": list(self.levels),
+ "max_level": self.max_level,
+ "metadata": dict(self.metadata),
+ }
+
+ @classmethod
+ def from_dict(cls, data: Dict[str, Any]) -> "CommunityHierarchy":
+ """Instantiate hierarchy from a dictionary."""
+ raw_communities = data.get("communities", {})
+ if isinstance(raw_communities, list):
+ communities = {
+ str(c_data["id"]): HierarchicalCommunity.from_dict(c_data)
+ for c_data in raw_communities
+ }
+ else:
+ communities = {
+ cid: HierarchicalCommunity.from_dict(c_data)
+ for cid, c_data in raw_communities.items()
+ }
+ return cls(
+ communities=communities,
+ metadata=dict(data.get("metadata", {})),
+ )
+
+ def to_json(self, indent: Optional[int] = None) -> str:
+ """Serialize hierarchy to a JSON string."""
+ return json.dumps(self.to_dict(), indent=indent, sort_keys=True)
+
+ @classmethod
+ def from_json(cls, json_str: str) -> "CommunityHierarchy":
+ """Instantiate hierarchy from a JSON string."""
+ return cls.from_dict(json.loads(json_str))
+
+ def __len__(self) -> int:
+ return len(self._communities)
+
+ def __iter__(self):
+ return iter(self._communities.values())
+
+ def __getitem__(self, community_id: str) -> HierarchicalCommunity:
+ return self._communities[str(community_id)]
+
+ def __contains__(self, community_id: str) -> bool:
+ return str(community_id) in self._communities
+
+ def __repr__(self) -> str:
+ return (
+ f"CommunityHierarchy(levels={self.levels}, "
+ f"total_communities={len(self._communities)}, "
+ f"max_level={self.max_level})"
+ )
+
+
+class CommunityHierarchyBuilder:
+ """Multi-level hierarchy builder supporting Louvain and Leiden."""
+
+ @staticmethod
+ def _clean_weight(val: Any) -> float:
+ """Sanitize edge weights to non-negative floats."""
+ if val is None:
+ return 1.0
+ try:
+ w = float(val)
+ if math.isnan(w):
+ return 1.0
+ return max(0.0, w)
+ except (ValueError, TypeError):
+ return 1.0
+
+ def __init__(
+ self,
+ algorithm: str = "louvain",
+ resolution: Union[float, List[float]] = 1.0,
+ seed: Optional[int] = 42,
+ directed: Optional[bool] = None,
+ weight: Optional[str] = "weight",
+ threshold: float = 1e-7,
+ max_levels: Optional[int] = None,
+ id_prefix: str = "c_",
+ **kwargs: Any,
+ ) -> None:
+ algo_norm = algorithm.lower().strip()
+ if algo_norm in ("louvain", "default"):
+ self.algorithm = "louvain"
+ elif algo_norm == "leiden":
+ self.algorithm = "leiden"
+ else:
+ raise ValueError(
+ f"Unsupported algorithm '{algorithm}'. "
+ f"Supported algorithms: 'louvain', 'leiden'"
+ )
+
+ if isinstance(resolution, (list, tuple)):
+ if len(resolution) == 0:
+ self.resolution: Union[float, List[float]] = [1.0]
+ else:
+ for r in resolution:
+ if float(r) <= 0:
+ raise ValueError(
+ "Resolution values must be positive (> 0)"
+ )
+ self.resolution = [float(r) for r in resolution]
+ else:
+ if float(resolution) <= 0:
+ raise ValueError("Resolution must be positive (> 0)")
+ self.resolution = float(resolution)
+
+ if max_levels is not None and max_levels <= 0:
+ raise ValueError("max_levels must be a positive integer (> 0)")
+ self.max_levels = max_levels
+
+ self.seed = seed
+ self.directed = directed
+ self.weight = weight
+ self.threshold = threshold
+ self.id_prefix = id_prefix
+ self.config = kwargs
+ self._fallback_used = False
+
+ def build(self, graph: Any) -> CommunityHierarchy:
+ """Build hierarchical community structure from graph input."""
+ self._fallback_used = False
+ nx_graph = self._to_networkx(graph)
+
+ if nx_graph.number_of_nodes() == 0:
+ return CommunityHierarchy(
+ communities={},
+ graph=nx_graph,
+ metadata={"algorithm": self.algorithm, "fallback": False},
+ )
+
+ if self.algorithm == "leiden":
+ partitions = self._build_leiden_partitions(nx_graph)
+ else:
+ partitions = self._build_louvain_partitions(nx_graph)
+
+ if self.max_levels is not None and self.max_levels > 0:
+ partitions = partitions[:self.max_levels]
+
+ return self._build_hierarchy_from_partitions(nx_graph, partitions)
+
+ def _to_networkx(self, graph: Any) -> Union[nx.Graph, nx.DiGraph]:
+ """Convert input graph into NetworkX Graph or DiGraph."""
+ node_map: Dict[str, Any] = {}
+
+ def register_node(raw_id: Any) -> str:
+ if raw_id is None:
+ return ""
+ sid = str(raw_id)
+ if not sid:
+ return ""
+ if sid in node_map and node_map[sid] != raw_id:
+ raise ValueError(
+ f"Node identifier collision detected: distinct original "
+ f"nodes {repr(node_map[sid])} "
+ f"({type(node_map[sid]).__name__}) and {repr(raw_id)} "
+ f"({type(raw_id).__name__}) both serialize to '{sid}'."
+ )
+ node_map[sid] = raw_id
+ return sid
+
+ weight_attr = self.weight or "weight"
+
+ if isinstance(graph, (nx.Graph, nx.DiGraph)):
+ is_directed = (
+ self.directed
+ if self.directed is not None
+ else graph.is_directed()
+ )
+ out_graph = nx.DiGraph() if is_directed else nx.Graph()
+ for n, data in graph.nodes(data=True):
+ sn = register_node(n)
+ if sn:
+ out_graph.add_node(sn, **data)
+
+ is_multi = getattr(graph, "is_multigraph", lambda: False)()
+ for u, v, data in graph.edges(data=True):
+ su = register_node(u)
+ sv = register_node(v)
+ if not su or not sv:
+ continue
+ edge_data = dict(data)
+ w = self._clean_weight(edge_data.get(weight_attr, 1.0))
+ edge_data[weight_attr] = w
+ if (
+ (is_multi or not is_directed)
+ and out_graph.has_edge(su, sv)
+ ):
+ curr_w = self._clean_weight(
+ out_graph[su][sv].get(weight_attr, 1.0)
+ )
+ out_graph[su][sv][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(su, sv, **edge_data)
+ return out_graph
+
+ is_directed = self.directed if self.directed is not None else False
+ out_graph = nx.DiGraph() if is_directed else nx.Graph()
+
+ if isinstance(graph, KnowledgeGraph):
+ for entity in graph.entities:
+ if isinstance(entity, dict):
+ raw_id = entity.get("id", "")
+ eid = register_node(raw_id)
+ if eid:
+ out_graph.add_node(eid, **entity)
+ else:
+ eid = register_node(entity)
+ if eid:
+ out_graph.add_node(eid)
+
+ for rel in graph.relationships:
+ if isinstance(rel, dict):
+ src_raw = rel.get("source", rel.get("source_id", ""))
+ tgt_raw = rel.get("target", rel.get("target_id", ""))
+ src = register_node(src_raw)
+ tgt = register_node(tgt_raw)
+ if src and tgt:
+ data = dict(rel)
+ w = self._clean_weight(data.get(weight_attr, 1.0))
+ data[weight_attr] = w
+ if out_graph.has_edge(src, tgt):
+ curr_w = self._clean_weight(
+ out_graph[src][tgt].get(weight_attr, 1.0)
+ )
+ out_graph[src][tgt][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(src, tgt, **data)
+ elif isinstance(rel, (tuple, list)) and len(rel) >= 2:
+ src = register_node(rel[0])
+ tgt = register_node(rel[1])
+ if src and tgt:
+ w = self._clean_weight(
+ rel[2]
+ if len(rel) >= 3 and isinstance(rel[2], (int, float))
+ else 1.0
+ )
+ if out_graph.has_edge(src, tgt):
+ curr_w = self._clean_weight(
+ out_graph[src][tgt].get(weight_attr, 1.0)
+ )
+ out_graph[src][tgt][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(src, tgt, **{weight_attr: w})
+ return out_graph
+
+ if isinstance(graph, dict):
+ if "entities" in graph or "relationships" in graph:
+ for entity in graph.get("entities", []):
+ if isinstance(entity, dict):
+ raw_id = entity.get("id", "")
+ eid = register_node(raw_id)
+ if eid:
+ out_graph.add_node(eid, **entity)
+ else:
+ eid = register_node(entity)
+ if eid:
+ out_graph.add_node(eid)
+
+ for rel in graph.get("relationships", []):
+ if isinstance(rel, dict):
+ src_raw = rel.get("source", rel.get("source_id", ""))
+ tgt_raw = rel.get("target", rel.get("target_id", ""))
+ src = register_node(src_raw)
+ tgt = register_node(tgt_raw)
+ if src and tgt:
+ data = dict(rel)
+ w = self._clean_weight(data.get(weight_attr, 1.0))
+ data[weight_attr] = w
+ if out_graph.has_edge(src, tgt):
+ curr_w = self._clean_weight(
+ out_graph[src][tgt].get(weight_attr, 1.0)
+ )
+ out_graph[src][tgt][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(src, tgt, **data)
+ elif isinstance(rel, (tuple, list)) and len(rel) >= 2:
+ src = register_node(rel[0])
+ tgt = register_node(rel[1])
+ if src and tgt:
+ w = self._clean_weight(
+ rel[2]
+ if len(rel) >= 3 and isinstance(rel[2], (int, float))
+ else 1.0
+ )
+ if out_graph.has_edge(src, tgt):
+ curr_w = self._clean_weight(
+ out_graph[src][tgt].get(weight_attr, 1.0)
+ )
+ out_graph[src][tgt][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(src, tgt, **{weight_attr: w})
+ return out_graph
+
+ if "nodes" in graph or "edges" in graph:
+ for n in graph.get("nodes", []):
+ if isinstance(n, dict):
+ raw_id = n.get("id", "")
+ nid = register_node(raw_id)
+ if nid:
+ out_graph.add_node(nid, **n)
+ else:
+ nid = register_node(n)
+ if nid:
+ out_graph.add_node(nid)
+
+ for e in graph.get("edges", []):
+ if isinstance(e, dict):
+ src_raw = e.get("source", e.get("source_id", ""))
+ tgt_raw = e.get("target", e.get("target_id", ""))
+ src = register_node(src_raw)
+ tgt = register_node(tgt_raw)
+ if src and tgt:
+ data = dict(e)
+ w = self._clean_weight(data.get(weight_attr, 1.0))
+ data[weight_attr] = w
+ if out_graph.has_edge(src, tgt):
+ curr_w = self._clean_weight(
+ out_graph[src][tgt].get(weight_attr, 1.0)
+ )
+ out_graph[src][tgt][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(src, tgt, **data)
+ elif isinstance(e, (tuple, list)) and len(e) >= 2:
+ src = register_node(e[0])
+ tgt = register_node(e[1])
+ if src and tgt:
+ w = self._clean_weight(
+ e[2]
+ if len(e) >= 3 and isinstance(e[2], (int, float))
+ else 1.0
+ )
+ if out_graph.has_edge(src, tgt):
+ curr_w = self._clean_weight(
+ out_graph[src][tgt].get(weight_attr, 1.0)
+ )
+ out_graph[src][tgt][weight_attr] = curr_w + w
+ else:
+ out_graph.add_edge(src, tgt, **{weight_attr: w})
+ return out_graph
+
+ for node, nbrs in graph.items():
+ node_id = register_node(node)
+ if not node_id:
+ continue
+ out_graph.add_node(node_id)
+ if isinstance(nbrs, (list, set, tuple)):
+ for nbr in nbrs:
+ nbr_id = register_node(nbr)
+ if not nbr_id:
+ continue
+ if out_graph.has_edge(node_id, nbr_id):
+ curr_w = self._clean_weight(
+ out_graph[node_id][nbr_id].get(
+ weight_attr, 1.0
+ )
+ )
+ out_graph[node_id][nbr_id][weight_attr] = (
+ curr_w + 1.0
+ )
+ else:
+ out_graph.add_edge(
+ node_id, nbr_id, **{weight_attr: 1.0}
+ )
+ return out_graph
+
+ raise TypeError(f"Unsupported graph input type: {type(graph)}")
+
+ def _refine_partition(
+ self, G: Union[nx.Graph, nx.DiGraph], partition: List[Set[Any]]
+ ) -> List[Set[Any]]:
+ """Refine partition into connected or weakly connected components."""
+ refined: List[Set[Any]] = []
+ is_directed = G.is_directed()
+
+ for comm in partition:
+ if not comm:
+ continue
+ sub = G.subgraph(comm)
+ if is_directed:
+ components = list(nx.weakly_connected_components(sub))
+ else:
+ components = list(nx.connected_components(sub))
+ refined.extend(components)
+
+ return refined
+
+ def _leiden_communities_native(
+ self,
+ G: Union[nx.Graph, nx.DiGraph],
+ resolution: float = 1.0,
+ seed: Optional[int] = None,
+ weight: Optional[str] = "weight",
+ max_iter: int = 20,
+ ) -> List[Set[Any]]:
+ """Native Leiden community detection with local moving and refinement."""
+ nodes = list(G.nodes())
+ n_nodes = len(nodes)
+ if n_nodes <= 1:
+ return [set(nodes)]
+
+ rng = random.Random(seed)
+ strengths: Dict[Any, float] = {}
+ total_weight = 0.0
+ adj: Dict[Any, Dict[Any, float]] = {n: {} for n in nodes}
+
+ for u in nodes:
+ u_strength = 0.0
+ nbrs = set(G.successors(u) if G.is_directed() else G.neighbors(u))
+ if G.is_directed():
+ nbrs.update(G.predecessors(u))
+ for v in nbrs:
+ w = 0.0
+ if G.has_edge(u, v):
+ w += self._clean_weight(
+ G[u][v].get(weight or "weight", 1.0)
+ )
+ if G.is_directed() and G.has_edge(v, u):
+ w += self._clean_weight(
+ G[v][u].get(weight or "weight", 1.0)
+ )
+ adj[u][v] = w
+ u_strength += w
+ strengths[u] = u_strength
+ total_weight += u_strength
+
+ m2 = total_weight
+ if m2 <= 0.0:
+ return [{n} for n in nodes]
+
+ node_to_comm: Dict[Any, int] = {n: i for i, n in enumerate(nodes)}
+ comm_to_nodes: Dict[int, Set[Any]] = {
+ i: {n} for i, n in enumerate(nodes)
+ }
+ comm_tot: Dict[int, float] = {
+ i: strengths[n] for i, n in enumerate(nodes)
+ }
+
+ improved = True
+ iteration = 0
+ while improved and iteration < max_iter:
+ improved = False
+ iteration += 1
+ shuffled = list(nodes)
+ rng.shuffle(shuffled)
+
+ for u in shuffled:
+ curr_c = node_to_comm[u]
+ k_u = strengths[u]
+
+ comm_weights: Dict[int, float] = defaultdict(float)
+ for v, w in adj[u].items():
+ comm_weights[node_to_comm[v]] += w
+
+ k_u_curr = comm_weights.get(curr_c, 0.0)
+ best_c = curr_c
+ best_gain = 0.0
+
+ for cand_c, k_u_cand in comm_weights.items():
+ if cand_c == curr_c:
+ continue
+ tot_cand = comm_tot[cand_c]
+ tot_curr = comm_tot[curr_c]
+ gain = (k_u_cand - k_u_curr) / m2 - (
+ resolution * k_u * (tot_cand - (tot_curr - k_u))
+ ) / (m2 * m2)
+ if gain > best_gain:
+ best_gain = gain
+ best_c = cand_c
+
+ if best_c != curr_c and best_gain > 1e-8:
+ comm_to_nodes[curr_c].remove(u)
+ comm_tot[curr_c] -= k_u
+ if not comm_to_nodes[curr_c]:
+ del comm_to_nodes[curr_c]
+ del comm_tot[curr_c]
+
+ node_to_comm[u] = best_c
+ comm_to_nodes[best_c].add(u)
+ comm_tot[best_c] += k_u
+ improved = True
+
+ refined_comms: List[Set[Any]] = []
+ for c_id, c_nodes in comm_to_nodes.items():
+ if len(c_nodes) <= 1:
+ refined_comms.append(set(c_nodes))
+ continue
+
+ sub_c_to_nodes: Dict[int, Set[Any]] = {}
+ sub_node_to_c: Dict[Any, int] = {}
+ for idx, u in enumerate(c_nodes):
+ sub_c_to_nodes[idx] = {u}
+ sub_node_to_c[u] = idx
+
+ for u in c_nodes:
+ curr_sub = sub_node_to_c[u]
+ k_u = strengths[u]
+
+ sub_weights: Dict[int, float] = defaultdict(float)
+ for v, w in adj[u].items():
+ if v in c_nodes:
+ sub_weights[sub_node_to_c[v]] += w
+
+ best_sub = curr_sub
+ best_sub_gain = 0.0
+ for cand_sub, k_u_cand in sub_weights.items():
+ if cand_sub == curr_sub:
+ continue
+ tot_cand = sum(
+ strengths[x] for x in sub_c_to_nodes[cand_sub]
+ )
+ tot_curr = sum(
+ strengths[x] for x in sub_c_to_nodes[curr_sub]
+ )
+ gain = (
+ k_u_cand - sub_weights.get(curr_sub, 0.0)
+ ) / m2 - (
+ resolution * k_u * (tot_cand - (tot_curr - k_u))
+ ) / (m2 * m2)
+ if gain > best_sub_gain:
+ best_sub_gain = gain
+ best_sub = cand_sub
+
+ if best_sub != curr_sub and best_sub_gain > 1e-8:
+ sub_c_to_nodes[curr_sub].remove(u)
+ if not sub_c_to_nodes[curr_sub]:
+ del sub_c_to_nodes[curr_sub]
+ sub_node_to_c[u] = best_sub
+ sub_c_to_nodes[best_sub].add(u)
+
+ for s_nodes in sub_c_to_nodes.values():
+ if s_nodes:
+ refined_comms.append(set(s_nodes))
+
+ return refined_comms
+
+ def _detect_leiden_communities(
+ self,
+ G: Union[nx.Graph, nx.DiGraph],
+ resolution: float = 1.0,
+ weight: Optional[str] = "weight",
+ ) -> List[Set[Any]]:
+ """Detect communities using Leiden with optional C library fallback."""
+ weight_key = weight or "weight"
+ try:
+ import igraph as ig
+ import leidenalg
+
+ nodes = list(G.nodes())
+ node_idx = {n: i for i, n in enumerate(nodes)}
+ ig_graph = ig.Graph(directed=G.is_directed())
+ ig_graph.add_vertices(len(nodes))
+ edges = []
+ weights = []
+ for u, v, data in G.edges(data=True):
+ edges.append((node_idx[u], node_idx[v]))
+ weights.append(
+ self._clean_weight(data.get(weight_key, 1.0))
+ )
+
+ ig_graph.add_edges(edges)
+ if weights and weight is not None:
+ ig_graph.es["weight"] = weights
+
+ partition = leidenalg.find_partition(
+ ig_graph,
+ leidenalg.RBConfigurationVertexPartition,
+ weights="weight" if (weights and weight is not None) else None,
+ resolution_parameter=resolution,
+ seed=self.seed,
+ )
+ return [{nodes[idx] for idx in comm} for comm in partition]
+ except (ImportError, Exception):
+ pass
+
+ try:
+ from cdlib import algorithms
+
+ cd_comms = algorithms.leiden(G, weights=weight)
+ return [set(c) for c in cd_comms.communities]
+ except (ImportError, Exception):
+ pass
+
+ return self._leiden_communities_native(
+ G, resolution=resolution, seed=self.seed, weight=weight
+ )
+
+ def _build_louvain_partitions(
+ self, G: Union[nx.Graph, nx.DiGraph]
+ ) -> List[List[Set[Any]]]:
+ """Generate multi-level coarsened partitions using Louvain."""
+ if G.number_of_nodes() == 0:
+ return []
+ if G.number_of_nodes() == 1:
+ return [[set(G.nodes())]]
+
+ partitions: List[List[Set[Any]]] = []
+ weight_attr = self.weight or "weight"
+ current_g = G.copy()
+ for u, v in current_g.edges():
+ current_g[u][v][weight_attr] = self._clean_weight(
+ current_g[u][v].get(weight_attr, 1.0)
+ )
+
+ super_to_orig: Dict[Any, Set[Any]] = {n: {n} for n in G.nodes()}
+ level = 0
+
+ while True:
+ if self.max_levels is not None and level >= self.max_levels:
+ break
+
+ if isinstance(self.resolution, (list, tuple)):
+ curr_res = float(
+ self.resolution[min(level, len(self.resolution) - 1)]
+ )
+ else:
+ curr_res = float(self.resolution)
+
+ curr_weight = self.weight if level == 0 else weight_attr
+
+ try:
+ raw_comms = nx_comm.louvain_communities(
+ current_g,
+ weight=curr_weight,
+ resolution=curr_res,
+ threshold=self.threshold,
+ seed=self.seed,
+ )
+ except (
+ ZeroDivisionError,
+ FloatingPointError,
+ RuntimeError,
+ nx.NetworkXError,
+ ) as e:
+ logger.warning(
+ f"Louvain partitioning failed at level {level}: {e}. "
+ f"Using singleton fallback. Traceback:\n"
+ f"{traceback.format_exc()}"
+ )
+ self._fallback_used = True
+ raw_comms = [{n} for n in current_g.nodes()]
+
+ refined_orig_comms: List[Set[Any]] = []
+ for c in raw_comms:
+ orig_set: Set[Any] = set()
+ for sn in c:
+ orig_set.update(super_to_orig[sn])
+ sub = G.subgraph(orig_set)
+ if G.is_directed():
+ comps = list(nx.weakly_connected_components(sub))
+ else:
+ comps = list(nx.connected_components(sub))
+ refined_orig_comms.extend(comps)
+
+ if partitions and (
+ set(frozenset(s) for s in refined_orig_comms)
+ == set(frozenset(s) for s in partitions[-1])
+ or len(refined_orig_comms) >= len(partitions[-1])
+ ):
+ break
+
+ partitions.append(refined_orig_comms)
+ level += 1
+
+ if (
+ len(refined_orig_comms) <= 1
+ or current_g.number_of_edges() == 0
+ ):
+ break
+
+ new_super_to_orig: Dict[int, Set[Any]] = {}
+ node_to_new_super: Dict[Any, int] = {}
+ for idx, comp in enumerate(refined_orig_comms):
+ new_super_to_orig[idx] = comp
+ for n in comp:
+ node_to_new_super[n] = idx
+
+ next_g = nx.DiGraph() if G.is_directed() else nx.Graph()
+ next_g.add_nodes_from(range(len(refined_orig_comms)))
+
+ for u, v, data in G.edges(data=True):
+ su = node_to_new_super[u]
+ sv = node_to_new_super[v]
+ if su == sv:
+ continue
+ w = self._clean_weight(data.get(weight_attr, 1.0))
+ if next_g.has_edge(su, sv):
+ next_g[su][sv][weight_attr] += w
+ else:
+ next_g.add_edge(su, sv, **{weight_attr: w})
+
+ if next_g.number_of_edges() == 0:
+ break
+
+ current_g = next_g
+ super_to_orig = new_super_to_orig
+
+ return partitions
+
+ def _build_leiden_partitions(
+ self, G: Union[nx.Graph, nx.DiGraph]
+ ) -> List[List[Set[Any]]]:
+ """Generate multi-level coarsened partitions using Leiden."""
+ if G.number_of_nodes() == 0:
+ return []
+ if G.number_of_nodes() == 1:
+ return [[set(G.nodes())]]
+
+ partitions: List[List[Set[Any]]] = []
+ weight_attr = self.weight or "weight"
+ current_g = G.copy()
+ for u, v in current_g.edges():
+ current_g[u][v][weight_attr] = self._clean_weight(
+ current_g[u][v].get(weight_attr, 1.0)
+ )
+
+ super_to_orig: Dict[Any, Set[Any]] = {n: {n} for n in G.nodes()}
+ level = 0
+
+ while True:
+ if self.max_levels is not None and level >= self.max_levels:
+ break
+
+ if isinstance(self.resolution, (list, tuple)):
+ curr_res = float(
+ self.resolution[min(level, len(self.resolution) - 1)]
+ )
+ else:
+ curr_res = float(self.resolution)
+
+ curr_weight = self.weight if level == 0 else weight_attr
+
+ try:
+ raw_comms = self._detect_leiden_communities(
+ current_g, resolution=curr_res, weight=curr_weight
+ )
+ except (
+ ZeroDivisionError,
+ FloatingPointError,
+ RuntimeError,
+ nx.NetworkXError,
+ ) as e:
+ logger.warning(
+ f"Leiden community detection failed at level {level}: {e}. "
+ f"Using singleton fallback. Traceback:\n"
+ f"{traceback.format_exc()}"
+ )
+ self._fallback_used = True
+ raw_comms = [{n} for n in current_g.nodes()]
+
+ refined_orig_comms: List[Set[Any]] = []
+ for c in raw_comms:
+ orig_set: Set[Any] = set()
+ for sn in c:
+ orig_set.update(super_to_orig[sn])
+ sub = G.subgraph(orig_set)
+ if G.is_directed():
+ comps = list(nx.weakly_connected_components(sub))
+ else:
+ comps = list(nx.connected_components(sub))
+ refined_orig_comms.extend(comps)
+
+ if partitions and (
+ set(frozenset(s) for s in refined_orig_comms)
+ == set(frozenset(s) for s in partitions[-1])
+ or len(refined_orig_comms) >= len(partitions[-1])
+ ):
+ break
+
+ partitions.append(refined_orig_comms)
+ level += 1
+
+ if (
+ len(refined_orig_comms) <= 1
+ or current_g.number_of_edges() == 0
+ ):
+ break
+
+ new_super_to_orig: Dict[int, Set[Any]] = {}
+ node_to_new_super: Dict[Any, int] = {}
+ for idx, comp in enumerate(refined_orig_comms):
+ new_super_to_orig[idx] = comp
+ for n in comp:
+ node_to_new_super[n] = idx
+
+ next_g = nx.DiGraph() if G.is_directed() else nx.Graph()
+ next_g.add_nodes_from(range(len(refined_orig_comms)))
+
+ for u, v, data in G.edges(data=True):
+ su = node_to_new_super[u]
+ sv = node_to_new_super[v]
+ if su == sv:
+ continue
+ w = self._clean_weight(data.get(weight_attr, 1.0))
+ if next_g.has_edge(su, sv):
+ next_g[su][sv][weight_attr] += w
+ else:
+ next_g.add_edge(su, sv, **{weight_attr: w})
+
+ if next_g.number_of_edges() == 0:
+ break
+
+ current_g = next_g
+ super_to_orig = new_super_to_orig
+
+ return partitions
+
+ def _build_hierarchy_from_partitions(
+ self,
+ G: Union[nx.Graph, nx.DiGraph],
+ partitions: List[List[Set[Any]]],
+ ) -> CommunityHierarchy:
+ """Construct communities with O(|V|) parent-child resolution."""
+ communities: Dict[str, HierarchicalCommunity] = {}
+ level_communities: List[List[HierarchicalCommunity]] = []
+ is_directed = G.is_directed()
+
+ for level_idx, raw_level in enumerate(partitions):
+ sorted_raw = [
+ s
+ for s in sorted(
+ raw_level, key=lambda nodes: sorted(str(n) for n in nodes)
+ )
+ if s
+ ]
+ current_level_comms: List[HierarchicalCommunity] = []
+
+ for c_idx, node_set in enumerate(sorted_raw):
+ comm_id = f"{self.id_prefix}{level_idx}_{c_idx}"
+ entity_ids = sorted(str(n) for n in node_set)
+ sub_size = len(entity_ids)
+
+ sub = G.subgraph(node_set)
+ canonical_edges = canonicalize_edges(
+ sub.edges(data=True), directed=is_directed
+ )
+ internal_edges = sub.number_of_edges()
+
+ if is_directed:
+ total_incident = sum(
+ G.in_degree(n) + G.out_degree(n) for n in sub.nodes
+ )
+ external_edges = total_incident - 2 * internal_edges
+ else:
+ total_degree = sum(G.degree(n) for n in sub.nodes)
+ external_edges = total_degree - 2 * internal_edges
+
+ density = float(nx.density(sub))
+ denom = 2.0 * internal_edges + external_edges
+ conductance = (external_edges / denom) if denom > 0 else 0.0
+
+ metrics = {
+ "internal_edges": int(internal_edges),
+ "external_edges": max(0, int(external_edges)),
+ "density": float(density),
+ "conductance": float(conductance),
+ }
+
+ comm = HierarchicalCommunity(
+ id=comm_id,
+ level=level_idx,
+ index=c_idx,
+ entity_ids=entity_ids,
+ child_ids=[],
+ parent_id=None,
+ size=sub_size,
+ metrics=metrics,
+ content_hash="",
+ edges=canonical_edges,
+ directed=is_directed,
+ )
+ communities[comm_id] = comm
+ current_level_comms.append(comm)
+
+ level_communities.append(current_level_comms)
+
+ # O(|V|) parent-child resolution per level transition
+ for level_idx in range(len(level_communities) - 1):
+ children = level_communities[level_idx]
+ parents = level_communities[level_idx + 1]
+
+ node_to_parent: Dict[str, str] = {}
+ for p in parents:
+ for node in p.entity_ids:
+ node_to_parent[node] = p.id
+
+ for child in children:
+ if child.entity_ids:
+ parent_votes = [
+ node_to_parent[node]
+ for node in child.entity_ids
+ if node in node_to_parent
+ ]
+ if parent_votes:
+ parent_id = Counter(parent_votes).most_common(1)[0][0]
+ child.parent_id = parent_id
+ if parent_id in communities:
+ communities[parent_id].child_ids.append(child.id)
+
+ # Finalize child ordering and deterministic content hashes
+ for comm in communities.values():
+ comm.child_ids.sort()
+ comm.content_hash = compute_community_hash(
+ comm.level,
+ comm.index,
+ comm.entity_ids,
+ comm.child_ids,
+ edges=comm.edges,
+ directed=is_directed,
+ )
+
+ metadata = {
+ "algorithm": self.algorithm,
+ "fallback": self._fallback_used,
+ "levels_count": len(partitions),
+ }
+ return CommunityHierarchy(
+ communities=communities, graph=G, metadata=metadata
+ )
diff --git a/semantica/kg/methods.py b/semantica/kg/methods.py
index fb9475f0..83e51e85 100644
--- a/semantica/kg/methods.py
+++ b/semantica/kg/methods.py
@@ -145,6 +145,7 @@ from ..utils.logging import get_logger
from ..utils.custom_methods import CUSTOM_METHOD_FELL_BACK, call_custom_method
from .centrality_calculator import CentralityCalculator
from .community_detector import CommunityDetector
+from .community_hierarchy import CommunityHierarchy, CommunityHierarchyBuilder
from .config import kg_config
from .connectivity_analyzer import ConnectivityAnalyzer
from .entity_resolver import EntityResolver
@@ -891,6 +892,73 @@ def detect_communities_label_propagation(
raise
+def build_community_hierarchy(
+ graph: Any,
+ method: str = "louvain",
+ resolution: Union[float, List[float]] = 1.0,
+ seed: Optional[int] = 42,
+ **kwargs: Any,
+) -> CommunityHierarchy:
+ """
+ Build a multi-level community hierarchy from a knowledge graph.
+
+ Args:
+ graph: Input graph (NetworkX Graph/DiGraph, Semantica dict,
+ or KnowledgeGraph)
+ method: Community detection algorithm ("louvain" or "leiden",
+ default: "louvain")
+ resolution: Modularity resolution parameter or list of resolutions
+ seed: Random seed for deterministic reproducibility (default: 42)
+ **kwargs: Additional options passed to CommunityHierarchyBuilder
+
+ Returns:
+ CommunityHierarchy container
+ """
+ custom_method = method_registry.get("community_hierarchy", method)
+ if custom_method and custom_method is not build_community_hierarchy:
+ fallback = kwargs.pop("fallback_on_custom_error", False)
+ result = call_custom_method(
+ logger,
+ method,
+ custom_method,
+ graph,
+ fallback_on_custom_error=fallback,
+ resolution=resolution,
+ seed=seed,
+ **kwargs,
+ )
+ if result is not CUSTOM_METHOD_FELL_BACK:
+ return result
+
+ try:
+ algo = (
+ "louvain"
+ if method.lower().strip() == "default"
+ else method.lower().strip()
+ )
+ builder = CommunityHierarchyBuilder(
+ algorithm=algo,
+ resolution=resolution,
+ seed=seed,
+ **kwargs,
+ )
+ return builder.build(graph)
+ except Exception as e:
+ logger.error(f"Failed to build community hierarchy: {e}")
+ raise
+
+
+method_registry.register(
+ "community_hierarchy", "default", build_community_hierarchy
+)
+method_registry.register(
+ "community_hierarchy", "louvain", build_community_hierarchy
+)
+method_registry.register(
+ "community_hierarchy", "leiden", build_community_hierarchy
+)
+
+
# Helper functions
def _get_node_embedding(
diff --git a/semantica/kg/registry.py b/semantica/kg/registry.py
index 0c55c2f6..22972f56 100644
--- a/semantica/kg/registry.py
+++ b/semantica/kg/registry.py
@@ -59,6 +59,7 @@ class MethodRegistry:
"community": {},
"connectivity": {},
"temporal": {},
+ "community_hierarchy": {},
}
@classmethod
@@ -177,7 +178,8 @@ class AlgorithmRegistry:
"path_finding": {},
"link_prediction": {},
"centrality": {},
- "community_detection": {}
+ "community_detection": {},
+ "community_hierarchy": {},
}
self._metadata = {}
self._capabilities = {}
@@ -234,7 +236,15 @@ class AlgorithmRegistry:
Returns:
Algorithm class or None if not found
"""
- return self._algorithms.get(category, {}).get(name)
+ algo = self._algorithms.get(category, {}).get(name)
+ if (
+ algo is None and
+ category == "community_hierarchy" and
+ name in ("louvain", "leiden", "default")
+ ):
+ from .community_hierarchy import CommunityHierarchyBuilder
+ return CommunityHierarchyBuilder
+ return algo
def create_instance(self, category: str, name: str, **kwargs) -> Any:
"""
@@ -253,10 +263,13 @@ class AlgorithmRegistry:
"""
if name not in self._algorithms.get(category, {}):
raise ValueError(f"Algorithm {name} not found in category {category}")
- algorithm_class = self._algorithms[category][name]
+ algorithm_class = self.get(category, name)
if algorithm_class is None:
raise TypeError(f"Algorithm {name} has no implementation class registered")
+ if category == "community_hierarchy":
+ algo_name = "louvain" if name == "default" else name
+ kwargs.setdefault("algorithm", algo_name)
return algorithm_class(**kwargs)
def list_category(self, category: str) -> List[str]:
@@ -485,6 +498,76 @@ class AlgorithmRegistry:
capabilities=["iterative_labeling", "convergence_detection"]
)
+ # Hierarchical community detection
+ self.register(
+ "community_hierarchy",
+ "default",
+ None,
+ metadata={
+ "description": (
+ "Default hierarchical community detection (Louvain)"
+ ),
+ "parameters": [
+ "resolution", "seed", "threshold", "max_levels"
+ ],
+ "complexity": "O(V log V + E)",
+ "quality": "High",
+ "use_case": "Hierarchical GraphRAG clustering",
+ },
+ capabilities=[
+ "multi_level",
+ "coarsening",
+ "deterministic",
+ "indexed_hierarchy",
+ ],
+ )
+ self.register(
+ "community_hierarchy",
+ "louvain",
+ None,
+ metadata={
+ "description": (
+ "Multi-level Louvain hierarchical community detection"
+ ),
+ "parameters": [
+ "resolution", "seed", "threshold", "max_levels"
+ ],
+ "complexity": "O(V log V + E)",
+ "quality": "High",
+ "use_case": "Hierarchical GraphRAG clustering",
+ },
+ capabilities=[
+ "multi_level",
+ "coarsening",
+ "deterministic",
+ "indexed_hierarchy",
+ ],
+ )
+ self.register(
+ "community_hierarchy",
+ "leiden",
+ None,
+ metadata={
+ "description": (
+ "Multi-level Leiden hierarchical community detection "
+ "with refinement"
+ ),
+ "parameters": ["resolution", "seed", "max_levels"],
+ "complexity": "O(V log V + E)",
+ "quality": "High",
+ "use_case": (
+ "Hierarchical GraphRAG clustering with guaranteed "
+ "connectivity"
+ ),
+ },
+ capabilities=[
+ "multi_level",
+ "refinement",
+ "deterministic",
+ "indexed_hierarchy",
+ ],
+ )
+
# Global algorithm registry
algorithm_registry = AlgorithmRegistry()
diff --git a/tests/kg/test_community_hierarchy.py b/tests/kg/test_community_hierarchy.py
new file mode 100644
index 00000000..f039a20c
--- /dev/null
+++ b/tests/kg/test_community_hierarchy.py
@@ -0,0 +1,931 @@
+"""
+Tests for Hierarchical Community Structure and Multi-Level Coarsening.
+"""
+
+import networkx as nx
+import pytest
+
+from semantica.kg import (
+ CommunityHierarchy,
+ CommunityHierarchyBuilder,
+ HierarchicalCommunity,
+ KnowledgeGraph,
+ build_community_hierarchy,
+)
+from semantica.kg.registry import algorithm_registry, method_registry
+
+
+# ---------------------------------------------------------------------------
+# HierarchicalCommunity Dataclass Tests
+# ---------------------------------------------------------------------------
+
+class TestHierarchicalCommunity:
+ """Unit tests for HierarchicalCommunity dataclass."""
+
+ def test_create_hierarchical_community_defaults(self):
+ comm = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["node_b", "node_a"],
+ )
+ assert comm.id == "c_0_0"
+ assert comm.level == 0
+ assert comm.index == 0
+ assert comm.entity_ids == ["node_a", "node_b"]
+ assert comm.size == 2
+ assert comm.child_ids == []
+ assert comm.parent_id is None
+ assert comm.metrics == {}
+ assert len(comm.content_hash) == 64
+
+ def test_content_hash_deterministic(self):
+ comm1 = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["z", "a", "m"],
+ child_ids=["c_prev_2", "c_prev_1"],
+ )
+ comm2 = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["a", "m", "z"],
+ child_ids=["c_prev_1", "c_prev_2"],
+ )
+ assert comm1.content_hash == comm2.content_hash
+
+ def test_content_hash_changes_on_difference(self):
+ comm1 = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["a", "b"],
+ )
+ comm2 = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["a", "c"],
+ )
+ assert comm1.content_hash != comm2.content_hash
+
+ def test_to_dict_and_from_dict(self):
+ comm = HierarchicalCommunity(
+ id="c_1_2",
+ level=1,
+ index=2,
+ entity_ids=["n1", "n2"],
+ child_ids=["c_0_1"],
+ parent_id="c_2_0",
+ metrics={"density": 0.75, "internal_edges": 1},
+ )
+ data = comm.to_dict()
+ restored = HierarchicalCommunity.from_dict(data)
+ assert restored.id == comm.id
+ assert restored.level == comm.level
+ assert restored.index == comm.index
+ assert restored.entity_ids == comm.entity_ids
+ assert restored.child_ids == comm.child_ids
+ assert restored.parent_id == comm.parent_id
+ assert restored.size == comm.size
+ assert restored.metrics == comm.metrics
+ assert restored.content_hash == comm.content_hash
+
+
+# ---------------------------------------------------------------------------
+# CommunityHierarchy Container Tests
+# ---------------------------------------------------------------------------
+
+class TestCommunityHierarchyContainer:
+ """Unit tests for CommunityHierarchy container."""
+
+ def test_empty_hierarchy(self):
+ hierarchy = CommunityHierarchy()
+ assert hierarchy.is_empty is True
+ assert len(hierarchy) == 0
+ assert hierarchy.levels == []
+ assert hierarchy.max_level == -1
+ assert hierarchy.root_communities == []
+ assert hierarchy.leaf_communities == []
+ assert hierarchy.get_community("c_0_0") is None
+ assert hierarchy.get_community_for_node("node_1") is None
+
+ def test_container_indexing_and_traversal(self):
+ c0_0 = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["n1", "n2"],
+ parent_id="c_1_0",
+ )
+ c0_1 = HierarchicalCommunity(
+ id="c_0_1",
+ level=0,
+ index=1,
+ entity_ids=["n3"],
+ parent_id="c_1_0",
+ )
+ c1_0 = HierarchicalCommunity(
+ id="c_1_0",
+ level=1,
+ index=0,
+ entity_ids=["n1", "n2", "n3"],
+ child_ids=["c_0_0", "c_0_1"],
+ parent_id=None,
+ )
+
+ hierarchy = CommunityHierarchy([c0_0, c0_1, c1_0])
+
+ assert hierarchy.is_empty is False
+ assert len(hierarchy) == 3
+ assert hierarchy.levels == [0, 1]
+ assert hierarchy.max_level == 1
+ assert len(hierarchy.root_communities) == 1
+ assert hierarchy.root_communities[0].id == "c_1_0"
+ assert len(hierarchy.leaf_communities) == 2
+ assert [c.id for c in hierarchy.leaf_communities] == ["c_0_0", "c_0_1"]
+
+ # get_community
+ assert hierarchy.get_community("c_0_0") == c0_0
+ assert hierarchy.get_community("nonexistent") is None
+
+ # get_communities_at_level
+ assert hierarchy.get_communities_at_level(0) == [c0_0, c0_1]
+ assert hierarchy.get_communities_at_level(1) == [c1_0]
+ assert hierarchy.get_communities_at_level(99) == []
+
+ # get_children
+ assert hierarchy.get_children("c_1_0") == [c0_0, c0_1]
+ assert hierarchy.get_children(c1_0) == [c0_0, c0_1]
+ assert hierarchy.get_children("c_0_0") == []
+
+ # get_parent
+ assert hierarchy.get_parent("c_0_0") == c1_0
+ assert hierarchy.get_parent(c0_1) == c1_0
+ assert hierarchy.get_parent("c_1_0") is None
+
+ # get_community_for_node (O(1))
+ assert hierarchy.get_community_for_node("n1") == c0_0
+ assert hierarchy.get_community_for_node("n1", level=0) == c0_0
+ assert hierarchy.get_community_for_node("n1", level=1) == c1_0
+ assert hierarchy.get_community_for_node("n3", level=0) == c0_1
+ assert hierarchy.get_community_for_node("n3", level=1) == c1_0
+ assert hierarchy.get_community_for_node("missing_node") is None
+ assert hierarchy.get_community_for_node("n1", level=99) is None
+
+ # Container dunder methods
+ assert "c_0_0" in hierarchy
+ assert "c_9_9" not in hierarchy
+ assert hierarchy["c_0_0"] == c0_0
+ all_comms = list(hierarchy)
+ assert len(all_comms) == 3
+
+ def test_to_dict_and_to_json_roundtrip(self):
+ c0 = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["a", "b"]
+ )
+ hierarchy = CommunityHierarchy([c0])
+
+ d = hierarchy.to_dict()
+ restored_from_dict = CommunityHierarchy.from_dict(d)
+ assert len(restored_from_dict) == 1
+ assert restored_from_dict["c_0_0"].entity_ids == ["a", "b"]
+ matched_comm = restored_from_dict.get_community_for_node("a")
+ assert matched_comm == restored_from_dict["c_0_0"]
+
+ json_str = hierarchy.to_json()
+ assert isinstance(json_str, str)
+ restored_from_json = CommunityHierarchy.from_json(json_str)
+ assert len(restored_from_json) == 1
+ assert restored_from_json["c_0_0"].id == "c_0_0"
+
+ def test_get_subgraph_networkx(self):
+ g = nx.Graph()
+ g.add_edge("1", "2")
+ g.add_edge("2", "3")
+ g.add_edge("3", "4")
+
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["1", "2"]
+ )
+ hierarchy = CommunityHierarchy([c], graph=g)
+
+ sub = hierarchy.get_subgraph("c_0_0")
+ assert isinstance(sub, nx.Graph)
+ assert set(sub.nodes()) == {"1", "2"}
+ assert sub.has_edge("1", "2")
+ assert not sub.has_edge("2", "3")
+
+ def test_get_subgraph_knowledge_graph(self):
+ kg = KnowledgeGraph(
+ entities=[{"id": "e1"}, {"id": "e2"}, {"id": "e3"}],
+ relationships=[
+ {"source": "e1", "target": "e2", "type": "KNOWS"},
+ {"source": "e2", "target": "e3", "type": "KNOWS"},
+ ],
+ metadata={"source": "test"},
+ )
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["e1", "e2"]
+ )
+ hierarchy = CommunityHierarchy([c])
+
+ sub = hierarchy.get_subgraph("c_0_0", graph=kg)
+ assert isinstance(sub, KnowledgeGraph)
+ assert len(sub.entities) == 2
+ assert len(sub.relationships) == 1
+ assert sub.relationships[0]["source"] == "e1"
+
+ def test_get_subgraph_dict_representations(self):
+ kg_dict = {
+ "entities": [{"id": "x"}, {"id": "y"}, {"id": "z"}],
+ "relationships": [
+ {"source": "x", "target": "y", "weight": 1.0},
+ {"source": "y", "target": "z", "weight": 1.0},
+ ],
+ }
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["x", "y"]
+ )
+ hierarchy = CommunityHierarchy([c], graph=kg_dict)
+
+ sub_kg = hierarchy.get_subgraph("c_0_0")
+ assert len(sub_kg["entities"]) == 2
+ assert len(sub_kg["relationships"]) == 1
+
+ nodes_dict = {
+ "nodes": [{"id": "p"}, {"id": "q"}],
+ "edges": [{"source": "p", "target": "q"}],
+ }
+ c2 = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["p", "q"]
+ )
+ hierarchy2 = CommunityHierarchy([c2], graph=nodes_dict)
+ sub_nodes = hierarchy2.get_subgraph("c_0_0")
+ assert len(sub_nodes["nodes"]) == 2
+ assert len(sub_nodes["edges"]) == 1
+
+ def test_get_subgraph_errors(self):
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["a"]
+ )
+ hierarchy = CommunityHierarchy([c])
+
+ with pytest.raises(ValueError, match="graph must be provided"):
+ hierarchy.get_subgraph("c_0_0")
+
+ with pytest.raises(KeyError, match="not found"):
+ hierarchy.get_subgraph("c_unknown", graph=nx.Graph())
+
+
+# ---------------------------------------------------------------------------
+# CommunityHierarchyBuilder Invariant Tests
+# ---------------------------------------------------------------------------
+
+class TestCommunityHierarchyBuilder:
+ """Core tests for CommunityHierarchyBuilder algorithms and invariants."""
+
+ def _verify_all_hierarchy_invariants(
+ self, graph: nx.Graph, hierarchy: CommunityHierarchy
+ ):
+ """Helper to assert all structural and mathematical invariants."""
+ assert not hierarchy.is_empty
+ all_graph_nodes = {str(n) for n in graph.nodes()}
+ levels = hierarchy.levels
+ assert len(levels) >= 1
+
+ for level in levels:
+ level_comms = hierarchy.get_communities_at_level(level)
+ assert len(level_comms) > 0
+
+ # Disjoint and complete coverage invariant
+ level_nodes = []
+ for comm in level_comms:
+ assert comm.level == level
+ assert comm.size == len(comm.entity_ids)
+ level_nodes.extend(comm.entity_ids)
+
+ assert set(level_nodes) == all_graph_nodes
+ assert len(level_nodes) == len(all_graph_nodes)
+
+ # Inverted index consistency
+ for comm in level_comms:
+ for node_id in comm.entity_ids:
+ indexed_comm = hierarchy.get_community_for_node(
+ node_id, level=level
+ )
+ assert indexed_comm is not None
+ assert indexed_comm.id == comm.id
+
+ # Hierarchical containment invariants between adjacent levels
+ for l_idx in range(len(levels) - 1):
+ child_level = levels[l_idx]
+ parent_level = levels[l_idx + 1]
+
+ children = hierarchy.get_communities_at_level(child_level)
+ parents = hierarchy.get_communities_at_level(parent_level)
+ parent_map = {p.id: p for p in parents}
+
+ for child in children:
+ assert child.parent_id is not None
+ assert child.parent_id in parent_map
+ parent = parent_map[child.parent_id]
+ # Child entity set must be a subset of parent entity set
+ assert set(child.entity_ids).issubset(set(parent.entity_ids))
+ assert child.id in parent.child_ids
+
+ # Parent entity set must be the exact union of child entity sets
+ for parent in parents:
+ assert len(parent.child_ids) > 0
+ union_child_entities = set()
+ for cid in parent.child_ids:
+ c = hierarchy.get_community(cid)
+ assert c is not None
+ union_child_entities.update(c.entity_ids)
+ assert set(parent.entity_ids) == union_child_entities
+
+ # Root communities must have parent_id == None
+ top_level = hierarchy.max_level
+ top_comms = hierarchy.get_communities_at_level(top_level)
+ for c in top_comms:
+ assert c.parent_id is None
+
+ # Leaf communities must have child_ids == []
+ bottom_level = levels[0]
+ bottom_comms = hierarchy.get_communities_at_level(bottom_level)
+ for c in bottom_comms:
+ assert c.child_ids == []
+
+ def test_build_louvain_karate_club(self):
+ g = nx.karate_club_graph()
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(g)
+
+ assert hierarchy.max_level >= 1
+ self._verify_all_hierarchy_invariants(g, hierarchy)
+
+ def test_build_leiden_karate_club(self):
+ g = nx.karate_club_graph()
+ builder = CommunityHierarchyBuilder(algorithm="leiden", seed=42)
+ hierarchy = builder.build(g)
+
+ assert hierarchy.max_level >= 1
+ self._verify_all_hierarchy_invariants(g, hierarchy)
+
+ def test_non_merging_communities_invariant(self):
+ # Construct graph where one cluster merges, but another does not.
+ g = nx.Graph()
+ for u in range(10):
+ for v in range(u + 1, 10):
+ g.add_edge(str(u), str(v))
+ g.add_edge("isolated_a", "isolated_b")
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(g)
+
+ self._verify_all_hierarchy_invariants(g, hierarchy)
+
+ if hierarchy.max_level >= 1:
+ for parent in hierarchy.get_communities_at_level(1):
+ if len(parent.child_ids) == 1:
+ child = hierarchy.get_community(parent.child_ids[0])
+ assert child is not None
+ assert set(parent.entity_ids) == set(child.entity_ids)
+
+ def test_directed_graph_with_weakly_connected_refinement(self):
+ g = nx.DiGraph()
+ g.add_edges_from([("1", "2"), ("2", "3"), ("3", "1")])
+ g.add_edges_from([("4", "5"), ("5", "6"), ("6", "4")])
+ g.add_edge("3", "4")
+
+ builder = CommunityHierarchyBuilder(
+ algorithm="louvain", seed=42, directed=True
+ )
+ hierarchy = builder.build(g)
+
+ self._verify_all_hierarchy_invariants(g, hierarchy)
+
+ for comm in hierarchy:
+ sub = g.subgraph(comm.entity_ids)
+ assert nx.is_weakly_connected(sub)
+
+ def test_isolated_nodes_handling(self):
+ g = nx.erdos_renyi_graph(20, 0.15, seed=42)
+ g.add_node(999)
+ g.add_node(1000)
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(g)
+
+ self._verify_all_hierarchy_invariants(g, hierarchy)
+
+ for level in hierarchy.levels:
+ c999 = hierarchy.get_community_for_node("999", level=level)
+ c1000 = hierarchy.get_community_for_node("1000", level=level)
+ assert c999 is not None
+ assert c1000 is not None
+ assert "999" in c999.entity_ids
+ assert "1000" in c1000.entity_ids
+
+ def test_empty_graph(self):
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(nx.Graph())
+ assert hierarchy.is_empty is True
+ assert hierarchy.levels == []
+ assert hierarchy.max_level == -1
+
+ def test_single_node_graph(self):
+ g = nx.Graph()
+ g.add_node("single")
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(g)
+
+ assert not hierarchy.is_empty
+ assert hierarchy.levels == [0]
+ assert hierarchy.max_level == 0
+ comm = hierarchy.get_community_for_node("single")
+ assert comm is not None
+ assert comm.entity_ids == ["single"]
+ assert comm.parent_id is None
+ assert comm.child_ids == []
+
+ def test_deterministic_reproducibility(self):
+ g = nx.erdos_renyi_graph(40, 0.1, seed=123)
+
+ builder1 = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ builder2 = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+
+ h1 = builder1.build(g)
+ h2 = builder2.build(g)
+
+ assert h1.to_dict() == h2.to_dict()
+
+ builder_leiden1 = CommunityHierarchyBuilder(
+ algorithm="leiden", seed=42
+ )
+ builder_leiden2 = CommunityHierarchyBuilder(
+ algorithm="leiden", seed=42
+ )
+
+ hl1 = builder_leiden1.build(g)
+ hl2 = builder_leiden2.build(g)
+
+ assert hl1.to_dict() == hl2.to_dict()
+
+ def test_knowledge_graph_dataclass_input(self):
+ kg = KnowledgeGraph(
+ entities=[{"id": f"n{i}"} for i in range(10)],
+ relationships=[
+ {"source": f"n{i}", "target": f"n{i+1}", "weight": 1.0}
+ for i in range(9)
+ ],
+ )
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(kg)
+
+ assert not hierarchy.is_empty
+ for i in range(10):
+ assert hierarchy.get_community_for_node(f"n{i}") is not None
+
+ def test_semantica_dict_input(self):
+ data = {
+ "entities": [{"id": "a"}, {"id": "b"}, {"id": "c"}],
+ "relationships": [
+ {"source": "a", "target": "b"},
+ {"source": "b", "target": "c"},
+ ],
+ }
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(data)
+
+ assert not hierarchy.is_empty
+ assert hierarchy.get_community_for_node("a") is not None
+
+ def test_max_levels_constraint(self):
+ g = nx.erdos_renyi_graph(60, 0.08, seed=42)
+ builder = CommunityHierarchyBuilder(
+ algorithm="louvain", seed=42, max_levels=1
+ )
+ hierarchy = builder.build(g)
+
+ assert len(hierarchy.levels) == 1
+ assert hierarchy.max_level == 0
+
+ def test_unsupported_algorithm_raises(self):
+ with pytest.raises(ValueError, match="Unsupported algorithm"):
+ CommunityHierarchyBuilder(algorithm="invalid_algo")
+
+ def test_community_metrics(self):
+ g = nx.Graph()
+ g.add_edges_from([("1", "2"), ("2", "3"), ("3", "1")])
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ hierarchy = builder.build(g)
+
+ comm = hierarchy.get_community_for_node("1")
+ assert comm is not None
+ assert comm.metrics["internal_edges"] == 3
+ assert comm.metrics["external_edges"] == 0
+ assert comm.metrics["density"] == 1.0
+ assert comm.metrics["conductance"] == 0.0
+
+
+# ---------------------------------------------------------------------------
+# Integration & Registry Tests
+# ---------------------------------------------------------------------------
+
+class TestIntegrationAndRegistry:
+ """Tests for integration into semantica.kg, methods.py, and registry.py."""
+
+ def test_build_community_hierarchy_convenience_function(self):
+ g = nx.karate_club_graph()
+ h_louvain = build_community_hierarchy(g, method="louvain", seed=42)
+ assert isinstance(h_louvain, CommunityHierarchy)
+ assert not h_louvain.is_empty
+
+ h_leiden = build_community_hierarchy(g, method="leiden", seed=42)
+ assert isinstance(h_leiden, CommunityHierarchy)
+ assert not h_leiden.is_empty
+
+ def test_method_registry_integration(self):
+ default_fn = method_registry.get("community_hierarchy", "default")
+ louvain_fn = method_registry.get("community_hierarchy", "louvain")
+ leiden_fn = method_registry.get("community_hierarchy", "leiden")
+
+ assert callable(default_fn)
+ assert callable(louvain_fn)
+ assert callable(leiden_fn)
+
+ def test_algorithm_registry_integration(self):
+ cls_louvain = algorithm_registry.get("community_hierarchy", "louvain")
+ cls_leiden = algorithm_registry.get("community_hierarchy", "leiden")
+ cls_default = algorithm_registry.get("community_hierarchy", "default")
+
+ assert cls_louvain is CommunityHierarchyBuilder
+ assert cls_leiden is CommunityHierarchyBuilder
+ assert cls_default is CommunityHierarchyBuilder
+
+ inst_louvain = algorithm_registry.create_instance(
+ "community_hierarchy", "louvain", seed=42
+ )
+ assert isinstance(inst_louvain, CommunityHierarchyBuilder)
+ assert inst_louvain.algorithm == "louvain"
+
+ inst_leiden = algorithm_registry.create_instance(
+ "community_hierarchy", "leiden", seed=42
+ )
+ assert isinstance(inst_leiden, CommunityHierarchyBuilder)
+ assert inst_leiden.algorithm == "leiden"
+
+ inst_default = algorithm_registry.create_instance(
+ "community_hierarchy", "default", seed=42
+ )
+ assert isinstance(inst_default, CommunityHierarchyBuilder)
+ assert inst_default.algorithm == "louvain"
+
+ def test_build_community_hierarchy_default_method(self):
+ g = nx.karate_club_graph()
+ h_default = build_community_hierarchy(g, method="default", seed=42)
+ assert isinstance(h_default, CommunityHierarchy)
+ assert not h_default.is_empty
+
+
+# ---------------------------------------------------------------------------
+# Extended Edge Case & Robustness Tests
+# ---------------------------------------------------------------------------
+
+class TestCommunityHierarchyEdgeCases:
+ """Rigorous robustness tests for edge cases and input variants."""
+
+ def test_entity_and_child_ids_deduplication(self):
+ comm = HierarchicalCommunity(
+ id="c_0_0",
+ level=0,
+ index=0,
+ entity_ids=["b", "a", "b", "a"],
+ child_ids=["c_prev_1", "c_prev_1"],
+ )
+ assert comm.entity_ids == ["a", "b"]
+ assert comm.size == 2
+ assert comm.child_ids == ["c_prev_1"]
+
+ def test_multigraph_parallel_edges_weight_aggregation(self):
+ mg = nx.MultiGraph()
+ mg.add_edge("a", "b", weight=2.0)
+ mg.add_edge("a", "b", weight=3.0)
+ mg.add_edge("b", "c", weight=1.0)
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ converted = builder._to_networkx(mg)
+ assert converted.get_edge_data("a", "b")["weight"] == 5.0
+ assert converted.get_edge_data("b", "c")["weight"] == 1.0
+
+ hierarchy = builder.build(mg)
+ assert not hierarchy.is_empty
+
+ def test_multidigraph_parallel_edges_weight_aggregation(self):
+ mdg = nx.MultiDiGraph()
+ mdg.add_edge("x", "y", weight=1.5)
+ mdg.add_edge("x", "y", weight=2.5)
+
+ builder = CommunityHierarchyBuilder(
+ algorithm="louvain", directed=True, seed=42
+ )
+ converted = builder._to_networkx(mdg)
+ assert converted.is_directed()
+ assert converted.get_edge_data("x", "y")["weight"] == 4.0
+
+ def test_empty_and_invalid_resolution_handling(self):
+ builder_empty = CommunityHierarchyBuilder(resolution=[])
+ assert builder_empty.resolution == [1.0]
+
+ with pytest.raises(ValueError, match="Resolution.*must be positive"):
+ CommunityHierarchyBuilder(resolution=0.0)
+
+ with pytest.raises(ValueError, match="Resolution.*must be positive"):
+ CommunityHierarchyBuilder(resolution=[1.0, -0.5])
+
+ def test_invalid_max_levels_handling(self):
+ with pytest.raises(ValueError, match="max_levels.*positive"):
+ CommunityHierarchyBuilder(max_levels=0)
+
+ with pytest.raises(ValueError, match="max_levels.*positive"):
+ CommunityHierarchyBuilder(max_levels=-2)
+
+ def test_leiden_multi_resolution_list(self):
+ g = nx.erdos_renyi_graph(30, 0.15, seed=42)
+ builder = CommunityHierarchyBuilder(
+ algorithm="leiden", resolution=[1.5, 0.8], seed=42
+ )
+ hierarchy = builder.build(g)
+ assert not hierarchy.is_empty
+ assert hierarchy.max_level >= 0
+
+ def test_get_subgraph_adjacency_dict(self):
+ adj = {
+ "node_1": ["node_2"],
+ "node_2": ["node_1", "node_3"],
+ "node_3": ["node_2"],
+ }
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["node_1", "node_2"]
+ )
+ hierarchy = CommunityHierarchy([c])
+ sub = hierarchy.get_subgraph("c_0_0", graph=adj)
+ assert isinstance(sub, dict)
+ assert set(sub.keys()) == {"node_1", "node_2"}
+ assert sub["node_1"] == ["node_2"]
+ assert sub["node_2"] == ["node_1"]
+
+ def test_get_subgraph_source_id_target_id(self):
+ kg = KnowledgeGraph(
+ entities=[{"id": "e1"}, {"id": "e2"}, {"id": "e3"}],
+ relationships=[
+ {"source_id": "e1", "target_id": "e2", "type": "KNOWS"},
+ {"source_id": "e2", "target_id": "e3", "type": "KNOWS"},
+ ],
+ )
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["e1", "e2"]
+ )
+ hierarchy = CommunityHierarchy([c])
+ sub = hierarchy.get_subgraph("c_0_0", graph=kg)
+ assert isinstance(sub, KnowledgeGraph)
+ assert len(sub.entities) == 2
+ assert len(sub.relationships) == 1
+ assert sub.relationships[0]["source_id"] == "e1"
+
+ def test_get_community_for_node_lowest_available_level(self):
+ c = HierarchicalCommunity(
+ id="c_2_0", level=2, index=0, entity_ids=["alpha", "beta"]
+ )
+ hierarchy = CommunityHierarchy([c])
+ matched = hierarchy.get_community_for_node("alpha", level=None)
+ assert matched is not None
+ assert matched.id == "c_2_0"
+
+ def test_from_dict_with_communities_as_list(self):
+ c = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["n1"]
+ )
+ data = {"communities": [c.to_dict()]}
+ restored = CommunityHierarchy.from_dict(data)
+ assert len(restored) == 1
+ assert "c_0_0" in restored
+
+ def test_edge_weight_sanitization(self):
+ g = nx.Graph()
+ g.add_edge("1", "2", weight="invalid")
+ g.add_edge("2", "3", weight=-5.0)
+ g.add_edge("3", "4", weight=float("nan"))
+ g.add_edge("4", "5", weight=None)
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ converted = builder._to_networkx(g)
+ assert converted.get_edge_data("1", "2")["weight"] == 1.0
+ assert converted.get_edge_data("2", "3")["weight"] == 0.0
+ assert converted.get_edge_data("3", "4")["weight"] == 1.0
+ assert converted.get_edge_data("4", "5")["weight"] == 1.0
+
+ hierarchy = builder.build(g)
+ assert not hierarchy.is_empty
+
+ def test_edge_weight_change_invalidates_content_hash(self):
+ g1 = nx.Graph()
+ g1.add_edge("a", "b", weight=1.0)
+ g1.add_edge("b", "c", weight=1.0)
+ g1.add_edge("a", "c", weight=1.0)
+
+ g2 = nx.Graph()
+ g2.add_edge("a", "b", weight=5.0)
+ g2.add_edge("b", "c", weight=1.0)
+ g2.add_edge("a", "c", weight=1.0)
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ h1 = builder.build(g1)
+ h2 = builder.build(g2)
+
+ c1 = h1.get_community_for_node("a", level=0)
+ c2 = h2.get_community_for_node("a", level=0)
+ assert c1 is not None and c2 is not None
+ assert c1.entity_ids == c2.entity_ids
+ assert c1.content_hash != c2.content_hash
+
+ def test_edge_topology_change_invalidates_content_hash(self):
+ g1 = nx.Graph()
+ g1.add_edge("a", "b")
+ g1.add_edge("b", "c")
+ g1.add_edge("a", "c")
+
+ g2 = nx.Graph()
+ g2.add_edge("a", "b")
+ g2.add_edge("b", "c")
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ h1 = builder.build(g1)
+ h2 = builder.build(g2)
+
+ c1 = h1.get_community_for_node("a", level=0)
+ c2 = h2.get_community_for_node("a", level=0)
+ assert c1 is not None and c2 is not None
+ assert c1.entity_ids == c2.entity_ids
+ assert c1.content_hash != c2.content_hash
+
+ def test_node_identifier_collision_networkx_raises(self):
+ g = nx.Graph()
+ g.add_node(1)
+ g.add_node("1")
+ g.add_edge(1, 2)
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ with pytest.raises(ValueError, match="collision detected"):
+ builder.build(g)
+
+ def test_node_identifier_collision_dict_entities_raises(self):
+ graph_dict = {
+ "entities": [{"id": 1}, {"id": "1"}],
+ "relationships": [{"source": 1, "target": 2}],
+ }
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ with pytest.raises(ValueError, match="collision detected"):
+ builder.build(graph_dict)
+
+ def test_node_identifier_collision_adjacency_dict_raises(self):
+ adj_dict = {
+ 1: [2],
+ "1": [3],
+ }
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ with pytest.raises(ValueError, match="collision detected"):
+ builder.build(adj_dict)
+
+ def test_louvain_multi_resolution_list(self):
+ g = nx.karate_club_graph()
+ builder = CommunityHierarchyBuilder(
+ algorithm="louvain",
+ resolution=[3.0, 1.0, 0.3],
+ seed=42,
+ )
+ hierarchy = builder.build(g)
+ assert len(hierarchy.levels) >= 1
+ assert hierarchy.metadata.get("algorithm") == "louvain"
+ assert hierarchy.metadata.get("fallback") is False
+
+ def test_custom_method_receives_resolution_and_seed(self):
+ captured_kwargs = {}
+
+ def dummy_custom(graph, **kwargs):
+ captured_kwargs.update(kwargs)
+ return CommunityHierarchy(communities={}, graph=graph)
+
+ method_registry.register(
+ "community_hierarchy", "test_custom_method_args", dummy_custom
+ )
+
+ g = nx.path_graph(3)
+ res = build_community_hierarchy(
+ g,
+ method="test_custom_method_args",
+ resolution=2.75,
+ seed=999,
+ )
+ assert isinstance(res, CommunityHierarchy)
+ assert captured_kwargs.get("resolution") == 2.75
+ assert captured_kwargs.get("seed") == 999
+
+ def test_hierarchy_metadata_to_dict_and_from_dict(self):
+ c0 = HierarchicalCommunity(
+ id="c_0_0", level=0, index=0, entity_ids=["a", "b"]
+ )
+ hierarchy = CommunityHierarchy(
+ [c0], metadata={"algorithm": "leiden", "fallback": False}
+ )
+ d = hierarchy.to_dict()
+ assert d["metadata"] == {"algorithm": "leiden", "fallback": False}
+ restored = CommunityHierarchy.from_dict(d)
+ assert restored.metadata == {"algorithm": "leiden", "fallback": False}
+
+ def test_canonicalize_edges_idempotency_and_no_nested_attributes(self):
+ from semantica.kg.community_hierarchy import canonicalize_edges
+
+ raw = [("a", "b", {"weight": 2.5, "label": "FRIEND"})]
+ c1 = canonicalize_edges(raw)
+ c2 = canonicalize_edges(c1)
+ c3 = canonicalize_edges(c2)
+
+ assert c1 == c2 == c3
+ assert "attributes" in c1[0]
+ assert "attributes" not in c1[0]["attributes"]
+ assert c1[0]["attributes"]["weight"] == 2.5
+ assert c1[0]["attributes"]["label"] == "FRIEND"
+
+ def test_directed_edge_endpoints_orientation_preserved(self):
+ g = nx.DiGraph()
+ nx.add_cycle(g, ["z", "a", "b"])
+
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+ h = builder.build(g)
+ c = h.get_community_for_node("z", level=0)
+ assert c is not None
+ assert c.directed is True
+
+ edge_pairs = [(e["source"], e["target"]) for e in c.edges]
+ assert ("z", "a") in edge_pairs
+ assert ("a", "b") in edge_pairs
+ assert ("b", "z") in edge_pairs
+ assert ("a", "z") not in edge_pairs
+
+ d = c.to_dict()
+ assert d["directed"] is True
+ c_restored = HierarchicalCommunity.from_dict(d)
+ assert c_restored.edges == c.edges
+ assert c_restored.directed is True
+
+ def test_node_collision_in_relationships_without_entities_raises(self):
+ g = {
+ "relationships": [
+ {"source": 1, "target": 2},
+ {"source": "1", "target": 3},
+ ]
+ }
+ builder = CommunityHierarchyBuilder(seed=42)
+ with pytest.raises(ValueError, match="collision detected"):
+ builder.build(g)
+
+ def test_node_collision_in_adjacency_neighbors_raises(self):
+ adj = {1: [2], 3: ["2"]}
+ builder = CommunityHierarchyBuilder(seed=42)
+ with pytest.raises(ValueError, match="collision detected"):
+ builder.build(adj)
+
+ def test_builder_fallback_flag_resets_on_subsequent_builds(self):
+ builder = CommunityHierarchyBuilder(algorithm="louvain", seed=42)
+
+ g_fail = nx.Graph()
+ g_fail.add_edge("a", "b", weight=0.0)
+ h1 = builder.build(g_fail)
+ assert h1.metadata.get("fallback") is True
+
+ g_ok = nx.karate_club_graph()
+ h2 = builder.build(g_ok)
+ assert h2.metadata.get("fallback") is False
+
+ def test_custom_weight_attribute_name_preserved(self):
+ g = nx.Graph()
+ g.add_edge("a", "b", score=10.0)
+ g.add_edge("b", "c", score=10.0)
+ g.add_edge("a", "c", score=10.0)
+ g.add_edge("c", "d", score=0.1)
+ g.add_edge("d", "e", score=10.0)
+ g.add_edge("e", "f", score=10.0)
+ g.add_edge("d", "f", score=10.0)
+
+ builder = CommunityHierarchyBuilder(
+ algorithm="louvain", weight="score", seed=42
+ )
+ h = builder.build(g)
+ c0 = h.get_community_for_node("a", level=0)
+ assert c0 is not None
+ assert all("score" in e["attributes"] for e in c0.edges)
+ assert all("weight" not in e["attributes"] for e in c0.edges)