Download tools/convert_internal.py from koreashin/simcheongi: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/koreashin/simcheongi/resolve/main/tools/convert_internal.py
- Command line
-
hf download hf://koreashin/simcheongi/tools/convert_internal.py
-
curl -L -o convert_internal.py https://huggingface.co/koreashin/simcheongi/resolve/main/tools/convert_internal.py
13.9 kB
| #!/usr/bin/env python | |
| """Convert episodes of the internal collector format into 'simcheongi-bc/1' (docs/DATA_FORMAT.md). | |
| Internal format (one run directory): | |
| <run>/index.jsonl one row per episode {"id", ...} | |
| <run>/run_*.json optional, params.v_max (expert speed limit, default 0.6 m/s) | |
| <run>/episodes/<id>/decisions.npz per-decision arrays (frame_ticks, lidar, lidar_unknown, ultra, hist_rig, | |
| req_history*, ego_velocity, ego_acceleration, route_ahead*, cmd_c1, | |
| plan_expert, state, ...) | |
| <run>/episodes/<id>/decisions.jsonl per-decision expert debug fields -> reason codes | |
| <run>/episodes/<id>/frames/<tick:05d>.jpg 1280x720 frames | |
| <run>/episodes/<id>/obstacles.npz/.json optional (obstacle episodes): yield, block, people_state, ahead_hit, | |
| pred_hit, people radii | |
| A collector root with INDEX.json {"runs": [...], "train_ids": [...]} can be given with --roots (relative run paths are | |
| resolved against --index-base). | |
| Per-decision loss weight written to steps.npz 'weight' (the recipe of the released rounds; every factor optional): | |
| w = view 1, or 0 when --view-poses is given and the decision's heading differs > --view-max-deg (25) from | |
| every recorded camera pose within --view-radius (0.6 m) (renderer validity) | |
| x restart / person --restart-weight K on 'restart' decisions (|ego_velocity| < 0.1 m/s and the label moves | |
| > 0.5 m in 5 s and not 'person ahead'), else --person-weight K on 'person ahead' decisions (a | |
| present person's disc within 0.05 m of the robot footprint extended 2.0 m forward), else 1 | |
| x mask / stand 0 with --mask-static-yield on decisions whose label is a yield caused only by standing people | |
| (old expert labels), else --stand-weight K on decisions with a standing person in the 2 m box | |
| av3u recipe: older data --person-weight 2 --restart-weight 5 --mask-static-yield | |
| newer data --person-weight 2 --restart-weight 5 --stand-weight 3 | |
| reason_weight = 0 on obstacle decisions labelled yield or block (the reason head has no such class), else 1. | |
| python tools/convert_internal.py --runs /data/run_a,/data/run_b --out /data/bc_ab --person-weight 2 --restart-weight 5 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import shutil | |
| import sys | |
| import numpy as np | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from simcheongi import preprocess as P # noqa: E402 | |
| from simcheongi.data import FORMAT, hash_split # noqa: E402 | |
| FOOT_LEN, FOOT_HALF_W, FOOT_FWD = 0.45, 0.165, 0.0 # robot footprint (m) of the training simulator | |
| AHEAD_M, MARGIN_M = 2.0, 0.05 | |
| RESTART_V_MAX, RESTART_P5_MIN = 0.1, 0.5 | |
| COPY_KEYS = ("frame_ticks", "lidar", "lidar_unknown", "ultra", "hist_rig", "req_history", "req_history_velocity", | |
| "req_history_acceleration", "ego_velocity", "ego_acceleration", "route_ahead", "route_ahead_valid") | |
| # ------------------------------------------------------------------------------------------------ weights | |
| def disc_rect_dist(px, py, X, Y, TH, hl, hw, fwd=0.0): | |
| """distance (>= 0; 0 inside) from points to rectangles centred at (X + fwd along TH, Y), half sizes hl / hw.""" | |
| c, s = np.cos(TH), np.sin(TH) | |
| dx, dy = px - X, py - Y | |
| u = c * dx + s * dy - fwd | |
| v = -s * dx + c * dy | |
| ex = np.maximum(np.abs(u) - hl, 0.0) | |
| ey = np.maximum(np.abs(v) - hw, 0.0) | |
| return np.hypot(ex, ey) | |
| def ahead2(state, people_state, radii): | |
| """'person ahead': (D,) bool from robot states (D, >=3) world x, y, yaw, people (D, Np, 5) present, x, y, vx, vy.""" | |
| S = np.asarray(state, dtype=np.float64) | |
| PS = np.asarray(people_state, dtype=np.float64) | |
| R = np.asarray(radii, dtype=np.float64).reshape(-1) | |
| D = S.shape[0] | |
| flag = np.zeros(D, dtype=bool) | |
| if D == 0 or PS.ndim != 3 or PS.shape[1] == 0: | |
| return flag | |
| hl, hw, fwd = FOOT_LEN / 2 + AHEAD_M / 2, FOOT_HALF_W, FOOT_FWD + AHEAD_M / 2 | |
| for i in range(D): | |
| pres = PS[i, :, 0] > 0.5 | |
| if not pres.any(): | |
| continue | |
| d = disc_rect_dist(PS[i, pres, 1], PS[i, pres, 2], S[i, 0], S[i, 1], S[i, 2], hl, hw, fwd) - R[pres] | |
| flag[i] = float(np.min(d)) <= MARGIN_M | |
| return flag | |
| def static_only_yield(O): | |
| y = O["yield"].astype(bool) | |
| ps = O["people_state"] | |
| if ps.shape[1] == 0: | |
| return np.zeros(len(y), bool) | |
| static = (ps[:, :, 0] > 0.5) & (np.hypot(ps[:, :, 3], ps[:, :, 4]) < 0.05) | |
| hit = O["ahead_hit"] | O["pred_hit"] | |
| return y & hit.any(1) & ~(hit & ~static).any(1) | |
| def static_ahead2(O, a2): | |
| ps = O["people_state"] | |
| if ps.shape[1] == 0: | |
| return np.zeros(len(a2), bool) | |
| static = (ps[:, :, 0] > 0.5) & (np.hypot(ps[:, :, 3], ps[:, :, 4]) < 0.05) | |
| return a2 & static.any(1) | |
| class ViewDev: | |
| """min heading difference (deg) to the recorded camera poses within radius (180 when none).""" | |
| def __init__(self, rx, ry, ryaw, radius=0.6): | |
| self.rx, self.ry, self.ryaw = (np.asarray(v, dtype=np.float64) for v in (rx, ry, ryaw)) | |
| self.r = self.B = float(radius) | |
| kx, ky = np.floor(self.rx / self.B).astype(np.int64), np.floor(self.ry / self.B).astype(np.int64) | |
| self.buckets = {} | |
| for i, k in enumerate(zip(kx.tolist(), ky.tolist())): | |
| self.buckets.setdefault(k, []).append(i) | |
| self.buckets = {k: np.asarray(v) for k, v in self.buckets.items()} | |
| def __call__(self, x, y, yaw): | |
| kx, ky = int(np.floor(x / self.B)), int(np.floor(y / self.B)) | |
| cand = [self.buckets[k] for k in ((kx + a, ky + b) for a in (-1, 0, 1) for b in (-1, 0, 1)) if k in self.buckets] | |
| if not cand: | |
| return 180.0 | |
| ii = np.concatenate(cand) | |
| ii = ii[np.hypot(self.rx[ii] - x, self.ry[ii] - y) <= self.r] | |
| if not len(ii): | |
| return 180.0 | |
| return float(np.degrees(np.abs((self.ryaw[ii] - yaw + np.pi) % (2 * np.pi) - np.pi)).min()) | |
| def load_view_poses(path, radius): | |
| a = np.loadtxt(path, delimiter=",", skiprows=1, ndmin=2) | |
| if a.shape[1] >= 4: | |
| a = a[a[:, 3] > 0.5] | |
| return ViewDev(a[:, 0], a[:, 1], a[:, 2], radius) | |
| # ------------------------------------------------------------------------------------------------ conversion | |
| def run_vmax(run): | |
| for f in sorted(os.listdir(run)): | |
| if f.startswith("run_") and f.endswith(".json"): | |
| try: | |
| return float(json.load(open(os.path.join(run, f)))["params"]["v_max"]) | |
| except Exception: # noqa: BLE001 | |
| pass | |
| return P.V_MAX_DEFAULT | |
| def episode_weights(ed, z, a, vd, stats): | |
| D = len(z["frame_ticks"]) | |
| w = np.ones(D, np.float64) | |
| if vd is not None: | |
| st = z["state"] | |
| vdev = np.array([vd(float(x), float(y), float(t)) for x, y, t in st[:, :3]]) | |
| w = (vdev <= a.view_max_deg).astype(np.float64) | |
| stats["view_weight0"] += int((w == 0).sum()) | |
| rw = np.ones(D, np.float32) | |
| op = os.path.join(ed, "obstacles.npz") | |
| if not os.path.exists(op): | |
| return w.astype(np.float32), rw | |
| with np.load(op) as O: | |
| O = {k: O[k] for k in O.files} | |
| rw = np.where(O["yield"].astype(bool) | O["block"].astype(bool), 0.0, 1.0).astype(np.float32) | |
| stats["reason_masked"] += int((rw == 0).sum()) | |
| people = json.load(open(os.path.join(ed, "obstacles.json")))["obstacles"]["people"] | |
| radii = np.array([p["r"] for p in people], dtype=np.float64) | |
| a2 = ahead2(z["state"].astype(np.float64), O["people_state"].astype(np.float64), radii) | |
| if "ahead2" in O: | |
| assert np.array_equal(O["ahead2"].astype(bool), a2), f"{ed}: stored ahead2 differs from the recomputed flag" | |
| v = np.linalg.norm(z["ego_velocity"].astype(np.float64), axis=1) | |
| p5 = np.linalg.norm(z["plan_expert"][:, 49, :2].astype(np.float64), axis=1) | |
| restart = (v < RESTART_V_MAX) & (p5 > RESTART_P5_MIN) & ~a2 | |
| mult = np.where(restart, a.restart_weight, np.where(a2, a.person_weight, 1.0)) | |
| stats["ahead2"] += int(a2.sum()) | |
| stats["restart"] += int(restart.sum()) | |
| if a.mask_static_yield: | |
| m0 = static_only_yield(O) | |
| mult = np.where(m0, 0.0, mult) | |
| stats["static_yield_masked"] += int(m0.sum()) | |
| else: | |
| m0 = np.zeros(D, bool) | |
| if a.stand_weight != 1.0: | |
| su = static_ahead2(O, O["ahead2"].astype(bool) if "ahead2" in O else np.zeros(D, bool)) | |
| mult = np.where(~m0 & su, mult * a.stand_weight, mult) | |
| stats["stand_up"] += int((~m0 & su).sum()) | |
| return (w * mult).astype(np.float32), rw | |
| def link(src, dst, how): | |
| if how == "hardlink": | |
| try: | |
| os.link(src, dst) | |
| return | |
| except OSError: | |
| pass | |
| if how == "symlink": | |
| os.symlink(os.path.abspath(src), dst) | |
| return | |
| shutil.copyfile(src, dst) | |
| def convert_episode(run, eid, out_root, out_id, a, vd, vmax, stats): | |
| ed = os.path.join(run, "episodes", eid) | |
| with np.load(os.path.join(ed, "decisions.npz")) as z: | |
| z = {k: z[k] for k in z.files} | |
| D = len(z["frame_ticks"]) | |
| rows = [json.loads(l) for l in open(os.path.join(ed, "decisions.jsonl")) if l.strip()] \ | |
| if os.path.exists(os.path.join(ed, "decisions.jsonl")) else [] | |
| out = {k: z[k] for k in COPY_KEYS} | |
| out["cmd"] = z["cmd_c1"].astype(np.int8) | |
| out["plan"] = z["plan_expert"].astype(np.float32) | |
| out["reason"] = np.array([P.reason_code(rows[i] if i < len(rows) else {}, vmax) for i in range(D)], np.int64) | |
| out["weight"], out["reason_weight"] = episode_weights(ed, z, a, vd, stats) | |
| out["prev"] = (np.arange(D) - 1).astype(np.int32) | |
| od = os.path.join(out_root, "episodes", out_id) | |
| os.makedirs(os.path.join(od, "frames"), exist_ok=True) | |
| for tk in sorted(set(int(t) for t in z["frame_ticks"].ravel())): | |
| dst = os.path.join(od, "frames", f"{tk:05d}.jpg") | |
| if not os.path.exists(dst): | |
| link(os.path.join(ed, "frames", f"{tk:05d}.jpg"), dst, a.frames) | |
| np.savez(os.path.join(od, "steps.npz"), **out) | |
| stats["episodes"] += 1 | |
| stats["decisions"] += D | |
| stats["weight0"] += int((out["weight"] <= 0).sum()) | |
| return D | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("--runs", default="", help="comma list of run directories (index.jsonl + episodes/)") | |
| ap.add_argument("--roots", default="", help="comma list of collector roots with INDEX.json (runs + train_ids)") | |
| ap.add_argument("--index-base", default=".", help="base directory of relative run paths inside INDEX.json") | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--view-poses", default="", help="CSV x,y,yaw[,valid] of recorded camera poses (header row)") | |
| ap.add_argument("--view-max-deg", type=float, default=25.0) | |
| ap.add_argument("--view-radius", type=float, default=0.6) | |
| ap.add_argument("--person-weight", type=float, default=1.0) | |
| ap.add_argument("--restart-weight", type=float, default=1.0) | |
| ap.add_argument("--mask-static-yield", action="store_true") | |
| ap.add_argument("--stand-weight", type=float, default=1.0) | |
| ap.add_argument("--val-frac", type=float, default=0.0, help="episode share written as split 'val' (hash)") | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--frames", default="copy", choices=("copy", "hardlink", "symlink")) | |
| ap.add_argument("--max-episodes", type=int, default=0, help="per run (0 = all)") | |
| a = ap.parse_args() | |
| jobs = [] # (run, [ids] or None) | |
| for r in [x for x in a.runs.split(",") if x]: | |
| jobs.append((r, None)) | |
| for root in [x for x in a.roots.split(",") if x]: | |
| I = json.load(open(os.path.join(root, "INDEX.json"))) | |
| ids = set(I.get("train_ids") or []) or None | |
| for r in I["runs"]: | |
| jobs.append((r if os.path.isabs(r) else os.path.join(a.index_base, r), ids)) | |
| assert jobs, "--runs or --roots" | |
| vd = load_view_poses(a.view_poses, a.view_radius) if a.view_poses else None | |
| os.makedirs(os.path.join(a.out, "episodes"), exist_ok=True) | |
| stats = {k: 0 for k in ("episodes", "decisions", "weight0", "view_weight0", "ahead2", "restart", | |
| "static_yield_masked", "stand_up", "reason_masked")} | |
| index = [] | |
| for run, ids in jobs: | |
| vmax = run_vmax(run) | |
| rows = [json.loads(l) for l in open(os.path.join(run, "index.jsonl")) if l.strip()] | |
| tag = os.path.basename(os.path.normpath(run)) | |
| n = 0 | |
| for row in rows: | |
| eid = row["id"] | |
| if ids is not None and eid not in ids: | |
| continue | |
| if not os.path.exists(os.path.join(run, "episodes", eid, "decisions.npz")): | |
| continue | |
| out_id = f"{tag}__{eid}" | |
| D = convert_episode(run, eid, a.out, out_id, a, vd, vmax, stats) | |
| index.append({"id": out_id, "n": D, "split": hash_split(out_id, a.val_frac, a.seed)}) | |
| n += 1 | |
| if a.max_episodes and n >= a.max_episodes: | |
| break | |
| with open(os.path.join(a.out, "index.jsonl"), "w") as f: | |
| for r in index: | |
| f.write(json.dumps(r) + "\n") | |
| recipe = {k: getattr(a, k) for k in ("person_weight", "restart_weight", "mask_static_yield", "stand_weight", | |
| "view_max_deg", "view_radius")} | |
| recipe["view_poses"] = bool(a.view_poses) | |
| json.dump({"format": FORMAT, "frame_ext": ".jpg", "source": "internal collector format", "recipe": recipe, | |
| "stats": stats}, open(os.path.join(a.out, "dataset.json"), "w"), indent=1) | |
| print(json.dumps(stats)) | |
| if __name__ == "__main__": | |
| main() | |