Add the submitted RoboDojo controller bundles: swap_blocks, make_kong, plug_in_charger, pour_by_language
Browse filesFiles changed (20)
- robodojo/make_kong/controller.pyAdded+596
- robodojo/make_kong/scene.pyAdded+78
- robodojo/make_kong/triangulation.pyAdded+149
- robodojo/make_kong/vision.pyAdded+45
- robodojo/plug_in_charger/controller.pyAdded+70
- robodojo/plug_in_charger/ctl.pyAdded+372
- robodojo/plug_in_charger/ctl2.pyAdded+808
- robodojo/plug_in_charger/geom3.pyAdded+62
- robodojo/plug_in_charger/kin.pyAdded+119
- robodojo/plug_in_charger/kin_model.jsonAdded+158
- robodojo/plug_in_charger/motion.pyAdded+64
- robodojo/plug_in_charger/perception.pyAdded+151
- robodojo/plug_in_charger/robot.pyAdded+136
- robodojo/plug_in_charger/tilt.pyAdded+33
- robodojo/pour_by_language/controller.pyAdded+290
- robodojo/pour_by_language/motion.pyAdded+295
- robodojo/pour_by_language/perception.pyAdded+165
- robodojo/swap_blocks/README.mdAdded+7
- robodojo/swap_blocks/controller.pyAdded+267
- robodojo/swap_blocks/operate.pyAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596"""make_kong controller.
Wait for the opponent (franka) to knock one back-row tile face-up, push the matchingfront-row group face-up, then pick the face-down pile tile with the left arm, hand itto the right arm, stand it upright and place it at the right end of the row.
Everything that varies (which tile is knocked, whether pushes/grasps worked) is readfrom cam_high and the measured robot state. Scene constants are static config facts(task config make_kong.yml, mahjong asset metadata), see scene.py."""import osimport sysimport jsonimport timeimport traceback
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))if HERE not in sys.path: sys.path.insert(0, HERE)
import robodojo_toolkit as tk # noqa: E402from scene import * # noqa: E402,F401,F403import vision # noqa: E402
ARM_I = {"left": 0, "right": 1}JSL = {"left": slice(0, 6), "right": slice(7, 13)}GJ = {"left": 6, "right": 13} # gripper column in 14-D joint rowsGE = {"left": 7, "right": 15} # gripper column in 16-D native EEF rows
def qmul(a, b): w1, x1, y1, z1 = a w2, x2, y2, z2 = b return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])
def qaxis(axis, ang): axis = np.asarray(axis, float) / np.linalg.norm(axis) return np.r_[np.cos(ang / 2), np.sin(ang / 2) * axis]
def qrot(q, v): """Rotate vector v by wxyz quaternion q.""" p = np.r_[0.0, v] qc = np.array([q[0], -q[1], -q[2], -q[3]]) return qmul(qmul(q, p), qc)[1:]
def push_quat(pitch_deg): """Home orientation (fingers forward +y, closing along x) pitched down.""" return qmul(qaxis([1, 0, 0], -np.radians(pitch_deg)), Q_HOME)
def push_link6(x, ytip, ztip, pitch_deg): th = np.radians(pitch_deg) return np.array([x, ytip - TIP_LEN * np.cos(th), ztip + TIP_LEN * np.sin(th)])
class EpisodeOver(Exception): pass
class Bot: def __init__(self, ctx): self.ctx = ctx self.out = getattr(ctx, "output_dir", None) or "/tmp/make_kong_out" os.makedirs(self.out, exist_ok=True) self.logf = open(os.path.join(self.out, "controller_log.txt"), "a") self.t0 = time.time() self.planner = tk.shared_planner() self.meta, self.img = None, {} self.observe() self.jcmd = np.array(self.meta["states"], float) # last commanded joint row self.g = {"left": float(self.jcmd[6]), "right": float(self.jcmd[13])}
# ------------------------------------------------------------------ basics def log(self, *a): s = "[%6.1fs step %s] " % (time.time() - self.t0, self.meta.get("step_id") if self.meta else "?") + \ " ".join(str(x) for x in a) print(s, flush=True) try: self.logf.write(s + "\n") self.logf.flush() except Exception: pass
def save(self, tag, cams=("cam_high",)): try: from PIL import Image for c in cams: if c in self.img: Image.fromarray(self.img[c]).save(os.path.join(self.out, "%03d_%s_%s.png" % (self.step, tag, c))) except Exception as e: # never let logging break control self.log("save failed", e)
@property def step(self): return int(self.meta.get("step_id") or 0)
@property def states(self): return np.array(self.meta["states"], float)
def pos(self, arm): return np.array(self.meta["eef_positions"][ARM_I[arm]], float)
def quat(self, arm): return np.array(self.meta["eef_quaternions_wxyz"][ARM_I[arm]], float)
def grip_meas(self, arm): return float(self.meta["states"][GJ[arm]])
def _update(self, reply): meta, img = tk.parse_reply(reply) self.meta, self.img = meta, img if tk.episode_ended(reply): raise EpisodeOver()
def observe(self): self._update(self.ctx.call("robodojo_observe"))
def _send(self, rows): rows = np.asarray(rows, float) if self.step + len(rows) > STEP_LIMIT: rows = rows[:max(0, STEP_LIMIT - self.step)] if not len(rows): raise EpisodeOver() tool = "robodojo_step" if rows.shape[1] == 14 else "robodojo_step_ee" for s in range(0, len(rows), 50): self._update(self.ctx.call(tool, actions=rows[s:s + 50].tolist()))
# --------------------------------------------------------------- joint rows def run_joint(self, rows, ramp=None): """rows: N x 14. Gripper columns are forced to the commanded openings; ramp = {arm: target} ramps that gripper linearly over the rows.""" rows = np.array(rows, float).reshape(-1, 14) n = len(rows) for arm in ("left", "right"): if ramp and arm in ramp: rows[:, GJ[arm]] = np.linspace(self.g[arm], ramp[arm], n + 1)[1:] self.g[arm] = float(ramp[arm]) else: rows[:, GJ[arm]] = self.g[arm] rows[:, [6, 13]] = np.clip(rows[:, [6, 13]], 0.0, 1.0) self._send(rows) self.jcmd = rows[-1].copy()
def arm_rows(self, arm, joint_list): """Joint rows moving one arm through joint_list, the other arm holding its command.""" rows = [] for j in joint_list: r = self.jcmd.copy() r[JSL[arm]] = j rows.append(r) return np.array(rows)
def hold(self, n=1): self.run_joint(np.repeat(self.jcmd[None], n, axis=0))
def gripper(self, arm, opening, n=8): self.run_joint(np.repeat(self.jcmd[None], n, axis=0), ramp={arm: opening})
# ----------------------------------------------------------------- planner def plan(self, arm, p, q, grip=None, tries=None): """Collision-aware (robot + table only) free-space move; tries fallback waypoints.""" targets = [(p, q)] if tries is None else tries for (pp, qq) in targets: state = self.jcmd.copy() state[JSL[arm]] = self.states[JSL[arm]] state[GJ[arm]] = self.g[arm] try: r = self.planner.plan(arm, state.tolist(), {"position": list(map(float, pp)), "quaternion_wxyz": list(map(float, qq))}, gripper_opening=grip) except Exception as e: self.log("plan exception", e) continue if r.get("status") != "Success": self.log("plan failed", arm, np.round(pp, 3), r.get("reason")) continue acts = np.array(r["actions"], float) other = "right" if arm == "left" else "left" acts[:, JSL[other]] = self.jcmd[JSL[other]] self.run_joint(acts, ramp=None if grip is None else {arm: grip}) err = tk.pose_error(self.meta, arm, {"position": list(pp), "quaternion_wxyz": list(qq)}) self.log("plan ok", arm, np.round(pp, 3), "rows", len(acts), "err", np.round(err, 4)) return True return False
def plan_rows(self, arm, tries): """Plan (without executing) through fallback targets; returns this arm's joint rows or None.""" for (pp, qq) in tries: state = self.jcmd.copy() state[JSL[arm]] = self.states[JSL[arm]] state[GJ[arm]] = self.g[arm] try: r = self.planner.plan(arm, state.tolist(), {"position": list(map(float, pp)), "quaternion_wxyz": list(map(float, qq))}) except Exception as e: self.log("plan exception", e) continue if r.get("status") == "Success": self.log("planned", arm, np.round(pp, 3), "rows", len(r["actions"])) return np.array(r["actions"], float)[:, JSL[arm]] self.log("plan failed", arm, np.round(pp, 3), r.get("reason")) return None
def run_parallel(self, arm_joint_rows, ramp=None): """Execute per-arm joint trajectories simultaneously (shorter ones hold their last row).""" n = max(len(v) for v in arm_joint_rows.values()) rows = np.repeat(self.jcmd[None], n, axis=0) for arm, js in arm_joint_rows.items(): js = np.asarray(js, float) rows[:, JSL[arm]] = np.vstack([js, np.repeat(js[-1:], n - len(js), axis=0)]) self.run_joint(rows, ramp=ramp)
def plan_joint_goal(self, arm, pp, qq, grip=None): """Plan to a pose and return (rows, final_joints) without executing.""" state = self.jcmd.copy() state[JSL[arm]] = self.states[JSL[arm]] state[GJ[arm]] = self.g[arm] r = self.planner.plan(arm, state.tolist(), {"position": list(map(float, pp)), "quaternion_wxyz": list(map(float, qq))}, gripper_opening=grip) if r.get("status") != "Success": return None, None acts = np.array(r["actions"], float) return acts, acts[-1][JSL[arm]].copy()
# -------------------------------------------------------------- native EEF def ee_path(self, arm, poses, grip=None, ramp_rows=None): """Native IK path for one arm through [(p, q), ...]; other arm keeps its measured pose.""" wps = [{arm: {"position": list(map(float, p)), "quaternion_wxyz": list(map(float, q))}} for p, q in poses] rows = np.array(tk.ee_rows(self.meta, wps), float) other = "right" if arm == "left" else "left" rows[:, GE[other]] = self.g[other] if grip is None: rows[:, GE[arm]] = self.g[arm] else: n = len(rows) if ramp_rows is None else min(ramp_rows, len(rows)) ramp = np.full(len(rows), float(grip)) ramp[:n] = np.linspace(self.g[arm], grip, n + 1)[1:] rows[:, GE[arm]] = ramp self.g[arm] = float(grip) rows[:, [7, 15]] = np.clip(rows[:, [7, 15]], 0.0, 1.0) self._send(rows) self.jcmd[JSL[arm]] = self.states[JSL[arm]] self.jcmd[JSL[other]] = self.states[JSL[other]] self.jcmd[6], self.jcmd[13] = self.g["left"], self.g["right"]
def ee_line(self, arm, p_to, q=None, step=0.01, extra=0, grip=None): p0 = self.pos(arm) p1 = np.asarray(p_to, float) q = self.quat(arm) if q is None else np.asarray(q, float) n = max(1, int(np.ceil(np.linalg.norm(p1 - p0) / step))) poses = [(p0 + min(1.0, k / n) * (p1 - p0), q) for k in range(1, n + 1 + extra)] self.ee_path(arm, poses, grip=grip) err = tk.pose_error(self.meta, arm, {"position": list(p1), "quaternion_wxyz": list(q)}) return err
# ============================================================================ phasesdef wait_for_discard(bot): """Hold at home while the franka discards; return the knocked back-tile index.""" img0 = bot.img["cam_high"] g0 = vision.back_green(img0) bot.log("initial back-tile green", np.round(g0, 2)) bot.save("start", ("cam_high",)) last, stable, cand = None, 0, None while bot.step < WAIT_MAX_STEPS: bot.hold(WAIT_POLL) im = bot.img["cam_high"] g = vision.back_green(im) fr = vision.franka_change(img0, im) ratio = g / np.maximum(g0, 0.05) order = np.argsort(ratio) cand = int(order[0]) ok = ratio[cand] < 0.35 and ratio[order[1]] > 0.6 and fr < FRANKA_BACK_FRAC bot.log("wait g", np.round(g, 2), "franka", round(fr, 4), "cand", cand, "ok", ok) if ok and cand == last: stable += 1 else: stable = 1 if ok else 0 last = cand if ok else None if stable >= 2: break if cand is None: cand = 0 bot.save("discarded", ("cam_high",)) bot.log("knocked back tile", cand, "x", BACK_X[cand], "-> group", BACK_GROUP[cand]) return BACK_GROUP[cand]
def push_candidates(arm, group): if arm == "left": return [20, 30, 12] if group == 0 else [12, 20, 30] return [12, 20, 30]
def densify(start, js, max_jump=MAX_ROW_JUMP): """Insert joint-space interpolation rows so no joint moves more than max_jump per row.""" out, prev = [], np.asarray(start, float) for j in js: n = max(1, int(np.ceil(np.max(np.abs(j - prev)) / max_jump))) for k in range(1, n + 1): out.append(prev + (j - prev) * k / n) prev = j return out
def build_push(bot, arm, xs, pitch, seed, deep=0.0): """IK joint lists for pushing each tile in xs. Returns per-tile dict or None.""" q = push_quat(pitch) out = [] s = np.array(seed, float) prev_x = None for x in xs: seg = {} lat = [] if prev_x is not None: for k in range(1, PUSH_LAT_ROWS + 1): xx = prev_x + (x - prev_x) * k / PUSH_LAT_ROWS lat.append(push_link6(xx, PUSH_Y0, PUSH_ZTIP, pitch)) fwd = [push_link6(x, y, PUSH_ZTIP, pitch) for y in np.arange(PUSH_Y0 + PUSH_DY_FWD, PUSH_Y1 + deep + 1e-9, PUSH_DY_FWD)] ys_back = np.linspace(PUSH_Y1 + deep, PUSH_Y0, int(np.ceil((PUSH_Y1 + deep - PUSH_Y0) / PUSH_DY_BACK)) + 1)[1:] back = [push_link6(x, y, PUSH_ZTIP, pitch) for y in ys_back] for name, pts in (("lat", lat), ("fwd", fwd), ("back", back)): seg_start = s.copy() js = [] for p in pts: j, info = tk.ik(arm, s.tolist(), {"position": list(map(float, p)), "quaternion_wxyz": list(q)}) j = np.array(j, float) if not info.get("converged") or np.max(np.abs(j - s)) > IK_MAX_JUMP: return None js.append(j) s = j seg[name] = densify(seg_start, js) seg["x"] = x out.append(seg) prev_x = x return out
def tile_fallen(bot, x): return vision.front_fallen_score(bot.img["cam_high"], x)
def find_push(bot, arm, group, xs): """First pitch whose plan to the pre pose, descent and push path are all feasible. Returns (pitch, plan_rows, descend_joints, segments) or None.""" for pitch in push_candidates(arm, group): q = push_quat(pitch) pre = push_link6(xs[0], PUSH_Y0, PUSH_ZTIP + PUSH_PRE_DZ, pitch) rows, jf = bot.plan_joint_goal(arm, pre, q) if rows is None: bot.log("push pre-plan failed pitch", pitch) continue # descend from the pre pose (PUSH_PRE_DZ above) to the push height s = jf down = [] for k in range(1, 4): p = push_link6(xs[0], PUSH_Y0, PUSH_ZTIP + PUSH_PRE_DZ * (1 - k / 3), pitch) j, info = tk.ik(arm, s.tolist(), {"position": list(map(float, p)), "quaternion_wxyz": list(q)}) j = np.array(j, float) if not info.get("converged") or np.max(np.abs(j - s)) > IK_MAX_JUMP: down = None break down.append(j) s = j if down is None: bot.log("push descend IK failed pitch", pitch) continue segs = build_push(bot, arm, xs, pitch, s) if segs is None: bot.log("push path IK failed pitch", pitch) continue return pitch, rows, down, segs return None
def push_group(bot, group): xs = list(GROUP_X[group]) arm = "left" if group in (0, 1) else "right" if arm == "right": xs = xs[::-1] before = [tile_fallen(bot, x) for x in xs] bot.log("push group", group, "arm", arm, "xs", xs, "white-before", np.round(before, 2)) found = find_push(bot, arm, group, xs) if found is None: bot.log("NO push plan found") return None pitch, plan_rows, down, segs = found bot.log("push pitch", pitch) other = "right" if arm == "left" else "left" plan_rows[:, JSL[other]] = bot.jcmd[JSL[other]] # known-feasible way back: joints before the approach, the approach rows, the pre-pose joints bot.push_return = {"arm": arm, "start": bot.jcmd[JSL[arm]].copy(), "approach": plan_rows[:, JSL[arm]].copy()} bot.run_joint(plan_rows, ramp={arm: 0.0}) bot.run_joint(bot.arm_rows(arm, down)) for i, seg in enumerate(segs): if seg["lat"]: bot.run_joint(bot.arm_rows(arm, seg["lat"])) bot.run_joint(bot.arm_rows(arm, seg["fwd"])) bot.run_joint(bot.arm_rows(arm, seg["back"])) sc = tile_fallen(bot, seg["x"]) bot.log("pushed x", seg["x"], "white", round(sc, 2)) if sc < FALLEN_WHITE: bot.log("tile not down; retry deeper") redo = build_push(bot, arm, [seg["x"]], pitch, bot.jcmd[JSL[arm]], deep=PUSH_RETRY_DEEP) if redo: bot.run_joint(bot.arm_rows(arm, redo[0]["fwd"])) bot.run_joint(bot.arm_rows(arm, redo[0]["back"])) bot.log("retry white", round(tile_fallen(bot, seg["x"]), 2)) bot.save("pushed", ("cam_high",)) # lift the pushing arm clear of the row before any free-space planning s = bot.jcmd[JSL[arm]].copy() q = push_quat(pitch) lift = [] x_last = segs[-1]["x"] for k in range(1, 5): p = push_link6(x_last, PUSH_Y0 - 0.01 * k, PUSH_ZTIP + PUSH_LIFT * k / 4, pitch) j, info = tk.ik(arm, s.tolist(), {"position": list(map(float, p)), "quaternion_wxyz": list(q)}) j = np.array(j, float) if not info.get("converged"): break lift.append(j) s = j if lift: bot.run_joint(bot.arm_rows(arm, lift)) res = [round(tile_fallen(bot, x), 2) for x in GROUP_X[group]] bot.log("group white after", res) allx = [x for gg in GROUP_X for x in gg] bot.log("all front white", [round(tile_fallen(bot, x), 2) for x in allx]) return arm
def retreat_rows(bot): """Pushing arm back to its pre-push joints: interpolate to the push pre pose, then the approach reversed.""" pr = getattr(bot, "push_return", None) if pr is None: return None, None arm = pr["arm"] back = pr["approach"][::-1] rows = densify(bot.jcmd[JSL[arm]], [back[0]]) + list(back[1:]) + [pr["start"]] return arm, np.array(rows)
def pick_target(bot, push_arm): approach = [([PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L), ([PILE_X + 0.05, PILE_Y - 0.05, PICK_APPROACH_Z + 0.08], Q_DOWN_L)] rarm, rrows = retreat_rows(bot) if rarm == "left": bot.run_joint(bot.arm_rows("left", rrows)) bot.log("left retreated", np.round(bot.pos("left"), 3)) left = bot.plan_rows("left", approach) if left is None: bot.plan("left", None, None, tries=[(HOME_POSE["left"], Q_HOME)]) left = bot.plan_rows("left", approach) if left is None: bot.log("pick approach plan failed") return False moves = {"left": left} if rarm == "right": moves["right"] = rrows bot.run_parallel(moves, ramp={"left": 1.0}) bot.log("pick approach done; left", np.round(bot.pos("left"), 3), "right", np.round(bot.pos("right"), 3)) if np.linalg.norm(bot.pos("left")[:2] - [PILE_X, PILE_Y]) > 0.01: bot.ee_line("left", [PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L, step=0.01, extra=2) bot.save("pick_above", ("cam_high", "cam_left_wrist")) for attempt in range(2): z = PICK_GRASP_Z - 0.004 * attempt err = bot.ee_line("left", [PILE_X, PILE_Y, z], Q_DOWN_L, step=0.0045, extra=1) bot.log("pick descended err", np.round(err, 4), "pos", np.round(bot.pos("left"), 4)) bot.gripper("left", 0.0, n=8) bot.hold(2) gm = bot.grip_meas("left") bot.log("pick grip measured", round(gm, 3)) bot.save("pick_closed", ("cam_left_wrist",)) if gm > GRIP_HOLD_MIN_LEN: bot.ee_line("left", [PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L, step=0.0045) gm = bot.grip_meas("left") bot.log("lifted, grip", round(gm, 3)) if gm > GRIP_HOLD_MIN_LEN: return True bot.log("grasp miss; reopening") bot.gripper("left", 1.0, n=6) bot.ee_line("left", [PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L, step=0.01) return False
def handover(bot): ok = bot.plan("left", HO_LEFT, Q_DOWN_L, grip=0.0, tries=[(HO_LEFT, Q_DOWN_L), ([HO_LEFT[0] - 0.05, HO_LEFT[1], HO_LEFT[2] + 0.05], Q_DOWN_L)]) if not ok: return False if np.linalg.norm(bot.pos("left") - HO_LEFT) > 0.005: bot.ee_line("left", HO_LEFT, Q_DOWN_L, step=0.01, extra=2) tile_z = bot.pos("left")[2] - GRASP_CENTER_BELOW_L6 tile_x = bot.pos("left")[0] tile_y = bot.pos("left")[1] pre = [tile_x + HO_RIGHT_PRE_DX, tile_y, tile_z + HO_RIGHT_DZ] fin = [tile_x + HO_RIGHT_DX, tile_y, tile_z + HO_RIGHT_DZ] ok = bot.plan("right", pre, Q_MX, grip=1.0, tries=[(pre, Q_MX), ([pre[0] + 0.05, pre[1] - 0.05, pre[2] + 0.05], Q_MX)]) if not ok: return False bot.ee_line("right", fin, Q_MX, step=0.004, extra=1) bot.save("ho_right_in", ("cam_high", "cam_right_wrist")) bot.gripper("right", 0.0, n=8) bot.hold(1) gm = bot.grip_meas("right") bot.log("handover right grip", round(gm, 3)) if gm < GRIP_HOLD_MIN_WID: bot.log("right grasp miss") return False bot.gripper("left", 1.0, n=6) lp = bot.pos("left") bot.ee_line("left", [lp[0], lp[1], lp[2] + 0.06], Q_DOWN_L, step=0.01) gm = bot.grip_meas("right") bot.log("after left release, right grip", round(gm, 3)) bot.save("ho_done", ("cam_high", "cam_right_wrist")) ok = bot.plan("left", LEFT_PARK, Q_DOWN_L, grip=1.0, tries=[(LEFT_PARK, Q_DOWN_L), ([-0.2, -0.3, 1.15], Q_DOWN_L), ([-0.25, -0.35, 1.0], Q_HOME)]) if not ok: bot.log("left park failed; lifting left instead") lp = bot.pos("left") bot.ee_line("left", [lp[0] - 0.10, lp[1] - 0.05, lp[2] + 0.02], Q_DOWN_L, step=0.01) return gm >= GRIP_HOLD_MIN_WID
def rotate_and_place(bot): p6 = bot.pos("right") q6 = bot.quat("right") xaxis = qrot(q6, [1.0, 0.0, 0.0]) tip = p6 + TIP_LEN * xaxis bot.log("rotate about tip", np.round(tip, 4)) poses = [] for k in range(1, ROT_ROWS + 1): phi = np.radians(90.0 * k / ROT_ROWS) pos = tip + TIP_LEN * np.array([np.cos(phi), 0.0, np.sin(phi)]) + np.array([0, 0, ROT_LIFT * k / ROT_ROWS]) poses.append((pos, qmul(qaxis([0, 1, 0], -phi), Q_MX))) poses += [poses[-1]] * 2 bot.ee_path("right", poses) gm = bot.grip_meas("right") bot.log("rotated; right grip", round(gm, 3), "pos", np.round(bot.pos("right"), 4)) bot.save("rotated", ("cam_high", "cam_right_wrist")) place_x = GOAL_X + PLACE_DX bot.ee_line("right", [place_x, GOAL_Y, PLACE_ABOVE_Z], Q_DOWN_R, step=0.015, extra=1) err = bot.ee_line("right", [place_x, GOAL_Y, PLACE_Z], Q_DOWN_R, step=0.005, extra=2) bot.log("placed err", np.round(err, 4), "pos", np.round(bot.pos("right"), 4)) bot.save("placed", ("cam_high", "cam_right_wrist")) bot.gripper("right", 1.0, n=6) rp = bot.pos("right") bot.ee_line("right", [rp[0], rp[1], rp[2] + 0.03], Q_DOWN_R, step=0.01) bot.save("released", ("cam_high", "cam_right_wrist")) return True
def run_task(bot): group = wait_for_discard(bot) push_arm = push_group(bot, group) if not pick_target(bot, push_arm): bot.log("pick failed") return if not handover(bot): bot.log("handover failed") return rotate_and_place(bot) bot.hold(5) bot.log("done")
def main(ctx): bot = None try: bot = Bot(ctx) run_task(bot) except EpisodeOver: if bot: bot.log("episode over") except Exception: msg = traceback.format_exc() if bot: bot.log("EXCEPTION", msg) else: print(msg, flush=True) finally: if bot: bot.log("final step", bot.step)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778"""Static facts for make_kong. Sources:- task config make_kong.yml: all object xlim/ylim are single values (no layout randomization); only the knocked back tile (push label) is random per episode.- mahjong asset metadata: tile extents 0.0449 (x) x 0.0647 (y) x 0.0328 (z).- make_kong.py: success = matching group z-up <30 deg, other 9 y-up <7 deg, mahjong9_0 y-up <7 deg within 0.015 m of (0.319, -0.15), all grippers open; 600-step limit.- robot geometry (X5): fingertip 0.154 m along link6 x, closing along link6 y; home link6 quat.Motion constants below were verified in the manual episode (memory/PROGRESS.md)."""import numpy as np
STEP_LIMIT = 600TABLE_Z = 0.765TILE_W, TILE_H, TILE_T = 0.0449, 0.0647, 0.0328
# front row (straight_front, y = -0.15): groups 0..3 then the mahjong4 pairFRONT_Y = -0.15GROUP_X = [[-0.325, -0.279, -0.233], [-0.187, -0.141, -0.095], [-0.049, -0.003, 0.043], [0.089, 0.135, 0.181]]PAIR_X = [0.227, 0.273]# back row (opponent, y = 0.05): mahjong5..8 at these x, matching group0..3BACK_Y = 0.05BACK_X = [0.0, 0.046, -0.046, -0.092]BACK_GROUP = [0, 1, 2, 3]# pile: other0 at (-0.4, -0.05) with the face-down target mahjong9_0 on topPILE_X, PILE_Y = -0.4, -0.05PILE_TOP_Z = TABLE_Z + 2 * TILE_TGOAL_X, GOAL_Y = 0.319, -0.15
# robotTIP_LEN = 0.154Q_HOME = np.array([0.7071068, 0.0, 0.0, 0.7071068]) # fingers +y, closing along xQ_DOWN_L = np.array([0.5, -0.5, 0.5, 0.5]) # fingers down, closing along world xQ_MX = np.array([0.0, 0.0, 0.0, 1.0]) # fingers -x, closing along world yQ_DOWN_R = np.array([0.0, 0.7071068, 0.0, -0.7071068]) # fingers down, closing along world y
# waiting for the discardWAIT_POLL = 4WAIT_MAX_STEPS = 160FRANKA_BACK_FRAC = 0.01
# pushing (fingertip path, gripper closed, pitched down)PUSH_Y0 = -0.21 # start / retract tip y (front faces at -0.1664)PUSH_Y1 = -0.128 # deepest tip yPUSH_DY_FWD = 0.006PUSH_DY_BACK = 0.012PUSH_ZTIP = 0.815 # tile top 0.8297PUSH_PRE_DZ = 0.03PUSH_LAT_ROWS = 4PUSH_LIFT = 0.08PUSH_RETRY_DEEP = 0.012IK_MAX_JUMP = 0.35MAX_ROW_JUMP = 0.15 # rad per 25 Hz joint row inside push paths (densified)FALLEN_WHITE = 0.35
# pick (left, top-down pinch of the 64.7 mm length along x)PICK_APPROACH_Z = 1.02PICK_GRASP_Z = 0.960 # tip 0.806; tile spans z 0.798..0.8306GRASP_CENTER_BELOW_L6 = PICK_GRASP_Z - (TABLE_Z + 1.5 * TILE_T)GRIP_HOLD_MIN_LEN = 0.3 # measured ~0.575 when holding the lengthGRIP_HOLD_MIN_WID = 0.2 # measured ~0.39 when holding the width
# handover (tile centre at HO_LEFT - GRASP_CENTER_BELOW_L6)HO_LEFT = np.array([0.0, -0.25, 1.0955])HO_RIGHT_PRE_DX = 0.214 # right link6 relative to tile centreHO_RIGHT_DX = 0.164 # tip 1.0 cm past the centre toward +x endHO_RIGHT_DZ = -0.004LEFT_PARK = np.array([-0.15, -0.30, 1.10])
# rotate (about the right fingertip, fingers -x -> down) and placeROT_ROWS = 14ROT_LIFT = 0.02PLACE_DX = -HO_RIGHT_DZ # tile centre offset along link6 z becomes world -xPLACE_ABOVE_Z = 1.0664PLACE_Z = TABLE_Z + TILE_H / 2 + (HO_RIGHT_DX - TIP_LEN) + TIP_LEN + 0.0007
# measured link6 poses at the zero-joint home configuration (robot fact, episode start states)HOME_POSE = {"left": np.array([-0.2995, -0.3523, 0.9215]), "right": np.array([0.3005, -0.3523, 0.9215])}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149"""Self-contained RGB camera models, pixel rays, projection and multi-view triangulation.
NumPy only. Import it from this skill folder, or copy the file into a bundle:
sys.path.insert(0, "/workspace/.agents/skills/rgb-position-calibration") from triangulation import triangulate, project, pixel_ray, ray_plane
or run ``python triangulation.py views.json`` (a JSON list of views, see triangulate).
The constants are the simulator-verified pinhole models in CALIBRATION.md: ideal640 x 480 pinholes, square pixels, OpenCV camera axes (+x right, +y down, +z forward).``cam_high`` is fixed to the world; each wrist camera is the measured link6 pose of itsarm composed with a fixed mount. Pass the ``meta`` of the reply the image came with(``eef_positions`` and ``eef_quaternions_wxyz``, ordered [left, right]), so a wristcamera's pose matches its image."""from __future__ import annotations
from itertools import combinationsimport jsonimport sys
import numpy as np
CAMERAS = ("cam_high", "cam_left_wrist", "cam_right_wrist")WIDTH, HEIGHT = 640, 480# fx = focal_length * width / horizontal_aperture; fy = fx (Isaac renders square pixels).K_HIGH = np.array([[288.1325, 0.0, 320.0], [0.0, 288.1325, 240.0], [0.0, 0.0, 1.0]])K_WRIST = np.array([[397.0413, 0.0, 320.0], [0.0, 397.0413, 240.0], [0.0, 0.0, 1.0]])T_ENV_FROM_HIGH = np.array([[1.0, 0.0, 0.0, 0.0], [0.0, -0.866025, 0.5, -0.41], [0.0, -0.5, -0.866025, 1.308], [0.0, 0.0, 0.0, 1.0]])T_LINK6_FROM_WRIST = np.array([[0.0, -0.50003, 0.866008, 0.084842], [-1.0, 0.0, 0.0, 0.0], [0.0, -0.866008, -0.50003, 0.05094], [0.0, 0.0, 0.0, 1.0]])
# Advisory limits for triangulate() warnings; tune from your own validation.MIN_RAY_ANGLE_DEG = 10.0MAX_RAY_DISTANCE_M = 0.005MAX_REPROJECTION_PX = 3.0
def transform(position, quaternion_wxyz): """4x4 pose matrix from a position and a wxyz quaternion.""" w, x, y, z = np.asarray(quaternion_wxyz, dtype=float) / np.linalg.norm(quaternion_wxyz) matrix = np.eye(4) matrix[:3, :3] = [[1 - 2*(y*y + z*z), 2*(x*y - w*z), 2*(x*z + w*y)], [2*(x*y + w*z), 1 - 2*(x*x + z*z), 2*(y*z - w*x)], [2*(x*z - w*y), 2*(y*z + w*x), 1 - 2*(x*x + y*y)]] matrix[:3, 3] = position return matrix
def intrinsics(camera): """3x3 K of one camera.""" if camera not in CAMERAS: raise ValueError(f"camera must be one of {CAMERAS}") return (K_HIGH if camera == "cam_high" else K_WRIST).copy()
def camera_pose(camera, meta=None): """4x4 T_env_from_cam. Wrist cameras need the observation ``meta`` of their image.""" if camera == "cam_high": return T_ENV_FROM_HIGH.copy() if camera not in CAMERAS: raise ValueError(f"camera must be one of {CAMERAS}") if meta is None: raise ValueError("Wrist cameras need the observation meta (measured link6 pose)") arm = 0 if camera == "cam_left_wrist" else 1 link6 = transform(np.asarray(meta["eef_positions"][arm], dtype=float), np.asarray(meta["eef_quaternions_wxyz"][arm], dtype=float)) return link6 @ T_LINK6_FROM_WRIST
def pixel_ray(camera, pixel, meta=None): """(origin, unit direction) in the environment frame for pixel (u, v).""" pose = camera_pose(camera, meta) u, v = np.asarray(pixel, dtype=float).reshape(2) direction = pose[:3, :3] @ np.linalg.solve(intrinsics(camera), [u, v, 1.0]) return pose[:3, 3].copy(), direction / np.linalg.norm(direction)
def ray_plane(camera, pixel, height, meta=None): """Point where a pixel ray meets the horizontal plane z = height (single-view estimate).""" origin, direction = pixel_ray(camera, pixel, meta) if abs(direction[2]) < 1e-9 or (height - origin[2]) / direction[2] <= 0: raise ValueError("Ray does not reach that plane in front of the camera") return origin + direction * (height - origin[2]) / direction[2]
def project(camera, point, meta=None): """((u, v), depth_m) of an environment point; depth <= 0 means behind the camera.""" pose = camera_pose(camera, meta) local = pose[:3, :3].T @ (np.asarray(point, dtype=float).reshape(3) - pose[:3, 3]) uvw = intrinsics(camera) @ local return (uvw[:2] / uvw[2]).tolist() if abs(uvw[2]) > 1e-12 else [float("nan")] * 2, float(local[2])
def triangulate(views): """Least-squares 3-D point from two or more views of the same physical feature.
``views``: [{"camera": name, "pixel": [u, v], "meta": meta}, ...]; ``meta`` is the observation the image came with (required for wrist cameras). Views taken at different times are valid only if the feature did not move in between.
Returns the point with its evidence: per-view ray distance (m) and reprojection error (px), depth, the largest pairwise ray angle and advisory ``warnings``. An empty warning list is necessary, not sufficient: a wrong pixel correspondence can still agree by chance, so confirm with a third view or a measured-motion check. """ if len(views) < 2: raise ValueError("Triangulation needs at least two views") rays = [pixel_ray(view["camera"], view["pixel"], view.get("meta")) for view in views] system, target = np.zeros((3, 3)), np.zeros(3) for origin, direction in rays: orthogonal = np.eye(3) - np.outer(direction, direction) system += orthogonal target += orthogonal @ origin angles = [float(np.degrees(np.arccos(np.clip(abs(a[1] @ b[1]), 0.0, 1.0)))) for a, b in combinations(rays, 2)] if max(angles) < 0.5: raise ValueError("Rays are nearly parallel; take a view from a different direction") point = np.linalg.solve(system, target) distances = [float(np.linalg.norm((np.eye(3) - np.outer(d, d)) @ (point - o))) for o, d in rays] reprojection, depths = [], [] for view in views: pixel, depth = project(view["camera"], point, view.get("meta")) reprojection.append(float(np.linalg.norm(np.subtract(pixel, view["pixel"])))) depths.append(depth) warnings = [] if max(angles) < MIN_RAY_ANGLE_DEG: warnings.append(f"max ray angle {max(angles):.1f} deg < {MIN_RAY_ANGLE_DEG:g}: depth is poorly constrained") if min(depths) <= 0: warnings.append("point is behind a camera: wrong correspondence or stale pose") if max(distances) > MAX_RAY_DISTANCE_M: warnings.append(f"rays miss by {1000*max(distances):.1f} mm: check correspondence and image/pose pairing") if max(reprojection) > MAX_REPROJECTION_PX: warnings.append(f"reprojection error {max(reprojection):.1f} px > {MAX_REPROJECTION_PX:g}") return {"point": point.tolist(), "ray_distances_m": distances, "reprojection_px": reprojection, "depths_m": depths, "max_ray_angle_deg": max(angles), "warnings": warnings}
if __name__ == "__main__": if len(sys.argv) != 2: sys.exit("usage: python triangulation.py views.json") with open(sys.argv[1]) as stream: print(json.dumps(triangulate(json.load(stream)), indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445"""cam_high checks at fixed table locations (cam_high is fixed; model in triangulation.py)."""import numpy as npfrom triangulation import projectfrom scene import BACK_X, BACK_Y, TABLE_Z, TILE_H, TILE_T, FRONT_Y
def _uv(p): (u, v), _ = project("cam_high", p) return int(round(u)), int(round(v))
def _patch(im, u, v, hu, hv): h, w = im.shape[:2] return im[max(0, v - hv):min(h, v + hv + 1), max(0, u - hu):min(w, u + hu + 1)].astype(int)
def green_frac(p): r, g, b = p[..., 0], p[..., 1], p[..., 2] return float(((g > 90) & (g > r + 40) & (g > b + 40)).mean()) if p.size else 0.0
def white_frac(p): return float((p.min(axis=-1) > 150).mean()) if p.size else 0.0
def back_green(im): """Green (tile back) fraction at each standing back-row tile (mahjong5..8).""" out = [] for x in BACK_X: u, v = _uv([x, BACK_Y, 0.81]) out.append(green_frac(_patch(im, u, v, 6, 4))) return np.array(out)
def franka_change(im0, im): """Fraction of changed pixels in the franka's home region versus the first frame.""" a = im0[0:160, 200:440].astype(float) b = im[0:160, 200:440].astype(float) return float((np.abs(a - b).mean(axis=-1) > 30).mean())
def front_fallen_score(im, x): """White fraction where a pushed front tile lies face-up (behind its standing spot).""" u, v = _uv([x, FRONT_Y + TILE_T / 2 + TILE_H / 2, TABLE_Z + TILE_T]) return white_frac(_patch(im, u, v, 6, 3))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""plug_in_charger controller: scan -> decide -> [relocate] -> tilted grasp -> roll/carry -> insert -> release -> home.
Perception is depth/RGB geometry on the wrist and high cameras; motion is our own IK (kin.py) and joint-spacetrajectories sent through robodojo_step. Logs go to /workspace/output/run/log.txt."""import jsonimport osimport sysimport timeimport traceback
HERE = os.path.dirname(os.path.abspath(__file__))if HERE not in sys.path: sys.path.insert(0, HERE)
import numpy as np # noqa: E402import ctl # noqa: E402import ctl2 # noqa: E402
STATE_PATH = os.path.join(ctl.OUTDIR, "state.json")
def _plain(x): if isinstance(x, np.ndarray): return x.tolist() if isinstance(x, (np.floating,)): return float(x) if isinstance(x, (np.integer,)): return int(x) if isinstance(x, dict): return {k: _plain(v) for k, v in x.items()} if isinstance(x, (list, tuple)): return [_plain(v) for v in x] return x
def run_pipeline(ctx, S): ctl2.scan(ctx, S) t = time.time() ctl2.decide(ctx, S) ctl.log(S, "decide took %.1f s" % (time.time() - t)) if S.get("relocate"): ctl2.pick(ctx, S) ctl2.place(ctx, S) ctl2.grasp_tilted(ctx, S) ctl2.carry(ctx, S) ctl2.insert(ctx, S) ctl2.release_home(ctx, S)
def main(ctx): S = {"grip_cmd": {"left": 1.0, "right": 1.0}} t0 = time.time() ctl.log(S, "controller start") try: run_pipeline(ctx, S) except ctl2.Ended as e: ctl.log(S, "episode ended during", e) except Exception: ctl.log(S, "controller error:\n" + traceback.format_exc()) finally: ctl.log(S, "controller done: step", S.get("step"), "complete", S.get("task_complete"), "wall %.0f s" % (time.time() - t0)) try: os.makedirs(os.path.dirname(STATE_PATH), exist_ok=True) with open(STATE_PATH, "w") as f: json.dump(_plain(S), f, indent=1) except Exception: pass return S123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372"""Phases of the plug_in_charger controller. Each phase takes (ctx, S) where S is a dict state."""import json, os, timeimport numpy as npimport robot as Rimport perception as Pcimport motion as Mimport geom3 as G
STRIP_TOP = Pc.STRIP_TOPTABLE_Z = Pc.TABLE_ZPRE_Z = 1.00 # link6 z for top-down pregrasp view / liftGRASP_Z = 0.931 # link6 z when grasping the lying chargerGRASP_SHIFT = 0.008 # grasp point offset from top-face centre, away from prongs# nominal charger model in link6 frame after tipping (link6 z up, prongs down)TIP_L6 = np.array([0.1518, 0.0006, -0.049]) # prong-pair centre at the tipsBODY_BOTTOM_L6 = -0.0325PRONG_LEN = 0.0165OUTDIR = os.path.join(R.OUT, "run")
def log(S, *a): msg = " ".join(str(x) for x in a) line = f"[{time.strftime('%H:%M:%S')}] {msg}" print(line, flush=True) os.makedirs(OUTDIR, exist_ok=True) with open(os.path.join(OUTDIR, "log.txt"), "a") as f: f.write(line + "\n")
SAVE_IMAGES = os.environ.get("CHARGER_DEV") == "1"
def observe(ctx, S, tag=""): o = R.observe(ctx) upd(S, o.meta) if SAVE_IMAGES: try: o.save(tag, OUTDIR) except Exception: pass return o
def topdown_q(psi): """Gripper pointing down, link6 z = (cos psi, sin psi, 0).""" return G.R2q(G.Rz(psi) @ G.Ry(np.pi / 2))
def other(arm): return "left" if arm == "right" else "right"
def scan(ctx, S, strip_view=True, force_H=None): """Coarse localisation from cam_high, then pregrasp view + nadir strip view in parallel.""" o = observe(ctx, S, "_scan0") objs = Pc.find_objects(o) ch, st = objs["charger"], objs["strip"] log(S, "coarse charger", None if ch is None else (ch["c"].round(4).tolist(), round(ch["len"], 4), round(ch["wid"], 4)), "strip", None if st is None else (st["c"].round(4).tolist(), st["a"].round(3).tolist(), round(st["len"], 4))) if ch is None or st is None: raise RuntimeError("objects not found") S["coarse_charger"] = ch["c"].tolist() S["coarse_strip"] = dict(c=st["c"].tolist(), a=st["a"].tolist()) H = force_H or ("right" if ch["c"][0] > 0 else "left") V = other(H) S["H"], S["V"] = H, V # pregrasp view over the charger (camera on the robot side) pv = [ch["c"][0], ch["c"][1] + 0.01, PRE_Z] for psi in (-90, -45, -135, 0, 180, 45, 135, 90): rows_h, mh = M.plan(ctx, H, pv, topdown_q(np.radians(psi))) if rows_h is not None: break # nadir strip view: image x along the strip axis, gripper pointing away from robot a = np.array(st["a"]) pos, q, Rl6 = G.nadir_cam_link6([st["c"][0], st["c"][1], STRIP_TOP], 0.14, a) if Rl6[1, 0] < 0: pos, q, Rl6 = G.nadir_cam_link6([st["c"][0], st["c"][1], STRIP_TOP], 0.14, -a) if strip_view: rows_v, mv = M.plan(ctx, V, pos, q) else: rows_v = home_rows(S, [V], 25) log(S, "plans", H, None if rows_h is None else len(rows_h), V, None if rows_v is None else len(rows_v)) plans = [(arm, rows) for arm, rows in ((H, rows_h), (V, rows_v)) if rows is not None] if rows_h is None: raise RuntimeError("pregrasp plan failed: " + json.dumps(R.summarize(mh))) rows = M.merge(S["state"], plans) M.run_rows(ctx, rows, lambda m: log(S, m)) o = observe(ctx, S, "_scan1") fine = Pc.charger_fine(o, f"cam_{H}_wrist") if fine is None: raise RuntimeError("charger not seen in pregrasp view") S["charger"] = {k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in fine.items()} log(S, "charger fine", fine["c"].round(4).tolist(), "p", fine["p"].round(3).tolist(), "La/Lb", round(fine["La"], 4), round(fine["Lb"], 4), "prong_px", fine["prong_px"]) if strip_view and rows_v is not None: S["strip"] = None sl = Pc.strip_slots(o, f"cam_{V}_wrist") if sl is not None: S["strip"] = dict(c=sl["c"].tolist(), a=sl["a"].tolist(), b=sl["b"].tolist(), len=sl["len"], groups=[dict(c=g["c"].tolist(), n=g["n"], span=g["span"]) for g in sl["groups"]]) log(S, "strip fine", sl["c"].round(4).tolist(), "a", sl["a"].round(4).tolist(), [(g["c"].round(4).tolist(), g["n"], round(g["span"], 4)) for g in sl["groups"]]) return S
def upd(S, meta): if meta is None: return meta S["step"] = meta.get("step_id", S.get("step")) if meta.get("states"): S["state"] = list(meta["states"]) if meta.get("eef_positions"): S["eef_pos"] = meta["eef_positions"] S["eef_q"] = meta["eef_quaternions_wxyz"] S["ended"] = bool(meta.get("episode_ended")) steps = (meta.get("transition") or {}).get("steps") or [] S["task_complete"] = bool(meta.get("task_complete")) or any(bool(s.get("task_complete")) for s in steps) lim = meta.get("episode_limits") or {} if "remaining_episode_steps" in lim: S["remaining"] = lim["remaining_episode_steps"] return meta
def home_rows(S, arms, n): st = np.array(S["state"], float) goal = st.copy() for arm in arms: c = M.ARM_COLS[arm] g = np.zeros(7); g[6] = 1.0 goal[c] = g return M.interp(st, goal, n)
def eef_target(S, arm, pos=None, q=None, grip=None): i = M.ARM_IDX[arm] pos = S["eef_pos"][i] if pos is None else pos q = S["eef_q"][i] if q is None else q if grip is None: grip = S["state"][M.ARM_COLS[arm]][6] return {"position": [float(x) for x in pos], "quaternion_wxyz": [float(x) for x in q], "gripper_closed": bool(grip < 0.5), "gripper_opening": float(np.clip(grip, 0, 1))}
def step_eef(ctx, S, arm, waypoints, grip=None, other_hold=None): """waypoints: list of (pos, q) for `arm`; the other arm holds its current measured pose.""" o = other(arm) hold = other_hold or eef_target(S, o) targets = [] for pos, q in waypoints: t = {arm: eef_target(S, arm, pos, q, grip), o: hold} targets.append(t) meta, imgs = R.step_eef(ctx, targets) upd(S, meta) return meta, imgs
def lin_waypoints(p0, p1, q, max_step=0.015, settle=2): p0, p1 = np.asarray(p0, float), np.asarray(p1, float) n = max(1, int(np.ceil(np.linalg.norm(p1 - p0) / max_step))) wps = [(p0 + (p1 - p0) * (k / n), q) for k in range(1, n + 1)] return wps + [(p1, q)] * settle
def grasp(ctx, S, refine=False): H, V = S["H"], S["V"] ch = S["charger"] c, p = np.array(ch["c"]), np.array(ch["p"]) g = c - GRASP_SHIFT * p psi = float(np.arctan2(-p[1], -p[0])) q = topdown_q(psi) S["psi_grasp"] = psi rows_h, mh = M.plan(ctx, H, [g[0], g[1], PRE_Z], q, 1.0) if rows_h is None: raise RuntimeError("pregrasp plan failed " + json.dumps(R.summarize(mh))) rows_v = home_rows(S, [V], max(20, len(rows_h))) rows = M.merge(S["state"], [(H, rows_h), (V, rows_v)]) meta, _ = M.run_rows(ctx, rows, lambda m: log(S, m)); upd(S, meta) if refine: o = observe(ctx, S, "_pregrasp") fine = Pc.charger_fine(o, f"cam_{H}_wrist") if fine is not None and np.linalg.norm(fine["c"] - c) < 0.03 and fine["p"] @ p > 0.9: log(S, "refined charger", fine["c"].round(4).tolist(), "shift mm", ((fine["c"] - c) * 1000).round(2).tolist(), "p", fine["p"].round(3).tolist()) c = fine["c"] S["charger"]["c"] = c.tolist() g = c - GRASP_SHIFT * p else: log(S, "refine failed", None if fine is None else (fine["c"].round(4).tolist(), fine["p"].round(3).tolist())) # descend rows_h, mh = M.plan(ctx, H, [g[0], g[1], GRASP_Z], q, 1.0) if rows_h is None: raise RuntimeError("descend plan failed " + json.dumps(R.summarize(mh))) meta, _ = M.run_rows(ctx, rows_h, lambda m: log(S, m)); upd(S, meta) i = M.ARM_IDX[H] log(S, "at grasp", np.round(S["eef_pos"][i], 4).tolist()) # close gp = [g[0], g[1], GRASP_Z] meta, _ = step_eef(ctx, S, H, [(gp, q)] * 10, grip=0.0) log(S, "closed grip", round(S["state"][M.ARM_COLS[H]][6], 4), R.summarize(meta)) # lift meta, _ = step_eef(ctx, S, H, lin_waypoints(gp, [g[0], g[1], PRE_Z], q, 0.0175, 1), grip=0.0) log(S, "lifted", np.round(S["eef_pos"][i], 4).tolist(), "grip", round(S["state"][M.ARM_COLS[H]][6], 4)) return S
def choose_group(S): st = S["strip"] groups = [g for g in st["groups"] if g["n"] == 3 and abs(g["span"] - 0.0117) < 0.0025] if not groups: groups = [g for g in st["groups"] if g["n"] >= 2] if not groups: raise RuntimeError("no socket group found") c = np.array(st["c"]) g = min(groups, key=lambda g: np.linalg.norm(np.array(g["c"]) - c)) return np.array(g["c"]), np.array(st["a"])
def insert_frame(a): """link6 orientation for insertion: z up, y along strip axis a, x horizontal pointing +y (away from robot).""" b = np.array([-a[1], a[0]]) if b[1] < 0: b = -b psi = float(np.arctan2(b[1], b[0])) return G.Rz(psi), psi
def link6_for_tip(tip_world, Rl6, tip_l6): return np.asarray(tip_world, float) - Rl6 @ np.asarray(tip_l6, float)
def transport(ctx, S, h=0.05): H = S["H"] gc, a = choose_group(S) Rl6, psi = insert_frame(a) q = G.R2q(Rl6) S["target"] = gc.tolist(); S["ins_q"] = q.tolist(); S["ins_psi"] = psi tip = S.get("tip_l6", TIP_L6.tolist()) pos = link6_for_tip([gc[0], gc[1], STRIP_TOP + h], Rl6, tip) log(S, "target group", gc.round(4).tolist(), "psi", round(psi, 3), "pre-insert link6", pos.round(4).tolist()) rows, mp = M.plan(ctx, H, pos, q, 0.0, force_grip=0.0) if rows is None: log(S, "direct transport plan failed", R.summarize(mp)) # tip in place first, then move i = M.ARM_IDX[H] cur = np.array(S["eef_pos"][i]) rows, mp = M.plan(ctx, H, [cur[0], cur[1], PRE_Z], G.R2q(G.Rz(S["psi_grasp"])), 0.0, force_grip=0.0) if rows is None: raise RuntimeError("tip plan failed " + json.dumps(R.summarize(mp))) meta, _ = M.run_rows(ctx, rows, lambda m: log(S, m)); upd(S, meta) rows, mp = M.plan(ctx, H, pos, q, 0.0, force_grip=0.0) if rows is None: raise RuntimeError("transport plan failed " + json.dumps(R.summarize(mp))) meta, _ = M.run_rows(ctx, rows, lambda m: log(S, m)); upd(S, meta) i = M.ARM_IDX[H] log(S, "transport done; eef", np.round(S["eef_pos"][i], 4).tolist(), "goal", pos.round(4).tolist()) return S
def charger_inhand(o, arm): """Charger body in link6 frame from the holding wrist camera (prongs down, link6 z up).""" cam = f"cam_{arm}_wrist" i = M.ARM_IDX[arm] P, valid = o.points(cam) Rm = G.q2R(o.eef_q[i]); p0 = np.array(o.eef_pos[i]) L = (P - p0) @ Rm gray = o.rgb(cam).astype(int).mean(-1) m = valid & (gray > 120) & (L[..., 0] > 0.11) & (L[..., 0] < 0.2) & (np.abs(L[..., 1]) < 0.03) & \ (L[..., 2] > -0.06) & (L[..., 2] < 0.04) pts = L[m] if len(pts) < 500: return None mid = pts[(pts[:, 2] > np.percentile(pts[:, 2], 30)) & (pts[:, 2] < np.percentile(pts[:, 2], 70))] x_near = float(np.percentile(mid[:, 0], 10)) z_top = float(np.percentile(pts[:, 2], 99)) up = pts[pts[:, 2] > z_top - 0.03] y_lo, y_hi = np.percentile(up[:, 1], [1, 99]) tip = [x_near + 0.01325, float((y_lo + y_hi) / 2), z_top - 0.0485 - PRONG_LEN] return dict(tip=tip, x_near=x_near, z_top=z_top, y=(float(y_lo), float(y_hi)), n=int(len(pts)))
def measure_inhand(ctx, S, o=None): o = o or observe(ctx, S, "_inhand") inh = charger_inhand(o, S["H"]) if inh is not None: S["tip_l6"] = inh["tip"] log(S, "inhand tip_l6", np.round(inh["tip"], 4).tolist(), "z_top", round(inh["z_top"], 4), "n", inh["n"]) else: log(S, "inhand measurement failed") return inh
def goto_tip(ctx, S, tip_world, iters=3, tol=0.0002, settle=2): """Servo link6 so that the measured prong tip lands at tip_world (world).""" H = S["H"]; i = M.ARM_IDX[H] Rl6 = G.Rz(S["ins_psi"]); q = S["ins_q"] goal = link6_for_tip(tip_world, Rl6, S["tip_l6"]) cmd = goal.copy() cur = np.array(S["eef_pos"][i]) meta, _ = step_eef(ctx, S, H, lin_waypoints(cur, cmd, q, 0.015, settle), grip=0.0) for k in range(iters): meas = np.array(S["eef_pos"][i]) err = goal - meas if np.linalg.norm(err) < tol: break cmd = cmd + err meta, _ = step_eef(ctx, S, H, [(cmd, q)] * settle, grip=0.0) meas = np.array(S["eef_pos"][i]) rerr = G.rot_err(G.q2R(S["eef_q"][i]), Rl6) log(S, "goto_tip err mm", np.round((goal - meas) * 1000, 2).tolist(), "rot deg", round(np.degrees(rerr), 2), "step", S["step"]) return meta, cmd
def insert(ctx, S, h0=0.004, h_end=None, dz=0.001, slip_tol=0.0015): """Lower the prongs from h0 above the strip top in dz steps; stop when the charger slips in the grasp.""" H = S["H"]; i = M.ARM_IDX[H] Rl6 = G.Rz(S["ins_psi"]); q = S["ins_q"] gc = np.array(S["target"]) + np.array(S.get("search_off", [0.0, 0.0])) tip_ref = np.array(S["tip_l6"]) h_end = -PRONG_LEN - 0.0005 if h_end is None else h_end h = h0 res = dict(blocked=False, h=h, slip=0.0) while h > h_end + 1e-6: h = max(h_end, h - dz) goal = link6_for_tip([gc[0], gc[1], STRIP_TOP + h], Rl6, tip_ref) meta, imgs = step_eef(ctx, S, H, [(goal, q)] * 2, grip=0.0) inh = charger_inhand(R.Obs(meta, imgs), H) slip = (inh["tip"][2] - tip_ref[2]) if inh else float("nan") ez = (np.array(S["eef_pos"][i]) - goal) * 1000 log(S, f"insert h={h * 1000:.1f}mm eef_err_mm={np.round(ez, 2).tolist()} slip_mm={slip * 1000:.2f} step={S['step']}") res.update(h=h, slip=slip) if S.get("ended"): break if slip > slip_tol: res["blocked"] = True break return res
def release_and_home(ctx, S, n_home=30): H = S["H"]; i = M.ARM_IDX[H] Rl6 = G.Rz(S["ins_psi"]); q = S["ins_q"] cur = np.array(S["eef_pos"][i]) step_eef(ctx, S, H, [(cur, q)] * 6, grip=1.0) log(S, "opened", round(S["state"][M.ARM_COLS[H]][6], 3)) back = cur - Rl6[:, 0] * 0.06 + np.array([0, 0, 0.03]) step_eef(ctx, S, H, lin_waypoints(cur, back, q, 0.015, 1), grip=1.0) rows = home_rows(S, ["left", "right"], n_home) meta, _ = M.run_rows(ctx, rows, lambda m: log(S, m)); upd(S, meta) log(S, "home: step", S["step"], "task_complete", S.get("task_complete")) return S
def relocate(ctx, S, place_xy): """Put the held charger back down (lying, same yaw) at place_xy and hand the job to the other arm.""" H, V = S["H"], S["V"] q = topdown_q(S["psi_grasp"]) i = M.ARM_IDX[H] rows, mp = M.plan(ctx, H, [place_xy[0], place_xy[1], PRE_Z], q, 0.0, force_grip=0.0) if rows is None: raise RuntimeError("relocate plan failed " + json.dumps(R.summarize(mp))) meta, _ = M.run_rows(ctx, rows, lambda m: log(S, m)); upd(S, meta) cur = np.array(S["eef_pos"][i]) down = [place_xy[0], place_xy[1], GRASP_Z + 0.002] step_eef(ctx, S, H, lin_waypoints(cur, down, q, 0.0175, 1), grip=0.0) step_eef(ctx, S, H, [(down, q)] * 6, grip=1.0) step_eef(ctx, S, H, lin_waypoints(down, [down[0], down[1], down[2] + 0.04], q, 0.0175, 0), grip=1.0) p = np.array(S["charger"]["p"]) c_new = np.array(place_xy) + GRASP_SHIFT * p S["charger"]["c"] = c_new.tolist() S["H"], S["V"] = V, H log(S, "relocated to", np.round(c_new, 4).tolist(), "step", S["step"], "new H", S["H"]) return S123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808"""Tilted-grasp plug-in pipeline driven by our own IK (kin.py) and joint-space trajectories.
Flow: scan -> optional relocation by the charger-side arm H (top-down pick, place with prongs along the insertiondirection b) -> tilted grasp by the strip-side arm V (gripper pitched BETA from vertical, fingers on the width faces,approaching from the USB end) -> wrist roll (prongs down) -> pre-insert above the socket -> descend -> release -> home."""import jsonimport numpy as npimport robot as Rimport perception as Pcimport motion as Mimport geom3 as Gimport kinimport tiltfrom ctl import log, observe, upd, other, topdown_q, choose_group, PRE_Z, GRASP_Z, GRASP_SHIFT, STRIP_TOP, TABLE_Z
BETA = np.radians(45)FP, FT = 0.008, -0.003 # fingertip centre relative to body centre along P (prongs) and T (into table)BACK = 0.06 # pregrasp offset along -link6 xFINGER = 0.16 # fingertip distance ahead of link6 (clearance checks)HALF_T = 0.01325TIP_FROM_CENTER = 0.04075PRONG_LEN = 0.0165
# ---------------------------------------------------------------- low-level helpersdef gcol(arm): return M.ARM_COLS[arm].stop - 1
def jcols(arm): s = M.ARM_COLS[arm].start return slice(s, s + 6)
def qarm(S, arm): return np.array(S["state"], float)[jcols(arm)]
def cmd_row(S): """Current measured joints with the commanded (not measured) gripper values.""" row = np.array(S["state"], float) gc = S.setdefault("grip_cmd", {"left": 1.0, "right": 1.0}) for arm in ("left", "right"): row[gcol(arm)] = gc[arm] return row
class Ended(Exception): """The episode ended (step limit or native termination); stop sending robot calls."""
RATE = 0.085 # mean joint speed of planned moves, rad/step (cosine peak ~0.134; j6 saturates ~0.19)
def run(ctx, S, rows, tag): if S.get("ended"): raise Ended(tag) meta, imgs = M.run_rows(ctx, rows) upd(S, meta) log(S, tag, "step", S["step"], "rows", len(rows), "ended", S.get("ended"), "complete", S.get("task_complete")) if S.get("ended"): raise Ended(tag) return meta, imgs
J6_RATE = 0.105 # wrist roll may go faster (cosine peak ~0.165 < measured saturation ~0.19)
def nsteps(dq, rate=RATE, lo=6): """Cosine profile: peak joint speed ~1.57*rate rad/step.""" dq = np.abs(np.asarray(dq))[[0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]] r = np.full(12, rate) r[[5, 11]] = max(rate, J6_RATE) return int(max(lo, np.ceil((dq / r).max()) + 1))
def joint_rows(S, goals, n=None, grips=None, settle=0, delays=None): """Cosine joint interpolation from the measured state. goals {arm: q6}; grips {arm: g}; delays {arm: k}.""" start = cmd_row(S) goal = start.copy() for arm, q in goals.items(): goal[jcols(arm)] = q for arm, g in (grips or {}).items(): goal[gcol(arm)] = g if n is None: n = nsteps(goal - start) delays = delays or {} tot = n + max([0] + list(delays.values())) rows = np.tile(start, (tot + settle, 1)) for arm in ("left", "right"): d = delays.get(arm, 0) part = M.interp(start, goal, n) cols = M.ARM_COLS[arm] rows[d:d + n, cols] = part[:, cols] rows[d + n:, cols] = goal[cols] for arm, g in (grips or {}).items(): rows[:, gcol(arm)] = g # step command: closes in ~3 steps, opens to ~0.85 in ~3 steps S["grip_cmd"][arm] = g return rows
def rotvec(Rm): c = np.clip((np.trace(Rm) - 1) / 2, -1, 1) th = np.arccos(c) if th < 1e-9: return np.zeros(3) if th > np.pi - 1e-6: w, V = np.linalg.eigh(Rm + Rm.T) ax = V[:, np.argmax(w)] return ax * th return th / (2 * np.sin(th)) * np.array([Rm[2, 1] - Rm[1, 2], Rm[0, 2] - Rm[2, 0], Rm[1, 0] - Rm[0, 1]])
def expso3(w): th = np.linalg.norm(w) if th < 1e-12: return np.eye(3) k = w / th K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]]) return np.eye(3) + np.sin(th) * K + (1 - np.cos(th)) * K @ K
def pose_interp(T0, T1, s): T = np.eye(4) T[:3, :3] = T0[:3, :3] @ expso3(s * rotvec(T0[:3, :3].T @ T1[:3, :3])) T[:3, 3] = T0[:3, 3] + s * (T1[:3, 3] - T0[:3, 3]) return T
def line_qs(arm, q0, T1, n): """IK along a straight Cartesian line from fk(q0) to T1 (cosine timing). Returns list of q or None.""" T0 = kin.fk(arm, q0) q = np.array(q0, float) out = [] for k in range(1, n + 1): s = 0.5 - 0.5 * np.cos(np.pi * k / n) q, ok = kin.ik(arm, pose_interp(T0, T1, s), q) if not ok: return None out.append(q.copy()) return out
def line_rows(S, arm, T1, n, grip=None, settle=1): qs = line_qs(arm, qarm(S, arm), T1, n) if qs is None: # fall back to a joint-space move to the goal pose q = solve(arm, T1, qarm(S, arm)) if q is None: raise RuntimeError(f"IK failed for {arm} line target {np.round(T1[:3, 3], 3).tolist()}") log(S, "line IK failed; joint move instead") return joint_rows(S, {arm: q}, n=max(n, nsteps(np.r_[q - qarm(S, arm), 0, np.zeros(7)])), grips=None if grip is None else {arm: grip}, settle=settle) base = cmd_row(S) rows = np.tile(base, (n + settle, 1)) rows[:n, jcols(arm)] = qs rows[n:, jcols(arm)] = qs[-1] if grip is not None: rows[:, gcol(arm)] = grip S["grip_cmd"][arm] = grip return rows
def solve(arm, T, seed): """Nearest in-limit IK solution to `seed`, or None.""" q, ok = kin.ik(arm, T, seed) if ok: return q sols = kin.ik_all(arm, T, current=seed) return sols[0] if sols else None
def path_min_z(arm, q0, q1, n=12, reach=FINGER): """Lowest point of link6 / fingertip along a joint interpolation.""" zs = [] for s in np.linspace(0, 1, n): T = kin.fk(arm, (1 - s) * np.asarray(q0) + s * np.asarray(q1)) zs += [T[2, 3], (T[:3, 3] + reach * T[:3, 0])[2]] return float(min(zs))
def arm_points(arm, q): """Crude end-effector skeleton: wrist (behind link6), link6, mid-gripper, fingertips.""" T = kin.fk(arm, q) x = T[:3, 0] return np.array([T[:3, 3] + k * x for k in (-0.12, -0.06, 0.0, 0.08, FINGER)])
def arms_min_dist(rows, stride=2): rows = np.asarray(rows) best = 9.0 for r in rows[::stride]: pl, pr = arm_points("left", r[0:6]), arm_points("right", r[7:13]) best = min(best, float(np.linalg.norm(pl[:, None] - pr[None], axis=-1).min())) return best
def safe_rows(S, arm, q_goal, grip=None, settle=1, tag=""): """Move `arm` to q_goal while the other arm (if away from home) returns home; delay `arm` until they stay clear.""" o = other(arm) grips = None if grip is None else {arm: grip} if np.abs(qarm(S, o)).max() < 0.02: return joint_rows(S, {arm: q_goal}, grips=grips, settle=settle) goals = {arm: q_goal, o: np.zeros(6)} start = cmd_row(S) need = min(0.12, arms_min_dist(start[None]) - 0.005) for d in range(0, 41, 4): g0 = dict(S["grip_cmd"]) rows = joint_rows(S, goals, grips=grips, delays={arm: d}, settle=settle) dmin = arms_min_dist(rows, stride=1) if dmin >= need: break S["grip_cmd"] = g0 log(S, tag, f"{o} home first, {arm} delay", d, "min arm dist", round(dmin, 3)) return rows
def Tpose(pos, Rm): T = np.eye(4); T[:3, :3] = Rm; T[:3, 3] = pos return T
# ---------------------------------------------------------------- scanCH_VIEW_H = (0.20, 0.17, 0.23) # wrist-camera heights above the charger top faceST_VIEW_H = (0.14, 0.16) # ... above the strip top (slot detection needs a close nadir view)BASE_XY = {"left": np.array([-0.3, -0.6]), "right": np.array([0.3, -0.6])}
def solve_fast(arm, T, seed, nseeds=6): q, ok = kin.ik(arm, T, seed) if ok: return q q = kin.feasible(arm, T, kin.SEEDS[:nseeds]) return q
def view_q(arm, xy, z_top, heights, img_dirs, seed): """Joint solution putting `arm`'s wrist camera straight above xy, image x along one of img_dirs.""" for h in heights: for d in img_dirs: pos, _, Rl6 = G.nadir_cam_link6([xy[0], xy[1], z_top], h, d) q = solve_fast(arm, Tpose(pos, Rl6), seed) if q is not None: return q return None
def _dirs_toward(arm, xy, axis=None): """Image-x directions whose gripper heading (z x d) points away from the arm base.""" u = np.asarray(xy, float) - BASE_XY[arm] u /= np.linalg.norm(u) if axis is not None: a = np.asarray(axis, float) / np.linalg.norm(axis) cands = [a, -a] cands.sort(key=lambda d: -(np.array([-d[1], d[0]]) @ u)) return cands out = [] for dth in (0, 30, -30, 60, -60): t = np.radians(dth) v = np.array([np.cos(t) * u[0] - np.sin(t) * u[1], np.sin(t) * u[0] + np.cos(t) * u[1]]) out.append(np.array([v[1], -v[0]])) # d with z x d = v return out
def _store_charger(S, fine): S["charger"] = {k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in fine.items()}
def _store_strip(S, sl): S["strip"] = dict(c=sl["c"].tolist(), a=sl["a"].tolist(), b=sl["b"].tolist(), len=sl["len"], groups=[dict(c=g["c"].tolist(), n=g["n"], span=g["span"]) for g in sl["groups"]]) log(S, "strip fine", sl["c"].round(4).tolist(), "a", sl["a"].round(4).tolist(), [(g["c"].round(4).tolist(), g["n"], round(g["span"], 4)) for g in sl["groups"]])
def _charger_ok(fine, c_ref, tol=0.05): if fine is None or fine.get("border") or fine["prong_px"] < 8: return False L1, L2 = max(fine["La"], fine["Lb"]), min(fine["La"], fine["Lb"]) return np.linalg.norm(np.asarray(fine["c"]) - c_ref) < tol and 0.040 < L1 < 0.056 and 0.034 < L2 < 0.048
def scan(ctx, S): S.setdefault("grip_cmd", {"left": 1.0, "right": 1.0}) o = observe(ctx, S, "_scan0") objs = Pc.find_objects(o) ch, st = objs["charger"], objs["strip"] if ch is None or st is None: raise RuntimeError("objects not found") log(S, "coarse charger", ch["c"].round(4).tolist(), "strip", st["c"].round(4).tolist(), st["a"].round(3).tolist()) S["coarse_charger"] = ch["c"].tolist() S["coarse_strip"] = dict(c=st["c"].tolist(), a=st["a"].tolist()) cc, sc, a = ch["c"], st["c"], np.array(st["a"]) H = "right" if cc[0] > 0 else "left" V = "right" if sc[0] > 0 else "left" S["H"], S["V"] = H, V z_ch = TABLE_Z + Pc.CHG_T q0 = {arm: qarm(S, arm) for arm in ("left", "right")} parallel = False if H != V: qc = view_q(H, cc, z_ch, CH_VIEW_H, _dirs_toward(H, cc), q0[H]) qs = view_q(V, sc, STRIP_TOP, ST_VIEW_H, _dirs_toward(V, sc, a), q0[V]) if qc is not None and qs is not None: g0 = dict(S["grip_cmd"]) rows = joint_rows(S, {H: qc, V: qs}, settle=1) S["grip_cmd"] = g0 dmin = arms_min_dist(rows) parallel = dmin > 0.12 log(S, "parallel views min arm dist", round(dmin, 3)) else: log(S, "parallel view IK failed: charger", qc is not None, "strip", qs is not None) if parallel: run(ctx, S, rows, "scan views") o = observe(ctx, S, "_scan1") fine = Pc.charger_fine(o, f"cam_{H}_wrist") sl = Pc.strip_slots(o, f"cam_{V}_wrist") else: # one arm does both: strip first (its view may also show the charger), then the charger if needed for A in ([H, V] if H != V else [H]): qs = view_q(A, sc, STRIP_TOP, ST_VIEW_H, _dirs_toward(A, sc, a), q0[A]) qc = None if qs is None else view_q(A, cc, z_ch, CH_VIEW_H, _dirs_toward(A, cc), qs) if qc is not None: break if qs is None or qc is None: raise RuntimeError("no arm reaches both views") run(ctx, S, joint_rows(S, {A: qs}, settle=1), "strip view") o = observe(ctx, S, "_scan1") sl = Pc.strip_slots(o, f"cam_{A}_wrist") fine = Pc.charger_fine(o, f"cam_{A}_wrist") if not _charger_ok(fine, cc): run(ctx, S, joint_rows(S, {A: qc}, settle=1), "charger view") o = observe(ctx, S, "_scan2") fine = Pc.charger_fine(o, f"cam_{A}_wrist") if not _charger_ok(fine, cc): raise RuntimeError("charger not seen in close view: " + str(None if fine is None else (fine["c"].round(4).tolist(), fine["prong_px"]))) _store_charger(S, fine) log(S, "charger fine", fine["c"].round(4).tolist(), "p", fine["p"].round(3).tolist(), "prong_px", fine["prong_px"], "La/Lb", round(fine["La"], 4), round(fine["Lb"], 4)) if sl is None or not sl["groups"]: raise RuntimeError("strip slots not found") _store_strip(S, sl) return S
# ---------------------------------------------------------------- planningdef nominal_inhand(T_grasp, c_xy, p_xy): """Charger frame in link6 coordinates for a charger lying at c with prong direction p, grasped at T_grasp.""" p = np.array([p_xy[0], p_xy[1], 0.0]); p /= np.linalg.norm(p) Pw, Tw = p, np.array([0, 0, -1.0]) Ww = np.cross(Tw, Pw) center = np.array([c_xy[0], c_xy[1], TABLE_Z + HALF_T]) Rg, tg = T_grasp[:3, :3], T_grasp[:3, 3] C = Rg.T @ np.stack([Pw, Tw, Ww], 1) # columns P, T, W in link6 ctr = Rg.T @ (center - tg) ctr[1] = 0.0 # fingers centre the body along W return dict(C=C.tolist(), center=ctr.tolist(), tip=(ctr + TIP_FROM_CENTER * C[:, 0]).tolist())
def insert_T(inh, tip_world, b, s=1): """link6 pose placing the in-hand prong tip at tip_world, prongs down, thickness axis along s*b.""" C = np.array(inh["C"]) Pw = np.array([0, 0, -1.0]); Tw = s * np.array([b[0], b[1], 0.0]); Tw /= np.linalg.norm(Tw) Ww = np.cross(Tw, Pw) Rl6 = np.stack([Pw, Tw, Ww], 1) @ C.T return Tpose(np.asarray(tip_world) - Rl6 @ np.array(inh["tip"]), Rl6)
FLIP = np.diag([1.0, -1.0, -1.0]) # gripper rolled 180 deg about its axis (same physical grasp, j6 + pi)
def tilted_poses(c, p, flip=0): Tg = tilt.grasp_pose(c, p, BETA, fP=FP, fT=FT) Tpre = tilt.grasp_pose(c, p, BETA, fP=FP, fT=FT, back=BACK) if flip: Tg[:3, :3] = Tg[:3, :3] @ FLIP Tpre[:3, :3] = Tpre[:3, :3] @ FLIP Tlift = Tg.copy(); Tlift[2, 3] += 0.06 return Tg, Tpre, Tlift
def tilted_ok(arm, c, p, flip=0, seed=None): seed = np.zeros(6) if seed is None else seed Tg, Tpre, Tlift = tilted_poses(c, p, flip) qs = [] for T in (Tpre, Tg, Tlift): q = solve(arm, T, seed if not qs else qs[-1]) if q is None: return None qs.append(q) return qs
def socket_groups(S): """Socket centres (mean of the outer slots of a complete top-row triple), the one nearest the strip centre first.""" st = S["strip"] groups = [g for g in st["groups"] if g["n"] == 3 and abs(g["span"] - 0.0117) < 0.0025] if not groups: groups = [g for g in st["groups"] if g["n"] >= 2 and abs(g["span"] - 0.0117) < 0.0025] if not groups: raise RuntimeError("no socket group found") c = np.array(st["c"]) groups.sort(key=lambda g: np.linalg.norm(np.array(g["c"]) - c)) return [np.array(g["c"], float) for g in groups]
def strip_dist(S, xy): st = S["strip"] c, a = np.array(st["c"]), np.array(st["a"]) d = np.asarray(xy) - c t = np.clip(d @ a, -0.08, 0.08) return float(np.linalg.norm(d - t * a))
def decide(ctx, S): """Pick socket group, insertion direction b, and whether the charger must be relocated first.""" H, V = S["H"], S["V"] a = np.array(S["strip"]["a"], float) b = np.array([-a[1], a[0]]) if b[1] < 0: b = -b c, p = np.array(S["charger"]["c"]), np.array(S["charger"]["p"]) # insertion feasibility with the nominal in-hand model for a grasp with p along b; preferred group first cands = [] for gc in socket_groups(S): for arm in [V, other(V)]: for bb in (b, -b): for flip in (0, 1): Tg, _, _ = tilted_poses([0, 0], bb, flip) inh = nominal_inhand(Tg, [0, 0], bb) ok = all(solve_fast(arm, insert_T(inh, [gc[0], gc[1], STRIP_TOP + h], bb), np.zeros(6)) is not None for h in (-PRONG_LEN, 0.0, 0.03)) if ok: cands.append((arm, bb, flip)) if cands: break if cands: break log(S, "insert candidates", [(arm, np.round(bb, 3).tolist(), f) for arm, bb, f in cands], "group", np.round(gc, 4).tolist()) if not cands: raise RuntimeError("socket not reachable") V, b, flip = cands[0] S["target"] = gc.tolist() S["V"] = V; S["b"] = b.tolist(); S["flip"] = flip # direct tilted grasp? if p @ b > 0.5 and strip_dist(S, c) > 0.07 and tilted_ok(V, c, p, flip) is not None: S["relocate"] = None log(S, "direct tilted grasp by", V) return S # relocation: H picks with some grasp mode, places the charger at a spot with prongs along b for picker in (H, other(H)): modes = [] for mode in PICK_MODES: for fl in (0, 1): Tp = pick_pose(c, p, mode, fl) q1 = solve_fast(picker, lifted(Tp), np.zeros(6)) if q1 is not None and solve_fast(picker, Tp, q1) is not None: modes.append((mode, fl)) log(S, "pick modes", picker, [(round(np.degrees(m[0])), m[1], fl) for m, fl in modes]) if modes: break if not modes: raise RuntimeError("charger not pickable") H = S["H"] = picker best = None sx = 1 if V == "right" else -1 spots = [] for x in np.arange(-0.04, 0.30, 0.04): for y in np.arange(-0.25, -0.02, 0.04): xy = np.array([sx * x, y]) d = strip_dist(S, xy) if d >= 0.09 and np.linalg.norm(xy - c) > 0.03: # keep away from the insertion arm's parked fingertips (x=+-0.3, y=-0.19) so the arms stay clear crowd = max(0.0, 0.18 - np.linalg.norm(xy - np.array([sx * 0.3, -0.19]))) spots.append((abs(d - 0.11) + 0.3 * np.linalg.norm(xy - gc) + 1.0 * crowd, xy)) spots.sort(key=lambda t: t[0]) for cost, xy in spots: if tilted_ok(V, xy, b, flip) is None: continue for mode, fl in modes: Tq = place_pose(c, p, xy, b, pick_pose(c, p, mode, fl)) q1 = solve(H, lifted(Tq), np.zeros(6)) if q1 is not None and solve(H, Tq, q1) is not None: best = (xy, mode, fl) break if best: break if best is None: raise RuntimeError("no relocation spot") xy, mode, fl = best S["relocate"] = dict(xy=xy.tolist(), mode=list(mode), flip=fl) log(S, "relocate to", np.round(xy, 3).tolist(), "mode", round(np.degrees(mode[0])), mode[1], fl, "by", H) return S
# ---------------------------------------------------------------- relocation pick & place (H)# (beta, s): gripper tilted beta from vertical toward s*P (s=+1: wrist on the USB side)PICK_MODES = [(0.0, 1), (np.radians(25), -1), (np.radians(25), 1), (np.radians(45), -1), (np.radians(45), 1)]LIFT = 0.07
def charger_frame(c_xy, p_xy): p = np.array([p_xy[0], p_xy[1], 0.0]); p /= np.linalg.norm(p) Tw = np.array([0, 0, -1.0]) F = np.eye(4); F[:3, :3] = np.stack([p, Tw, np.cross(Tw, p)], 1) F[:3, 3] = [c_xy[0], c_xy[1], TABLE_Z + HALF_T] return F
def pick_pose(c, p, mode, flip=0): beta, sgn = mode F = charger_frame(c, p) P, Tw = F[:3, 0], F[:3, 1] if beta == 0: T = tilt.frame_pose(F[:3, 3], P, Tw, 0.0, fP=-GRASP_SHIFT, fT=0.0058) else: T = tilt.frame_pose(F[:3, 3], sgn * P, Tw, beta, fP=0.008, fT=FT) if flip: T[:3, :3] = T[:3, :3] @ FLIP return T
def place_pose(c, p, c_new, p_new, T_pick): """Same hand-object relation as T_pick, with the charger lying at c_new with prongs along p_new (+1 mm).""" Fo, Fn = charger_frame(c, p), charger_frame(c_new, p_new) T = Fn @ np.linalg.inv(Fo) @ T_pick T[2, 3] += 0.001 return T
def lifted(T, dz=LIFT): T = T.copy(); T[2, 3] += dz return T
def pick(ctx, S): H, V = S["H"], S["V"] c, p = np.array(S["charger"]["c"]), np.array(S["charger"]["p"]) rl = S["relocate"] Tp = pick_pose(c, p, rl["mode"], rl["flip"]) q_pre = solve(H, lifted(Tp), qarm(S, H)) if q_pre is None: raise RuntimeError("pick pregrasp IK failed") run(ctx, S, safe_rows(S, H, q_pre, grip=1.0, tag="pick"), "pick pregrasp") o = observe(ctx, S, "_pickpre") fine = Pc.charger_fine(o, f"cam_{H}_wrist") if fine is not None and np.linalg.norm(fine["c"] - c) < 0.02 and fine["p"] @ p > 0.95: log(S, "pick refine shift mm", np.round((fine["c"] - c) * 1000, 1).tolist()) c = fine["c"]; S["charger"]["c"] = c.tolist() Tp = pick_pose(c, p, rl["mode"], rl["flip"]) run(ctx, S, line_rows(S, H, Tp, 9, settle=1), "pick descend") run(ctx, S, joint_rows(S, {}, n=4, grips={H: 0.0}), "pick close") log(S, "grip", round(S["state"][gcol(H)], 4)) if S["state"][gcol(H)] < 0.45: raise RuntimeError("pick missed (gripper closed on nothing)") run(ctx, S, line_rows(S, H, lifted(Tp), 8, grip=0.0, settle=0), "pick lift") S["pick_T"] = Tp.tolist() return S
def place(ctx, S): H = S["H"] rl = S["relocate"] c, p = np.array(S["charger"]["c"]), np.array(S["charger"]["p"]) xy, b = np.array(rl["xy"]), np.array(S["b"]) Tq = place_pose(c, p, xy, b, np.array(S["pick_T"])) q_up = solve(H, lifted(Tq), qarm(S, H)) if q_up is None: raise RuntimeError("place IK failed") Tp = np.array(S["pick_T"]) F = np.linalg.inv(Tp) @ charger_frame(c, p) inh = dict(C=F[:3, :3].tolist(), center=F[:3, 3].tolist(), tip=(F[:3, 3] + TIP_FROM_CENTER * F[:3, 0]).tolist()) zmin = held_path_min_z(H, qarm(S, H), q_up, inh) log(S, "place path: charger min z above table mm", round((zmin - TABLE_Z) * 1000, 1)) if zmin < TABLE_Z + 0.03: q_hi = solve(H, lifted(Tq, LIFT + 0.06), qarm(S, H)) if q_hi is not None and held_path_min_z(H, qarm(S, H), q_hi, inh) > zmin: run(ctx, S, joint_rows(S, {H: q_hi}), "place carry high") q_up = solve(H, lifted(Tq), qarm(S, H)) run(ctx, S, joint_rows(S, {H: q_up}), "place carry") run(ctx, S, line_rows(S, H, Tq, 8, grip=0.0, settle=1), "place descend") run(ctx, S, joint_rows(S, {}, n=3, grips={H: 1.0}), "place open") run(ctx, S, line_rows(S, H, lifted(Tq), 8, settle=0), "place lift") S["charger_pred"] = xy.tolist() o = observe(ctx, S, "_placed") fine = Pc.charger_fine(o, f"cam_{H}_wrist") if fine is not None and np.linalg.norm(fine["c"] - xy) < 0.03 and fine["p"] @ b > 0.9: S["charger"] = {k: (v.tolist() if isinstance(v, np.ndarray) else v) for k, v in fine.items()} log(S, "placed charger", fine["c"].round(4).tolist(), "p", fine["p"].round(3).tolist(), "pred", np.round(xy, 4).tolist()) else: S["charger"] = dict(c=xy.tolist(), p=b.tolist()) log(S, "placed charger NOT measured; using prediction", None if fine is None else (fine["c"].round(4).tolist(), fine["p"].round(3).tolist())) return S
# ---------------------------------------------------------------- tilted grasp (V)def grasp_tilted(ctx, S): H, V = S["H"], S["V"] c, p = np.array(S["charger"]["c"]), np.array(S["charger"]["p"]) flip = S.get("flip", 0) Tg, Tpre, Tlift = tilted_poses(c, p, flip) q_pre = solve(V, Tpre, qarm(S, V)) if q_pre is None: raise RuntimeError("tilted pregrasp IK failed") pmz = path_min_z(V, qarm(S, V), q_pre) q_via = None if pmz < TABLE_Z + 0.04: q_via = solve(V, lifted(Tpre, 0.08), qarm(S, V)) if q_via is not None and path_min_z(V, qarm(S, V), q_via) < pmz: q_via = None log(S, "tgrasp path min z", round(pmz, 3), "via", q_via is not None) run(ctx, S, safe_rows(S, V, q_pre if q_via is None else q_via, grip=1.0, tag="tgrasp"), "tgrasp pregrasp") if q_via is not None: run(ctx, S, line_rows(S, V, Tpre, 7, settle=1), "tgrasp pregrasp down") o = observe(ctx, S, "_tpre") fine = Pc.charger_fine(o, f"cam_{V}_wrist") if fine is not None and not fine.get("border") and np.linalg.norm(fine["c"] - c) < 0.015 and fine["p"] @ p > 0.95: log(S, "tgrasp refine shift mm", np.round((fine["c"] - c) * 1000, 1).tolist(), "p", fine["p"].round(3).tolist()) c, p = np.asarray(fine["c"]), np.asarray(fine["p"]) S["charger"]["c"], S["charger"]["p"] = c.tolist(), p.tolist() Tg, _, Tlift = tilted_poses(c, p, flip) else: log(S, "tgrasp refine skipped", None if fine is None else (fine["c"].round(4).tolist(), fine["p"].round(3).tolist())) run(ctx, S, line_rows(S, V, Tg, 10, settle=1), "tgrasp approach") Tm = kin.fk(V, qarm(S, V)) run(ctx, S, joint_rows(S, {}, n=4, grips={V: 0.0}), "tgrasp close") log(S, "grip", round(S["state"][gcol(V)], 4)) if S["state"][gcol(V)] < 0.45: raise RuntimeError("tilted grasp missed (gripper closed on nothing)") S["inhand"] = nominal_inhand(Tm, c, p) run(ctx, S, line_rows(S, V, Tlift, 8, grip=0.0, settle=0), "tgrasp lift") return S
# ---------------------------------------------------------------- carry, insert, releasedef body_points_l6(inh): """Charger body corners and prong tips in link6 coordinates (from the in-hand model).""" C, ctr = np.array(inh["C"]), np.array(inh["center"]) pts = [ctr + C @ np.array([sp * 0.02425, st * HALF_T, sw * 0.021]) for sp in (-1, 1) for st in (-1, 1) for sw in (-1, 1)] pts.append(np.array(inh["tip"])) return np.array(pts)
def held_path_min_z(arm, q0, q1, inh, n=16): """Lowest charger point along a joint interpolation, ignoring the last 0 m (destination is checked separately).""" B = body_points_l6(inh) zs = [] for s_ in np.linspace(0, 1, n): T = kin.fk(arm, (1 - s_) * np.asarray(q0) + s_ * np.asarray(q1)) zs.append((B @ T[:3, :3].T + T[:3, 3])[:, 2].min()) return float(min(zs))
def carry(ctx, S, h=0.03, h_via=0.10): """Roll the prongs down and bring the tips above the socket. If the direct joint path dips toward the table, go via a pose h_via above the socket and descend in a straight line.""" V = S["V"] gc, b = np.array(S["target"]), np.array(S["b"]) inh = S["inhand"] q0 = qarm(S, V) best = None for s in (1, -1): T = insert_T(inh, [gc[0], gc[1], STRIP_TOP + h], b, s) Tv = insert_T(inh, [gc[0], gc[1], STRIP_TOP + h_via], b, s) for d6 in (0.0, np.pi, -np.pi): seed = q0.copy(); seed[5] += d6 q = solve(V, T, seed) if q is None: continue zmin = held_path_min_z(V, q0, q, inh) via = None if zmin < STRIP_TOP + 0.02: qv = solve(V, Tv, seed) if qv is None: continue zmin = held_path_min_z(V, q0, qv, inh) if zmin < STRIP_TOP + 0.02: continue via = qv cost = np.abs((q if via is None else via) - q0).max() + (0.3 if via is not None else 0.0) if best is None or cost < best[0]: best = (cost, q, s, via, zmin) if best is None: raise RuntimeError("pre-insert IK failed / no clear carry path") _, q, s, via, zmin = best S["ins_s"] = s log(S, "carry: s", s, "via", via is not None, "dq", np.round((q if via is None else via) - q0, 2).tolist(), "charger min z above strip top mm", round((zmin - STRIP_TOP) * 1000, 1)) if via is None: run(ctx, S, joint_rows(S, {V: q}, settle=1), "carry") else: run(ctx, S, joint_rows(S, {V: via}, settle=0), "carry via") run(ctx, S, line_rows(S, V, insert_T(inh, [gc[0], gc[1], STRIP_TOP + h], b, s), 7, grip=0.0, settle=1), "carry down") return S
def tip_now(S): V = S["V"] T = kin.fk(V, qarm(S, V)) return T[:3, :3] @ np.array(S["inhand"]["tip"]) + T[:3, 3]
def goto_tip(ctx, S, tip_world, n=6, settle=2, tag="goto"): V = S["V"] T = insert_T(S["inhand"], tip_world, S["b"], S["ins_s"]) rows = line_rows(S, V, T, n, grip=0.0, settle=settle) return run(ctx, S, rows, tag)
def inhand_measure(o, S): """Charger body seen by the holding wrist camera (depth). Offsets of the body from the nominal in-hand model: dP along the prong axis (+ = toward the prongs), dT along the thickness axis; bottom = world z of the prong face.""" V = S["V"] cam = f"cam_{V}_wrist" P, valid = o.points(cam) rgb = o.rgb(cam).astype(int) m = valid & (rgb[..., 1] > rgb[..., 0] + 15) & (rgb[..., 2] > rgb[..., 0] + 10) pts = P[m] q = np.array(o.states, float)[jcols(V)] T = kin.fk(V, q) inh = S["inhand"] C, ctr = np.array(inh["C"]), np.array(inh["center"]) X = ((pts - T[:3, 3]) @ T[:3, :3] - ctr) @ C keep = (np.abs(X[:, 0]) < 0.04) & (np.abs(X[:, 1]) < 0.03) & (np.abs(X[:, 2]) < 0.035) X, pts = X[keep], pts[keep] if len(X) < 3000: return None t = X[:, 1] tm = np.median(t) face = t[np.abs(t - tm) < 0.002] dT = float(np.median(face) - np.sign(tm) * HALF_T) dP = float(np.percentile(X[:, 0], 99.5) - 0.02425) bottom = float(np.percentile(pts[:, 2], 0.5)) tip_fk = T[:3, :3] @ np.array(inh["tip"]) + T[:3, 3] return dict(dP=dP, dT=dT, bottom=bottom, tip_fk_z=float(tip_fk[2]), n=int(len(X)))
def apply_inhand(S, mi): """Shift the in-hand model by the measured offsets (bounded).""" inh = S["inhand"] C = np.array(inh["C"]) dP = mi["dP"] if abs(mi["dP"]) < 0.006 else 0.0 dT = mi["dT"] if abs(mi["dT"]) < 0.003 else 0.0 d = C @ np.array([dP, dT, 0.0]) inh["center"] = (np.array(inh["center"]) + d).tolist() inh["tip"] = (np.array(inh["tip"]) + d).tolist() return dP, dT
SEARCH = [(0.0, 0.0), (0.0008, 0.0), (-0.0008, 0.0), (0.0, 0.0008), (0.0, -0.0008), (0.0016, 0.0), (-0.0016, 0.0)]
def insert(ctx, S, h0=0.003, dz=0.0015, h_check=-0.0015, h_end=-0.018, block_tol=0.0009): """Closed-loop insertion: approach above the socket, correct the in-hand model from wrist depth, descend a little, verify that the charger follows (prongs entered), else lift and try the next small offset.""" gc0 = np.array(S["target"], float) a2 = np.array(S["strip"]["a"], float); b2 = np.array([-a2[1], a2[0]]) meta, imgs = goto_tip(ctx, S, [gc0[0], gc0[1], STRIP_TOP + h0], n=8, settle=1, tag="approach") for k, (oa, ob) in enumerate(SEARCH): gc = gc0 + oa * a2 + ob * b2 if k: meta, imgs = goto_tip(ctx, S, [gc[0], gc[1], STRIP_TOP + h0], n=3, settle=1, tag=f"above {k}") mi = inhand_measure(R.Obs(meta, imgs), S) if mi is not None: dP, dT = apply_inhand(S, mi) log(S, "inhand dP %.2f dT %.2f mm (applied %.2f %.2f) n %d" % (mi["dP"] * 1e3, mi["dT"] * 1e3, dP * 1e3, dT * 1e3, mi["n"])) if max(abs(dP), abs(dT)) > 0.0003: meta, imgs = goto_tip(ctx, S, [gc[0], gc[1], STRIP_TOP + h0], n=1, settle=1, tag="re-above") else: log(S, "inhand measurement failed") n = int(round((h0 - h_check) / dz)) meta, imgs = goto_tip(ctx, S, [gc[0], gc[1], STRIP_TOP + h_check], n=n, settle=1, tag=f"enter {k}") mi = inhand_measure(R.Obs(meta, imgs), S) lag = None if mi is None else mi["bottom"] - PRONG_LEN - (STRIP_TOP + h_check) log(S, f"enter try {k} off mm ({oa * 1e3:.1f},{ob * 1e3:.1f}) actual tip above cmd:", None if lag is None else round(lag * 1e3, 2)) if lag is not None and lag > block_tol and k + 1 < len(SEARCH) and S.get("remaining", 99) > 60: continue S["ins_off"] = [oa, ob] n = int(round((h_check - h_end) / dz)) meta, imgs = goto_tip(ctx, S, [gc[0], gc[1], STRIP_TOP + h_end], n=n, settle=2, tag="descend") mi = inhand_measure(R.Obs(meta, imgs), S) log(S, "seated: bottom above strip top mm", None if mi is None else round((mi["bottom"] - STRIP_TOP) * 1e3, 2), "tip FK rel top", round((tip_now(S)[2] - STRIP_TOP) * 1e3, 2)) return S return S
def release_home(ctx, S): V = S["V"] run(ctx, S, joint_rows(S, {}, n=3, grips={V: 1.0}), "open") T = kin.fk(V, qarm(S, V)) for back, up in ((0.06, 0.02), (0.04, 0.04), (0.0, 0.05), (0.03, 0.0)): Tb = T.copy(); Tb[:3, 3] -= back * T[:3, 0]; Tb[2, 3] += up qs = line_qs(V, qarm(S, V), Tb, 6) if qs is not None: run(ctx, S, line_rows(S, V, Tb, 6, settle=0), "retreat") break else: log(S, "retreat skipped: no line IK") home = {"left": np.zeros(6), "right": np.zeros(6)} n = nsteps(np.r_[qarm(S, "left"), 0, qarm(S, "right"), 0], rate=0.11) run(ctx, S, joint_rows(S, home, n=n, grips={"left": 1.0, "right": 1.0}, settle=3), "home") log(S, "final: complete", S.get("task_complete"), "step", S["step"]) return S1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Small rotation helpers (wxyz quaternions, numpy)."""import numpy as np
def q2R(q): w, x, y, z = q return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])
def R2q(R): R = np.asarray(R, float) t = np.trace(R) if t > 0: s = np.sqrt(t + 1.0) * 2 q = [0.25 * s, (R[2, 1] - R[1, 2]) / s, (R[0, 2] - R[2, 0]) / s, (R[1, 0] - R[0, 1]) / s] elif R[0, 0] > R[1, 1] and R[0, 0] > R[2, 2]: s = np.sqrt(1.0 + R[0, 0] - R[1, 1] - R[2, 2]) * 2 q = [(R[2, 1] - R[1, 2]) / s, 0.25 * s, (R[0, 1] + R[1, 0]) / s, (R[0, 2] + R[2, 0]) / s] elif R[1, 1] > R[2, 2]: s = np.sqrt(1.0 + R[1, 1] - R[0, 0] - R[2, 2]) * 2 q = [(R[0, 2] - R[2, 0]) / s, (R[0, 1] + R[1, 0]) / s, 0.25 * s, (R[1, 2] + R[2, 1]) / s] else: s = np.sqrt(1.0 + R[2, 2] - R[0, 0] - R[1, 1]) * 2 q = [(R[1, 0] - R[0, 1]) / s, (R[0, 2] + R[2, 0]) / s, (R[1, 2] + R[2, 1]) / s, 0.25 * s] q = np.array(q) q /= np.linalg.norm(q) return q if q[0] >= 0 else -q
def Rz(t): c, s = np.cos(t), np.sin(t) return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1.0]])
def Ry(t): c, s = np.cos(t), np.sin(t) return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
def rot_err(Ra, Rb): """Angle (rad) between two rotation matrices.""" c = (np.trace(Ra.T @ Rb) - 1) / 2 return float(np.arccos(np.clip(c, -1, 1)))
# wrist camera mount in link6 frame (measured from camera_to_world_usd)CAM_POS_L6 = np.array([0.0848, 0.0, 0.0509])CAM_R_L6 = np.array([[0.0, 0.5, -0.866], [-1.0, 0.0, 0.0], [0.0, 0.866, 0.5]]) # columns: cam x, cam y(up), cam z(back)
def nadir_cam_link6(target, height, img_x): """link6 pose putting the wrist camera `height` above `target`, optical axis straight down, image +x along horizontal unit `img_x`.""" ax = np.array([img_x[0], img_x[1], 0.0]); ax /= np.linalg.norm(ax) zc = np.array([0, 0, 1.0]) Rcw = np.stack([ax, np.cross(zc, ax), zc], 1) C = CAM_R_L6 / np.linalg.norm(CAM_R_L6, axis=0) Rl6 = Rcw @ C.T cam = np.asarray(target, float) + np.array([0, 0, height]) return cam - Rl6 @ CAM_POS_L6, R2q(Rl6), Rl6123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119"""Product-of-exponentials FK/IK for the ARX X5 arms (screw axes identified from robodojo_fk_preview)."""import json, osimport numpy as np
_MODEL = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "kin_model.json")))# measured joint limits in the sim (robot-only preview), with small margins# j4 lower stop near home (-0.30) is a self-collision, true range is about [-2.2, 1.78]LIMITS = np.array([[-3.2, 3.2], [-0.2, 3.2], [-0.03, 3.2], [-2.15, 1.75], [-1.53, 1.53], [-3.13, 3.13]])
def _hat(w): return np.array([[0, -w[2], w[1]], [w[2], 0, -w[0]], [-w[1], w[0], 0]])
def _exp(S, th): w, v = np.asarray(S[:3]), np.asarray(S[3:]) W = _hat(w) R = np.eye(3) + np.sin(th) * W + (1 - np.cos(th)) * W @ W p = (np.eye(3) * th + (1 - np.cos(th)) * W + (th - np.sin(th)) * W @ W) @ v T = np.eye(4); T[:3, :3] = R; T[:3, 3] = p return T
def _adj(T): R, p = T[:3, :3], T[:3, 3] A = np.zeros((6, 6)); A[:3, :3] = R; A[3:, 3:] = R; A[3:, :3] = _hat(p) @ R return A
def fk(arm, q): m = _MODEL[arm] T = np.eye(4) for S, th in zip(m["S"], q): T = T @ _exp(S, th) return T @ np.array(m["M"])
def jac_space(arm, q): m = _MODEL[arm] J = np.zeros((6, 6)); T = np.eye(4) for i, (S, th) in enumerate(zip(m["S"], q)): J[:, i] = _adj(T) @ np.asarray(S) T = T @ _exp(S, th) return J
def _err(Tc, Td): """6-vector [rot; pos] error in space frame (small-angle).""" Re = Td[:3, :3] @ Tc[:3, :3].T c = np.clip((np.trace(Re) - 1) / 2, -1, 1); th = np.arccos(c) if th < 1e-9: w = np.zeros(3) else: w = th / (2 * np.sin(th)) * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]]) dp = Td[:3, 3] - Tc[:3, 3] # space twist: v = dp - w x p return np.concatenate([w, dp - np.cross(w, Tc[:3, 3])]), th, np.linalg.norm(dp)
def ik(arm, Td, seed, iters=200, tol_p=1e-5, tol_r=1e-4, lam=1e-3): q = np.clip(np.array(seed, float), LIMITS[:, 0], LIMITS[:, 1]) for _ in range(iters): Tc = fk(arm, q) e, er, ep = _err(Tc, Td) if ep < tol_p and er < tol_r: return q, True J = jac_space(arm, q) dq = J.T @ np.linalg.solve(J @ J.T + lam * np.eye(6), e) n = np.abs(dq).max() if n > 0.3: dq *= 0.3 / n q = np.clip(q + dq, LIMITS[:, 0], LIMITS[:, 1]) Tc = fk(arm, q); e, er, ep = _err(Tc, Td) return q, (ep < 1e-4 and er < 1e-3)
SEEDS = [ [0, 0.8, 0.3, 0.5, 0.5, 0], [0, 1.5, 1.0, 0.5, 0, 0], [1.2, 2.5, 1.5, 0.9, 1.55, 0], [-1.2, 2.5, 1.5, 0.9, -1.55, 0], [0.5, 2.0, 1.2, 0.8, 0.8, 0], [-0.5, 2.0, 1.2, 0.8, -0.8, 0], [0, 2.2, 1.8, 1.2, 0, 0], [0.8, 1.8, 0.6, 1.0, 1.2, 1.0], [-0.8, 1.8, 0.6, 1.0, -1.2, -1.0], [0, 1.2, 0.2, 1.0, 0, 0], [1.0, 1.2, 0.5, 0.3, 1.0, 0], [-1.0, 1.2, 0.5, 0.3, -1.0, 0],]
def ik_all(arm, Td, current=None, extra_seeds=()): """Return list of distinct valid solutions sorted by distance from `current`.""" seeds = ([list(current)] if current is not None else []) + [list(s) for s in extra_seeds] + SEEDS sols = [] for s in seeds: q, ok = ik(arm, Td, s) if ok and all(np.abs(q - p).max() > 1e-2 for p in sols): sols.append(q) if current is not None: sols.sort(key=lambda q: np.abs(q - np.asarray(current)).sum()) return sols
def feasible(arm, Td, seeds=None): for s in (seeds or SEEDS): q, ok = ik(arm, Td, s) if ok: return q return None
def pose_T(pos, quat): import geom3 as G T = np.eye(4); T[:3, :3] = G.q2R(quat); T[:3, 3] = pos return T
def link_points(arm, q): """Origins of joint frames (for crude collision checks): positions after each joint, plus link6 and fingertip.""" m = _MODEL[arm] pts = [] T = np.eye(4) for S, th in zip(m["S"], q): T = T @ _exp(S, th) Te = fk(arm, q) return Te123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158{ "left": { "M": [ [ -0.0003019400210180212, -0.9999999544161108, 9.702566854125297e-26, -0.299529100084835 ], [ 0.9999999544161108, -0.0003019400210180212, -3.213408536945272e-22, -0.35229984143838877 ], [ 3.2134086834249366e-22, -2.350988701644575e-38, 1.0, 0.921499982020169 ], [ 0.0, 0.0, 0.0, 1.0 ] ], "S": [ [ 5.236445397770718e-22, -6.674508044974221e-22, 0.9999999999999996, -0.4499999880790708, 0.30000001192092896, 4.358752859632132e-22 ], [ -0.9999999544161111, -0.00030194002101772814, 2.563409445845804e-17, 0.0002613290838715461, -0.8654999462420302, -0.42990938555641667 ], [ 0.9999999543891264, 0.00030194002100973735, -7.346410206640364e-06, -0.0002562306753505189, 0.86549774283676, 0.6939093855376925 ], [ 0.9999999543891264, 0.00030194002100973735, -7.346410206640364e-06, -0.00027493918694610224, 0.9214977397406093, 0.44890938554430326 ], [ -7.3464098717656335e-06, -2.2181752522009713e-09, -0.9999999999730151, 0.3812498421524958, -0.29952712862970887, -2.8001532004096573e-06 ], [ -0.00030194002101787526, 0.9999999544161099, -3.6759003429895545e-16, -0.9214999400146152, -0.0002782377239392517, -0.2996354598526621 ] ] }, "right": { "M": [ [ -0.0003019400210180212, -0.9999999544161108, 9.702566854125297e-26, 0.3004709237570229 ], [ 0.9999999544161108, -0.0003019400210180212, -3.213408536945272e-22, -0.35229984143838877 ], [ 3.2134086834249366e-22, -2.350988701644575e-38, 1.0, 0.921499982020169 ], [ 0.0, 0.0, 0.0, 1.0 ] ], "S": [ [ 5.236445397770718e-22, -6.674508044974221e-22, 0.9999999999999996, -0.44999998807907077, -0.3000000119209289, 3.5404787351492606e-23 ], [ -0.9999999544161111, -0.00030194002101772814, 2.563409445845804e-17, 0.00026132908387154613, -0.8654999462420303, -0.43009054957622606 ], [ 0.9999999543891264, 0.00030194002100973735, -7.346410206640364e-06, -0.0002562306753505189, 0.8655021506830591, 0.6940905495574969 ], [ 0.9999999543891264, 0.00030194002100973735, -7.346410206640364e-06, -0.00027493918694610224, 0.9215021475869086, 0.44909054956410804 ], [ -7.3464098717656335e-06, -2.2181752522009713e-09, -0.9999999999730151, 0.38124984215249585, 0.3004728951959583, -2.801484105613864e-06 ], [ -0.00030194002101787526, 0.9999999544161099, -3.6759003429895545e-16, -0.9214999400146152, -0.00027823772393903114, 0.30036453663886076 ] ] }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364"""Motion primitives on top of the MCP robot tools."""import jsonimport numpy as npimport robot as R
ARM_COLS = {"left": slice(0, 7), "right": slice(7, 14)}ARM_IDX = {"left": 0, "right": 1}
def state(meta): return np.array(meta["states"], float)
def plan(ctx, arm, pos, quat, gripper=None, force_grip=None): """cuRobo preview; returns (rows ndarray Nx14 or None, meta). force_grip: set this arm's gripper column on every row (keeps squeeze force on a held object).""" meta, _ = R.free_move(ctx, arm, pos, quat, gripper, preview=True) mp = meta.get("motion_plan") or {} tp = mp.get("trajectory_preview") or meta.get("trajectory_preview") or {} acts = tp.get("actions") if mp.get("status") not in (None, "Success") or not acts: return None, meta rows = np.array(acts, float) if force_grip is not None: rows[:, ARM_COLS[arm].stop - 1] = force_grip return rows, meta
def merge(start, plans): """plans: list of (arm, rows). Each arm's columns follow its plan; padded with last row.""" n = max(len(r) for _, r in plans) out = np.tile(np.asarray(start, float), (n, 1)) for arm, rows in plans: cols = ARM_COLS[arm] full = np.vstack([rows, np.repeat(rows[-1:], n - len(rows), 0)]) out[:, cols] = full[:, cols] return out
def run_rows(ctx, rows, log=None): meta = None rows = np.asarray(rows, float) for i in range(0, len(rows), 50): meta, imgs = R.step_joints(ctx, rows[i:i + 50].tolist()) if log: log(f"run_rows {i}:{i + 50} -> {R.summarize(meta)}") if meta.get("episode_ended"): break return meta, imgs
def interp(start, goal, n): start, goal = np.asarray(start, float), np.asarray(goal, float) t = np.linspace(0, 1, n + 1)[1:, None] s = 0.5 - 0.5 * np.cos(np.pi * t) # smooth start/stop return start + s * (goal - start)
def fk_check(ctx, rows): """FK preview of up to 50 rows (pads). Returns list of (L pos, R pos).""" rows = np.asarray(rows, float) pad = np.vstack([rows, np.repeat(rows[-1:], 50 - len(rows), 0)]) if len(rows) < 50 else rows[:50] rep = ctx.call("robodojo_fk_preview", actions=pad.tolist()) return json.loads(rep["content"][0]["text"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151"""Depth/RGB perception for the charger task (no Gemini needed in sim)."""import numpy as npimport cv2
TABLE_Z = 0.7655STRIP_TOP = 0.784CHG_T = 0.0265 # charger thickness (vertical when lying)SLOT_THR = 0.0025 # depth below the strip top that marks a slot opening
def components(P, valid, zmin, zmax, region=None, min_px=30): z = P[..., 2] m = valid & (z > zmin) & (z < zmax) if region is not None: m &= region n, lab, st, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8)) out = [] for i in range(1, n): if st[i, 4] >= min_px: out.append(lab == i) return out
def pca2(xy): c = xy.mean(0) w, V = np.linalg.eigh(np.cov((xy - c).T)) a = V[:, 1] if a[0] < 0: a = -a b = np.array([-a[1], a[0]]) pa, pb = (xy - c) @ a, (xy - c) @ b return c, a, b, (pa.min(), pa.max()), (pb.min(), pb.max())
def find_objects(obs, cam="cam_high"): """Coarse charger and strip estimates from the high camera. Returns dict(charger=dict(c, top_z, ...), strip=dict(c, a, b, len, wid)).""" P, valid = obs.points(cam) rgb = obs.rgb(cam).astype(int) # table area only (exclude robot bodies near y<-0.42 and the far wall) region = (np.abs(P[..., 0]) < 0.6) & (P[..., 1] > -0.40) & (P[..., 1] < 0.45) res = {"charger": None, "strip": None, "others": []} for m in components(P, valid, TABLE_Z + 0.006, TABLE_Z + 0.08, region): pts = P[m] col = rgb[m].mean(0) c, a, b, ra, rb = pca2(pts[:, :2]) L, W = ra[1] - ra[0], rb[1] - rb[0] ztop = np.percentile(pts[:, 2], 90) info = dict(c=c, a=a, b=b, len=L, wid=W, ztop=ztop, n=int(m.sum()), col=col) if L > 0.11 and W < 0.06 and abs(ztop - STRIP_TOP) < 0.01: res["strip"] = info elif 0.025 < L < 0.08 and 0.015 < W < 0.07: if res["charger"] is None or info["n"] > res["charger"]["n"]: res["charger"] = info else: res["others"].append(info) return res
def charger_fine(obs, cam): """Charger lying flat (T vertical) seen from above by a wrist camera. Returns dict(c=top-face centre xy, p=unit prong direction xy, L, W, ztop) or None.""" P, valid = obs.points(cam) z = P[..., 2] top = valid & (np.abs(z - (TABLE_Z + CHG_T)) < 0.004) comps = components(P, top, -1, 9, None, 200) if not comps: return None m = max(comps, key=lambda k: k.sum()) c, a, b, ra, rb = pca2(P[m][:, :2]) # refine centre to the middle of the extents c = c + a * (ra[0] + ra[1]) / 2 + b * (rb[0] + rb[1]) / 2 La, Lb = ra[1] - ra[0], rb[1] - rb[0] # prongs: things 5..22 mm above the table just outside the body outline cand = valid & (z > TABLE_Z + 0.005) & (z < TABLE_Z + 0.022) & ~m q = P[cand][:, :2] - c best, score = None, -1 for ax, half, other in ((a, La / 2, b), (-a, La / 2, b), (b, Lb / 2, a), (-b, Lb / 2, a)): s = q @ ax; t = q @ other n = int(((s > half + 0.002) & (s < half + 0.020) & (np.abs(t) < 0.009)).sum()) if n > score: best, score = ax, n border = bool(m[:2].any() or m[-2:].any() or m[:, :2].any() or m[:, -2:].any()) return dict(c=c, p=best, La=La, Lb=Lb, ztop=float(np.median(z[m])), prong_px=score, a=a, b=b, border=border)
def ray_plane(obs, cam, uv, zp): cp = obs.meta["camera_parameters"][cam] K = np.array(cp["intrinsic_matrix"]); T = np.array(cp["camera_to_world_usd"]) uv = np.atleast_2d(uv) dc = np.stack([(uv[:, 0] - K[0, 2]) / K[0, 0], -(uv[:, 1] - K[1, 2]) / K[1, 1], -np.ones(len(uv))], -1) dw = dc @ T[:3, :3].T t = (zp - T[2, 3]) / dw[:, 2] return T[:3, 3] + t[:, None] * dw
def strip_slots(obs, cam, dark=110, depth_mask=True): """Slots of the power strip seen from above (close wrist view). Returns dict(c, a, b, len, groups=[dict(c=pair centre xy, slots=[xy..])]) or None.""" P, valid = obs.points(cam) z = P[..., 2] top = valid & (np.abs(z - STRIP_TOP) < 0.003) comps = components(P, top, -1, 9, None, 500) if not comps: return None m = max(comps, key=lambda k: k.sum()) c, a, b, ra, rb = pca2(P[m][:, :2]) c = c + a * (ra[0] + ra[1]) / 2 + b * (rb[0] + rb[1]) / 2 hull = cv2.convexHull(np.argwhere(m)[:, ::-1].astype(np.int32)) hm = np.zeros(m.shape, np.uint8); cv2.fillConvexPoly(hm, hull, 1) hm = cv2.erode(hm, np.ones((5, 5), np.uint8)).astype(bool) gray = obs.rgb(cam).astype(int).mean(-1) dk = hm & ((valid & (z < STRIP_TOP - SLOT_THR)) if depth_mask else (gray < dark)) n, lab, st, cen = cv2.connectedComponentsWithStats(dk.astype(np.uint8)) slots = [] for i in range(1, n): if st[i, 4] < 6 or st[i, 4] > 2000: continue vv, uu = np.nonzero(lab == i) W = ray_plane(obs, cam, np.stack([uu, vv], -1).astype(float), STRIP_TOP)[:, :2] sc, sa, sb, sra, srb = pca2(W) if depth_mask: # rays that hit the far wall less than SLOT_THR below the rim are missing from the mask: # shift the centroid back by half that strip along the ray's horizontal travel cp = obs.meta["camera_parameters"][cam] Tc = np.array(cp["camera_to_world_usd"]) ray = sc - Tc[:2, 3] sc = sc + 0.5 * SLOT_THR * ray / (Tc[2, 3] - STRIP_TOP) slen, swid = sra[1] - sra[0], srb[1] - srb[0] ang = np.degrees(np.arccos(min(1.0, abs(sa @ b)))) # 0 => slot runs along strip short axis slots.append(dict(c=sc, len=slen, wid=swid, ang=ang, n=len(uu))) straight = [s for s in slots if s["ang"] < 12 and 0.003 < s["len"] < 0.010] straight.sort(key=lambda s: (s["c"] - c) @ a) groups, cur = [], [] for s in straight: if cur and ((s["c"] - cur[-1]["c"]) @ a) > 0.009: groups.append(cur); cur = [] cur.append(s) if cur: groups.append(cur) out = [] for g in groups: pos = np.array([s["c"] for s in g]) if len(g) >= 2: ends = pos[[0, -1]] span = (ends[1] - ends[0]) @ a gc = ends.mean(0) if len(g) == 3 or abs(span - 0.0117) < 0.002 else pos.mean(0) else: gc, span = pos[0], 0.0 out.append(dict(c=gc, n=len(g), span=span, slots=[s["c"] for s in g])) return dict(c=c, a=a, b=b, len=ra[1] - ra[0], wid=rb[1] - rb[0], groups=out, slots=slots)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""Thin MCP helpers shared by the controller and dev scripts."""import base64, io, json, osimport numpy as npfrom PIL import Image
HOME = [0.0] * 6OUT = "/workspace/output"
def parse(reply): meta = json.loads(reply["content"][0]["text"]) imgs = {} names = {a["content_index"]: (a["kind"], a["camera"]) for a in meta.get("attachments", [])} for i, blk in enumerate(reply["content"]): if i in names and blk.get("type") == "image": imgs[names[i]] = blk return meta, imgs
def decode_rgb(blk): return np.array(Image.open(io.BytesIO(base64.b64decode(blk["data"]))).convert("RGB"))
def decode_depth(blk): return np.array(Image.open(io.BytesIO(base64.b64decode(blk["data"])))).astype(np.float64) * 0.001
class Obs: def __init__(self, meta, imgs): self.meta, self.imgs = meta, imgs self.step_id = meta.get("step_id") self.states = meta.get("states") self.eef_pos = meta.get("eef_positions") self.eef_q = meta.get("eef_quaternions_wxyz") self._cache = {}
def rgb(self, cam): k = ("rgb", cam) if k not in self._cache: self._cache[k] = decode_rgb(self.imgs[k]) return self._cache[k]
def depth(self, cam): k = ("depth", cam) if k not in self._cache: self._cache[k] = decode_depth(self.imgs[k]) return self._cache[k]
def points(self, cam): """World xyz per pixel from depth (distance to image plane).""" cp = self.meta["camera_parameters"][cam] K = np.array(cp["intrinsic_matrix"]); T = np.array(cp["camera_to_world_usd"]) d = self.depth(cam) H, W = d.shape u, v = np.meshgrid(np.arange(W), np.arange(H)) x = (u - K[0, 2]) / K[0, 0] * d; y = (v - K[1, 2]) / K[1, 1] * d P = np.stack([x, -y, -d], -1).reshape(-1, 3) @ T[:3, :3].T + T[:3, 3] return P.reshape(H, W, 3), d > 0
def project(self, cam, pw): cp = self.meta["camera_parameters"][cam] K = np.array(cp["intrinsic_matrix"]); T = np.array(cp["camera_to_world_usd"]) pc = (np.asarray(pw) - T[:3, 3]) @ T[:3, :3] z = -pc[..., 2] return np.stack([K[0, 0] * pc[..., 0] / z + K[0, 2], K[1, 1] * -pc[..., 1] / z + K[1, 2]], -1)
def save(self, tag="", outdir=None): outdir = outdir or os.path.join(OUT, "live") os.makedirs(outdir, exist_ok=True) paths = [] for (kind, cam), blk in self.imgs.items(): if kind == "rgb": p = os.path.join(outdir, f"{self.step_id:04d}{tag}_{cam}.png") open(p, "wb").write(base64.b64decode(blk["data"])) paths.append(p) return paths
def observe(ctx): return Obs(*parse(ctx.call("robodojo_observe")))
def summarize(meta): t = meta.get("transition", {}) or {} s = {"step_id": meta.get("step_id"), "remaining": (meta.get("episode_limits") or {}).get("remaining_episode_steps"), "ended": meta.get("episode_ended"), "task_complete": meta.get("task_complete")} for k in ("status", "goal_reached", "executed_control_blocks"): if k in t: s[k] = t[k] if "measured_goal_error" in t: e = t["measured_goal_error"] s["err"] = (round(e.get("final_position_error_m", -1), 4), round(e.get("final_rotation_error_rad", -1), 4)) mp = meta.get("motion_plan") if mp and mp.get("status") != "Success": s["plan"] = {k: mp.get(k) for k in ("status", "failure_stage", "reason")} if "ik_diagnostics" in t: s["ik"] = str(t["ik_diagnostics"])[:300] return s
def free_move(ctx, arm, pos, quat, gripper=None, preview=False): target = {"position": [float(x) for x in pos], "quaternion_wxyz": [float(x) for x in quat]} if gripper is not None: target["gripper_opening"] = float(gripper) kw = dict(arm=arm, target=target) if preview: kw.update(preview_only=True, include_trajectory=True) meta, imgs = parse(ctx.call("robodojo_free_space_move", **kw)) return meta, imgs
def step_eef(ctx, targets): return parse(ctx.call("robodojo_step_eef", targets=targets))
def step_joints(ctx, actions): return parse(ctx.call("robodojo_step", actions=[[float(x) for x in a] for a in actions]))
def pose_math(ctx, **kw): return json.loads(ctx.call("robodojo_pose_math", **kw)["content"][0]["text"])
def compose(ctx, pos, quat, dpos=None, drot_axis_angle=None, frame="environment"): delta = {} if dpos is not None: delta["position_m"] = [float(x) for x in dpos] if drot_axis_angle is not None: delta["rotation"] = {"representation": "axis_angle_vector_rad", "value": [float(x) for x in drot_axis_angle]} r = pose_math(ctx, operation="compose_pose", base_pose={"position_m": [float(x) for x in pos], "rotation": {"representation": "quaternion_wxyz", "value": [float(x) for x in quat]}}, delta_pose=delta, delta_frame=frame) return r["pose"]["position_m"], r["pose"]["quaternion_wxyz"]123456789101112131415161718192021222324252627282930313233"""Tilted grasp geometry. Charger frame: P = prong direction, T = thickness axis (the face the fingertips point into).Gripper (link6) x = cos(beta)*T + sin(beta)*P, link6 y along the width axis W; fingertip centre at body centre + fP*P + fT*T."""import numpy as npTABLE_Z = 0.7655HALF_T = 0.01325TIP_FROM_CENTER = 0.04075 # prong tips from body centre along PFINGER_D = 0.158 # fingertip centre ahead of link6
def frame_pose(center, P, T, beta, fP=0.005, fT=0.0, d=FINGER_D, back=0.0): P = np.asarray(P, float); T = np.asarray(T, float) x = np.cos(beta) * T + np.sin(beta) * P W = np.cross(T, P) y = W z = np.cross(x, y) if z[2] < -1e-9: y = -W; z = np.cross(x, y) Rm = np.stack([x, y, z], 1) F = np.asarray(center) + fP * P + fT * T Tm = np.eye(4); Tm[:3, :3] = Rm; Tm[:3, 3] = F - (d + back) * x return Tm
def grasp_pose(c_xy, p_xy, beta, back=0.0, **kw): p = np.array([p_xy[0], p_xy[1], 0.0]); p /= np.linalg.norm(p) center = np.array([c_xy[0], c_xy[1], TABLE_Z + HALF_T]) return frame_pose(center, p, np.array([0, 0, -1.0]), beta, back=back, **kw)
def insert_pose(tip, b_xy, beta, back=0.0, **kw): b = np.array([b_xy[0], b_xy[1], 0.0]); b /= np.linalg.norm(b) center = np.asarray(tip, float) + np.array([0, 0, TIP_FROM_CENTER]) return frame_pose(center, np.array([0, 0, -1.0]), b, beta, back=back, **kw)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290"""pour_by_language controller: parse instruction, locate bottles/bowls by colour, pour each pair in order."""import jsonimport reimport sysimport timefrom pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))from motion import Robot, EpisodeEnded, QUAT_FWD, interp, merge, log, roll_quat, ik, arm_move_rows, ik_fk, fk_batch # noqa: E402from perception import find_objects, assign_colors, COLOR_RGB # noqa: E402
J_HOME = [0.0] * 6J_LIFT = [0.0, 0.45, 0.722, -0.271, 0.0, 0.0] # idle arm EEF ~18 cm above homeHOME_EEF = {"left": [-0.29953, -0.3523, 0.9215], "right": [0.30047, -0.3523, 0.9215]}GRASP_DY = 0.132 # link6 behind visible-bottle-centre estimateHOLD_DY = 0.14 # bottle axis ahead of link6 while heldGRASP_Z = 0.085 # link6 height above table when grasping (wrist housing must clear bowl rims)LIFT_DZ = 0.160 # link6 height above table when carryingMOUTH_L = 0.133 # grasp axis -> mouth distance (for bottle top at table+0.219)POUR_MOUTH_DZ = 0.08 # mouth height above table during the pour arcAPPROACH_BACK = 0.10 # pre-approach: link6 this far in front (-y) of the grasp poseGRIP_MIN = 0.75 # gripper opening below this after closing => missed the bodyRETREAT_BACK = 0.10 # after release, back the open fingers out this far before going homeHOLD_STEPS = 25 # steps held at the steepest pour angle (flow saturates after ~20)
class GraspFailed(RuntimeError): pass
def parse_instruction(text): """Return ordered list of (bottle_colour, bowl_colour).""" pairs = re.findall(r"(\w+)\s+bottle\s+into\s+the\s+(?:\w+\s+)?(\w+)\s+bowl", text.lower()) out = [] for b, w in pairs: out.append((b, w)) return out
def full_row(R): return list(R.state)
def arm_sign(arm): return 1.0 if arm == "right" else -1.0
def solve(R, arm, pos, quat, seed, what): (q, ep, er), = ik_fk(R, arm, [(pos, quat, seed)]) if ep > 0.003 or er > 0.02: log(f"IK {what} poor ({ep:.4f} m, {er:.4f} rad); trying cuRobo") try: q = ik(R, arm, pos, quat) except RuntimeError as e: log("cuRobo IK failed too:", str(e)[-120:]) return q
def safe_rows(R, arm, a_row, b_row, n, zmin): """Joint interpolation a->b (n rows); if FK shows link6 dipping below zmin, go via a raised midpoint.""" rows = interp(a_row, b_row, n) fk = fk_batch(R, rows[:: max(1, len(rows) // 12)]) low = min(f[arm][0][2] for f in fk) if low >= zmin: return rows log(f"path dips to {low:.3f} < {zmin:.3f}; adding raised via point") s = 0 if arm == "left" else 7 mid = fk_batch(R, [interp(a_row, b_row, 2)[0]])[0][arm] pm = list(mid[0]); pm[2] += (zmin - low) + 0.02 qm = solve(R, arm, pm, mid[1], interp(a_row, b_row, 2)[0][s:s + 6], "via") m_row = list(a_row); m_row[s:s + 6] = qm h = n // 2 return interp(a_row, m_row, h) + interp(m_row, b_row, n - h)
def sideways(R, arm, a_row, j_mid, b_row, tz, n=18): """Row path a->b, through the via point j_mid (two smooth halves) when given.""" zmin = tz + LIFT_DZ - 0.01 if j_mid is None: return safe_rows(R, arm, a_row, b_row, n, zmin) m_row = list(a_row) s = 0 if arm == "left" else 7 m_row[s:s + 6] = list(j_mid) h = (n + 6) // 2 return safe_rows(R, arm, a_row, m_row, h, zmin) + safe_rows(R, arm, m_row, b_row, h, zmin)
def pour_pair(R, arm, bottle, bowl, tz, hold_steps=HOLD_STEPS, debug=None): s = arm_sign(arm) idle = "left" if arm == "right" else "right" ai = 7 if arm == "right" else 0 # first joint column of working arm top = bottle.get("top_z", tz + 0.219) L = top - (tz + GRASP_Z) # grasp axis -> mouth log(f"pour {arm}: bottle {bottle.get('color')} ({bottle['x']:.3f},{bottle['y']:.3f}) -> bowl {bowl.get('color')} ({bowl['x']:.3f},{bowl['y']:.3f}) L={L:.3f}") gx, gy = bottle["x"], bottle["y"] - GRASP_DY gz = tz + GRASP_Z py = bowl["y"] - HOLD_DY th0 = np.radians(126) mx0, mz0 = bowl["x"] + s * 0.010, tz + POUR_MOUTH_DZ + 0.005 pre = [mx0 + s * L * np.sin(th0), py, max(mz0 - L * np.cos(th0), tz + LIFT_DZ)] # key poses (FK-based IK, seeded from nearby solutions) seed0 = [-s * 0.3, 1.6, 0.6, 1.0, -s * 0.3, 0.0] j_pa = solve(R, arm, [gx, gy - APPROACH_BACK, gz + 0.02], QUAT_FWD, seed0, "preapproach") j_above = j_pa j_grasp = solve(R, arm, [gx, gy, gz], QUAT_FWD, j_pa, "grasp") j_lift = solve(R, arm, [gx, gy, tz + LIFT_DZ], QUAT_FWD, j_grasp, "lift") j_back = solve(R, arm, [gx, py, tz + LIFT_DZ + 0.015], QUAT_FWD, j_lift, "back") j_pre = solve(R, arm, pre, QUAT_FWD, j_back, "prepour") j_mid = None # long sideways moves: via point keeps the carried bottle away from the bottle row if abs(pre[0] - gx) > 0.08: j_mid = solve(R, arm, [(gx + pre[0]) / 2, py - 0.01, tz + LIFT_DZ + 0.02], QUAT_FWD, [(a + b) / 2 for a, b in zip(j_back, j_pre)], "mid") mx, mz = bowl["x"] + s * 0.007, tz + POUR_MOUTH_DZ j_arc, seed = [], list(j_pre) for deg in (138, 150): th = np.radians(deg) seed = list(seed); seed[5] = j_pre[5] - s * th seed = solve(R, arm, [mx + s * L * np.sin(th), py, mz - L * np.cos(th)], roll_quat(-s * th), seed, f"arc{deg}") j_arc.append(seed) j_ret = solve(R, arm, [gx, gy - RETREAT_BACK, gz + 0.04], QUAT_FWD, j_grasp, "retreat") log("IK done; pre", [round(v, 2) for v in j_pre], "arc j6", [round(j[5], 2) for j in j_arc])
# 1. approach to a point in front of the bottle; idle arm lifts at the same time home_row = list(R.state) b = list(home_row); b[ai:ai + 6] = j_pa; b[ai + 6] = 1.0 acts_app = interp(home_row, b, 30) idle_rows = interp(J_HOME + [1.0], J_LIFT + [1.0], 22) R.step(merge(acts_app, idle, idle_rows), "approach") if debug: debug(R, "above") # 2. move in (forward and slightly down) around the bottle body, close, lift R.step(arm_move_rows(R, arm, j_grasp, 10, gripper=1.0, start=_cmd(R, arm, j_pa, 1.0)), "insert") log("grasp eef", [round(v, 3) for v in R.eef(arm)[0]], "rem", R.remaining) row = _cmd(R, arm, j_grasp, 0.0) R.step([row] * 3, "close") grip = R.state[ai + 6] log("gripper", round(grip, 3)) if grip < GRIP_MIN: row = _cmd(R, arm, j_grasp, 1.0) R.step([row] * 3, "reopen") R.step(arm_move_rows(R, arm, j_pa, 8, gripper=1.0, start=row), "backout") go_home(R, "fail_home") raise GraspFailed(f"gripper closed to {grip:.3f}") R.step(arm_move_rows(R, arm, j_lift, 8, gripper=0.0, start=row), "lift") # 3. transport: straight back out of the bottle row, then sideways to pre-pour (smooth, no swing) a = _cmd(R, arm, j_lift, 0.0) m = _cmd(R, arm, j_back, 0.0) b = _cmd(R, arm, j_pre, 0.0) R.step(safe_rows(R, arm, a, m, 16, tz + LIFT_DZ - 0.01), "back") R.step(sideways(R, arm, m, j_mid, b, tz), "transport") if debug: debug(R, "prepour") # 4. tilt: joint6 to 126 deg, then arc keeping the mouth over the bowl to 138 and 150 deg a = _cmd(R, arm, j_pre, 0.0) b = list(a); b[ai + 5] = j_pre[5] - s * th0 rows = interp(a, b, 12) prev = b for sol, n in zip(j_arc, (6, 6)): c = list(prev); c[ai:ai + 6] = sol rows += interp(prev, c, n) prev = c rows += [list(prev)] * hold_steps R.step(rows, "pour") if debug: debug(R, "poured") log("poured, rem", R.remaining) # 5. untilt over the bowl, carry back above the original spot, lower, release R.step(interp(prev, _cmd(R, arm, j_pre, 0.0), 12), "untilt") a = _cmd(R, arm, j_pre, 0.0) m = _cmd(R, arm, j_back, 0.0) b = _cmd(R, arm, j_lift, 0.0) R.step(sideways(R, arm, a, j_mid, m, tz, n=16), "carry") R.step(safe_rows(R, arm, m, b, 14, tz + LIFT_DZ - 0.01), "carry_in") j_place = solve(R, arm, [gx, gy, gz + 0.006], QUAT_FWD, j_grasp, "place") R.step(arm_move_rows(R, arm, j_place, 8, gripper=0.0, start=b), "lower") row = _cmd(R, arm, j_place, 1.0) R.step([row] * 3, "open") # 6. retreat up and back out of the bottle, then both arms home R.step(arm_move_rows(R, arm, j_ret, 6, gripper=1.0, start=row), "retreat") go_home(R, "home", start=_cmd(R, arm, j_ret, 1.0)) log("home done, rem", R.remaining)
def go_home(R, name="home", start=None, n=20): a = list(start) if start is not None else list(R.state) b = J_HOME + [1.0] + J_HOME + [1.0] R.step(interp(a, b, n) + [b] * 3, name)
def _cmd(R, arm, j, grip): """Commanded row: working arm at joints j / gripper grip, other arm at its measured joints.""" row = list(R.state) s = 0 if arm == "left" else 7 row[s:s + 6] = list(j) row[s + 6] = grip return row
def choose_arm(bottle, bowl): if bottle["x"] < -0.07: return "left" if bottle["x"] > 0.07: return "right" return "left" if bowl["x"] < 0 else "right"
def scene(R): meta, rgb, depth = R.observe() objs, tz = find_objects(meta, rgb, depth) bottles = [o for o in objs if o["kind"] == "bottle"] bowls = [o for o in objs if o["kind"] == "bowl" and o["height"] < 0.06] log("found", len(bottles), "bottles", len(bowls), "bowls, table", round(tz, 3)) for o in bottles + bowls: log(f" {o['kind']} ({o['x']:.3f},{o['y']:.3f}) h={o['height']:.3f} rgb={[int(v) for v in o['rgb']]}") return bottles, bowls, tz
def identify(R, pairs): """Initial colour identification (before any liquid changes the bowls' look).""" bottles, bowls, tz = scene(R) names_b = [p[0] for p in pairs] names_w = [p[1] for p in pairs] if len(bottles) < len(set(names_b)) or len(bowls) < len(set(names_w)): raise RuntimeError(f"perception: {len(bottles)} bottles / {len(bowls)} bowls") bmap = assign_colors(bottles, list(dict.fromkeys(names_b))) wmap = assign_colors(bowls, list(dict.fromkeys(names_w))) for k, (b, w) in enumerate(pairs): log(f"pair {k}: {b} bottle ({bmap[b]['x']:.3f},{bmap[b]['y']:.3f}) cost {bmap[b]['color_cost']:.0f}" f" -> {w} bowl ({wmap[w]['x']:.3f},{wmap[w]['y']:.3f}) cost {wmap[w]['color_cost']:.0f}") return bmap, wmap, tz
def track(prev, objs, max_d=0.06): """Current detection nearest to a previously identified object (objects can be nudged).""" best, bd = None, max_d for o in objs: d = np.hypot(o["x"] - prev["x"], o["y"] - prev["y"]) if d < bd: best, bd = o, d if best is None: return prev best = dict(best) best["color"] = prev.get("color") return best
def main(ctx, start_pair=0): R = Robot(ctx, "ctl") try: _main(R, start_pair) except EpisodeEnded as e: log("episode ended (before", str(e) + ")") except Exception as e: # never end with an error: try to leave both arms home import traceback log("controller error:", repr(e)) traceback.print_exc() try: if not R.ended and R.last is not None: go_home(R, "rescue_home", n=25) except Exception as e2: log("rescue failed:", repr(e2)) log("controller done; episode ended", R.ended, "remaining steps", R.remaining if R.last else None)
def _main(R, start_pair=0): meta, rgb, depth = R.observe() instr = meta.get("instruction", "") pairs = parse_instruction(instr) log("instruction:", instr, "pairs:", pairs) bmap, wmap, tz = identify(R, pairs) for k in range(start_pair, len(pairs)): for attempt in range(2): if R.ended: return bottles, bowls, tz_now = scene(R) bottle = track(bmap[pairs[k][0]], bottles) bowl = track(wmap[pairs[k][1]], bowls) if bottle["height"] < 0.12: log("bottle no longer upright; stopping") return try: pour_pair(R, choose_arm(bottle, bowl), bottle, bowl, tz) break except GraspFailed as e: log(f"pair {k} attempt {attempt}: {e}") else: log(f"pair {k} failed twice; stopping") return123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295"""Motion helpers: cuRobo previews, merged dual-arm joint execution, EEF stepping."""import jsonimport osimport time
import numpy as np
from perception import parse_obs
QUAT_FWD = [0.70710678, 0.0, 0.0, 0.70710678] # home link6 orientation (gripper points +y)HOME = [0.0] * 6LOG_DIR = "/workspace/output"
def log(*args): print(f"[{time.strftime('%H:%M:%S')}]", *args, flush=True)
class EpisodeEnded(RuntimeError): """The episode terminated (success or step limit); no further robot calls are allowed."""
def meta_of(reply): return json.loads(reply["content"][0]["text"])
class Robot: def __init__(self, ctx, tag="run"): try: os.makedirs(LOG_DIR, exist_ok=True) except OSError: pass self.ctx = ctx self.tag = tag self.ncall = 0 self.last = None # last meta self.ended = False
def _save(self, name, meta): self.ncall += 1 try: slim = {k: v for k, v in meta.items() if k not in ("camera_parameters",)} if "motion_plan" in slim and "trajectory_preview" in slim["motion_plan"]: slim["motion_plan"] = dict(slim["motion_plan"]) with open(os.path.join(LOG_DIR, f"{self.tag}_{self.ncall:03d}_{name}.json"), "w") as f: json.dump(slim, f) except Exception as e: # logging must never break control print("log fail", e)
def _track(self, meta): if meta.get("episode_ended"): self.ended = True if "states" in meta: self.last = meta
def call(self, tool, **kw): if self.ended: raise EpisodeEnded(tool) return self.ctx.call(tool, **kw)
def observe(self): r = self.call("robodojo_observe") meta, rgb, depth = parse_obs(r) self._track(meta) return meta, rgb, depth
@property def state(self): return list(self.last["states"])
@property def remaining(self): return self.last["episode_limits"]["remaining_episode_steps"]
def eef(self, arm): i = 0 if arm == "left" else 1 return list(self.last["eef_positions"][i]), list(self.last["eef_quaternions_wxyz"][i])
def plan(self, arm, pos, quat, gripper=None): target = {"position": [float(v) for v in pos], "quaternion_wxyz": [float(v) for v in quat]} if gripper is not None: target["gripper_opening"] = float(gripper) r = self.call("robodojo_free_space_move", arm=arm, target=target, preview_only=True, include_trajectory=True) meta = meta_of(r) self._track(meta) mp = meta.get("motion_plan", {}) self._save(f"plan_{arm}", {"motion_plan": {k: v for k, v in mp.items() if k != "trajectory_preview"}}) if mp.get("status") != "Success": raise RuntimeError(f"plan failed {arm} {pos}: {mp.get('status')} {mp.get('failure_stage')} {mp.get('reason')}") return [list(a) for a in mp["trajectory_preview"]["actions"]], mp
def step(self, actions, name="step"): """Execute 14D joint rows in chunks of <=50; returns last meta.""" meta = None for i in range(0, len(actions), 50): chunk = [[float(v) for v in a] for a in actions[i:i + 50]] r = self.call("robodojo_step", actions=chunk) meta = meta_of(r) self._track(meta) self._save(name, {k: v for k, v in meta.items() if k not in ("transition",)} | {"transition_summary": summarize_transition(meta.get("transition"))}) if meta.get("episode_ended") or meta.get("task_complete") or (meta.get("transition") or {}).get("task_complete"): self.ended = self.ended or meta.get("episode_ended", False) return meta
def step_eef(self, targets, name="eef"): meta = None for i in range(0, len(targets), 50): r = self.call("robodojo_step_eef", targets=targets[i:i + 50]) meta = meta_of(r) self._track(meta) self._save(name, {k: v for k, v in meta.items() if k not in ("transition",)} | {"transition_summary": summarize_transition(meta.get("transition"))}) return meta
def summarize_transition(tr): if not tr: return None out = {k: v for k, v in tr.items() if k != "steps"} steps = tr.get("steps") or [] out["n_steps"] = len(steps) if steps: out["first_step"] = steps[0] out["last_step"] = steps[-1] return out
def interp(a, b, n): """n rows linearly interpolated from a (exclusive) to b (inclusive), smoothstep timing.""" a = np.asarray(a, float) b = np.asarray(b, float) rows = [] for k in range(1, n + 1): s = k / n s = s * s * (3 - 2 * s) rows.append(list(a + (b - a) * s)) return rows
def n_for(a, b, vmax=0.06, nmin=3): """Number of 25 Hz steps to move joints a->b with peak per-step joint delta about vmax.""" d = np.max(np.abs(np.asarray(a[:6]) - np.asarray(b[:6]))) return max(nmin, int(np.ceil(1.5 * d / vmax)))
def arm_cols(arm): return slice(0, 7) if arm == "left" else slice(7, 14)
def merge(rows, arm, arm_rows): """Replace the 7 columns of `arm` in rows with arm_rows (padded with its last row).""" n = max(len(rows), len(arm_rows)) out = [] for k in range(n): r = list(rows[min(k, len(rows) - 1)]) a = arm_rows[min(k, len(arm_rows) - 1)] s = arm_cols(arm) r[s] = list(a) out.append(r) return out
def qmul(a, b): w1, x1, y1, z1 = a w2, x2, y2, z2 = b return [w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2, w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2, w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2, w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2]
def qaxis(axis, ang): axis = np.asarray(axis, float) / np.linalg.norm(axis) s = np.sin(ang / 2) return [float(np.cos(ang / 2)), *(float(v) for v in axis * s)]
def roll_quat(phi, base=QUAT_FWD): """Rotate the home orientation about its local x (approach) axis by phi. phi > 0 tilts a held upright bottle's neck toward world +x.""" q = qmul(base, qaxis([1, 0, 0], phi)) n = np.linalg.norm(q) q = [v / n for v in q] if q[0] < 0: q = [-v for v in q] return q
def ik(R, arm, pos, quat): """Joint solution (6) for a link6 pose, via a cuRobo preview from the current state.""" _, mp = R.plan(arm, pos, quat) return list(mp["final_arm_joint_state"])
def arm_move_rows(R, arm, j_target, n, gripper=None, start=None): """Rows interpolating only `arm` joints from current measured (or `start`) row to j_target.""" a = list(start) if start is not None else list(R.state) b = list(a) s = 0 if arm == "left" else 7 b[s:s + 6] = list(j_target) if gripper is not None: b[s + 6] = gripper a[s + 6] = gripper return interp(a, b, n)
def resample(rows, factor): """Stretch a trajectory in time by `factor` (linear resampling of joint rows).""" rows = np.asarray(rows, float) n = len(rows) m = int(round(n * factor)) t_old = np.linspace(0, 1, n) t_new = np.linspace(0, 1, m) out = np.stack([np.interp(t_new, t_old, rows[:, j]) for j in range(rows.shape[1])], axis=1) return [list(r) for r in out]
def qconj(q): return [q[0], -q[1], -q[2], -q[3]]
def qlog(q): """Rotation vector of unit quaternion q (shortest).""" q = np.asarray(q, float) if q[0] < 0: q = -q v = q[1:] n = np.linalg.norm(v) if n < 1e-12: return np.zeros(3) ang = 2 * np.arctan2(n, q[0]) return v / n * ang
def fk_batch(R, rows): """FK of up to 50 14-D rows -> list of {'left':(p,q), 'right':(p,q)}.""" rows = [list(map(float, r)) for r in rows] n = len(rows) pad = rows + [rows[-1]] * (50 - n) r = R.call("robodojo_fk_preview", actions=pad) m = meta_of(r) out = [] for t in m["trajectory"][:n]: out.append({a: (np.array(t[a]["position"]), list(t[a]["quaternion_wxyz"])) for a in ("left", "right")}) return out
def ik_fk(R, arm, targets, iters=12, eps=1e-3, tol_p=5e-4, tol_r=3e-3): """Numerical DLS IK through robodojo_fk_preview. targets: list of (pos, quat, q_init(6)); up to 7 solved per FK call. Returns list of (q, perr, rerr).""" s = 0 if arm == "left" else 7 base = [0.0] * 6 + [1.0] + [0.0] * 6 + [1.0] results = [] for k0 in range(0, len(targets), 7): group = targets[k0:k0 + 7] qs = [np.array(t[2], float) for t in group] done = [False] * len(group) errs = [(1.0, 1.0)] * len(group) for it in range(iters): rows = [] for q in qs: r0 = list(base); r0[s:s + 6] = list(q); rows.append(r0) for j in range(6): r1 = list(r0); r1[s + j] += eps; rows.append(r1) fk = fk_batch(R, rows) for i, (pos, quat, _) in enumerate(group): if done[i]: continue p0, q0 = fk[7 * i][arm] ep = np.asarray(pos, float) - p0 er = qlog(qmul(quat, qconj(q0))) errs[i] = (float(np.linalg.norm(ep)), float(np.linalg.norm(er))) if errs[i][0] < tol_p and errs[i][1] < tol_r: done[i] = True continue J = np.zeros((6, 6)) for j in range(6): p1, q1 = fk[7 * i + 1 + j][arm] J[:3, j] = (p1 - p0) / eps J[3:, j] = qlog(qmul(q1, qconj(q0))) / eps e = np.concatenate([ep, er * 0.3]) Jw = J.copy(); Jw[3:] *= 0.3 lam = 1e-3 dq = Jw.T @ np.linalg.solve(Jw @ Jw.T + lam * np.eye(6), e) mx = np.max(np.abs(dq)) if mx > 0.4: dq *= 0.4 / mx qs[i] = qs[i] + dq if all(done): break for i in range(len(group)): results.append((list(map(float, qs[i])), errs[i][0], errs[i][1])) return results123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Observation parsing and depth-based geometry for the pour task."""import base64import ioimport json
import numpy as npfrom PIL import Image
def parse_obs(reply): """Return (meta, rgb dict, depth dict in metres) from an MCP observation reply.""" content = reply["content"] meta = json.loads(content[0]["text"]) rgb, depth = {}, {} for att in meta.get("attachments", []): block = content[att["content_index"]] data = base64.b64decode(block["data"]) img = Image.open(io.BytesIO(data)) if att["kind"] == "rgb": rgb[att["camera"]] = np.asarray(img.convert("RGB")) elif att["kind"] == "depth": depth[att["camera"]] = np.asarray(img).astype(np.float32) * 0.001 return meta, rgb, depth
def cam_matrices(meta, cam): p = meta["camera_parameters"][cam] K = np.array(p["intrinsic_matrix"], dtype=float) T = np.array(p["camera_to_world_usd"], dtype=float) return K, T
def deproject(meta, depth, cam, us, vs): """Pixel arrays (u right, v down) + depth -> world points (N,3).""" K, T = cam_matrices(meta, cam) us = np.asarray(us, dtype=float) vs = np.asarray(vs, dtype=float) z = depth[cam][vs.astype(int), us.astype(int)] x = (us - K[0, 2]) / K[0, 0] * z y = (vs - K[1, 2]) / K[1, 1] * z p_usd = np.stack([x, -y, -z], axis=-1) return p_usd @ T[:3, :3].T + T[:3, 3]
def project(meta, cam, pts): """World points (N,3) -> pixel (u,v) arrays.""" K, T = cam_matrices(meta, cam) pts = np.atleast_2d(pts) p_usd = (pts - T[:3, 3]) @ T[:3, :3] z = -p_usd[:, 2] u = K[0, 0] * p_usd[:, 0] / z + K[0, 2] v = K[1, 1] * (-p_usd[:, 1]) / z + K[1, 2] return u, v, z
def world_cloud(meta, depth, cam="cam_high"): h, w = depth[cam].shape vv, uu = np.mgrid[0:h, 0:w] pts = deproject(meta, depth, cam, uu.ravel(), vv.ravel()) return pts.reshape(h, w, 3)
TABLE_Z_DEFAULT = 0.765
# Reference RGB for colour words that may appear in instructions.COLOR_RGB = { "red": (230, 20, 20), "turquoise": (20, 220, 205), "cyan": (20, 220, 220), "teal": (0, 128, 128), "violet": (200, 180, 230), "purple": (150, 80, 200), "lavender": (200, 180, 230), "white": (240, 240, 240), "black": (38, 38, 38), "brown": (90, 62, 50), "gray": (128, 128, 128), "grey": (128, 128, 128), "green": (30, 200, 40), "blue": (30, 60, 220), "yellow": (230, 220, 30), "orange": (240, 140, 20), "pink": (240, 150, 190), "magenta": (230, 30, 200), "silver": (190, 190, 195), "gold": (210, 175, 55), "beige": (225, 210, 175), "navy": (20, 30, 110), "olive": (128, 128, 0), "maroon": (128, 20, 20), "cream": (250, 240, 210), "tan": (210, 180, 140),}
def table_height(P): z = P[150:450, 100:540, 2].ravel() z = z[(z > 0.5) & (z < 1.0)] hist, edges = np.histogram(z, bins=350, range=(0.5, 1.2)) k = np.argmax(hist) return float(edges[k] + edges[k + 1]) / 2
def find_objects(meta, rgb, depth, cam="cam_high"): """Segment objects standing on the table in front of the robot from cam_high depth.""" from scipy import ndimage P = world_cloud(meta, depth, cam) tz = table_height(P) z = P[..., 2] mask = (z > tz + 0.008) & (np.abs(P[..., 0]) < 0.45) & (P[..., 1] > -0.30) & (P[..., 1] < 0.35) # exclude the grippers / arms: anything whose top is near the robot (y < -0.18 and high) lab, n = ndimage.label(mask) objs = [] img = rgb[cam] for i in range(1, n + 1): m = lab == i if m.sum() < 150: continue pts = P[m] hgt = pts[:, 2].max() - tz xs, ys = pts[:, 0], pts[:, 1] width = np.percentile(xs, 98) - np.percentile(xs, 2) cols = img[m] obj = {"n": int(m.sum()), "height": float(hgt), "width": float(width), "x": float((np.percentile(xs, 98) + np.percentile(xs, 2)) / 2), "y_front": float(np.percentile(ys, 2)), "y_back": float(np.percentile(ys, 98)), "u": float(np.nonzero(m)[1].mean()), "v": float(np.nonzero(m)[0].mean())} grounded = pts[:, 2].min() < tz + 0.03 if not grounded: obj["kind"] = "other" elif 0.12 < hgt < 0.40 and width < 0.15: obj["kind"] = "bottle" # body points (lower 45% of height) give the body radius / centre body = pts[pts[:, 2] < tz + 0.45 * hgt] bw = np.percentile(body[:, 0], 98) - np.percentile(body[:, 0], 2) obj["x"] = float((np.percentile(body[:, 0], 98) + np.percentile(body[:, 0], 2)) / 2) obj["radius"] = float(bw / 2) obj["y"] = float(np.percentile(body[:, 1], 2) + bw / 2) obj["body_top"] = float(_body_top(pts, tz, bw)) colmask = pts[:, 2] < tz + 0.6 * hgt obj["rgb"] = [float(c) for c in np.median(cols[colmask], 0)] elif 0.015 < hgt < 0.10 and 0.06 < width < 0.25: obj["kind"] = "bowl" obj["y"] = float((obj["y_front"] + obj["y_back"]) / 2) obj["radius"] = float(width / 2) obj["rgb"] = [float(c) for c in np.median(cols, 0)] if obj.get("kind", "other") == "other": obj["kind"] = "other" obj["y"] = float((obj["y_front"] + obj["y_back"]) / 2) obj["rgb"] = [float(c) for c in np.median(cols, 0)] obj["top_z"] = float(pts[:, 2].max()) objs.append(obj) return objs, tz
def _body_top(pts, tz, bw): """Height where the bottle narrows below 70% of the body width.""" zs = np.arange(tz + 0.02, pts[:, 2].max(), 0.01) for z0 in zs: s = pts[(pts[:, 2] >= z0) & (pts[:, 2] < z0 + 0.01)] if len(s) > 10 and (np.percentile(s[:, 0], 98) - np.percentile(s[:, 0], 2)) < 0.7 * bw: return z0 return pts[:, 2].max()
def color_dist(rgb, name): ref = np.array(COLOR_RGB[name], float) c = np.array(rgb, float) # compare in a rough perceptual way: chroma-normalised + brightness return float(np.linalg.norm(c - ref))
def assign_colors(objs, names): """Hungarian assignment of colour names to objects (len(objs) >= len(names)).""" from itertools import permutations C = np.array([[color_dist(o["rgb"], nm) if nm in COLOR_RGB else 1e3 for nm in names] for o in objs]) best = min(permutations(range(len(objs)), len(names)), key=lambda perm: sum(C[i, j] for j, i in enumerate(perm))) out = {} for j, i in enumerate(best): out[names[j]] = objs[i] objs[i]["color"] = names[j] objs[i]["color_cost"] = float(C[i, j]) return out1234567# Swap blocks controller
`controller.py:main(ctx)` uses color-based RGB localization and native depth unprojection. It finds the three pale mats, identifies the two occupied mats, and derives the three transfers through the empty mat. All motion uses native pose formatting and cuRobo. Wrist RGB/depth verifies lifted and placed blocks. Presses use one closed-gripper descent and retreat per transfer. The active arm returns to its measured initial EEF pose; the unused arm remains home.
The learned grasp geometry uses a 30-degree lean toward +x, with link6 offset [-0.075, 0, 0.115] from a visible block top. Lift is 0.08m. Button descent ends 0.1375m above the measured top surface; retreat is 0.2225m above it. These offsets were confirmed by direct exploration success before autonomous development.
Run development via `python code/swap_blocks/operate.py` in an existing exploration episode. The isolated runner supplies the context directly to `main`. Outputs go to `/workspace/output/events.json`. No training weights, network access, external model calls, prior episode frames, or simulator internals are used.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267"""Observation-driven three-move swap. All physical control uses native MCP."""import base64import jsonimport mathfrom pathlib import Path
import cv2import numpy as np
OUT = Path('/workspace/output')
def metadata(reply): return json.loads(next(b['text'] for b in reply['content'] if b['type'] == 'text'))
def rgb(reply, camera='cam_high'): obs = metadata(reply) index = next(a['content_index'] for a in obs['attachments'] if a['kind'] == 'rgb' and a['camera'] == camera) return cv2.imdecode(np.frombuffer(base64.b64decode(reply['content'][index]['data']), np.uint8), 1)
def masks(im): hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV) mat = cv2.inRange(hsv, np.array([18,25,160]), np.array([40,155,255])) red = (((hsv[:,:,0] <= 3) | (hsv[:,:,0] >= 175)) & (hsv[:,:,1] > 130) & (hsv[:,:,2] > 160)).astype(np.uint8)*255 orange = cv2.inRange(hsv, np.array([4,140,160]), np.array([16,255,255])) return mat, red, orange
def components(mask): n, labels, stats, centroids = cv2.connectedComponentsWithStats(mask) return [(stats[i], centroids[i], labels == i) for i in range(1,n)]
def mat_centers(im): mat, _, _ = masks(im) h,w = im.shape[:2] found = [] for s,c,m in components(mat): x,y,bw,bh,area = s if 20 <= bw <= 85 and 20 <= bh <= 85 and .7 < bw/bh < 1.5 and area > 250: if .15*w < c[0] < .85*w and .25*h < c[1] < .85*h: found.append([float(x+(bw-1)/2), float(y+(bh-1)/2)]) if len(found) != 3: raise RuntimeError(f'Expected three mat disks, found {found}') return sorted(found)
def block_pixel(im, anchor=None): _, red, _ = masks(im) if anchor is not None: yy,xx = np.indices(red.shape) red[((xx-anchor[0])**2 + (yy-anchor[1])**2) > 27**2] = 0 candidates = [(s,c,m) for s,c,m in components(red) if s[4] >= 35 and s[2]>=6 and s[3]>=6] if not candidates: return None if anchor is None: ref = np.array([im.shape[1]/2, im.shape[0]*.56]) s,c,m = min(candidates,key=lambda t: np.linalg.norm(t[1]-ref)) else: s,c,m = min(candidates,key=lambda t: np.linalg.norm(t[1]-anchor)) # Bright top face instead of the lower shaded front face. v = im[:,:,2] top = m & (v >= max(225, int(np.percentile(v[m],75))-5)) if np.count_nonzero(top) < 12: top = m yy,xx = np.where(top) center = np.array([np.mean(xx),np.mean(yy)]) # Select an actual interior pixel, avoiding antialiased boundaries. dist = cv2.distanceTransform(top.astype(np.uint8), cv2.DIST_L2, 3) valid = dist >= min(2.5,float(dist.max())) vy,vx = np.where(valid) k = np.argmin((vx-center[0])**2+(vy-center[1])**2) return [float(vx[k]),float(vy[k])]
def button_pixel(im): _,_,orange = masks(im) h,w = im.shape[:2] cs = [(s,c,m) for s,c,m in components(orange) if s[4]>100 and 12<s[2]<100 and 12<s[3]<100 and .2*w<c[0]<.8*w and .4*h<c[1]<.9*h] if not cs: raise RuntimeError('Button not visible') s,c,m = max(cs,key=lambda t:t[0][4]) return [float(round(c[0])),float(round(c[1]))]
class Ended(Exception): pass
class Swap: def __init__(self,ctx): self.ctx=ctx self.reply=ctx.call('robodojo_observe') self.obs=metadata(self.reply) self.home_pos=self.obs['eef_positions'][0] self.home_q=self.obs['eef_quaternions_wxyz'][0] self.anchors=mat_centers(rgb(self.reply)) self.presses=0 self.events=[] self.qtilt=self.rotation([0,math.pi/3,0]) self.qdown=self.rotation([0,math.pi/2,0]) OUT.mkdir(parents=True,exist_ok=True) self.log('initial',anchors=self.anchors)
def log(self,event,**data): row=dict(event=event,step=self.obs.get('step_id'),**data) print(json.dumps(row),flush=True) self.events.append(row) (OUT/'events.json').write_text(json.dumps(self.events,indent=2))
def rotation(self,euler): return metadata(self.ctx.call('robodojo_pose_math',operation='convert_rotation', rotation={'representation':'euler_xyz_extrinsic_rad','value':euler}, output_representation='quaternion_wxyz'))['quaternion_wxyz']
def accept(self,r): self.reply=r self.obs=metadata(r) tr=self.obs.get('transition',{}) if self.obs.get('episode_ended') or tr.get('episode_ended'): self.log('native_terminal',transition_status=tr.get('status'),presses=self.presses) raise Ended()
def move(self,pos,q=None,opening=0,label='move',contact=False): q=self.qtilt if q is None else q target=metadata(self.ctx.call('robodojo_pose_math',operation='format_target', target_kind='free_space_move',pose={'position_m':list(map(float,pos)), 'rotation':{'representation':'quaternion_wxyz','value':q}},gripper_opening=opening))['target'] r=self.ctx.call('robodojo_free_space_move',arm='left',target=target) self.accept(r) plan=self.obs.get('motion_plan',{}) tr=self.obs.get('transition',{}) if plan.get('status')!='Success': raise RuntimeError(f'{label}: planner rejected target: {plan}') err=tr.get('measured_goal_error',{}) pe=err.get('final_position_error_m',1) re=err.get('final_rotation_error_rad',1) self.log(label,target=pos,position_error=pe,rotation_error=re) if pe>(.008 if contact else .004) or re>.04: raise RuntimeError(f'{label}: physical tracking error {err}')
def grip(self,opening): a=list(self.obs['states']);a[6]=opening self.accept(self.ctx.call('robodojo_step',actions=[a]*8)) actual=self.obs['states'][6] self.log('grip',command=opening,measured=actual) if opening==0 and not .20<actual<.8: raise RuntimeError(f'No cube retained by gripper: {actual}')
def point(self,pixel,camera='cam_high'): p=metadata(self.ctx.call('robodojo_pixel_to_position', observation_step_id=self.obs['step_id'],method='auto', selections=[{'camera':camera,'pixel':list(map(float,pixel))}])) if p.get('status')!='Success' or p.get('quality',{}).get('label')!='good': raise RuntimeError(f'Unreliable surface geometry {p}') return p['position_environment_m']
def block(self,index): # The button approach can hide half a cube and bias its centroid. if self.obs['step_id'] > 0: self.move(self.home_pos,self.home_q,1,'clear_view') pix=block_pixel(rgb(self.reply),self.anchors[index]) if pix is None: self.move(self.home_pos,self.home_q,1,'clear_view') pix=block_pixel(rgb(self.reply),self.anchors[index]) if pix is None: raise RuntimeError(f'No block at mat {index}') p=self.point(pix) self.log('block_localized',mat=index,pixel=pix,point=p) return p
def mat(self,index): im=rgb(self.reply); mat,_,_=masks(im) u,v=self.anchors[index] # Refresh the center when enough of the current empty disk is visible. cs=[] for s,c,m in components(mat): x,y,bw,bh,area=s if area>300 and 25<=bw<=70 and 25<=bh<=70 and np.linalg.norm(c-[u,v])<20: cs.append([float(x+(bw-1)/2),float(y+(bh-1)/2)]) if cs: u,v=min(cs,key=lambda x:np.linalg.norm(np.array(x)-self.anchors[index])) if not mat[int(round(v)),int(round(u))]: yy,xx=np.where(mat) d=(xx-u)**2+(yy-v)**2 if len(d)==0 or d.min()>10**2: raise RuntimeError(f'Destination mat {index} occluded') k=d.argmin();u,v=float(xx[k]),float(yy[k]) p=self.point([u,v]) self.log('mat_localized',mat=index,pixel=[u,v],point=p) return p
def verify_block(self,target_xy,min_z,max_z,label): im=rgb(self.reply,'cam_left_wrist') pix=block_pixel(im) if pix is None: raise RuntimeError(f'{label}: block not visible in wrist') p=self.point(pix,'cam_left_wrist') self.log(label,point=p,pixel=pix) if not min_z<p[2]<max_z or np.linalg.norm(np.array(p[:2])-target_xy)>.032: raise RuntimeError(f'{label}: unexpected block position {p}')
def transfer(self,source,destination): p=self.block(source) grasp=[p[0]-.075,p[1],p[2]+.115] above=[grasp[0],grasp[1],grasp[2]+.08] self.move(above,opening=1,label='approach') self.move(grasp,opening=1,label='descend_grasp') self.grip(0) self.move(above,opening=0,label='lift') self.verify_block(p[:2],p[2]+.035,p[2]+.13,'lift_verified') d=self.mat(destination) carry=[d[0]-.075,d[1],d[2]+.229] place=[d[0]-.075,d[1],d[2]+.149] start=np.array(self.obs['eef_positions'][0]) count=max(1,int(math.ceil(np.linalg.norm(np.array(carry)-start)/.055))) for k in range(1,count+1): target=(start+(np.array(carry)-start)*(k/count)).tolist() self.move(target,label='carry') if self.obs['states'][6] < .25: raise RuntimeError('Cube slipped during carry') self.move(place,label='place',contact=True) self.grip(1) self.move([d[0]-.075,d[1],d[2]+.245],opening=1,label='clear_placement') self.verify_block(d[:2],d[2]+.020,d[2]+.05,'placement_verified') self.log('transfer_complete',source=source,destination=destination)
def press(self): if self.presses>=3: raise RuntimeError('Refusing a fourth press') p=self.point(button_pixel(rgb(self.reply))) self.log('button_localized',point=p) # Exactly one descent and retreat, with a 8.5cm clearance stroke. top=[p[0],p[1],p[2]+.2225] low=[p[0],p[1],p[2]+.1375] self.move(top,self.qdown,0,'button_approach') self.move(low,self.qdown,0,'button_press',contact=True) self.presses+=1 self.move(top,self.qdown,0,'button_release') self.log('press_complete',presses=self.presses)
def run(self): occupied=[i for i,a in enumerate(self.anchors) if block_pixel(rgb(self.reply),a) is not None] empty=[i for i in range(3) if i not in occupied] if len(occupied)!=2 or len(empty)!=1: raise RuntimeError(f'Invalid initial occupancy {occupied}') a,b=occupied;c=empty[0] sequence=[(a,c),(b,a),(c,b)] self.log('sequence',sequence=sequence) for source,dest in sequence: self.transfer(source,dest) self.press() self.move(self.home_pos,self.home_q,1,'home') self.log('finished',presses=self.presses)
def main(ctx): task=Swap(ctx) try: task.run() except Ended: return1234from api.runtime import Contextfrom controller import mainwith Context() as ctx: main(ctx)robodojo/make_kong/controller.pyAdded+596
robodojo/make_kong/scene.pyAdded+78
robodojo/make_kong/triangulation.pyAdded+149
robodojo/make_kong/vision.pyAdded+45
robodojo/plug_in_charger/controller.pyAdded+70
robodojo/plug_in_charger/ctl.pyAdded+372
robodojo/plug_in_charger/ctl2.pyAdded+808
robodojo/plug_in_charger/geom3.pyAdded+62
robodojo/plug_in_charger/kin.pyAdded+119
robodojo/plug_in_charger/kin_model.jsonAdded+158
robodojo/plug_in_charger/motion.pyAdded+64
robodojo/plug_in_charger/perception.pyAdded+151
robodojo/plug_in_charger/robot.pyAdded+136
robodojo/plug_in_charger/tilt.pyAdded+33
robodojo/pour_by_language/controller.pyAdded+290
robodojo/pour_by_language/motion.pyAdded+295
robodojo/pour_by_language/perception.pyAdded+165
robodojo/swap_blocks/README.mdAdded+7
robodojo/swap_blocks/controller.pyAdded+267
robodojo/swap_blocks/operate.pyAdded+4