Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Enhance reasoning module with variable unification and add comprehensive tests
KaifAhmad1971b42631ef4
diff --git a/semantica/reasoning/abductive_reasoner.py b/semantica/reasoning/abductive_reasoner.pyindex 942a1b52..cabc4dbb 100644--- a/semantica/reasoning/abductive_reasoner.py+++ b/semantica/reasoning/abductive_reasoner.py@@ -34,6 +34,7 @@ License: MITfrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Dict, List, Optional+import refrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger@@ -203,9 +204,58 @@ class AbductiveReasoner:def _rule_explains_observation(self, rule: Rule, observation: Observation) -> bool:"""Check if rule can explain observation."""- # Simple check: rule conclusion matches observation- # Can be enhanced with more sophisticated matching- return True+ # Check if rule conclusion matches observation description+ # Try exact match first+ if rule.conclusion == observation.description:+ return True++ # Try unification if variables are involved+ if "?" in rule.conclusion:+ bindings = self._unify(rule.conclusion, observation.description, {})+ if bindings is not None:+ return True++ return False++ def _parse_predicate(self, text: str) -> tuple[str, List[str]]:+ """Parse 'Predicate(arg1, arg2)' into ('Predicate', ['arg1', 'arg2'])."""+ if not isinstance(text, str):+ return text, []+ match = re.match(r"(\w+)\((.+)\)", text)+ if not match:+ return text, []+ predicate = match.group(1)+ args = [arg.strip() for arg in match.group(2).split(",")]+ return predicate, args++ def _unify(self, condition: str, fact: str, bindings: Dict[str, str]) -> Optional[Dict[str, str]]:+ """+ Try to unify a condition (with vars) against a fact.+ Returns new bindings if successful, None otherwise.+ """+ if condition == fact:+ return bindings++ cond_pred, cond_args = self._parse_predicate(condition)+ fact_pred, fact_args = self._parse_predicate(fact)++ if cond_pred != fact_pred:+ return None+ if len(cond_args) != len(fact_args):+ return None++ new_bindings = bindings.copy()+ for c_arg, f_arg in zip(cond_args, fact_args):+ if c_arg.startswith("?"):+ if c_arg in new_bindings:+ if new_bindings[c_arg] != f_arg:+ return None # Conflict+ else:+ new_bindings[c_arg] = f_arg+ else:+ if c_arg != f_arg:+ return None # Constant mismatch+ return new_bindingsdef _calculate_coverage(self, rule: Rule, observation: Observation) -> float:"""Calculate how well rule covers observation."""diff --git a/semantica/reasoning/deductive_reasoner.py b/semantica/reasoning/deductive_reasoner.pyindex eb96ff95..c89de59c 100644--- a/semantica/reasoning/deductive_reasoner.py+++ b/semantica/reasoning/deductive_reasoner.py@@ -32,6 +32,7 @@ License: MITfrom dataclasses import dataclass, fieldfrom typing import Any, Dict, List, Optional, Set+import refrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger@@ -148,12 +149,16 @@ class DeductiveReasoner:rules = self.rule_manager.get_all_rules()for rule in rules:- # Check if rule can be applied- if self._can_apply_rule(rule, premises):- conclusion = self._apply_rule_to_premises(rule, premises)+ # Find all matches (bindings) for the rule+ matches = self._find_matches(rule.conditions, {})++ for bindings in matches:+ conclusion = self._apply_rule_to_premises(rule, premises, bindings)if conclusion:- conclusions.append(conclusion)- self.known_facts.add(conclusion.statement)+ # Check if conclusion is new (not in known facts)+ if conclusion.statement not in self.known_facts:+ conclusions.append(conclusion)+ self.known_facts.add(conclusion.statement)self.progress_tracker.stop_tracking(tracking_id,@@ -168,39 +173,127 @@ class DeductiveReasoner:)raise- def _can_apply_rule(self, rule: Rule, premises: List[Premise]) -> bool:- """Check if rule can be applied to premises."""- # Check if all rule conditions match premises- premise_statements = {p.statement for p in premises}-- for condition in rule.conditions:- if (- condition not in premise_statements- and condition not in self.known_facts- ):- return False+ def _parse_predicate(self, text: str) -> tuple[str, List[str]]:+ """Parse 'Predicate(arg1, arg2)' into ('Predicate', ['arg1', 'arg2'])."""+ if not isinstance(text, str):+ return text, []+ match = re.match(r"(\w+)\((.+)\)", text)+ if not match:+ return text, []+ predicate = match.group(1)+ args = [arg.strip() for arg in match.group(2).split(",")]+ return predicate, args++ def _unify(self, condition: str, fact: str, bindings: Dict[str, str]) -> Optional[Dict[str, str]]:+ """+ Try to unify a condition (with vars) against a fact.+ Returns new bindings if successful, None otherwise.+ """+ if condition == fact:+ return bindings++ cond_pred, cond_args = self._parse_predicate(condition)+ fact_pred, fact_args = self._parse_predicate(fact)++ if cond_pred != fact_pred:+ return None+ if len(cond_args) != len(fact_args):+ return None++ new_bindings = bindings.copy()+ for c_arg, f_arg in zip(cond_args, fact_args):+ if c_arg.startswith("?"):+ if c_arg in new_bindings:+ if new_bindings[c_arg] != f_arg:+ return None # Conflict+ else:+ new_bindings[c_arg] = f_arg+ else:+ if c_arg != f_arg:+ return None # Constant mismatch+ return new_bindings++ def _substitute_bindings(self, text: str, bindings: Dict[str, str]) -> str:+ """Substitute variables in text with bindings."""+ if not isinstance(text, str):+ return text+ pred, args = self._parse_predicate(text)+ if not args:+ return text++ new_args = []+ for arg in args:+ if arg in bindings:+ new_args.append(bindings[arg])+ else:+ new_args.append(arg)++ return f"{pred}({', '.join(new_args)})"- return True+ def _find_matches(self, conditions: List[str], bindings: Dict[str, str]) -> List[Dict[str, str]]:+ """+ Recursively find all bindings that satisfy the conditions.+ """+ if not conditions:+ return [bindings]++ first = conditions[0]+ # Substitute current bindings into first condition before matching+ first_substituted = self._substitute_bindings(first, bindings)+ rest = conditions[1:]++ valid_bindings = []++ # Try to match 'first' against all known facts+ for fact in self.known_facts:+ # Skip if fact is not a string (unhashable/objects) for now+ if not isinstance(fact, str):+ continue++ unified = self._unify(first_substituted, fact, bindings)+ if unified is not None:+ # Recursive step+ results = self._find_matches(rest, unified)+ valid_bindings.extend(results)++ return valid_bindingsdef _apply_rule_to_premises(- self, rule: Rule, premises: List[Premise]+ self, rule: Rule, premises: List[Premise], bindings: Dict[str, str]) -> Optional[Conclusion]:"""Apply rule to premises and generate conclusion."""- # Find matching premises- matching_premises = [- p- for p in premises- if p.statement in rule.conditions or p.statement in self.known_facts- ]-+ # Find matching premises (those that support the bindings)+ # This is a bit approximate, ideally we track which premise supported which condition+ matching_premises = []++ # Instantiate conclusion+ conclusion_stmt = rule.conclusion+ if bindings:+ conclusion_stmt = self._substitute_bindings(conclusion_stmt, bindings)++ # Find premises that match the conditions (instantiated)+ for cond in rule.conditions:+ instantiated = self._substitute_bindings(cond, bindings)+ for p in premises:+ if p.statement == instantiated:+ matching_premises.append(p)+ break+ # Note: some conditions might be matched by self.known_facts which are not in 'premises' arg+ # but are in self.known_facts.+ # If a premise is not in the passed list but in known_facts, we can't add it to matching_premises list+ # unless we find the Premise object.+ # But known_facts stores strings.+ # So matching_premises might be incomplete if we rely on known_facts.+ # However, for this method signature, we return a Conclusion with premises.+conclusion = Conclusion(- conclusion_id=f"conc_{len(matching_premises)}",- statement=rule.conclusion,+ conclusion_id=f"conc_{rule.name}_{len(matching_premises)}",+ statement=conclusion_stmt,premises=matching_premises,rule_applied=rule,confidence=rule.confidence,- proof_steps=[f"Applied rule: {rule.name}"],- metadata={"rule_id": rule.rule_id},+ proof_steps=[f"Applied rule: {rule.name} with bindings {bindings}"],+ metadata={"rule_id": rule.rule_id, "bindings": bindings},)return conclusion@@ -272,6 +365,7 @@ class DeductiveReasoner:return None# Check if goal is already known+ # Try direct matchif goal in self.known_facts:return Conclusion(conclusion_id=f"known_{goal}",@@ -279,35 +373,65 @@ class DeductiveReasoner:confidence=1.0,proof_steps=["Known fact"],)++ # Try unification with known facts+ if isinstance(goal, str) and "?" in goal:+ for fact in self.known_facts:+ if isinstance(fact, str):+ if self._unify(goal, fact, {}) is not None:+ return Conclusion(+ conclusion_id=f"known_{fact}",+ statement=fact,+ confidence=1.0,+ proof_steps=[f"Known fact (matched pattern {goal})"],+ )# Find rules that can prove goalrules = self.rule_manager.get_all_rules()- applicable_rules = [r for r in rules if r.conclusion == goal]-- for rule in applicable_rules:++ # Use unified matching for finding applicable rules+ applicable_rules_and_bindings = []+ for r in rules:+ bindings = self._unify(r.conclusion, goal, {})+ if bindings is not None:+ applicable_rules_and_bindings.append((r, bindings))++ for rule, initial_bindings in applicable_rules_and_bindings:# Try to prove all premisespremise_conclusions = []all_proven = True+ current_bindings = initial_bindings.copy()for condition in rule.conditions:+ # Instantiate condition with current bindings+ instantiated_cond = self._substitute_bindings(condition, current_bindings)+premise_conclusion = self._prove_backward(- condition, proof, depth + 1, max_depth, **options+ instantiated_cond, proof, depth + 1, max_depth, **options)if premise_conclusion:premise_conclusions.append(premise_conclusion)+ # Update bindings if we proved something more specific+ new_bindings = self._unify(instantiated_cond, premise_conclusion.statement, current_bindings)+ if new_bindings:+ current_bindings = new_bindingselse:all_proven = Falsebreakif all_proven:# All premises proven, rule can fire+ # Instantiate conclusion with final bindings+ final_conclusion = self._substitute_bindings(rule.conclusion, current_bindings)+conclusion = Conclusion(conclusion_id=f"conc_{goal}",- statement=goal,- premises=[Premise(p, p) for p in rule.conditions],+ statement=final_conclusion,+ premises=[p for p in premise_conclusions], # Use actual premises foundrule_applied=rule,confidence=rule.confidence,- proof_steps=[f"Proved using rule: {rule.name}"],+ proof_steps=[f"Proved using rule: {rule.name} with bindings {current_bindings}"],+ metadata={"rule_id": rule.rule_id, "bindings": current_bindings})return conclusiondiff --git a/semantica/reasoning/inference_engine.py b/semantica/reasoning/inference_engine.pyindex 17a352dc..588caeee 100644--- a/semantica/reasoning/inference_engine.py+++ b/semantica/reasoning/inference_engine.py@@ -29,6 +29,7 @@ Author: Semantica ContributorsLicense: MIT"""+import refrom dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Any, Callable, Dict, List, Optional, Set@@ -194,10 +195,12 @@ class InferenceEngine:)for rule in rules:- # Check if rule can fire- if self._can_rule_fire(rule):- # Apply rule- result = self._apply_rule(rule)+ # Find all matches for the rule+ matches = self._find_matches(rule.conditions, {})++ for bindings in matches:+ # Apply rule with bindings+ result = self._apply_rule(rule, bindings=bindings)if result:# Only consider it a new inference if the fact wasn't already knownif self.add_fact(result.conclusion):@@ -244,47 +247,83 @@ class InferenceEngine:tracking_id, message="Checking if goal is already a fact...")- is_fact = False+ # Check for direct match or unification with facts+ found_fact = None++ # First try direct match (fastest)try:if goal in self.facts:- is_fact = True+ found_fact = goalexcept TypeError:if goal in self.unhashable_facts:- is_fact = True-- if is_fact:+ found_fact = goal++ # If not found and goal looks like a pattern (string with ?), try unification+ if found_fact is None and isinstance(goal, str) and "?" in goal:+ for fact in self.facts:+ if isinstance(fact, str):+ # Try to unify to see if it matches+ if self._unify(goal, fact, {}) is not None:+ found_fact = fact+ break++ if found_fact:self.progress_tracker.stop_tracking(- tracking_id, status="completed", message="Goal is already a fact"+ tracking_id, status="completed", message=f"Goal proven by fact: {found_fact}")- return InferenceResult(conclusion=goal, confidence=1.0)+ return InferenceResult(conclusion=found_fact, confidence=1.0)# Find rules that can prove the goalself.progress_tracker.update_tracking(tracking_id, message="Finding rules that can prove the goal...")rules = self.rule_manager.get_all_rules()- applicable_rules = [r for r in rules if self._rule_concludes(r, goal)]++ # Use unified matching for finding applicable rules+ applicable_rules_and_bindings = []+ for r in rules:+ bindings = self._unify(r.conclusion, goal, {})+ if bindings is not None:+ applicable_rules_and_bindings.append((r, bindings))self.progress_tracker.update_tracking(tracking_id,- message=f"Found {len(applicable_rules)} applicable rules, trying to prove premises...",+ message=f"Found {len(applicable_rules_and_bindings)} applicable rules, trying to prove premises...",)- for rule in applicable_rules:- # Try to prove premises- premises = []++ for rule, initial_bindings in applicable_rules_and_bindings:+ # Try to prove premises with bindings, propagating bindings between premises+ current_bindings = initial_bindings.copy()+ premises_results = []all_premises_proven = True-- for premise in rule.conditions:- premise_result = self.backward_chain(premise, **options)++ for cond in rule.conditions:+ # Instantiate condition with current bindings+ instantiated_cond = self._substitute_bindings(cond, current_bindings)++ # Recursively prove this condition+ premise_result = self.backward_chain(instantiated_cond, **options)+if premise_result:- premises.append(premise_result.conclusion)+ premises_results.append(premise_result.conclusion)++ # If the premise had variables, update bindings based on the proven fact+ # We unify the instantiated condition (which might still have vars) with the proven conclusion+ new_bindings = self._unify(instantiated_cond, premise_result.conclusion, current_bindings)+ if new_bindings is not None:+ current_bindings = new_bindings+ else:+ # This implies a conflict, which shouldn't happen if backward_chain returned success+ # on instantiated_cond, but good to be safe+ all_premises_proven = False+ breakelse:all_premises_proven = Falsebreakif all_premises_proven:# All premises proven, rule can fire- result = self._apply_rule(rule, premises)+ result = self._apply_rule(rule, premises=premises_results, bindings=current_bindings)if result:self.progress_tracker.stop_tracking(tracking_id,@@ -304,38 +343,115 @@ class InferenceEngine:)raise- def _can_rule_fire(self, rule: Rule) -> bool:- """Check if rule can fire (all conditions met)."""- for condition in rule.conditions:- try:- if condition not in self.facts:- return False- except TypeError:- if condition not in self.unhashable_facts:- return False- return True-- def _rule_concludes(self, rule: Rule, goal: Any) -> bool:- """Check if rule concludes the goal."""- return rule.conclusion == goal+ def _parse_predicate(self, text: str) -> tuple[str, List[str]]:+ """Parse 'Predicate(arg1, arg2)' into ('Predicate', ['arg1', 'arg2'])."""+ if not isinstance(text, str):+ return text, []+ match = re.match(r"(\w+)\((.+)\)", text)+ if not match:+ return text, []+ predicate = match.group(1)+ args = [arg.strip() for arg in match.group(2).split(",")]+ return predicate, args++ def _unify(self, condition: str, fact: str, bindings: Dict[str, str]) -> Optional[Dict[str, str]]:+ """+ Try to unify a condition (with vars) against a fact.+ Returns new bindings if successful, None otherwise.+ """+ # Handle exact string match shortcut+ if condition == fact:+ return bindings++ cond_pred, cond_args = self._parse_predicate(condition)+ fact_pred, fact_args = self._parse_predicate(fact)++ if cond_pred != fact_pred:+ return None+ if len(cond_args) != len(fact_args):+ return None++ new_bindings = bindings.copy()+ for c_arg, f_arg in zip(cond_args, fact_args):+ if c_arg.startswith("?"):+ if c_arg in new_bindings:+ if new_bindings[c_arg] != f_arg:+ return None # Conflict+ else:+ new_bindings[c_arg] = f_arg+ else:+ if c_arg != f_arg:+ return None # Constant mismatch+ return new_bindings++ def _find_matches(self, conditions: List[str], bindings: Dict[str, str]) -> List[Dict[str, str]]:+ """+ Recursively find all bindings that satisfy the conditions.+ """+ if not conditions:+ return [bindings]++ first = conditions[0]+ # Substitute current bindings into first condition before matching+ first_substituted = self._substitute_bindings(first, bindings)+ rest = conditions[1:]++ valid_bindings = []++ # Try to match 'first' against all facts+ for fact in self.facts:+ # Skip if fact is not a string (unhashable/objects) for now, or handle str()+ if not isinstance(fact, str):+ continue++ unified = self._unify(first_substituted, fact, bindings)+ if unified is not None:+ # Recursive step+ results = self._find_matches(rest, unified)+ valid_bindings.extend(results)++ return valid_bindings++ def _substitute_bindings(self, text: str, bindings: Dict[str, str]) -> str:+ """Substitute variables in text with bindings."""+ if not isinstance(text, str):+ return text+ pred, args = self._parse_predicate(text)+ if not args:+ return text++ new_args = []+ for arg in args:+ if arg in bindings:+ new_args.append(bindings[arg])+ else:+ new_args.append(arg)++ return f"{pred}({', '.join(new_args)})"def _apply_rule(- self, rule: Rule, premises: Optional[List[Any]] = None+ self, rule: Rule, premises: Optional[List[Any]] = None, bindings: Optional[Dict[str, str]] = None) -> Optional[InferenceResult]:"""Apply rule and return inference result."""+ conclusion = rule.conclusion+ if bindings:+ conclusion = self._substitute_bindings(conclusion, bindings)+if premises is None:- premises = list(rule.conditions)+ # Reconstruct premises from bindings if not provided (approximate)+ premises = [self._substitute_bindings(c, bindings or {}) for c in rule.conditions]result = InferenceResult(- conclusion=rule.conclusion,+ conclusion=conclusion,premises=premises,rule_used=rule,confidence=rule.confidence,- metadata={"rule_name": rule.name, "rule_id": rule.rule_id},+ metadata={"rule_name": rule.name, "rule_id": rule.rule_id, "bindings": bindings},)return result+def infer(self, query: Any, **options) -> List[InferenceResult]:"""Perform inference based on strategy.diff --git a/tests/test_reasoning_extended.py b/tests/test_reasoning_extended.pynew file mode 100644index 00000000..459c5829--- /dev/null+++ b/tests/test_reasoning_extended.py@@ -0,0 +1,152 @@+import pytest+from semantica.reasoning import (+ DeductiveReasoner,+ AbductiveReasoner,+ Premise,+ Observation,+ HypothesisRanking,+ Argument+)++# --- DeductiveReasoner Tests ---++def deductive_reasoner():+ return DeductiveReasoner()++def test_deductive_apply_logic(deductive_reasoner):+ # Rule: IF Human(?x) THEN Mortal(?x)+ rule = deductive_reasoner.rule_manager.define_rule("IF Human(?x) THEN Mortal(?x)")+ deductive_reasoner.rule_manager.add_rule(rule)++ premises = [Premise("p1", "Human(Socrates)")]++ # We need to ensure the reasoner can handle variable matching or at least exact matching+ # Based on my reading of DeductiveReasoner, it uses _can_apply_rule which checks strict containment+ # if variables aren't handled.+ # Let's check if DeductiveReasoner uses InferenceEngine's unification or its own simple logic.+ # It uses self._can_apply_rule which does: condition in premise_statements.+ # This implies EXACT string match unless updated.++ # So for now, let's test exact match to verify baseline behavior+ deductive_reasoner.rule_manager.clear_rules()+ rule = deductive_reasoner.rule_manager.define_rule("IF Human(Socrates) THEN Mortal(Socrates)")+ deductive_reasoner.rule_manager.add_rule(rule)++ conclusions = deductive_reasoner.apply_logic(premises)++ assert len(conclusions) >= 1+ assert conclusions[0].statement == "Mortal(Socrates)"++def test_deductive_apply_logic_with_variables(deductive_reasoner):+ # This test checks if DeductiveReasoner supports variables like InferenceEngine+ rule = deductive_reasoner.rule_manager.define_rule("IF Human(?x) THEN Mortal(?x)")+ deductive_reasoner.rule_manager.add_rule(rule)++ premises = [Premise("p1", "Human(Plato)")]++ # If DeductiveReasoner supports variables, it should deduce Mortal(Plato)+ conclusions = deductive_reasoner.apply_logic(premises)++ assert len(conclusions) > 0+ assert conclusions[0].statement == "Mortal(Plato)"++def test_deductive_prove_theorem_with_variables(deductive_reasoner):+ # Rule: IF Parent(?a, ?b) THEN Ancestor(?a, ?b)+ rule = deductive_reasoner.rule_manager.define_rule("IF Parent(?a, ?b) THEN Ancestor(?a, ?b)")+ deductive_reasoner.rule_manager.add_rule(rule)+ deductive_reasoner.add_fact("Parent(Zeus, Ares)")++ # Prove Ancestor(Zeus, Ares)+ proof = deductive_reasoner.prove_theorem("Ancestor(Zeus, Ares)")++ assert proof is not None+ assert proof.valid is True+ assert proof.steps[-1].statement == "Ancestor(Zeus, Ares)"++def test_deductive_prove_theorem(deductive_reasoner):+ # Rule: IF P THEN Q+ rule = deductive_reasoner.rule_manager.define_rule("IF P THEN Q")+ deductive_reasoner.rule_manager.add_rule(rule)+ deductive_reasoner.add_fact("P")++ proof = deductive_reasoner.prove_theorem("Q")++ assert proof is not None+ assert proof.valid is True+ assert len(proof.steps) > 0+ assert proof.steps[-1].statement == "Q"++def test_deductive_validate_argument(deductive_reasoner):+ rule = deductive_reasoner.rule_manager.define_rule("IF Rain THEN Wet")+ deductive_reasoner.rule_manager.add_rule(rule)+ deductive_reasoner.add_fact("Rain")++ premises = [Premise("p1", "Rain")]+ # Note: Conclusion object needed for argument? Argument class has 'conclusion' field which is Conclusion type.+ # But usually we validate if premises lead to a conclusion statement.+ # The validate_argument method checks if argument.conclusion.statement follows.++ from semantica.reasoning.deductive_reasoner import Conclusion+ conc = Conclusion("c1", "Wet")++ arg = Argument("arg1", premises=premises, conclusion=conc)++ result = deductive_reasoner.validate_argument(arg)++ assert result["valid"] is True++# --- AbductiveReasoner Tests ---++def abductive_reasoner():+ return AbductiveReasoner()++def test_abductive_generate_hypotheses(abductive_reasoner):+ # Setup a rule that could explain an observation+ # Rule: IF Rain THEN WetGrass+ rule = abductive_reasoner.rule_manager.define_rule("IF Rain THEN WetGrass")+ abductive_reasoner.rule_manager.add_rule(rule)++ obs = Observation("o1", "WetGrass")++ # Current implementation of _rule_explains_observation returns True for everything+ # So it should find the rule as a hypothesis+ hypotheses = abductive_reasoner.generate_hypotheses([obs])++ assert len(hypotheses) > 0+ assert "Rain" in hypotheses[0].premises # The premise of the rule is the hypothesis (Rain caused WetGrass)++def test_abductive_filtering(abductive_reasoner):+ # Rule 1: IF Rain THEN WetGrass+ r1 = abductive_reasoner.rule_manager.define_rule("IF Rain THEN WetGrass")+ abductive_reasoner.rule_manager.add_rule(r1)++ # Rule 2: IF Fire THEN Smoke+ r2 = abductive_reasoner.rule_manager.define_rule("IF Fire THEN Smoke")+ abductive_reasoner.rule_manager.add_rule(r2)++ obs = Observation("o1", "WetGrass")++ hypotheses = abductive_reasoner.generate_hypotheses([obs])++ # Should only find hypothesis related to WetGrass (Rain)+ # Should NOT find hypothesis related to Smoke (Fire)++ relevant_hypotheses = [h for h in hypotheses if "Rain" in h.premises or "IF Rain" in h.explanation]+ irrelevant_hypotheses = [h for h in hypotheses if "Fire" in h.premises or "IF Fire" in h.explanation]++ assert len(relevant_hypotheses) > 0+ assert len(irrelevant_hypotheses) == 0++def test_abductive_find_explanations(abductive_reasoner):+ rule = abductive_reasoner.rule_manager.define_rule("IF Fire THEN Smoke")+ abductive_reasoner.rule_manager.add_rule(rule)+ obs = Observation("o1", "Smoke")++ explanations = abductive_reasoner.find_explanations([obs])++ assert len(explanations) == 1+ assert explanations[0].best_hypothesis is not None+ assert "Fire" in explanations[0].best_hypothesis.premises+diff --git a/tests/test_reasoning_inference.py b/tests/test_reasoning_inference.pynew file mode 100644index 00000000..9f2b27f6--- /dev/null+++ b/tests/test_reasoning_inference.py@@ -0,0 +1,154 @@+import pytest+from unittest.mock import MagicMock, patch+from semantica.reasoning import (+ InferenceEngine,+ RuleManager,+ ExplanationGenerator,+ InferenceResult,+ Rule,+ RuleType+)++# --- Fixtures ---++def inference_engine():+ return InferenceEngine()++def rule_manager():+ return RuleManager()++def explanation_generator():+ return ExplanationGenerator()++# --- Test Rule Parsing (RuleManager) ---++def test_rule_parsing_simple(rule_manager):+ rule_def = "IF Person(?x) THEN Human(?x)"+ rule = rule_manager.define_rule(rule_def, name="HumanRule")++ assert rule.name == "HumanRule"+ assert rule.rule_type == RuleType.IMPLICATION+ assert len(rule.conditions) == 1+ assert rule.conditions[0] == "Person(?x)"+ assert rule.conclusion == "Human(?x)"++def test_rule_parsing_multiple_conditions(rule_manager):+ rule_def = "IF Parent(?x, ?y) AND Parent(?y, ?z) THEN Grandparent(?x, ?z)"+ rule = rule_manager.define_rule(rule_def)++ assert len(rule.conditions) == 2+ assert rule.conditions[0] == "Parent(?x, ?y)"+ assert rule.conditions[1] == "Parent(?y, ?z)"+ assert rule.conclusion == "Grandparent(?x, ?z)"++def test_rule_parsing_invalid(rule_manager):+ with pytest.raises(Exception):+ rule_manager.define_rule("INVALID RULE SYNTAX")++# --- Test InferenceEngine (Forward Chaining) ---++def test_forward_chaining_exact_match(inference_engine):+ # Rule: IF A THEN B+ inference_engine.add_rule("IF A THEN B")+ inference_engine.add_fact("A")++ results = inference_engine.forward_chain()++ assert len(results) >= 1+ inferred_facts = [res.conclusion for res in results]+ assert "B" in inferred_facts++def test_forward_chaining_simple(inference_engine):+ # Rule: IF Person(?x) THEN Human(?x)+ inference_engine.add_rule("IF Person(?x) THEN Human(?x)")++ # Fact: Person(Alice)+ inference_engine.add_fact("Person(Alice)")++ results = inference_engine.forward_chain()++ assert len(results) >= 1+ # Check if Human(Alice) is inferred+ inferred_facts = [res.conclusion for res in results]+ assert "Human(Alice)" in inferred_facts++def test_forward_chaining_transitive(inference_engine):+ # Rule: IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)+ inference_engine.add_rule("IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)")++ inference_engine.add_fact("Parent(Alice, Bob)")+ inference_engine.add_fact("Parent(Bob, Charlie)")++ results = inference_engine.forward_chain()++ inferred_facts = [res.conclusion for res in results]+ assert "Grandparent(Alice, Charlie)" in inferred_facts++def test_forward_chaining_no_match(inference_engine):+ inference_engine.add_rule("IF A(?x) THEN B(?x)")+ inference_engine.add_fact("C(Item)")++ results = inference_engine.forward_chain()+ assert len(results) == 0++# --- Test InferenceEngine (Backward Chaining) ---++def test_backward_chaining_success(inference_engine):+ # Rule: IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)+ inference_engine.add_rule("IF Parent(?a, ?b) AND Parent(?b, ?c) THEN Grandparent(?a, ?c)")++ inference_engine.add_fact("Parent(Alice, Bob)")+ inference_engine.add_fact("Parent(Bob, Charlie)")++ # Goal: Prove Grandparent(Alice, Charlie)+ proof = inference_engine.backward_chain("Grandparent(Alice, Charlie)")++ assert proof is not None+ # Depending on implementation, proof might be a boolean or a Proof object+ # The notebook says: if proof: print(...)+ assert bool(proof) is True++def test_backward_chaining_failure(inference_engine):+ inference_engine.add_rule("IF A(?x) THEN B(?x)")+ inference_engine.add_fact("A(1)")++ proof = inference_engine.backward_chain("B(2)")+ assert not proof++# --- Test ExplanationGenerator ---++def test_explanation_generation(explanation_generator):+ # Create a dummy InferenceResult+ rule = Rule("r1", "test_rule", ["A(?x)"], "B(?x)")+ result = InferenceResult(+ conclusion="B(1)",+ premises=["A(1)"],+ rule_used=rule,+ confidence=1.0+ )++ explanation = explanation_generator.generate_explanation(result)++ assert explanation is not None+ assert explanation.conclusion == "B(1)"+ # Check if natural language explanation is generated+ assert isinstance(explanation.natural_language, str)+ assert "B(1)" in explanation.natural_language+ assert "test_rule" in explanation.natural_language or "r1" in explanation.natural_language++# --- Test Edge Cases ---++def test_duplicate_facts(inference_engine):+ assert inference_engine.add_fact("A(1)") is True+ assert inference_engine.add_fact("A(1)") is False # Duplicate+ assert len(inference_engine.facts) == 1++def test_max_iterations(inference_engine):+ # Create a rule that generates infinite facts if not controlled+ # e.g., IF Num(?x) THEN Num(?x+1) - hard to simulate with string matching without eval+ # Instead, let's just test config setting+ engine = InferenceEngine(max_iterations=5)+ assert engine.max_iterations == 5