# Graph Analytics in Semantica: Centrality, Community Detection, and Link Prediction

> Explore graph analytics in Semantica including centrality metrics community detection and link prediction with the semantica kg package. Unlock deeper insights from your knowledge graphs.

- Repository: [Semantica /semantica](https://github.com/semantica-agi/semantica)
- Tags: deep-dive
- Published: 2026-08-09

---

**Semantica provides a built-in graph analytics stack supporting centrality metrics, community detection algorithms, and link prediction heuristics through the `semantica.kg` package.**

The open-source Semantica framework (available at `semantica-agi/semantica`) ships with a compact yet powerful knowledge-graph processing engine. These capabilities enable users to calculate node importance, discover hidden clusters, and predict missing relationships without requiring external tools. The analytics modules are designed to work out-of-the-box with pure-Python implementations while automatically leveraging NetworkX for performance when available.

## Centrality Analysis with CentralityCalculator

The `CentralityCalculator` class in [`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py) computes multiple node importance metrics. This class automatically falls back to pure-Python implementations when the optional **NetworkX** dependency is not installed.

### Available Centrality Metrics

The calculator exposes five core algorithms:

- **Degree Centrality** – Measures direct connections per node via `calculate_degree_centrality()`
- **Betweenness Centrality** – Identifies bridge nodes using `calculate_betweenness_centrality()`
- **Closeness Centrality** – Calculates average shortest path length to all other nodes
- **Eigenvector Centrality** – Weights nodes based on the importance of their neighbors
- **PageRank** – Computes probabilistic importance scores via `calculate_pagerank()`

### Computing PageRank and Degree Centrality

```python
from semantica.kg import CentralityCalculator

calc = CentralityCalculator()
pagerank = calc.calculate_pagerank(graph)          # dict[node_id → score]

degree = calc.calculate_degree_centrality(graph)   # {"centrality":…, "rankings":…}

print("Top PageRank node:", max(pagerank, key=pagerank.get))
print("Top degree node:", degree["rankings"][0]["node"])

```

## Community Detection Algorithms

The `CommunityDetector` class in [`semantica/kg/community_detector.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/community_detector.py) identifies clusters within knowledge graphs using multiple established algorithms.

### Supported Detection Methods

According to the Semantica source code, the module supports four clustering approaches:

1. **Louvain** – Hierarchical modularity optimization via `detect_communities_louvain()`
2. **Leiden** – Improved Louvain variant guaranteeing well-connected communities via `detect_communities_leiden()`
3. **Label Propagation** – Fast, near-linear time clustering via `detect_communities_label_propagation()`
4. **K-Clique** – Detects overlapping communities based on clique percolation

Like the centrality module, these methods prefer NetworkX’s optimized routines but provide basic fallbacks for environments without the optional dependency.

### Detecting Communities with Louvain

```python
from semantica.kg import CommunityDetector

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

print(f"Detected {len(communities['communities'])} communities")
print("Node → community mapping (sample):",
      list(communities["node_assignments"].items())[:5])

```

## Link Prediction Heuristics

The `LinkPredictor` class in [`semantica/kg/link_predictor.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/link_predictor.py) scores and predicts missing edges using classic graph topology heuristics.

### Prediction Algorithms

The implementation supports five proximity indexes:

- **Preferential Attachment** – Assumes high-degree nodes are likely to connect (`_preferential_attachment()`)
- **Common Neighbors** – Counts shared adjacent nodes
- **Jaccard Coefficient** – Normalizes common neighbors by union of neighbor sets
- **Adamic-Adar Index** – Weights common neighbors by their inverse logarithmic degree
- **Resource Allocation Index** – Distributes limited resources across common neighbors

### Batch Prediction and Top-K Extraction

The predictor supports batch scoring with exclusion of existing edges:

```python
from semantica.kg import LinkPredictor

predictor = LinkPredictor(method="preferential_attachment")
top_links = predictor.predict_links(
    graph, top_k=10, exclude_existing=True
)

print("Highest-scoring missing links:")
for src, dst, score in top_links:
    print(f"  {src} ↔ {dst}: {score:.4f}")

```

Individual edge scoring is available via `score_link()`, while `predict_links()` handles the full graph scan and ranking.

## MCP Tool Integration

The analytics stack exposes a unified interface through the MCP graph tool in [`mcp/tools/graph.py`](https://github.com/semantica-agi/semantica/blob/main/mcp/tools/graph.py). The `handle_get_graph_analytics` function orchestrates the three engines based on a requested metrics list.

```python
from semantica.mcp.tools.graph import handle_get_graph_analytics

analytics = handle_get_graph_analytics(
    {"metrics": ["pagerank", "betweenness", "communities"], "top_n": 5}
)
print("Analytics summary:", analytics)

```

This wrapper calls `CentralityCalculator().calculate_*()` and `CommunityDetector().detect_communities()` while logging progress via Semantica’s internal progress-tracker utilities, making large-scale runs observable.

## Optional Dependencies and Performance

All three analytics modules are **optional-dependency-aware**. They function immediately with pure-Python code, but if `networkx` is available, the algorithms execute considerably faster using optimized C-backed implementations. This design ensures the `semantica.kg` package remains portable while offering production-grade performance when dependencies permit.

## Summary

- **CentralityCalculator** ([`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py)) provides degree, betweenness, closeness, eigenvector, and PageRank metrics with automatic NetworkX acceleration.
- **CommunityDetector** ([`semantica/kg/community_detector.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/community_detector.py)) implements Louvain, Leiden, label-propagation, and k-clique algorithms for cluster identification.
- **LinkPredictor** ([`semantica/kg/link_predictor.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/link_predictor.py)) offers preferential attachment, common-neighbors, Jaccard, Adamic-Adar, and resource-allocation heuristics for missing edge prediction.
- The **MCP graph tool** ([`mcp/tools/graph.py`](https://github.com/semantica-agi/semantica/blob/main/mcp/tools/graph.py)) aggregates all analytics through `handle_get_graph_analytics()` for unified access.
- All modules degrade gracefully to pure-Python implementations when NetworkX is unavailable.

## Frequently Asked Questions

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

Semantica’s graph analytics classes accept internal graph objects that represent knowledge-graph structures. While the specific serialization format depends on the broader Semantica ingestion pipeline, the `CentralityCalculator`, `CommunityDetector`, and `LinkPredictor` classes operate on standardized graph representations that support node IDs and edge mappings.

### Can I run centrality calculations without installing NetworkX?

Yes. The `CentralityCalculator` class in [`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py) automatically falls back to pure-Python implementations when NetworkX is not installed. While the calculations will be slower on large graphs, all metrics—including PageRank and betweenness centrality—remain fully functional.

### How does the link predictor handle existing edges?

The `LinkPredictor.predict_links()` method accepts an `exclude_existing=True` parameter that filters out edges already present in the graph. This ensures the returned top-k results contain only potential new connections rather than existing relationships.

### Which community detection algorithm should I use for large knowledge graphs?

For large-scale graphs, the **Louvain** or **Label Propagation** algorithms available in [`semantica/kg/community_detector.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/community_detector.py) offer the best performance characteristics. Louvain provides high-quality modularity-based clusters, while Label Propagation runs in near-linear time and requires no resolution parameter tuning.