oxirs-star 0.2.4

RDF-star and SPARQL-star grammar support for quoted triples
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
//! Graph diff tool for comparing annotated RDF-star graphs
//!
//! This module provides comprehensive diff capabilities for RDF-star graphs,
//! including triple comparison, annotation changes, provenance tracking,
//! and multiple output formats.

use crate::annotations::{AnnotationStore, ProvenanceRecord, TripleAnnotation};
use crate::model::{StarGraph, StarTriple};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use thiserror::Error;
use tracing::info;

/// Errors related to graph diff operations
#[derive(Error, Debug)]
pub enum DiffError {
    #[error("Comparison failed: {0}")]
    ComparisonFailed(String),

    #[error("Invalid graph: {0}")]
    InvalidGraph(String),

    #[error("Serialization error: {0}")]
    SerializationError(String),
}

/// Type of change in a diff
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ChangeType {
    /// Triple added in new version
    Added,
    /// Triple removed from old version
    Removed,
    /// Triple exists in both but annotations changed
    Modified,
    /// Triple unchanged
    Unchanged,
}

impl fmt::Display for ChangeType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ChangeType::Added => write!(f, "ADDED"),
            ChangeType::Removed => write!(f, "REMOVED"),
            ChangeType::Modified => write!(f, "MODIFIED"),
            ChangeType::Unchanged => write!(f, "UNCHANGED"),
        }
    }
}

/// Annotation change details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnnotationChange {
    /// Type of change
    pub change_type: ChangeType,

    /// Old annotation (if exists)
    pub old_annotation: Option<TripleAnnotation>,

    /// New annotation (if exists)
    pub new_annotation: Option<TripleAnnotation>,

    /// Specific fields that changed
    pub changed_fields: Vec<String>,

    /// Provenance changes
    pub provenance_changes: Vec<ProvenanceChange>,
}

/// Provenance change details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProvenanceChange {
    /// Change type
    pub change_type: ChangeType,

    /// Old provenance
    pub old_provenance: Option<ProvenanceRecord>,

    /// New provenance
    pub new_provenance: Option<ProvenanceRecord>,
}

/// Triple difference entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TripleDiff {
    /// The triple being compared
    pub triple: StarTriple,

    /// Type of change
    pub change_type: ChangeType,

    /// Annotation changes
    pub annotation_changes: Option<AnnotationChange>,

    /// Context information
    pub context: HashMap<String, String>,
}

/// Graph diff result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphDiff {
    /// Comparison timestamp
    pub timestamp: DateTime<Utc>,

    /// Old graph identifier
    pub old_id: String,

    /// New graph identifier
    pub new_id: String,

    /// All differences
    pub differences: Vec<TripleDiff>,

    /// Summary statistics
    pub summary: DiffSummary,

    /// Comparison options used
    pub options: DiffOptions,
}

/// Diff summary statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiffSummary {
    /// Total triples in old graph
    pub old_triple_count: usize,

    /// Total triples in new graph
    pub new_triple_count: usize,

    /// Number of added triples
    pub added_count: usize,

    /// Number of removed triples
    pub removed_count: usize,

    /// Number of modified triples
    pub modified_count: usize,

    /// Number of unchanged triples
    pub unchanged_count: usize,

    /// Total annotation changes
    pub annotation_changes_count: usize,

    /// Total provenance changes
    pub provenance_changes_count: usize,

    /// Similarity percentage
    pub similarity_percentage: f64,
}

impl DiffSummary {
    /// Calculate similarity percentage
    fn calculate_similarity(old_count: usize, new_count: usize, unchanged: usize) -> f64 {
        let total = old_count.max(new_count);
        if total == 0 {
            100.0
        } else {
            (unchanged as f64 / total as f64) * 100.0
        }
    }
}

/// Options for diff comparison
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiffOptions {
    /// Compare annotations
    pub compare_annotations: bool,

    /// Compare provenance chains
    pub compare_provenance: bool,

    /// Compare trust scores
    pub compare_trust_scores: bool,

    /// Compare timestamps
    pub compare_timestamps: bool,

    /// Include unchanged triples in output
    pub include_unchanged: bool,

    /// Ignore metadata changes
    pub ignore_metadata: bool,

    /// Context depth for nested triples
    pub context_depth: usize,
}

impl Default for DiffOptions {
    fn default() -> Self {
        Self {
            compare_annotations: true,
            compare_provenance: true,
            compare_trust_scores: true,
            compare_timestamps: false,
            include_unchanged: false,
            ignore_metadata: false,
            context_depth: 10,
        }
    }
}

/// Graph diff tool
pub struct GraphDiffTool {
    /// Comparison options
    options: DiffOptions,
}

