oxirs-embed 0.2.4

Knowledge graph embeddings with TransE, ComplEx, and custom models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Temporal Embeddings Module for Time-Aware Knowledge Graph Embeddings
//!
//! This module provides temporal embedding capabilities for knowledge graphs
//! that evolve over time, capturing temporal patterns and dynamics.
//!
//! ## Features
//!
//! - **Time-Aware Embeddings**: Embed entities/relations with temporal context
//! - **Temporal Evolution**: Track how embeddings change over time
//! - **Time Series Analysis**: Analyze temporal patterns in knowledge graphs
//! - **Temporal Queries**: Support time-based queries and predictions
//! - **Event Detection**: Detect significant temporal events
//! - **Forecasting**: Predict future entity/relation states
//!
//! ## Temporal Models
//!
//! - **TTransE**: Temporal extension of TransE
//! - **TA-DistMult**: Time-aware DistMult
//! - **DE-SimplE**: Diachronic embedding model
//! - **ChronoR**: Recurrent temporal embeddings
//! - **TeMP**: Temporal message passing
//!
//! ## Use Cases
//!
//! - Historical data analysis
//! - Event prediction
//! - Temporal reasoning
//! - Dynamic knowledge graphs
//! - Time-series forecasting

use anyhow::Result;
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info};

use crate::{ModelConfig, TrainingStats, Triple, Vector};
use uuid::Uuid;

// Type aliases to simplify complex types
type TemporalEntityEmbeddings = Arc<RwLock<HashMap<String, BTreeMap<DateTime<Utc>, Vector>>>>;
type TemporalRelationEmbeddings = Arc<RwLock<HashMap<String, BTreeMap<DateTime<Utc>, Vector>>>>;

// Placeholder for time series analysis (will be implemented with scirs2-stats)
#[derive(Debug, Clone, Default)]
pub struct TimeSeriesAnalyzer;

#[derive(Debug, Clone)]
pub enum ForecastMethod {
    ExponentialSmoothing,
    Arima,
    Prophet,
}

/// Temporal granularity
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum TemporalGranularity {
    /// Second-level precision
    Second,
    /// Minute-level precision
    Minute,
    /// Hour-level precision
    Hour,
    /// Day-level precision
    Day,
    /// Week-level precision
    Week,
    /// Month-level precision
    Month,
    /// Year-level precision
    Year,
    /// Custom duration
    Custom(i64), // seconds
}

/// Temporal scope
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TemporalScope {
    /// Point in time
    Instant(DateTime<Utc>),
    /// Time interval
    Interval {
        start: DateTime<Utc>,
        end: DateTime<Utc>,
    },
    /// Periodic (e.g., every Monday)
    Periodic {
        start: DateTime<Utc>,
        period: Duration,
        count: Option<usize>,
    },
    /// Unbounded (always valid)
    Unbounded,
}

/// Temporal triple with time information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalTriple {
    /// The RDF triple
    pub triple: Triple,
    /// Temporal scope when this triple is valid
    pub scope: TemporalScope,
    /// Confidence score (0.0-1.0)
    pub confidence: f32,
    /// Source/provenance information
    pub source: Option<String>,
}

impl TemporalTriple {
    /// Create a new temporal triple
    pub fn new(triple: Triple, scope: TemporalScope) -> Self {
        Self {
            triple,
            scope,
            confidence: 1.0,
            source: None,
        }
    }

    /// Check if this triple is valid at the given time
    pub fn is_valid_at(&self, time: &DateTime<Utc>) -> bool {
        match &self.scope {
            TemporalScope::Instant(instant) => instant == time,
            TemporalScope::Interval { start, end } => time >= start && time <= end,
            TemporalScope::Periodic {
                start,
                period,
                count,
            } => {
                let elapsed = time.signed_duration_since(*start);
                if elapsed < Duration::zero() {
                    return false;
                }
                if let Some(max_count) = count {
                    let num_periods = elapsed.num_seconds() / period.num_seconds();
                    num_periods < *max_count as i64
                } else {
                    true
                }
            }
            TemporalScope::Unbounded => true,
        }
    }
}

