"""split.json for one task's monitor data (pour's rules, 2026-11-17, plus sort's: a misaligned-only ending is not a failure). Episodes in seed order. - real episodes: train until it holds 60 failures, then validation until 10 more, then test; successes go with the split of their seed range; - injected sets (every directory but real): failures 20 train, 10 validation, the rest test; - `suboptimal` (evaluation only, never a failure or training success): an injected set's episode that still succeeded after its release / push, and any misaligned-only ending. Rows: run directory, episode, seed, kind, label (failure / success / suboptimal), split, and for failures failure_type: the task's events / reasons (dropped, tipped, spilled, never_grasped, wrong_hole, on_rim, ...) if any, else `ended_early` (the episode ended before the time limit), `stuck` (the arm moved less than 0.02 rad in every joint over the last 3 s before the time limit) or `slow` (still moving at the time limit), plus failure_step (the failure onset; training stops each failed episode there, the 5 s tail is for evaluation only). - `sim_fault` (split `excluded`): a physics blow-up, any arm joint faster than 10 rad/s (normal motion stays below ~2; nest's thin cup walls can explode when squeezed into each other). Never used for training or evaluation. python split.py runs/monitor_""" import json, sys from pathlib import Path import h5py import numpy as np CONTROL_HZ = 10 FAULT_SPEED = 10.0 # rad/s def failure_type(e, qpos, limit): """What kind of failure an episode is (see the module docstring).""" events = [k[6:-11] for k in e if k.startswith("final_") and k.endswith("_onset_step") and k != "final_failure_onset_step" and e[k] >= 0] events += [r for r in e.get("failure_reasons", []) if r not in ("fail", "timeout", "failure") and r not in events] if events: return "-".join(events) onset = int(e.get("final_failure_onset_step", e["steps"])) if onset < limit - 6 * CONTROL_HZ: return "ended_early" window = qpos[max(0, onset - 3 * CONTROL_HZ):onset, :7] return "stuck" if len(window) and np.ptp(window, axis=0).max() < 0.02 else "slow" root = Path(sys.argv[1]) rows = [] for d in sorted(root.glob("*/batch_*")): kind = d.parent.name E = json.load(open(d / "episodes.json")) inj = json.load(open(d / "injections.json")) if (d / "injections.json").exists() else None limit = max(e["steps"] for e in E) # the time limit (episodes stop there, tail included) h5 = h5py.File(d / "trajectories.h5") for i, e in enumerate(E): reasons = [r for r in e.get("failure_reasons", []) if r not in ("fail", "timeout")] disturbed = kind != "real" and (inj is None or str(e["seed"]) in inj) # pushes have no injections.json if not e["success"]: label = "suboptimal" if reasons == ["misaligned"] else "failure" else: label = "suboptimal" if disturbed else "success" if np.abs(h5[f"traj_{i}/obs/qvel"][:, :9]).max() > FAULT_SPEED: label = "sim_fault" row = dict(dir=str(d.relative_to(root)), episode=f"traj_{i}", seed=e["seed"], kind=kind, label=label) if not e["success"] and label != "sim_fault": row["failure_type"] = failure_type(e, h5[f"traj_{i}/obs/qpos"][:], limit) row["failure_step"] = int(e.get("final_failure_onset_step", e["steps"])) rows.append(row) rows.sort(key=lambda r: r["seed"]) quota = {"real": (60, 70), "inject": (20, 30)} seen = {"real": 0, "inject": 0} for r in rows: group = "real" if r["kind"] == "real" else "inject" if r["label"] == "suboptimal": r["split"] = "suboptimal" continue if r["label"] == "sim_fault": r["split"] = "excluded" continue if group == "inject" and r["label"] == "success": r["split"] = "unused" # the release never happened continue a, b = quota[group] r["split"] = "train" if seen[group] < a else "validation" if seen[group] < b else "test" if r["label"] == "failure": seen[group] += 1 (root / "split.json").write_text(json.dumps(rows, indent=1)) count = {} for r in rows: key = f"{r['split']}/{'real' if r['kind'] == 'real' else 'injected'}/{r['label']}" count[key] = count.get(key, 0) + 1 for k in sorted(count): print(f"{k:40s} {count[k]}") types = {} for r in rows: if r["label"] == "failure": key = f"{'real' if r['kind'] == 'real' else 'injected'}/{r['failure_type']}" types[key] = types.get(key, 0) + 1 print("failure types:", dict(sorted(types.items(), key=lambda kv: -kv[1]))) print("total", len(rows), "episodes")