File size: 6,203 Bytes
78a3b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Installation checks, fixed-scene smoke checks, expert replay and reference export."""
import argparse
import contextlib
import importlib.metadata
import json
from pathlib import Path
import sys

from .runtime import RESOURCES, configure, reference_manifest, evaluation_protocol, task_manifest


def ids(value, available):
    selected = list(available) if value == "all" else [int(v) for v in value.split(",")]
    if not selected or len(set(selected)) != len(selected) or set(selected) - set(available):
        raise ValueError(f"ids must be unique members of {list(available)}")
    return selected


def doctor():
    from . import get_suite
    suite = get_suite()
    if suite.n_tasks != len(task_manifest()):
        raise ValueError("task count differs from manifest")
    return dict(passed=True, tasks=suite.n_tasks,
                references=[r["id"] for r in reference_manifest()["references"]],
                packages={p: importlib.metadata.version(p) for p in
                          ("numpy", "scipy", "torch", "mujoco", "robosuite", "h5py", "PyOpenGL")})


def smoke(task_id):
    import numpy as np
    from . import get_suite, make_env
    protocol = evaluation_protocol()
    env, obs = make_env(task_id)
    try:
        initial = get_suite().get_task_init_states(task_id)[protocol["initial_state_indices"][0]]
        state_error = float(np.max(np.abs(env.sim.get_state().flatten() - initial)))
        if state_error > 1e-12 or env.check_success():
            raise ValueError("fixed initial state mismatch")
        def validate_images(observation):
            for camera in protocol["camera_names"]:
                image = observation[camera + "_image"]
                if image.shape != (*protocol["camera_resolution"], 3) or image.dtype != np.uint8:
                    raise ValueError("invalid camera observation")

        validate_images(obs)
        before = float(env.sim.data.time)
        obs, _, _, _ = env.step([0, 0, 0, 0, 0, 0, -1])
        validate_images(obs)
        elapsed = float(env.sim.data.time) - before
        if not np.isclose(elapsed, 1 / protocol["control_frequency_hz"], atol=1e-9):
            raise ValueError("incorrect native step frequency")
        return dict(id=task_id, passed=True, initial_state_error=state_error,
                    camera_names=protocol["camera_names"],
                    camera_resolution=protocol["camera_resolution"],
                    initialization_steps=0, elapsed_seconds=elapsed,
                    success_after_one_step=bool(env.check_success()))
    finally:
        env.close()


def replay(task_id):
    import h5py
    import numpy as np
    from . import make_env
    row = next(r for r in reference_manifest()["references"] if r["id"] == task_id)
    folder = RESOURCES / "expert_reference"
    with h5py.File(folder / row["files"]["dataset"]["path"], "r") as f:
        actions = f["data/demo_0/actions"][:]
        first = f["data/demo_0/states"][0]
    env, _ = make_env(task_id, camera_obs=False)
    try:
        error = float(np.max(np.abs(first - env.sim.get_state().flatten())))
        if error > 1e-12:
            raise ValueError("expert and test initial state differ")
        first_success = None
        for i, action in enumerate(actions, 1):
            env.step(action)
            if env.check_success() and first_success is None:
                first_success = i
        if not env.check_success():
            raise ValueError(f"expert replay did not succeed: {task_id}")
        return dict(id=task_id, success=True, actions=len(actions),
                    first_success_step=first_success, initial_state_error=error)
    finally:
        env.close()


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=("doctor", "smoke", "replay-experts", "export-references"))
    parser.add_argument("--ids", default="all")
    parser.add_argument("--renderer", choices=("osmesa", "egl"), default="osmesa")
    parser.add_argument("--output", type=Path,
                        help="required destination directory for export-references; optional JSON report otherwise")
    args = parser.parse_args(argv)
    if args.command == "export-references" and args.output is None:
        parser.error("export-references requires --output DIRECTORY")
    results = []
    try:
        configure(renderer=args.renderer)
        if args.command == "export-references":
            from .export_references import convert
            rows = {r["id"]: r for r in reference_manifest()["references"]}
            selected = ids(args.ids, rows)
            output = args.output.expanduser().resolve()
            for tid in selected:
                destination = output / f"task_{tid:03d}"
                if destination.exists() or destination.is_symlink():
                    raise FileExistsError(f"refusing to overwrite {destination}")
            for tid in selected:
                with contextlib.redirect_stdout(sys.stderr):
                    result = convert(rows[tid], output / f"task_{tid:03d}")
                print(json.dumps(result), flush=True)
            return 0
        if args.command == "doctor":
            with contextlib.redirect_stdout(sys.stderr):
                results.append(doctor())
            print(json.dumps(results[-1]), flush=True)
        else:
            available = ([t["id"] for t in task_manifest()] if args.command == "smoke"
                         else [r["id"] for r in reference_manifest()["references"]])
            for tid in ids(args.ids, available):
                with contextlib.redirect_stdout(sys.stderr):
                    result = smoke(tid) if args.command == "smoke" else replay(tid)
                results.append(result)
                print(json.dumps(result), flush=True)
        if args.output:
            args.output.parent.mkdir(parents=True, exist_ok=True)
            args.output.write_text(json.dumps(dict(passed=True, command=args.command, results=results), indent=2) + "\n")
        return 0
    except (ValueError, OSError) as exc:
        parser.exit(1, str(exc) + "\n")


if __name__ == "__main__":
    raise SystemExit(main())