File size: 9,490 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
#!/usr/bin/env python3
"""
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:
    # Fallback if tqdm not available
    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:
        # Load problemset (each worker needs its own copy)
        problemset = problems.load_problemset(problemset_id)
        
        # Create log file path if logging is enabled
        log_file = None
        if log_dir:
            os.makedirs(log_dir, exist_ok=True)
            log_file = os.path.join(log_dir, f"{problem}_log.jsonl")
        
        # Create pattern prover
        config = PatternProverConfig(
            max_depth=max_depth,
            max_iterations=max_iterations,
            verbose=verbose,
            log_file=log_file
        )
        prover = PatternProver(config)
        
        # Initialize and solve
        state = problemset.initialize_problem(problem)
        result = prover.proof_search(problem, state)
        
        # Extract proof if successful
        proof_text = None
        if result.success:
            try:
                # Get solution actions first to verify structure
                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:
                    # Make a copy since reconstruct_proof modifies the list
                    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)
    """
    # Load problemset to get problem list
    print(f"Loading problemset: {problemset_id}")
    problemset = problems.load_problemset(problemset_id)
    print(f"Loaded {len(problemset)} problems")
    
    # Get problems to evaluate
    problem_names = problemset.problem_names()
    if max_problems is not None:
        problem_names = problem_names[:max_problems]
    
    # Determine number of workers
    if num_workers is None:
        import multiprocessing
        num_workers = multiprocessing.cpu_count()
    
    print(f"Evaluating {len(problem_names)} problems using {num_workers} workers...")
    print()
    
    # Set up log directory
    if log_dir is None:
        log_dir = os.path.join(output_dir, "logs")
    
    # Prepare arguments for workers
    worker_args = [
        (problem, problemset_id, max_depth, max_iterations, verbose, log_dir)
        for problem in problem_names
    ]
    
    # Evaluate in parallel
    results = {
        "results": [],
        "num_proved": 0,
        "num_total": len(problem_names),
        "solved_problems": []
    }
    
    if num_workers == 1:
        # Sequential execution (useful for debugging)
        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:
        # Parallel execution
        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)
                    })
    
    # Sort results by problem name for consistency
    results["results"].sort(key=lambda x: x['problem'])
    
    # Print summary
    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()
    
    # Save results
    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()


#command to run:
# python eval_pattern_prover.py --problemset extrinsic-95--output-dir results/pattern_prover --num-workers 4 --log-dir results/pattern_prover_95