Skip to main content

ruvector_core/advanced/
hypergraph.rs

1//! # Hypergraph Support for N-ary Relationships
2//!
3//! Implements hypergraph structures for representing complex multi-entity relationships
4//! beyond traditional pairwise similarity. Based on HyperGraphRAG (NeurIPS 2025) architecture.
5
6use crate::error::{Result, RuvectorError};
7use crate::types::{DistanceMetric, VectorId};
8use serde::{Deserialize, Serialize};
9use std::collections::{HashMap, HashSet};
10use std::time::{SystemTime, UNIX_EPOCH};
11use uuid::Uuid;
12
13/// Hyperedge connecting multiple vectors with description and embedding
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Hyperedge {
16    /// Unique identifier for the hyperedge
17    pub id: String,
18    /// Vector IDs connected by this hyperedge
19    pub nodes: Vec<VectorId>,
20    /// Natural language description of the relationship
21    pub description: String,
22    /// Embedding of the hyperedge description
23    pub embedding: Vec<f32>,
24    /// Confidence weight (0.0-1.0)
25    pub confidence: f32,
26    /// Optional metadata
27    pub metadata: HashMap<String, String>,
28}
29
30/// Temporal hyperedge with time attributes
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct TemporalHyperedge {
33    /// Base hyperedge
34    pub hyperedge: Hyperedge,
35    /// Creation timestamp (Unix epoch seconds)
36    pub timestamp: u64,
37    /// Optional expiration timestamp
38    pub expires_at: Option<u64>,
39    /// Temporal context (hourly, daily, monthly)
40    pub granularity: TemporalGranularity,
41}
42
43/// Temporal granularity for indexing
44#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
45pub enum TemporalGranularity {
46    Hourly,
47    Daily,
48    Monthly,
49    Yearly,
50}
51
52impl Hyperedge {
53    /// Create a new hyperedge
54    pub fn new(
55        nodes: Vec<VectorId>,
56        description: String,
57        embedding: Vec<f32>,
58        confidence: f32,
59    ) -> Self {
60        Self {
61            id: Uuid::new_v4().to_string(),
62            nodes,
63            description,
64            embedding,
65            confidence: confidence.clamp(0.0, 1.0),
66            metadata: HashMap::new(),
67        }
68    }
69
70    /// Get hyperedge order (number of nodes)
71    pub fn order(&self) -> usize {
72        self.nodes.len()
73    }
74
75    /// Check if hyperedge contains a specific node
76    pub fn contains_node(&self, node: &VectorId) -> bool {
77        self.nodes.contains(node)
78    }
79}
80
81impl TemporalHyperedge {
82    /// Create a new temporal hyperedge with current timestamp
83    pub fn new(hyperedge: Hyperedge, granularity: TemporalGranularity) -> Self {
84        let timestamp = SystemTime::now()
85            .duration_since(UNIX_EPOCH)
86            .unwrap()
87            .as_secs();
88
89        Self {
90            hyperedge,
91            timestamp,
92            expires_at: None,
93            granularity,
94        }
95    }
96
97    /// Check if hyperedge is expired
98    pub fn is_expired(&self) -> bool {
99        if let Some(expires_at) = self.expires_at {
100            let now = SystemTime::now()
101                .duration_since(UNIX_EPOCH)
102                .unwrap()
103                .as_secs();
104            now > expires_at
105        } else {
106            false
107        }
108    }
109
110    /// Get time bucket for indexing
111    pub fn time_bucket(&self) -> u64 {
112        match self.granularity {
113            TemporalGranularity::Hourly => self.timestamp / 3600,
114            TemporalGranularity::Daily => self.timestamp / 86400,
115            TemporalGranularity::Monthly => self.timestamp / (86400 * 30),
116            TemporalGranularity::Yearly => self.timestamp / (86400 * 365),
117        }
118    }
119}
120
121/// Hypergraph index with bipartite graph storage
122pub struct HypergraphIndex {
123    /// Entity nodes
124    entities: HashMap<VectorId, Vec<f32>>,
125    /// Hyperedges
126    hyperedges: HashMap<String, Hyperedge>,
127    /// Temporal hyperedges indexed by time bucket
128    temporal_index: HashMap<u64, Vec<String>>,
129    /// Bipartite graph: entity -> hyperedge IDs
130    entity_to_hyperedges: HashMap<VectorId, HashSet<String>>,
131    /// Bipartite graph: hyperedge -> entity IDs
132    hyperedge_to_entities: HashMap<String, HashSet<VectorId>>,
133    /// Distance metric for embeddings
134    distance_metric: DistanceMetric,
135}
136
137impl HypergraphIndex {
138    /// Create a new hypergraph index
139    pub fn new(distance_metric: DistanceMetric) -> Self {
140        Self {
141            entities: HashMap::new(),
142            hyperedges: HashMap::new(),
143            temporal_index: HashMap::new(),
144            entity_to_hyperedges: HashMap::new(),
145            hyperedge_to_entities: HashMap::new(),
146            distance_metric,
147        }
148    }
149
150    /// Add an entity node
151    pub fn add_entity(&mut self, id: VectorId, embedding: Vec<f32>) {
152        self.entities.insert(id.clone(), embedding);
153        self.entity_to_hyperedges.entry(id).or_default();
154    }
155
156    /// Add a hyperedge
157    pub fn add_hyperedge(&mut self, hyperedge: Hyperedge) -> Result<()> {
158        let edge_id = hyperedge.id.clone();
159
160        // Verify all nodes exist
161        for node in &hyperedge.nodes {
162            if !self.entities.contains_key(node) {
163                return Err(RuvectorError::InvalidInput(format!(
164                    "Entity {} not found in hypergraph",
165                    node
166                )));
167            }
168        }
169
170        // Update bipartite graph
171        for node in &hyperedge.nodes {
172            self.entity_to_hyperedges
173                .entry(node.clone())
174                .or_default()
175                .insert(edge_id.clone());
176        }
177
178        let nodes_set: HashSet<VectorId> = hyperedge.nodes.iter().cloned().collect();
179        self.hyperedge_to_entities
180            .insert(edge_id.clone(), nodes_set);
181
182        self.hyperedges.insert(edge_id, hyperedge);
183        Ok(())
184    }
185
186    /// Add a temporal hyperedge
187    pub fn add_temporal_hyperedge(&mut self, temporal_edge: TemporalHyperedge) -> Result<()> {
188        let bucket = temporal_edge.time_bucket();
189        let edge_id = temporal_edge.hyperedge.id.clone();
190
191        self.add_hyperedge(temporal_edge.hyperedge)?;
192
193        self.temporal_index.entry(bucket).or_default().push(edge_id);
194
195        Ok(())
196    }
197
198    /// Search hyperedges by embedding similarity
199    pub fn search_hyperedges(&self, query_embedding: &[f32], k: usize) -> Vec<(String, f32)> {
200        let mut results: Vec<(String, f32)> = self
201            .hyperedges
202            .iter()
203            .map(|(id, edge)| {
204                let distance = self.compute_distance(query_embedding, &edge.embedding);
205                (id.clone(), distance)
206            })
207            .collect();
208
209        results.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
210        results.truncate(k);
211        results
212    }
213
214    /// Get k-hop neighbors in hypergraph
215    /// Returns all nodes reachable within k hops from the start node
216    pub fn k_hop_neighbors(&self, start_node: VectorId, k: usize) -> HashSet<VectorId> {
217        let mut visited = HashSet::new();
218        let mut current_layer = HashSet::new();
219        current_layer.insert(start_node.clone());
220        visited.insert(start_node); // Start node is at distance 0
221
222        for _hop in 0..k {
223            let mut next_layer = HashSet::new();
224
225            for node in current_layer.iter() {
226                // Get all hyperedges containing this node
227                if let Some(hyperedges) = self.entity_to_hyperedges.get(node) {
228                    for edge_id in hyperedges {
229                        // Get all nodes in this hyperedge
230                        if let Some(nodes) = self.hyperedge_to_entities.get(edge_id) {
231                            for neighbor in nodes.iter() {
232                                if !visited.contains(neighbor) {
233                                    visited.insert(neighbor.clone());
234                                    next_layer.insert(neighbor.clone());
235                                }
236                            }
237                        }
238                    }
239                }
240            }
241
242            if next_layer.is_empty() {
243                break;
244            }
245            current_layer = next_layer;
246        }
247
248        visited
249    }
250
251    /// Query temporal hyperedges in a time range
252    pub fn query_temporal_range(&self, start_bucket: u64, end_bucket: u64) -> Vec<String> {
253        let mut results = Vec::new();
254        for bucket in start_bucket..=end_bucket {
255            if let Some(edges) = self.temporal_index.get(&bucket) {
256                results.extend(edges.iter().cloned());
257            }
258        }
259        results
260    }
261
262    /// Get hyperedge by ID
263    pub fn get_hyperedge(&self, id: &str) -> Option<&Hyperedge> {
264        self.hyperedges.get(id)
265    }
266
267    /// Get statistics
268    pub fn stats(&self) -> HypergraphStats {
269        let total_edges = self.hyperedges.len();
270        let total_entities = self.entities.len();
271        let avg_degree = if total_entities > 0 {
272            self.entity_to_hyperedges
273                .values()
274                .map(|edges| edges.len())
275                .sum::<usize>() as f32
276                / total_entities as f32
277        } else {
278            0.0
279        };
280
281        HypergraphStats {
282            total_entities,
283            total_hyperedges: total_edges,
284            avg_entity_degree: avg_degree,
285        }
286    }
287
288    fn compute_distance(&self, a: &[f32], b: &[f32]) -> f32 {
289        crate::distance::distance(a, b, self.distance_metric).unwrap_or(f32::MAX)
290    }
291}
292
293/// Hypergraph statistics
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct HypergraphStats {
296    pub total_entities: usize,
297    pub total_hyperedges: usize,
298    pub avg_entity_degree: f32,
299}
300
301/// Causal hypergraph memory for agent reasoning
302pub struct CausalMemory {
303    /// Hypergraph index
304    index: HypergraphIndex,
305    /// Causal relationship tracking: (cause_id, effect_id) -> success_count
306    causal_counts: HashMap<(VectorId, VectorId), u32>,
307    /// Action latencies: action_id -> avg_latency_ms
308    latencies: HashMap<VectorId, f32>,
309    /// Utility function weights
310    alpha: f32, // similarity weight
311    beta: f32,  // causal uplift weight
312    gamma: f32, // latency penalty weight
313}
314
315impl CausalMemory {
316    /// Create a new causal memory with default utility weights
317    pub fn new(distance_metric: DistanceMetric) -> Self {
318        Self {
319            index: HypergraphIndex::new(distance_metric),
320            causal_counts: HashMap::new(),
321            latencies: HashMap::new(),
322            alpha: 0.7,
323            beta: 0.2,
324            gamma: 0.1,
325        }
326    }
327
328    /// Set custom utility function weights
329    pub fn with_weights(mut self, alpha: f32, beta: f32, gamma: f32) -> Self {
330        self.alpha = alpha;
331        self.beta = beta;
332        self.gamma = gamma;
333        self
334    }
335
336    /// Add a causal relationship
337    pub fn add_causal_edge(
338        &mut self,
339        cause: VectorId,
340        effect: VectorId,
341        context: Vec<VectorId>,
342        description: String,
343        embedding: Vec<f32>,
344        latency_ms: f32,
345    ) -> Result<()> {
346        // Create hyperedge connecting cause, effect, and context
347        let mut nodes = vec![cause.clone(), effect.clone()];
348        nodes.extend(context);
349
350        let hyperedge = Hyperedge::new(nodes, description, embedding, 1.0);
351        self.index.add_hyperedge(hyperedge)?;
352
353        // Update causal counts
354        *self
355            .causal_counts
356            .entry((cause.clone(), effect.clone()))
357            .or_insert(0) += 1;
358
359        // Update latency
360        let entry = self.latencies.entry(cause).or_insert(0.0);
361        *entry = (*entry + latency_ms) / 2.0; // Running average
362
363        Ok(())
364    }
365
366    /// Query with utility function: U = α·similarity + β·causal_uplift - γ·latency
367    pub fn query_with_utility(
368        &self,
369        query_embedding: &[f32],
370        action_id: VectorId,
371        k: usize,
372    ) -> Vec<(String, f32)> {
373        let mut results: Vec<(String, f32)> = self
374            .index
375            .hyperedges
376            .iter()
377            .filter(|(_, edge)| edge.contains_node(&action_id))
378            .map(|(id, edge)| {
379                let similarity = 1.0
380                    - self
381                        .index
382                        .compute_distance(query_embedding, &edge.embedding);
383                let causal_uplift = self.compute_causal_uplift(&edge.nodes);
384                let latency = self.latencies.get(&action_id).copied().unwrap_or(0.0);
385
386                let utility = self.alpha * similarity + self.beta * causal_uplift
387                    - self.gamma * (latency / 1000.0); // Normalize latency to 0-1 range
388
389                (id.clone(), utility)
390            })
391            .collect();
392
393        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); // Sort by utility descending
394        results.truncate(k);
395        results
396    }
397
398    fn compute_causal_uplift(&self, nodes: &[VectorId]) -> f32 {
399        if nodes.len() < 2 {
400            return 0.0;
401        }
402
403        // Compute average causal strength for pairs in this hyperedge
404        let mut total_uplift = 0.0;
405        let mut count = 0;
406
407        for i in 0..nodes.len() - 1 {
408            for j in i + 1..nodes.len() {
409                if let Some(&success_count) = self
410                    .causal_counts
411                    .get(&(nodes[i].clone(), nodes[j].clone()))
412                {
413                    total_uplift += (success_count as f32).ln_1p(); // Log scale
414                    count += 1;
415                }
416            }
417        }
418
419        if count > 0 {
420            total_uplift / count as f32
421        } else {
422            0.0
423        }
424    }
425
426    /// Get hypergraph index
427    pub fn index(&self) -> &HypergraphIndex {
428        &self.index
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn test_hyperedge_creation() {
438        let nodes = vec!["1".to_string(), "2".to_string(), "3".to_string()];
439        let desc = "Test relationship".to_string();
440        let embedding = vec![0.1, 0.2, 0.3];
441        let edge = Hyperedge::new(nodes, desc, embedding, 0.95);
442
443        assert_eq!(edge.order(), 3);
444        assert!(edge.contains_node(&"1".to_string()));
445        assert!(!edge.contains_node(&"4".to_string()));
446        assert_eq!(edge.confidence, 0.95);
447    }
448
449    #[test]
450    fn test_temporal_hyperedge() {
451        let nodes = vec!["1".to_string(), "2".to_string()];
452        let desc = "Temporal relationship".to_string();
453        let embedding = vec![0.1, 0.2];
454        let edge = Hyperedge::new(nodes, desc, embedding, 1.0);
455
456        let temporal = TemporalHyperedge::new(edge, TemporalGranularity::Hourly);
457
458        assert!(!temporal.is_expired());
459        assert!(temporal.time_bucket() > 0);
460    }
461
462    #[test]
463    fn test_hypergraph_index() {
464        let mut index = HypergraphIndex::new(DistanceMetric::Cosine);
465
466        // Add entities
467        index.add_entity("1".to_string(), vec![1.0, 0.0, 0.0]);
468        index.add_entity("2".to_string(), vec![0.0, 1.0, 0.0]);
469        index.add_entity("3".to_string(), vec![0.0, 0.0, 1.0]);
470
471        // Add hyperedge
472        let edge = Hyperedge::new(
473            vec!["1".to_string(), "2".to_string(), "3".to_string()],
474            "Triple relationship".to_string(),
475            vec![0.5, 0.5, 0.5],
476            0.9,
477        );
478        index.add_hyperedge(edge).unwrap();
479
480        let stats = index.stats();
481        assert_eq!(stats.total_entities, 3);
482        assert_eq!(stats.total_hyperedges, 1);
483    }
484
485    #[test]
486    fn test_k_hop_neighbors() {
487        let mut index = HypergraphIndex::new(DistanceMetric::Cosine);
488
489        // Create a small hypergraph
490        index.add_entity("1".to_string(), vec![1.0]);
491        index.add_entity("2".to_string(), vec![1.0]);
492        index.add_entity("3".to_string(), vec![1.0]);
493        index.add_entity("4".to_string(), vec![1.0]);
494
495        let edge1 = Hyperedge::new(
496            vec!["1".to_string(), "2".to_string()],
497            "e1".to_string(),
498            vec![1.0],
499            1.0,
500        );
501        let edge2 = Hyperedge::new(
502            vec!["2".to_string(), "3".to_string()],
503            "e2".to_string(),
504            vec![1.0],
505            1.0,
506        );
507        let edge3 = Hyperedge::new(
508            vec!["3".to_string(), "4".to_string()],
509            "e3".to_string(),
510            vec![1.0],
511            1.0,
512        );
513
514        index.add_hyperedge(edge1).unwrap();
515        index.add_hyperedge(edge2).unwrap();
516        index.add_hyperedge(edge3).unwrap();
517
518        let neighbors = index.k_hop_neighbors("1".to_string(), 2);
519        assert!(neighbors.contains(&"1".to_string()));
520        assert!(neighbors.contains(&"2".to_string()));
521        assert!(neighbors.contains(&"3".to_string()));
522    }
523
524    #[test]
525    fn test_causal_memory() {
526        let mut memory = CausalMemory::new(DistanceMetric::Cosine);
527
528        memory.index.add_entity("1".to_string(), vec![1.0, 0.0]);
529        memory.index.add_entity("2".to_string(), vec![0.0, 1.0]);
530
531        memory
532            .add_causal_edge(
533                "1".to_string(),
534                "2".to_string(),
535                vec![],
536                "Action 1 causes effect 2".to_string(),
537                vec![0.5, 0.5],
538                100.0,
539            )
540            .unwrap();
541
542        let results = memory.query_with_utility(&[0.6, 0.4], "1".to_string(), 5);
543        assert!(!results.is_empty());
544    }
545}