File size: 5,576 Bytes
9d57416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run the synthetic facts → prover → question export → mock scoring example."""
import argparse
import json
from pathlib import Path

from embodied_pipeline.domain import storage
import subprocess
import sys
import tempfile

import numpy as np

from embodied_pipeline.gen import facts
from embodied_pipeline.prover import compile as compiler, interp
from np.prover_questions import question


HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
VERSION = 'speed.value.at_time/single_ego'


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--out', type=Path, help='new output directory (default: a retained temporary directory)')
    args = parser.parse_args()
    if args.out is None:
        out = Path(tempfile.mkdtemp(prefix='embodied-quickstart-'))
    else:
        out = args.out.resolve()
        out.mkdir(parents=True, exist_ok=False)
    print(f'Output: {out}', flush=True)

    # Same two-room fixture as test_prover_facts, with a moving observer.
    segment = out / 'synthetic'
    segment.mkdir()
    script = json.loads((HERE / 'script.json').read_text(encoding='utf-8'))
    # The synthetic mover uses its centre as the track point and faces +u at yaw zero.
    script['actors'][0]['body_registration'] = dict(center=dict(forward_m=0., left_m=0.),
                                                   forward=dict(world_at_yaw0=[1., 0.]))
    (segment / 'script.json').write_text(json.dumps(script, ensure_ascii=False), encoding='utf-8')
    (segment / 'capability.json').write_bytes((HERE / 'capability.json').read_bytes())
    np.savez(segment / 'static-bands.npz', occupied=np.zeros((100, 100), dtype=np.uint8))
    np.savez(segment / 'nav.npz', navigable=np.ones((100, 100), dtype=bool),
             island=np.zeros((100, 100), dtype=np.int32), distance_m=np.ones((100, 100), dtype=np.float32))
    np.savez(segment / 'regions.npz', region=np.zeros((100, 100), dtype=np.int32))
    n = script['actors'][1]['recording']['frame_count']
    t = np.arange(n) / script['control_hz']
    # Two steady plateaus retain full-trajectory variation and local stability.
    # The queried 0.8 m/s plateau also lies outside
    # the registered batch-constant prior's acceptance band (criterion 乙).
    observer_xy = np.c_[.8*t+.4*np.maximum(t-4., 0.), t*0]
    np.savez(segment / 'curves.npz', t=t, **{
        'actor-000__u': -3. + t, 'actor-000__v': np.zeros(n), 'actor-000__yaw': np.zeros(n),
        'observer-000__u': -4.+observer_xy[:, 0], 'observer-000__v': 2.+observer_xy[:, 1],
        'observer-000__cam_yaw': np.zeros(n), 'observer-000__cam_pitch': np.zeros(n),
    })
    facts.write(segment, segment)
    print(f'Facts: {segment / "facts.npz"}, {storage.stored_path(segment / "facts.json")} (segments=1, samples={n})', flush=True)

    # Use the compiler API so even plans.json stays outside the checkout.
    plans = out / 'plans.json'
    compiled = compiler.compile_all()
    plans.write_text(json.dumps(dict(meta=dict(git_head=compiler.head(), sources=compiler.sources()),
                                    versions=compiled), ensure_ascii=False), encoding='utf-8')
    interp.PLANS = plans
    print(f'Plans: {plans} (versions={len(compiled)})', flush=True)

    proved = interp.run(segment, VERSION, methods=interp.BASIC_METHODS, k_packages=1, pin={'1': ('t', 2.)})
    packages = proved.get('packages') or []
    if not packages:
        raise RuntimeError(f'No questions produced: {proved}')
    meta = json.loads(storage.read_text(segment / 'facts.json'))
    questions = segment / 'questions.jsonl'
    with questions.open('w', encoding='utf-8') as stream:
        for index, package in enumerate(packages):
            row = question(VERSION, index, package, meta, script['actors'])
            stream.write(json.dumps(row, ensure_ascii=False) + '\n')
    print(f'Prover packages (private): {questions} (questions={len(packages)})', flush=True)

    evaluation = out / 'evaluation'
    subprocess.run([sys.executable, '-B', str(ROOT / 'tools/evaluation/np_export.py'),
                    '--questions', str(questions), '--out', str(evaluation)], check=True)
    exported = json.loads((evaluation / 'export.json').read_text(encoding='utf-8'))
    if exported['items'] != len(packages) or exported['skipped']:
        raise RuntimeError(f'Incomplete evaluation export: {exported}')
    items, truth = evaluation / 'items.jsonl', evaluation / 'truth.jsonl'
    print(f'Public input: {items} (questions={exported["items"]})')
    print(f'Private truth: {truth} (questions={exported["items"]})', flush=True)

    run = out / 'mock-run'
    subprocess.run([sys.executable, '-B', str(ROOT / 'tools/evaluation/runner.py'), 'run',
                    '--items', str(items), '--endpoint', str(HERE / 'mock.json'),
                    '--settings', '{"text_only": true}', '--out', str(run)], check=True)
    subprocess.run([sys.executable, '-B', str(ROOT / 'tools/evaluation/runner.py'), 'score',
                    '--run', str(run), '--truth', str(truth)], check=True)
    summary = json.loads((run / 'summary.json').read_text(encoding='utf-8'))['overall']
    print(f'Mock answers: {run / "responses.jsonl"}')
    print(f'Scores: {run / "scores.jsonl"}, {run / "summary.json"}')
    result = dict(output=str(out), questions=exported['items'], **summary)
    print(json.dumps(result, ensure_ascii=False))
    if summary['passed'] != exported['items']:
        raise RuntimeError('Mock did not pass every exported question; inspect scores.jsonl')


if __name__ == '__main__':
    main()