File size: 13,813 Bytes
f1adc24 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | #!/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
@dataclass
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)
|