/// Temporal embedding configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalEmbeddingConfig {
    /// Base model configuration
    pub base_config: ModelConfig,
    /// Temporal granularity
    pub granularity: TemporalGranularity,
    /// Time embedding dimensions
    pub time_dim: usize,
    /// Enable temporal decay
    pub enable_decay: bool,
    /// Decay rate (for exponential decay)
    pub decay_rate: f32,
    /// Enable temporal smoothing
    pub enable_smoothing: bool,
    /// Smoothing window size
    pub smoothing_window: usize,
    /// Enable forecasting
    pub enable_forecasting: bool,
    /// Forecast horizon (number of time steps)
    pub forecast_horizon: usize,
    /// Enable event detection
    pub enable_event_detection: bool,
    /// Event threshold
    pub event_threshold: f32,
}

impl Default for TemporalEmbeddingConfig {
    fn default() -> Self {
        Self {
            base_config: ModelConfig::default(),
            granularity: TemporalGranularity::Day,
            time_dim: 32,
            enable_decay: true,
            decay_rate: 0.9,
            enable_smoothing: true,
            smoothing_window: 7,
            enable_forecasting: true,
            forecast_horizon: 30,
            enable_event_detection: false,
            event_threshold: 0.7,
        }
    }
}

/// Temporal event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalEvent {
    /// Event ID
    pub event_id: String,
    /// Event type
    pub event_type: String,
    /// Timestamp
    pub timestamp: DateTime<Utc>,
    /// Entities involved
    pub entities: Vec<String>,
    /// Relations involved
    pub relations: Vec<String>,
    /// Event significance score
    pub significance: f32,
    /// Event description
    pub description: Option<String>,
}

/// Temporal forecast result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalForecast {
    /// Entity or relation being forecasted
    pub target: String,
    /// Forecast timestamps
    pub timestamps: Vec<DateTime<Utc>>,
    /// Predicted embeddings
    pub predictions: Vec<Vector>,
    /// Confidence intervals (lower, upper)
    pub confidence_intervals: Vec<(Vector, Vector)>,
    /// Forecast accuracy (if validation data available)
    pub accuracy: Option<f32>,
}

/// Temporal embedding model
pub struct TemporalEmbeddingModel {
    config: TemporalEmbeddingConfig,
    model_id: Uuid,

    // Entity embeddings over time: entity -> time -> embedding
    entity_embeddings: TemporalEntityEmbeddings,

    // Relation embeddings over time: relation -> time -> embedding
    relation_embeddings: TemporalRelationEmbeddings,

    // Time embeddings: timestamp -> time embedding
    time_embeddings: Arc<RwLock<BTreeMap<DateTime<Utc>, Vector>>>,

    // Temporal triples
    temporal_triples: Arc<RwLock<Vec<TemporalTriple>>>,

    // Detected events
    events: Arc<RwLock<Vec<TemporalEvent>>>,

    // Time series analyzer
    time_series_analyzer: Option<TimeSeriesAnalyzer>,

    // Training state
    is_trained: Arc<RwLock<bool>>,
}

impl TemporalEmbeddingModel {
    /// Create a new temporal embedding model
    pub fn new(config: TemporalEmbeddingConfig) -> Self {
        info!(
            "Creating temporal embedding model with time_dim={}",
            config.time_dim
        );

        Self {
            model_id: Uuid::new_v4(),
            time_series_analyzer: Some(TimeSeriesAnalyzer),
            config,
            entity_embeddings: Arc::new(RwLock::new(HashMap::new())),
            relation_embeddings: Arc::new(RwLock::new(HashMap::new())),
            time_embeddings: Arc::new(RwLock::new(BTreeMap::new())),
            temporal_triples: Arc::new(RwLock::new(Vec::new())),
            events: Arc::new(RwLock::new(Vec::new())),
            is_trained: Arc::new(RwLock::new(false)),
        }
    }

    /// Add a temporal triple
    pub async fn add_temporal_triple(&mut self, temporal_triple: TemporalTriple) -> Result<()> {
        let mut triples = self.temporal_triples.write().await;
        triples.push(temporal_triple);
        Ok(())
    }

    /// Get entity embedding at a specific time
    pub async fn get_entity_embedding_at_time(
        &self,
        entity: &str,
        time: &DateTime<Utc>,
    ) -> Result<Vector> {
        let embeddings = self.entity_embeddings.read().await;

        if let Some(time_series) = embeddings.get(entity) {
            // Find the closest time point
            if let Some((_, embedding)) = time_series.range(..=time).next_back() {
                return Ok(embedding.clone());
            }
        }

        Err(anyhow::anyhow!(
            "Entity '{}' not found at time {}",
            entity,
            time
        ))
    }

