| |
| """ |
| Pattern-based baseline prover using backward chaining heuristics. |
| Works with Peano's PyProofState and action system. |
| """ |
|
|
| import re |
| import json |
| import os |
| from typing import Optional, List |
| from dataclasses import dataclass |
|
|
| import peano |
| from proofsearch import ProofSearchResult, TreeSearchNode, HolophrasmNode |
| from action import ProofAction |
|
|
|
|
| @dataclass |
| class PatternProverConfig: |
| """Configuration for pattern-based prover.""" |
| max_depth: int = 30 |
| max_iterations: int = 5000 |
| verbose: bool = False |
| log_file: Optional[str] = None |
|
|
|
|
| class PatternProver: |
| """ |
| Pattern-based baseline prover using backward chaining heuristics. |
| Works with Peano's PyProofState and action system. |
| """ |
| |
| def __init__(self, config: PatternProverConfig = None): |
| self.config = config or PatternProverConfig() |
| self._iterations = 0 |
| self._log_entries = [] |
| self._current_problem = None |
| self._solution_path = [] |
| |
| def proof_search(self, problem: str, state: peano.PyProofState): |
| """ |
| Pattern-based proof search. |
| |
| Args: |
| problem: Problem name (unused, for interface compatibility) |
| state: Initial Peano proof state |
| |
| Returns: |
| ProofSearchResult compatible with ProofSearchAgent |
| """ |
| self._iterations = 0 |
| self._log_entries = [] |
| self._current_problem = problem |
| |
| |
| initial_goal = state.format_goal() |
| self._log(f"Starting proof search for problem: {problem}") |
| self._log(f"Initial goal: {initial_goal}") |
| |
| root = TreeSearchNode(HolophrasmNode([state])) |
| |
| |
| solved = self._pattern_search(root) |
| |
| |
| if self.config.log_file: |
| self._write_log() |
| |
| |
| examples = [] |
| |
| return ProofSearchResult( |
| problem=problem, |
| success=solved, |
| root=root, |
| examples=examples, |
| iterations=self._iterations |
| ) |
| |
| def _log(self, message: str, goal: str = None, action: str = None): |
| """Log a message with optional goal and action.""" |
| entry = { |
| 'iteration': self._iterations, |
| 'message': message, |
| } |
| if goal: |
| entry['goal'] = goal |
| if action: |
| entry['action'] = str(action) |
| self._log_entries.append(entry) |
| |
| if self.config.verbose: |
| print(f"[{self._iterations}] {message}") |
| if goal: |
| print(f" Goal: {goal}") |
| if action: |
| print(f" Action: {action}") |
| |
| def _write_log(self): |
| """Write log entries to file.""" |
| log_data = { |
| 'problem': self._current_problem, |
| 'solved': len(self._log_entries) > 0 and 'Solution found' in self._log_entries[-1].get('message', ''), |
| 'iterations': self._iterations, |
| 'log_entries': self._log_entries |
| } |
| |
| |
| os.makedirs(os.path.dirname(self.config.log_file) if os.path.dirname(self.config.log_file) else '.', exist_ok=True) |
| with open(self.config.log_file, 'a') as f: |
| f.write(json.dumps(log_data) + '\n') |
| |
| |
| def _pattern_search(self, root: TreeSearchNode) -> bool: |
| """Recursive pattern-based search using DFS.""" |
| return self._pattern_search_recursive(root, depth=0) |
| |
| def _pattern_search_recursive(self, node: TreeSearchNode, depth: int) -> bool: |
| """Recursive DFS with pattern-based action selection.""" |
| if depth > self.config.max_depth: |
| return False |
| |
| if node.is_solved(): |
| self._log("Solution found!", goal=node.state_node.goal() if hasattr(node.state_node, 'goal') else None) |
| return True |
| |
| if node.is_dead(): |
| return False |
| |
| if self._iterations >= self.config.max_iterations: |
| self._log("Max iterations reached") |
| return False |
| |
| self._iterations += 1 |
| |
| |
| if node.state_node.is_conjunctive(): |
| return self._solve_conjunctive_node(node, depth) |
| |
| |
| if not hasattr(node.state_node, '_proof_states') or not node.state_node._proof_states: |
| return False |
| |
| state = node.state_node._proof_states[0] |
| goal_str = state.format_goal() |
| |
| |
| actions = node.state_node.actions |
| if not actions: |
| return False |
| |
| |
| prioritized_actions = self._prioritize_actions_by_pattern(state, goal_str, actions) |
| |
| |
| if node._children is None: |
| node._children = [] |
| |
| |
| for action in prioritized_actions: |
| try: |
| |
| self._log(f"Trying action (depth {depth})", goal=goal_str, action=str(action)) |
| |
| |
| expanded_state = node.state_node.expand(action) |
| |
| |
| child_node = TreeSearchNode(expanded_state, parent=(node, action)) |
| |
| |
| node._children.append(child_node) |
| |
| if self._pattern_search_recursive(child_node, depth + 1): |
| |
| node._solution_action = action |
| return True |
| except Exception as e: |
| self._log(f"Error expanding action: {e}", goal=goal_str, action=str(action)) |
| continue |
| |
| return False |
| |
| def _solve_conjunctive_node(self, node: TreeSearchNode, depth: int) -> bool: |
| """Solve a conjunctive node - all children must be solved.""" |
| |
| actions = node.state_node.actions |
| if not actions: |
| return False |
| |
| |
| if node._children is None: |
| node._children = [] |
| |
| |
| while len(node._children) < len(actions): |
| idx = len(node._children) |
| subgoal_state = node.state_node.expand(str(idx)) |
| child_node = TreeSearchNode(subgoal_state, parent=(node, str(idx))) |
| node._children.append(child_node) |
| |
| |
| for i, child_node in enumerate(node._children): |
| if not child_node.is_solved(): |
| if not self._pattern_search_recursive(child_node, depth + 1): |
| return False |
| |
| |
| |
| |
| return True |
| |
| def _prioritize_actions_by_pattern(self, state: peano.PyProofState, |
| goal_str: str, actions: List) -> List: |
| """ |
| Prioritize actions based on goal pattern. |
| Improved pattern matching including double negation detection. |
| |
| Returns: |
| List of actions in priority order (highest first) |
| """ |
| |
| if actions and isinstance(actions[0], str): |
| return actions |
| |
| goal_clean = goal_str.strip() |
| prioritized = [] |
| others = [] |
| |
| |
| def is_double_negation(s: str) -> bool: |
| |
| return s.startswith('(not (not ') and s.endswith('))') |
| |
| |
| def extract_from_double_negation(s: str) -> Optional[str]: |
| if is_double_negation(s): |
| |
| inner = s[10:-2] |
| return inner |
| return None |
| |
| |
| if is_double_negation(goal_clean): |
| inner = extract_from_double_negation(goal_clean) |
| |
| |
| for a in actions: |
| action_str = str(a) |
| |
| if hasattr(a, 'is_intro') and a.is_intro(): |
| prioritized.append(a) |
| |
| elif any(name in action_str for name in ['and_el', 'and_er', 'iff_el', 'iff_er']): |
| prioritized.append(a) |
| else: |
| others.append(a) |
| return prioritized + others |
| |
| |
| if goal_clean.startswith('[') and '->' in goal_clean: |
| for a in actions: |
| if hasattr(a, 'is_intro') and a.is_intro(): |
| prioritized.append(a) |
| else: |
| others.append(a) |
| return prioritized + others |
| |
| |
| if goal_clean.startswith('(and '): |
| for a in actions: |
| action_str = str(a) |
| if 'and_i' in action_str: |
| prioritized.append(a) |
| else: |
| others.append(a) |
| return prioritized + others |
| |
| |
| if goal_clean.startswith('(or '): |
| |
| or_il_actions = [] |
| or_ir_actions = [] |
| for a in actions: |
| action_str = str(a) |
| if 'or_il' in action_str: |
| or_il_actions.append(a) |
| elif 'or_ir' in action_str: |
| or_ir_actions.append(a) |
| else: |
| others.append(a) |
| return or_il_actions + or_ir_actions + others |
| |
| |
| if goal_clean.startswith('(not ') and not is_double_negation(goal_clean): |
| for a in actions: |
| action_str = str(a) |
| if 'not_i' in action_str: |
| prioritized.append(a) |
| else: |
| others.append(a) |
| return prioritized + others |
| |
| |
| if goal_clean.startswith('(iff '): |
| for a in actions: |
| action_str = str(a) |
| if 'iff_i' in action_str: |
| prioritized.append(a) |
| else: |
| others.append(a) |
| return prioritized + others |
| |
| |
| if goal_clean == 'false' or goal_clean == '(false)': |
| |
| for a in actions: |
| action_str = str(a) |
| if 'not_e' in action_str or 'exfalso' in action_str: |
| prioritized.append(a) |
| else: |
| others.append(a) |
| return prioritized + others |
| |
| |
| |
| elimination_actions = [] |
| intro_actions = [] |
| apply_actions = [] |
| construct_actions = [] |
| |
| for a in actions: |
| action_str = str(a) |
| |
| if any(name in action_str for name in ['and_el', 'and_er', 'or_e', 'iff_el', 'iff_er']): |
| elimination_actions.append(a) |
| elif hasattr(a, 'is_intro') and a.is_intro(): |
| intro_actions.append(a) |
| elif hasattr(a, 'is_apply') and a.is_apply(): |
| apply_actions.append(a) |
| elif hasattr(a, 'is_construct') and a.is_construct(): |
| construct_actions.append(a) |
| else: |
| others.append(a) |
| |
| |
| em_actions = [] |
| for a in actions: |
| action_str = str(a) |
| if 'em' in action_str: |
| em_actions.append(a) |
| |
| |
| return elimination_actions + em_actions + apply_actions + construct_actions + intro_actions + others |
|
|
|
|
| def make_pattern_prover(config=None): |
| """Factory function to create pattern prover (for compatibility).""" |
| if config is None: |
| config = PatternProverConfig() |
| return PatternProver(config) |
|
|