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
154            .entry(id)
155            .or_insert_with(HashSet::new);
156    }
157
158    /// Add a hyperedge
159    pub fn add_hyperedge(&mut self, hyperedge: Hyperedge) -> Result<()> {
160        let edge_id = hyperedge.id.clone();
161
162        // Verify all nodes exist
163        for node in &hyperedge.nodes {
164            if !self.entities.contains_key(node) {
165                return Err(RuvectorError::InvalidInput(format!(
166                    "Entity {} not found in hypergraph",
167                    node
168                )));
169            }
170        }
171
172        // Update bipartite graph
173        for node in &hyperedge.nodes {
174            self.entity_to_hyperedges
175                .entry(node.clone())
176                .or_insert_with(HashSet::new)
177                .insert(edge_id.clone());
178        }
179
180        let nodes_set: HashSet<VectorId> = hyperedge.nodes.iter().cloned().collect();
181        self.hyperedge_to_entities
182            .insert(edge_id.clone(), nodes_set);
183
184        self.hyperedges.insert(edge_id, hyperedge);
185        Ok(())
186    }
187
188    /// Add a temporal hyperedge
189    pub fn add_temporal_hyperedge(&mut self, temporal_edge: TemporalHyperedge) -> Result<()> {
190        let bucket = temporal_edge.time_bucket();
191        let edge_id = temporal_edge.hyperedge.id.clone();
192
193        self.add_hyperedge(temporal_edge.hyperedge)?;
194
195        self.temporal_index
196            .entry(bucket)
197            .or_insert_with(Vec::new)
198            .push(edge_id);
199
200        Ok(())
201    }
202
203    /// Search hyperedges by embedding similarity
204    pub fn search_hyperedges(&self, query_embedding: &[f32], k: usize) -> Vec<(String, f32)> {
205        let mut results: Vec<(String, f32)> = self
206            .hyperedges
207            .iter()
208            .map(|(id, edge)| {
209                let distance = self.compute_distance(query_embedding, &edge.embedding);
210                (id.clone(), distance)
211            })
212            .collect();
213
214        results.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
215        results.truncate(k);
216        results
217    }
218
219    /// Get k-hop neighbors in hypergraph
220    /// Returns all nodes reachable within k hops from the start node
221    pub fn k_hop_neighbors(&self, start_node: VectorId, k: usize) -> HashSet<VectorId> {
222        let mut visited = HashSet::new();
223        let mut current_layer = HashSet::new();
224        current_layer.insert(start_node.clone());
225        visited.insert(start_node); // Start node is at distance 0
226
227        for _hop in 0..k {
228            let mut next_layer = HashSet::new();
229
230            for node in current_layer.iter() {
231                // Get all hyperedges containing this node
232                if let Some(hyperedges) = self.entity_to_hyperedges.get(node) {
233                    for edge_id in hyperedges {
234                        // Get all nodes in this hyperedge
235                        if let Some(nodes) = self.hyperedge_to_entities.get(edge_id) {
236                            for neighbor in nodes.iter() {
237                                if !visited.contains(neighbor) {
238                                    visited.insert(neighbor.clone());
239                                    next_layer.insert(neighbor.clone());
240                                }
241                            }
242                        }
243                    }
244                }
245            }
246
247            if next_layer.is_empty() {
248                break;
249            }
250            current_layer = next_layer;
251        }
252
253        visited
254    }
255
256    /// Query temporal hyperedges in a time range
257    pub fn query_temporal_range(&self, start_bucket: u64, end_bucket: u64) -> Vec<String> {
258        let mut results = Vec::new();
259        for bucket in start_bucket..=end_bucket {
260            if let Some(edges) = self.temporal_index.get(&bucket) {
261                results.extend(edges.iter().cloned());
262            }
263        }
264        results
265    }
266
267    /// Get hyperedge by ID
268    pub fn get_hyperedge(&self, id: &str) -> Option<&Hyperedge> {
269        self.hyperedges.get(id)
270    }
271
272    /// Get statistics
273    pub fn stats(&self) -> HypergraphStats {
274        let total_edges = self.hyperedges.len();
275        let total_entities = self.entities.len();
276        let avg_degree = if total_entities > 0 {
277            self.entity_to_hyperedges
278                .values()
279                .map(|edges| edges.len())
280                .sum::<usize>() as f32
281                / total_entities as f32
282        } else {
283            0.0
284        };
285
286        HypergraphStats {
287            total_entities,
288            total_hyperedges: total_edges,
289            avg_entity_degree: avg_degree,
290        }
291    }
292
293    fn compute_distance(&self, a: &[f32], b: &[f32]) -> f32 {
294        crate::distance::distance(a, b, self.distance_metric).unwrap_or(f32::MAX)
295    }
296}
297
298/// Hypergraph statistics
299#[derive(Debug, Clone, Serialize, Deserialize)]
300pub struct HypergraphStats {
301    pub total_entities: usize,
302    pub total_hyperedges: usize,
303    pub avg_entity_degree: f32,
304}
305
306/// Causal hypergraph memory for agent reasoning
307pub struct CausalMemory {
308    /// Hypergraph index
309    index: HypergraphIndex,
310    /// Causal relationship tracking: (cause_id, effect_id) -> success_count
311    causal_counts: HashMap<(VectorId, VectorId), u32>,
312    /// Action latencies: action_id -> avg_latency_ms
313    latencies: HashMap<VectorId, f32>,
314    /// Utility function weights
315    alpha: f32, // similarity weight
316    beta: f32,  // causal uplift weight
317    gamma: f32, // latency penalty weight
318}
319
320impl CausalMemory {
321    /// Create a new causal memory with default utility weights
322    pub fn new(distance_metric: DistanceMetric) -> Self {
323        Self {
324            index: HypergraphIndex::new(distance_metric),
325            causal_counts: HashMap::new(),
326            latencies: HashMap::new(),
327            alpha: 0.7,
328            beta: 0.2,
329            gamma: 0.1,
330        }
331    }
332
333    /// Set custom utility function weights
334    pub fn with_weights(mut self, alpha: f32, beta: f32, gamma: f32) -> Self {
335        self.alpha = alpha;
336        self.beta = beta;
337        self.gamma = gamma;
338        self
339    }
340
341    /// Add a causal relationship
342    pub fn add_causal_edge(
343        &mut self,
344        cause: VectorId,
345        effect: VectorId,
346        context: Vec<VectorId>,
347        description: String,
348        embedding: Vec<f32>,
349        latency_ms: f32,
350    ) -> Result<()> {
351        // Create hyperedge connecting cause, effect, and context
352        let mut nodes = vec![cause.clone(), effect.clone()];
353        nodes.extend(context);
354
355        let hyperedge = Hyperedge::new(nodes, description, embedding, 1.0);
356        self.index.add_hyperedge(hyperedge)?;
357
358        // Update causal counts
359        *self
360            .causal_counts
361            .entry((cause.clone(), effect.clone()))
362            .or_insert(0) += 1;
363
364        // Update latency
365        let entry = self.latencies.entry(cause).or_insert(0.0);
366        *entry = (*entry + latency_ms) / 2.0; // Running average
367
368        Ok(())
369    }
370
371    /// Query with utility function: U = α·similarity + β·causal_uplift - γ·latency
372    pub fn query_with_utility(
373        &self,
374        query_embedding: &[f32],
375        action_id: VectorId,
376        k: usize,
377    ) -> Vec<(String, f32)> {
378        let mut results: Vec<(String, f32)> = self
379            .index
380            .hyperedges
381            .iter()
382            .filter(|(_, edge)| edge.contains_node(&action_id))
383            .map(|(id, edge)| {
384                let similarity = 1.0
385                    - self
386                        .index
387                        .compute_distance(query_embedding, &edge.embedding);
388                let causal_uplift = self.compute_causal_uplift(&edge.nodes);
389                let latency = self.latencies.get(&action_id).copied().unwrap_or(0.0);
390
391                let utility = self.alpha * similarity + self.beta * causal_uplift
392                    - self.gamma * (latency / 1000.0); // Normalize latency to 0-1 range
393
394                (id.clone(), utility)
395            })
396            .collect();
397
398        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); // Sort by utility descending
399        results.truncate(k);
400        results
401    }
402
403    fn compute_causal_uplift(&self, nodes: &[VectorId]) -> f32 {
404        if nodes.len() < 2 {
405            return 0.0;
406        }
407
408        // Compute average causal strength for pairs in this hyperedge
409        let mut total_uplift = 0.0;
410        let mut count = 0;
411
412        for i in 0..nodes.len() - 1 {
413            for j in i + 1..nodes.len() {
414                if let Some(&success_count) = self
415                    .causal_counts
416                    .get(&(nodes[i].clone(), nodes[j].clone()))
417                {
418                    total_uplift += (success_count as f32).ln_1p(); // Log scale
419                    count += 1;
420                }
421            }
422        }
423
424        if count > 0 {
425            total_uplift / count as f32
426        } else {
427            0.0
428        }
429    }
430
431    /// Get hypergraph index
432    pub fn index(&self) -> &HypergraphIndex {
433        &self.index
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn test_hyperedge_creation() {
443        let nodes = vec!["1".to_string(), "2".to_string(), "3".to_string()];
444        let desc = "Test relationship".to_string();
445        let embedding = vec![0.1, 0.2, 0.3];
446        let edge = Hyperedge::new(nodes, desc, embedding, 0.95);
447
448        assert_eq!(edge.order(), 3);
449        assert!(edge.contains_node(&"1".to_string()));
450        assert!(!edge.contains_node(&"4".to_string()));
451        assert_eq!(edge.confidence, 0.95);
452    }
453
454    #[test]
455    fn test_temporal_hyperedge() {
456        let nodes = vec!["1".to_string(), "2".to_string()];
457        let desc = "Temporal relationship".to_string();
458        let embedding = vec![0.1, 0.2];
459        let edge = Hyperedge::new(nodes, desc, embedding, 1.0);
460
461        let temporal = TemporalHyperedge::new(edge, TemporalGranularity::Hourly);
462
463        assert!(!temporal.is_expired());
464        assert!(temporal.time_bucket() > 0);
465    }
466
467    #[test]
468    fn test_hypergraph_index() {
469        let mut index = HypergraphIndex::new(DistanceMetric::Cosine);
470
471        // Add entities
472        index.add_entity("1".to_string(), vec![1.0, 0.0, 0.0]);
473        index.add_entity("2".to_string(), vec![0.0, 1.0, 0.0]);
474        index.add_entity("3".to_string(), vec![0.0, 0.0, 1.0]);
475
476        // Add hyperedge
477        let edge = Hyperedge::new(
478            vec!["1".to_string(), "2".to_string(), "3".to_string()],
479            "Triple relationship".to_string(),
480            vec![0.5, 0.5, 0.5],
481            0.9,
482        );
483        index.add_hyperedge(edge).unwrap();
484
485        let stats = index.stats();
486        assert_eq!(stats.total_entities, 3);
487        assert_eq!(stats.total_hyperedges, 1);
488    }
489
490    #[test]
491    fn test_k_hop_neighbors() {
492        let mut index = HypergraphIndex::new(DistanceMetric::Cosine);
493
494        // Create a small hypergraph
495        index.add_entity("1".to_string(), vec![1.0]);
496        index.add_entity("2".to_string(), vec![1.0]);
497        index.add_entity("3".to_string(), vec![1.0]);
498        index.add_entity("4".to_string(), vec![1.0]);
499
500        let edge1 = Hyperedge::new(vec!["1".to_string(), "2".to_string()], "e1".to_string(), vec![1.0], 1.0);
501        let edge2 = Hyperedge::new(vec!["2".to_string(), "3".to_string()], "e2".to_string(), vec![1.0], 1.0);
502        let edge3 = Hyperedge::new(vec!["3".to_string(), "4".to_string()], "e3".to_string(), vec![1.0], 1.0);
503
504        index.add_hyperedge(edge1).unwrap();
505        index.add_hyperedge(edge2).unwrap();
506        index.add_hyperedge(edge3).unwrap();
507
508        let neighbors = index.k_hop_neighbors("1".to_string(), 2);
509        assert!(neighbors.contains(&"1".to_string()));
510        assert!(neighbors.contains(&"2".to_string()));
511        assert!(neighbors.contains(&"3".to_string()));
512    }
513
514    #[test]
515    fn test_causal_memory() {
516        let mut memory = CausalMemory::new(DistanceMetric::Cosine);
517
518        memory.index.add_entity("1".to_string(), vec![1.0, 0.0]);
519        memory.index.add_entity("2".to_string(), vec![0.0, 1.0]);
520
521        memory
522            .add_causal_edge(
523                "1".to_string(),
524                "2".to_string(),
525                vec![],
526                "Action 1 causes effect 2".to_string(),
527                vec![0.5, 0.5],
528                100.0,
529            )
530            .unwrap();
531
532        let results = memory.query_with_utility(&[0.6, 0.4], "1".to_string(), 5);
533        assert!(!results.is_empty());
534    }
535}