# How to Perform Graph Analytics: Centrality and Community Detection in Semantica

> Discover how to perform graph analytics like centrality and community detection using Semantica's specialized engines. Accelerate node importance scoring and cluster detection with NetworkX.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: how-to-guide
- Published: 2026-08-14

---

**Semantica provides two dedicated engines—`CentralityCalculator` and `CommunityDetector`—that enable graph analytics with optional NetworkX acceleration for computing node importance scores and detecting community clusters.**

The `semantica-agi/semantica` repository ships with built-in graph analytics capabilities that work out-of-the-box without external dependencies. This guide covers how to compute centrality metrics and run community detection algorithms using the framework's pure-Python implementations, with automatic upgrades to NetworkX-backed performance when available.

## Understanding the Centrality Engine

The **centrality engine** in Semantica measures node importance through multiple well-established graph algorithms. According to the source code in [`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py), the `CentralityCalculator` class provides a unified interface for degree, betweenness, closeness, eigenvector, and PageRank centrality.

### How Centrality Calculation Works

The engine follows a consistent execution pattern across all algorithms:

- **NetworkX detection**: On initialization, the calculator attempts to import NetworkX and sets `self.use_networkx`. When available, calculations delegate to optimized NetworkX implementations.
- **Fallback mode**: Without NetworkX, the engine builds an adjacency list via `_build_adjacency` and runs pure-Python algorithms.
- **Standardized output**: Every method returns a dictionary containing raw scores, sorted rankings, and metadata such as `max_degree` or `total_nodes`.

The `calculate_all_centrality()` helper invokes individual methods sequentially, producing a comprehensive report in a single call.

### Computing Multiple Centrality Metrics

```python
from semantica.kg import CentralityCalculator

# Example graph in Semantica's internal format

graph = {
    "entities": [{"id": "A"}, {"id": "B"}, {"id": "C"}],
    "relationships": [
        {"source": "A", "target": "B"},
        {"source": "B", "target": "C"},
        {"source": "C", "target": "A"},
    ],
}

calc = CentralityCalculator()
all_centrality = calc.calculate_all_centrality(graph)

print("Degree centrality:", all_centrality["degree"]["centrality"])
print("PageRank:", all_centrality["pagerank"]["centrality"])

```

## Understanding the Community Detection Engine

The **community detection engine** identifies densely connected subgraphs using multiple algorithmic approaches. As implemented in [`semantica/kg/community_detector.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/community_detector.py), the `CommunityDetector` class supports **Louvain**, **Leiden**, **overlapping k-clique**, and **label propagation** methods.

### How Community Detection Works

The engine shares architectural patterns with the centrality calculator:

- **Algorithm dispatch**: The `detect_communities()` method routes to concrete implementations based on the `algorithm` parameter (also accessible via the `method` alias).
- **NetworkX integration**: When available, the engine leverages NetworkX's `greedy_modularity_communities`, `k_clique_communities`, and other optimized algorithms.
- **Pure-Python fallback**: Without NetworkX, `_basic_community_detection` and `_basic_overlapping_detection` provide lightweight greedy heuristics.
- **Rich results**: Output includes community lists, node-to-community mappings, modularity scores, and algorithm metadata.

Additional helpers—`calculate_community_metrics()` and `analyze_community_structure()`—expose quality metrics and intra-/inter-community edge statistics.

### Running Louvain Community Detection

```python
from semantica.kg import CommunityDetector

detector = CommunityDetector()
result = detector.detect_communities(graph, algorithm="louvain")

print("Found", len(result["communities"]), "communities")
print("Modularity:", result["modularity"])
print("Node assignments:", result["node_assignments"])

```

### Processing Large Graphs with Label Propagation

For graphs exceeding the `chunk_size` threshold, the engine automatically activates chunked processing to manage memory efficiently:

```python
detector = CommunityDetector()
communities = detector.detect_communities(
    graph,
    algorithm="label_propagation",
    max_iterations=200,
    random_seed=42,
    chunk_size=5000,   # activates chunked mode for >5k nodes

)

print("Communities detected:", len(communities["communities"]))

```

## Combining Centrality and Community Analytics

A common workflow merges node importance scores with community membership for richer insights. The engines' standardized outputs make this straightforward:

```python

# Centrality

centrality = CentralityCalculator().calculate_degree_centrality(graph)

# Communities

communities = CommunityDetector().detect_communities(graph, algorithm="louvain")

# Example: list top-5 high-degree nodes together with their community id

top_nodes = centrality["rankings"][:5]
for entry in top_nodes:
    node = entry["node"]
    score = entry["score"]
    comm_id = communities["node_assignments"].get(node, None)
    print(f"Node {node}: degree={score:.3f}, community={comm_id}")

```

## Shared Infrastructure: Adjacency, Logging, and Progress Tracking

Both engines rely on common utilities defined across the Semantica codebase:

| Component | Implementation | Purpose |
|-----------|---------------|---------|
| **Adjacency construction** | `_build_adjacency()` method | Normalizes any graph representation—dictionaries with `relationships` arrays, custom objects, or NetworkX graphs—into a simple `{node: [neighbors]}` map |
| **Progress tracking** | `get_progress_tracker()` in [`semantica/utils/progress_tracker.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/utils/progress_tracker.py) | Creates a singleton tracker; heavy steps wrap with `start_tracking()` and `stop_tracking()` |
| **Logging** | `get_logger()` in [`semantica/utils/logging.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/utils/logging.py) | Supplies module-specific loggers (`centrality_calculator` or `community_detector`) for debug and info output |

This shared infrastructure ensures consistent behavior and observability across analytics operations.

## Enabling NetworkX Acceleration

The engines function without external dependencies, but **installing NetworkX unlocks significant performance gains**:

```bash
pip install networkx

```

With NetworkX present, both calculators automatically detect and use optimized C-backed implementations for computationally intensive algorithms like betweenness centrality and Louvain modularity optimization.

## Summary

- **Two dedicated engines** handle graph analytics in Semantica: `CentralityCalculator` for node importance and `CommunityDetector` for community identification.
- **Pure-Python with NetworkX boost**: Engines work immediately on any installation; add `networkx` for accelerated computation.
- **Five centrality metrics** available: degree, betweenness, closeness, eigenvector, and PageRank via `calculate_all_centrality()`.
- **Four community algorithms** supported: Louvain, Leiden, overlapping k-clique, and label propagation through `detect_communities()`.
- **Automatic chunking** handles large graphs without manual configuration.
- **Shared utilities** in `semantica/utils/` provide adjacency construction, progress tracking, and structured logging.

## Frequently Asked Questions

### What graph formats does Semantica accept for analytics?

Semantica's `_build_adjacency()` method accepts multiple formats: dictionaries with `entities` and `relationships` keys (the native format), custom graph objects, or existing NetworkX graphs. The method normalizes all inputs into a simple adjacency list representation.

### How do I know if NetworkX acceleration is active?

Both engines set `self.use_networkx` during initialization. Check this attribute on your calculator or detector instance. The engines also log their mode at debug level through module-specific loggers.

### Can I run community detection without NetworkX installed?

Yes. The `CommunityDetector` falls back to `_basic_community_detection()` and `_basic_overlapping_detection()`—lightweight greedy heuristics that produce valid results without external dependencies. NetworkX simply provides faster, more mature implementations.

### What is the modularity score returned by community detection?

Modularity measures the quality of a community partition by comparing the density of edges inside communities against a random baseline. Values range from -0.5 to 1, with higher scores indicating stronger community structure. The `result["modularity"]` field contains this metric when the selected algorithm supports it.