File size: 6,064 Bytes
04782c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Task clock: per family, recorded seconds per episode across authors.

usage: analyse.py OUT_DIR/meta.jsonl RESULT_DIR [OUT_DIR/sample_ids.txt]
Creates RESULT_DIR if missing and replaces clock.json, clock.tsv and datasets.tsv in it. Use a new RESULT_DIR per run.

Per dataset: mean episode seconds = frames / fps / episodes; kept with 5 or more episodes and frames, fps > 0.
fixed_length (v2 only): the usable lengths read (positive numbers among the at most 5,000 fetch.py keeps) all lie
within 2 frames of each other, computed only with 5 or more of them. Usable lengths can number fewer than total_episodes.
kind: "policy" if the repository name matches classify.POLICY, else "teleop" (a name proxy, not a recorded fact).
Per family and kind: each author's median of their datasets' means, then p10/p50/p90 across authors (linear).
clock.tsv publishes a teleop family with MIN_AUTHORS or more authors that passed the purity reading (PURITY_FAILED)."""
import json, sys, os, statistics as st, collections
if len(sys.argv) < 3:
    sys.exit(__doc__)
MIN_AUTHORS = 10
PURITY_FAILED = {"open-close": "failed the family purity reading twice (7/10 on the fresh sample)"}
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import classify

def q(xs, p):
    xs = sorted(xs)
    if not xs: return None
    k = (len(xs) - 1) * p; f = int(k); c = min(f + 1, len(xs) - 1)
    return xs[f] + (xs[c] - xs[f]) * (k - f)

keep = {l.strip() for l in open(sys.argv[3]) if l.strip()} if len(sys.argv) > 3 else None
recs, n_all, n_err, seen = [], 0, 0, set()
for l in open(sys.argv[1]):
    d = json.loads(l)
    if (keep is not None and d["id"] not in keep) or d["id"] in seen: continue
    seen.add(d["id"]); n_all += 1
    if "err" in d: n_err += 1; continue
    eps, fr, fps = d.get("eps") or 0, d.get("frames") or 0, d.get("fps") or 0
    if eps < 5 or fr <= 0 or fps <= 0: continue
    d["mean_s"] = fr / fps / eps
    lens = [x for x in (d.get("lens") or []) if isinstance(x, (int, float)) and x > 0]
    if len(lens) >= 5:
        d["med_s"] = st.median(lens) / fps
        d["fixed"] = (max(lens) - min(lens)) <= 2
    d["family"] = classify.family(d); d["kind"] = "policy" if classify.is_policy(d) else "teleop"
    d["author"] = d["id"].split("/")[0]
    recs.append(d)

def summarise(rows, drop_fixed=False):
    if drop_fixed: rows = [r for r in rows if not r.get("fixed")]
    by = collections.defaultdict(list)
    for r in rows: by[r["author"]].append(r["mean_s"])
    a = [st.median(v) for v in by.values()]
    return {"datasets": len(rows), "authors": len(by), "episodes": sum(r["eps"] for r in rows),
            "hours": round(sum(r["frames"] / r["fps"] for r in rows) / 3600, 1),
            "p10_s": q(a, .1), "p50_s": q(a, .5), "p90_s": q(a, .9)}

out = {"read": {"listed_so": n_all, "fetch_errors": n_err, "kept_eps_ge_5": len(recs)}, "families": {}}
fams = sorted({r["family"] for r in recs})
for kind in ("teleop", "policy"):
    for f in fams:
        rows = [r for r in recs if r["family"] == f and r["kind"] == kind]
        if not rows: continue
        s = summarise(rows)
        v2 = [r for r in rows if "fixed" in r]
        s["v2_with_lengths"] = len(v2); s["v2_fixed_length"] = sum(1 for r in v2 if r["fixed"])
        s["p50_s_without_fixed"] = summarise(rows, True)["p50_s"]
        mm = [(r["med_s"], r["mean_s"]) for r in v2]
        s["v2_median_over_mean_p50"] = q([a / b for a, b in mm], .5) if mm else None
        out["families"][f"{kind}:{f}"] = s
os.makedirs(sys.argv[2], exist_ok=True)
json.dump(out, open(f"{sys.argv[2]}/clock.json", "w"), indent=1)
with open(f"{sys.argv[2]}/datasets.tsv", "w") as f:
    f.write("id\tauthor\tkind\tfamily\trobot\tversion\tepisodes\tframes\tfps\tmean_episode_s\tmedian_episode_s\tfixed_length\n")
    for r in sorted(recs, key=lambda r: r["id"]):
        f.write("\t".join(str(x) for x in [r["id"], r["author"], r["kind"], r["family"], r.get("robot"), r.get("v"), r["eps"], r["frames"], r["fps"],
                round(r["mean_s"], 2), round(r["med_s"], 2) if "med_s" in r else "NA", {True: "yes", False: "no"}.get(r.get("fixed"), "NA")]) + "\n")
def fmt(x):
    return "NA" if x is None else f"{x:.1f}"
cols = ["family", "authors", "datasets", "episodes", "recorded_hours", "p10_s", "p50_s", "p90_s",
        "p50_s_without_fixed_length_datasets", "illustrative_episodes_per_hour_at_p50", "rollout_proxy_authors",
        "rollout_proxy_p50_s", "note"]
pub, unpub, other = [], [], []
for f in fams:
    s = out["families"].get(f"teleop:{f}")
    if s is None: continue
    p = out["families"].get(f"policy:{f}")
    if f == "other":
        note = "unmatched by every family rule"
    elif f in PURITY_FAILED:
        note = "not published: " + PURITY_FAILED[f]
    elif s["authors"] < MIN_AUTHORS:
        note = f"not published: {s['authors']} authors (rule needs {MIN_AUTHORS})"
    else:
        note = "published"
    show = note == "published"
    row = [f, s["authors"], s["datasets"], s["episodes"], s["hours"],
           fmt(s["p10_s"] if show else None), fmt(s["p50_s"] if show else None), fmt(s["p90_s"] if show else None),
           fmt(s["p50_s_without_fixed"] if show else None), round(3600 / s["p50_s"]) if show else "NA",
           p["authors"] if (show and p) else ("0" if show else "NA"),
           fmt(p["p50_s"]) if (show and p and p["authors"] >= MIN_AUTHORS) else "NA", note]
    (pub if show else other if f == "other" else unpub).append(row)
pub.sort(key=lambda r: -r[1]); unpub.sort(key=lambda r: -r[1])
with open(f"{sys.argv[2]}/clock.tsv", "w") as fh:
    fh.write("\t".join(cols) + "\n")
    for row in pub + unpub + other:
        fh.write("\t".join(str(x) for x in row) + "\n")
print(json.dumps(out["read"]))
for k, s in sorted(out["families"].items(), key=lambda kv: -kv[1]["authors"]):
    print(f"{k:22s} ds={s['datasets']:5d} au={s['authors']:4d} eps={s['episodes']:7d} h={s['hours']:7.1f} p10={s['p10_s']:.1f} p50={s['p50_s']:.1f} p90={s['p90_s']:.1f} fixed={s['v2_fixed_length']}/{s['v2_with_lengths']} p50nofix={s['p50_s_without_fixed']}")