#!/usr/bin/env python3 """Is this dataset self-contained? Run it before shipping one. A recorded episode is numbers: generalised coordinates and contact patches keyed by shape index. Whether anyone else can turn those back into a scene depends on what travels with them. This rebuilds the scene from the dataset ALONE -- numpy and pandas, no Isaac Sim, no USD, no DexVerse, nothing from this repository -- and measures how far the recorded contact points land from the surface it rebuilt. Sub-millimetre means a recipient sees exactly what the physics saw. python tools/check_dataset.py datasets/cube It reports what is missing rather than guessing: meta/assets/ every collider, the joint tree, and the shape-index legend. Without it a reader cannot place a single body. meta/assets/source_assets/ the source USDs themselves, so the recipient needs none of the art this task was authored from. An asset that is not ours to redistribute says so in sources.json (`not_packaged`) and is not counted against the dataset. meta/task.bddl the task as a LIBERO-style BDDL problem, written on every --record since 2026-09-28. meta/rig/ the hand as built, for anything that needs skin weights or the MANO mapping. The scene rebuild does not need it. Datasets recorded before those existed can be backfilled by re-running the same task once with --record; the geometry depends on the task and the rig, not on the demo. This tool prints the exact command. """ from __future__ import annotations import argparse import glob import json import os import sys import numpy as np REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(REPO, "tools")) from contact_io import SIDECAR_DIR as _SIDECAR # noqa: E402 (numpy only) _BOX_F = np.array([[0, 1, 2], [0, 2, 3], [4, 6, 5], [4, 7, 6], [0, 4, 5], [0, 5, 1], [1, 5, 6], [1, 6, 2], [2, 6, 7], [2, 7, 3], [3, 7, 4], [3, 4, 0]]) _BOX_V = np.array([[-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]], dtype=float) def _read_obj(path): v, f = [], [] with open(path) as fh: for line in fh: if line.startswith("v "): v.append([float(x) for x in line.split()[1:4]]) elif line.startswith("f "): idx = [int(t.split("/")[0]) - 1 for t in line.split()[1:]] for k in range(1, len(idx) - 1): f.append([idx[0], idx[k], idx[k + 1]]) return np.array(v), np.array(f, dtype=int) def _point_tri_distance(P, T): """True distance from each point in P (n,3) to a triangle soup T (m,3,3). Barycentric test first, then the three edges. NOT min(plane, vertex): that shortcut reports ~0 for a point sitting in a large triangle's PLANE but metres outside the triangle, which turns this check into a rubber stamp. Copied from viz/demo_scene.py rather than imported, because the point of this tool is that a dataset can be checked with numpy and nothing else. """ A, B, C = T[:, 0], T[:, 1], T[:, 2] n = np.cross(B - A, C - A) n /= np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-12) v0, v1 = B - A, C - A d00 = np.einsum("ij,ij->i", v0, v0) d01 = np.einsum("ij,ij->i", v0, v1) d11 = np.einsum("ij,ij->i", v1, v1) den = d00 * d11 - d01 * d01 + 1e-20 edges = [(A, B - A), (B, C - B), (C, A - C)] elen = [np.einsum("ij,ij->i", e, e) + 1e-20 for _, e in edges] out = np.empty(len(P)) for i, p in enumerate(P): t = np.einsum("ij,ij->i", p - A, n) v2 = (p - t[:, None] * n) - A d20 = np.einsum("ij,ij->i", v2, v0) d21 = np.einsum("ij,ij->i", v2, v1) u = (d11 * d20 - d01 * d21) / den v = (d00 * d21 - d01 * d20) / den d = np.where((u >= 0) & (v >= 0) & (u + v <= 1), np.abs(t), np.inf) for (X, e), L2 in zip(edges, elen): sclamp = np.clip(np.einsum("ij,ij->i", p - X, e) / L2, 0.0, 1.0) d = np.minimum(d, np.linalg.norm(p - (X + sclamp[:, None] * e), axis=1)) out[i] = d.min() return out def _episode_meta(root: str, episode: int) -> dict: """The episode's line in meta/episodes.jsonl ({} when there is none).""" p = os.path.join(root, "meta", "episodes.jsonl") if os.path.exists(p): with open(p) as fh: for line in fh: if line.strip(): r = json.loads(line) if r.get("episode_index") == episode: return r return {} def rebuild(assets_dir: str, state: np.ndarray, ep_meta: dict | None = None): """World triangles of every collider for one observation.state row. ``ep_meta`` (the episode's line in meta/episodes.jsonl) puts welded roots at that episode's recorded anchor; without it they sit where the scene was built.""" from scene_assets import _rot, body_poses, load, weld_anchored bodies, shapes = load(assets_dir) if ep_meta is not None: bodies = weld_anchored(bodies, ep_meta, os.path.dirname(os.path.abspath(assets_dir))) poses = body_poses(bodies, state) soup = [] cache: dict = {} for sh in shapes["shapes"]: if sh["mesh"]: if sh["mesh"] not in cache: v, f = _read_obj(os.path.join(assets_dir, sh["mesh"])) cache[sh["mesh"]] = (v * np.asarray(sh["scale"]), f) v, f = cache[sh["mesh"]] elif sh["type"] == "BOX": v, f = _BOX_V * np.asarray(sh["scale"]), _BOX_F else: continue # sphere/capsule/plane: not meshed here st = np.asarray(sh["transform"]) bp = poses[sh["body"]] vv = np.stack([_rot(st[3:7], p) for p in v]) + st[:3] vw = np.stack([_rot(bp[3:7], p) for p in vv]) + bp[:3] soup.append(vw[f]) return (np.vstack(soup) if soup else np.zeros((0, 3, 3))), bodies, shapes #: Config keys that are bookkeeping, not how the episode was simulated. _BOOKKEEPING = {"record", "task_name", "randomize_seed", "from_config", "stop_file", "compile_contacts", "compile_episodes", "compile_out", "trace", "replay", "replay_log", "tune_file", "dump_model", "export_scene", "stop_after", "skip_hold_s", # collect_chain's per-session controls # where THIS machine's headset room sits relative to the sim (xr_local.json): # machine 1 -90, machine 2 0 (2026-10-28 merge); the recorded poses are sim-frame "xr_anchor_yaw", # how Kit's viewport was lit and rendered, not how anything was simulated "key_light_dir", "rtx", "shadows", "aa_mode", "ambient_light", "async_render"} #: Gains computed from the hand's inertia as measured at launch (kd_rot = #: 2*zeta*sqrt(kp_rot*I), I the hand's COMPOSITE inertia about the wrist: sum of #: m_k |p_k - p_wrist|^2 over the finger bodies, so it moves with the pose the #: fingers happen to be in at that moment). Launches differ by ~2e-5 relative #: (gear_mesh, 2026-09-29: 0.4289548 vs 0.4289471) and up to 2.3e-3 #: (pipe_push_fit_fixed, 2026-10-02: 0.4299472 vs 0.4289545, left hand only), #: past the 1e-6 every setting gets, so these alone are compared at 1 %. #: Nobody sets a gain 1 % off. _DERIVED_FROM_INERTIA = {"kd_rot", "wrist_kd_rot"} _DERIVED_RTOL = 1e-2 def _configs_alike(root: str, hashes: dict) -> tuple[bool, list[str]]: """Do these config snapshots hold the same settings? Keys one build did not have yet are not compared; floats agree to 1e-6 relative. Returns (alike, the keys that differed only by float noise).""" cfgs = [] for h in hashes: cp = os.path.join(root, "meta", "configs", f"{h}.json") if not os.path.exists(cp): return False, [] with open(cp) as fh: cfgs.append(json.load(fh)) def close(a, b, key=""): """Equal, or equal up to float noise -- recursively, because a derived gain can sit inside a nested setting (wrist_gains_by_hand[side].kd_rot).""" if isinstance(a, dict) and isinstance(b, dict): return a.keys() == b.keys() and all(close(a[k], b[k], k) for k in a) if isinstance(a, list) and isinstance(b, list): return len(a) == len(b) and all(close(x, y, key) for x, y in zip(a, b)) num = (int, float) if isinstance(a, num) and isinstance(b, num) and not isinstance(a, bool) \ and not isinstance(b, bool): if key in _DERIVED_FROM_INERTIA: return abs(a - b) <= _DERIVED_RTOL * max(abs(a), abs(b)) return abs(a - b) <= 1e-6 * max(abs(a), abs(b), 1.0) return a == b noise = set() for k in set.intersection(*(set(c) for c in cfgs)) - _BOOKKEEPING: vals = [c[k] for c in cfgs] if all(v == vals[0] for v in vals): continue if all(close(vals[0], v, k) for v in vals[1:]): noise.add(k) continue return False, [] return True, sorted(noise) def summarise(root: str) -> bool: """The WHOLE dataset: how many demos, and were they collected alike. The per-episode geometry check below answers "can a recipient rebuild this scene". It says nothing about how much data there is, which is the first thing anyone actually wants to know -- and nothing about whether the episodes belong together, which is the thing most likely to be quietly wrong. Both come out of meta/episodes.jsonl, which the collector already writes. """ p = os.path.join(root, "meta", "episodes.jsonl") if not os.path.exists(p): print(" episodes/ ❌ meta/episodes.jsonl MISSING — cannot say how " "many demos this is") return False eps = [] with open(p) as fh: for line in fh: line = line.strip() if line: eps.append(json.loads(line)) if not eps: print(" episodes/ none recorded yet") return True hz = 0.0 try: with open(os.path.join(root, "meta", "info.json")) as fh: hz = float((json.load(fh).get("collection_config") or {}) .get("physics_hz") or 0.0) except Exception: # noqa: BLE001 pass frames = sum(int(e.get("length", 0)) for e in eps) acc = sum(1 for e in eps if e.get("operator_verdict") == "accept") held = sum(1 for e in eps if (e.get("success_terms") or {}) .get("criterion_held_at_end")) dur = f", {frames / hz:.0f} s of sim at {hz:g} Hz" if hz else "" print(f" episodes/ {len(eps)} demos, {frames} frames{dur}") tasks = sorted({t for e in eps for t in (e.get("tasks") or [])}) print(f" task: {'; '.join(tasks) if tasks else '—'}") ok = True if acc != len(eps): print(f" {acc} accepted, {len(eps) - acc} NOT accepted " f"— a discarded demo should not be here at all") ok = False if held != len(eps): print(f" ⚠️ {len(eps) - held} did not still hold the " f"criterion at the end (saved anyway, which is the operator's " f"call — but they are not the same demo as the rest)") # 🔴 The one that quietly ruins a dataset: retuning mid-collection. Physics # that changed between episodes makes them incomparable, and nothing in the # frames themselves says so. hashes = {} for e in eps: hashes.setdefault(e.get("config_hash", "?"), []).append( e.get("episode_index")) same, noise = _configs_alike(root, hashes) if len(hashes) == 1: print(f" one config across all of them " f"({next(iter(hashes))})") elif same: # A new session writes a new snapshot even when nothing was retuned: # wrist_kd_rot is derived from the hand's measured inertia and moves # in the 7th digit between launches. Same values = collected alike. print(f" {len(hashes)} config snapshots, the same settings" + (f" (float noise only: {', '.join(noise)})" if noise else "")) else: print(f" ❌ {len(hashes)} DIFFERENT configs — these " f"episodes were not collected alike:") for h, idx in sorted(hashes.items(), key=lambda kv: -len(kv[1])): rng = f"{min(idx)}..{max(idx)}" if len(idx) > 1 else str(idx[0]) print(f" {h} {len(idx):3d} episode(s) [{rng}]") ok = False # A missing sidecar is a demo with no contact data, which is most of why # this dataset exists. npq = len(glob.glob(os.path.join(root, "data", "episode_*.parquet"))) nnz = len(glob.glob(os.path.join(root, _SIDECAR["hand-object"], "episode_*.npz"))) if not (npq == nnz == len(eps)): print(f" ❌ {len(eps)} in episodes.jsonl but {npq} " f"parquet and {nnz} contact file(s)") ok = False return ok def _source_assets(root: str) -> bool: """Did every asset that MAY travel actually travel? The scene rebuilds from the colliders alone, so this is not what makes a dataset replayable -- it is what makes it replayable WITHOUT fetching the art it was authored from. An asset barred by licence is reported, not counted against the dataset: nothing here can fix it and the recipient is told where to get it. """ adir = os.path.join(root, "meta", "assets") sp = os.path.join(adir, "sources.json") if not os.path.exists(sp): print(" source_assets/ — (no sources.json: recorded before asset " "provenance existed)") return True try: with open(sp) as fh: rows = (json.load(fh) or {}).get("assets") or [] except (OSError, ValueError) as exc: print(f" source_assets/ ❌ sources.json unreadable ({exc})") return False withheld = [r for r in rows if r.get("not_packaged")] packaged, missing = [], [] for r in rows: if r.get("not_packaged"): continue rel = r.get("package") if rel and os.path.exists(os.path.join(adir, rel)): packaged.append(r["asset"]) else: missing.append(r["asset"]) n_want = len(rows) - len(withheld) print(f" source_assets/ {len(packaged)}/{n_want} source assets packaged" + (f"; {len(withheld)} withheld by licence " f"({', '.join(r['asset'] for r in withheld)})" if withheld else "")) for r in withheld: print(f" {r['asset']}: {r['not_packaged']}") if missing: print(f" ❌ not packaged and not excused: " f"{', '.join(missing)}\n" f" re-record with --copy-source-assets (the " f"default), or say why in\n" f" tools/scene_assets.NON_REDISTRIBUTABLE") return False return True def main() -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("root") ap.add_argument("--episode", type=int, default=None, help="episode index (default: the first in meta/episodes.jsonl)") ap.add_argument("--frames", type=int, default=4, help="frames to check") ap.add_argument("--points", type=int, default=80, help="contacts per frame") a = ap.parse_args() root = os.path.expanduser(a.root) ok = True import pandas as pd if a.episode is None: # A dataset need not start at 0: rj45_insert's first ten were archived. a.episode = 0 ep_path = os.path.join(root, "meta", "episodes.jsonl") if os.path.exists(ep_path): with open(ep_path) as fh: idx = [json.loads(line)["episode_index"] for line in fh if line.strip()] if idx: a.episode = min(idx) pq = os.path.join(root, "data", f"episode_{a.episode:06d}.parquet") if not os.path.exists(pq): print(f"❌ no {pq}") return 1 ok = summarise(root) and ok df = pd.read_parquet(pq) state = np.stack(df["observation.state"].to_numpy()) print(f"\n episode {a.episode} (--episode to check another):") print(f" data/ {len(df)} frames, {state.shape[1]} state coords") if "wall_timestamp" in df and len(df) > 1: wall = float(df.wall_timestamp.iloc[-1] - df.wall_timestamp.iloc[0]) sim = float(df.timestamp.iloc[-1] - df.timestamp.iloc[0]) if wall > 0: print(f" timing/ {sim:.2f} simulation s / {wall:.2f} wall s = {sim / wall:.2f}x real time") if "contact_dropped_count" in df: dropped = df.contact_dropped_count.to_numpy() print(f" contacts/ {int(dropped.sum())} valid faces omitted by the recording cap " f"over {int((dropped > 0).sum())} frames") else: with open(os.path.join(root, "meta", "info.json")) as fh: info = json.load(fh) config = info.get("collection_config") or {} # info.json describes the latest session; older episodes name theirs. ep_path = os.path.join(root, "meta", "episodes.jsonl") if os.path.exists(ep_path): with open(ep_path) as fh: for line in fh: ep = json.loads(line) if line.strip() else {} if ep.get("episode_index") == a.episode and ep.get("config_hash"): cp = os.path.join(root, "meta", "configs", ep["config_hash"] + ".json") if os.path.exists(cp): with open(cp) as cf: config = json.load(cf) break cap = int(config.get("max_faces", 0)) if cap > 0 and (df.contact_count >= cap).any(): print(f" contacts/hand_obj/ WARNING: {int((df.contact_count >= cap).sum())}/{len(df)} " f"frames reached the legacy {cap}-face cap; patches may be incomplete. " "The original face count was not recorded.") cpath = os.path.join(root, _SIDECAR["hand-object"], f"episode_{a.episode:06d}.npz") z = np.load(cpath) if os.path.exists(cpath) else None if z is None: print(" contacts/hand_obj/ none for this episode") else: fr = sorted({int(k.split("_")[0]) for k in z.files}) print(f" contacts/hand_obj/ {len(fr)} frames with contact, " f"{int(df['contact_count'].sum())} patches") mjc = df["mj_contact_count"] if "mj_contact_count" in df else None if mjc is not None and (mjc >= 0).any(): print(f" contacts/ solver forces (mj_*) on {int((mjc > 0).sum())} frames, " f"{int(mjc[mjc > 0].sum())} solver contacts") else: print(" contacts/ no solver forces (mj_*): recorded before they existed, " "state-only, or --no-solver-contacts") assets = os.path.join(root, "meta", "assets") if not os.path.isdir(assets): task = "" try: with open(os.path.join(root, "meta", "info.json")) as fh: task = json.load(fh)["collection_config"].get("task", task) except Exception: # noqa: BLE001 pass print(" meta/assets/ ❌ MISSING — a recipient cannot place any body.\n" f" backfill: record one throwaway demo of the same task with " f"the same rig,\n then copy its meta/assets/ here:\n" f" collect_env.py --headless --task {task} --record /tmp/x --steps 200\n" f" cp -r /tmp/x/meta/assets {root}/meta/") ok = False else: ep_meta = _episode_meta(root, a.episode) T, bodies, shapes = rebuild(assets, state[0], ep_meta) nm = sum(1 for s in shapes["shapes"] if s["mesh"]) print(f" meta/assets/ {len(bodies['bodies'])} bodies, " f"{len(shapes['shapes'])} shapes ({nm} meshes), " f"{len(T)} triangles rebuilt from the dataset alone") if z is not None and len(T): import contact_io # tools/ is on sys.path, see the top fr = contact_io.frames_with_contact(z) pick = fr[::max(1, len(fr) // a.frames)][:a.frames] worst = 0.0 for f in pick: # The patch (and the solver's contacts) of frame f came out of the collision # pass BEFORE step f, i.e. the poses of observation.state[f-1]; state[f] is after # the step. Against state[f] a fast tool reads millimetres off (hammer_nail_fixed # 2026-10-03, hammer at 1.8 m/s: 3.43 mm vs 0.14 mm against state[f-1]). T, _b, _s = rebuild(assets, state[max(f - 1, 0)], ep_meta) _cf = contact_io.read(z, f, limit=a.points) if _cf is None: continue d = _point_tri_distance(_cf["c"], T) worst = max(worst, float(np.median(d))) mjs = "" if _cf.get("mj_pos") is not None and len(_cf["mj_pos"]): # The solver's points are the reduced set of the same # surface, so they sit on it too; and the net force says # whether the sign convention survived the trip. dm = _point_tri_distance(_cf["mj_pos"], T) fz = float(_cf["mj_force"].sum(axis=0)[2]) mjs = (f"; {len(dm)} solver contacts {np.median(dm) * 1e3:.2f} mm off, " f"net force on the object {fz:+.2f} N up") worst = max(worst, float(np.median(dm))) print(f" frame {f:6d}: contacts sit {np.median(d) * 1e3:5.2f} mm " f"from the rebuilt surface (max {d.max() * 1e3:.2f}){mjs}") if worst > 0.005: print(" ⚠️ more than a contact voxel — the geometry here is " "NOT what produced these contacts") ok = False # 🔴 ONE RIG PER HAND, checked against what the dataset says it recorded. # A bare isdir() reports "present" for a two-handed dataset carrying only # one of the two rigs -- and the missing hand then cannot be skinned or # exported at all, which is exactly the kind of quiet incompleteness this # tool exists to catch. rig = os.path.join(root, "meta", "rig") hands = [] try: with open(os.path.join(root, "meta", "info.json")) as fh: hands = [s for s in (json.load(fh).get("hands") or []) if s in ("left", "right")] except (OSError, ValueError, KeyError): pass if not os.path.isdir(rig): print(" meta/rig/ — (only needed for skin weights / MANO export)") elif len(hands) > 1: have = [s for s in hands if os.path.isdir(os.path.join(rig, s))] miss = [s for s in hands if s not in have] print(f" meta/rig/ {len(have)}/{len(hands)} hands " f"({', '.join(have) or 'none'})" + (f" ❌ MISSING {', '.join(miss)}" if miss else "")) if miss: ok = False else: print(" meta/rig/ present") for f in ("info.json", "episodes.jsonl", "tasks.jsonl", "scene.json"): if not os.path.exists(os.path.join(root, "meta", f)): print(f" meta/{f} ❌ MISSING") ok = False # The task, as a reader that speaks BDDL rather than this repo's JSON # wants it. Regenerating it needs tools/task_bddl.py, which a recipient # of the dataset alone does not have -- so its absence is a gap, not a # convenience. if os.path.exists(os.path.join(root, "meta", "task.bddl")): print(" meta/task.bddl present") else: print(" meta/task.bddl ❌ MISSING — regenerate with " "`python tools/task_bddl.py " f"{os.path.join(root, 'meta', 'task.json')} " f"-o {os.path.join(root, 'meta', 'task.bddl')}`") ok = False ok = _source_assets(root) and ok total = sum(os.path.getsize(p) for p in glob.glob(os.path.join(root, "**", "*"), recursive=True) if os.path.isfile(p)) print(f"\n {'✅ self-contained' if ok else '❌ NOT self-contained'} — " f"{total / 1e6:.0f} MB total") return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())