Download experiments/learnability/exp_pattern_prover/pattern_prover.py from MilaAI4Math/OpenExpDatasets: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/datasets/MilaAI4Math/OpenExpDatasets/resolve/9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/exp_pattern_prover/pattern_prover.py
- Command line
-
hf download hf://datasets/MilaAI4Math/OpenExpDatasets@9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/exp_pattern_prover/pattern_prover.py
-
curl -L -o pattern_prover.py https://huggingface.co/datasets/MilaAI4Math/OpenExpDatasets/resolve/9ebb8c742abb4f651ff8dec02d985ecd22c9d044/experiments/learnability/exp_pattern_prover/pattern_prover.py
13.8 kB
| #!/usr/bin/env python3 | |
| """ | |
| 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 | |
| class PatternProverConfig: | |
| """Configuration for pattern-based prover.""" | |
| max_depth: int = 30 | |
| max_iterations: int = 5000 | |
| verbose: bool = False | |
| log_file: Optional[str] = None # Path to log file for detailed logging | |
| 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 = [] # Store log entries for this problem | |
| self._current_problem = None | |
| self._solution_path = [] # Track solution path (list of (node, action) tuples) | |
| 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 | |
| # Log initial state | |
| 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])) | |
| # Try to solve using pattern-based search | |
| solved = self._pattern_search(root) | |
| # Write log if configured | |
| if self.config.log_file: | |
| self._write_log() | |
| # Extract examples (empty for baseline) | |
| 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 | |
| } | |
| # Append to log file (one JSON object per line) | |
| 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 | |
| # Special handling for conjunctive nodes - all children must be solved | |
| if node.state_node.is_conjunctive(): | |
| return self._solve_conjunctive_node(node, depth) | |
| # Get current state | |
| 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() | |
| # Get available actions | |
| actions = node.state_node.actions | |
| if not actions: | |
| return False | |
| # Pattern-based action selection - get prioritized list | |
| prioritized_actions = self._prioritize_actions_by_pattern(state, goal_str, actions) | |
| # Initialize children list if needed | |
| if node._children is None: | |
| node._children = [] | |
| # Try actions in priority order | |
| for action in prioritized_actions: | |
| try: | |
| # Log the action being tried | |
| self._log(f"Trying action (depth {depth})", goal=goal_str, action=str(action)) | |
| # Expand the state node with the action | |
| expanded_state = node.state_node.expand(action) | |
| # Create child TreeSearchNode and try it | |
| child_node = TreeSearchNode(expanded_state, parent=(node, action)) | |
| # Store child in parent's children list (needed for proof reconstruction) | |
| node._children.append(child_node) | |
| if self._pattern_search_recursive(child_node, depth + 1): | |
| # Mark this node with the solution action | |
| 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.""" | |
| # Get available actions (string indices for subgoals) | |
| actions = node.state_node.actions | |
| if not actions: | |
| return False | |
| # Initialize children list | |
| if node._children is None: | |
| node._children = [] | |
| # Create child nodes for each subgoal if not already created | |
| 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) | |
| # Try to solve each subgoal in order | |
| 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 # This subgoal failed, can't solve conjunctive node | |
| # All subgoals solved - node is now solved | |
| # Note: For conjunctive nodes, is_solved() checks all children are solved | |
| # and get_solution_actions() returns [dfs(c) for c in node._children] | |
| 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 are strings (conjunctive node indices), return as-is | |
| if actions and isinstance(actions[0], str): | |
| return actions | |
| goal_clean = goal_str.strip() | |
| prioritized = [] | |
| others = [] | |
| # Helper to check for double negation pattern: (not (not ...)) | |
| def is_double_negation(s: str) -> bool: | |
| # Match (not (not ...)) | |
| return s.startswith('(not (not ') and s.endswith('))') | |
| # Helper to extract inner content from double negation | |
| def extract_from_double_negation(s: str) -> Optional[str]: | |
| if is_double_negation(s): | |
| # Remove outer (not (not ...)) | |
| inner = s[10:-2] # Remove "(not (not " and "))" | |
| return inner | |
| return None | |
| # PATTERN 0: Double negation (not (not A)) - try to prove A | |
| if is_double_negation(goal_clean): | |
| inner = extract_from_double_negation(goal_clean) | |
| # Prefer actions that can work with the inner proposition | |
| # This is a heuristic - we want to prove the inner, then use double negation elimination | |
| for a in actions: | |
| action_str = str(a) | |
| # Prefer intro actions that might help prove the inner | |
| if hasattr(a, 'is_intro') and a.is_intro(): | |
| prioritized.append(a) | |
| # Also prefer elimination rules that might extract from context | |
| 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 | |
| # PATTERN 1: Goal is implication [A -> B] | |
| 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 | |
| # PATTERN 2: Goal is conjunction (and A B) | |
| 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 | |
| # PATTERN 3: Goal is disjunction (or A B) | |
| if goal_clean.startswith('(or '): | |
| # Try or_il first, then or_ir | |
| 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 | |
| # PATTERN 4: Goal is negation (not A) | |
| 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 | |
| # PATTERN 5: Goal is biconditional (iff A B) | |
| 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 | |
| # PATTERN 6: Goal is false | |
| if goal_clean == 'false' or goal_clean == '(false)': | |
| # Look for contradiction - prefer not_e, exfalso | |
| 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 | |
| # PATTERN 7: Goal is atomic - try forward chaining | |
| # Prefer elimination rules that can extract from context | |
| elimination_actions = [] | |
| intro_actions = [] | |
| apply_actions = [] | |
| construct_actions = [] | |
| for a in actions: | |
| action_str = str(a) | |
| # Prefer elimination rules | |
| 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) | |
| # Also check if we can use excluded middle for case analysis | |
| em_actions = [] | |
| for a in actions: | |
| action_str = str(a) | |
| if 'em' in action_str: | |
| em_actions.append(a) | |
| # Order: elimination > excluded middle > apply > construct > intro > others | |
| 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) | |