Graph Analytics in Semantica: Centrality Measures and Community Visualization

Semantica provides an end-to-end pipeline for graph analytics through the CentralityCalculator and AnalyticsVisualizer classes, enabling computation of degree, betweenness, closeness, eigenvector, and PageRank centrality alongside community-aware network visualizations.

The semantica-agi/semantica repository delivers a full-stack toolkit for performing graph analytics on knowledge graphs. Its architecture cleanly separates metric computation from rendering, allowing you to calculate standard centrality scores and visualize them as interactive dashboards or network diagrams with minimal boilerplate code.

Computing Centrality Measures

The graph analytics workflow begins in semantica/kg/centrality_calculator.py. The CentralityCalculator class orchestrates calculations across five standard metrics, optionally delegating to NetworkX for performance when available.

Supported Centrality Metrics

The calculator exposes individual methods for each metric, all returning a standardized dictionary containing raw scores and ranked node lists:

  • calculate_degree_centrality(graph) – Counts direct connections per node
  • calculate_betweenness_centrality(graph) – Identifies bridge nodes lying on shortest paths
  • calculate_closeness_centrality(graph) – Measures average distance to all other nodes
  • calculate_eigenvector_centrality(graph) – Weights connections by neighbor importance
  • calculate_pagerank(graph) – Applies the PageRank algorithm for directed influence

Each method produces a payload with the structure {"centrality": {...}, "rankings": [...]}, ready for downstream visualization. For batch processing, calculate_all_centrality(graph) computes all five measures in a single call.

from semantica.kg.centrality_calculator import CentralityCalculator

calc = CentralityCalculator()

# graph can be a dict with "entities"/"relationships" or a NetworkX Graph

centrality_all = calc.calculate_all_centrality(graph)

# Extract specific measure for visualization

degree_results = centrality_all["centrality_measures"]["degree"]

Community Detection Integration

While Semantica focuses on visualization and analysis, it expects community assignments from external detection algorithms such as Louvain or Leiden. The visualization layers accept a communities dictionary formatted as {"node_assignments": {"node_id": community_id, ...}}, which maps each entity to its respective community identifier.

Visualizing Graph Analytics Results

Semantica splits visualization into two specialized layers: statistical analytics dashboards and knowledge graph network renderings.

Analytics Dashboards with AnalyticsVisualizer

Located in semantica/visualization/analytics_visualizer.py, the AnalyticsVisualizer class transforms centrality data into publication-ready charts. Key methods include visualize_centrality_rankings for bar charts of top-N nodes and visualize_centrality_comparison for multi-metric grouped comparisons.

from semantica.visualization import AnalyticsVisualizer

av = AnalyticsVisualizer(color_scheme="vibrant")

# Top-10 degree centrality bar chart

fig = av.visualize_centrality_rankings(
    degree_results,
    centrality_type="degree",
    top_n=10,
    output="interactive"
)

For comparative analysis across multiple metrics:

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

av.visualize_centrality_comparison(
    centrality_results,
    top_n=15,
    output="png",
    file_path="centrality_comparison.png"
)

Knowledge Graph Rendering with KGVisualizer

The KGVisualizer class in semantica/visualization/kg_visualizer.py embeds analytics directly into network diagrams. It normalizes any knowledge graph input, builds Plotly layouts via semantica/visualization/utils/layout_algorithms.py, and scales nodes by centrality scores or colors them by community assignment.

from semantica.visualization import KGVisualizer

kg_viz = KGVisualizer(layout="force", color_scheme="pastel")

# Scale nodes by degree centrality, color by entity type

graph_fig = kg_viz.visualize_centrality(
    graph,
    centrality=degree_results,
    centrality_type="degree",
    output="interactive",
    node_color_by="type",
    hover_data=["type", "metadata"]
)

To overlay community structures detected externally:

kg_viz.visualize_communities(
    graph,
    communities,
    output="html",
    file_path="communities.html"
)

Customizing and Exporting Results

Both visualizers support consistent styling through semantica/visualization/utils/color_schemes.py, which provides the ColorScheme enum and palette utilities. Layout algorithms (Force-Directed, Hierarchical, Circular) reside in semantica/visualization/utils/layout_algorithms.py.

Export functionality is handled by semantica/visualization/utils/export_formats.py. Specify output="html", "png", or "svg" and provide a file_path to persist static files, or use "interactive" to return a Plotly Figure for notebook rendering. The module instruments all operations with ProgressTracker for real-time CLI feedback and raises clear ProcessingError exceptions with installation instructions if optional dependencies like Plotly or NetworkX are missing.

Summary

  • CentralityCalculator in semantica/kg/centrality_calculator.py computes degree, betweenness, closeness, eigenvector, and PageRank centrality with optional NetworkX acceleration
  • All centrality methods return normalized dictionaries containing both raw scores and sorted rankings
  • AnalyticsVisualizer generates statistical charts including rankings, distributions, and comparative dashboards
  • KGVisualizer renders interactive knowledge graphs with nodes sized by centrality and colored by community or type
  • Export helpers support PNG, SVG, HTML, and interactive Plotly formats via export_plotly_figure

Frequently Asked Questions

What centrality measures does Semantica support?

Semantica supports five standard graph analytics metrics: degree, betweenness, closeness, eigenvector, and PageRank centrality. Each is implemented as a dedicated method in semantica/kg/centrality_calculator.py that returns normalized scores and ranked node lists.

How do I visualize communities in a Semantica knowledge graph?

Pass your community detection results to KGVisualizer.visualize_communities. The method expects a dictionary with a node_assignments key mapping node IDs to community IDs. The visualizer automatically assigns distinct colors from semantica/visualization/utils/color_schemes.py to each community cluster.

Can I export static images of my graph analytics visualizations?

Yes. Both AnalyticsVisualizer and KGVisualizer accept an output parameter set to "png", "svg", or "html" along with a file_path argument. The underlying export_plotly_figure helper in semantica/visualization/utils/export_formats.py handles the rendering and file I/O.

Does Semantica require NetworkX to perform graph analytics?

No. While CentralityCalculator delegates to NetworkX for computational speed when the library is available, it functions gracefully with standard Python dictionaries containing "entities" and "relationships" keys. Missing optional dependencies trigger descriptive ProcessingError exceptions rather than import failures.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →