Distance Intelligence in Semantica: Semantic Neighbourhood Enrichment for Knowledge Graphs
Distance Intelligence is a Semantica framework feature that enriches knowledge graph nodes with semantic neighbourhood metadata—calculating graph-embedding distances rather than just topological connectivity—to enable proximity-aware retrieval and causal analysis.
The Distance Intelligence system in the semantica-agi/semantica repository transforms raw graph topology into semantically meaningful proximity data. By computing embedding-based distances and caching distance matrices, the KG module enables queries that understand how "close" concepts are in semantic space, powering features from ego-mode visualizations to confidence-weighted retrieval.
What is Distance Intelligence?
Distance Intelligence moves beyond simple hop-counting to measure semantic proximity using graph embeddings. Every node in the knowledge graph receives a semantic neighbourhood description that quantifies its relationship to other nodes based on vector-space distances rather than just edge connectivity.
This capability enables sophisticated queries such as "how semantically close is A to B?" while returning rich path metadata including distance bands, confidence decay metrics, and full traversal paths. The implementation spans three tightly-coupled architectural layers within the KG core.
How Distance Intelligence Works in the KG Module
The implementation resides primarily in semantica/context/context_graph.py and consists of three integrated layers that handle computation, API exposure, and consumption.
Embedding and Distance Caching Layer
At the foundation, the Embedding & Distance Cache computes graph embeddings and maintains per-session distance matrices. This layer ensures thread-safe reuse and automatic cache invalidation through the embedding cache referenced in semantica/vector_store/embedding_cache.py and distance-metadata flags defined in the context graph module.
API and Metadata Enrichment Layer
The middle layer exposes methods that attach distance intelligence to neighbor queries. When calling ContextGraph.get_neighbors() with include_distance_metadata=True, the system decorates each result with three critical fields:
distance_band– Human-readable proximity classification ("direct", "near", "mid-range", or "distant")confidence_decay– Product of edge weights along the traversed pathpath_to_anchor– Complete node sequence from source to neighbor
This implementation at line 58 of semantica/context/context_graph.py enables downstream components to reason about relationship strength without manually calculating graph distances.
Visualization and Retrieval Integration
The top layer consumes distance metadata for UI rendering and search ranking. The Explorer interface renders ego-mode heat-maps through explorer/src/workspaces/GraphWorkspace/GraphInspectorPanel.tsx, while the retrieval API reads metadata when proximity_weight > 0 to blend similarity scores with graph proximity.
The Distance Band Classification System
Distance Intelligence categorizes semantic proximity using a deterministic hop-count classifier defined in semantica/utils/helpers.py. The classify_path_distance() function implements the following taxonomy:
def classify_path_distance(hop_count: int) -> str:
"""Map hop count → distance band."""
if hop_count <= 1:
return "direct"
if hop_count <= 3:
return "near"
if hop_count <= 6:
return "mid-range"
return "distant"
This classification appears in the distance_band field of every neighbor result when metadata enrichment is enabled. The confidence decay value complements this by representing the multiplied edge weights along the path, providing a continuous measure of relationship strength that contrasts with the discrete band classification.
Practical Implementation: Code Examples
Retrieving Neighbors with Distance Metadata
To fetch enriched neighbor data including distance bands and paths, use the include_distance_metadata flag in ContextGraph.get_neighbors():
from semantica.context import ContextGraph
# Assume g is a populated ContextGraph instance
neighbors = g.get_neighbors(
"A",
hops=3,
include_distance_metadata=True,
)
for n in neighbors:
print(
f"{n['id']} – hop:{n['hop']} – band:{n['distance_band']} "
f"– decay:{n['confidence_decay']:.3f}"
)
Each dictionary in the returned list contains the node's identifier, hop count, distance band classification, confidence decay value, and the full path to anchor.
Filtering by Confidence and Distance
For sorted, filtered neighbor lists, the get_neighbor_distances() method builds upon the base neighbor query and applies confidence thresholds:
# Return only neighbors with confidence decay exceeding 0.4
filtered = g.get_neighbor_distances(
node_id="A",
hops=4,
min_confidence=0.4,
)
for item in filtered:
print(item["id"], item["distance_band"], item["confidence_decay"])
This helper method calls get_neighbors(..., include_distance_metadata=True) internally, then filters and sorts results by hop count and confidence decay according to the implementation in lines 34-59 of semantica/context/context_graph.py.
Proximity-Blended Retrieval
Applications can weight search results by semantic proximity using the proximity_weight parameter in the retrieve() method:
results = g.retrieve(
query="machine learning",
top_k=10,
proximity_weight=0.3, # 30% weight from distance decay
include_distance_metadata=True,
)
The retrieval engine calculates the final ranking score by multiplying the base semantic similarity by the factor (1 - proximity_weight) + proximity_weight * confidence_decay. This produces results that balance textural relevance with graph-topological proximity.
Advanced Applications
Distance Intelligence propagates through higher-level APIs to support complex reasoning workflows:
-
Causal chain analysis – The
trace_decision_causality()function annotates each reasoning step with distance bands, allowing downstream logic to distinguish between "near" and "distant" causal influences. -
Hybrid precedent search – The
find_precedents_hybrid()method acceptsdistance_bandfilters to surface only closely related historical precedents, ignoring semantically distant matches regardless of their lexical similarity. -
Confidence decay propagation – Required paths accumulate edge weights to calculate multiplicative confidence values, enabling probabilistic reasoning across the graph.
Summary
- Distance Intelligence enriches knowledge graph nodes with semantic proximity metadata beyond simple hop counts.
- The system classifies distances into four bands ("direct", "near", "mid-range", "distant") using the
classify_path_distance()helper insemantica/utils/helpers.py. - Enable metadata enrichment by setting
include_distance_metadata=Truewhen callingContextGraph.get_neighbors()insemantica/context/context_graph.py. - Each enriched result contains
distance_band,confidence_decay, andpath_to_anchorfields. - Use
proximity_weightin retrieval queries to blend semantic similarity scores with graph-based confidence decay. - The Explorer UI visualizes this data through
GraphInspectorPanel.tsx, rendering proximity heat-maps and path inspections.
Frequently Asked Questions
What is Distance Intelligence in Semantica?
Distance Intelligence is a framework feature that calculates semantic distances between knowledge graph nodes using graph embeddings rather than just topological edges. It enriches query results with proximity metadata including distance bands, confidence decay values, and full traversal paths to enable context-aware retrieval and reasoning.
How does the distance band classification work?
The system uses the classify_path_distance() function in semantica/utils/helpers.py to map hop counts to human-readable categories: "direct" for 1 hop or less, "near" for 2-3 hops, "mid-range" for 4-6 hops, and "distant" for anything beyond 6 hops. This classification appears in the distance_band field when include_distance_metadata=True is specified.
What files contain the Distance Intelligence implementation?
The core implementation resides in semantica/context/context_graph.py (API methods), semantica/utils/helpers.py (distance classification), and semantica/vector_store/embedding_cache.py (matrix caching). User-facing documentation lives in docs/guides/distance-intelligence.md, while the Explorer UI consumes this data through explorer/src/workspaces/GraphWorkspace/GraphInspectorPanel.tsx.
How can I use proximity weighting in retrieval queries?
Pass the proximity_weight parameter (float between 0.0 and 1.0) to the retrieve() method on your ContextGraph instance. The engine blends the base similarity score with the result's confidence_decay value using the formula (1 - proximity_weight) + proximity_weight * confidence_decay, prioritizing nodes that are both textually relevant and graph-proximate to the query context.
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 →