oxirs-rule 0.2.4

Forward/backward rule engine for RDFS, OWL, and SWRL reasoning
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
/// Truth Maintenance System (TMS) for belief revision.
///
/// A classical JTMS (Justification-based Truth Maintenance System) that tracks
/// beliefs (nodes) and their justifications. Retracting an axiom propagates
/// the "unsupported" status to all transitively dependent nodes.
use std::collections::{HashMap, HashSet};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// How a TMS node is justified.
#[derive(Debug, Clone, PartialEq)]
pub enum Justification {
    /// The node is an axiom — always supported unless explicitly retracted.
    Axiom,
    /// The node is derived from one or more other nodes.
    Derived {
        /// Indices of nodes this node depends on.
        from: Vec<usize>,
    },
}

/// A single belief node in the TMS.
#[derive(Debug, Clone)]
pub struct TmsNode {
    /// Unique identifier.
    pub id: usize,
    /// The statement this node represents (e.g. a fact, rule conclusion).
    pub statement: String,
    /// Whether this node is currently supported (believed).
    pub supported: bool,
    /// How this node is justified.
    pub justification: Justification,
}

/// Justification-based Truth Maintenance System.
///
/// Nodes can be axioms (always-on unless retracted) or derived (supported
/// only when all antecedent nodes are supported).
#[derive(Debug, Default)]
pub struct TruthMaintenanceSystem {
    nodes: Vec<TmsNode>,
    /// Set of node IDs that have been explicitly retracted.
    assumptions: HashSet<usize>,
}

impl TruthMaintenanceSystem {
    /// Create an empty TMS.
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            assumptions: HashSet::new(),
        }
    }

    /// Add an axiom node.  Axiom nodes are always supported until retracted.
    ///
    /// Returns the new node's `id`.
    pub fn add_axiom(&mut self, statement: impl Into<String>) -> usize {
        let id = self.nodes.len();
        self.nodes.push(TmsNode {
            id,
            statement: statement.into(),
            supported: true,
            justification: Justification::Axiom,
        });
        id
    }

    /// Add a derived node that is supported exactly when all nodes in `from`
    /// are supported.
    ///
    /// Returns the new node's `id`.
    pub fn add_derived(&mut self, statement: impl Into<String>, from: Vec<usize>) -> usize {
        let id = self.nodes.len();
        let supported = from
            .iter()
            .all(|&dep| self.nodes.get(dep).map(|n| n.supported).unwrap_or(false));
        self.nodes.push(TmsNode {
            id,
            statement: statement.into(),
            supported,
            justification: Justification::Derived { from },
        });
        id
    }

    /// Retract (un-support) a node and propagate unsupport to all dependents.
    pub fn retract(&mut self, node_id: usize) {
        if node_id >= self.nodes.len() {
            return;
        }
        self.assumptions.insert(node_id);
        self.nodes[node_id].supported = false;
        // Propagate transitively to all reachable dependents
        let affected = self.reachable(node_id);
        for dep_id in affected {
            self.nodes[dep_id].supported = false;
        }
    }

    /// Attempt to re-support a node that was previously retracted.
    ///
    /// For an axiom: re-supports unless still in the retraction set (but we
    /// remove it from the set here).  For a derived node: re-supports only
    /// when all antecedents are supported.
    pub fn restore(&mut self, node_id: usize) {
        if node_id >= self.nodes.len() {
            return;
        }
        self.assumptions.remove(&node_id);
        let supported = self.compute_supported(node_id);
        self.nodes[node_id].supported = supported;
        // Re-evaluate downstream nodes transitively
        let downstream = self.reachable(node_id);
        for dep_id in downstream {
            let s = self.compute_supported(dep_id);
            self.nodes[dep_id].supported = s;
        }
    }

    /// Return whether node `node_id` is currently supported.
    pub fn is_supported(&self, node_id: usize) -> bool {
        self.nodes
            .get(node_id)
            .map(|n| n.supported)
            .unwrap_or(false)
    }

    /// Count supported nodes.
    pub fn supported_count(&self) -> usize {
        self.nodes.iter().filter(|n| n.supported).count()
    }

    /// Count unsupported nodes.
    pub fn unsupported_count(&self) -> usize {
        self.nodes.iter().filter(|n| !n.supported).count()
    }

    /// Return all node IDs that **directly** depend on `node_id`.
    pub fn dependents(&self, node_id: usize) -> Vec<usize> {
        self.nodes
            .iter()
            .filter(|n| match &n.justification {
                Justification::Derived { from } => from.contains(&node_id),
                _ => false,
            })
            .map(|n| n.id)
            .collect()
    }

    /// Return a slice of all nodes.
    pub fn all_nodes(&self) -> &[TmsNode] {
        &self.nodes
    }

    /// Return all node IDs transitively reachable from `root_id` via the
    /// "depended-upon-by" relation (i.e. nodes that would be invalidated if
    /// `root_id` were retracted).
    pub fn reachable(&self, root_id: usize) -> Vec<usize> {
        let mut visited = HashSet::new();
        let mut stack = vec![root_id];
        while let Some(current) = stack.pop() {
            for dep in self.dependents(current) {
                if visited.insert(dep) {
                    stack.push(dep);
                }
            }
        }
        let mut result: Vec<usize> = visited.into_iter().collect();
        result.sort_unstable();
        result
    }

    // -----------------------------------------------------------------------
    // Private helpers
    // -----------------------------------------------------------------------

    /// Recompute whether node `id` should be supported given current state.
    fn compute_supported(&self, id: usize) -> bool {
        if self.assumptions.contains(&id) {
            return false;
        }
        match self.nodes.get(id) {
            None => false,
            Some(node) => match &node.justification {
                Justification::Axiom => true,
                Justification::Derived { from } => from.iter().all(|&dep| self.is_supported(dep)),
            },
        }
    }

    /// Build an index of node_id → indices of nodes that depend on it.
    #[allow(dead_code)]
    fn build_dependent_index(&self) -> HashMap<usize, Vec<usize>> {
        let mut index: HashMap<usize, Vec<usize>> = HashMap::new();
        for node in &self.nodes {
            if let Justification::Derived { from } = &node.justification {
                for &dep in from {
                    index.entry(dep).or_default().push(node.id);
                }
            }
        }
        index
    }
}

