"""依頼 399 の 1: 実機の記録 (so101f 30 回・so101g 7 回) の 空で閉じた所ごとに, 爪の高さ (机から) と 固定側の爪・動く爪とブロックの距離を MuJoCo (clear_345 と同じ場面) で出す. 比べる相手: so101g の学習に入った つかみ直しのお手本 14 本 (recover_v1 の成功) の 空の閉じ. アーム・カメラは動かさない. KIOXIA の記録・台帳・データセットは読むだけ. - 爪の間の点・ブロックの位置: 依頼 376 の lib_376 のまま (so101f は check_376/traj_376.npy をそのまま使う. so101g は同じ作り方で出す) - 閉じた・空: analyze_376 と同じ (爪の値が 20 より上から 12 未満. 20 コマ後に 5 未満 = 空. ブロックから水平 50 mm 以内) - 爪と机: 依頼 379 の jaw_table_379 と同じ (実際の関節 state を Scene.pose に入れ, 爪 (gripper・moving_jaw) と机の距離. 爪の値が初めて 20 を切ったコマ). 負 = 机にめり込む値 (実機では机に押し付けている) - 固定側の爪 (gripper の体)・動く爪 (moving_jaw) とブロック: 閉じる 30 コマ前から 閉じ始め (爪が 20 を切ったコマ) までの最小. ブロックは そのときの位置 (analyze_376.block_ref) と 最初のコマの向き (yaw_lib_343.read_block) /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python so101/check_399/explore_399.py """ import csv import json import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent SO101 = HERE.parent sys.path.insert(0, str(SO101 / "check_376")) sys.path.insert(0, str(SO101 / "ideal_var")) import analyze_376 as A # noqa: E402 import lib_376 as L # noqa: E402 KX = Path("/Volumes/KIOXIA/r2r2r-data") RECOVER = KX / "datasets/so101_redblock_box_ideal_var_v2_recover_v1" BEFORE = 30 # 閉じる前に見るコマ数 (1 秒) def first_frame(trial, key="desk"): import av fn = L.LOG / "so101" / trial / f"videos/observation.images.{key}/chunk-000/file-000.mp4" with av.open(str(fn)) as c: for f in c.decode(video=0): return f.to_ndarray(format="rgb24") def read_yaw(img_rgb, cam): import yaw_lib_343 as Y r, why = Y.read_block(np.ascontiguousarray(img_rgb[:, :, ::-1]), cam) return (None, why) if r is None else (float(r["yaw"]), "") def block_track(trial, cam, every=3): """explore_376.block_track と同じ (机のカメラを every コマおき. (コマ, x, y, 面積)). explore_376 は読み込むと動くので写した""" import av fn = L.LOG / "so101" / trial / "videos/observation.images.desk/chunk-000/file-000.mp4" out, first, last = [], None, None with av.open(str(fn)) as c: for i, f in enumerate(c.decode(video=0)): last = (i, f) if i % every: continue det, why = L.detect_block(f.to_ndarray(format="rgb24")) if i == 0: first = (det, why) if det: xy = L.px_to_desk(cam, [det["u"], det["v"]]) out.append([i, xy[0], xy[1], det["area"]]) i, f = last det, _ = L.detect_block(f.to_ndarray(format="rgb24")) if det and i % every: xy = L.px_to_desk(cam, [det["u"], det["v"]]) out.append([i, xy[0], xy[1], det["area"]]) return np.array(out).reshape(-1, 4), first def g_trials(arm, cam): """so101g の数えた 7 回 (progress_385.tsv の skip でない行) を traj_376 と同じ形で""" import pandas as pd rows = [r for r in csv.DictReader(open(L.LOG / "progress_385.tsv"), delimiter="\t") if r["result"] in ("success", "failure")] data = {} for r in rows: t = r["trial"] df = pd.read_parquet(L.LOG / "so101" / t / "data/chunk-000/file-000.parquet") Q = np.stack(df["observation.state"].to_numpy()).astype(float) Aa = np.stack(df["action"].to_numpy()).astype(float) trk, (b0, why0) = block_track(t, cam) xy0 = L.px_to_desk(cam, [b0["u"], b0["v"]]) if b0 else None data[t] = dict(Q=Q, A=Aa, P=arm.path(Q), b0=b0, row=dict(r), xy0=xy0, track=trk) print("so101g", r["n"], r["place"], t, r["result"], r["fail_reason"], len(Q), xy0, flush=True) return data def kind_of(g, i): """閉じた所 i の様子. so101g は空で閉じると 10〜20 コマで開き直すので (つかみ直しのお手本の外し方と同じ形), analyze_376 の「20 コマ後の値」だけでは決めない: 閉じてから 25 コマの最小が 5 未満 = 空, 20 コマ後まで 7 以上のまま = つかんだ""" n = len(g) w = g[i:min(i + 25, n)] if w.min() < 5: return "empty" if g[i:min(i + 21, n)].min() >= A.HELD_G: return "held" return "partial" def close_start(g, i): """閉じた所 i の前で 爪が初めて 20 を切ったコマ""" k = i while k > 0 and g[k - 1] < 20 and i - k < 60: k -= 1 return k def closed_len(g, i): """閉じてから 開き直す (20 より上) までのコマ数 (開かなければ None)""" j = next((k for k in range(i, len(g)) if g[k] > A.OPEN_G), None) return None if j is None else int(j - i) def closes(e): """ブロックの近く (水平 50 mm 以内) で閉じた所の一覧""" Q, P = e["Q"], e["P"] g, n = Q[:, 5], len(Q) at = A.block_ref(e["track"], e["b0"]["area"], e["xy0"]) B = np.array([at(i) for i in range(n)]) dist = np.linalg.norm(P[:, :2] - B, axis=1) out = [] for i in A.close_events(g): if dist[i] > A.NEAR_MM: continue kc = close_start(g, i) j1 = min(kc + 30, n - 1) out.append({"frame": int(i), "kc": int(kc), "kind": kind_of(g, i), "grip_after": float(g[min(i + 20, n - 1)]), "grip_min_25": float(g[i:min(i + 25, n)].min()), "closed_frames": closed_len(g, i), "rise_1s_mm": round(float(P[j1, 2] - P[kc, 2]), 1), "B": B[kc].tolist(), "rel": A.rel(P[kc], B[kc])[0].tolist(), "dist": float(dist[kc])}) return out def sim_close(S, Q, kc, bxy, yaw): """閉じ始めの 爪と机 (実際), 閉じる前 BEFORE コマの 固定側・動く爪とブロックの最小 (mm)""" import recover_380 as R380 sc, geo = S.sc, S.geo J = R380.Jaws() sc.block([1000, 1000], 0) sc.pose(Q[kc]) jt = float(geo.dist(geo.jaw, geo.table)) jt_m = float(geo.dist(J.moving, geo.table)) jt_f = float(geo.dist(J.fixed, geo.table)) jt_close = np.inf for k in range(kc, min(kc + 10, len(Q))): # 閉じる 10 コマの間の最小 sc.pose(Q[k]) jt_close = min(jt_close, float(geo.dist(geo.jaw, geo.table))) sc.block(list(bxy), yaw) f, m, ff, mf = np.inf, np.inf, None, None for k in range(max(kc - BEFORE, 0), kc + 1): sc.pose(Q[k]) a, b = geo.dist(J.fixed, geo.blk), geo.dist(J.moving, geo.blk) if a < f: f, ff = a, k if b < m: m, mf = b, k sc.pose(Q[kc]) f_kc, m_kc = geo.dist(J.fixed, geo.blk), geo.dist(J.moving, geo.blk) sc.block([1000, 1000], 0) return {"jaw_table": round(jt, 2), "jaw_table_min_10": round(jt_close, 2), "jaw_table_moving": round(jt_m, 2), "jaw_table_fixed": round(jt_f, 2), "fixed_block_min": round(float(f), 2), "fixed_frame_before": int(kc - ff), "moving_block_min": round(float(m), 2), "moving_frame_before": int(kc - mf), "fixed_block_at_close": round(float(f_kc), 2), "moving_block_at_close": round(float(m_kc), 2)} def demo_closes(arm, S, cam): """つかみ直しのお手本 14 本 (so101g の学習に入った recover_v1 の成功) の 最初の空の閉じ""" import pandas as pd labs = [x for x in json.loads((RECOVER / "episode_labels.json").read_text())["episodes"] if x["label"] == "success"] out = [] for lab in labs: ep = lab["episode_index"] df = pd.read_parquet(RECOVER / f"data/chunk-000/file-{ep:03d}.parquet") Q = np.stack(df["observation.state"].to_numpy()).astype(float) Aa = np.stack(df["action"].to_numpy()).astype(float) P, Pa = arm.path(Q), arm.path(Aa) b = np.asarray(lab["block_xy_mm"], float) g = Q[:, 5] ev = A.close_events(g) i = ev[0] kc = close_start(g, i) # 指令の 空の閉じ (指令の爪が初めて 20 を切ったコマ) ka = int(np.argmax((Aa[1:, 5] < 20) & (Aa[:-1, 5] >= 20))) + 1 r = {"episode_index": ep, "plan_index": lab["plan_index"], "request": lab["request"], "recover": lab["recover"], "yaw": lab["yaw"], "block_xy": b.tolist(), "kc": int(kc), "rel_state": A.rel(P[kc], b)[0].tolist(), "rel_sent": A.rel(Pa[ka], b)[0].tolist(), "grip_after": float(g[min(i + 20, len(g) - 1)]), "closed_frames": closed_len(g, i), "rise_1s_mm": round(float(P[min(kc + 30, len(P) - 1), 2] - P[kc, 2]), 1), **sim_close(S, Q, kc, b, lab["yaw"])} out.append(r) print("demo", ep, lab["plan_index"], r["recover"]["kind_ja"], np.round(r["rel_state"], 1), r["jaw_table"], r["fixed_block_min"], flush=True) return out def main(): import clear_345 as CL arm, cam, info = L.setup() S = CL.scene() T = np.load(SO101 / "check_376/traj_376.npy", allow_pickle=True).item() F = T["data"] G = g_trials(arm, cam) rows = [] for model, D in (("so101f", F), ("so101g", G)): for t, e in D.items(): r = e["row"] if r["result"] not in ("success", "failure"): continue yaw, why = read_yaw(first_frame(t), cam) if yaw is None: print("向きが読めない", t, why) cl = closes(e) for c in cl: c.update(sim_close(S, e["Q"], c["kc"], c["B"], 0.0 if yaw is None else yaw)) rows.append({"model": model, "trial": t, "n": int(r["n"]), "place": int(r["place"]), "result": r["result"], "fail_reason": r["fail_reason"], "yaw": yaw, "yaw_why": why, "block_xy0": np.round(e["xy0"], 1).tolist(), "closes": cl}) print(model, r["n"], r["place"], r["result"], [(c["kind"], round(c["jaw_table"], 1), c["fixed_block_min"], np.round(c["rel"], 0).tolist()) for c in cl], flush=True) demo = demo_closes(arm, S, cam) gtraj = {t: {k: v for k, v in e.items()} for t, e in G.items()} np.save(HERE / "traj_399_g.npy", {"info": info, "data": gtraj}, allow_pickle=True) (HERE / "closes_399.json").write_text(json.dumps({"made_by": "so101/check_399/explore_399.py (依頼 399 の 1)", "grasp_center": info, "trials": rows, "demo": demo}, ensure_ascii=False, indent=1) + "\n") print("[WROTE]", HERE / "closes_399.json") if __name__ == "__main__": main()