    /// Get relation embedding at a specific time
    pub async fn get_relation_embedding_at_time(
        &self,
        relation: &str,
        time: &DateTime<Utc>,
    ) -> Result<Vector> {
        let embeddings = self.relation_embeddings.read().await;

        if let Some(time_series) = embeddings.get(relation) {
            // Find the closest time point
            if let Some((_, embedding)) = time_series.range(..=time).next_back() {
                return Ok(embedding.clone());
            }
        }

        Err(anyhow::anyhow!(
            "Relation '{}' not found at time {}",
            relation,
            time
        ))
    }

    /// Train temporal embeddings
    pub async fn train_temporal(&mut self, epochs: usize) -> Result<TrainingStats> {
        info!("Training temporal embeddings for {} epochs", epochs);

        let start_time = std::time::Instant::now();
        let mut loss_history = Vec::new();

        for epoch in 0..epochs {
            let loss = self.train_epoch(epoch).await?;
            loss_history.push(loss);

            if epoch % 10 == 0 {
                debug!("Epoch {}/{}: loss={:.6}", epoch + 1, epochs, loss);
            }
        }

        *self.is_trained.write().await = true;

        let elapsed = start_time.elapsed().as_secs_f64();
        let final_loss = *loss_history.last().unwrap_or(&0.0);

        info!(
            "Temporal training completed in {:.2}s, final loss: {:.6}",
            elapsed, final_loss
        );

        Ok(TrainingStats {
            epochs_completed: epochs,
            final_loss,
            training_time_seconds: elapsed,
            convergence_achieved: final_loss < 0.01,
            loss_history,
        })
    }

    /// Train a single epoch
    async fn train_epoch(&mut self, _epoch: usize) -> Result<f64> {
        // Simplified training - in a real implementation, this would:
        // 1. Sample temporal triples
        // 2. Compute time-aware embeddings
        // 3. Calculate temporal loss (considering time decay)
        // 4. Update embeddings with gradient descent

        // Initialize some sample embeddings for testing
        let triples = self.temporal_triples.read().await;
        let dim = self.config.base_config.dimensions;

        use scirs2_core::random::Random;
        let mut rng = Random::default();

        for temporal_triple in triples.iter() {
            let embedding = Vector::new(
                (0..dim)
                    .map(|_| rng.random_range(-1.0..1.0) as f32)
                    .collect(),
            );

            // Store embedding with timestamp
            let timestamp = match &temporal_triple.scope {
                TemporalScope::Instant(t) => *t,
                TemporalScope::Interval { start, .. } => *start,
                _ => Utc::now(),
            };

            let entity = temporal_triple.triple.subject.iri.clone();
            let mut entity_embs = self.entity_embeddings.write().await;
            entity_embs
                .entry(entity)
                .or_insert_with(BTreeMap::new)
                .insert(timestamp, embedding);
        }

        Ok(0.1) // Simplified loss
    }

    /// Forecast future embeddings
    pub async fn forecast(&self, entity: &str, horizon: usize) -> Result<TemporalForecast> {
        info!(
            "Forecasting {} time steps ahead for entity: {}",
            horizon, entity
        );

        let embeddings = self.entity_embeddings.read().await;

        if let Some(time_series) = embeddings.get(entity) {
            let timestamps: Vec<DateTime<Utc>> = time_series.keys().cloned().collect();
            let last_time = timestamps
                .last()
                .ok_or_else(|| anyhow::anyhow!("No temporal data for entity: {}", entity))?;

            // Generate future timestamps based on granularity
            let time_step = match self.config.granularity {
                TemporalGranularity::Second => Duration::seconds(1),
                TemporalGranularity::Minute => Duration::minutes(1),
                TemporalGranularity::Hour => Duration::hours(1),
                TemporalGranularity::Day => Duration::days(1),
                TemporalGranularity::Week => Duration::weeks(1),
                TemporalGranularity::Month => Duration::days(30),
                TemporalGranularity::Year => Duration::days(365),
                TemporalGranularity::Custom(secs) => Duration::seconds(secs),
            };

            let mut future_timestamps = Vec::new();
            let mut predictions = Vec::new();
            let mut confidence_intervals = Vec::new();

            for i in 1..=horizon {
                let future_time = *last_time + time_step * i as i32;
                future_timestamps.push(future_time);

                // Simple forecasting: use last known embedding with decay
                let last_embedding = time_series
                    .values()
                    .last()
                    .expect("time_series should have at least one embedding");
                let decay_factor = self.config.decay_rate.powi(i as i32);

                let prediction = last_embedding.mapv(|v| v * decay_factor);
                let std_dev = 0.1 * (1.0 - decay_factor);

                let lower = last_embedding.mapv(|v| (v * decay_factor) - std_dev);
                let upper = last_embedding.mapv(|v| (v * decay_factor) + std_dev);

                predictions.push(prediction);
                confidence_intervals.push((lower, upper));
            }

            Ok(TemporalForecast {
                target: entity.to_string(),
                timestamps: future_timestamps,
                predictions,
                confidence_intervals,
                accuracy: None,
            })
        } else {
            Err(anyhow::anyhow!("Entity '{}' not found", entity))
        }
    }

