Skip to main content

oxirs_rule/
active_learning.rs

1//! Active Learning for Rule Validation
2//!
3//! Implements active learning strategies to efficiently validate rules by selecting
4//! the most informative examples for manual review, reducing validation effort.
5//!
6//! # Features
7//!
8//! - **Uncertainty Sampling**: Select rules with highest prediction uncertainty
9//! - **Query-by-Committee**: Use ensemble disagreement to find ambiguous cases
10//! - **Diversity Sampling**: Ensure diverse rule coverage
11//! - **Expected Model Change**: Select examples that would change the model most
12//! - **Validation Workflow**: Interactive validation with feedback loops
13//! - **Confidence Tracking**: Monitor validation confidence over time
14//!
15//! # Example
16//!
17//! ```rust
18//! use oxirs_rule::active_learning::{ActiveLearner, SamplingStrategy};
19//! use oxirs_rule::{Rule, RuleAtom, Term};
20//!
21//! let mut learner = ActiveLearner::new();
22//!
23//! // Add candidate rules for validation
24//! let rule = Rule {
25//!     name: "candidate_rule".to_string(),
26//!     body: vec![RuleAtom::Triple {
27//!         subject: Term::Variable("X".to_string()),
28//!         predicate: Term::Constant("hasParent".to_string()),
29//!         object: Term::Variable("Y".to_string()),
30//!     }],
31//!     head: vec![RuleAtom::Triple {
32//!         subject: Term::Variable("Y".to_string()),
33//!         predicate: Term::Constant("hasChild".to_string()),
34//!         object: Term::Variable("X".to_string()),
35//!     }],
36//! };
37//!
38//! learner.add_candidate_rule(rule, 0.75);
39//!
40//! // Select most informative rule for validation
41//! let next_rule = learner.select_next_for_validation(SamplingStrategy::UncertaintySampling);
42//!
43//! if let Some(selected) = next_rule {
44//!     println!("Please validate: {}", selected.name);
45//!     // User validates and provides feedback
46//!     learner.record_validation(&selected.name, true, 0.95);
47//! }
48//! # Ok::<(), anyhow::Error>(())
49//! ```
50
51use crate::Rule;
52use scirs2_core::random::prelude::*;
53use std::collections::HashMap;
54use tracing::info;
55
56/// Sampling strategy for active learning
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub enum SamplingStrategy {
59    /// Select rules with highest uncertainty
60    UncertaintySampling,
61    /// Use ensemble disagreement
62    QueryByCommittee,
63    /// Ensure diverse rule coverage
64    DiversitySampling,
65    /// Expected model change
66    ExpectedModelChange,
67    /// Random sampling (baseline)
68    RandomSampling,
69}
70
71/// Candidate rule with confidence
72#[derive(Debug, Clone)]
73pub struct CandidateRule {
74    /// Rule to validate
75    pub rule: Rule,
76    /// Predicted confidence (0.0 to 1.0)
77    pub confidence: f64,
78    /// Validation status
79    pub validated: bool,
80    /// Validation result (if validated)
81    pub validation_result: Option<bool>,
82    /// Actual confidence after validation
83    pub actual_confidence: Option<f64>,
84    /// Selection count
85    pub selection_count: usize,
86}
87
88/// Validation feedback
89#[derive(Debug, Clone)]
90pub struct ValidationFeedback {
91    /// Rule name
92    pub rule_name: String,
93    /// Is rule correct?
94    pub is_correct: bool,
95    /// Confidence in validation (0.0 to 1.0)
96    pub confidence: f64,
97    /// Timestamp
98    pub timestamp: std::time::SystemTime,
99}
100
101/// Active learner for rule validation
102pub struct ActiveLearner {
103    /// Candidate rules to validate
104    candidates: HashMap<String, CandidateRule>,
105    /// Validation history
106    validation_history: Vec<ValidationFeedback>,
107    /// Random number generator
108    rng: StdRng,
109    /// Diversity weight (0.0 to 1.0)
110    diversity_weight: f64,
111    /// Minimum confidence threshold
112    min_confidence_threshold: f64,
113    /// Committee size for query-by-committee
114    committee_size: usize,
115}
116
117impl Default for ActiveLearner {
118    fn default() -> Self {
119        Self::new()
120    }
121}
122
123impl ActiveLearner {
124    /// Create a new active learner
125    pub fn new() -> Self {
126        let seed = std::time::SystemTime::now()
127            .duration_since(std::time::UNIX_EPOCH)
128            .expect("SystemTime should be after UNIX_EPOCH")
129            .as_secs();
130        Self {
131            candidates: HashMap::new(),
132            validation_history: Vec::new(),
133            rng: seeded_rng(seed),
134            diversity_weight: 0.3,
135            min_confidence_threshold: 0.5,
136            committee_size: 5,
137        }
138    }
139
140    /// Add a candidate rule for validation
141    pub fn add_candidate_rule(&mut self, rule: Rule, confidence: f64) {
142        let name = rule.name.clone();
143        self.candidates.insert(
144            name,
145            CandidateRule {
146                rule,
147                confidence: confidence.clamp(0.0, 1.0),
148                validated: false,
149                validation_result: None,
150                actual_confidence: None,
151                selection_count: 0,
152            },
153        );
154    }
155
156    /// Select next rule for validation using specified strategy
157    pub fn select_next_for_validation(&mut self, strategy: SamplingStrategy) -> Option<Rule> {
158        let unvalidated: Vec<_> = self
159            .candidates
160            .iter()
161            .filter(|(_, c)| !c.validated)
162            .map(|(name, c)| (name.clone(), c.clone()))
163            .collect();
164
165        if unvalidated.is_empty() {
166            return None;
167        }
168
169        let selected_name = match strategy {
170            SamplingStrategy::UncertaintySampling => self.uncertainty_sampling(&unvalidated),
171            SamplingStrategy::QueryByCommittee => self.query_by_committee(&unvalidated),
172            SamplingStrategy::DiversitySampling => self.diversity_sampling(&unvalidated),
173            SamplingStrategy::ExpectedModelChange => self.expected_model_change(&unvalidated),
174            SamplingStrategy::RandomSampling => self.random_sampling(&unvalidated),
175        }?;
176
177        // Increment selection count
178        if let Some(candidate) = self.candidates.get_mut(&selected_name) {
179            candidate.selection_count += 1;
180            info!(
181                "Selected rule '{}' for validation (confidence: {:.3})",
182                selected_name, candidate.confidence
183            );
184            return Some(candidate.rule.clone());
185        }
186
187        None
188    }
189
190    /// Record validation result
191    pub fn record_validation(&mut self, rule_name: &str, is_correct: bool, confidence: f64) {
192        if let Some(candidate) = self.candidates.get_mut(rule_name) {
193            candidate.validated = true;
194            candidate.validation_result = Some(is_correct);
195            candidate.actual_confidence = Some(confidence.clamp(0.0, 1.0));
196
197            self.validation_history.push(ValidationFeedback {
198                rule_name: rule_name.to_string(),
199                is_correct,
200                confidence: confidence.clamp(0.0, 1.0),
201                timestamp: std::time::SystemTime::now(),
202            });
203
204            info!(
205                "Recorded validation for '{}': correct={}, confidence={:.3}",
206                rule_name, is_correct, confidence
207            );
208        }
209    }
210
211    /// Get validation accuracy
212    pub fn validation_accuracy(&self) -> f64 {
213        let validated: Vec<_> = self
214            .candidates
215            .values()
216            .filter(|c| c.validated && c.validation_result.is_some())
217            .collect();
218
219        if validated.is_empty() {
220            return 0.0;
221        }
222
223        let correct_predictions = validated
224            .iter()
225            .filter(|c| {
226                let predicted_correct = c.confidence >= self.min_confidence_threshold;
227                let actually_correct = c.validation_result.unwrap_or(false);
228                predicted_correct == actually_correct
229            })
230            .count();
231
232        correct_predictions as f64 / validated.len() as f64
233    }
234
235    /// Get validation coverage (percentage validated)
236    pub fn validation_coverage(&self) -> f64 {
237        if self.candidates.is_empty() {
238            return 0.0;
239        }
240
241        let validated_count = self.candidates.values().filter(|c| c.validated).count();
242        validated_count as f64 / self.candidates.len() as f64
243    }
244
245    /// Get validation history
246    pub fn get_validation_history(&self) -> &[ValidationFeedback] {
247        &self.validation_history
248    }
249
250    /// Set diversity weight
251    pub fn set_diversity_weight(&mut self, weight: f64) {
252        self.diversity_weight = weight.clamp(0.0, 1.0);
253    }
254
255    /// Set minimum confidence threshold
256    pub fn set_min_confidence_threshold(&mut self, threshold: f64) {
257        self.min_confidence_threshold = threshold.clamp(0.0, 1.0);
258    }
259
260    /// Uncertainty sampling: select rule with lowest confidence
261    fn uncertainty_sampling(&self, candidates: &[(String, CandidateRule)]) -> Option<String> {
262        candidates
263            .iter()
264            .min_by(|a, b| {
265                let uncertainty_a = (a.1.confidence - 0.5).abs();
266                let uncertainty_b = (b.1.confidence - 0.5).abs();
267                uncertainty_a
268                    .partial_cmp(&uncertainty_b)
269                    .unwrap_or(std::cmp::Ordering::Equal)
270            })
271            .map(|(name, _)| name.clone())
272    }
273
274    /// Query-by-committee: select rule with highest disagreement
275    fn query_by_committee(&mut self, candidates: &[(String, CandidateRule)]) -> Option<String> {
276        // Simulate committee by adding noise to confidence scores
277        let mut scores: Vec<(String, f64)> = candidates
278            .iter()
279            .map(|(name, candidate)| {
280                let mut committee_votes = Vec::new();
281                for _ in 0..self.committee_size {
282                    let noise: f64 = self.rng.random::<f64>() * 0.2 - 0.1; // +/- 10%
283                    let vote = (candidate.confidence + noise).clamp(0.0, 1.0);
284                    committee_votes.push(vote);
285                }
286
287                // Calculate variance as disagreement
288                let mean: f64 = committee_votes.iter().sum::<f64>() / committee_votes.len() as f64;
289                let variance: f64 = committee_votes
290                    .iter()
291                    .map(|v| (v - mean).powi(2))
292                    .sum::<f64>()
293                    / committee_votes.len() as f64;
294
295                (name.clone(), variance)
296            })
297            .collect();
298
299        scores.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
300        scores.first().map(|(name, _)| name.clone())
301    }
302
303    /// Diversity sampling: select most diverse rule
304    fn diversity_sampling(&self, candidates: &[(String, CandidateRule)]) -> Option<String> {
305        // Simple diversity based on rule structure differences
306        let validated_rules: Vec<_> = self
307            .candidates
308            .values()
309            .filter(|c| c.validated)
310            .map(|c| &c.rule)
311            .collect();
312
313        candidates
314            .iter()
315            .max_by(|a, b| {
316                let diversity_a = self.calculate_diversity(&a.1.rule, &validated_rules);
317                let diversity_b = self.calculate_diversity(&b.1.rule, &validated_rules);
318                diversity_a
319                    .partial_cmp(&diversity_b)
320                    .unwrap_or(std::cmp::Ordering::Equal)
321            })
322            .map(|(name, _)| name.clone())
323    }
324
325    /// Expected model change: select rule that would change model most
326    fn expected_model_change(&self, candidates: &[(String, CandidateRule)]) -> Option<String> {
327        // Prioritize rules with extreme confidence (very high or very low)
328        candidates
329            .iter()
330            .max_by(|a, b| {
331                let change_a = (a.1.confidence - 0.5).abs();
332                let change_b = (b.1.confidence - 0.5).abs();
333                change_a
334                    .partial_cmp(&change_b)
335                    .unwrap_or(std::cmp::Ordering::Equal)
336            })
337            .map(|(name, _)| name.clone())
338    }
339
340    /// Random sampling: baseline strategy
341    fn random_sampling(&mut self, candidates: &[(String, CandidateRule)]) -> Option<String> {
342        if candidates.is_empty() {
343            return None;
344        }
345        let idx: usize = self.rng.gen_range(0..candidates.len());
346        Some(candidates[idx].0.clone())
347    }
348
349    /// Calculate diversity score
350    fn calculate_diversity(&self, rule: &Rule, validated_rules: &[&Rule]) -> f64 {
351        if validated_rules.is_empty() {
352            return 1.0;
353        }
354
355        let similarities: Vec<f64> = validated_rules
356            .iter()
357            .map(|vr| self.rule_similarity(rule, vr))
358            .collect();
359
360        let avg_similarity = similarities.iter().sum::<f64>() / similarities.len() as f64;
361        1.0 - avg_similarity
362    }
363
364    /// Calculate rule similarity (simple structural comparison)
365    fn rule_similarity(&self, rule1: &Rule, rule2: &Rule) -> f64 {
366        let body_size_diff = (rule1.body.len() as i32 - rule2.body.len() as i32).abs() as f64;
367        let head_size_diff = (rule1.head.len() as i32 - rule2.head.len() as i32).abs() as f64;
368
369        let max_size =
370            (rule1.body.len() + rule1.head.len()).max(rule2.body.len() + rule2.head.len()) as f64;
371
372        if max_size == 0.0 {
373            return 1.0;
374        }
375
376        1.0 - (body_size_diff + head_size_diff) / max_size
377    }
378
379    /// Get validation statistics
380    pub fn get_statistics(&self) -> ValidationStatistics {
381        let total = self.candidates.len();
382        let validated = self.candidates.values().filter(|c| c.validated).count();
383        let correct = self
384            .candidates
385            .values()
386            .filter(|c| c.validated && c.validation_result == Some(true))
387            .count();
388
389        let avg_confidence = if validated > 0 {
390            self.candidates
391                .values()
392                .filter(|c| c.validated)
393                .filter_map(|c| c.actual_confidence)
394                .sum::<f64>()
395                / validated as f64
396        } else {
397            0.0
398        };
399
400        ValidationStatistics {
401            total_candidates: total,
402            validated_count: validated,
403            correct_count: correct,
404            incorrect_count: validated - correct,
405            average_confidence: avg_confidence,
406            validation_coverage: self.validation_coverage(),
407            validation_accuracy: self.validation_accuracy(),
408        }
409    }
410
411    /// Clear all candidates and history
412    pub fn clear(&mut self) {
413        self.candidates.clear();
414        self.validation_history.clear();
415    }
416}
417
418/// Validation statistics
419#[derive(Debug, Clone)]
420pub struct ValidationStatistics {
421    /// Total number of candidate rules
422    pub total_candidates: usize,
423    /// Number of validated rules
424    pub validated_count: usize,
425    /// Number of correct rules
426    pub correct_count: usize,
427    /// Number of incorrect rules
428    pub incorrect_count: usize,
429    /// Average validation confidence
430    pub average_confidence: f64,
431    /// Validation coverage (0.0 to 1.0)
432    pub validation_coverage: f64,
433    /// Validation accuracy (0.0 to 1.0)
434    pub validation_accuracy: f64,
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440    use crate::{RuleAtom, Term};
441
442    fn create_test_rule(name: &str) -> Rule {
443        Rule {
444            name: name.to_string(),
445            body: vec![RuleAtom::Triple {
446                subject: Term::Variable("X".to_string()),
447                predicate: Term::Constant("p".to_string()),
448                object: Term::Variable("Y".to_string()),
449            }],
450            head: vec![RuleAtom::Triple {
451                subject: Term::Variable("X".to_string()),
452                predicate: Term::Constant("q".to_string()),
453                object: Term::Variable("Y".to_string()),
454            }],
455        }
456    }
457
458    #[test]
459    fn test_active_learner_creation() {
460        let learner = ActiveLearner::new();
461        assert_eq!(learner.validation_coverage(), 0.0);
462        assert_eq!(learner.validation_accuracy(), 0.0);
463    }
464
465    #[test]
466    fn test_add_candidate_rule() {
467        let mut learner = ActiveLearner::new();
468        let rule = create_test_rule("rule1");
469        learner.add_candidate_rule(rule, 0.75);
470
471        assert_eq!(learner.candidates.len(), 1);
472        assert_eq!(learner.validation_coverage(), 0.0);
473    }
474
475    #[test]
476    fn test_uncertainty_sampling() -> Result<(), Box<dyn std::error::Error>> {
477        let mut learner = ActiveLearner::new();
478
479        // Add rules with varying confidence
480        learner.add_candidate_rule(create_test_rule("high_conf"), 0.95);
481        learner.add_candidate_rule(create_test_rule("low_conf"), 0.15);
482        learner.add_candidate_rule(create_test_rule("uncertain"), 0.52);
483
484        let selected = learner.select_next_for_validation(SamplingStrategy::UncertaintySampling);
485        assert!(selected.is_some());
486
487        // Should select the most uncertain (closest to 0.5)
488        let rule_name = selected.ok_or("expected Some value")?.name;
489        assert_eq!(rule_name, "uncertain");
490        Ok(())
491    }
492
493    #[test]
494    fn test_record_validation() {
495        let mut learner = ActiveLearner::new();
496        learner.add_candidate_rule(create_test_rule("rule1"), 0.75);
497
498        learner.record_validation("rule1", true, 0.9);
499
500        assert_eq!(learner.validation_coverage(), 1.0);
501        assert_eq!(learner.validation_history.len(), 1);
502    }
503
504    #[test]
505    fn test_validation_accuracy() {
506        let mut learner = ActiveLearner::new();
507        learner.set_min_confidence_threshold(0.6);
508
509        // Add rules and validate
510        learner.add_candidate_rule(create_test_rule("correct_high"), 0.8);
511        learner.record_validation("correct_high", true, 0.9);
512
513        learner.add_candidate_rule(create_test_rule("correct_low"), 0.3);
514        learner.record_validation("correct_low", false, 0.2);
515
516        let accuracy = learner.validation_accuracy();
517        assert_eq!(accuracy, 1.0); // Both predictions were correct
518    }
519
520    #[test]
521    fn test_validation_coverage() {
522        let mut learner = ActiveLearner::new();
523
524        learner.add_candidate_rule(create_test_rule("rule1"), 0.7);
525        learner.add_candidate_rule(create_test_rule("rule2"), 0.8);
526        learner.add_candidate_rule(create_test_rule("rule3"), 0.6);
527
528        assert_eq!(learner.validation_coverage(), 0.0);
529
530        learner.record_validation("rule1", true, 0.9);
531        assert!((learner.validation_coverage() - 0.333).abs() < 0.01);
532
533        learner.record_validation("rule2", true, 0.85);
534        assert!((learner.validation_coverage() - 0.666).abs() < 0.01);
535    }
536
537    #[test]
538    fn test_query_by_committee() {
539        let mut learner = ActiveLearner::new();
540
541        learner.add_candidate_rule(create_test_rule("rule1"), 0.5);
542        learner.add_candidate_rule(create_test_rule("rule2"), 0.9);
543
544        let selected = learner.select_next_for_validation(SamplingStrategy::QueryByCommittee);
545        assert!(selected.is_some());
546    }
547
548    #[test]
549    fn test_diversity_sampling() {
550        let mut learner = ActiveLearner::new();
551
552        learner.add_candidate_rule(create_test_rule("rule1"), 0.7);
553        learner.add_candidate_rule(create_test_rule("rule2"), 0.8);
554
555        // Validate one rule first
556        learner.record_validation("rule1", true, 0.9);
557
558        let selected = learner.select_next_for_validation(SamplingStrategy::DiversitySampling);
559        assert!(selected.is_some());
560    }
561
562    #[test]
563    fn test_random_sampling() {
564        let mut learner = ActiveLearner::new();
565
566        learner.add_candidate_rule(create_test_rule("rule1"), 0.7);
567        learner.add_candidate_rule(create_test_rule("rule2"), 0.8);
568
569        let selected = learner.select_next_for_validation(SamplingStrategy::RandomSampling);
570        assert!(selected.is_some());
571    }
572
573    #[test]
574    fn test_validation_statistics() {
575        let mut learner = ActiveLearner::new();
576
577        learner.add_candidate_rule(create_test_rule("rule1"), 0.8);
578        learner.add_candidate_rule(create_test_rule("rule2"), 0.6);
579        learner.add_candidate_rule(create_test_rule("rule3"), 0.9);
580
581        learner.record_validation("rule1", true, 0.95);
582        learner.record_validation("rule2", false, 0.3);
583
584        let stats = learner.get_statistics();
585        assert_eq!(stats.total_candidates, 3);
586        assert_eq!(stats.validated_count, 2);
587        assert_eq!(stats.correct_count, 1);
588        assert_eq!(stats.incorrect_count, 1);
589        assert!((stats.validation_coverage - 0.666).abs() < 0.01);
590    }
591
592    #[test]
593    fn test_clear() {
594        let mut learner = ActiveLearner::new();
595
596        learner.add_candidate_rule(create_test_rule("rule1"), 0.7);
597        learner.record_validation("rule1", true, 0.9);
598
599        learner.clear();
600
601        assert_eq!(learner.candidates.len(), 0);
602        assert_eq!(learner.validation_history.len(), 0);
603    }
604}