Skip to main content

oxirs_rule/
explainable_generation.rs

1//! Explainable Rule Generation
2//!
3//! Provides transparency in rule generation by explaining how rules were learned,
4//! derived, or synthesized. Helps users understand and trust automatically generated rules.
5//!
6//! # Features
7//!
8//! - **Rule Provenance Tracking**: Track how rules were generated
9//! - **Feature Importance**: Identify which features contributed to rule generation
10//! - **Confidence Explanation**: Explain confidence scores
11//! - **Counterfactual Analysis**: Show what would change the rule
12//! - **Natural Language Explanations**: Generate human-readable explanations
13//! - **Visual Explanations**: Generate rule dependency graphs
14//!
15//! # Example
16//!
17//! ```rust
18//! use oxirs_rule::explainable_generation::{ExplainableGenerator, ExplanationType};
19//! use oxirs_rule::{Rule, RuleAtom, Term};
20//!
21//! let mut generator = ExplainableGenerator::new();
22//!
23//! // Generate a rule with explanation
24//! let rule = Rule {
25//!     name: "transitivity_rule".to_string(),
26//!     body: vec![
27//!         RuleAtom::Triple {
28//!             subject: Term::Variable("X".to_string()),
29//!             predicate: Term::Constant("knows".to_string()),
30//!             object: Term::Variable("Y".to_string()),
31//!         },
32//!         RuleAtom::Triple {
33//!             subject: Term::Variable("Y".to_string()),
34//!             predicate: Term::Constant("knows".to_string()),
35//!             object: Term::Variable("Z".to_string()),
36//!         },
37//!     ],
38//!     head: vec![RuleAtom::Triple {
39//!         subject: Term::Variable("X".to_string()),
40//!         predicate: Term::Constant("knows_indirectly".to_string()),
41//!         object: Term::Variable("Z".to_string()),
42//!     }],
43//! };
44//!
45//! generator.register_rule(rule, "Learned from 100 examples with 95% confidence");
46//!
47//! // Get explanation
48//! let explanation = generator.explain("transitivity_rule", ExplanationType::NaturalLanguage);
49//! if let Some(exp) = explanation {
50//!     println!("{}", exp);
51//! }
52//! # Ok::<(), anyhow::Error>(())
53//! ```
54
55use crate::Rule;
56use std::collections::HashMap;
57use tracing::info;
58
59/// Type of explanation
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
61pub enum ExplanationType {
62    /// Natural language explanation
63    NaturalLanguage,
64    /// Feature importance analysis
65    FeatureImportance,
66    /// Confidence breakdown
67    ConfidenceAnalysis,
68    /// Counterfactual analysis
69    Counterfactual,
70    /// Provenance trace
71    Provenance,
72}
73
74/// Generation method
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum GenerationMethod {
77    /// Learned from data
78    MachineLearning,
79    /// Derived from existing rules
80    Derivation,
81    /// Manually authored
82    Manual,
83    /// Synthesized automatically
84    Synthesis,
85    /// Transferred from another domain
86    Transfer,
87}
88
89/// Rule metadata for explanation
90#[derive(Debug, Clone)]
91pub struct RuleMetadata {
92    /// Rule name
93    pub rule_name: String,
94    /// Generation method
95    pub generation_method: GenerationMethod,
96    /// Confidence score (0.0 to 1.0)
97    pub confidence: f64,
98    /// Number of supporting examples
99    pub support_count: usize,
100    /// Feature importance scores
101    pub feature_importance: HashMap<String, f64>,
102    /// Generation description
103    pub description: String,
104    /// Parent rules (if derived)
105    pub parent_rules: Vec<String>,
106    /// Timestamp
107    pub timestamp: std::time::SystemTime,
108}
109
110/// Feature contribution
111#[derive(Debug, Clone)]
112pub struct FeatureContribution {
113    /// Feature name
114    pub feature: String,
115    /// Importance score
116    pub importance: f64,
117    /// Description
118    pub description: String,
119}
120
121/// Explainable rule generator
122pub struct ExplainableGenerator {
123    /// Registered rules
124    rules: HashMap<String, Rule>,
125    /// Rule metadata
126    metadata: HashMap<String, RuleMetadata>,
127    /// Explanation cache
128    explanation_cache: HashMap<(String, ExplanationType), String>,
129}
130
131impl Default for ExplainableGenerator {
132    fn default() -> Self {
133        Self::new()
134    }
135}
136
137impl ExplainableGenerator {
138    /// Create a new explainable generator
139    pub fn new() -> Self {
140        Self {
141            rules: HashMap::new(),
142            metadata: HashMap::new(),
143            explanation_cache: HashMap::new(),
144        }
145    }
146
147    /// Register a rule with simple description
148    pub fn register_rule(&mut self, rule: Rule, description: impl Into<String>) {
149        let name = rule.name.clone();
150        self.rules.insert(name.clone(), rule);
151
152        self.metadata.insert(
153            name.clone(),
154            RuleMetadata {
155                rule_name: name.clone(),
156                generation_method: GenerationMethod::Manual,
157                confidence: 1.0,
158                support_count: 0,
159                feature_importance: HashMap::new(),
160                description: description.into(),
161                parent_rules: Vec::new(),
162                timestamp: std::time::SystemTime::now(),
163            },
164        );
165
166        info!("Registered rule '{}' with explanation", name);
167    }
168
169    /// Register a rule with full metadata
170    pub fn register_rule_with_metadata(&mut self, rule: Rule, metadata: RuleMetadata) {
171        let name = rule.name.clone();
172        self.rules.insert(name.clone(), rule);
173        self.metadata.insert(name.clone(), metadata);
174
175        // Clear explanation cache for this rule
176        self.explanation_cache
177            .retain(|(rule_name, _), _| rule_name != &name);
178    }
179
180    /// Get explanation for a rule
181    pub fn explain(
182        &mut self,
183        rule_name: &str,
184        explanation_type: ExplanationType,
185    ) -> Option<String> {
186        // Check cache first
187        let cache_key = (rule_name.to_string(), explanation_type);
188        if let Some(cached) = self.explanation_cache.get(&cache_key) {
189            return Some(cached.clone());
190        }
191
192        let rule = self.rules.get(rule_name)?;
193        let metadata = self.metadata.get(rule_name)?;
194
195        let explanation = match explanation_type {
196            ExplanationType::NaturalLanguage => {
197                self.generate_natural_language_explanation(rule, metadata)
198            }
199            ExplanationType::FeatureImportance => {
200                self.generate_feature_importance_explanation(metadata)
201            }
202            ExplanationType::ConfidenceAnalysis => self.generate_confidence_explanation(metadata),
203            ExplanationType::Counterfactual => {
204                self.generate_counterfactual_explanation(rule, metadata)
205            }
206            ExplanationType::Provenance => self.generate_provenance_explanation(metadata),
207        };
208
209        // Cache the explanation
210        self.explanation_cache
211            .insert(cache_key, explanation.clone());
212
213        Some(explanation)
214    }
215
216    /// Generate natural language explanation
217    fn generate_natural_language_explanation(
218        &self,
219        rule: &Rule,
220        metadata: &RuleMetadata,
221    ) -> String {
222        let mut explanation = format!("Rule '{}' ", rule.name);
223
224        match metadata.generation_method {
225            GenerationMethod::MachineLearning => {
226                explanation.push_str(&format!(
227                    "was learned from {} examples with {:.1}% confidence. ",
228                    metadata.support_count,
229                    metadata.confidence * 100.0
230                ));
231            }
232            GenerationMethod::Derivation => {
233                explanation.push_str("was derived from existing rules. ");
234                if !metadata.parent_rules.is_empty() {
235                    explanation.push_str(&format!(
236                        "Parent rules: {}. ",
237                        metadata.parent_rules.join(", ")
238                    ));
239                }
240            }
241            GenerationMethod::Manual => {
242                explanation.push_str("was manually authored. ");
243            }
244            GenerationMethod::Synthesis => {
245                explanation.push_str("was automatically synthesized. ");
246            }
247            GenerationMethod::Transfer => {
248                explanation.push_str("was transferred from another domain. ");
249            }
250        }
251
252        explanation.push_str(&format!("\n\n{}", metadata.description));
253
254        if rule.body.len() == 1 {
255            explanation.push_str("\n\nThis rule has 1 condition.");
256        } else {
257            explanation.push_str(&format!(
258                "\n\nThis rule has {} conditions.",
259                rule.body.len()
260            ));
261        }
262
263        if rule.head.len() == 1 {
264            explanation.push_str(" It produces 1 conclusion.");
265        } else {
266            explanation.push_str(&format!(" It produces {} conclusions.", rule.head.len()));
267        }
268
269        explanation
270    }
271
272    /// Generate feature importance explanation
273    fn generate_feature_importance_explanation(&self, metadata: &RuleMetadata) -> String {
274        let mut explanation = format!(
275            "Feature Importance Analysis for Rule '{}'\n\n",
276            metadata.rule_name
277        );
278
279        if metadata.feature_importance.is_empty() {
280            explanation.push_str("No feature importance data available.");
281            return explanation;
282        }
283
284        let mut features: Vec<_> = metadata.feature_importance.iter().collect();
285        features.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_or(std::cmp::Ordering::Equal));
286
287        explanation.push_str("Top contributing features:\n");
288        for (idx, (feature, importance)) in features.iter().take(5).enumerate() {
289            explanation.push_str(&format!(
290                "{}. {}: {:.1}%\n",
291                idx + 1,
292                feature,
293                **importance * 100.0
294            ));
295        }
296
297        explanation
298    }
299
300    /// Generate confidence explanation
301    fn generate_confidence_explanation(&self, metadata: &RuleMetadata) -> String {
302        let mut explanation = format!("Confidence Analysis for Rule '{}'\n\n", metadata.rule_name);
303
304        explanation.push_str(&format!(
305            "Overall Confidence: {:.1}%\n\n",
306            metadata.confidence * 100.0
307        ));
308
309        explanation.push_str(&format!(
310            "Based on {} supporting examples.\n\n",
311            metadata.support_count
312        ));
313
314        let confidence_level = if metadata.confidence >= 0.9 {
315            "Very High"
316        } else if metadata.confidence >= 0.75 {
317            "High"
318        } else if metadata.confidence >= 0.6 {
319            "Moderate"
320        } else if metadata.confidence >= 0.4 {
321            "Low"
322        } else {
323            "Very Low"
324        };
325
326        explanation.push_str(&format!("Confidence Level: {}\n\n", confidence_level));
327
328        if metadata.confidence < 0.6 {
329            explanation.push_str(
330                "⚠️  Note: This rule has low confidence and may need additional validation.\n",
331            );
332        }
333
334        explanation
335    }
336
337    /// Generate counterfactual explanation
338    fn generate_counterfactual_explanation(&self, rule: &Rule, metadata: &RuleMetadata) -> String {
339        let mut explanation = format!("Counterfactual Analysis for Rule '{}'\n\n", rule.name);
340
341        explanation.push_str("What would change this rule:\n\n");
342
343        explanation.push_str("1. If the rule body had fewer conditions, it would match more cases but might be less specific.\n");
344        explanation.push_str("2. If the rule body had more conditions, it would match fewer cases but be more specific.\n");
345        explanation.push_str("3. If the confidence threshold were lowered, this rule might be accepted even with less evidence.\n");
346
347        if metadata.support_count < 100 {
348            explanation.push_str(&format!(
349                "4. With more supporting examples (currently {}), the confidence could increase.\n",
350                metadata.support_count
351            ));
352        }
353
354        explanation
355    }
356
357    /// Generate provenance explanation
358    fn generate_provenance_explanation(&self, metadata: &RuleMetadata) -> String {
359        let mut explanation = format!("Provenance Trace for Rule '{}'\n\n", metadata.rule_name);
360
361        explanation.push_str(&format!(
362            "Generation Method: {:?}\n",
363            metadata.generation_method
364        ));
365        explanation.push_str(&format!(
366            "Created: {:?}\n",
367            metadata
368                .timestamp
369                .duration_since(std::time::UNIX_EPOCH)
370                .unwrap_or_default()
371                .as_secs()
372        ));
373        explanation.push_str(&format!("Support Count: {}\n", metadata.support_count));
374        explanation.push_str(&format!("Confidence: {:.3}\n\n", metadata.confidence));
375
376        if !metadata.parent_rules.is_empty() {
377            explanation.push_str("Derived from rules:\n");
378            for parent in &metadata.parent_rules {
379                explanation.push_str(&format!("  - {}\n", parent));
380            }
381        }
382
383        explanation.push_str(&format!("\n{}", metadata.description));
384
385        explanation
386    }
387
388    /// Get feature contributions
389    pub fn get_feature_contributions(&self, rule_name: &str) -> Vec<FeatureContribution> {
390        let metadata = match self.metadata.get(rule_name) {
391            Some(m) => m,
392            None => return Vec::new(),
393        };
394
395        let mut contributions: Vec<_> = metadata
396            .feature_importance
397            .iter()
398            .map(|(feature, importance)| FeatureContribution {
399                feature: feature.clone(),
400                importance: *importance,
401                description: format!("Contributes {:.1}% to rule generation", importance * 100.0),
402            })
403            .collect();
404
405        contributions.sort_by(|a, b| {
406            b.importance
407                .partial_cmp(&a.importance)
408                .unwrap_or(std::cmp::Ordering::Equal)
409        });
410
411        contributions
412    }
413
414    /// Get rule metadata
415    pub fn get_metadata(&self, rule_name: &str) -> Option<&RuleMetadata> {
416        self.metadata.get(rule_name)
417    }
418
419    /// Get all registered rules
420    pub fn get_rules(&self) -> Vec<String> {
421        self.rules.keys().cloned().collect()
422    }
423
424    /// Clear cache
425    pub fn clear_cache(&mut self) {
426        self.explanation_cache.clear();
427    }
428
429    /// Remove rule
430    pub fn remove_rule(&mut self, rule_name: &str) -> bool {
431        let removed = self.rules.remove(rule_name).is_some();
432        self.metadata.remove(rule_name);
433        self.explanation_cache
434            .retain(|(name, _), _| name != rule_name);
435        removed
436    }
437}
438
439#[cfg(test)]
440mod tests {
441    use super::*;
442    use crate::{RuleAtom, Term};
443
444    fn create_test_rule(name: &str) -> Rule {
445        Rule {
446            name: name.to_string(),
447            body: vec![RuleAtom::Triple {
448                subject: Term::Variable("X".to_string()),
449                predicate: Term::Constant("p".to_string()),
450                object: Term::Variable("Y".to_string()),
451            }],
452            head: vec![RuleAtom::Triple {
453                subject: Term::Variable("X".to_string()),
454                predicate: Term::Constant("q".to_string()),
455                object: Term::Variable("Y".to_string()),
456            }],
457        }
458    }
459
460    #[test]
461    fn test_generator_creation() {
462        let generator = ExplainableGenerator::new();
463        assert_eq!(generator.get_rules().len(), 0);
464    }
465
466    #[test]
467    fn test_register_rule() {
468        let mut generator = ExplainableGenerator::new();
469        let rule = create_test_rule("test_rule");
470
471        generator.register_rule(rule, "Test description");
472
473        assert_eq!(generator.get_rules().len(), 1);
474        assert!(generator.get_rules().contains(&"test_rule".to_string()));
475    }
476
477    #[test]
478    fn test_natural_language_explanation() -> Result<(), Box<dyn std::error::Error>> {
479        let mut generator = ExplainableGenerator::new();
480        let rule = create_test_rule("test_rule");
481
482        generator.register_rule(rule, "A simple test rule");
483
484        let explanation = generator.explain("test_rule", ExplanationType::NaturalLanguage);
485        assert!(explanation.is_some());
486
487        let exp = explanation.ok_or("expected Some value")?;
488        assert!(exp.contains("test_rule"));
489        assert!(exp.contains("manually authored"));
490        Ok(())
491    }
492
493    #[test]
494    fn test_feature_importance_explanation() -> Result<(), Box<dyn std::error::Error>> {
495        let mut generator = ExplainableGenerator::new();
496        let rule = create_test_rule("test_rule");
497
498        let mut feature_importance = HashMap::new();
499        feature_importance.insert("feature1".to_string(), 0.6);
500        feature_importance.insert("feature2".to_string(), 0.3);
501        feature_importance.insert("feature3".to_string(), 0.1);
502
503        let metadata = RuleMetadata {
504            rule_name: "test_rule".to_string(),
505            generation_method: GenerationMethod::MachineLearning,
506            confidence: 0.85,
507            support_count: 100,
508            feature_importance,
509            description: "Learned rule".to_string(),
510            parent_rules: Vec::new(),
511            timestamp: std::time::SystemTime::now(),
512        };
513
514        generator.register_rule_with_metadata(rule, metadata);
515
516        let explanation = generator.explain("test_rule", ExplanationType::FeatureImportance);
517        assert!(explanation.is_some());
518
519        let exp = explanation.ok_or("expected Some value")?;
520        assert!(exp.contains("feature1"));
521        assert!(exp.contains("60.0%"));
522        Ok(())
523    }
524
525    #[test]
526    fn test_confidence_explanation() -> Result<(), Box<dyn std::error::Error>> {
527        let mut generator = ExplainableGenerator::new();
528        let rule = create_test_rule("high_conf_rule");
529
530        let metadata = RuleMetadata {
531            rule_name: "high_conf_rule".to_string(),
532            generation_method: GenerationMethod::MachineLearning,
533            confidence: 0.92,
534            support_count: 500,
535            feature_importance: HashMap::new(),
536            description: "High confidence rule".to_string(),
537            parent_rules: Vec::new(),
538            timestamp: std::time::SystemTime::now(),
539        };
540
541        generator.register_rule_with_metadata(rule, metadata);
542
543        let explanation = generator.explain("high_conf_rule", ExplanationType::ConfidenceAnalysis);
544        assert!(explanation.is_some());
545
546        let exp = explanation.ok_or("expected Some value")?;
547        assert!(exp.contains("92.0%"));
548        assert!(exp.contains("500"));
549        assert!(exp.contains("Very High"));
550        Ok(())
551    }
552
553    #[test]
554    fn test_provenance_explanation() -> Result<(), Box<dyn std::error::Error>> {
555        let mut generator = ExplainableGenerator::new();
556        let rule = create_test_rule("derived_rule");
557
558        let metadata = RuleMetadata {
559            rule_name: "derived_rule".to_string(),
560            generation_method: GenerationMethod::Derivation,
561            confidence: 0.88,
562            support_count: 200,
563            feature_importance: HashMap::new(),
564            description: "Derived from parent rules".to_string(),
565            parent_rules: vec!["parent1".to_string(), "parent2".to_string()],
566            timestamp: std::time::SystemTime::now(),
567        };
568
569        generator.register_rule_with_metadata(rule, metadata);
570
571        let explanation = generator.explain("derived_rule", ExplanationType::Provenance);
572        assert!(explanation.is_some());
573
574        let exp = explanation.ok_or("expected Some value")?;
575        assert!(exp.contains("Derivation"));
576        assert!(exp.contains("parent1"));
577        assert!(exp.contains("parent2"));
578        Ok(())
579    }
580
581    #[test]
582    fn test_get_feature_contributions() {
583        let mut generator = ExplainableGenerator::new();
584        let rule = create_test_rule("test_rule");
585
586        let mut feature_importance = HashMap::new();
587        feature_importance.insert("high_importance".to_string(), 0.8);
588        feature_importance.insert("low_importance".to_string(), 0.2);
589
590        let metadata = RuleMetadata {
591            rule_name: "test_rule".to_string(),
592            generation_method: GenerationMethod::MachineLearning,
593            confidence: 0.85,
594            support_count: 100,
595            feature_importance,
596            description: "Test".to_string(),
597            parent_rules: Vec::new(),
598            timestamp: std::time::SystemTime::now(),
599        };
600
601        generator.register_rule_with_metadata(rule, metadata);
602
603        let contributions = generator.get_feature_contributions("test_rule");
604        assert_eq!(contributions.len(), 2);
605        assert_eq!(contributions[0].feature, "high_importance");
606        assert!((contributions[0].importance - 0.8).abs() < 0.01);
607    }
608
609    #[test]
610    fn test_explanation_caching() {
611        let mut generator = ExplainableGenerator::new();
612        let rule = create_test_rule("cached_rule");
613
614        generator.register_rule(rule, "Cache test");
615
616        // First call - generates explanation
617        let exp1 = generator.explain("cached_rule", ExplanationType::NaturalLanguage);
618
619        // Second call - should use cache
620        let exp2 = generator.explain("cached_rule", ExplanationType::NaturalLanguage);
621
622        assert_eq!(exp1, exp2);
623    }
624
625    #[test]
626    fn test_remove_rule() {
627        let mut generator = ExplainableGenerator::new();
628        let rule = create_test_rule("removable_rule");
629
630        generator.register_rule(rule, "To be removed");
631        assert_eq!(generator.get_rules().len(), 1);
632
633        let removed = generator.remove_rule("removable_rule");
634        assert!(removed);
635        assert_eq!(generator.get_rules().len(), 0);
636    }
637
638    #[test]
639    fn test_clear_cache() {
640        let mut generator = ExplainableGenerator::new();
641        let rule = create_test_rule("test_rule");
642
643        generator.register_rule(rule, "Test");
644
645        // Generate explanation to populate cache
646        generator.explain("test_rule", ExplanationType::NaturalLanguage);
647        assert!(!generator.explanation_cache.is_empty());
648
649        generator.clear_cache();
650        assert!(generator.explanation_cache.is_empty());
651    }
652}