    /// Detect temporal events
    pub async fn detect_events(&mut self, threshold: f32) -> Result<Vec<TemporalEvent>> {
        info!("Detecting temporal events with threshold: {}", threshold);

        let entity_embeddings = self.entity_embeddings.read().await;
        let mut detected_events = Vec::new();

        // Detect significant changes in embeddings over time
        for (entity, time_series) in entity_embeddings.iter() {
            let mut prev_embedding: Option<&Vector> = None;
            let mut prev_time: Option<&DateTime<Utc>> = None;

            for (time, embedding) in time_series.iter() {
                if let (Some(prev_emb), Some(prev_t)) = (prev_embedding, prev_time) {
                    // Calculate change magnitude
                    let diff: Vec<f32> = embedding
                        .values
                        .iter()
                        .zip(prev_emb.values.iter())
                        .map(|(a, b)| (a - b).abs())
                        .collect();
                    let change_magnitude = diff.iter().sum::<f32>() / diff.len() as f32;

                    if change_magnitude > threshold {
                        let event = TemporalEvent {
                            event_id: format!("event_{}_{}", entity, time.timestamp()),
                            event_type: "embedding_shift".to_string(),
                            timestamp: *time,
                            entities: vec![entity.clone()],
                            relations: Vec::new(),
                            significance: change_magnitude,
                            description: Some(format!(
                                "Significant embedding change detected for '{}' between {} and {}",
                                entity, prev_t, time
                            )),
                        };
                        detected_events.push(event);
                    }
                }

                prev_embedding = Some(embedding);
                prev_time = Some(time);
            }
        }

        // Store detected events
        let mut events = self.events.write().await;
        events.extend(detected_events.clone());

        info!("Detected {} temporal events", detected_events.len());
        Ok(detected_events)
    }

    /// Get all detected events
    pub async fn get_events(&self) -> Vec<TemporalEvent> {
        self.events.read().await.clone()
    }

    /// Query triples valid at a specific time
    pub async fn query_at_time(&self, time: &DateTime<Utc>) -> Vec<Triple> {
        let triples = self.temporal_triples.read().await;
        triples
            .iter()
            .filter(|tt| tt.is_valid_at(time))
            .map(|tt| tt.triple.clone())
            .collect()
    }

    /// Get temporal statistics
    pub async fn get_temporal_stats(&self) -> TemporalStats {
        let entity_embeddings = self.entity_embeddings.read().await;
        let relation_embeddings = self.relation_embeddings.read().await;
        let triples = self.temporal_triples.read().await;
        let events = self.events.read().await;

        // Calculate time span
        let all_times: Vec<DateTime<Utc>> = entity_embeddings
            .values()
            .flat_map(|ts| ts.keys().cloned())
            .collect();

        let (min_time, max_time) = if all_times.is_empty() {
            (None, None)
        } else {
            (
                all_times.iter().min().cloned(),
                all_times.iter().max().cloned(),
            )
        };

        TemporalStats {
            num_temporal_triples: triples.len(),
            num_entities: entity_embeddings.len(),
            num_relations: relation_embeddings.len(),
            num_time_points: all_times.len(),
            num_events: events.len(),
            time_span_start: min_time,
            time_span_end: max_time,
            granularity: self.config.granularity.clone(),
        }
    }
}

