# Graph Analytics Functions in Semantica: Centrality Algorithms and Knowledge Graph Visualization

> Explore Semantica's graph analytics functions: degree, betweenness, closeness, eigenvector, and PageRank centrality algorithms. Visualize your knowledge graphs interactively with Semantica.

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

---

**Semantica provides five centrality algorithms—degree, betweenness, closeness, eigenvector, and PageRank—alongside interactive visualization tools for knowledge graphs, implemented across [`centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/centrality_calculator.py) and [`analytics_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/analytics_visualizer.py) in the `semantica-agi/semantica` repository.**

The `semantica-agi/semantica` repository delivers a comprehensive suite of **graph analytics functions in Semantica** designed for knowledge graph analysis and exploration. These capabilities split into two main domains: mathematical centrality computation and interactive visualization rendering. Engineers and data scientists leverage these tools to quantify node importance and generate publication-ready visualizations directly from graph structures.

## Centrality Computation via CentralityCalculator

Located in [`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py), the `CentralityCalculator` class serves as the primary engine for node-importance quantification. This component implements optimized algorithms that return standardized result dictionaries containing both raw scores and sorted rankings.

### Supported Centrality Measures

The calculator exposes five distinct metrics for analyzing knowledge graphs:

- **`calculate_degree_centrality(graph)`** – Returns normalized connection counts for each node.
- **`calculate_betweenness_centrality(graph)`** – Quantifies how often a node appears on shortest paths between other nodes.
- **`calculate_closeness_centrality(graph)`** – Computes the inverse of the average shortest-path distance to all other nodes.
- **`calculate_eigenvector_centrality(graph, max_iter=100, tol=1e-6)`** – Performs power iteration on the adjacency matrix to measure influence based on connection quality.
- **`calculate_pagerank(graph)`** – Executes sparse-matrix power iteration with damping factor to compute authority scores.

Each method returns a dictionary with two keys: `centrality` (mapping nodes to numerical scores) and `rankings` (a sorted list of `{'node': ..., 'score': ...}` dictionaries).

### Batch Processing with calculate_all_centrality

For comprehensive analysis, the `calculate_all_centrality(graph, centrality_types=None)` method executes multiple algorithms in a single call. When NetworkX is installed, implementations delegate to its highly optimized C-backed functions; otherwise, pure-Python fallbacks ensure cross-platform compatibility without external dependencies.

```python
from semantica.kg import CentralityCalculator

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

# Access raw degree scores

degree_scores = all_centrality["degree"]["centrality"]

# Retrieve top-5 nodes by PageRank

top_pr = all_centrality["pagerank"]["rankings"][:5]
print(top_pr)

```

## Interactive Analytics Visualization

The `AnalyticsVisualizer` class in [`semantica/visualization/analytics_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/analytics_visualizer.py) transforms raw graph metrics into interactive Plotly charts or static image exports. This component handles both individual metric plotting and comparative multi-algorithm analysis.

### Centrality Rankings and Comparisons

The visualizer specializes in ranking charts and comparative analysis:

- **`visualize_centrality_rankings(centrality, centrality_type='degree', top_n=20)`** – Generates horizontal bar charts displaying the highest-scoring nodes for any single metric.
- **`visualize_centrality_comparison(centrality_results, top_n=10)`** – Creates grouped bar charts juxtaposing multiple centrality measures (e.g., degree vs. PageRank) on the same node set.

Both methods support the `output` parameter: set to `"interactive"` for Plotly Figure objects or provide file paths for HTML/PNG export via the `export_plotly_figure` helper.

### Structural and Community Analysis

Beyond centrality, the visualizer handles structural graph properties:

- **`visualize_community_structure(graph, communities)`** – Renders detected community clusters using the underlying KG visualizer.
- **`visualize_connectivity(connectivity)`** – Displays component counts and size distributions via indicator panels and bar charts.
- **`visualize_degree_distribution(graph)`** – Generates histograms showing the frequency distribution of node degrees.
- **`visualize_metrics_dashboard(metrics)`** – Composes multi-panel dashboards combining node counts, edge density, average path length, and graph diameter.

```python
from semantica.visualization import AnalyticsVisualizer

viz = AnalyticsVisualizer(color_scheme="default")
deg_result = calc.calculate_degree_centrality(my_graph)

fig = viz.visualize_centrality_rankings(
    deg_result,
    centrality_type="degree",
    top_n=10,
    output="interactive"
)
fig.show()  # Launches interactive Plotly window

```