impl GraphDiffTool {
    /// Create a new diff tool with default options
    pub fn new() -> Self {
        Self {
            options: DiffOptions::default(),
        }
    }

    /// Create with custom options
    pub fn with_options(options: DiffOptions) -> Self {
        Self { options }
    }

    /// Compare two graphs
    pub fn compare(
        &self,
        old_graph: &StarGraph,
        new_graph: &StarGraph,
        old_annotations: Option<&AnnotationStore>,
        new_annotations: Option<&AnnotationStore>,
    ) -> Result<GraphDiff, DiffError> {
        info!("Starting graph comparison");

        let old_triples: HashSet<StarTriple> = old_graph.triples().iter().cloned().collect();
        let new_triples: HashSet<StarTriple> = new_graph.triples().iter().cloned().collect();

        let mut differences = Vec::new();

        // Find added triples
        for triple in new_triples.difference(&old_triples) {
            let annotation_changes = if self.options.compare_annotations {
                self.get_annotation_changes(triple, None, new_annotations)?
            } else {
                None
            };

            differences.push(TripleDiff {
                triple: triple.clone(),
                change_type: ChangeType::Added,
                annotation_changes,
                context: HashMap::new(),
            });
        }

        // Find removed triples
        for triple in old_triples.difference(&new_triples) {
            let annotation_changes = if self.options.compare_annotations {
                self.get_annotation_changes(triple, old_annotations, None)?
            } else {
                None
            };

            differences.push(TripleDiff {
                triple: triple.clone(),
                change_type: ChangeType::Removed,
                annotation_changes,
                context: HashMap::new(),
            });
        }

        // Find unchanged/modified triples
        for triple in old_triples.intersection(&new_triples) {
            let annotation_changes = if self.options.compare_annotations {
                self.compare_annotations(triple, old_annotations, new_annotations)?
            } else {
                None
            };

            let change_type = if annotation_changes.is_some() {
                ChangeType::Modified
            } else {
                ChangeType::Unchanged
            };

            if self.options.include_unchanged || change_type == ChangeType::Modified {
                differences.push(TripleDiff {
                    triple: triple.clone(),
                    change_type,
                    annotation_changes,
                    context: HashMap::new(),
                });
            }
        }

        // Calculate summary
        let added_count = differences
            .iter()
            .filter(|d| d.change_type == ChangeType::Added)
            .count();
        let removed_count = differences
            .iter()
            .filter(|d| d.change_type == ChangeType::Removed)
            .count();
        let modified_count = differences
            .iter()
            .filter(|d| d.change_type == ChangeType::Modified)
            .count();
        let unchanged_count = old_triples
            .intersection(&new_triples)
            .count()
            .saturating_sub(modified_count);

        let annotation_changes_count = differences
            .iter()
            .filter(|d| d.annotation_changes.is_some())
            .count();

        let provenance_changes_count: usize = differences
            .iter()
            .filter_map(|d| d.annotation_changes.as_ref())
            .map(|ac| ac.provenance_changes.len())
            .sum();

        let similarity_percentage = DiffSummary::calculate_similarity(
            old_triples.len(),
            new_triples.len(),
            unchanged_count,
        );

        let summary = DiffSummary {
            old_triple_count: old_triples.len(),
            new_triple_count: new_triples.len(),
            added_count,
            removed_count,
            modified_count,
            unchanged_count,
            annotation_changes_count,
            provenance_changes_count,
            similarity_percentage,
        };

        Ok(GraphDiff {
            timestamp: Utc::now(),
            old_id: format!("old_{}", old_graph.len()),
            new_id: format!("new_{}", new_graph.len()),
            differences,
            summary,
            options: self.options.clone(),
        })
    }

    /// Get annotation changes for a triple (added/removed)
    fn get_annotation_changes(
        &self,
        triple: &StarTriple,
        old_store: Option<&AnnotationStore>,
        new_store: Option<&AnnotationStore>,
    ) -> Result<Option<AnnotationChange>, DiffError> {
        let old_annotation = old_store.and_then(|store| store.get_annotation(triple));
        let new_annotation = new_store.and_then(|store| store.get_annotation(triple));

        if old_annotation.is_none() && new_annotation.is_none() {
            return Ok(None);
        }

        let change_type = match (&old_annotation, &new_annotation) {
            (None, Some(_)) => ChangeType::Added,
            (Some(_), None) => ChangeType::Removed,
            _ => ChangeType::Modified,
        };

        Ok(Some(AnnotationChange {
            change_type,
            old_annotation: old_annotation.cloned(),
            new_annotation: new_annotation.cloned(),
            changed_fields: vec![],
            provenance_changes: vec![],
        }))
    }

