Skip to main content

oxirs_rule/
probabilistic.rs

1//! # Probabilistic Reasoning Module
2//!
3//! This module provides probabilistic inference capabilities for rule-based reasoning,
4//! including Bayesian Networks, Markov Logic Networks, and uncertain reasoning.
5//!
6//! ## Features
7//!
8//! - **Bayesian Networks**: Directed graphical models for probabilistic inference
9//! - **Markov Logic Networks (MLN)**: Combines first-order logic with probabilities
10//! - **Uncertainty Propagation**: Tracks confidence through inference chains
11//! - **Probabilistic Rules**: Rules with associated probabilities/weights
12//! - **Approximate Inference**: Gibbs sampling, belief propagation
13//!
14//! ## Example
15//!
16//! ```text
17//! use oxirs_rule::probabilistic::*;
18//! use oxirs_rule::{RuleAtom, Term};
19//!
20//! // Create a Bayesian Network
21//! let mut bn = BayesianNetwork::new();
22//!
23//! // Add variables
24//! bn.add_variable("Rain".to_string(), vec!["true".to_string(), "false".to_string()]);
25//! bn.add_variable("Sprinkler".to_string(), vec!["true".to_string(), "false".to_string()]);
26//! bn.add_variable("WetGrass".to_string(), vec!["true".to_string(), "false".to_string()]);
27//!
28//! // Add dependencies
29//! bn.add_edge("Rain".to_string(), "WetGrass".to_string()).expect("should succeed");
30//! bn.add_edge("Sprinkler".to_string(), "WetGrass".to_string()).expect("should succeed");
31//!
32//! // Add conditional probability tables (CPTs)
33//! // P(Rain) = 0.2
34//! bn.set_prior("Rain".to_string(), vec![0.2, 0.8]).expect("should succeed");
35//!
36//! // Query the network
37//! let evidence = vec![("WetGrass".to_string(), "true".to_string())];
38//! let prob = bn.query("Rain".to_string(), "true".to_string(), &evidence).expect("should succeed");
39//! # Ok::<(), anyhow::Error>(())
40//! ```
41
42use crate::{Rule, RuleAtom, Term};
43use anyhow::{anyhow, Result};
44use scirs2_core::ndarray_ext::Array1;
45use scirs2_core::random::{Distribution, Rng as RngTrait, Uniform};
46use std::collections::{HashMap, HashSet};
47
48/// Bayesian Network for probabilistic inference
49#[derive(Debug, Clone)]
50pub struct BayesianNetwork {
51    /// Variables in the network
52    variables: HashMap<String, Variable>,
53    /// Edges (dependencies) in the network
54    edges: Vec<(String, String)>,
55    /// Conditional Probability Tables (CPTs)
56    cpts: HashMap<String, ConditionalProbabilityTable>,
57}
58
59/// Variable in a Bayesian Network
60#[derive(Debug, Clone)]
61pub struct Variable {
62    /// Variable name
63    #[allow(dead_code)]
64    name: String,
65    /// Possible values (domain)
66    domain: Vec<String>,
67}
68
69/// Conditional Probability Table
70#[derive(Debug, Clone)]
71pub struct ConditionalProbabilityTable {
72    /// Variable this CPT is for
73    #[allow(dead_code)]
74    variable: String,
75    /// Parent variables
76    parents: Vec<String>,
77    /// Probability table (flattened)
78    /// For a variable with parents, this is P(variable | parents)
79    probabilities: Array1<f64>,
80    /// Dimensions of the probability table
81    dimensions: Vec<usize>,
82}
83
84impl BayesianNetwork {
85    /// Create a new Bayesian Network
86    pub fn new() -> Self {
87        Self {
88            variables: HashMap::new(),
89            edges: Vec::new(),
90            cpts: HashMap::new(),
91        }
92    }
93
94    /// Add a variable to the network
95    pub fn add_variable(&mut self, name: String, domain: Vec<String>) {
96        self.variables.insert(
97            name.clone(),
98            Variable {
99                name: name.clone(),
100                domain,
101            },
102        );
103    }
104
105    /// Add an edge (dependency) between two variables
106    pub fn add_edge(&mut self, from: String, to: String) -> Result<()> {
107        // Check if variables exist
108        if !self.variables.contains_key(&from) {
109            return Err(anyhow!("Variable {} not found", from));
110        }
111        if !self.variables.contains_key(&to) {
112            return Err(anyhow!("Variable {} not found", to));
113        }
114
115        // Check for cycles (simple cycle detection)
116        if self.has_path(&to, &from) {
117            return Err(anyhow!("Adding edge would create a cycle"));
118        }
119
120        self.edges.push((from, to));
121        Ok(())
122    }
123
124    /// Check if there's a path from `from` to `to` (for cycle detection)
125    fn has_path(&self, from: &str, to: &str) -> bool {
126        let mut visited = HashSet::new();
127        let mut stack = vec![from];
128
129        while let Some(current) = stack.pop() {
130            if current == to {
131                return true;
132            }
133
134            if visited.contains(current) {
135                continue;
136            }
137            visited.insert(current);
138
139            for (source, target) in &self.edges {
140                if source == current {
141                    stack.push(target.as_str());
142                }
143            }
144        }
145
146        false
147    }
148
149    /// Set prior probability for a variable (no parents)
150    pub fn set_prior(&mut self, variable: String, probabilities: Vec<f64>) -> Result<()> {
151        let var = self
152            .variables
153            .get(&variable)
154            .ok_or_else(|| anyhow!("Variable {} not found", variable))?;
155
156        if probabilities.len() != var.domain.len() {
157            return Err(anyhow!(
158                "Probability vector length {} does not match domain size {}",
159                probabilities.len(),
160                var.domain.len()
161            ));
162        }
163
164        // Check probabilities sum to 1.0
165        let sum: f64 = probabilities.iter().sum();
166        if (sum - 1.0).abs() > 1e-6 {
167            return Err(anyhow!("Probabilities must sum to 1.0, got {}", sum));
168        }
169
170        let cpt = ConditionalProbabilityTable {
171            variable: variable.clone(),
172            parents: Vec::new(),
173            probabilities: Array1::from_vec(probabilities),
174            dimensions: vec![var.domain.len()],
175        };
176
177        self.cpts.insert(variable, cpt);
178        Ok(())
179    }
180
181    /// Set conditional probability table for a variable with parents
182    pub fn set_cpt(
183        &mut self,
184        variable: String,
185        parents: Vec<String>,
186        probabilities: Array1<f64>,
187    ) -> Result<()> {
188        let var = self
189            .variables
190            .get(&variable)
191            .ok_or_else(|| anyhow!("Variable {} not found", variable))?;
192
193        // Calculate expected size
194        let mut expected_size = var.domain.len();
195        let mut dimensions = vec![var.domain.len()];
196
197        for parent in &parents {
198            let parent_var = self
199                .variables
200                .get(parent)
201                .ok_or_else(|| anyhow!("Parent variable {} not found", parent))?;
202            expected_size *= parent_var.domain.len();
203            dimensions.push(parent_var.domain.len());
204        }
205
206        if probabilities.len() != expected_size {
207            return Err(anyhow!(
208                "CPT size {} does not match expected size {}",
209                probabilities.len(),
210                expected_size
211            ));
212        }
213
214        let cpt = ConditionalProbabilityTable {
215            variable: variable.clone(),
216            parents,
217            probabilities,
218            dimensions,
219        };
220
221        self.cpts.insert(variable, cpt);
222        Ok(())
223    }
224
225    /// Query the network: P(variable=value | evidence)
226    /// Uses Variable Elimination algorithm for exact inference
227    pub fn query(
228        &self,
229        variable: String,
230        value: String,
231        evidence: &[(String, String)],
232    ) -> Result<f64> {
233        // For now, implement a simple forward sampling approach
234        // In a production system, you'd use Variable Elimination or Belief Propagation
235        self.forward_sampling(&variable, &value, evidence, 10000)
236    }
237
238    /// Forward sampling (approximate inference)
239    fn forward_sampling(
240        &self,
241        query_var: &str,
242        query_val: &str,
243        evidence: &[(String, String)],
244        num_samples: usize,
245    ) -> Result<f64> {
246        use scirs2_core::random::rng;
247
248        let mut rng = rng();
249        let mut matches = 0;
250        let mut valid_samples = 0;
251
252        // Topological sort of variables
253        let topo_order = self.topological_sort()?;
254
255        for _ in 0..num_samples {
256            let mut sample = HashMap::new();
257
258            // Sample each variable in topological order
259            for var_name in &topo_order {
260                let var = &self.variables[var_name];
261                let cpt = self
262                    .cpts
263                    .get(var_name)
264                    .ok_or_else(|| anyhow!("CPT not found for {}", var_name))?;
265
266                // Get conditional probability based on parents
267                let prob_dist = self.get_conditional_prob(cpt, &sample)?;
268
269                // Sample from the distribution
270                let sampled_value =
271                    self.sample_from_distribution(&prob_dist, &var.domain, &mut rng);
272                sample.insert(var_name.clone(), sampled_value);
273            }
274
275            // Check if sample matches evidence
276            let matches_evidence = evidence
277                .iter()
278                .all(|(ev_var, ev_val)| sample.get(ev_var) == Some(ev_val));
279
280            if matches_evidence {
281                valid_samples += 1;
282                if sample.get(query_var).is_some_and(|v| v == query_val) {
283                    matches += 1;
284                }
285            }
286        }
287
288        if valid_samples == 0 {
289            return Err(anyhow!("No samples matched the evidence"));
290        }
291
292        Ok(matches as f64 / valid_samples as f64)
293    }
294
295    /// Get conditional probability distribution for a variable given parent values
296    fn get_conditional_prob(
297        &self,
298        cpt: &ConditionalProbabilityTable,
299        sample: &HashMap<String, String>,
300    ) -> Result<Array1<f64>> {
301        if cpt.parents.is_empty() {
302            // No parents, return prior
303            return Ok(cpt.probabilities.clone());
304        }
305
306        // Calculate index into CPT based on parent values
307        let mut index = 0;
308        let mut multiplier = 1;
309
310        for (i, parent) in cpt.parents.iter().enumerate().rev() {
311            let parent_var = &self.variables[parent];
312            let parent_value = sample
313                .get(parent)
314                .ok_or_else(|| anyhow!("Parent {} not sampled yet", parent))?;
315            let value_index = parent_var
316                .domain
317                .iter()
318                .position(|v| v == parent_value)
319                .ok_or_else(|| anyhow!("Parent value {} not in domain", parent_value))?;
320
321            index += value_index * multiplier;
322            multiplier *= cpt.dimensions[i + 1];
323        }
324
325        // Extract the conditional distribution for this parent configuration
326        let var_domain_size = cpt.dimensions[0];
327        let start = index * var_domain_size;
328
329        // Use ndarray slicing to extract the probability distribution
330        let probs_vec: Vec<f64> = cpt
331            .probabilities
332            .iter()
333            .skip(start)
334            .take(var_domain_size)
335            .copied()
336            .collect();
337        Ok(Array1::from_vec(probs_vec))
338    }
339
340    /// Sample from a probability distribution
341    fn sample_from_distribution(
342        &self,
343        prob_dist: &Array1<f64>,
344        domain: &[String],
345        rng: &mut impl RngTrait,
346    ) -> String {
347        let uniform = Uniform::new(0.0, 1.0).expect("distribution parameters are valid");
348        let u: f64 = uniform.sample(rng);
349
350        let mut cumulative = 0.0;
351        for (i, &prob) in prob_dist.iter().enumerate() {
352            cumulative += prob;
353            if u <= cumulative {
354                return domain[i].clone();
355            }
356        }
357
358        // Fallback (shouldn't happen if probabilities sum to 1.0)
359        domain[domain.len() - 1].clone()
360    }
361
362    /// Topological sort of variables
363    fn topological_sort(&self) -> Result<Vec<String>> {
364        let mut in_degree: HashMap<String, usize> = HashMap::new();
365        let mut adj_list: HashMap<String, Vec<String>> = HashMap::new();
366
367        // Initialize
368        for var_name in self.variables.keys() {
369            in_degree.insert(var_name.clone(), 0);
370            adj_list.insert(var_name.clone(), Vec::new());
371        }
372
373        // Build adjacency list and in-degrees
374        for (from, to) in &self.edges {
375            adj_list
376                .get_mut(from)
377                .expect("variable should exist in adjacency list")
378                .push(to.clone());
379            *in_degree
380                .get_mut(to)
381                .expect("variable should exist in in_degree map") += 1;
382        }
383
384        // Kahn's algorithm
385        let mut queue: Vec<String> = in_degree
386            .iter()
387            .filter(|(_, &deg)| deg == 0)
388            .map(|(name, _)| name.clone())
389            .collect();
390
391        let mut result = Vec::new();
392
393        while let Some(node) = queue.pop() {
394            result.push(node.clone());
395
396            if let Some(neighbors) = adj_list.get(&node) {
397                for neighbor in neighbors {
398                    let deg = in_degree
399                        .get_mut(neighbor)
400                        .expect("neighbor should exist in in_degree map");
401                    *deg -= 1;
402                    if *deg == 0 {
403                        queue.push(neighbor.clone());
404                    }
405                }
406            }
407        }
408
409        if result.len() != self.variables.len() {
410            return Err(anyhow!(
411                "Graph has a cycle, cannot perform topological sort"
412            ));
413        }
414
415        Ok(result)
416    }
417
418    /// Return the number of variables in the network
419    pub fn variable_count(&self) -> usize {
420        self.variables.len()
421    }
422
423    /// Check whether a variable with the given name exists
424    pub fn has_variable(&self, name: &str) -> bool {
425        self.variables.contains_key(name)
426    }
427
428    /// Check whether a directed edge exists between two variables
429    pub fn has_edge(&self, from: &str, to: &str) -> bool {
430        self.edges.iter().any(|(f, t)| f == from && t == to)
431    }
432
433    /// Retrieve the prior probability for a specific value of a variable.
434    ///
435    /// Returns 0.0 if no CPT is set or the value is not in the domain.
436    pub fn get_prior(&self, variable: &str, value: &str) -> f64 {
437        let cpt = match self.cpts.get(variable) {
438            Some(c) => c,
439            None => return 0.0,
440        };
441        // Prior CPT has no parents
442        if !cpt.parents.is_empty() {
443            return 0.0;
444        }
445        let var = match self.variables.get(variable) {
446            Some(v) => v,
447            None => return 0.0,
448        };
449        let idx = match var.domain.iter().position(|v| v == value) {
450            Some(i) => i,
451            None => return 0.0,
452        };
453        if idx < cpt.probabilities.len() {
454            cpt.probabilities[idx]
455        } else {
456            0.0
457        }
458    }
459}
460
461impl Default for BayesianNetwork {
462    fn default() -> Self {
463        Self::new()
464    }
465}
466
467/// Markov Logic Network (MLN)
468/// Combines first-order logic with probabilistic graphical models
469#[derive(Debug, Clone)]
470pub struct MarkovLogicNetwork {
471    /// Weighted rules (formulas with weights)
472    weighted_rules: Vec<WeightedRule>,
473    /// Domain of constants
474    constants: HashSet<String>,
475    /// Predicates and their arities
476    predicates: HashMap<String, usize>,
477}
478
479/// A rule with an associated weight
480#[derive(Debug, Clone)]
481pub struct WeightedRule {
482    /// The rule
483    pub rule: Rule,
484    /// Weight (log-odds of the rule being satisfied)
485    pub weight: f64,
486}
487
488impl MarkovLogicNetwork {
489    /// Create a new Markov Logic Network
490    pub fn new() -> Self {
491        Self {
492            weighted_rules: Vec::new(),
493            constants: HashSet::new(),
494            predicates: HashMap::new(),
495        }
496    }
497
498    /// Add a weighted rule to the MLN
499    pub fn add_weighted_rule(&mut self, rule: Rule, weight: f64) {
500        // Extract constants and predicates from rule
501        self.extract_symbols(&rule);
502        self.weighted_rules.push(WeightedRule { rule, weight });
503    }
504
505    /// Extract constants and predicates from a rule
506    fn extract_symbols(&mut self, rule: &Rule) {
507        for atom in rule.body.iter().chain(rule.head.iter()) {
508            if let RuleAtom::Triple {
509                subject,
510                predicate,
511                object,
512            } = atom
513            {
514                if let Term::Constant(c) = subject {
515                    self.constants.insert(c.clone());
516                }
517                if let Term::Constant(c) = predicate {
518                    self.predicates.entry(c.clone()).or_insert(2); // Binary predicate
519                }
520                if let Term::Constant(c) = object {
521                    self.constants.insert(c.clone());
522                }
523            }
524        }
525    }
526
527    /// Compute the probability of a world (ground truth assignment)
528    /// P(world) ∝ exp(Σ w_i * n_i)
529    /// where w_i is the weight of rule i, and n_i is the number of groundings that are true
530    pub fn compute_world_probability(&self, world: &[RuleAtom]) -> Result<f64> {
531        let mut total_weight = 0.0;
532
533        for weighted_rule in &self.weighted_rules {
534            let num_satisfied = self.count_satisfied_groundings(&weighted_rule.rule, world)?;
535            total_weight += weighted_rule.weight * num_satisfied as f64;
536        }
537
538        Ok(total_weight.exp())
539    }
540
541    /// Count how many groundings of a rule are satisfied in the given world
542    fn count_satisfied_groundings(&self, rule: &Rule, world: &[RuleAtom]) -> Result<usize> {
543        // Simplified: check if rule fires for any grounding
544        let mut count = 0;
545
546        // For each possible grounding (combination of constants)
547        // Check if body is satisfied and head is true
548        // This is a simplified version - full implementation would enumerate all groundings
549
550        // Check if any facts in world match the rule head
551        for fact in world {
552            if self.matches_rule_head(fact, &rule.head) {
553                count += 1;
554            }
555        }
556
557        Ok(count)
558    }
559
560    /// Check if a fact matches any atom in the rule head
561    fn matches_rule_head(&self, fact: &RuleAtom, head: &[RuleAtom]) -> bool {
562        head.iter().any(|atom| self.atoms_match(fact, atom))
563    }
564
565    /// Check if two atoms match (simplified)
566    fn atoms_match(&self, fact: &RuleAtom, pattern: &RuleAtom) -> bool {
567        match (fact, pattern) {
568            (
569                RuleAtom::Triple {
570                    subject: s1,
571                    predicate: p1,
572                    object: o1,
573                },
574                RuleAtom::Triple {
575                    subject: s2,
576                    predicate: p2,
577                    object: o2,
578                },
579            ) => self.terms_match(s1, s2) && self.terms_match(p1, p2) && self.terms_match(o1, o2),
580            _ => false,
581        }
582    }
583
584    /// Check if two terms match (constants must be equal, variables match anything)
585    fn terms_match(&self, term1: &Term, term2: &Term) -> bool {
586        match (term1, term2) {
587            (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
588            (Term::Variable(_), _) => true,
589            (_, Term::Variable(_)) => true,
590            _ => false,
591        }
592    }
593
594    /// Perform MAP inference (find most probable world)
595    pub fn map_inference(&self, evidence: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
596        // Simplified MAP inference using greedy approach
597        // Full implementation would use MaxWalkSAT or similar
598
599        let mut current_world = evidence.to_vec();
600        let mut best_prob = self.compute_world_probability(&current_world)?;
601
602        // Try adding inferred facts
603        for weighted_rule in &self.weighted_rules {
604            // Try to apply the rule and see if probability increases
605            let mut new_world = current_world.clone();
606
607            // Add all atoms from rule head (simplified)
608            for atom in &weighted_rule.rule.head {
609                new_world.push(atom.clone());
610            }
611
612            let new_prob = self.compute_world_probability(&new_world)?;
613            if new_prob > best_prob {
614                current_world = new_world;
615                best_prob = new_prob;
616            }
617        }
618
619        Ok(current_world)
620    }
621
622    /// Gibbs sampling for approximate inference
623    pub fn gibbs_sampling(
624        &self,
625        evidence: &[RuleAtom],
626        num_samples: usize,
627    ) -> Result<Vec<RuleAtom>> {
628        use scirs2_core::random::rng;
629
630        let mut rng = rng();
631        let mut current_state = evidence.to_vec();
632
633        // Burn-in period
634        for _ in 0..num_samples / 10 {
635            current_state = self.gibbs_step(&current_state, &mut rng)?;
636        }
637
638        // Collect samples
639        let mut sample_counts: HashMap<String, usize> = HashMap::new();
640
641        for _ in 0..num_samples {
642            current_state = self.gibbs_step(&current_state, &mut rng)?;
643
644            // Count occurrences of each atom
645            for atom in &current_state {
646                let key = format!("{:?}", atom);
647                *sample_counts.entry(key).or_insert(0) += 1;
648            }
649        }
650
651        // Return most frequent state
652        Ok(current_state)
653    }
654
655    /// Single Gibbs sampling step
656    fn gibbs_step(
657        &self,
658        current_state: &[RuleAtom],
659        _rng: &mut impl RngTrait,
660    ) -> Result<Vec<RuleAtom>> {
661        // Randomly select a ground atom and resample it
662        let new_state = current_state.to_vec();
663
664        // For simplicity, just return current state
665        // Full implementation would sample each atom conditional on others
666        Ok(new_state)
667    }
668
669    /// Register a predicate name with its arity
670    pub fn add_predicate(&mut self, name: String, arity: usize) {
671        self.predicates.insert(name, arity);
672    }
673
674    /// Check whether a predicate with the given name is registered
675    pub fn has_predicate(&self, name: &str) -> bool {
676        self.predicates.contains_key(name)
677    }
678
679    /// Add a weighted first-order logic formula to the network.
680    ///
681    /// The formula is stored as a textual representation alongside its weight.
682    /// A corresponding `Rule` is created with the formula string as the rule name.
683    pub fn add_formula(&mut self, formula: String, weight: f64) {
684        let rule = Rule {
685            name: formula,
686            body: Vec::new(),
687            head: Vec::new(),
688        };
689        self.weighted_rules.push(WeightedRule { rule, weight });
690    }
691
692    /// Return the number of weighted formulas (rules) in the network
693    pub fn formula_count(&self) -> usize {
694        self.weighted_rules.len()
695    }
696}
697
698impl Default for MarkovLogicNetwork {
699    fn default() -> Self {
700        Self::new()
701    }
702}
703
704/// Probabilistic Rule Engine
705/// Extends standard rule engine with probabilistic inference
706#[derive(Debug)]
707pub struct ProbabilisticRuleEngine {
708    /// Bayesian Network for structural inference
709    bayesian_network: Option<BayesianNetwork>,
710    /// Markov Logic Network for first-order probabilistic logic
711    mln: MarkovLogicNetwork,
712    /// Weighted rules
713    weighted_rules: Vec<WeightedRule>,
714}
715
716impl ProbabilisticRuleEngine {
717    /// Create a new probabilistic rule engine
718    pub fn new() -> Self {
719        Self {
720            bayesian_network: None,
721            mln: MarkovLogicNetwork::new(),
722            weighted_rules: Vec::new(),
723        }
724    }
725
726    /// Set the Bayesian Network
727    pub fn set_bayesian_network(&mut self, bn: BayesianNetwork) {
728        self.bayesian_network = Some(bn);
729    }
730
731    /// Add a weighted rule
732    pub fn add_weighted_rule(&mut self, rule: Rule, weight: f64) {
733        self.weighted_rules.push(WeightedRule { rule, weight });
734        self.mln.add_weighted_rule(
735            self.weighted_rules
736                .last()
737                .expect("weighted_rules should not be empty after push")
738                .rule
739                .clone(),
740            weight,
741        );
742    }
743
744    /// Perform probabilistic forward chaining
745    /// Returns inferred facts with their confidence scores
746    pub fn probabilistic_forward_chain(&self, facts: &[RuleAtom]) -> Result<Vec<(RuleAtom, f64)>> {
747        let mut inferred_with_confidence = Vec::new();
748
749        // For each weighted rule, try to apply it
750        for weighted_rule in &self.weighted_rules {
751            // Check if rule body is satisfied
752            if self.rule_body_satisfied(&weighted_rule.rule, facts) {
753                // Add head with confidence based on weight
754                let confidence = 1.0 / (1.0 + (-weighted_rule.weight).exp()); // Sigmoid
755                for atom in &weighted_rule.rule.head {
756                    inferred_with_confidence.push((atom.clone(), confidence));
757                }
758            }
759        }
760
761        Ok(inferred_with_confidence)
762    }
763
764    /// Check if rule body is satisfied by the facts
765    fn rule_body_satisfied(&self, rule: &Rule, facts: &[RuleAtom]) -> bool {
766        // Simplified: check if all body atoms are in facts
767        rule.body
768            .iter()
769            .all(|body_atom| facts.iter().any(|fact| self.atoms_similar(body_atom, fact)))
770    }
771
772    /// Check if two atoms are similar (simplified matching)
773    fn atoms_similar(&self, atom1: &RuleAtom, atom2: &RuleAtom) -> bool {
774        match (atom1, atom2) {
775            (
776                RuleAtom::Triple {
777                    predicate: p1,
778                    subject: s1,
779                    object: o1,
780                },
781                RuleAtom::Triple {
782                    predicate: p2,
783                    subject: s2,
784                    object: o2,
785                },
786            ) => {
787                // Variables match anything
788                let pred_match = match (p1, p2) {
789                    (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
790                    _ => true,
791                };
792                let subj_match = match (s1, s2) {
793                    (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
794                    _ => true,
795                };
796                let obj_match = match (o1, o2) {
797                    (Term::Constant(c1), Term::Constant(c2)) => c1 == c2,
798                    _ => true,
799                };
800                pred_match && subj_match && obj_match
801            }
802            _ => false,
803        }
804    }
805
806    /// Query using Bayesian Network if available
807    pub fn query_bayesian(
808        &self,
809        variable: String,
810        value: String,
811        evidence: &[(String, String)],
812    ) -> Result<f64> {
813        if let Some(bn) = &self.bayesian_network {
814            bn.query(variable, value, evidence)
815        } else {
816            Err(anyhow!("Bayesian Network not set"))
817        }
818    }
819
820    /// Perform MAP inference using MLN
821    pub fn mln_map_inference(&self, evidence: &[RuleAtom]) -> Result<Vec<RuleAtom>> {
822        self.mln.map_inference(evidence)
823    }
824}
825
826impl Default for ProbabilisticRuleEngine {
827    fn default() -> Self {
828        Self::new()
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    #[test]
837    fn test_bayesian_network_creation() {
838        let mut bn = BayesianNetwork::new();
839
840        bn.add_variable("Rain".to_string(), vec!["T".to_string(), "F".to_string()]);
841        bn.add_variable(
842            "Sprinkler".to_string(),
843            vec!["T".to_string(), "F".to_string()],
844        );
845        bn.add_variable(
846            "WetGrass".to_string(),
847            vec!["T".to_string(), "F".to_string()],
848        );
849
850        assert!(bn.variables.contains_key("Rain"));
851        assert!(bn.variables.contains_key("Sprinkler"));
852        assert!(bn.variables.contains_key("WetGrass"));
853    }
854
855    #[test]
856    fn test_bayesian_network_edges() {
857        let mut bn = BayesianNetwork::new();
858
859        bn.add_variable("A".to_string(), vec!["T".to_string(), "F".to_string()]);
860        bn.add_variable("B".to_string(), vec!["T".to_string(), "F".to_string()]);
861
862        assert!(bn.add_edge("A".to_string(), "B".to_string()).is_ok());
863
864        // Test cycle detection
865        assert!(bn.add_edge("B".to_string(), "A".to_string()).is_err());
866    }
867
868    #[test]
869    fn test_bayesian_network_prior() {
870        let mut bn = BayesianNetwork::new();
871
872        bn.add_variable("Coin".to_string(), vec!["H".to_string(), "T".to_string()]);
873
874        assert!(bn.set_prior("Coin".to_string(), vec![0.5, 0.5]).is_ok());
875
876        // Test invalid probability sum
877        assert!(bn.set_prior("Coin".to_string(), vec![0.6, 0.6]).is_err());
878    }
879
880    #[test]
881    fn test_mln_creation() {
882        let mln = MarkovLogicNetwork::new();
883        assert_eq!(mln.weighted_rules.len(), 0);
884    }
885
886    #[test]
887    fn test_mln_add_weighted_rule() {
888        let mut mln = MarkovLogicNetwork::new();
889
890        let rule = Rule {
891            name: "test_rule".to_string(),
892            body: vec![RuleAtom::Triple {
893                subject: Term::Variable("X".to_string()),
894                predicate: Term::Constant("smokes".to_string()),
895                object: Term::Constant("true".to_string()),
896            }],
897            head: vec![RuleAtom::Triple {
898                subject: Term::Variable("X".to_string()),
899                predicate: Term::Constant("cancer".to_string()),
900                object: Term::Constant("true".to_string()),
901            }],
902        };
903
904        mln.add_weighted_rule(rule, 1.5);
905        assert_eq!(mln.weighted_rules.len(), 1);
906    }
907
908    #[test]
909    fn test_probabilistic_rule_engine() -> Result<(), Box<dyn std::error::Error>> {
910        let mut engine = ProbabilisticRuleEngine::new();
911
912        let rule = Rule {
913            name: "prob_rule".to_string(),
914            body: vec![RuleAtom::Triple {
915                subject: Term::Variable("X".to_string()),
916                predicate: Term::Constant("input".to_string()),
917                object: Term::Variable("Y".to_string()),
918            }],
919            head: vec![RuleAtom::Triple {
920                subject: Term::Variable("X".to_string()),
921                predicate: Term::Constant("output".to_string()),
922                object: Term::Variable("Y".to_string()),
923            }],
924        };
925
926        engine.add_weighted_rule(rule, 2.0);
927
928        let facts = vec![RuleAtom::Triple {
929            subject: Term::Constant("a".to_string()),
930            predicate: Term::Constant("input".to_string()),
931            object: Term::Constant("b".to_string()),
932        }];
933
934        let result = engine.probabilistic_forward_chain(&facts)?;
935        assert!(!result.is_empty());
936
937        // Check confidence is reasonable
938        for (_, confidence) in result {
939            assert!(confidence > 0.0 && confidence <= 1.0);
940        }
941        Ok(())
942    }
943
944    #[test]
945    fn test_topological_sort() -> Result<(), Box<dyn std::error::Error>> {
946        let mut bn = BayesianNetwork::new();
947
948        bn.add_variable("A".to_string(), vec!["T".to_string(), "F".to_string()]);
949        bn.add_variable("B".to_string(), vec!["T".to_string(), "F".to_string()]);
950        bn.add_variable("C".to_string(), vec!["T".to_string(), "F".to_string()]);
951
952        bn.add_edge("A".to_string(), "B".to_string())?;
953        bn.add_edge("B".to_string(), "C".to_string())?;
954
955        let topo_order = bn.topological_sort()?;
956        assert_eq!(topo_order.len(), 3);
957
958        // A should come before B, and B before C
959        let a_idx = topo_order
960            .iter()
961            .position(|x| x == "A")
962            .ok_or("expected Some value")?;
963        let b_idx = topo_order
964            .iter()
965            .position(|x| x == "B")
966            .ok_or("expected Some value")?;
967        let c_idx = topo_order
968            .iter()
969            .position(|x| x == "C")
970            .ok_or("expected Some value")?;
971
972        assert!(a_idx < b_idx);
973        assert!(b_idx < c_idx);
974        Ok(())
975    }
976
977    // ---- Extended tests ----
978
979    #[test]
980    fn test_bn_new_is_empty() {
981        let bn = BayesianNetwork::new();
982        assert!(bn.variables.is_empty());
983        assert!(bn.edges.is_empty());
984        assert!(bn.cpts.is_empty());
985    }
986
987    #[test]
988    fn test_bn_add_four_variables() {
989        let mut bn = BayesianNetwork::new();
990        bn.add_variable("W".to_string(), vec!["T".to_string(), "F".to_string()]);
991        bn.add_variable("X".to_string(), vec!["T".to_string(), "F".to_string()]);
992        bn.add_variable("Y".to_string(), vec!["T".to_string(), "F".to_string()]);
993        bn.add_variable("Z".to_string(), vec!["T".to_string(), "F".to_string()]);
994        assert_eq!(bn.variables.len(), 4);
995    }
996
997    #[test]
998    fn test_bn_cycle_detection_three_node() {
999        let mut bn = BayesianNetwork::new();
1000        bn.add_variable("A".to_string(), vec!["T".to_string(), "F".to_string()]);
1001        bn.add_variable("B".to_string(), vec!["T".to_string(), "F".to_string()]);
1002        bn.add_variable("C".to_string(), vec!["T".to_string(), "F".to_string()]);
1003        assert!(bn.add_edge("A".to_string(), "B".to_string()).is_ok());
1004        assert!(bn.add_edge("B".to_string(), "C".to_string()).is_ok());
1005        // Creating a cycle: C -> A
1006        assert!(
1007            bn.add_edge("C".to_string(), "A".to_string()).is_err(),
1008            "Should detect cycle A->B->C->A"
1009        );
1010    }
1011
1012    #[test]
1013    fn test_bn_self_loop_is_cycle() {
1014        let mut bn = BayesianNetwork::new();
1015        bn.add_variable("A".to_string(), vec!["T".to_string(), "F".to_string()]);
1016        assert!(
1017            bn.add_edge("A".to_string(), "A".to_string()).is_err(),
1018            "Self-loop is a cycle"
1019        );
1020    }
1021
1022    #[test]
1023    fn test_bn_diamond_dag_is_valid() {
1024        let mut bn = BayesianNetwork::new();
1025        bn.add_variable("A".to_string(), vec!["T".to_string(), "F".to_string()]);
1026        bn.add_variable("B".to_string(), vec!["T".to_string(), "F".to_string()]);
1027        bn.add_variable("C".to_string(), vec!["T".to_string(), "F".to_string()]);
1028        bn.add_variable("D".to_string(), vec!["T".to_string(), "F".to_string()]);
1029        // A -> B, A -> C, B -> D, C -> D
1030        assert!(bn.add_edge("A".to_string(), "B".to_string()).is_ok());
1031        assert!(bn.add_edge("A".to_string(), "C".to_string()).is_ok());
1032        assert!(bn.add_edge("B".to_string(), "D".to_string()).is_ok());
1033        assert!(bn.add_edge("C".to_string(), "D".to_string()).is_ok());
1034        assert_eq!(bn.edges.len(), 4);
1035    }
1036
1037    #[test]
1038    fn test_bn_add_edge_nonexistent_from() {
1039        let mut bn = BayesianNetwork::new();
1040        bn.add_variable("B".to_string(), vec!["T".to_string(), "F".to_string()]);
1041        assert!(bn.add_edge("Ghost".to_string(), "B".to_string()).is_err());
1042    }
1043
1044    #[test]
1045    fn test_bn_add_edge_nonexistent_to() {
1046        let mut bn = BayesianNetwork::new();
1047        bn.add_variable("A".to_string(), vec!["T".to_string(), "F".to_string()]);
1048        assert!(bn.add_edge("A".to_string(), "Ghost".to_string()).is_err());
1049    }
1050
1051    #[test]
1052    fn test_bn_prior_invalid_sum() {
1053        let mut bn = BayesianNetwork::new();
1054        bn.add_variable("X".to_string(), vec!["a".to_string(), "b".to_string()]);
1055        assert!(
1056            bn.set_prior("X".to_string(), vec![0.3, 0.8]).is_err(),
1057            "Prob sum > 1 should fail"
1058        );
1059    }
1060
1061    #[test]
1062    fn test_bn_prior_valid() {
1063        let mut bn = BayesianNetwork::new();
1064        bn.add_variable("X".to_string(), vec!["a".to_string(), "b".to_string()]);
1065        assert!(bn.set_prior("X".to_string(), vec![0.3, 0.7]).is_ok());
1066    }
1067
1068    #[test]
1069    fn test_bn_prior_unknown_variable() {
1070        let mut bn = BayesianNetwork::new();
1071        assert!(
1072            bn.set_prior("Ghost".to_string(), vec![0.5, 0.5]).is_err(),
1073            "Unknown variable should fail"
1074        );
1075    }
1076
1077    #[test]
1078    fn test_bn_topological_sort_single_node() -> Result<(), Box<dyn std::error::Error>> {
1079        let mut bn = BayesianNetwork::new();
1080        bn.add_variable("Alone".to_string(), vec!["T".to_string(), "F".to_string()]);
1081        let topo = bn.topological_sort()?;
1082        assert_eq!(topo.len(), 1);
1083        assert_eq!(topo[0], "Alone");
1084        Ok(())
1085    }
1086
1087    #[test]
1088    fn test_bn_topological_sort_no_edges() -> Result<(), Box<dyn std::error::Error>> {
1089        let mut bn = BayesianNetwork::new();
1090        bn.add_variable("P".to_string(), vec!["T".to_string(), "F".to_string()]);
1091        bn.add_variable("Q".to_string(), vec!["T".to_string(), "F".to_string()]);
1092        bn.add_variable("R".to_string(), vec!["T".to_string(), "F".to_string()]);
1093        let topo = bn.topological_sort()?;
1094        assert_eq!(topo.len(), 3);
1095        Ok(())
1096    }
1097
1098    #[test]
1099    fn test_bn_query_returns_probability() -> Result<(), Box<dyn std::error::Error>> {
1100        let mut bn = BayesianNetwork::new();
1101        bn.add_variable("Rain".to_string(), vec!["T".to_string(), "F".to_string()]);
1102        bn.set_prior("Rain".to_string(), vec![0.3, 0.7])?;
1103        let result = bn.query("Rain".to_string(), "T".to_string(), &[]);
1104        assert!(result.is_ok(), "query should succeed");
1105        let prob = result?;
1106        assert!(
1107            (0.0..=1.0).contains(&prob),
1108            "probability should be in [0,1]"
1109        );
1110        Ok(())
1111    }
1112
1113    #[test]
1114    fn test_mln_new_is_empty() {
1115        let mln = MarkovLogicNetwork::new();
1116        assert_eq!(mln.weighted_rules.len(), 0);
1117    }
1118
1119    #[test]
1120    fn test_mln_add_multiple_rules() {
1121        let mut mln = MarkovLogicNetwork::new();
1122        for i in 0..5usize {
1123            let rule = Rule {
1124                name: format!("rule_{}", i),
1125                body: vec![RuleAtom::Triple {
1126                    subject: Term::Variable("X".to_string()),
1127                    predicate: Term::Constant(format!("p{}", i)),
1128                    object: Term::Variable("Y".to_string()),
1129                }],
1130                head: vec![RuleAtom::Triple {
1131                    subject: Term::Variable("X".to_string()),
1132                    predicate: Term::Constant(format!("q{}", i)),
1133                    object: Term::Variable("Y".to_string()),
1134                }],
1135            };
1136            mln.add_weighted_rule(rule, 1.0 + i as f64);
1137        }
1138        assert_eq!(mln.weighted_rules.len(), 5);
1139    }
1140
1141    #[test]
1142    fn test_prob_engine_new_is_empty() {
1143        let engine = ProbabilisticRuleEngine::new();
1144        assert_eq!(engine.weighted_rules.len(), 0);
1145    }
1146
1147    #[test]
1148    fn test_prob_engine_with_no_rules_empty_facts() -> Result<(), Box<dyn std::error::Error>> {
1149        let engine = ProbabilisticRuleEngine::new();
1150        let result = engine.probabilistic_forward_chain(&[])?;
1151        assert!(
1152            result.is_empty(),
1153            "No rules and empty facts => empty result"
1154        );
1155        Ok(())
1156    }
1157
1158    #[test]
1159    fn test_prob_engine_confidence_in_range() -> Result<(), Box<dyn std::error::Error>> {
1160        let mut engine = ProbabilisticRuleEngine::new();
1161        let rule = Rule {
1162            name: "range_test".to_string(),
1163            body: vec![RuleAtom::Triple {
1164                subject: Term::Variable("X".to_string()),
1165                predicate: Term::Constant("likes".to_string()),
1166                object: Term::Variable("Y".to_string()),
1167            }],
1168            head: vec![RuleAtom::Triple {
1169                subject: Term::Variable("X".to_string()),
1170                predicate: Term::Constant("enjoysCompanyOf".to_string()),
1171                object: Term::Variable("Y".to_string()),
1172            }],
1173        };
1174        engine.add_weighted_rule(rule, 0.9);
1175        let facts = vec![RuleAtom::Triple {
1176            subject: Term::Constant("alice".to_string()),
1177            predicate: Term::Constant("likes".to_string()),
1178            object: Term::Constant("bob".to_string()),
1179        }];
1180        let result = engine.probabilistic_forward_chain(&facts)?;
1181        for (_, confidence) in &result {
1182            assert!(
1183                *confidence >= 0.0 && *confidence <= 1.0,
1184                "confidence out of range: {}",
1185                confidence
1186            );
1187        }
1188        Ok(())
1189    }
1190
1191    #[test]
1192    fn test_prob_engine_multiple_facts_has_results() -> Result<(), Box<dyn std::error::Error>> {
1193        let mut engine = ProbabilisticRuleEngine::new();
1194        let rule = Rule {
1195            name: "multi".to_string(),
1196            body: vec![RuleAtom::Triple {
1197                subject: Term::Variable("X".to_string()),
1198                predicate: Term::Constant("input".to_string()),
1199                object: Term::Variable("Y".to_string()),
1200            }],
1201            head: vec![RuleAtom::Triple {
1202                subject: Term::Variable("X".to_string()),
1203                predicate: Term::Constant("output".to_string()),
1204                object: Term::Variable("Y".to_string()),
1205            }],
1206        };
1207        engine.add_weighted_rule(rule, 1.5);
1208        let facts = vec![
1209            RuleAtom::Triple {
1210                subject: Term::Constant("a".to_string()),
1211                predicate: Term::Constant("input".to_string()),
1212                object: Term::Constant("b".to_string()),
1213            },
1214            RuleAtom::Triple {
1215                subject: Term::Constant("c".to_string()),
1216                predicate: Term::Constant("input".to_string()),
1217                object: Term::Constant("d".to_string()),
1218            },
1219        ];
1220        let result = engine.probabilistic_forward_chain(&facts)?;
1221        // Should get at least one result (rule application)
1222        assert!(
1223            !result.is_empty(),
1224            "Should get at least one result from rule application"
1225        );
1226        Ok(())
1227    }
1228
1229    #[test]
1230    fn test_prob_engine_add_weighted_rule_increments_count() {
1231        let mut engine = ProbabilisticRuleEngine::new();
1232        assert_eq!(engine.weighted_rules.len(), 0);
1233        let rule = Rule {
1234            name: "r1".to_string(),
1235            body: vec![],
1236            head: vec![],
1237        };
1238        engine.add_weighted_rule(rule, 0.5);
1239        assert_eq!(engine.weighted_rules.len(), 1);
1240    }
1241
1242    #[test]
1243    fn test_bn_variable_domain_stored() {
1244        let mut bn = BayesianNetwork::new();
1245        let domain = vec!["low".to_string(), "medium".to_string(), "high".to_string()];
1246        bn.add_variable("Risk".to_string(), domain.clone());
1247        assert!(bn.variables.contains_key("Risk"));
1248        let var = &bn.variables["Risk"];
1249        assert_eq!(var.domain, domain);
1250    }
1251
1252    #[test]
1253    fn test_bn_prior_zero_prob_valid() {
1254        let mut bn = BayesianNetwork::new();
1255        bn.add_variable("X".to_string(), vec!["T".to_string(), "F".to_string()]);
1256        // P(T)=0, P(F)=1 — valid distribution
1257        assert!(bn.set_prior("X".to_string(), vec![0.0, 1.0]).is_ok());
1258    }
1259}