| |
| """ |
| Evaluation script for pattern-based baseline prover. |
| Evaluates on extrinsic propositional logic problemset. |
| """ |
|
|
| import os |
| import json |
| import sys |
| from typing import Optional |
| from concurrent.futures import ProcessPoolExecutor, as_completed |
| from functools import partial |
|
|
| import problems |
| from learning.exp_pattern_prover.pattern_prover import PatternProver, PatternProverConfig |
| from proofsearch import format_blocks_with_indent |
|
|
| try: |
| from tqdm import tqdm |
| except ImportError: |
| |
| def tqdm(iterable, **kwargs): |
| return iterable |
|
|
|
|
| def _evaluate_single_problem(args): |
| """Worker function to evaluate a single problem (for multiprocessing).""" |
| problem, problemset_id, max_depth, max_iterations, verbose, log_dir = args |
| |
| try: |
| |
| problemset = problems.load_problemset(problemset_id) |
| |
| |
| log_file = None |
| if log_dir: |
| os.makedirs(log_dir, exist_ok=True) |
| log_file = os.path.join(log_dir, f"{problem}_log.jsonl") |
| |
| |
| config = PatternProverConfig( |
| max_depth=max_depth, |
| max_iterations=max_iterations, |
| verbose=verbose, |
| log_file=log_file |
| ) |
| prover = PatternProver(config) |
| |
| |
| state = problemset.initialize_problem(problem) |
| result = prover.proof_search(problem, state) |
| |
| |
| proof_text = None |
| if result.success: |
| try: |
| |
| solution_actions = result.root.get_solution_actions() |
| if solution_actions is None or (isinstance(solution_actions, list) and len(solution_actions) == 0): |
| proof_text = "<proof reconstruction failed: No solution actions found>" |
| else: |
| |
| actions_copy = [a for a in solution_actions] if isinstance(solution_actions, list) else solution_actions |
| proof_text = format_blocks_with_indent(result.root.reconstruct_proof()) |
| except Exception as e: |
| import traceback |
| proof_text = f"<proof reconstruction failed: {e}>\n{traceback.format_exc()}" |
| |
| return { |
| 'problem': problem, |
| 'success': result.success, |
| 'iterations': result.iterations, |
| 'proof': proof_text, |
| 'error': None |
| } |
| except Exception as e: |
| import traceback |
| return { |
| 'problem': problem, |
| 'success': False, |
| 'iterations': 0, |
| 'proof': None, |
| 'error': f"{str(e)}\n{traceback.format_exc()}" |
| } |
|
|
|
|
| def evaluate_pattern_prover( |
| problemset_id: str = 'extrinsic-propositional-logic', |
| max_problems: Optional[int] = None, |
| max_depth: int = 30, |
| max_iterations: int = 5000, |
| verbose: bool = False, |
| output_dir: str = '.', |
| num_workers: Optional[int] = None, |
| log_dir: Optional[str] = None, |
| ): |
| """ |
| Evaluate pattern prover on a problemset. |
| |
| Args: |
| problemset_id: ID of problemset to evaluate on |
| max_problems: Maximum number of problems to evaluate (None = all) |
| max_depth: Maximum search depth |
| max_iterations: Maximum iterations |
| verbose: Print verbose output |
| output_dir: Directory to save results |
| num_workers: Number of parallel workers (None = use all CPU cores) |
| """ |
| |
| print(f"Loading problemset: {problemset_id}") |
| problemset = problems.load_problemset(problemset_id) |
| print(f"Loaded {len(problemset)} problems") |
| |
| |
| problem_names = problemset.problem_names() |
| if max_problems is not None: |
| problem_names = problem_names[:max_problems] |
| |
| |
| if num_workers is None: |
| import multiprocessing |
| num_workers = multiprocessing.cpu_count() |
| |
| print(f"Evaluating {len(problem_names)} problems using {num_workers} workers...") |
| print() |
| |
| |
| if log_dir is None: |
| log_dir = os.path.join(output_dir, "logs") |
| |
| |
| worker_args = [ |
| (problem, problemset_id, max_depth, max_iterations, verbose, log_dir) |
| for problem in problem_names |
| ] |
| |
| |
| results = { |
| "results": [], |
| "num_proved": 0, |
| "num_total": len(problem_names), |
| "solved_problems": [] |
| } |
| |
| if num_workers == 1: |
| |
| for args in worker_args: |
| result = _evaluate_single_problem(args) |
| results["results"].append(result) |
| if result['success']: |
| results["num_proved"] += 1 |
| results["solved_problems"].append(result['problem']) |
| if verbose: |
| status = "✓" if result['success'] else "✗" |
| print(f"{status} {result['problem']}: {result['iterations']} iterations") |
| else: |
| |
| with ProcessPoolExecutor(max_workers=num_workers) as executor: |
| futures = { |
| executor.submit(_evaluate_single_problem, args): args[0] |
| for args in worker_args |
| } |
| |
| for future in tqdm(as_completed(futures), total=len(futures), desc="Evaluating"): |
| problem_name = futures[future] |
| try: |
| result = future.result() |
| results["results"].append(result) |
| if result['success']: |
| results["num_proved"] += 1 |
| results["solved_problems"].append(result['problem']) |
| if verbose: |
| status = "✓" if result['success'] else "✗" |
| print(f"{status} {result['problem']}: {result['iterations']} iterations") |
| except Exception as e: |
| print(f"Error evaluating {problem_name}: {e}") |
| results["results"].append({ |
| 'problem': problem_name, |
| 'success': False, |
| 'iterations': 0, |
| 'proof': None, |
| 'error': str(e) |
| }) |
| |
| |
| results["results"].sort(key=lambda x: x['problem']) |
| |
| |
| print() |
| print("=" * 60) |
| print("SUMMARY") |
| print("=" * 60) |
| print(f"Solved: {results['num_proved']}/{results['num_total']}") |
| if results['num_total'] > 0: |
| print(f"Pass rate: {results['num_proved']/results['num_total']*100:.1f}%") |
| print() |
| |
| if results['solved_problems']: |
| print("Solved problems:") |
| for p in sorted(results['solved_problems']): |
| print(f" - {p}") |
| print() |
| |
| |
| os.makedirs(output_dir, exist_ok=True) |
| output_file = os.path.join(output_dir, "pattern_prover_results.json") |
| with open(output_file, 'w') as f: |
| json.dump(results, f, indent=2) |
| print(f"Results saved to: {output_file}") |
| |
| return results |
|
|
|
|
| def main(): |
| """Main entry point.""" |
| import argparse |
| |
| parser = argparse.ArgumentParser(description="Evaluate pattern-based prover") |
| parser.add_argument( |
| '--problemset', |
| type=str, |
| default='extrinsic-propositional-logic', |
| help='Problemset ID (default: extrinsic-propositional-logic)' |
| ) |
| parser.add_argument( |
| '--max-problems', |
| type=int, |
| default=None, |
| help='Maximum number of problems to evaluate (default: all)' |
| ) |
| parser.add_argument( |
| '--max-depth', |
| type=int, |
| default=30, |
| help='Maximum search depth (default: 30)' |
| ) |
| parser.add_argument( |
| '--max-iterations', |
| type=int, |
| default=5000, |
| help='Maximum iterations (default: 5000)' |
| ) |
| parser.add_argument( |
| '--verbose', |
| action='store_true', |
| help='Print verbose output' |
| ) |
| parser.add_argument( |
| '--output-dir', |
| type=str, |
| default='.', |
| help='Output directory for results (default: current directory)' |
| ) |
| parser.add_argument( |
| '--num-workers', |
| type=int, |
| default=None, |
| help='Number of parallel workers (default: use all CPU cores)' |
| ) |
| parser.add_argument( |
| '--log-dir', |
| type=str, |
| default=None, |
| help='Directory for detailed logs (default: output_dir/logs)' |
| ) |
| |
| args = parser.parse_args() |
| |
| evaluate_pattern_prover( |
| problemset_id=args.problemset, |
| max_problems=args.max_problems, |
| max_depth=args.max_depth, |
| max_iterations=args.max_iterations, |
| verbose=args.verbose, |
| output_dir=args.output_dir, |
| num_workers=args.num_workers, |
| log_dir=args.log_dir |
| ) |
|
|
|
|
| if __name__ == '__main__': |
| main() |
|
|
|
|
| |
| |