File size: 7,881 Bytes
85968f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Score replies on the decision test: at each failure state, does the reply retry the failed target or replan?

    python3 score.py replies/activemoma.jsonl                  one file of replies
    python3 score.py replies/*.jsonl                           several, one row each
    python3 score.py replies/*.jsonl --by-task                 also per task

A file of replies has one JSON object per line, {"id": <state id>, "reply": <the model's reply as text>}, for all 154
states of states.jsonl. Only the Python standard library is needed.

A reply is judged by its first tool call, <tool_call>{"name": ..., "arguments": {...}}</tool_call>, against the target X
of the failed call (Appendix B.2 of the paper):

  retry    approach, pick or place on X again, with arguments the skill takes and values in their ranges;
  replan   a call that leaves X: approach, pick, place, find or search of another object; a find or search of X's
           name whose other_than passes over X itself (another object of that name); a release of the held object
           when X was where it was to go;
  other    anything else: no call, go_to, done, a find or search of X itself, a call on X that cannot be run, a
           call on another name of the same fixture.

The replan rate is the share of replies that replan, taken at the states whose verdict is unrecoverable (no executed
retry passed) and at those whose verdict is recoverable (an executed retry passed); the selectivity J is their
difference in points. States without a verdict are not scored.
"""
import argparse, json, math
from pathlib import Path

HERE = Path(__file__).resolve().parent
SUBJECT = {"approach": "object_name", "pick": "object_name", "place": "target_name"}
# the arguments each skill takes besides its target, with the range of values a call may use (None: a name)
RANGES = {"approach": {"distance": (0.2, 1.5), "angle": (-180.0, 180.0), "support": None, "standoff": (0.05, 1.0), "shift": (-1.0, 1.0)},
          "pick": {"grasp": (0, 9)},
          "place": {"height": (-0.3, 0.6), "top": (0.0, 2.5), "beyond": (-1.0, 1.0), "sideways": (-1.0, 1.0)}}
LOOKS = ("find", "search")
PASS_OVER_M = {True: 1.0, False: 0.15}     # radius within which other_than passes over a fixture, or a small object


def call_of(text):
    """the first tool call of a reply, or None"""
    start = (text or "").find("<tool_call>")
    if start < 0:
        return None
    try:
        call, _ = json.JSONDecoder().raw_decode(text[start + len("<tool_call>"):].lstrip())
    except ValueError:
        return None
    return call if isinstance(call, dict) else None


def runnable(name, args):
    """a call on X that can be executed as a retry: known arguments, values in range"""
    if any(a != SUBJECT[name] and a not in RANGES[name] for a in args):
        return False
    for arg, value in args.items():
        if arg == SUBJECT[name] or value is None:
            continue
        bounds = RANGES[name][arg]
        if bounds is None:
            if not isinstance(value, str):
                return False
        elif not (isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and bounds[0] <= value <= bounds[1]):
            return False
    return True


def passes_over(other_than, state):
    """whether a find or search of X's name with this other_than looks for another object of that name"""
    pos = state.get("target_position")
    if not other_than or pos is None:
        return False
    try:
        rows = other_than if isinstance(other_than[0], (list, tuple)) else [other_than]
        pts = [(float(p[0]), float(p[1])) for p in rows if isinstance(p, (list, tuple)) and len(p) in (2, 3)]
    except Exception:
        return False
    radius = PASS_OVER_M[bool(state["target_is_fixture"])]
    return any(math.hypot(px - float(pos[0]), py - float(pos[1])) <= radius + 1e-9 for px, py in pts)


def judge(state, reply):
    """retry, replan or other"""
    call = call_of(reply)
    if not isinstance(call, dict) or not isinstance(call.get("name"), str):
        return "other"
    name, args = call["name"], call.get("arguments", {})
    if not isinstance(args, dict):
        return "other"
    x, same_fixture = state["target"], set(state["other_names_of_target"])
    if name in SUBJECT:
        target = args.get(SUBJECT[name])
        if target == x:
            return "retry" if runnable(name, args) else "other"
        if not isinstance(target, str) or not target or target in same_fixture:
            return "other"
        if any(a != SUBJECT[name] and a not in RANGES[name] for a in args):
            return "other"
        return "replan"
    if name in LOOKS:
        target = args.get("object_name")
        if not isinstance(target, str) or not target:
            return "other"
        if target != x:
            return "other" if target in same_fixture else "replan"
        return "replan" if passes_over(args.get("other_than"), state) else "other"
    if name == "release":
        return "replan" if state["target_is_where_the_held_object_goes"] else "other"
    return "other"


def load_states(path):
    return {s["id"]: s for s in map(json.loads, Path(path).read_text(encoding="utf-8").splitlines()) if s}


def load_kinds(path, states):
    rows = {r["id"]: r["reply"] for r in map(json.loads, Path(path).read_text(encoding="utf-8").splitlines())}
    missing = set(states) - set(rows)
    if missing:
        raise SystemExit(f"{path}: {len(missing)} of {len(states)} states have no reply (first: {sorted(missing)[0]})")
    return {i: judge(states[i], rows[i]) for i in states}


def rates(kinds, states, ids):
    u = [i for i in ids if states[i]["verdict"] == "unrecoverable"]
    r = [i for i in ids if states[i]["verdict"] == "recoverable"]
    nu, nr = sum(kinds[i] == "replan" for i in u), sum(kinds[i] == "replan" for i in r)
    return nu / max(len(u), 1), nr / max(len(r), 1), nu, len(u), nr, len(r)


def row(name, kinds, states, ids):
    pu, pr, nu, tu, nr, tr = rates(kinds, states, ids)
    judged = [i for i in ids if states[i]["verdict"]]
    retry = sum(kinds[i] == "retry" for i in judged) / max(len(judged), 1)
    return f"{name:38s} {nu:3d}/{tu:<3d} {100 * pu:5.1f}%    {nr:3d}/{tr:<3d} {100 * pr:5.1f}%    {100 * (pu - pr):6.1f}      {100 * retry:5.1f}%"


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("replies", nargs="*", help="files of replies")
    ap.add_argument("--states", default=str(HERE / "states.jsonl"))
    ap.add_argument("--by-task", action="store_true", help="also one block per task")
    ap.add_argument("--unseen-scenes", action="store_true", help="only the 82 states whose scenes are in no training data")
    args = ap.parse_args()
    states = load_states(args.states)
    ids = sorted(i for i in states if not args.unseen_scenes or states[i]["scene_in_no_training_data"])
    n = lambda v: sum(states[i]["verdict"] == v for i in ids)
    print(f"states {len(ids)}: unrecoverable {n('unrecoverable')}, recoverable {n('recoverable')}, no verdict {n(None)}")
    head = f"{'replies':38s} {'replans at unrecoverable':>15s}  {'at recoverable':>16s}  {'J (points)':>10s}  {'retries':>9s}"
    files = list(args.replies)
    kinds = {f: load_kinds(f, states) for f in files}
    if args.replies:
        print(head)
        for f in args.replies:
            print(row(Path(f).stem, kinds[f], states, ids))
        if args.by_task:
            for task in sorted({states[i]["task"] for i in ids}):
                sub = [i for i in ids if states[i]["task"] == task]
                print(f"\n{task} ({len(sub)} states)\n{head}")
                for f in args.replies:
                    print(row(Path(f).stem, kinds[f], states, sub))


if __name__ == "__main__":
    main()