## Knowledge Graph Rendering Components

The `KGVisualizer` class in [`semantica/visualization/kg_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/kg_visualizer.py) provides lower-level rendering primitives that power the analytics layer. These methods handle the actual geometric layout and aesthetic mapping of graph structures:

- **`visualize_network(graph)`** – Renders complete network layouts with force-directed positioning.
- **`visualize_communities(graph, communities)`** – Applies color overlays to distinguish community assignments.
- **`visualize_centrality(graph, centrality)`** – Scales node sizes proportionally to centrality scores.
- **`visualize_entity_types(graph)`** – Applies color coding based on node ontological types.
- **`visualize_relationship_matrix(graph)`** – Generates adjacency matrix heatmaps for dense connectivity analysis.

```python
from semantica.visualization import KGVisualizer

kg_viz = KGVisualizer()
kg_viz.visualize_communities(
    my_graph, 
    community_labels, 
    output="html", 
    file_path="communities.html"
)

```

## Convenience API Entry Points

The [`semantica/visualization/methods.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/visualization/methods.py) module implements a facade pattern that simplifies access to the visualization stack. High-level functions such as `visualize_kg`, `visualize_analytics`, `visualize_ontology`, and `visualize_temporal` automatically route arguments to the appropriate `KGVisualizer` or `AnalyticsVisualizer` methods based on the requested graph type and analysis context.

## Comparative Centrality Analysis Example

To analyze node importance across multiple dimensions simultaneously:

```python
centrality_results = {
    "degree": calc.calculate_degree_centrality(my_graph),
    "betweenness": calc.calculate_betweenness_centrality(my_graph),
    "pagerank": calc.calculate_pagerank(my_graph),
}

fig = viz.visualize_centrality_comparison(
    centrality_results,
    top_n=8,
    output="interactive"
)
fig.show()

```

This pattern helps identify nodes that rank highly in specific contexts (e.g., high betweenness but moderate degree) versus universally important hub nodes.

## Summary

- **Five centrality algorithms** (degree, betweenness, closeness, eigenvector, PageRank) are implemented in [`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py) via the `CentralityCalculator` class.
- **Standardized output format** includes both `centrality` dictionaries and `rankings` lists for consistent downstream processing.
- **Dual visualization modes** support interactive Plotly exploration and static file export (HTML, PNG) through `AnalyticsVisualizer`.
- **Layered architecture** separates mathematical computation (`CentralityCalculator`), high-level charting (`AnalyticsVisualizer`), and geometric rendering (`KGVisualizer`).
- **Optional NetworkX integration** provides accelerated calculations when available, with pure-Python fallbacks ensuring portability.

## Frequently Asked Questions

### What centrality algorithms does Semantica support?

Semantica supports five graph centrality measures: **degree**, **betweenness**, **closeness**, **eigenvector**, and **PageRank**. These are implemented in [`semantica/kg/centrality_calculator.py`](https://github.com/semantica-agi/semantica/blob/main/semantica/kg/centrality_calculator.py) through the `CentralityCalculator` class, with each algorithm available as both individual methods and via the batch `calculate_all_centrality` processor.

### How does Semantica handle visualization output formats?

The visualization system supports dual output modes controlled by the `output` parameter. Set `output="interactive"` to receive Plotly Figure objects for Jupyter notebooks or web applications, or specify file paths with formats like `html` or `png` to generate static exports. The `export_plotly_figure` helper in [`analytics_visualizer.py`](https://github.com/semantica-agi/semantica/blob/main/analytics_visualizer.py) manages the serialization logic.

### Can I compute multiple centrality measures at once?

Yes. The `calculate_all_centrality(graph, centrality_types=None)` method in `CentralityCalculator` executes all supported algorithms in a single pass and returns a unified results dictionary. This approach optimizes performance by reusing graph traversals and ensures consistent node ordering across different metrics.

### What dependencies are required for graph analytics in Semantica?

The core analytics functions require only standard Python libraries. However, when **NetworkX** is installed, `CentralityCalculator` automatically delegates to its optimized C-backed implementations for significantly faster computation on large graphs. The visualization components require **Plotly** for interactive chart generation.