    /// Compare annotations for a triple that exists in both graphs
    fn compare_annotations(
        &self,
        triple: &StarTriple,
        old_store: Option<&AnnotationStore>,
        new_store: Option<&AnnotationStore>,
    ) -> Result<Option<AnnotationChange>, DiffError> {
        let old_annotation = old_store.and_then(|store| store.get_annotation(triple));
        let new_annotation = new_store.and_then(|store| store.get_annotation(triple));

        match (old_annotation, new_annotation) {
            (Some(old), Some(new)) => {
                let mut changed_fields = Vec::new();
                let provenance_changes = Vec::new();

                // Compare confidence
                if self.options.compare_trust_scores && old.confidence != new.confidence {
                    changed_fields.push("confidence".to_string());
                }

                // Compare source
                if old.source != new.source {
                    changed_fields.push("source".to_string());
                }

                // Compare timestamps
                if self.options.compare_timestamps && old.timestamp != new.timestamp {
                    changed_fields.push("timestamp".to_string());
                }

                // Compare provenance counts (simplified)
                if self.options.compare_provenance {
                    let old_prov_count = old.provenance.len();
                    let new_prov_count = new.provenance.len();

                    if old_prov_count != new_prov_count {
                        changed_fields.push("provenance_count".to_string());
                    }
                }

                if changed_fields.is_empty() && provenance_changes.is_empty() {
                    Ok(None)
                } else {
                    Ok(Some(AnnotationChange {
                        change_type: ChangeType::Modified,
                        old_annotation: Some(old.clone()),
                        new_annotation: Some(new.clone()),
                        changed_fields,
                        provenance_changes,
                    }))
                }
            }
            (Some(_), None) => self.get_annotation_changes(triple, old_store, new_store),
            (None, Some(_)) => self.get_annotation_changes(triple, old_store, new_store),
            (None, None) => Ok(None),
        }
    }

    /// Format diff as human-readable text
    pub fn format_text(&self, diff: &GraphDiff) -> String {
        let mut output = String::new();

        output.push_str("=== Graph Diff Report ===\n\n");
        output.push_str(&format!("Timestamp: {}\n", diff.timestamp));
        output.push_str(&format!("Old Graph: {}\n", diff.old_id));
        output.push_str(&format!("New Graph: {}\n\n", diff.new_id));

        output.push_str("--- Summary ---\n");
        output.push_str(&format!("Old triples: {}\n", diff.summary.old_triple_count));
        output.push_str(&format!("New triples: {}\n", diff.summary.new_triple_count));
        output.push_str(&format!("Added: {}\n", diff.summary.added_count));
        output.push_str(&format!("Removed: {}\n", diff.summary.removed_count));
        output.push_str(&format!("Modified: {}\n", diff.summary.modified_count));
        output.push_str(&format!("Unchanged: {}\n", diff.summary.unchanged_count));
        output.push_str(&format!(
            "Similarity: {:.2}%\n\n",
            diff.summary.similarity_percentage
        ));

        output.push_str("--- Changes ---\n");
        for (i, change) in diff.differences.iter().enumerate() {
            output.push_str(&format!(
                "\n{}. {} {}\n",
                i + 1,
                change.change_type,
                self.format_triple(&change.triple)
            ));

            if let Some(ref ann_change) = change.annotation_changes {
                output.push_str("   Annotation changes:\n");
                for field in &ann_change.changed_fields {
                    output.push_str(&format!("   - {}\n", field));
                }
                if !ann_change.provenance_changes.is_empty() {
                    output.push_str(&format!(
                        "   - {} provenance changes\n",
                        ann_change.provenance_changes.len()
                    ));
                }
            }
        }

        output
    }

    /// Format triple as string
    fn format_triple(&self, triple: &StarTriple) -> String {
        format!(
            "<{:?} {:?} {:?}>",
            triple.subject, triple.predicate, triple.object
        )
    }

    /// Export diff to JSON
    pub fn export_json(&self, diff: &GraphDiff) -> Result<String, DiffError> {
        serde_json::to_string_pretty(diff).map_err(|e| DiffError::SerializationError(e.to_string()))
    }

    /// Get options
    pub fn options(&self) -> &DiffOptions {
        &self.options
    }
}

impl Default for GraphDiffTool {
    fn default() -> Self {
        Self::new()
    }
}

/// Utility functions for graph comparison
pub mod utils {
    use super::*;

