Advanced Analytics in Semantica's ContextGraph: 8 Analytical Capabilities Explained
Semantica's ContextGraph supports eight advanced analytics features—centrality analysis, community detection, node embeddings, path finding, link prediction, similarity calculation, connectivity analysis, and graph-wide metrics—activated via advanced_analytics=True.
The ContextGraph serves as Semantica's in-memory knowledge graph backbone. When you enable advanced analytics, the graph gains a full Knowledge-Graph (KG) integration layer that transforms raw connectivity data into actionable intelligence. These capabilities ship with the semantica-agi/semantica repository and are implemented through a modular component system.
How to Enable Advanced Analytics
Analytics are opt-in at instantiation. Set advanced_analytics=True along with specific feature flags to load only what you need.
from semantica.context import ContextGraph
graph = ContextGraph(
advanced_analytics=True,
centrality_analysis=True,
community_detection=True,
node_embeddings=True,
)
The components populate self.kg_components when KG_AVAILABLE is true, as implemented in semantica/context/context_graph.py lines 179-189.
Centrality Analysis
Centrality analysis computes node importance through multiple lenses. The CentralityCalculator (imported from semantica.kg) provides:
- Degree centrality – raw connection count
- Betweenness centrality – bridge nodes between communities
- Closeness centrality – average distance to all other nodes
- Eigenvector centrality – importance of connections
- PageRank – recursive authority scoring
Core implementation resides in semantica/kg/centrality_calculator.py with optional NetworkX acceleration.
Retrieve scores via get_node_centrality():
centrality = graph.get_node_centrality("Python")
# Returns: {'degree': 0.33, 'betweenness': 0.12, 'closeness': 0.45, ...}
This method caches results in self._analytics_cache (lines 4132-4164 of context_graph.py).
Community Detection
Community detection identifies tightly connected node clusters using modularity-based algorithms. The CommunityDetector component analyzes topological structure to reveal natural groupings without supervision.
Use this for:
- Discovering implicit knowledge domains
- Validating ontology structure
- Recommending related concepts
Node Embeddings
Node embeddings generate low-dimensional vector representations suitable for machine learning pipelines. The NodeEmbedder produces embeddings comparable to Node2Vec, capturing structural equivalence and homophily.
Compute embeddings directly through the component:
embeddings = graph.kg_components["node_embedder"].compute_embeddings(
graph_store=graph,
node_labels=list(graph.node_type_index.keys()),
relationship_types=list(graph.edge_type_index.keys()),
)
Path Finding
Path finding retrieves optimal routes between arbitrary nodes. The PathFinder supports:
- Shortest-path queries
- Custom constraint-based path discovery
- Relationship-type filtering
Use this for explanation generation, chain-of-thought retrieval, or navigation interfaces.
Link Prediction
Link prediction anticipates missing relationships using graph-based heuristics. The LinkPredictor scores unobserved edges to surface:
- Potential knowledge gaps
- Recommended connections
- Data quality issues
Similarity Calculation
Similarity calculation offers three distinct modes controlled by similarity_type:
| Mode | Basis | Use Case |
|---|---|---|
content |
Lexical/node attributes | Keyword matching |
structural |
Topological position | Role equivalence |
embedding |
Vector similarity | Semantic search |
Call find_similar_nodes() to retrieve ranked results:
# Content-based similarity
similar = graph.find_similar_nodes("Python", similarity_type="content", top_k=5)
# Embedding-based similarity
similar_by_emb = graph.find_similar_nodes("Python", similarity_type="embedding", top_k=3)
Implementation spans lines 4090-4109 in context_graph.py.
Connectivity Analysis
Connectivity analysis exposes macroscopic graph health through ConnectivityAnalyzer:
- Connected component counts
- Graph diameter
- Density metrics
- Articulation points
Use these metrics to monitor knowledge graph integrity over time.
Graph-Wide Metrics
Graph-wide metrics provide aggregated statistics via internal helper methods:
_get_node_type_distribution()– histogram of entity categories_get_edge_type_distribution()– relationship frequency analysis_calculate_modularity()– community structure quality
Implementation visible in lines 4848-4868 of context_graph.py.
Running the Full Analytics Pipeline
Execute comprehensive analysis with analyze_graph_with_kg():
full_analysis = graph.analyze_graph_with_kg()
# Returns composite dictionary with centrality, communities, embeddings, connectivity
This orchestrates all KG components in sequence, with progress tracking and unified logging. Results populate self._analytics_cache to prevent redundant computation.
Key Implementation Files
| File | Purpose |
|---|---|
semantica/context/context_graph.py |
Core orchestration, caching, high-level APIs |
semantica/kg/centrality_calculator.py |
Centrality algorithm implementations |
semantica/kg/community_detector.py |
Modularity-based clustering |
semantica/kg/node_embedder.py |
Embedding generation (Node2Vec-style) |
semantica/kg/path_finder.py |
Route discovery utilities |
semantica/kg/link_predictor.py |
Missing edge prediction |
semantica/kg/similarity_calculator.py |
Multi-mode similarity scoring |
semantica/kg/connectivity_analyzer.py |
Graph topology metrics |
semantica/utils/logging.py |
Centralized analytics logging |
Summary
- Enable advanced analytics with
advanced_analytics=TrueatContextGraphinstantiation - Access 8 analytical capabilities through modular KG components loaded into
self.kg_components - Retrieve centrality scores via
get_node_centrality()with automatic caching - Compute three similarity modes (content, structural, embedding) through
find_similar_nodes() - Run comprehensive analysis using
analyze_graph_with_kg()for full pipeline execution - Locate implementations in
semantica/context/context_graph.pyand thesemantica/kg/module directory
Frequently Asked Questions
What is the performance cost of enabling advanced analytics?
Analytics components load lazily into self.kg_components only when flags are true. Computation-heavy operations cache results in self._analytics_cache, making repeated queries near-instant. Initial graph-wide analysis may take seconds for large graphs; use semantica/utils/progress_tracker.py for visibility.
Can I use individual analytics without loading all components?
Yes. Each analytic accepts independent boolean flags—set only centrality_analysis=True or node_embeddings=True to load specific modules. The KG_AVAILABLE guard ensures graceful degradation if dependencies are missing.
How does similarity_type="embedding" differ from "structural"?
Embedding similarity compares precomputed vector representations (cosine distance), capturing latent semantic relationships. Structural similarity compares topological position—nodes with similar connection patterns receive high scores regardless of attribute content. Use embedding similarity for semantic search, structural for role-based recommendation.
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:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →