File size: 4,802 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
#!/usr/bin/env python3
"""
Step 3: Extract training examples for a specific filter condition.

Takes a single filtered_candidates.json and the full examples_grouped.json
(from prove_and_extract.py on the 'none' filter), looks up proof results
for each candidate, and writes examples.json.

Optionally subsample N candidates (randomly) from the filtered set.

Usage:
    python split_examples.py \
        --grouped .../none/examples_grouped.json \
        --candidates .../novel-1.0/filtered_candidates.json \
        --output_dir .../novel-1.0

    # Keep only 50 randomly sampled candidates:
    python split_examples.py \
        --grouped .../none/examples_grouped.json \
        --candidates .../novel-1.0/filtered_candidates.json \
        --output_dir .../novel-1.0-N50 \
        -N 50 --seed 42
"""

import argparse
import json
import random
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(
        description='Extract training examples for a filtered candidate set')
    parser.add_argument('--grouped', required=True,
                        help='Path to examples_grouped.json (from prove_and_extract.py on none)')
    parser.add_argument('--candidates', required=True,
                        help='Path to filtered_candidates.json')
    parser.add_argument('--output_dir', required=True,
                        help='Output directory for examples')
    parser.add_argument('-N', type=int, default=None,
                        help='Randomly sample N candidates (default: keep all)')
    parser.add_argument('--seed', type=int, default=42,
                        help='Random seed for subsampling (default: 42)')
    args = parser.parse_args()

    # Load grouped examples (keyed by candidate statement)
    print(f"Loading grouped examples from {args.grouped}")
    with open(args.grouped) as f:
        grouped = json.load(f)

    stmt_to_entry = {}
    for entry in grouped['problems']:
        stmt_to_entry[entry['candidate']] = entry
    print(f"  {len(stmt_to_entry)} candidates with proof results")

    # Load filtered candidates
    print(f"\nLoading candidates from {args.candidates}")
    with open(args.candidates) as f:
        cand_data = json.load(f)

    filter_name = cand_data['filter']
    candidates = cand_data['candidates']
    print(f"  Filter: {filter_name}")
    print(f"  Candidates: {len(candidates)}")

    # Subsample if requested
    if args.N is not None and args.N < len(candidates):
        rng = random.Random(args.seed)
        candidates = rng.sample(candidates, args.N)
        print(f"  Subsampled to N={args.N} (seed={args.seed})")

    # Look up examples
    problems = []
    flat_examples = []
    missing = 0

    for stmt in candidates:
        entry = stmt_to_entry.get(stmt)
        if entry is None:
            missing += 1
            continue
        problems.append(entry)
        flat_examples.extend(entry['examples'])

    n_proved = sum(1 for p in problems if p['success'])
    n_examples = len(flat_examples)
    n_per_proved = [len(p['examples']) for p in problems if p['success']]
    avg_ex = sum(n_per_proved) / len(n_per_proved) if n_per_proved else 0

    print(f"\n  Matched: {len(problems)}, Missing: {missing}")
    print(f"  Proved: {n_proved}, Examples: {n_examples}, Avg/proved: {avg_ex:.1f}")

    # Save
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    with open(out_dir / 'examples_grouped.json', 'w') as f:
        json.dump({
            'filter': filter_name,
            'source_grouped': str(args.grouped),
            'source_candidates': str(args.candidates),
            'n_candidates': len(candidates),
            'n_sampled': args.N,
            'sample_seed': args.seed if args.N else None,
            'n_proved': n_proved,
            'n_examples': n_examples,
            'problems': problems,
        }, f, indent=2)

    with open(out_dir / 'examples.json', 'w') as f:
        json.dump(flat_examples, f)

    with open(out_dir / 'candidates.txt', 'w') as f:
        for stmt in candidates:
            f.write(stmt + '\n')

    summary = {
        'filter': filter_name,
        'source_grouped': str(args.grouped),
        'source_candidates': str(args.candidates),
        'n_candidates': len(candidates),
        'n_sampled': args.N,
        'n_proved': n_proved,
        'n_examples': n_examples,
        'avg_examples_per_problem': avg_ex,
    }
    with open(out_dir / 'summary.json', 'w') as f:
        json.dump(summary, f, indent=2)

    print(f"\nSaved to {out_dir}/")
    print(f"  examples.json ({n_examples} examples)")
    print(f"  examples_grouped.json ({len(problems)} problems)")
    print(f"  candidates.txt ({len(candidates)} statements)")
    print(f"  summary.json")


if __name__ == '__main__':
    main()