    /// Quick comparison of two graphs (basic stats only)
    pub fn quick_compare(old_graph: &StarGraph, new_graph: &StarGraph) -> DiffSummary {
        let old_triples: HashSet<StarTriple> = old_graph.triples().iter().cloned().collect();
        let new_triples: HashSet<StarTriple> = new_graph.triples().iter().cloned().collect();

        let added = new_triples.difference(&old_triples).count();
        let removed = old_triples.difference(&new_triples).count();
        let unchanged = old_triples.intersection(&new_triples).count();

        let similarity =
            DiffSummary::calculate_similarity(old_triples.len(), new_triples.len(), unchanged);

        DiffSummary {
            old_triple_count: old_triples.len(),
            new_triple_count: new_triples.len(),
            added_count: added,
            removed_count: removed,
            modified_count: 0,
            unchanged_count: unchanged,
            annotation_changes_count: 0,
            provenance_changes_count: 0,
            similarity_percentage: similarity,
        }
    }

    /// Check if two graphs are identical
    pub fn are_identical(graph1: &StarGraph, graph2: &StarGraph) -> bool {
        let triples1: HashSet<StarTriple> = graph1.triples().iter().cloned().collect();
        let triples2: HashSet<StarTriple> = graph2.triples().iter().cloned().collect();
        triples1 == triples2
    }

    /// Calculate Jaccard similarity between two graphs
    pub fn jaccard_similarity(graph1: &StarGraph, graph2: &StarGraph) -> f64 {
        let triples1: HashSet<StarTriple> = graph1.triples().iter().cloned().collect();
        let triples2: HashSet<StarTriple> = graph2.triples().iter().cloned().collect();

        let intersection = triples1.intersection(&triples2).count();
        let union = triples1.union(&triples2).count();

        if union == 0 {
            1.0
        } else {
            intersection as f64 / union as f64
        }
    }
}

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

    fn create_test_triple(subj: &str, pred: &str, obj: &str) -> StarTriple {
        StarTriple::new(
            StarTerm::iri(subj).unwrap(),
            StarTerm::iri(pred).unwrap(),
            StarTerm::iri(obj).unwrap(),
        )
    }

    #[test]
    fn test_diff_tool_creation() {
        let tool = GraphDiffTool::new();
        assert!(tool.options().compare_annotations);
        assert!(tool.options().compare_provenance);
    }

    #[test]
    fn test_quick_compare() {
        let mut graph1 = StarGraph::new();
        let mut graph2 = StarGraph::new();

        let triple1 = create_test_triple("http://ex.org/s1", "http://ex.org/p", "http://ex.org/o1");
        let triple2 = create_test_triple("http://ex.org/s2", "http://ex.org/p", "http://ex.org/o2");
        let triple3 = create_test_triple("http://ex.org/s3", "http://ex.org/p", "http://ex.org/o3");

        graph1.insert(triple1).unwrap();
        graph1.insert(triple2.clone()).unwrap();

        graph2.insert(triple2).unwrap();
        graph2.insert(triple3).unwrap();

        let summary = utils::quick_compare(&graph1, &graph2);
        assert_eq!(summary.old_triple_count, 2);
        assert_eq!(summary.new_triple_count, 2);
        assert_eq!(summary.added_count, 1);
        assert_eq!(summary.removed_count, 1);
        assert_eq!(summary.unchanged_count, 1);
    }

    #[test]
    fn test_identical_graphs() {
        let mut graph1 = StarGraph::new();
        let mut graph2 = StarGraph::new();

        let triple = create_test_triple("http://ex.org/s", "http://ex.org/p", "http://ex.org/o");

        graph1.insert(triple.clone()).unwrap();
        graph2.insert(triple).unwrap();

        assert!(utils::are_identical(&graph1, &graph2));
    }

    #[test]
    fn test_jaccard_similarity() {
        let mut graph1 = StarGraph::new();
        let mut graph2 = StarGraph::new();

        let triple1 = create_test_triple("http://ex.org/s1", "http://ex.org/p", "http://ex.org/o1");
        let triple2 = create_test_triple("http://ex.org/s2", "http://ex.org/p", "http://ex.org/o2");

        graph1.insert(triple1.clone()).unwrap();
        graph1.insert(triple2).unwrap();

        graph2.insert(triple1).unwrap();

        let similarity = utils::jaccard_similarity(&graph1, &graph2);
        assert!((similarity - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_change_type_display() {
        assert_eq!(format!("{}", ChangeType::Added), "ADDED");
        assert_eq!(format!("{}", ChangeType::Removed), "REMOVED");
        assert_eq!(format!("{}", ChangeType::Modified), "MODIFIED");
        assert_eq!(format!("{}", ChangeType::Unchanged), "UNCHANGED");
    }

    #[test]
    fn test_diff_options_default() {
        let options = DiffOptions::default();
        assert!(options.compare_annotations);
        assert!(options.compare_provenance);
        assert!(!options.include_unchanged);
    }
}