// ===========================================================================
// Tests
// ===========================================================================

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

    // --- Basic construction ---
    #[test]
    fn test_new_tms_is_empty() {
        let tms = TruthMaintenanceSystem::new();
        assert_eq!(tms.all_nodes().len(), 0);
        assert_eq!(tms.supported_count(), 0);
        assert_eq!(tms.unsupported_count(), 0);
    }

    #[test]
    fn test_add_axiom_returns_id() {
        let mut tms = TruthMaintenanceSystem::new();
        let id = tms.add_axiom("A");
        assert_eq!(id, 0);
    }

    #[test]
    fn test_axiom_is_supported() {
        let mut tms = TruthMaintenanceSystem::new();
        let id = tms.add_axiom("A");
        assert!(tms.is_supported(id));
    }

    #[test]
    fn test_multiple_axioms_ids_sequential() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_axiom("B");
        assert_eq!(a, 0);
        assert_eq!(b, 1);
    }

    // --- Derived nodes ---
    #[test]
    fn test_derived_node_supported_when_deps_supported() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_axiom("B");
        let c = tms.add_derived("C", vec![a, b]);
        assert!(tms.is_supported(c));
    }

    #[test]
    fn test_derived_node_unsupported_when_dep_unsupported() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B", vec![a]);
        tms.retract(a);
        assert!(!tms.is_supported(b));
    }

    #[test]
    fn test_derived_node_with_no_deps_is_supported() {
        let mut tms = TruthMaintenanceSystem::new();
        let c = tms.add_derived("C", vec![]);
        assert!(tms.is_supported(c));
    }

    // --- Retraction ---
    #[test]
    fn test_retract_axiom() {
        let mut tms = TruthMaintenanceSystem::new();
        let id = tms.add_axiom("A");
        tms.retract(id);
        assert!(!tms.is_supported(id));
    }

    #[test]
    fn test_retract_propagates_one_level() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B <- A", vec![a]);
        tms.retract(a);
        assert!(!tms.is_supported(a));
        assert!(!tms.is_supported(b));
    }

    #[test]
    fn test_retract_propagates_two_levels() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B <- A", vec![a]);
        let c = tms.add_derived("C <- B", vec![b]);
        tms.retract(a);
        assert!(!tms.is_supported(b));
        assert!(!tms.is_supported(c));
    }

    #[test]
    fn test_retract_does_not_affect_unrelated() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_axiom("B");
        tms.retract(a);
        assert!(!tms.is_supported(a));
        assert!(tms.is_supported(b));
    }

    #[test]
    fn test_retract_invalid_id_is_noop() {
        let mut tms = TruthMaintenanceSystem::new();
        tms.retract(999); // Should not panic
    }

    // --- Restore ---
    #[test]
    fn test_restore_axiom() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        tms.retract(a);
        tms.restore(a);
        assert!(tms.is_supported(a));
    }

    #[test]
    fn test_restore_propagates_to_derived() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B <- A", vec![a]);
        tms.retract(a);
        assert!(!tms.is_supported(b));
        tms.restore(a);
        assert!(tms.is_supported(a));
        assert!(tms.is_supported(b));
    }

    #[test]
    fn test_restore_does_not_restore_if_other_dep_still_retracted() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_axiom("B");
        let c = tms.add_derived("C <- A, B", vec![a, b]);
        tms.retract(a);
        tms.retract(b);
        tms.restore(a);
        // c still depends on b which is retracted
        assert!(!tms.is_supported(c));
    }

    // --- supported_count / unsupported_count ---
    #[test]
    fn test_counts_after_retract() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let _b = tms.add_axiom("B");
        let _c = tms.add_derived("C <- A", vec![a]);
        tms.retract(a);
        assert_eq!(tms.supported_count(), 1); // only B
        assert_eq!(tms.unsupported_count(), 2); // A and C
    }

    #[test]
    fn test_counts_all_supported() {
        let mut tms = TruthMaintenanceSystem::new();
        let _a = tms.add_axiom("A");
        let _b = tms.add_axiom("B");
        assert_eq!(tms.supported_count(), 2);
        assert_eq!(tms.unsupported_count(), 0);
    }

    // --- dependents ---
    #[test]
    fn test_dependents_empty_when_none() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        assert!(tms.dependents(a).is_empty());
    }

    #[test]
    fn test_dependents_returns_derived_nodes() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B <- A", vec![a]);
        let c = tms.add_derived("C <- A", vec![a]);
        let mut deps = tms.dependents(a);
        deps.sort_unstable();
        assert_eq!(deps, vec![b, c]);
    }

    // --- reachable ---
    #[test]
    fn test_reachable_empty() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        assert!(tms.reachable(a).is_empty());
    }

    #[test]
    fn test_reachable_chain() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B <- A", vec![a]);
        let c = tms.add_derived("C <- B", vec![b]);
        let reachable = tms.reachable(a);
        assert!(reachable.contains(&b));
        assert!(reachable.contains(&c));
    }

    #[test]
    fn test_reachable_diamond() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B <- A", vec![a]);
        let c = tms.add_derived("C <- A", vec![a]);
        let d = tms.add_derived("D <- B, C", vec![b, c]);
        let reachable = tms.reachable(a);
        assert!(reachable.contains(&b));
        assert!(reachable.contains(&c));
        assert!(reachable.contains(&d));
        assert_eq!(reachable.len(), 3);
    }

    // --- all_nodes ---
    #[test]
    fn test_all_nodes_returns_correct_slice() {
        let mut tms = TruthMaintenanceSystem::new();
        tms.add_axiom("A");
        tms.add_axiom("B");
        let nodes = tms.all_nodes();
        assert_eq!(nodes.len(), 2);
        assert_eq!(nodes[0].statement, "A");
        assert_eq!(nodes[1].statement, "B");
    }

    // --- justification content ---
    #[test]
    fn test_axiom_justification() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        assert_eq!(tms.all_nodes()[a].justification, Justification::Axiom);
    }

    #[test]
    fn test_derived_justification_from_ids() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        let b = tms.add_derived("B", vec![a]);
        assert_eq!(
            tms.all_nodes()[b].justification,
            Justification::Derived { from: vec![a] }
        );
    }

    // --- is_supported for out-of-range id ---
    #[test]
    fn test_is_supported_out_of_range() {
        let tms = TruthMaintenanceSystem::new();
        assert!(!tms.is_supported(999));
    }

    // --- Double retract is safe ---
    #[test]
    fn test_double_retract_is_idempotent() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        tms.retract(a);
        tms.retract(a);
        assert!(!tms.is_supported(a));
    }

    // --- Restore then retract ---
    #[test]
    fn test_restore_then_retract() {
        let mut tms = TruthMaintenanceSystem::new();
        let a = tms.add_axiom("A");
        tms.retract(a);
        tms.restore(a);
        assert!(tms.is_supported(a));
        tms.retract(a);
        assert!(!tms.is_supported(a));
    }
}