/// Temporal statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalStats {
    pub num_temporal_triples: usize,
    pub num_entities: usize,
    pub num_relations: usize,
    pub num_time_points: usize,
    pub num_events: usize,
    pub time_span_start: Option<DateTime<Utc>>,
    pub time_span_end: Option<DateTime<Utc>>,
    pub granularity: TemporalGranularity,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::NamedNode;

    #[tokio::test]
    async fn test_temporal_model_creation() {
        let config = TemporalEmbeddingConfig::default();
        let model = TemporalEmbeddingModel::new(config);
        assert_eq!(model.config.time_dim, 32);
    }

    #[tokio::test]
    async fn test_temporal_triple_validity() {
        let triple = Triple::new(
            NamedNode::new("http://example.org/alice").expect("should succeed"),
            NamedNode::new("http://example.org/worksFor").expect("should succeed"),
            NamedNode::new("http://example.org/company").expect("should succeed"),
        );

        let start = Utc::now();
        let end = start + Duration::days(365);

        let temporal_triple = TemporalTriple::new(triple, TemporalScope::Interval { start, end });

        let now = Utc::now();
        assert!(temporal_triple.is_valid_at(&now));

        let future = now + Duration::days(400);
        assert!(!temporal_triple.is_valid_at(&future));
    }

    #[tokio::test]
    async fn test_temporal_embedding_add_triple() {
        let config = TemporalEmbeddingConfig::default();
        let mut model = TemporalEmbeddingModel::new(config);

        let triple = Triple::new(
            NamedNode::new("http://example.org/alice").expect("should succeed"),
            NamedNode::new("http://example.org/knows").expect("should succeed"),
            NamedNode::new("http://example.org/bob").expect("should succeed"),
        );

        let temporal_triple = TemporalTriple::new(triple, TemporalScope::Instant(Utc::now()));

        model
            .add_temporal_triple(temporal_triple)
            .await
            .expect("should succeed");

        let stats = model.get_temporal_stats().await;
        assert_eq!(stats.num_temporal_triples, 1);
    }

    #[tokio::test]
    async fn test_temporal_training() {
        let config = TemporalEmbeddingConfig::default();
        let mut model = TemporalEmbeddingModel::new(config);

        // Add some temporal triples
        for i in 0..5 {
            let triple = Triple::new(
                NamedNode::new(&format!("http://example.org/entity_{}", i))
                    .expect("should succeed"),
                NamedNode::new("http://example.org/relation").expect("should succeed"),
                NamedNode::new("http://example.org/target").expect("should succeed"),
            );

            let temporal_triple = TemporalTriple::new(
                triple,
                TemporalScope::Instant(Utc::now() + Duration::days(i)),
            );

            model
                .add_temporal_triple(temporal_triple)
                .await
                .expect("should succeed");
        }

        let stats = model.train_temporal(10).await.expect("should succeed");
        assert_eq!(stats.epochs_completed, 10);
        assert!(stats.final_loss >= 0.0);
    }

    #[tokio::test]
    async fn test_temporal_forecasting() {
        let config = TemporalEmbeddingConfig::default();
        let mut model = TemporalEmbeddingModel::new(config);

        // Add temporal data
        let triple = Triple::new(
            NamedNode::new("http://example.org/entity").expect("should succeed"),
            NamedNode::new("http://example.org/relation").expect("should succeed"),
            NamedNode::new("http://example.org/target").expect("should succeed"),
        );

        let temporal_triple = TemporalTriple::new(triple, TemporalScope::Instant(Utc::now()));

        model
            .add_temporal_triple(temporal_triple)
            .await
            .expect("should succeed");
        model.train_temporal(5).await.expect("should succeed");

        let forecast = model
            .forecast("http://example.org/entity", 10)
            .await
            .expect("should succeed");
        assert_eq!(forecast.predictions.len(), 10);
        assert_eq!(forecast.timestamps.len(), 10);
    }

    #[tokio::test]
    async fn test_event_detection() {
        let config = TemporalEmbeddingConfig {
            event_threshold: 0.3,
            ..Default::default()
        };
        let mut model = TemporalEmbeddingModel::new(config);

        // Add temporal triples and train
        for i in 0..3 {
            let triple = Triple::new(
                NamedNode::new("http://example.org/entity").expect("should succeed"),
                NamedNode::new("http://example.org/relation").expect("should succeed"),
                NamedNode::new("http://example.org/target").expect("should succeed"),
            );

            let temporal_triple = TemporalTriple::new(
                triple,
                TemporalScope::Instant(Utc::now() + Duration::days(i)),
            );

            model
                .add_temporal_triple(temporal_triple)
                .await
                .expect("should succeed");
        }

        model.train_temporal(5).await.expect("should succeed");
        let _events = model.detect_events(0.3).await.expect("should succeed");

        // Events may or may not be detected depending on random initialization
        // Just verify the function executes without error (verified by unwrap)
    }
}