diff --git a/policies/drawer_top_open/kimi31pro-s1/episodes.csv b/policies/drawer_top_open/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a737af06b8968364118a1ffbccd1f204304c6485 --- /dev/null +++ b/policies/drawer_top_open/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1350,timeout,0 +620001,0,1350,timeout,0 +620002,0,1350,timeout,0 +620003,0,1350,timeout,0 +620004,0,1350,timeout,0 +620005,0,1350,timeout,0 +620006,0,1350,timeout,0 +620007,0,1350,timeout,0 +620008,0,1350,timeout,0 +620009,0,1350,timeout,0 +620010,0,1350,timeout,0 +620011,0,1350,timeout,0 +620012,0,1350,timeout,0 +620013,0,1350,timeout,0 +620014,0,1350,timeout,0 +620015,0,1350,timeout,0 +620016,0,1350,timeout,0 +620017,0,1350,timeout,0 +620018,0,1350,timeout,0 +620019,0,1350,timeout,0 +620020,0,1350,timeout,0 +620021,0,1350,timeout,0 +620022,0,1350,timeout,0 +620023,0,1350,timeout,0 +620024,0,1350,timeout,0 +620025,0,1350,timeout,0 +620026,0,1350,timeout,0 +620027,0,1350,timeout,0 +620028,0,1350,timeout,0 +620029,0,1350,timeout,0 +620030,0,1350,timeout,0 +620031,0,1350,timeout,0 +620032,0,1350,timeout,0 +620033,0,1350,timeout,0 +620034,0,1350,timeout,0 +620035,0,1350,timeout,0 +620036,0,1350,timeout,0 +620037,0,1350,timeout,0 +620038,0,1350,timeout,0 +620039,0,1350,timeout,0 +620040,0,1350,timeout,0 +620041,0,1350,timeout,0 +620042,0,1350,timeout,0 +620043,0,1350,timeout,0 +620044,0,1350,timeout,0 +620045,0,1350,timeout,0 +620046,0,1350,timeout,0 +620047,0,1350,timeout,0 +620048,0,1350,timeout,0 +620049,0,1350,timeout,0 +620050,0,1350,timeout,0 +620051,0,1350,timeout,0 +620052,0,1350,timeout,0 +620053,0,1350,timeout,0 +620054,0,1350,timeout,0 +620055,0,1350,timeout,0 +620056,0,1350,timeout,0 +620057,0,1350,timeout,0 +620058,0,1350,timeout,0 +620059,0,1350,timeout,0 +620060,0,1350,timeout,0 +620061,0,1350,timeout,0 +620062,0,1350,timeout,0 +620063,0,1350,timeout,0 +620064,0,1350,timeout,0 +620065,0,1350,timeout,0 +620066,0,1350,timeout,0 +620067,0,1350,timeout,0 +620068,0,1350,timeout,0 +620069,0,1350,timeout,0 +620070,0,1350,timeout,0 +620071,0,1350,timeout,0 +620072,0,1350,timeout,0 +620073,0,1350,timeout,0 +620074,0,1350,timeout,0 +620075,0,1350,timeout,0 +620076,0,1350,timeout,0 +620077,0,1350,timeout,0 +620078,0,1350,timeout,0 +620079,0,1350,timeout,0 +620080,0,1350,timeout,0 +620081,0,1350,timeout,0 +620082,0,1350,timeout,0 +620083,0,1350,timeout,0 +620084,0,1350,timeout,0 +620085,0,1350,timeout,0 +620086,0,1350,timeout,0 +620087,0,1350,timeout,0 +620088,0,1350,timeout,0 +620089,0,1350,timeout,0 +620090,0,1350,timeout,0 +620091,0,1350,timeout,0 +620092,0,1350,timeout,0 +620093,0,1350,timeout,0 +620094,0,1350,timeout,0 +620095,0,1350,timeout,0 +620096,0,1350,timeout,0 +620097,0,1350,timeout,0 +620098,0,1350,timeout,0 +620099,0,1350,timeout,0 diff --git a/policies/drawer_top_open/kimi31pro-s1/policy.py b/policies/drawer_top_open/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ce7637ed54d46233fe4664740ded50f390f17dbb --- /dev/null +++ b/policies/drawer_top_open/kimi31pro-s1/policy.py @@ -0,0 +1,143 @@ +"""Hand-written visual control for opening the cabinet's top drawer.""" +import cv2 +import numpy as np + + +class Policy: + """Approach, align to the top drawer handle, close, and pull.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + state = np.asarray(obs["low_dim_obs"], dtype=np.float32) + self.origin = state[18:22].copy() + self.t = 0 + self.pre = np.array([-1.2, 0.0, 0.0, 1.5, 1.57, -0.7, 0.0], dtype=np.float32) + self.forward = 0.08 + self.right = -0.05 + self.arm_yaw = 0.0 + self.track = None + self.missed = 0 + self.stable = 0 + self.close_t = None + self.last_detection = None + + def base_to(self, state, forward, right): + """Request a base displacement in the initial body frame.""" + ox, oy, _, yaw0 = self.origin + dx = ox + forward * np.cos(yaw0) + right * np.sin(yaw0) - state[18] + dy = oy + forward * np.sin(yaw0) - right * np.cos(yaw0) - state[19] + yaw = state[21] + ex = np.cos(yaw) * dx + np.sin(yaw) * dy + ey = -np.sin(yaw) * dx + np.cos(yaw) * dy + vx = np.clip(3.0 * ex, -0.14, 0.14) + vy = np.clip(3.0 * ey, -0.14, 0.14) + if 0.001 < abs(vx) < 0.065: + vx = np.sign(vx) * 0.065 + if 0.001 < abs(vy) < 0.065: + vy = np.sign(vy) * 0.065 + if abs(ex) < 0.007: + vx = 0.0 + if abs(ey) < 0.007: + vy = 0.0 + yaw_error = (yaw0 - yaw + np.pi) % (2 * np.pi) - np.pi + return vx, vy, np.clip(1.5 * yaw_error, -0.22, 0.22) + + @staticmethod + def handles(image): + """Find dark handle bars surrounded by the white cabinet panels.""" + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + spread = (np.max(image, axis=2).astype(np.int16) + - np.min(image, axis=2).astype(np.int16)) + dark = np.uint8((gray < 140) & (spread < 35)) + dark[:, :5] = 0 + dark[:, 80:] = 0 + dark[80:, :] = 0 + distance = cv2.distanceTransform(dark, cv2.DIST_L2, 3) + core = np.uint8(distance >= 1.2) + count, labels, stats, centroids = cv2.connectedComponentsWithStats(core, 8) + candidates = [] + for i in range(1, count): + x, y, w, h, area = [int(v) for v in stats[i]] + if area < 8 or w < 7 or w > 40 or h < 15 or h > 75: + continue + if y + h > 82 or h < 1.05 * w: + continue + x0, x1 = max(0, x - 3), min(84, x + w + 3) + y0, y1 = max(0, y - 3), min(84, y + h + 3) + background = ((gray[y0:y1, x0:x1] > 165) + & (spread[y0:y1, x0:x1] < 35)) + if float(np.mean(background)) < 0.35: + continue + cx, cy = centroids[i] + candidates.append((area, float(cx), float(cy), h, (x, y, w, h))) + return candidates + + def acquire(self, detections): + """Track the rightmost full handle, which is the top drawer here.""" + if self.track is None: + return max(detections, key=lambda item: item[1]) if detections else None + farther_right = [item for item in detections if item[1] > self.track[1] + 8] + if farther_right: + return max(farther_right, key=lambda item: item[1]) + near = [item for item in detections + if abs(item[1] - self.track[1]) < 20 and abs(item[2] - self.track[2]) < 30] + if near: + return min(near, key=lambda item: (item[1] - self.track[1]) ** 2 + + 0.25 * (item[2] - self.track[2]) ** 2) + return None + + def act(self, obs, tools): + state = np.asarray(obs["low_dim_obs"], dtype=np.float32) + raw = self.hold.copy() + raw[:4] = [0.0, 0.0, 0.74, 0.0] + alpha = 0.0 if self.t < 100 else min(1.0, (self.t - 99) / 110.0) + alpha = alpha * alpha * (3.0 - 2.0 * alpha) + raw[4:11] = alpha * self.pre + if self.t >= 230: + raw[6] = self.arm_yaw + raw[10] = self.arm_yaw + raw[18:20] = 0.0 + + if self.t < 230: + raw[0], raw[1], raw[3] = self.base_to(state, self.forward, self.right) + + if self.t >= 230 and self.close_t is None: + found = self.acquire(self.handles(tools.image("left_wrist"))) + if found is not None: + self.track = found + self.missed = 0 + else: + self.missed += 1 + self.last_detection = found + guidance = found if found is not None else self.track + if guidance is not None: + _, cx, cy, height, _ = guidance + if self.t % 2 == 0: + gain = 0.00025 if found is not None else 0.0001 + self.arm_yaw += float(np.clip(-gain * (cx - 42.0), -0.002, 0.002)) + self.arm_yaw = float(np.clip(self.arm_yaw, -0.65, 0.3)) + aligned = (found is not None and abs(cx - 42) < 6 + and 0 <= cy <= 72 and height >= 15) + self.stable = self.stable + 1 if aligned else 0 + else: + self.stable = 0 + if self.t % 2 == 0: + self.arm_yaw = float(np.clip(self.arm_yaw - 0.001, -0.65, 0.3)) + + raw[0] = 0.0 + raw[1] = 0.0 + yaw_error = (self.origin[3] - state[21] + np.pi) % (2 * np.pi) - np.pi + raw[3] = np.clip(2.0 * yaw_error, -0.25, 0.25) + if self.stable >= 12 or (self.t >= 800 and found is not None): + self.close_t = self.t + + if self.close_t is not None: + elapsed = self.t - self.close_t + raw[18] = 0.7 * min(1.0, (elapsed + 1) / 45.0) + if 70 <= elapsed < 290: + raw[0] = -0.18 + yaw_error = (self.origin[3] - state[21] + np.pi) % (2 * np.pi) - np.pi + raw[3] = np.clip(1.5 * yaw_error, -0.22, 0.22) + + self.t += 1 + return raw diff --git a/policies/drawer_top_open/kimi31pro-s2/episodes.csv b/policies/drawer_top_open/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2a920a7189e972aaa8ba4b418f2bf9c96618370b --- /dev/null +++ b/policies/drawer_top_open/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,474,success,0 +620001,1,520,success,0 +620002,1,475,success,0 +620003,1,475,success,0 +620004,1,748,success,0 +620005,0,1350,timeout,0 +620006,1,1169,success,0 +620007,1,478,success,0 +620008,1,464,success,0 +620009,1,867,success,0 +620010,1,458,success,0 +620011,1,471,success,0 +620012,0,1350,timeout,0 +620013,1,897,success,0 +620014,1,473,success,0 +620015,1,476,success,0 +620016,1,462,success,0 +620017,1,1186,success,0 +620018,1,477,success,0 +620019,1,477,success,0 +620020,1,535,success,0 +620021,1,476,success,0 +620022,1,477,success,0 +620023,1,471,success,0 +620024,0,1350,timeout,0 +620025,1,467,success,0 +620026,1,554,success,0 +620027,1,473,success,0 +620028,1,1346,success,0 +620029,1,942,success,0 +620030,1,472,success,0 +620031,1,468,success,0 +620032,0,1350,timeout,0 +620033,0,1350,timeout,0 +620034,1,475,success,0 +620035,1,829,success,0 +620036,1,493,success,0 +620037,1,745,success,0 +620038,1,475,success,0 +620039,1,462,success,0 +620040,1,1017,success,0 +620041,1,531,success,0 +620042,1,535,success,0 +620043,1,564,success,0 +620044,1,476,success,0 +620045,1,990,success,0 +620046,1,559,success,0 +620047,0,1350,timeout,0 +620048,1,461,success,0 +620049,1,474,success,0 +620050,1,458,success,0 +620051,1,473,success,0 +620052,1,852,success,0 +620053,1,474,success,0 +620054,1,472,success,0 +620055,1,688,success,0 +620056,1,533,success,0 +620057,1,1163,success,0 +620058,1,466,success,0 +620059,1,534,success,0 +620060,1,731,success,0 +620061,0,1350,timeout,0 +620062,1,1160,success,0 +620063,0,1350,timeout,0 +620064,1,473,success,0 +620065,1,464,success,0 +620066,1,1049,success,0 +620067,1,850,success,0 +620068,1,1111,success,0 +620069,1,480,success,0 +620070,1,1054,success,0 +620071,1,872,success,0 +620072,0,1350,timeout,0 +620073,0,1350,timeout,0 +620074,1,910,success,0 +620075,1,475,success,0 +620076,0,1350,timeout,0 +620077,1,471,success,0 +620078,1,461,success,0 +620079,1,1053,success,0 +620080,1,1045,success,0 +620081,0,1350,timeout,0 +620082,0,1350,timeout,0 +620083,1,474,success,0 +620084,1,475,success,0 +620085,1,531,success,0 +620086,0,1350,timeout,0 +620087,1,475,success,0 +620088,0,1350,timeout,0 +620089,1,459,success,0 +620090,1,467,success,0 +620091,1,1348,success,0 +620092,1,602,success,0 +620093,1,534,success,0 +620094,1,1078,success,0 +620095,1,855,success,0 +620096,1,469,success,0 +620097,0,1350,timeout,0 +620098,1,476,success,0 +620099,1,1197,success,0 diff --git a/policies/drawer_top_open/kimi31pro-s2/policy.py b/policies/drawer_top_open/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a94d00edd77fb8335f59e11b02c2bb1c11392055 --- /dev/null +++ b/policies/drawer_top_open/kimi31pro-s2/policy.py @@ -0,0 +1,178 @@ +"""Hand-written reach, grasp, and pull controller for the top cabinet drawer.""" + +import cv2 +import numpy as np + + +class Policy: + """Deterministic joint-space controller with closed-loop base guidance.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.cabinet_pose = np.array([0.30, 0.01, 0.74, 0.0], dtype=np.float32) + self.grasp_pose = np.array( + [-0.58, 0.0, -0.65, 0.80, 1.0, 0.0, 0.0], dtype=np.float32 + ) + self.phase = "initial" + self.pull_start = 240 + self.open_time = 0 + self.good_count = 0 + self.empty_count = 0 + self.aggressive_pull = False + + @staticmethod + def _angle_error(target, value): + return (target - value + np.pi) % (2.0 * np.pi) - np.pi + + @staticmethod + def _empty_grip(q): + # Fully closed fingers with no handle between them reach -0.02 rad. + return q[7] < -0.018 and q[8] < -0.018 + + @staticmethod + def _top_handle(image): + """Return the center of the large bar, excluding trim and lower handles.""" + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + neutral = ( + np.max(image, axis=2).astype(np.int16) + - np.min(image, axis=2).astype(np.int16) + ) < 35 + mask = ((gray < 145) & neutral).astype(np.uint8) + mask[:, :8] = 0 + mask[:, 76:] = 0 + count, _, stats, centers = cv2.connectedComponentsWithStats(mask, 8) + candidates = [] + for i in range(1, count): + x, y, w, h, area = stats[i] + density = area / float(w * h) + if ( + 45 <= h <= 82 + and 5 <= w <= 25 + and area >= 200 + and density > 0.50 + and centers[i, 0] > 18.0 + ): + candidates.append((area, centers[i])) + if not candidates: + return None + return max(candidates, key=lambda item: item[0])[1] + + def _approach_base(self, raw, q): + yaw = q[21] + raw[3] = np.clip( + 2.0 * self._angle_error(self.cabinet_pose[3], yaw), -0.35, 0.35 + ) + ex = self.cabinet_pose[0] - q[18] + ey = self.cabinet_pose[1] - q[19] + c, s = np.cos(yaw), np.sin(yaw) + vx = np.clip(2.0 * (c * ex + s * ey), -0.15, 0.15) + vy = np.clip(2.0 * (-s * ex + c * ey), -0.15, 0.15) + if abs(vx) > 0.02: + raw[0] = np.copysign(max(0.06, abs(vx)), vx) + if abs(vy) > 0.02: + raw[1] = np.copysign(max(0.06, abs(vy)), vy) + + def _guide_base(self, raw, q, pulling): + yaw = q[21] + raw[3] = np.clip( + 3.0 * self._angle_error(self.cabinet_pose[3], yaw), -0.5, 0.5 + ) + if pulling: + raw[0] = -0.08 + lateral_error = np.cos(yaw) * (self.cabinet_pose[1] - q[19]) + if abs(lateral_error) > 0.015: + raw[1] = np.clip(1.5 * lateral_error, -0.10, 0.10) + if abs(raw[1]) < 0.06: + raw[1] = np.copysign(0.06, raw[1]) + + def _pull_action(self, raw, q, pull_step): + self._guide_base(raw, q, pulling=pull_step < 300) + if self.aggressive_pull: + if pull_step < 300: + raw[0] = -0.10 + fraction = min(1.0, (pull_step + 1.0) / 180.0) + pitch_delta, wrist_delta = 0.30, -0.80 + else: + fraction = min(1.0, (pull_step + 1.0) / 240.0) + pitch_delta, wrist_delta = 0.15, -0.65 + pose = self.grasp_pose.copy() + pose[0] += pitch_delta * fraction + pose[3] += 0.50 * fraction + pose[5] += wrist_delta * fraction + raw[4:11] = pose + raw[18] = 1.0 + + def act(self, obs, tools): + q = np.asarray(obs["low_dim_obs"], dtype=np.float32) + t = int(obs["t"]) + + # Keep the successful baseline untouched. Only an actually empty close + # enters the camera-timed retry path. + if t == 200 and self.phase == "initial": + if self._empty_grip(q): + self.phase = "open" + self.open_time = t + self.good_count = 0 + self.aggressive_pull = True + else: + self.phase = "initial_ok" + if t >= 240 and self.phase == "initial_ok": + self.phase = "pull" + if self.phase == "retry_close" and t >= self.pull_start: + self.phase = "pull" + if self.phase == "pull": + pull_step = t - self.pull_start + if 150 <= pull_step < 300 and self._empty_grip(q): + self.empty_count += 1 + else: + self.empty_count = 0 + if self.empty_count >= 10: + self.phase = "open" + self.open_time = t + self.good_count = 0 + self.empty_count = 0 + + raw = np.zeros(20, dtype=np.float32) + raw[2] = 0.74 + raw[19] = 0.6 + + if self.phase in ("initial", "initial_ok"): + if t < 160: + self._approach_base(raw, q) + raw[18] = 0.0 + raw[4:11] = self.grasp_pose + else: + self._guide_base(raw, q, pulling=False) + raw[18] = 1.0 + raw[4:11] = self.grasp_pose + elif self.phase == "open": + self._approach_base(raw, q) + raw[18] = 0.0 + raw[4:11] = self.grasp_pose + if t - self.open_time >= 20 and t % 2 == 0: + center = self._top_handle(tools.image("left_wrist")) + if ( + center is not None + and 36.0 <= center[0] <= 49.0 + and 28.0 <= center[1] <= 48.0 + ): + self.good_count += 1 + else: + self.good_count = 0 + if self.good_count >= 2: + self.phase = "retry_close" + self.pull_start = t + 70 + self.close_start = t + elif self.phase == "retry_close": + self._guide_base(raw, q, pulling=False) + if t - self.close_start < 30: + raw[0] = 0.06 + raw[18] = 1.0 + raw[4:11] = self.grasp_pose + if t == self.close_start + 50 and self._empty_grip(q): + self.phase = "open" + self.open_time = t + self.good_count = 0 + else: + self._pull_action(raw, q, t - self.pull_start) + return raw diff --git a/policies/drawer_top_open/kimi31pro-s3/episodes.csv b/policies/drawer_top_open/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8feedeb69a271938442f4b7ea4476289827e12d4 --- /dev/null +++ b/policies/drawer_top_open/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,439,success,0 +620001,0,1350,timeout,0 +620002,0,1350,timeout,0 +620003,0,1350,timeout,0 +620004,0,1350,timeout,0 +620005,0,1350,timeout,0 +620006,0,1350,timeout,0 +620007,0,1350,timeout,0 +620008,0,1350,timeout,0 +620009,0,1350,timeout,0 +620010,0,1350,timeout,0 +620011,0,1350,timeout,0 +620012,0,1350,timeout,0 +620013,0,1350,timeout,0 +620014,1,436,success,0 +620015,0,1350,timeout,0 +620016,1,440,success,0 +620017,0,1350,timeout,0 +620018,1,445,success,0 +620019,0,1350,timeout,0 +620020,0,1350,timeout,0 +620021,0,1350,timeout,0 +620022,0,1350,timeout,0 +620023,1,444,success,0 +620024,1,449,success,0 +620025,0,1350,timeout,0 +620026,0,1350,timeout,0 +620027,0,1350,timeout,0 +620028,0,1350,timeout,0 +620029,0,1350,timeout,0 +620030,1,434,success,0 +620031,1,444,success,0 +620032,1,463,success,0 +620033,0,1350,timeout,0 +620034,0,1350,timeout,0 +620035,0,1350,timeout,0 +620036,0,1350,timeout,0 +620037,1,446,success,0 +620038,0,1350,timeout,0 +620039,0,1350,timeout,0 +620040,0,1350,timeout,0 +620041,0,1350,timeout,0 +620042,0,1350,timeout,0 +620043,0,1350,timeout,0 +620044,0,1350,timeout,0 +620045,0,1350,timeout,0 +620046,0,1350,timeout,0 +620047,0,1350,timeout,0 +620048,0,1350,timeout,0 +620049,0,1350,timeout,0 +620050,1,442,success,0 +620051,0,1350,timeout,0 +620052,1,448,success,0 +620053,0,1350,timeout,0 +620054,1,441,success,0 +620055,0,1350,timeout,0 +620056,0,1350,timeout,0 +620057,0,1350,timeout,0 +620058,1,447,success,0 +620059,0,1350,timeout,0 +620060,0,1350,timeout,0 +620061,0,1350,timeout,0 +620062,0,1350,timeout,0 +620063,0,1350,timeout,0 +620064,0,1350,timeout,0 +620065,0,1350,timeout,0 +620066,0,1350,timeout,0 +620067,0,1350,timeout,0 +620068,0,1350,timeout,0 +620069,0,1350,timeout,0 +620070,0,1350,timeout,0 +620071,0,1350,timeout,0 +620072,0,1350,timeout,0 +620073,0,1350,timeout,0 +620074,0,1350,timeout,0 +620075,0,1350,timeout,0 +620076,0,1350,timeout,0 +620077,0,1350,timeout,0 +620078,0,1350,timeout,0 +620079,0,1350,timeout,0 +620080,0,1350,timeout,0 +620081,0,1350,timeout,0 +620082,0,1350,timeout,0 +620083,0,1350,timeout,0 +620084,1,440,success,0 +620085,0,1350,timeout,0 +620086,0,1350,timeout,0 +620087,0,1350,timeout,0 +620088,1,446,success,0 +620089,0,1350,timeout,0 +620090,0,1350,timeout,0 +620091,0,1350,timeout,0 +620092,0,1350,timeout,0 +620093,0,1350,timeout,0 +620094,0,1350,timeout,0 +620095,0,1350,timeout,0 +620096,0,1350,timeout,0 +620097,0,1350,timeout,0 +620098,0,1350,timeout,0 +620099,0,1350,timeout,0 diff --git a/policies/drawer_top_open/kimi31pro-s3/policy.py b/policies/drawer_top_open/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..57a22acdb44babdfb424a8d411cdfba715da01fb --- /dev/null +++ b/policies/drawer_top_open/kimi31pro-s3/policy.py @@ -0,0 +1,67 @@ +"""Deterministic hand-written controller for the top cabinet drawer. + +The arm is raised before it is adducted (adduction while hanging collides with +the thigh). A short forward walk brings the left hand to the drawer handle. +The pull uses the opposite wrist orientation and a reduced gripper command; +both details keep the handle between the finger pads during the slow retreat. +""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.k = 0 + self.start = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.goal = self.start.copy() + self.goal[18] = 0.4 + # Left arm: raised shoulder, adduction, and the grasp wrist orientation. + self.goal[4:11] = [-0.6, -0.3, 0.0, 1.0, 1.55, 0.0, 0.0] + p = np.asarray(obs["low_dim_obs"], dtype=np.float32)[18:22] + self.y0 = float(p[1]) + self.yaw0 = float(p[3]) + + def _base(self, raw, obs, vx_world, vy_world, yaw_gain): + p = np.asarray(obs["low_dim_obs"], dtype=np.float32)[18:22] + yaw = float(p[3]) + c, s = np.cos(yaw), np.sin(yaw) + raw[0] = c * vx_world + s * vy_world + raw[1] = -s * vx_world + c * vy_world + yaw_error = (self.yaw0 - yaw + np.pi) % (2.0 * np.pi) - np.pi + raw[3] = float(np.clip(yaw_gain * yaw_error, -0.5, 0.5)) + return raw + + def act(self, obs, tools): + k = self.k + self.k += 1 + start, goal = self.start, self.goal + + if k < 61: + # Raise pitch/elbow first, then adduct and rotate the wrist. + raw = start + (goal - start) * min(1.0, k / 50.0) + u = min(1.0, k / 25.0) + raw[4] = start[4] + (goal[4] - start[4]) * u + raw[7] = start[7] + (goal[7] - start[7]) * u + return np.asarray(raw, dtype=np.float32) + + if k < 117: + j = k - 61 + raw = goal.copy() + vx = 0.25 if j < 45 else 0.0 + p = np.asarray(obs["low_dim_obs"], dtype=np.float32)[18:22] + vy = float(np.clip(1.0 * (self.y0 - float(p[1])), -0.1, 0.1)) + return self._base(raw, obs, vx, vy, 2.0) + + if k < 158: + j = k - 117 + raw = goal.copy() + raw[18] = 0.4 + 0.4 * min(1.0, j / 15.0) + return raw + + j = k - 158 + raw = goal.copy() + raw[18] = 0.8 + vx = -0.08 if j < 250 else 0.0 + p = np.asarray(obs["low_dim_obs"], dtype=np.float32)[18:22] + vy = float(np.clip(2.0 * (self.y0 - float(p[1])), -0.1, 0.1)) + return self._base(raw, obs, vx, vy, 5.0) diff --git a/policies/drawer_top_open/opus-s1/episodes.csv b/policies/drawer_top_open/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4c44a00124d6751e976f506b40b893f212ec01f3 --- /dev/null +++ b/policies/drawer_top_open/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,550,success,0 +620001,1,576,success,0 +620002,1,508,success,0 +620003,1,785,success,0 +620004,1,465,success,0 +620005,1,559,success,0 +620006,1,595,success,0 +620007,1,950,success,0 +620008,1,598,success,0 +620009,1,508,success,0 +620010,1,551,success,0 +620011,1,705,success,0 +620012,1,444,success,0 +620013,1,812,success,0 +620014,1,564,success,0 +620015,1,509,success,0 +620016,1,568,success,0 +620017,1,756,success,0 +620018,1,567,success,0 +620019,1,527,success,0 +620020,1,739,success,0 +620021,1,311,success,0 +620022,1,467,success,0 +620023,1,608,success,0 +620024,1,578,success,0 +620025,1,821,success,0 +620026,1,643,success,0 +620027,1,508,success,0 +620028,1,462,success,0 +620029,1,711,success,0 +620030,1,559,success,0 +620031,1,681,success,0 +620032,1,638,success,0 +620033,1,701,success,0 +620034,1,533,success,0 +620035,1,594,success,0 +620036,1,449,success,0 +620037,1,816,success,0 +620038,1,573,success,0 +620039,1,481,success,0 +620040,1,447,success,0 +620041,1,712,success,0 +620042,1,465,success,0 +620043,1,434,success,0 +620044,1,701,success,0 +620045,1,514,success,0 +620046,1,513,success,0 +620047,1,452,success,0 +620048,1,778,success,0 +620049,1,437,success,0 +620050,1,567,success,0 +620051,1,677,success,0 +620052,1,655,success,0 +620053,1,571,success,0 +620054,1,629,success,0 +620055,1,467,success,0 +620056,1,536,success,0 +620057,1,465,success,0 +620058,1,563,success,0 +620059,1,465,success,0 +620060,1,477,success,0 +620061,1,760,success,0 +620062,1,465,success,0 +620063,1,434,success,0 +620064,0,1350,timeout,0 +620065,1,765,success,0 +620066,1,511,success,0 +620067,1,505,success,0 +620068,1,513,success,0 +620069,1,679,success,0 +620070,1,589,success,0 +620071,1,507,success,0 +620072,1,449,success,0 +620073,1,514,success,0 +620074,1,562,success,0 +620075,1,537,success,0 +620076,1,648,success,0 +620077,1,562,success,0 +620078,1,598,success,0 +620079,1,479,success,0 +620080,1,463,success,0 +620081,1,432,success,0 +620082,1,465,success,0 +620083,1,521,success,0 +620084,1,567,success,0 +620085,1,559,success,0 +620086,1,928,success,0 +620087,1,605,success,0 +620088,1,645,success,0 +620089,1,900,success,0 +620090,1,587,success,0 +620091,1,929,success,0 +620092,1,466,success,0 +620093,1,717,success,0 +620094,1,465,success,0 +620095,1,466,success,0 +620096,1,585,success,0 +620097,1,465,success,0 +620098,1,515,success,0 +620099,1,673,success,0 diff --git a/policies/drawer_top_open/opus-s1/policy.py b/policies/drawer_top_open/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..01dd151e34d0a27e94854b677d66f702152f57da --- /dev/null +++ b/policies/drawer_top_open/opus-s1/policy.py @@ -0,0 +1,280 @@ +"""Open the top drawer: walk up to the cabinet, grasp the top handle with the left +hand, then walk backwards holding it. + +The cabinet sits at a fixed place in the odometry (world) frame; only the robot's +start pose varies between seeds. The robot walks to a fixed stand pose in front +of the handle and reaches for it with the gripper's fingers opening vertically. +Before closing, the left wrist camera checks where the handle bar ends inside +the open gripper and shifts the grasp sideways until the bar spans the fingers. +A missed grasp (gripper closes fully) is retried at other heights; a handle lost +while pulling is grasped again where the hand last held it. +""" + +import numpy as np +from scipy.optimize import least_squares + +# ---------------------------------------------------------------------------- +# Kinematics (approximate G1 arm chain, pelvis frame, waist assumed rigid) + + +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def fk_left(q, tool): + p = np.array([-0.0039635, 0, 0.054]) + R = np.eye(3) + p = p + R @ np.array([0.0039563, 0.10022, 0.23778]); R = R @ _rx(0.27931) + R = R @ _ry(q[0]) + p = p + R @ np.array([0, 0.038, -0.013831]); R = R @ _rx(-0.27925) @ _rx(q[1]) + p = p + R @ np.array([0, 0.00624, -0.1032]); R = R @ _rz(q[2]) + p = p + R @ np.array([0.015783, 0, -0.080518]); R = R @ _ry(q[3]) + p = p + R @ np.array([0.100, 0.00188791, -0.010]); R = R @ _rx(q[4]) + p = p + R @ np.array([0.038, 0, 0]); R = R @ _ry(q[5]) + p = p + R @ np.array([0.046, 0, 0]); R = R @ _rz(q[6]) + return p + R @ np.array([tool, 0, 0]), R + + +Q_LO = np.array([-3.0892, -0.05, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +Q_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +TOOL = 0.19 + + +def ik_left(target, q0, maxdown=0.3): + """Fingers' centre at target, opening axis in the world x-z plane (to pinch a + horizontal bar running along y), gripper pointing roughly forward.""" + q0 = np.clip(np.asarray(q0, float), Q_LO + 1e-3, Q_HI - 1e-3) + pref = np.array([1.0, 0, 0]) + + def res(q): + p, R = fk_left(q, TOOL) + return np.concatenate([ + 3 * (p - target), + [1.0 * R[1, 1]], + 0.05 * (R[:, 0] - pref), + [0.5 * max(0.0, -R[2, 0] - np.sin(maxdown))], + [0.5 * max(0.0, abs(R[1, 0]) - 0.5)], + [0.3 * max(0.0, -R[2, 1])], + 0.01 * (q - q0), + ]) + return least_squares(res, q0, bounds=(Q_LO, Q_HI)).x + + +# ---------------------------------------------------------------------------- +# Vision + + +def handle_band(w): + """Rows spanned by the handle bar in the (open-gripper) left wrist image. + + The bar shows as a near-vertical mid-grey band left of the image centre; + image-up is the robot's right. Returns (first_row, last_row) or None.""" + im = w.astype(float) + g = im.mean(2) + sat = im.max(2) - im.min(2) + m = (g > 70) & (g < 125) & (sat < 25) + m[:, :6] = False + m[:, 60:] = False + rows = np.nonzero(m.sum(1) >= 4)[0] + if len(rows) < 6: + return None + xs = np.nonzero(m[30:70])[1] + xc = float(xs.mean()) if len(xs) >= 20 else None + return int(rows.min()), int(rows.max()), xc + + +# ---------------------------------------------------------------------------- +# Grasp point on the closed top-drawer handle, odometry (world) frame: measured by +# grasping on the demonstration seed; the same on every development seed. +REF_GRASP = np.array([0.618, -0.02, 0.740]) + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + P = dict(STAND_X=0.43, STAND_DY=0.03, XPRE=0.12, XIN=0.02, VB=-0.3, + RETRACT=0.15, TRET=40, MAXREGRASP=4, RAMP=1, YAWTOL=0.02, + BAND_MIN_END=58, BAND_GOAL_END=70, BAND_PX_PER_M=700.0) + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 'look' + self.t0 = 0 + self.q = self.hold[4:11].astype(float).copy() + self.grasp = REF_GRASP.copy() + self.attempt = 0 + self.zoff = [0.0, -0.02, 0.02, -0.035, 0.035] + self.traj = None + self.hold_pose = None + self.settle = 0 + self.traj_pull = None + self.regrasps = 0 + self.ycorr = 0 + self.same_z = False + self.hand_world = self.grasp[:2].copy() + + # -- helpers + def go(self, p, t): + self.phase, self.t0 = p, t + + def rel(self, lo, pw): + x, y, yaw = lo[18], lo[19], lo[21] + d = pw[:2] - np.array([x, y]) + c, s = np.cos(yaw), np.sin(yaw) + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], pw[2] - lo[20]]) + + def base_goto(self, raw, lo, target, tol=0.012, ytol=0.03): + x, y, yaw = lo[18], lo[19], lo[21] + ex, ey = target[0] - x, target[1] - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + eyaw = wrap(target[2] - yaw) + vx = np.clip(1.2 * bx, -0.15, 0.15) + vy = np.clip(1.2 * by, -0.12, 0.12) + wz = np.clip(1.5 * eyaw, -0.3, 0.3) + done_xy = np.hypot(bx, by) < tol + sp = np.hypot(vx, vy) + if done_xy: + vx = vy = 0.0 + elif sp < 0.065: + vx, vy = vx / sp * 0.065, vy / sp * 0.065 + if abs(eyaw) < ytol: + wz = 0.0 + elif abs(wz) < 0.12: + wz = np.sign(wz) * 0.12 + raw[0], raw[1], raw[3] = vx, vy, wz + return done_xy and abs(eyaw) < ytol + + def arm_target(self, lo, dx): + r = self.rel(lo, self.grasp + np.array([0, 0, self.zoff[self.attempt]])) + return r + np.array([dx, 0, 0]) + + # -- main + def act(self, obs, tools): + lo = np.asarray(obs['low_dim_obs'], dtype=float) + t = int(obs['t']) + raw = self.hold.copy() + raw[4:11] = self.q + raw[18] = 0.0 + tt = t - self.t0 + ph = self.phase + P = self.P + + if ph == 'look': + if tt >= 3: + g = self.grasp + self.stand = np.array([g[0] - P['STAND_X'], g[1] + P['STAND_DY'], 0.0]) + self.go('walk', t) + elif ph == 'walk': + done = self.base_goto(raw, lo, self.stand, tol=0.02, ytol=0.04) + self.settle = self.settle + 1 if done else 0 + if self.settle > 5 or tt > 150: + self.go('pre', t) + self.qs = self.q.copy() + elif ph == 'pre': + if self.traj is None: + tgt_pre = self.arm_target(lo, -P['XPRE']) + q1 = ik_left(tgt_pre, self.q if self.attempt else np.array([-0.3, 0, -1.0, 0.5, 1.0, 0.8, 0.4])) + n = 6 + self.traj = [ik_left(self.arm_target(lo, -P['XPRE'] + (P['XPRE'] + P['XIN']) * i / n), q1) for i in range(n + 1)] + self.traj_q1 = q1 + a = min(1.0, tt / 35) + raw[4:11] = self.qs + a * (self.traj_q1 - self.qs) + if tt >= 40: + self.q = self.traj_q1.copy() + self.go('in', t) + elif ph == 'in': + f = min(1.0, tt / 40) * (len(self.traj) - 1) + i = min(int(f), len(self.traj) - 2) + a = f - i + raw[4:11] = (1 - a) * self.traj[i] + a * self.traj[i + 1] + if tt >= 48: + self.q = self.traj[-1].copy() + band = handle_band(tools.image('left_wrist')) + dy = 0.0 + if band is not None: + if band[1] < P['BAND_MIN_END']: + dy = -(P['BAND_GOAL_END'] - band[1]) / P['BAND_PX_PER_M'] + elif band[0] > 15: + dy = (band[0] - 5) / P['BAND_PX_PER_M'] + if dy != 0.0 and self.ycorr < 3: + self.ycorr += 1 + self.grasp[1] += float(np.clip(dy, -0.08, 0.08)) + self.same_z = True + self.go('retreat', t) + else: + self.go('close', t) + elif ph == 'close': + raw[18] = 1.0 + if tt >= 25: + if lo[44] < 0.95: + self.hold_pose = lo[18:22].copy() + self.go('pull', t) + else: + self.go('retreat', t) + elif ph == 'retreat': + raw[18] = 0.0 + f = min(1.0, tt / 30) * (len(self.traj) - 1) + i = min(int(f), len(self.traj) - 2) + a = f - i + rev = self.traj[::-1] + raw[4:11] = (1 - a) * rev[i] + a * rev[i + 1] + if tt >= 35: + self.q = self.traj[0].copy() + self.qs = self.q.copy() + if not self.same_z: + self.attempt = (self.attempt + 1) % len(self.zoff) + self.same_z = False + self.traj = None + self.go('pre', t) + elif ph == 'pull': + raw[18] = 1.0 + if self.traj_pull is None: + tgt = self.arm_target(lo, P['XIN']) + self.traj_pull = [ik_left(tgt - np.array([P['RETRACT'] * i / 4, 0, 0]), self.q) for i in range(5)] + f = min(1.0, tt / P['TRET']) * 4 + i = min(int(f), 3) + a = f - i + raw[4:11] = (1 - a) * self.traj_pull[i] + a * self.traj_pull[i + 1] + raw[0] = P['VB'] * min(1.0, (tt + 1) / P['RAMP']) if tt < 150 else 0.0 + if lo[44] < 0.9: + p, _ = fk_left(lo[0:7], TOOL) + c, s = np.cos(lo[21]), np.sin(lo[21]) + self.hand_world = np.array([lo[18] + c * p[0] - s * p[1], lo[19] + s * p[0] + c * p[1]]) + elif lo[44] > 0.97 and tt > 10 and self.regrasps < P['MAXREGRASP']: + # lost the handle: go back for it where the hand last held it + self.regrasps += 1 + self.grasp[0] = self.hand_world[0] + g = self.grasp + self.stand = np.array([g[0] - P['STAND_X'], g[1] + P['STAND_DY'], 0.0]) + self.q = raw[4:11].copy() + self.traj = None + self.traj_pull = None + self.attempt = 0 + self.ycorr = 0 + self.settle = 0 + self.go('walk', t) + return raw + eyaw = wrap(self.hold_pose[3] - lo[21]) + raw[3] = np.clip(2.0 * eyaw, -0.3, 0.3) if abs(eyaw) > P['YAWTOL'] else 0.0 + c, s = np.cos(lo[21]), np.sin(lo[21]) + ey = -s * (self.hold_pose[0] - lo[18]) + c * (self.hold_pose[1] - lo[19]) + raw[1] = np.clip(1.5 * ey, -0.1, 0.1) if abs(ey) > 0.02 else 0.0 + if tt > 200: + raw[18] = 0.0 + return raw diff --git a/policies/drawer_top_open/opus-s2/episodes.csv b/policies/drawer_top_open/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..eeaa9eab3a7bc737afe4681eabe689f8a3719c90 --- /dev/null +++ b/policies/drawer_top_open/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,680,success,0 +620001,1,575,success,0 +620002,1,542,success,0 +620003,1,570,success,0 +620004,1,545,success,0 +620005,1,549,success,0 +620006,1,536,success,0 +620007,1,624,success,0 +620008,1,549,success,0 +620009,1,573,success,0 +620010,1,572,success,0 +620011,1,531,success,0 +620012,1,570,success,0 +620013,1,528,success,0 +620014,1,536,success,0 +620015,1,548,success,0 +620016,1,527,success,0 +620017,1,549,success,0 +620018,1,526,success,0 +620019,1,540,success,0 +620020,1,570,success,0 +620021,1,524,success,0 +620022,1,523,success,0 +620023,1,537,success,0 +620024,1,527,success,0 +620025,1,677,success,0 +620026,1,541,success,0 +620027,1,539,success,0 +620028,1,523,success,0 +620029,1,539,success,0 +620030,1,530,success,0 +620031,1,577,success,0 +620032,1,573,success,0 +620033,1,596,success,0 +620034,1,533,success,0 +620035,1,534,success,0 +620036,1,556,success,0 +620037,1,573,success,0 +620038,1,562,success,0 +620039,1,534,success,0 +620040,1,544,success,0 +620041,1,545,success,0 +620042,1,568,success,0 +620043,1,539,success,0 +620044,1,540,success,0 +620045,1,548,success,0 +620046,1,534,success,0 +620047,1,574,success,0 +620048,1,533,success,0 +620049,1,534,success,0 +620050,1,595,success,0 +620051,1,541,success,0 +620052,1,556,success,0 +620053,1,570,success,0 +620054,1,591,success,0 +620055,1,536,success,0 +620056,1,535,success,0 +620057,1,541,success,0 +620058,1,679,success,0 +620059,1,542,success,0 +620060,1,534,success,0 +620061,1,572,success,0 +620062,1,554,success,0 +620063,1,532,success,0 +620064,1,555,success,0 +620065,1,620,success,0 +620066,1,533,success,0 +620067,1,570,success,0 +620068,1,533,success,0 +620069,1,547,success,0 +620070,1,596,success,0 +620071,1,540,success,0 +620072,1,536,success,0 +620073,1,541,success,0 +620074,1,552,success,0 +620075,1,538,success,0 +620076,1,651,success,0 +620077,1,546,success,0 +620078,1,547,success,0 +620079,1,590,success,0 +620080,1,534,success,0 +620081,1,569,success,0 +620082,1,552,success,0 +620083,1,539,success,0 +620084,1,528,success,0 +620085,1,534,success,0 +620086,0,1350,timeout,0 +620087,1,734,success,0 +620088,1,545,success,0 +620089,1,535,success,0 +620090,1,538,success,0 +620091,1,535,success,0 +620092,1,532,success,0 +620093,1,533,success,0 +620094,1,572,success,0 +620095,1,570,success,0 +620096,0,1350,timeout,0 +620097,1,536,success,0 +620098,1,524,success,0 +620099,1,651,success,0 diff --git a/policies/drawer_top_open/opus-s2/g1kin.py b/policies/drawer_top_open/opus-s2/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..eaa857222880a93cbe40aa50f4bcfa7d6f46db98 --- /dev/null +++ b/policies/drawer_top_open/opus-s2/g1kin.py @@ -0,0 +1,93 @@ +"""Approximate G1 arm forward kinematics (from the public g1_29dof URDF), pelvis frame.""" +import numpy as np + + +def rotx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def roty(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rotz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def rpy(r, p, y): + return rotz(y) @ roty(p) @ rotx(r) + + +TORSO = np.array([-0.0039635, 0.0, 0.054]) + + +def arm_chain(side): + s = 1.0 if side == 'L' else -1.0 + return [ + # (xyz, rpy, axis) + (np.array([0.0039563, s * 0.10022, 0.23778]), (s * 0.27931, 0, 0), 'y'), + (np.array([0.0, s * 0.038, -0.013831]), (-s * 0.27925, 0, 0), 'x'), + (np.array([0.0, s * 0.00624, -0.1032]), (0, 0, 0), 'z'), + (np.array([0.015783, 0.0, -0.080518]), (0, 0, 0), 'y'), + (np.array([0.100, s * 0.00188791, -0.010]), (0, 0, 0), 'x'), + (np.array([0.038, 0.0, 0.0]), (0, 0, 0), 'y'), + (np.array([0.046, 0.0, 0.0]), (0, 0, 0), 'z'), + ] + + +AX = {'x': rotx, 'y': roty, 'z': rotz} + + +def fk(q, side='L', tool=np.array([0.12, 0.0, 0.0])): + """Return (tool position, rotation) in pelvis frame, and the joint frames.""" + R = np.eye(3) + p = TORSO.copy() + frames = [] + for (xyz, r, ax), qi in zip(arm_chain(side), q): + p = p + R @ xyz + R = R @ rpy(*r) @ AX[ax](qi) + frames.append((p.copy(), R.copy())) + return p + R @ tool, R, frames + + +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def limits(side): + return LO, HI + + +def rot_err(R, Rd): + E = Rd @ R.T + w = np.array([E[2, 1] - E[1, 2], E[0, 2] - E[2, 0], E[1, 0] - E[0, 1]]) / 2 + return w + + +def ik(p_des, R_des, q0, side='L', tool=np.array([0.12, 0.0, 0.0]), w_rot=0.3, iters=300, + q_rest=None, w_rest=1e-4): + q = np.array(q0, dtype=float) + lo, hi = limits(side) + if q_rest is None: + q_rest = np.zeros(7) + for _ in range(iters): + p, R, _ = fk(q, side, tool) + e = np.concatenate([p_des - p, w_rot * rot_err(R, R_des)]) + if np.linalg.norm(e) < 1e-5: + break + J = np.zeros((6, 7)) + h = 1e-5 + for j in range(7): + dq = q.copy(); dq[j] += h + p2, R2, _ = fk(dq, side, tool) + J[:3, j] = (p2 - p) / h + J[3:, j] = w_rot * rot_err(R, R2) / h + lam = 1e-3 + A = J.T @ J + lam * np.eye(7) + w_rest * np.eye(7) + dq = np.linalg.solve(A, J.T @ e + w_rest * (q_rest - q)) + q = np.clip(q + dq, lo + 0.02, hi - 0.02) + p, R, _ = fk(q, side, tool) + return q, np.linalg.norm(p_des - p), np.linalg.norm(rot_err(R, R_des)) diff --git a/policies/drawer_top_open/opus-s2/handles.py b/policies/drawer_top_open/opus-s2/handles.py new file mode 100644 index 0000000000000000000000000000000000000000..14c0eee579c909d6a8e5d1f3308f21d72650f023 --- /dev/null +++ b/policies/drawer_top_open/opus-s2/handles.py @@ -0,0 +1,34 @@ +import numpy as np +from scipy import ndimage + + +def find_handles(img, vmin=55, vmax=110, min_area=12): + a = img.astype(np.int16) + v = a.max(axis=2) + sp = v - a.min(axis=2) + m = (sp < 14) & (v > vmin) & (v < vmax) + lab, n = ndimage.label(m) + out = [] + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + if len(xs) < min_area: + continue + cu, cv = xs.mean(), ys.mean() + X = np.stack([xs - cu, ys - cv]).astype(float) + ev, evec = np.linalg.eigh(X @ X.T / len(xs)) + d = evec[:, 1] + if d[0] < 0: + d = -d + proj = (xs - cu) * d[0] + (ys - cv) * d[1] + length = proj.max() - proj.min() + 1 + width = len(xs) / length + angle = float(np.degrees(np.arctan2(d[1], d[0]))) + if width < 1.5 or length < 6: + continue + # endpoints: mean of pixels within 1.5px of each extreme along axis + e1 = np.array([xs[proj <= proj.min() + 1.5].mean(), ys[proj <= proj.min() + 1.5].mean()]) + e2 = np.array([xs[proj >= proj.max() - 1.5].mean(), ys[proj >= proj.max() - 1.5].mean()]) + trunc = xs.min() <= 0 or xs.max() >= img.shape[1] - 1 or ys.min() <= 0 or ys.max() >= img.shape[0] - 1 + out.append(dict(c=(cu, cv), e1=e1, e2=e2, length=length, width=width, angle=angle, + area=len(xs), trunc=bool(trunc))) + return out diff --git a/policies/drawer_top_open/opus-s2/policy.py b/policies/drawer_top_open/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c7496ecdd6df9111950bcb5ea34f494982bdd2ed --- /dev/null +++ b/policies/drawer_top_open/opus-s2/policy.py @@ -0,0 +1,281 @@ +"""Open the top drawer of the kitchen cabinet. + +Pipeline: look at the drawer front with the left wrist camera, localise the top +handle in 3D (calibrated wrist camera + arm forward kinematics + known handle +height), walk to a standing spot, re-localise from close by, grasp the handle +with the left gripper rolled 90 degrees (fingers above/below the bar) and pull. +""" + +import numpy as np +from scipy.spatial.transform import Rotation + +from g1kin import fk, ik, rotx, roty, rotz +from handles import find_handles + +# Left wrist camera, in the wrist_yaw link frame: offset, rotation (rotvec), focal (px). +CAM_OFF = np.array([0.136654, 0.007828, 0.035661]) +CAM_R = Rotation.from_rotvec([-1.72328, 1.756228, -0.776116]).as_matrix() +CAM_F = 68.061685 +HZ = (0.7365, 0.6008, 0.4956) # world heights of the three stacked handle bars +HHALF = (0.0403, 0.0516, 0.0495) # their half lengths +Z_TOP = HZ[0] + +TOOL = np.array([0.16, 0.0, 0.0]) # grasp point between the fingertips, wrist_yaw frame +QR_SAFE = np.array([0.3, -0.2, 0.0, 1.2, 0.0, 0.0, 0.0]) + +STAND = np.array([0.30, 0.12]) # handle position in the pelvis frame when grasping +ROLL = np.pi / 2 +GRASP_DX = 0.02 # final grasp point beyond the bar (handle frame, m): bar deep between the fingers +GRASP_DY = -0.02 # lateral correction so the fingers close near the middle of the bar +V_STAR = 30.0 # bar row (rotated wrist image) seen just before good grasps + + +def cam_world(q, pel): + _, _, fr = fk(q, "L") + p, R = fr[6] + Ry = rotz(pel[3]) + C = np.array([pel[0], pel[1], pel[2]]) + Ry @ (p + R @ CAM_OFF) + return C, Ry @ R @ CAM_R + + +def ray_plane(C, R, uv, z): + d = R @ np.array([(uv[0] - 41.5) / CAM_F, (uv[1] - 41.5) / CAM_F, 1.0]) + if d[2] > -1e-3: + return None + return C + (z - C[2]) / d[2] * d + + +def _bar_center(C, R, h, z, half): + """Centre (x, y) and yaw of a bar of known height and half length, or None.""" + p1 = ray_plane(C, R, h["e1"], z) + p2 = ray_plane(C, R, h["e2"], z) + if p1 is None or p2 is None: + return None + L = np.linalg.norm(p1 - p2) + if h["trunc"]: + if not (0.015 < L < 2 * half + 0.02): + return None + e1_in = 1.5 < h["e1"][0] < 81.5 and 1.5 < h["e1"][1] < 81.5 + d = (p2 - p1) / (L + 1e-9) + if e1_in: + p2 = p1 + d * 2 * half + else: + p1 = p2 - d * 2 * half + elif abs(L - 2 * half) > 0.025: + return None + d = p1 - p2 + yaw = np.arctan2(-d[0], d[1]) + return np.array([(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2]), float(yaw), bool(h["trunc"]) + + +def localize_top(img, q, pel, prior=None): + """World position (x, y) and yaw of the top handle, or None. + + Every bar seen is tried as each of the three stacked handles (known heights); + the labelling under which the bars agree on one position wins. + """ + C, R = cam_world(q, pel) + hs = [h for h in find_handles(img) if abs(h["angle"]) < 40 and h["length"] > 8 and h["width"] > 1.6] + hs.sort(key=lambda h: h["c"][1]) + hyp = [] # (det index, k, centre, yaw, trunc) + for i, h in enumerate(hs): + for k in range(3): + r = _bar_center(C, R, h, HZ[k], HHALF[k]) + if r is not None: + hyp.append((i, k, r[0], r[1], r[2])) + if not hyp: + return None + best, best_score = None, -1e9 + for a in hyp: + members = [a] + for b in hyp: + if b[0] == a[0]: + continue + if (b[0] < a[0]) != (b[1] < a[1]) or b[1] == a[1]: + continue + if np.linalg.norm(b[2] - a[2]) < 0.03 and all(m[0] != b[0] for m in members): + members.append(b) + score = len(members) - 0.3 * sum(m[4] for m in members) + if prior is not None: + score -= 3.0 * np.linalg.norm(a[2] - prior) + if score > best_score: + best, best_score = members, score + w = np.array([0.3 if m[4] else 1.0 for m in best]) + c = sum(wi * m[2] for wi, m in zip(w, best)) / w.sum() + yaws = [m[3] for m in best if not m[4]] or [m[3] for m in best] + return c, float(np.median(yaws)), len(best) + + +def bar_row_rotated(img): + """Row at which the handle bar crosses the finger axis, in the wrist image rotated so + that world-up is image-up (gripper rolled 90 degrees). Returns (row, width) or None.""" + rot = np.ascontiguousarray(np.rot90(img, k=-1)) + best = None + for h in find_handles(rot): + if abs(h["angle"]) > 30 or h["width"] < 3.5 or h["length"] < 12: + continue + cu, cv = h["c"] + e1, e2 = h["e1"], h["e2"] + slope = (e2[1] - e1[1]) / (e2[0] - e1[0] + 1e-9) + row = cv + slope * (43 - cu) + if best is None or h["area"] > best[2]: + best = (row, h["width"], h["area"]) + return None if best is None else best[:2] + + +class Policy: + def reset(self, obs, tools): + o = np.asarray(obs["low_dim_obs"], float) + self.x0, self.y0, self.yaw0 = o[18], o[19], o[21] + self.t = 0 + self.phase = "look0" + self.pt = 0 + self.base_goal = None + self.yaw_goal = self.yaw0 + self.ql = np.zeros(7) + self.qr = np.zeros(7) + self.grip = 0.0 + self.handle = None + self.hyaw = 0.0 + self.dz = 0.0 + self.dbg = None + self.debug = getattr(self, "debug", False) + + # ---------------------------------------------------------------- base + def base_cmd(self, o): + if self.base_goal is None: + return 0.0, 0.0, 0.0, 0.0 + ex, ey = self.base_goal[0] - o[18], self.base_goal[1] - o[19] + c, s = np.cos(o[21]), np.sin(o[21]) + bx, by = c * ex + s * ey, -s * ex + c * ey + vx, vy = np.clip(1.5 * bx, -0.2, 0.2), np.clip(1.5 * by, -0.2, 0.2) + sp = np.hypot(vx, vy) + dist = np.hypot(bx, by) + if sp < 0.06: + if dist > 0.02: + vx, vy = vx / (sp + 1e-9) * 0.06, vy / (sp + 1e-9) * 0.06 + else: + vx = vy = 0.0 + eyaw = (self.yaw_goal - o[21] + np.pi) % (2 * np.pi) - np.pi + wz = np.clip(2.0 * eyaw, -0.4, 0.4) + if abs(wz) < 0.03: + wz = 0.0 + return vx, vy, wz, dist + + def handle_rel(self, o): + """Top handle in the current pelvis frame (x, y, z) and relative yaw.""" + d = self.handle - o[18:20] + c, s = np.cos(o[21]), np.sin(o[21]) + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], Z_TOP - o[20]]), self.hyaw - o[21] + + def grasp_R(self, ryaw): + return rotz(ryaw) @ rotx(ROLL) + + def set_stand_goal(self): + c, s = np.cos(self.hyaw), np.sin(self.hyaw) + off = np.array([c * STAND[0] - s * STAND[1], s * STAND[0] + c * STAND[1]]) + self.base_goal = self.handle - off + self.yaw_goal = self.hyaw + + def look(self, o, tools): + img = tools.image("left_wrist") + r = localize_top(img, o[0:7], o[18:22], prior=self.handle) + if r is None: + self.dbg = dict(look="fail") + return False + self.handle, self.hyaw = r[0], float(np.clip(r[1], -0.15, 0.15)) + self.dbg = dict(h=np.round(self.handle, 3).tolist(), yaw=round(self.hyaw, 3), n=r[2]) + return True + + # ---------------------------------------------------------------- act + def act(self, obs, tools): + o = np.asarray(obs["low_dim_obs"], float) + self.t += 1 + self.pt += 1 + qcur = o[0:7] + + if self.phase == "look0": + self.ql = np.zeros(7) + self.qr = np.zeros(7) + self.grip = 0.0 + if self.pt >= 25: + ok = self.look(o, tools) + if not ok: + self.handle = np.array([self.x0 + 0.54, self.y0]) + self.hyaw = 0.0 + self.set_stand_goal() + self.phase, self.pt = "walk", 0 + # arm pose for walking / second look: camera above and behind the handle + self.q_look, _, _ = ik(np.array([0.22, 0.12, 0.12]), roty(0.25), np.zeros(7), tool=TOOL) + elif self.phase == "walk": + s = min(1.0, self.pt / 30) + self.ql = s * self.q_look + self.qr = s * QR_SAFE + _, _, _, dist = self.base_cmd(o) + eyaw = abs(self.yaw_goal - o[21]) + if (dist < 0.02 and eyaw < 0.05 and self.pt > 40) or self.pt > 250: + self.phase, self.pt = "settle", 0 + elif self.phase == "settle": + if self.pt >= 20: + self.look(o, tools) + self.set_stand_goal() + hr, ryaw = self.handle_rel(o) + self.q_from = qcur.copy() + self.q_pre, _, _ = ik(hr + rotz(ryaw) @ np.array([-0.12, GRASP_DY, 0]), self.grasp_R(ryaw), + self.ql, tool=TOOL) + self.phase, self.pt = "pre", 0 + elif self.phase == "pre": + s = min(1.0, self.pt / 40) + self.ql = self.q_from + s * (self.q_pre - self.q_from) + if self.pt >= 55: + self.phase, self.pt = "approach", 0 + elif self.phase == "approach": + # -0.12 -> -0.05 (steps 0-40), dwell (40-70), -> GRASP_DX (70-100) + if self.pt < 40: + dx = -0.12 + 0.07 * self.pt / 40 + elif self.pt < 70: + dx = -0.05 + else: + dx = -0.05 + (0.05 + GRASP_DX) * min(1.0, (self.pt - 70) / 30) + if self.pt % 5 == 1: + if self.pt < 95: + r = bar_row_rotated(tools.image("left_wrist")) + if r is not None: + depth = max(0.03, -dx + 0.03) + err = r[0] - V_STAR + self.dz = float(np.clip(self.dz - 0.5 * err * depth / CAM_F, -0.05, 0.05)) + self.dbg = dict(bar=None if r is None else [round(float(r[0]), 1), round(float(r[1]), 1)], + dz=round(self.dz, 4)) + hr, ryaw = self.handle_rel(o) + self.ql, _, _ = ik(hr + rotz(ryaw) @ np.array([dx, GRASP_DY, 0]) + np.array([0, 0, self.dz]), + self.grasp_R(ryaw), self.ql, tool=TOOL, iters=40) + if self.pt >= 110: + self.phase, self.pt = "grasp", 0 + elif self.phase == "grasp": + self.grip = min(1.0, self.pt / 15) + if self.pt >= 40: + self.phase, self.pt = "pull", 0 + hr, ryaw = self.handle_rel(o) + self.pull_from = hr + rotz(ryaw) @ np.array([GRASP_DX, GRASP_DY, 0]) + np.array([0, 0, self.dz]) + self.pull_ryaw = ryaw + c, s_ = np.cos(self.hyaw), np.sin(self.hyaw) + self.base_goal = self.base_goal - 0.35 * np.array([c, s_]) + self.base_hold = True + elif self.phase == "pull": + s = min(1.0, self.pt / 80) + if self.pt % 4 == 1: + tgt = self.pull_from + rotz(self.pull_ryaw) @ np.array([-0.18 * s, 0, 0]) + self.ql, _, _ = ik(tgt, self.grasp_R(self.pull_ryaw), self.ql, tool=TOOL, iters=40) + + raw = np.zeros(20) + raw[2] = 0.74 + if self.phase in ("look0", "settle", "pre", "approach", "grasp") or (self.phase == "pull" and self.pt < 60): + vx = vy = wz = 0.0 + else: + vx, vy, wz, _ = self.base_cmd(o) + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4:11] = self.ql + raw[11:18] = self.qr + raw[18] = self.grip + raw[19] = 0.0 + return raw diff --git a/policies/drawer_top_open/opus-s3/episodes.csv b/policies/drawer_top_open/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..07131e27c2c9b81c0290dd5009debf129890e0b0 --- /dev/null +++ b/policies/drawer_top_open/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,650,success,0 +620001,1,612,success,0 +620002,1,619,success,0 +620003,1,582,success,0 +620004,1,610,success,0 +620005,1,676,success,0 +620006,1,595,success,0 +620007,1,560,success,0 +620008,1,592,success,0 +620009,1,632,success,0 +620010,1,622,success,0 +620011,1,689,success,0 +620012,1,709,success,0 +620013,1,727,success,0 +620014,1,593,success,0 +620015,1,603,success,0 +620016,1,644,success,0 +620017,1,644,success,0 +620018,1,632,success,0 +620019,1,546,success,0 +620020,1,610,success,0 +620021,1,651,success,0 +620022,1,635,success,0 +620023,1,629,success,0 +620024,1,640,success,0 +620025,1,624,success,0 +620026,1,599,success,0 +620027,1,597,success,0 +620028,1,677,success,0 +620029,1,664,success,0 +620030,1,714,success,0 +620031,1,616,success,0 +620032,1,632,success,0 +620033,1,601,success,0 +620034,1,665,success,0 +620035,1,586,success,0 +620036,1,603,success,0 +620037,1,612,success,0 +620038,1,583,success,0 +620039,1,624,success,0 +620040,1,585,success,0 +620041,1,683,success,0 +620042,1,747,success,0 +620043,1,630,success,0 +620044,1,648,success,0 +620045,1,632,success,0 +620046,1,593,success,0 +620047,1,646,success,0 +620048,1,706,success,0 +620049,1,585,success,0 +620050,1,685,success,0 +620051,1,627,success,0 +620052,1,598,success,0 +620053,1,586,success,0 +620054,1,604,success,0 +620055,1,628,success,0 +620056,1,592,success,0 +620057,1,587,success,0 +620058,1,609,success,0 +620059,1,671,success,0 +620060,1,607,success,0 +620061,1,681,success,0 +620062,1,623,success,0 +620063,1,603,success,0 +620064,1,573,success,0 +620065,1,605,success,0 +620066,1,587,success,0 +620067,1,590,success,0 +620068,1,600,success,0 +620069,1,596,success,0 +620070,1,586,success,0 +620071,1,589,success,0 +620072,1,825,success,0 +620073,1,751,success,0 +620074,1,550,success,0 +620075,1,654,success,0 +620076,1,588,success,0 +620077,1,601,success,0 +620078,1,604,success,0 +620079,1,613,success,0 +620080,1,716,success,0 +620081,1,595,success,0 +620082,1,761,success,0 +620083,1,598,success,0 +620084,1,643,success,0 +620085,1,582,success,0 +620086,1,620,success,0 +620087,1,623,success,0 +620088,1,630,success,0 +620089,1,661,success,0 +620090,1,585,success,0 +620091,1,658,success,0 +620092,1,683,success,0 +620093,1,572,success,0 +620094,1,669,success,0 +620095,1,613,success,0 +620096,1,584,success,0 +620097,1,617,success,0 +620098,1,629,success,0 +620099,1,575,success,0 diff --git a/policies/drawer_top_open/opus-s3/headcam.py b/policies/drawer_top_open/opus-s3/headcam.py new file mode 100644 index 0000000000000000000000000000000000000000..67d422c476041b426f57fc66e51cf7b5c89e1c8a --- /dev/null +++ b/policies/drawer_top_open/opus-s3/headcam.py @@ -0,0 +1,33 @@ +"""Head camera model (pelvis frame), calibrated from the left gripper seen at known arm poses.""" +import numpy as np + +# camera centre (pelvis frame), camera axes as columns (x right, y down, z optical), focal px +CAM_C = np.array([0.1379, 0.0027, 0.3873]) +CAM_R = np.array([[0.0242, -0.9044, 0.426], + [-0.9997, -0.0215, 0.0113], + [-0.001, -0.4261, -0.9047]]) +CAM_F = 70.59 + + +def ray(u, v): + """Unit ray (pelvis frame) through pixel (u, v) of the 84x84 head image.""" + d = CAM_R @ np.array([(u - 42.0) / CAM_F, (v - 42.0) / CAM_F, 1.0]) + return d / np.linalg.norm(d) + + +def project(p): + pc = CAM_R.T @ (np.asarray(p) - CAM_C) + return np.array([42 + CAM_F * pc[0] / pc[2], 42 + CAM_F * pc[1] / pc[2]]) + + +def on_plane_z(u, v, z): + """Point on the ray through (u,v) at pelvis-frame height z.""" + d = ray(u, v) + t = (z - CAM_C[2]) / d[2] + return CAM_C + t * d + + +def on_plane_x(u, v, x): + d = ray(u, v) + t = (x - CAM_C[0]) / d[0] + return CAM_C + t * d diff --git a/policies/drawer_top_open/opus-s3/kin.py b/policies/drawer_top_open/opus-s3/kin.py new file mode 100644 index 0000000000000000000000000000000000000000..a0033af48bf9eb616aaff67211436030d3a8b706 --- /dev/null +++ b/policies/drawer_top_open/opus-s3/kin.py @@ -0,0 +1,79 @@ +"""Approximate G1 arm kinematics (pelvis frame: x forward, y left, z up).""" +import numpy as np +from scipy.optimize import least_squares + + +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _rpy(r, p, y): + return _rz(y) @ _ry(p) @ _rx(r) + + +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +TORSO = np.array([-0.0039635, 0.0, 0.054]) +HAND = 0.12 # wrist-yaw joint to grasp centre (guess) + + +def fk(q, side="left", hand=HAND): + """Return (position, rotation) of the grasp point in the pelvis frame.""" + s = 1.0 if side == "left" else -1.0 + lo, hi = (LO, HI) if side == "left" else (np.array([LO[0], -HI[1], LO[2], LO[3], LO[4], LO[5], LO[6]]), None) + p = TORSO.copy() + R = np.eye(3) + + def step(t, Rj): + nonlocal p, R + p = p + R @ np.asarray(t) + R = R @ Rj + + step([0.0039563, s * 0.10022, 0.23778], _rpy(s * 0.27931, 5.4949e-05, -s * 0.00019159) @ _ry(q[0])) + step([0, s * 0.038, -0.013831], _rx(-s * 0.27925) @ _rx(q[1])) + step([0, s * 0.00624, -0.1032], _rz(q[2])) + step([0.015783, 0, -0.080518], _ry(q[3])) + step([0.100, s * 0.00188791, -0.010], _rx(q[4])) + step([0.038, 0, 0], _ry(q[5])) + step([0.046, 0, 0], _rz(q[6])) + return p + R @ np.array([hand, 0, 0]), R + + +def limits(side): + # shoulder roll limited so the upper arm does not hit the torso + if side == "left": + lo = LO.copy() + lo[1] = 0.02 + return lo, HI + # right arm: roll/yaw limits mirrored + lo = np.array([-3.0892, -2.2515, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) + hi = np.array([2.6704, -0.02, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + return lo, hi + + +def ik(target_p, target_R=None, side="left", q0=None, hand=HAND, w_rot=0.3, reg=0.01, q_ref=None): + lo, hi = limits(side) + q0 = np.zeros(7) if q0 is None else np.asarray(q0, float) + q_ref = q0 if q_ref is None else q_ref + + def res(q): + p, R = fk(q, side, hand) + r = [p - target_p] + if target_R is not None: + r.append(w_rot * (R - target_R).ravel()) + r.append(reg * (q - q_ref)) + return np.concatenate(r) + + sol = least_squares(res, np.clip(q0, lo + 1e-3, hi - 1e-3), bounds=(lo, hi)) + return sol.x, sol diff --git a/policies/drawer_top_open/opus-s3/policy.py b/policies/drawer_top_open/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f4a5edb8076235464ab53b6b16d7f3a929474666 --- /dev/null +++ b/policies/drawer_top_open/opus-s3/policy.py @@ -0,0 +1,377 @@ +"""Open the top drawer: walk to a fixed pose relative to the handle seen by the +head camera, grasp the handle with the left gripper (fingers vertical), pull.""" + +import numpy as np +from scipy import ndimage + +from headcam import on_plane_z, project +from kin import fk, ik + +TUCK_L = np.array([0.2, 0.25, 0.0, 1.3, 0.0, 0.0, 0.0]) # arms down, out of the head view +TUCK_R = np.array([0.2, -0.25, 0.0, 1.3, 0.0, 0.0, 0.0]) +RT = np.array([[1.0, 0, 0], [0, 0, -1.0], [0, 1.0, 0]]) # gripper forward, fingers vertical + +P = dict( + ZH=-0.02, # handle height in the pelvis frame + HX=0.31, # desired handle position in the pelvis frame after walking + HY=0.13, + PRE=0.06, + WALK_TOL=0.04, + KI=0.05, # pre-grasp stand-off + PULL_T=150.0, + HOOK=0.4, + PULL_D=0.12, + BACK_T=500, + BACK_D=0.30, + VBACK=-0.1, + EMPTY=-0.017, + RETRIES=2, + RETRY_D=0.18, + DX=0.10, # max grasp depth offset past the detected handle + DZ=0.005, + DY=-0.06, + ADV=0.0015, # approach speed per step + LAG=0.015, # contact: commanded minus measured hand x + BACKOFF=0.01, + KZ=0.2 / 537.0, + CT=43.0, + KY=0.0002, + BOT=75, + TOP=8, +) + + +def wood_edge(im): + """Bottom edge of the wooden counter front: v = m*u + b, or None.""" + g = im.astype(float) + wood = (g[..., 0] - g[..., 2]) > 30 + us, vs = [], [] + for u in range(8, 76): + rows = np.nonzero(wood[0:40, u])[0] + if len(rows): + r = rows[0] + while r + 1 < 40 and wood[r + 1, u]: + r += 1 + us.append(u) + vs.append(r + 0.5) + if len(us) < 20: + return None + us = np.array(us, float) + vs = np.array(vs) + A = np.stack([us, np.ones_like(us)], 1) + m, b = np.linalg.lstsq(A, vs, rcond=None)[0] + for _ in range(2): + keep = np.abs(vs - (m * us + b)) < 1.2 + if keep.sum() < 10: + break + m, b = np.linalg.lstsq(A[keep], vs[keep], rcond=None)[0] + return m, b + + +def detect_handle(im, pred=None): + """Top drawer handle in the head image: topmost dark horizontal bar below the counter.""" + g = im.astype(float).mean(axis=2) + # thin dark horizontal line: darker than the pixels a few rows above and below + d = np.zeros_like(g) + for k in (1, 2, 3): + up = np.full_like(g, 0.0) + dn = np.full_like(g, 0.0) + up[k:] = g[:-k] + dn[:-k] = g[k:] + d = np.maximum(d, np.minimum(up, dn) - g) + dark = (d > 25) & (g < 112) + loose = (d > 12) & (g < 132) + edge = wood_edge(im) + vv = np.arange(84)[:, None] + uu = np.arange(84)[None, :] + if edge is not None: + dark &= vv > edge[0] * uu + edge[1] + 3 + else: + dark[:8] = False + dark[60:] = False + dark[:, :10] = False + dark[:, 74:] = False + # horizontal runs of dark-line pixels, 6..30 px long, containing a dark core + runs = [] + for r in range(84): + row = dark[r] + u = 0 + while u < 84: + if row[u]: + s = u + while u < 84 and row[u]: + u += 1 + if 5 <= u - s <= 30: + # extend over the lighter ends of the bar + s0, u0 = s, u + while s > 0 and loose[r, s - 1] and s0 - s < 5: + s -= 1 + while u < 84 and loose[r, u] and u - u0 < 5: + u += 1 + runs.append((r, s, u)) + else: + u += 1 + best = None + for r, s, e in runs: + if True: + c = ((s + e - 1) / 2.0, float(r), e - s) + if pred is not None: + d = np.hypot(c[0] - pred[0], c[1] - pred[1]) + if d > 8: + continue + key = d + else: + key = c[1] + if best is None or key < best[0]: + best = (key, c) + return None if best is None else best[1] + + +def detect_bar(im): + """Handle bar in the left wrist image (gripper rolled 90 deg: the bar is a + vertical uniform-grey band). Returns (column centre, width, top row, bottom row).""" + g = im.astype(float).mean(axis=2) + mask = (g >= 86) & (g <= 106) + mask = ndimage.binary_opening(mask, np.ones((1, 3))) + lab, n = ndimage.label(mask) + best = None + for i in range(1, n + 1): + ys, xs = np.nonzero(lab == i) + if ys.max() - ys.min() < 12 or len(ys) < 60: + continue + if best is None or len(ys) > best[0]: + best = (len(ys), ys, xs) + if best is None: + return None + _, ys, xs = best + near = np.abs(ys - 42) <= 10 + c = xs[near].mean() if near.sum() >= 10 else xs.mean() + rows, counts = np.unique(ys, return_counts=True) + w = float(np.median(counts)) + return float(c), w, int(ys.min()), int(ys.max()) + + +def to_world(p, pel): + x, y, yaw = pel + c, s = np.cos(yaw), np.sin(yaw) + return np.array([x + c * p[0] - s * p[1], y + s * p[0] + c * p[1], p[2]]) + + +def to_body(pw, pel): + x, y, yaw = pel + c, s = np.cos(yaw), np.sin(yaw) + dx, dy = pw[0] - x, pw[1] - y + return np.array([c * dx + s * dy, -s * dx + c * dy, pw[2]]) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "settle" + self.t_phase = 0 + self.meas = [] + self.handle_w = None + self.q_left = np.zeros(7) + self.grip = 0.6 + self.dbg = "" + self.n_walk = 0 + self.hist = [] + self.qi = np.zeros(7) + self.bar = None + self.off = np.zeros(3) + self.n_lag = 0 + self.n_empty = 0 + self.retries = 0 + + def pel(self, obs): + lo = obs["low_dim_obs"] + return np.array([lo[18], lo[19], lo[21]]) + + def measure(self, obs, tools): + pred = None + if self.handle_w is not None: + pred = project(to_body(self.handle_w, self.pel(obs))) + det = detect_handle(tools.image("head"), pred) + if det is None: + return None + u, v, w = det + pb = on_plane_z(u, v, P["ZH"]) + return to_world(pb, self.pel(obs)) + + def walk_err(self, pel): + """Body-frame error to the stance with yaw 0 and the handle at (HX, HY).""" + goal = self.handle_w[:2] - np.array([P["HX"], P["HY"]]) + ew = goal - pel[:2] + c, s = np.cos(pel[2]), np.sin(pel[2]) + eb = np.array([c * ew[0] + s * ew[1], -s * ew[0] + c * ew[1]]) + return eb, np.linalg.norm(eb) + + def servo(self, tools): + """Centre the handle bar between the fingers using the left wrist camera.""" + self.bar = detect_bar(tools.image("left_wrist")) + if self.bar is None: + return + c, w, top, bot = self.bar + if w > 22 or bot - top < 15: + self.bar = None + return + self.off[2] -= np.clip(P["KZ"] * (c - P["CT"]), -0.0015, 0.0015) + # image up = world right (-y): centre the visible part of the bar vertically + mid = (min(bot, 80) + max(top, 3)) / 2.0 + self.off[1] -= np.clip(P["KY"] * (41.5 - mid), -0.0015, 0.0015) + self.off[1:] = np.clip(self.off[1:], [-0.12, -0.08], [0.08, 0.08]) + + def empty(self, obs): + """Fingers closed on nothing (they stop near -0.012 on the handle).""" + return float(np.mean(obs["low_dim_obs"][7:9])) < P["EMPTY"] + + def hand_now(self): + p, _ = fk(self.q_left, "left") + return p + + def goto(self, name): + self.phase = name + self.t_phase = 0 + + def arm(self, target, q0=None, pitch=0.0): + c, s = np.cos(pitch), np.sin(pitch) + Ry = np.array([[c, 0, s], [0, 1.0, 0], [-s, 0, c]]) + q, _ = ik(np.asarray(target, float), Ry @ RT, "left", q0=self.q_left if q0 is None else q0) + self.q_left = q + return q + + def act(self, obs, tools): + a = self.hold.copy() + pel = self.pel(obs) + self.t_phase += 1 + tp = self.t_phase + + if self.phase in ("settle", "walk", "measure"): + a[4:11] = TUCK_L + a[11:18] = TUCK_R + if self.phase == "settle": + if tp > 30: + m = self.measure(obs, tools) + if m is not None: + self.meas.append(m) + if tp >= 40: + if not self.meas: + self.dbg = "no handle" + return a + self.handle_w = np.median(np.array(self.meas), axis=0) + self.meas = [] + self.goto("walk") + elif self.phase == "walk": + eb, dist = self.walk_err(pel) + a[3] = np.clip(-1.5 * pel[2], -0.3, 0.3) + if dist > 0.012: + v = eb * np.clip(1.5 * dist, 0.07, 0.2) / dist + a[0], a[1] = v + self.dbg = f"eb={np.round(eb,3)}" + if (dist < 0.012 and abs(pel[2]) < 0.02) or tp > 300: + self.goto("measure") + elif self.phase == "measure": + if tp > 25: + m = self.measure(obs, tools) + if m is not None: + self.meas.append(m) + if tp >= 40: + if self.meas: + self.handle_w = np.median(np.array(self.meas), axis=0) + self.meas = [] + self.n_walk += 1 + eb, dist = self.walk_err(pel) + self.hist.append(np.round(eb, 3).tolist()) + if dist > P["WALK_TOL"] and self.n_walk < 3: + self.goto("walk") + else: + self.q_left = np.zeros(7) + self.goto("pregrasp") + else: + hb = to_body(self.handle_w, pel) + self.dbg = f"hb={np.round(hb,3)}" + if self.phase == "pregrasp": + if tp == 1: + self.off = np.array([-P["PRE"], P["DY"], P["DZ"]]) + self.grip = 0.0 + if tp > 35: + self.servo(tools) + self.arm(hb + self.off) + if tp >= 60: + self.goto("approach") + elif self.phase == "approach": + self.servo(tools) + self.off[0] += P["ADV"] + self.arm(hb + self.off) + pm, _ = fk(obs["low_dim_obs"][0:7], "left") + pc, _ = fk(self.q_left, "left") + lag = pc[0] - pm[0] + if tp == 1: + self.pel_app = pel.copy() + retreat = to_body(np.r_[self.pel_app[:2], 0.0], pel)[0] + lag = max(lag, retreat) + self.dbg = f"off={np.round(self.off,3)} lag={lag:.3f} bar={self.bar}" + self.n_lag = self.n_lag + 1 if (tp > 20 and lag > P["LAG"]) else 0 + if self.n_lag >= 5 or self.off[0] > P["DX"]: + self.off[0] -= P["BACKOFF"] + self.tgt_fix = hb + self.off + self.grasp_w = to_world(self.tgt_fix, pel) + self.hist.append(("grasp", np.round(self.off, 3).tolist(), round(float(lag), 3))) + self.goto("close") + elif self.phase == "close": + self.arm(self.tgt_fix) + self.grip = 1.0 + if tp >= 30: + self.back0 = pel.copy() + if self.empty(obs) and self.retries < P["RETRIES"]: + self.goto("lost") + else: + self.goto("pull") + elif self.phase == "lost": + # missed or dropped the handle: open, back the hand off, start over + self.grip = 0.0 + self.arm(self.tgt_fix - np.array([0.10 * min(1.0, tp / 30.0), 0, 0])) + if tp >= 40: + self.retries += 1 + self.hist.append(("retry", int(obs["t"]))) + self.handle_w = None + self.meas = [] + self.n_walk = 0 + self.qi = np.zeros(7) + self.n_empty = 0 + self.goto("settle") + elif self.phase == "pull": + # retract the arm while stepping backwards + fp = min(1.0, tp / 20.0) + f = min(1.0, max(0.0, tp - 20) / P["PULL_T"]) + # keep the hand's lateral world position on the bar while the body drifts + tb = to_body(self.grasp_w, pel) + tgt = np.array([self.tgt_fix[0] - P["PULL_D"] * f, tb[1], self.tgt_fix[2]]) + self.arm(tgt, pitch=P["HOOK"] * fp) + self.grip = 1.0 + moved = np.hypot(*(pel[:2] - self.back0[:2])) + self.dbg = f"moved={moved:.3f}" + if tp > 20 and tp < P["BACK_T"] and moved < P["BACK_D"]: + a[0] = P["VBACK"] + ey = to_body(np.r_[self.back0[:2], 0.0], pel)[1] + if abs(ey) > 0.01: + a[1] = np.clip(1.5 * ey, -0.1, 0.1) + a[3] = np.clip(-1.0 * pel[2], -0.2, 0.2) + self.n_empty = self.n_empty + 1 if self.empty(obs) else 0 + if self.n_empty >= 10: + if moved < P["RETRY_D"] and self.retries < P["RETRIES"]: + self.tgt_fix = self.hand_now() + self.goto("lost") + else: + # drawer pulled out to its stop: stand still + self.goto("done") + elif self.phase == "done": + self.grip = 0.0 + if self.phase in ("pregrasp", "approach"): + # integral action against gravity sag of the position-controlled arm + qm = obs["low_dim_obs"][0:7] + self.qi = np.clip(self.qi + P["KI"] * (self.q_left - qm), -0.1, 0.1) + a[4:11] = self.q_left + self.qi + a[11:18] = TUCK_R + a[18] = self.grip + return a diff --git a/policies/flip_cup/astra-s1/episodes.csv b/policies/flip_cup/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..fa84b891ef1a524784bc84db909190a4e340990a --- /dev/null +++ b/policies/flip_cup/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,1,1167,success,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,1,1141,success,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,1,1064,success,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,1,1071,success,0 +620018,0,1850,timeout,0 +620019,1,931,success,0 +620020,0,1850,timeout,0 +620021,1,1212,success,0 +620022,1,1150,success,0 +620023,0,1850,timeout,0 +620024,1,1183,success,0 +620025,1,1044,success,0 +620026,0,1850,timeout,0 +620027,1,1121,success,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,1,1010,success,0 +620031,1,1293,success,0 +620032,1,1120,success,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,1,1083,success,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,1,1351,success,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,1,1634,success,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,1,1081,success,0 +620057,0,1850,timeout,0 +620058,1,988,success,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,1,1385,success,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,1,1059,success,0 +620065,1,979,success,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,1,1202,success,0 +620079,1,1067,success,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,1,1241,success,0 +620084,1,1408,success,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,1,1065,success,0 +620088,1,1119,success,0 +620089,1,1055,success,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,1,1060,success,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/astra-s1/policy.py b/policies/flip_cup/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab7d4f3be137316e6731ae8cfbc6de031af24fe --- /dev/null +++ b/policies/flip_cup/astra-s1/policy.py @@ -0,0 +1,143 @@ +"""Deterministic camera-guided cup turnover. + +The head view selects the nearer hand. Pelvis feedback controls short base +adjustments; color segmentation in the wrist view guides the reach. Once the +cup is close, reach depth is latched while alignment settles. The hand then +retracts, pre-rotates, grasps, lifts, turns, lowers, releases, and withdraws. +All parameters are hand-written controller constants; no fitted components +or demonstration files are used at runtime. +""" + +import numpy as np +import cv2 + +class Policy: + + def cup(self, im): + f = im.astype(float) + m = (np.ptp(f, axis=2) < 27) & (f.mean(2) > 65) & (f.mean(2) < 238) + n, l, st, c = cv2.connectedComponentsWithStats(m.astype('uint8')) + ids = [i for i in range(1, n) if st[i, 4] > 40 and st[i, 1] < 76 and (not (st[i, 2] > 78 and st[i, 3] < 60 and (st[i, 1] > 24)))] + if not ids: + return None + i = max(ids, key=lambda i: st[i, 4]) + x, y, w, h, ar = st[i] + return np.array([c[i, 0], c[i, 1], w, h, ar]) + + def reset(self, obs, tools): + self.a = np.array(tools.hold_action()) + self.a[19:] = 0 + im = tools.image('head').astype(float) + r, g, b = im.transpose(2, 0, 1) + m = (np.ptp(im, 2) < 30) & (im.mean(2) < 205) & (im.mean(2) > 50) + m[14:] = False + y, x = np.where(m) + if len(x) < 5: + m = (r > 110) & (g > 70) & (b < g * 0.8) & (g < r * 0.92) + m[15:] = False + y, x = np.where(m) + cx = float(np.mean(x)) if len(x) else 25 + self.side = 1 if cx < 42 else -1 + self.idx = 5 if self.side == 1 else 12 + self.grip = 19 if self.side == 1 else 20 + self.forward_checked = False + self.depth_ready = False + self.ready_t = 0 + self.cam = 'left_wrist' if self.side == 1 else 'right_wrist' + dist = cx if self.side == 1 else 83 - cx + self.sr = 0.27 + self.sp = -0.6 + self.el = 0.2 + self.start = self.a.copy() + self.stage = -1 + self.t0 = 0 + self.grasp = None + self.base_y = float(obs['low_dim_obs'][22]) + (13 - dist) * 0.006 * self.side + + def arm(self, sp, sr, el, wr=0, g=0): + a = self.a.copy() + a[self.idx:self.idx + 7] = [sp, self.side * sr, 0, el, self.side * wr, 0, 0] + a[self.grip] = g + return a + + def act(self, obs, tools): + t = obs['t'] + u = t - self.t0 + if self.stage == -2: + dx = self.forward_x - obs['low_dim_obs'][21] + self.a[0] = max(0.08, min(0.18, 2 * dx)) if dx > 0.012 else 0 + self.a[3] = np.clip(-3 * obs['low_dim_obs'][24], -0.35, 0.35) + if dx < 0.012 or u > 120: + self.a[0] = 0 + self.a[3] = 0 + self.stage = 1 + self.t0 = t + 40 + elif self.stage == -1: + dy = self.base_y - obs['low_dim_obs'][22] + self.a[1] = np.sign(dy) * max(0.065, min(0.25, 2 * abs(dy))) if abs(dy) > 0.012 else 0 + self.a[3] = np.clip(-3 * obs['low_dim_obs'][24], -0.3, 0.3) + if abs(dy) < 0.012 and t > 40 or t > 220: + self.a[1] = 0 + self.a[3] = 0 + self.stage = 0 + self.t0 = t + self.start = self.a.copy() + elif self.stage == 0: + target = self.arm(self.sp, self.sr, self.el) + self.a = self.start + (target - self.start) * min(1, (u + 1) / 60) + if u >= 80: + self.stage = 1 + self.t0 = t + elif self.stage == 1: + if u >= 0 and u % 10 == 0: + c = self.cup(tools.image(self.cam)) + self.last_c = c + if c is not None: + x, y, w, h, area = c + if not self.forward_checked: + self.forward_checked = True + if w < 51: + self.forward_x = min(0.265, float(obs['low_dim_obs'][21]) + 0.08) + self.stage = -2 + self.t0 = t + return self.a + self.sr += self.side * 0.0009 * (42 - x) + self.el += np.clip((y - 43) * 0.002, -0.06, 0.06) + if w >= 73 and h >= 72 and (not self.depth_ready): + self.depth_ready = True + self.ready_t = t + if not self.depth_ready: + if abs(x - 42) < 7 and abs(y - 43) < 7: + if self.sp + self.a[4] > -1.15: + self.sp -= 0.018 + self.el += 0.027 + elif self.a[4] < 0.55: + self.a[4] += 0.015 + self.sp -= 0.015 + elif u > 50 and (abs(x - 42) < 3 and abs(y - 43) < 3 or t - self.ready_t > 100): + self.stage = 2 + self.t0 = t + self.start = self.a.copy() + self.grasp = (self.sp - 0.2, self.sr, self.el + 0.28) + else: + self.el += 0.015 + self.sr = float(np.clip(self.sr, -0.6, 0.6)) + self.sp = max(-2.2, self.sp) + self.el = float(np.clip(self.el, -0.5, 1.7)) + self.a = self.arm(self.sp, self.sr, self.el) + if u > 700: + self.stage = 2 + self.t0 = t + self.start = self.a.copy() + self.grasp = (self.sp - 0.2, self.sr, self.el + 0.28) + else: + sp, sr, el = self.grasp + poses = [(sp + 0.35, sr, el - 0.48, -1.1, 0), (sp, sr, el, -1.1, 0), (sp, sr, el, -1.1, 1), (sp - 0.25, sr, el, -1.1, 1), (sp - 0.25, sr, el, 1.97, 1), (sp, sr, el, 1.97, 1), (sp, sr, el, 1.97, 0), (-0.35, sr, 0, 0, 0)] + j = min(self.stage - 2, len(poses) - 1) + target = self.arm(*poses[j]) + self.a = self.start + (target - self.start) * min(1, (u + 1) / 65) + if u >= 99 and self.stage < 9: + self.stage += 1 + self.t0 = t + 1 + self.start = self.a.copy() + return self.a diff --git a/policies/flip_cup/astra-s2/episodes.csv b/policies/flip_cup/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2e6fb48c667f53e3b8c46ff23f07ddf3f15a8908 --- /dev/null +++ b/policies/flip_cup/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,1,1482,success,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,1,1433,success,0 +620005,1,1447,success,0 +620006,1,1499,success,0 +620007,0,1850,timeout,0 +620008,1,1403,success,0 +620009,1,1344,success,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,1,1378,success,0 +620013,1,1439,success,0 +620014,1,1668,success,0 +620015,1,1401,success,0 +620016,0,1850,timeout,0 +620017,1,1428,success,0 +620018,1,1474,success,0 +620019,0,1850,timeout,0 +620020,1,1488,success,0 +620021,0,1850,timeout,0 +620022,1,1462,success,0 +620023,1,1526,success,0 +620024,1,1417,success,0 +620025,1,1477,success,0 +620026,0,1850,timeout,0 +620027,1,1535,success,0 +620028,1,1467,success,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,1,1762,success,0 +620032,0,1850,timeout,0 +620033,1,1366,success,0 +620034,1,1482,success,0 +620035,1,1484,success,0 +620036,0,1850,timeout,0 +620037,1,1496,success,0 +620038,0,1850,timeout,0 +620039,1,1589,success,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,1,1373,success,0 +620046,1,1499,success,0 +620047,0,1850,timeout,0 +620048,1,1461,success,0 +620049,1,1383,success,0 +620050,1,1519,success,0 +620051,1,1477,success,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,1,1477,success,0 +620055,1,1475,success,0 +620056,1,1388,success,0 +620057,1,1460,success,0 +620058,0,1850,timeout,0 +620059,1,1412,success,0 +620060,1,1493,success,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,1,1429,success,0 +620064,1,1495,success,0 +620065,1,1366,success,0 +620066,0,1850,timeout,0 +620067,1,1365,success,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,1,1475,success,0 +620071,1,1380,success,0 +620072,1,1457,success,0 +620073,1,1537,success,0 +620074,1,1442,success,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,1,1401,success,0 +620078,1,1517,success,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,1,1451,success,0 +620082,1,1479,success,0 +620083,1,1675,success,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,1,1445,success,0 +620088,1,1433,success,0 +620089,1,1541,success,0 +620090,1,1406,success,0 +620091,1,1426,success,0 +620092,1,1483,success,0 +620093,1,1423,success,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,1,1589,success,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/astra-s2/policy.py b/policies/flip_cup/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b2263314394d58be744e244f8c0a610e347fa060 --- /dev/null +++ b/policies/flip_cup/astra-s2/policy.py @@ -0,0 +1,226 @@ +"""Deterministic cup-turning controller using camera segmentation, visual feedback, and joint-axis inverse kinematics. Runtime inputs are exclusively the robot cameras and proprioception.""" +import numpy as np +import cv2 +from scipy.spatial.transform import Rotation +from scipy.optimize import least_squares + +class Policy: + + def reset(self, obs, tools): + """Initialize the approach and estimate lateral alignment from the head camera.""" + self.a = np.array(tools.hold_action(), float) + self.a[19:] = 0 + self.a[5:12] = [-0.4, 0.15, 0, -0.8, 0, 0.9, 0] + self.a[12:19] = [-0.4, -0.15, 0, -0.8, 0, 0.9, 0] + self.phase = 'walk' + self.age = 0 + self.q = -0.4 + self.roll = 0.15 + self.height = 0.74 + self.pitch = 0.0 + self.box = None + self.missing = 0 + self.searchdir = 1 + self.angle = -0.3 + im = tools.image('head').astype(float) + r, g, b = im.transpose(2, 0, 1) + m = ((abs(r - b) < 20) & (abs(g - b) < 20) & (r > 70) & (r < 230)).astype('uint8') + m[16:] = 0 + n, l, st, cc = cv2.connectedComponentsWithStats(m) + candidates = [i for i in range(1, n) if st[i, 4] > 15 and st[i, 3] > 2] + self.basex = 0.3 + self.basey = 0.0 + if candidates: + k = max(candidates, key=lambda i: st[i, 4]) + x, y, w, h, _ = st[k] + self.basex = float(np.clip(0.3 - (y + h) * 0.008, 0.17, 0.3)) + self.basey = float(np.clip(-(cc[k, 0] - 17) * 0.008, -0.22, 0.15)) + + def detect(self, im): + """Find the neutral-colored cup and its bright, elongated handle in the wrist image.""" + a = im.astype(float) + r, g, b = a.transpose(2, 0, 1) + m = ((b > r - 7) & (b > g - 7) & (b < r + 25) & (r > 85) & (r < 239)).astype('uint8') + m[72:] = 0 + m[:, :3] = 0 + m[:, 81:] = 0 + n, l, st, cen = cv2.connectedComponentsWithStats(m) + choices = [i for i in range(1, n) if st[i, 4] > 50 and st[i, 3] > 8 and (st[i, 2] > 8) and (st[i, 2] <= 78)] + if not choices: + return None + i = max(choices, key=lambda i: st[i, 4]) + x, y, w, h, area = st[i] + bright = ((r > 210) & (g > 210) & (b > 210) & (b > g - 9)).astype('uint8') + bright[:max(0, y + 3)] = 0 + bright[min(84, y + h):] = 0 + bright[:, :max(0, x - 3)] = 0 + bright[:, min(84, x + w + 3):] = 0 + nn, ll, ss, cc = cv2.connectedComponentsWithStats(bright) + candidates = [j for j in range(1, nn) if ss[j, 4] >= 6 and ss[j, 3] >= 6 and (ss[j, 3] > ss[j, 2] * 1.2)] + if candidates: + j = max(candidates, key=lambda j: ss[j, 4]) + cx = cc[j, 0] + required = 46.0 if abs(cx - cen[i, 0]) > 6 else 38.0 + w = ss[j, 3] * 60.0 / required + y = ss[j, 1] + h = ss[j, 3] + else: + cx = cen[i, 0] + return np.array([cx, y + h, w, h, area]) + + def rotation(self, q): + """Compose the seven arm joint rotations in their physical axis order.""" + r = np.eye(3) + for ax, ang in zip('yxzyxyz', q): + r = r @ Rotation.from_euler(ax, ang).as_matrix() + return r + + def flip_target(self): + """Solve bounded wrist inverse kinematics for a half-turn while keeping the cup clear of the arm.""" + q = self.norm.copy() + target = Rotation.from_euler('x', np.pi).as_matrix() @ self.rotation(q) + q[0] -= 0.6 + q[2] = -2.6 + + def residual(v): + q[4:] = v + return Rotation.from_matrix(self.rotation(q).T @ target).as_rotvec() + sol = least_squares(residual, [0.8, 0.5, -0.4], bounds=([-1.97, -1.61, -1.61], [1.97, 1.61, 1.61])) + q[4:] = sol.x + return q.copy() + + def act(self, obs, tools): + """Advance the deterministic state machine by one control step.""" + a = self.a + self.age += 1 + t = obs['t'] + s = obs['low_dim_obs'] + if self.phase == 'walk': + x, y, z, yaw = s[21:25] + err = np.array([self.basex - x, self.basey - y]) + v = err * 2 + if np.linalg.norm(v) > 0.017: + v *= max(0.065, np.linalg.norm(v)) / np.linalg.norm(v) + else: + v *= 0 + a[:2] = [np.cos(yaw) * v[0] + np.sin(yaw) * v[1], -np.sin(yaw) * v[0] + np.cos(yaw) * v[1]] + a[3] = -3 * yaw + if self.age >= 180: + self.phase = 'reach' + self.age = 0 + a[:2] = 0 + a[3] = 0 + elif self.phase == 'reach': + if self.age % 5 == 0: + b = self.detect(tools.image('left_wrist')) + self.box = b + if b is not None: + cx, bot, w, h, area = b + self.missing = 0 + if self.roll < -0.5 and cx > 55 and (self.q > -0.6): + self.phase = 'sidestep' + self.age = 0 + self.sidegoal = s[22] - 0.16 + self.roll = np.clip(self.roll + (42 - cx) * 0.0008, -0.55, 0.75) + if abs(cx - 42) < 20: + self.height = np.clip(self.height + (55 - bot) * 0.0008, 0.45, 0.77) + if w >= 60 and abs(cx - 42) < 2.5 and (abs(bot - 55) < 8): + self.phase = 'close' + self.age = 0 + self.graspheight = self.height + elif w < 60 and abs(cx - 42) < 6 and (abs(bot - 55) < 7): + if self.q > -1.5: + self.q -= 0.018 + else: + self.pitch = min(0.65, self.pitch + 0.008) + else: + self.missing += 1 + self.height = min(0.77, self.height + 0.001) + if self.missing > 8: + self.angle = -0.55 + self.roll += self.searchdir * 0.012 + if self.roll < -0.5: + self.searchdir = 1 + if self.roll > 0.65: + self.searchdir = -1 + e = -0.8 + (self.q + 0.4) * (-0.8 / 1.1) + a[2] = self.height + a[4] = self.pitch + a[5:12] = [self.q, self.roll, 0, e, 0, self.angle - self.q - e - self.pitch, 0] + elif self.phase == 'sidestep': + a[2] = 0.74 + yaw = s[24] + dy = self.sidegoal - s[22] + v = np.sign(dy) * max(0.065, min(0.15, abs(dy) * 2)) if abs(dy) > 0.008 else 0.0 + a[0] = np.sin(yaw) * v + a[1] = np.cos(yaw) * v + a[3] = -3 * yaw + if self.age > 130: + a[:2] = 0 + a[3] = 0 + self.phase = 'reach' + self.age = 0 + self.roll = 0.15 + self.height = 0.74 + elif self.phase == 'close': + a[19] = 1.0 + if self.age > 70: + self.phase = 'lift' + self.age = 0 + self.ga = a.copy() + self.late = obs['t'] > 850 + target = Rotation.from_euler('y', a[4]).as_matrix() @ self.rotation(a[5:12]) + q = np.array([-1.46, 0.29, 0, -0.03, 0, 1.19, 0.0]) + + def residual(v): + q[4:] = v + return Rotation.from_matrix(self.rotation(q).T @ target).as_rotvec() + sol = least_squares(residual, [0, 1.19, 0], bounds=([-1.97, -1.61, -1.61], [1.97, 1.61, 1.61])) + q[4:] = sol.x + self.norm = q.copy() + self.ft = self.flip_target() + elif self.phase == 'lift': + a[2] = min(0.76, a[2] + 0.002) + f = np.clip((self.age - 60) / 100.0, 0, 1) + a[5:12] = self.ga[5:12] + (self.norm - self.ga[5:12]) * f + a[4] = self.ga[4] * (1 - f) + if self.age > 170: + self.phase = 'move' + self.age = 0 + elif self.phase == 'move': + x, y, z, yaw = s[21:25] + v = np.array([0.43 - x, -y]) * 2 + if np.linalg.norm(v) > 0.018: + v *= max(0.065, np.linalg.norm(v)) / np.linalg.norm(v) + else: + v *= 0 + a[:2] = [np.cos(yaw) * v[0] + np.sin(yaw) * v[1], -np.sin(yaw) * v[0] + np.cos(yaw) * v[1]] + a[3] = -3 * yaw + if self.age > 130: + self.phase = 'flip' + self.age = 0 + a[:2] = 0 + a[3] = 0 + elif self.phase == 'flip': + f = min(1.0, self.age / 220.0) + a[5:12] = self.norm + (self.ft - self.norm) * f + a[2] = 0.82 + if self.age > (240 if self.late else 270): + self.phase = 'lower' + self.age = 0 + elif self.phase == 'lower': + a[2] = max(0.76, a[2] - 0.001) + if self.age > (80 if self.late else 200): + self.phase = 'release' + self.age = 0 + elif self.phase == 'release': + a[19] = 0 + if self.age > 60: + self.phase = 'retreat' + self.age = 0 + elif self.phase == 'retreat': + a[2] = min(0.74, a[2] + 0.002) + a[4] = max(0.0, a[4] - 0.01) + target = np.array([-0.4, 0.15, 0, -0.8, 0, 0.9, 0]) + a[5:12] += np.clip(target - a[5:12], -0.02, 0.02) + return a.copy() diff --git a/policies/flip_cup/astra-s3/episodes.csv b/policies/flip_cup/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4065cd62cf619534c964dcd3366074401eccdc93 --- /dev/null +++ b/policies/flip_cup/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,1,1458,success,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,1,1472,success,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,1,1483,success,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,1,1313,success,0 +620014,1,1557,success,0 +620015,1,1306,success,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,1,1271,success,0 +620025,1,1277,success,0 +620026,0,1850,timeout,0 +620027,1,1492,success,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,1,1562,success,0 +620035,0,1850,timeout,0 +620036,1,1562,success,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,1,1262,success,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,1,1486,success,0 +620052,1,1462,success,0 +620053,1,1594,success,0 +620054,0,1850,timeout,0 +620055,1,1408,success,0 +620056,1,1562,success,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,1,1562,success,0 +620060,0,1850,timeout,0 +620061,1,1390,success,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,1,1052,success,0 +620066,1,1622,success,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,1,1422,success,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,1,1271,success,0 +620083,0,1850,timeout,0 +620084,1,1275,success,0 +620085,1,1563,success,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,1,1410,success,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,1,1275,success,0 diff --git a/policies/flip_cup/astra-s3/policy.py b/policies/flip_cup/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6d661d75feaf027be67250a0f75983b9c53057 --- /dev/null +++ b/policies/flip_cup/astra-s3/policy.py @@ -0,0 +1,176 @@ +"""Deterministic image-guided cup manipulation with analytic arm control.""" +import numpy as np +import cv2 +from scipy.spatial.transform import Rotation +from scipy.optimize import least_squares + +def rot(axis,a): + v=np.zeros(3);v[axis]=a + return Rotation.from_rotvec(v).as_matrix() +def fk(q): + sp,sr,sy,el,wr,wp,wy=q + m=rot(1,sp)@rot(0,sr)@rot(2,sy) + p=m@np.array([0,0,-.18]);m=m@rot(1,el);p+=m@np.array([0,0,-.18]) + m=m@rot(0,wr)@rot(1,wp)@rot(2,wy) + return p,m +LO=np.array([-3,-1.5,-2.6,-1.,-1.95,-1.6,-1.6]) +HI=np.array([2.6,2.2,2.6,2.05,1.95,1.6,1.6]) +def solve(p,m,q): + def residual(x): + a,b=fk(x) + return np.r_[(a-p)*10,Rotation.from_matrix(b.T@m).as_rotvec(),(x-q)*.002] + return least_squares(residual,np.clip(q,LO,HI),bounds=(LO,HI),max_nfev=100).x + +def detect(im,full=False): + hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV) + mask=((hsv[:,:,1]<45)&(hsv[:,:,2]>55)&(hsv[:,:,2]<235)).astype('uint8') + mask[79:]=0;mask[:,:3]=0;mask[:,81:]=0 + n,l,st,cent=cv2.connectedComponentsWithStats(mask) + cand=[] + for i in range(1,n): + x,y,w,h,area=st[i] + if area>25 and y<(79 if full else 60) and h>5 and w>3 and (area<2000 or full): + cand.append((area,i)) + if not cand:return None + _,i=max(cand) + return np.r_[cent[i],st[i,4]] if full else cent[i] + +class Controller: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=float) + self.a[19:21]=0 + self.q0=None + self.start=None + self.align_t=0 + self.good=0 + self.command=np.zeros(2) + self.last_feature=None + self.final_t=0 + self.final_good=0 + self.adjust_done=False + self.goal=None + self.settle_until=80 + self.move_until=80 + def act(self,obs,tools): + t=obs['t'];a=self.a + if self.start is None: + a[5:12]=[-.7,.32,0,-.5,0,.95,0] + pos=obs['low_dim_obs'][21:23];yaw=obs['low_dim_obs'][24] + a[3]=np.clip(-3*(yaw-.01),-.25,.25) if t>=80 else 0 + a[0:2]=0 + if self.goal is not None: + delta=self.goal-pos + if np.linalg.norm(delta)<.012 or t>=self.move_until: + self.goal=None;self.settle_until=t+65 + else: + v=delta*3 + speed=np.linalg.norm(v) + v*=np.clip(speed,.11,.2)/max(speed,1e-6) + c,sn=np.cos(yaw),np.sin(yaw) + a[0:2]=[c*v[0]+sn*v[1],-sn*v[0]+c*v[1]] + elif t>=self.settle_until: + f=detect(tools.image('left_wrist'));self.last_feature=f + if f is None:delta=np.array([0,-.12]) + else: + err=f-np.array([46.4,53.]) + delta=np.array([0,-err[0]*.0025]) + if abs(err[0])<8: + self.start=t;a[3]=0;return a.copy() + if abs(err[0])<4:delta[1]=0 + if abs(err[1])<5:delta[0]=0 + delta=np.clip(delta,-.12,.12) + self.goal=pos+delta + self.goal[0]=.164 + self.goal[0]=np.clip(self.goal[0],.09,.25) + self.goal[1]=np.clip(self.goal[1],-.65,.25) + self.move_until=t+100 + if t>=380: + self.start=t;a[0:2]=0;a[3]=0 + return a.copy() + t=t-self.start + if not hasattr(self,'pre_sr'): + ex=0 if self.last_feature is None else self.last_feature[0]-46.4 + self.pre_sr=.32-(np.clip(ex*.005,-.08,.08) if abs(ex)>8 else 0) + a[0:2]=0;a[3]=0 + if t>=320 and not self.adjust_done: + if self.final_t%20==0: + f=detect(tools.image('left_wrist'),True) + if f is not None: + ex,ey=f[:2]-[54.7,43.9] + a[6]-=np.clip(ex*.0007,-.015,.015) + a[10]+=np.clip(ey*.0018,-.035,.035) + if abs(ex)<8 and abs(ey)<8: + a[4]+=np.clip((1000-f[2])*.00003,-.012,.012) + a[6]=np.clip(a[6],-.3,.9);a[10]=np.clip(a[10],.4,1.35);a[4]=np.clip(a[4],.1,.55) + if abs(ex)<5 and abs(ey)<5 and abs(f[2]-1000)<250:self.final_good+=1 + else:self.final_good=0 + else: + a[10]=min(1.35,a[10]+.025) + if self.final_good>=2 or self.final_t>=260: + self.adjust_done=True + self.final_t+=1 + return a.copy() + if t>=320:t-=self.final_t + if t<90:a[5:12]=[-.7,self.pre_sr,0,-.5,0,1.2,0] + elif t<250: + k=(t-90)//40+1 + a[5:12]=[-.7-.15*k,self.pre_sr,0,-.5+.25*k,0,1.2-.1*k,0] + elif t<320: + cy=55 if self.last_feature is None else self.last_feature[1] + correction=np.clip(max(0,44-cy)*.02-max(0,cy-59)*.012,-.13,.13) + a[4]=.35+correction;a[10]=.9-correction + elif t<380:a[19]=1 + else: + if self.q0 is None: + self.q0=a[5:12].copy();self.p0,self.r0=fk(self.q0);self.q=self.q0.copy();self.grasp_pitch=a[4];self.place_extra=np.clip((.17-obs["low_dim_obs"][21])*1.5,0,.12) + if t<460: + p=self.p0+np.array([0,0,.12])*min(1,(t-379)/60) + self.q=solve(p,self.r0,self.q);a[5:12]=self.q + elif t<760: + angle=(t-459)*np.pi/300 + self.q=solve(self.p0+[0,0,.12],self.r0@rot(0,angle),self.q);a[5:12]=self.q + elif t<860: + u=(t-759)/100 + p=self.p0+np.array([.01*u*self.place_extra/.12,0,.12*(1-u)+.02*u*self.place_extra/.12]) + a[4]=self.grasp_pitch+self.place_extra*u + self.q=solve(p,self.r0@rot(0,np.pi),self.q);a[5:12]=self.q + else: + a[19]=0 + if t>940: + u=min(1,(t-940)/80) + p=self.p0+np.array([-.08*u,0,.03*u]) + self.q=solve(p,self.r0@rot(0,np.pi),self.q);a[5:12]=self.q + return a.copy() + + +SIGNS=np.array([1,-1,-1,1,-1,1,-1]) +def mirror_action(a): + b=np.asarray(a,dtype=float).copy() + b[1]*=-1;b[3]*=-1 + b[5:12]=np.asarray(a[12:19])*SIGNS + b[12:19]=np.asarray(a[5:12])*SIGNS + b[19]=a[20];b[20]=a[19] + return b +class MirrorTools: + def __init__(self,tools):self.tools=tools + def hold_action(self):return mirror_action(self.tools.hold_action()) + def image(self,camera): + camera={'left_wrist':'right_wrist','right_wrist':'left_wrist'}.get(camera,camera) + return self.tools.image(camera)[:,::-1].copy() +class Policy: + def reset(self,obs,tools): + h=cv2.cvtColor(tools.image('head'),cv2.COLOR_RGB2HSV) + mask=((h[:,:,1]<45)&(h[:,:,2]>30)&(h[:,:,2]<220)).astype('uint8');mask[12:]=0 + n,l,st,cent=cv2.connectedComponentsWithStats(mask) + self.mirror=False + if n>1: + i=1+np.argmax(st[1:,4]);self.mirror=cent[i,0]>42 + self.core=Controller();self.core.reset(self.observation(obs),self.tool(tools)) + def observation(self,obs): + if not self.mirror:return obs + o=obs.copy();v=obs['low_dim_obs'].copy();v[22]*=-1;v[24]*=-1;o['low_dim_obs']=v + return o + def tool(self,tools):return MirrorTools(tools) if self.mirror else tools + def act(self,obs,tools): + a=self.core.act(self.observation(obs),self.tool(tools)) + return mirror_action(a) if self.mirror else a diff --git a/policies/flip_cup/deepseek1017-s1/episodes.csv b/policies/flip_cup/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/deepseek1017-s1/policy.py b/policies/flip_cup/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9db80a78d08eb5a4eace2f69a5c464fa5aa2f1e9 --- /dev/null +++ b/policies/flip_cup/deepseek1017-s1/policy.py @@ -0,0 +1,220 @@ +"""Control policy for the "flip cup" task on the simulated Unitree G1. + +The robot starts in front of a counter. The target cup is upside down on the +counter top in front of the robot and is visible in the wrist cameras. The +policy is a deterministic scripted motion: + + 1. step forward to the counter, + 2. stand tall and raise the left arm so that the wrist camera looks down at + the cup, + 3. reach over the cup, close the gripper and lift it, + 4. rotate the wrist/elbow so that the cup is turned right way up, + 5. lower the arm again, open the gripper and back away. + +The arm targets are absolute joint angles; the policy only writes the joints it +needs and leaves the rest at the values reported by tools.hold_action(). +""" + +import numpy as np + + +def _lerp(a, b, t): + """Linear interpolation between two scalars with t clamped to [0, 1].""" + t = min(1.0, max(0.0, t)) + return a + (b - a) * t + + +def _ramp(t, t0, t1): + """Return a 0..1 interpolation parameter over the interval [t0, t1].""" + if t1 <= t0: + return 1.0 + return min(1.0, max(0.0, (t - t0) / float(t1 - t0))) + + +class Policy: + """Scripted pick, flip and place behaviour for the upside-down cup.""" + + # ── phase boundaries (control steps, 50 Hz) ──────────────────────────── + T_WALK_END = 40 + T_RPREP_END = 66 + T_LPREP_END = 92 + T_REACH_END = 116 + T_STRAFE_END = 136 + T_CLOSE_END = 178 + T_LIFT_END = 226 + T_FLIP_END = 276 + T_LOWER_END = 316 + T_OPEN_END = 348 + T_RETREAT_END = 420 + + # ── joint targets ────────────────────────────────────────────────────── + SP_TALL = 0.20 + EL_TALL = 0.00 + WP_TALL = -1.20 + SP_REACH = 0.40 + EL_REACH = 0.35 + SP_LIFT = 0.80 + EL_LIFT = 0.60 + WP_FLIP = 1.54 # wrist pitch after the 180 degree turn + SP_LOWER = 0.20 + EL_LOWER = 0.90 + + def reset(self, obs, tools): + """Prepare for one episode.""" + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + + def act(self, obs, tools): + """Return the 21-float action for the current control step.""" + t = int(obs.get("t", 0)) + h = np.asarray(tools.hold_action(), dtype=np.float32).copy() + + # Start from the current targets but never let the base drift. + a = h + a[0] = 0.0 + a[1] = 0.0 + a[3] = 0.0 + + # The left arm is the manipulating arm; keep the right arm neutral. + a[12:19] = self.hold[12:19] if hasattr(self, "hold") else a[12:19] + a[20] = 0.0 + + if t < self.T_WALK_END: + # Walk up to the counter. The base controller stops on contact. + a[0] = 0.30 + a[2] = 0.75 + a[4] = 0.0 + a[5:12] = self.hold[5:12] + a[19] = 0.0 + return a + + # From here on stand tall: this lifts the shoulders and puts the + # wrist cameras above the counter top. + a[2] = 1.0 + a[4] = 0.0 + a[19] = 0.0 + + if t < self.T_RPREP_END: + # Give the whole-body controller time to settle in the tall pose. + a[5] = self.SP_TALL + a[6] = 0.0 + a[7] = 0.0 + a[8] = self.EL_TALL + a[9] = 0.0 + a[10] = self.WP_TALL + a[11] = 0.0 + return a + + if t < self.T_LPREP_END: + # Raise the left arm to the observation pose over the counter. + a[5] = self.SP_TALL + a[6] = 0.0 + a[7] = 0.0 + a[8] = self.EL_TALL + a[9] = 0.0 + a[10] = self.WP_TALL + a[11] = 0.0 + return a + + if t < self.T_REACH_END: + # Reach forward over the counter until the cup is between the + # fingers (the wrist camera shows the cup centred here). + u = _ramp(t, self.T_LPREP_END, self.T_REACH_END) + a[5] = _lerp(self.SP_TALL, self.SP_REACH, u) + a[6] = 0.0 + a[7] = 0.0 + a[8] = _lerp(self.EL_TALL, self.EL_REACH, u) + a[9] = 0.0 + a[10] = self.WP_TALL + a[11] = 0.0 + return a + + if t < self.T_STRAFE_END: + # Small sideways step that slides the cup deeper into the gripper. + a[5] = self.SP_REACH + a[6] = 0.0 + a[7] = 0.0 + a[8] = self.EL_REACH + a[9] = 0.0 + a[10] = self.WP_TALL + a[11] = 0.0 + a[1] = 0.30 + return a + + if t < self.T_CLOSE_END: + # Close the gripper on the cup. + a[5] = self.SP_REACH + a[6] = 0.0 + a[7] = 0.0 + a[8] = self.EL_REACH + a[9] = 0.0 + a[10] = self.WP_TALL + a[11] = 0.0 + a[19] = 1.0 + return a + + if t < self.T_LIFT_END: + # Lift the cup clear of the counter. + u = _ramp(t, self.T_CLOSE_END, self.T_LIFT_END) + a[5] = _lerp(self.SP_REACH, self.SP_LIFT, u) + a[6] = 0.0 + a[7] = 0.0 + a[8] = _lerp(self.EL_REACH, self.EL_LIFT, u) + a[9] = 0.0 + a[10] = self.WP_TALL + a[11] = 0.0 + a[19] = 1.0 + return a + + if t < self.T_FLIP_END: + # Rotate the cup 180 degrees about the (horizontal) wrist pitch + # axis. The sum shoulder_pitch + elbow + wrist_pitch changes by + # ~pi, which turns the upside-down cup right way up. + u = _ramp(t, self.T_LIFT_END, self.T_FLIP_END) + a[5] = self.SP_LIFT + a[6] = 0.0 + a[7] = 0.0 + a[8] = _lerp(self.EL_LIFT, self.EL_REACH, u) + a[9] = 0.0 + a[10] = _lerp(self.WP_TALL, self.WP_FLIP, u) + a[11] = 0.0 + a[19] = 1.0 + return a + + if t < self.T_LOWER_END: + # Lower the flipped cup towards the counter while keeping the + # joint-angle sum constant (so the cup stays upright). + u = _ramp(t, self.T_FLIP_END, self.T_LOWER_END) + a[5] = _lerp(self.SP_LIFT, self.SP_LOWER, u) + a[6] = 0.0 + a[7] = 0.0 + a[8] = _lerp(self.EL_REACH, self.EL_LOWER, u) + a[9] = 0.0 + a[10] = self.WP_FLIP + a[11] = 0.0 + a[19] = 1.0 + return a + + if t < self.T_OPEN_END: + # Gently release the cup. + u = _ramp(t, self.T_LOWER_END, self.T_OPEN_END) + a[5] = self.SP_LOWER + a[6] = 0.0 + a[7] = 0.0 + a[8] = self.EL_LOWER + a[9] = 0.0 + a[10] = self.WP_FLIP + a[11] = 0.0 + a[19] = _lerp(1.0, 0.0, u) + return a + + # Retreat from the cup and settle so that the task condition can hold. + u = _ramp(t, self.T_OPEN_END, self.T_RETREAT_END) + a[5] = _lerp(self.SP_LOWER, 0.20, u) + a[6] = 0.0 + a[7] = 0.0 + a[8] = _lerp(self.EL_LOWER, 0.20, u) + a[9] = 0.0 + a[10] = _lerp(self.WP_FLIP, -0.50, u) + a[11] = 0.0 + a[19] = 0.0 + return a diff --git a/policies/flip_cup/deepseek1017-s2/episodes.csv b/policies/flip_cup/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/deepseek1017-s2/policy.py b/policies/flip_cup/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3d93ba3f4b94a0a09813a6862a1a50e82bfcf2e7 --- /dev/null +++ b/policies/flip_cup/deepseek1017-s2/policy.py @@ -0,0 +1,289 @@ +"""Hand-written control policy for turning an upside-down cup right way up. + +Observation model +----------------- +The robot's own head camera is the only view of the scene. The cup is the +dark, colour-neutral blob standing on the brightly lit work surface in the +upper part of the head view (it sits right at the boundary between the lit +surface and the checkered cloth). Its image position tells which arm is on +the cup's side. + +Control +------- + 1. find the cup in the head image and choose the arm on its side, + 2. yaw the base so the cup lines up with that arm, + 3. walk a fixed list of grasp postures with that arm; each attempt is + raise clear of the surface -> lean/settle -> close -> lift -> roll the + wrist over -> set down -> release, + 4. re-aim the base to a second lateral offset and repeat the list, + 5. finish in a compact stance. + +The whole thing is deterministic (no clocks, no random numbers) and never +commands anything outside the documented joint/velocity ranges. +""" + +import numpy as np + +# ---------------------------------------------------------------- cup finder + + +def _detect_cup(rgb): + """Locate the cup in a head-camera image (never raises).""" + try: + return _detect_cup_inner(rgb) + except Exception: + return None + + +def _detect_cup_inner(rgb): + """Locate the cup in a head-camera image. + + Returns (cx, cy, w, h) of the largest dark neutral blob in the upper part + of the image, or None. + """ + im = np.asarray(rgb).astype(np.float32) + h, w, _ = im.shape + r, g, b = im[:, :, 0], im[:, :, 1], im[:, :, 2] + rb = np.abs(r - b) + val = im.mean(2) + neutral = (rb < 24) & (val < 205) & (val > 40) + mask = np.zeros((h, w), np.uint8) + ylim = int(h * 0.62) + mask[:ylim] = neutral[:ylim] + # 4-neighbour erosion to drop single-pixel speckle + m = mask.astype(np.float32) + m2 = m.copy() + m2[1:, :] *= m[:-1, :] + m2[:-1, :] *= m[1:, :] + m2[:, 1:] *= m[:, :-1] + m2[:, :-1] *= m[:, 1:] + mask = (m2 > 0.5).astype(np.uint8) + best = None + seen = np.zeros_like(mask) + ys, xs = np.where(mask > 0) + for y0, x0 in zip(ys, xs): + if seen[y0, x0]: + continue + stack = [(y0, x0)] + seen[y0, x0] = 1 + pts = [] + while stack: + y, x = stack.pop() + pts.append((y, x)) + for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)): + yy, xx = y + dy, x + dx + if 0 <= yy < h and 0 <= xx < w and mask[yy, xx] and not seen[yy, xx]: + seen[yy, xx] = 1 + stack.append((yy, xx)) + n = len(pts) + if n < 16: + continue + py = np.array([p[0] for p in pts]) + px = np.array([p[1] for p in pts]) + bw = px.max() - px.min() + 1 + bh = py.max() - py.min() + 1 + if bw > 42 or bh > 42: + continue + if best is None or n > best[0]: + best = (n, float(px.mean()), float(py.mean()), int(bw), int(bh)) + if best is None: + return None + return best[1:] + + +# Grasp postures: (torso_pitch, shoulder_pitch, shoulder_roll, elbow, +# wrist_pitch, wrist_roll) +# The first group reaches for a cup that is close to the chest (the arm is +# folded, which is where the wrist camera actually sees the surface holding +# the cup); the later ones sweep progressively farther and higher. +_ATTEMPTS = [ + (0.00, 0.60, 0.00, 1.90, -1.20, 0.00), + (0.00, 0.72, 0.00, 1.95, -1.20, 1.50), + (0.00, 0.60, 0.00, 1.90, -1.20, -1.50), + (0.00, 0.70, 0.00, 1.70, -0.80, 0.00), + (0.00, 0.52, 0.00, 1.60, -0.90, 0.00), + (0.30, 1.30, -0.20, 0.10, 0.00, 0.00), + (0.65, 0.35, -0.30, 1.10, -1.00, 0.00), + (0.00, 1.10, 0.00, 0.20, 0.00, 0.00), +] + +# lateral base offsets (cup image column targets) tried in turn +_AIM_TARGETS_R = [30.0, 48.0] +_AIM_TARGETS_L = [54.0, 36.0] + + +class Policy: + """Deterministic scripted cup-flipping policy.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), np.float32) + self.height = float(self.hold[2]) + self.pitch = float(self.hold[4]) + self.left = np.array(self.hold[5:12], np.float32) + self.right = np.array(self.hold[12:19], np.float32) + self.grip_l = float(self.hold[19]) + self.grip_r = float(self.hold[20]) + self.cup = None + self.arm = "R" + self.pass_i = 0 + self.targets = _AIM_TARGETS_R + self.target_cx = self.targets[0] + self.phase = "settle" + self.phase_t = 0 + self.att = 0 + self.sub = 0 + + # -- helpers ----------------------------------------------------- + def _action(self, vx=0.0, vy=0.0, wz=0.0): + raw = self.hold.copy() + raw[0] = vx + raw[1] = vy + raw[2] = self.height + raw[3] = wz + raw[4] = self.pitch + raw[5:12] = self.left + raw[12:19] = self.right + raw[19] = self.grip_l + raw[20] = self.grip_r + return raw + + def _set_arm(self, sp, roll, el, wp, wr): + tgt = np.array([sp, roll, 0.0, el, wr, wp, 0.0], np.float32) + if self.arm == "R": + self.right = tgt + else: + self.left = tgt + + def _grip(self, closed): + v = 1.0 if closed else 0.0 + if self.arm == "R": + self.grip_r = v + else: + self.grip_l = v + + def _next_sub(self): + self.sub += 1 + self.phase_t = 0 + + # -- main loop --------------------------------------------------- + def act(self, obs, tools): + self.phase_t += 1 + + if self.phase == "settle": + if self.phase_t == 1: + self.cup = _detect_cup(tools.image("head")) + cx = self.cup[0] if self.cup is not None else 14.0 + if cx > 44.0: + self.arm = "L" + self.targets = _AIM_TARGETS_L + else: + self.arm = "R" + self.targets = _AIM_TARGETS_R + self.target_cx = self.targets[0] + if self.phase_t >= 5: + self.phase = "aim" + self.phase_t = 0 + return self._action() + + if self.phase == "aim": + if self.phase_t % 2 == 1: + self.cup = _detect_cup(tools.image("head")) + wz = 0.0 + if self.cup is not None: + err = self.cup[0] - self.target_cx + if abs(err) > 5.0 and self.phase_t < 26: + wz = float(np.clip(-0.035 * err, -0.45, 0.45)) + else: + self.phase = "grasp" + self.phase_t = 0 + self.sub = 0 + else: + wz = -0.18 if self.arm == "R" else 0.18 + if self.phase_t >= 26: + self.phase = "grasp" + self.phase_t = 0 + self.sub = 0 + return self._action(wz=wz) + + if self.phase == "grasp": + return self._grasp() + + return self._action() + + def _grasp(self): + pitch, sp, roll, el, wp, wr = _ATTEMPTS[self.att % len(_ATTEMPTS)] + # alternate the roll sign between passes over the list + if (self.att // len(_ATTEMPTS)) % 2 == 1: + roll = -roll + wp = wp - 0.25 + rp = roll + + if self.sub == 0: # raise the arm clear of the work surface + self.pitch = 0.0 + self._set_arm(sp, rp, el, wp, wr) + self._grip(False) + if self.phase_t >= 9: + self._next_sub() + return self._action() + + if self.sub == 1: # lean in / settle on the target posture + self.pitch = pitch + if self.phase_t >= 11: + self._next_sub() + return self._action() + + if self.sub == 2: # settle + if self.phase_t >= 4: + self._next_sub() + return self._action() + + if self.sub == 3: # close the gripper + self._grip(True) + if self.phase_t >= 11: + self._next_sub() + return self._action() + + if self.sub == 4: # lift + self.pitch = max(pitch - 0.20, 0.0) + self._set_arm(min(sp + 0.40, 2.5), rp * 0.7, + max(el - 0.55, 0.0), wp * 0.4, wr) + if self.phase_t >= 12: + self._next_sub() + return self._action() + + if self.sub == 5: # roll the wrist over to turn the cup upright + wrist = 1.6 if (self.att % 2 == 0) else -1.6 + self._set_arm(min(sp + 0.40, 2.5), rp * 0.7, + max(el - 0.55, 0.0), wrist, wr) + if self.phase_t >= 14: + self._next_sub() + return self._action() + + if self.sub == 6: # set it back down + self.pitch = pitch + self._set_arm(sp, rp, el, 1.6 if (self.att % 2 == 0) else -1.6, wr) + if self.phase_t >= 12: + self._next_sub() + return self._action() + + if self.sub == 7: # release, straighten up + self._grip(False) + if self.phase_t >= 8: + self.pitch = 0.0 + if self.phase_t >= 14: + self.att += 1 + self.sub = 0 + self.phase_t = 0 + if self.att >= len(_ATTEMPTS): + self.att = 0 + self.pass_i += 1 + if self.pass_i >= len(self.targets): + self.phase = "done" + else: + self.target_cx = self.targets[self.pass_i] + self.phase = "aim" + self.phase_t = 0 + return self._action() + + self.phase = "done" + return self._action() diff --git a/policies/flip_cup/deepseek1017-s3/episodes.csv b/policies/flip_cup/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/deepseek1017-s3/policy.py b/policies/flip_cup/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3755371e53e0f8f0d91e68f04b19b7874a64a35e --- /dev/null +++ b/policies/flip_cup/deepseek1017-s3/policy.py @@ -0,0 +1,364 @@ +"""Control policy for the ``flip_cup`` task. + +The policy is pure hand-written control logic (no learned components). It +uses the robot's own head camera to find the mug (a neutral-grey body sitting +on a bright yellow coaster), walks to the side of the counter where the mug +sits, and then runs a short sequence of arm/gripper poses that reach for the +mug, close the gripper, lift, rotate the wrist to turn the mug over and set it +back down. + +Everything is deterministic. No wall-clock time and no unseeded randomness +are used. +""" + +import cv2 +import numpy as np + + +# --------------------------------------------------------------------------- +# small image utilities +# --------------------------------------------------------------------------- + +def _cup_blobs(image): + """Return candidate mug blobs in a head image, largest first. + + The mug is a light neutral-grey object. The cream counter and the blue + floor are strongly coloured, so a low-saturation bright blob near the top + of the image is a good mug candidate. Each entry is ``(area, x, y, w, h)``. + """ + rgb = image.astype(np.int16) + hi = rgb.max(axis=2) + lo = rgb.min(axis=2) + neutral = ((hi - lo) < 26) & (rgb[:, :, 1] > 105) & (rgb[:, :, 1] < 246) + mask = cv2.morphologyEx( + neutral.astype(np.uint8), cv2.MORPH_OPEN, np.ones((2, 2), np.uint8) + ) + # The mug lives on the counter edge, i.e. near the top of the head view. + mask[34:, :] = 0 + n, _labels, stats, _cent = cv2.connectedComponentsWithStats(mask, 8) + out = [] + for i in range(1, n): + x, y, w, h, area = stats[i] + if area >= 9: + out.append((int(area), int(x), int(y), int(w), int(h))) + out.sort(reverse=True) + return out + + +def _coaster_centroid(image): + """Centroid of the bright-yellow coaster under the mug, or ``None``.""" + r = image[:, :, 0].astype(np.int16) + g = image[:, :, 1].astype(np.int16) + b = image[:, :, 2].astype(np.int16) + mask = ( + (r > 190) & (g > 160) & (b < 215) & ((r - b) > 35) & ((g - b) > 20) + ).astype(np.uint8) + mask[32:, :] = 0 + mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8)) + ys, xs = np.where(mask > 0) + if len(xs) < 6: + return None + return float(xs.mean()), float(ys.mean()), int(len(xs)) + + +def _find_mug(image): + """Best guess of the mug position in a head image or ``None``.""" + blobs = _cup_blobs(image) + if blobs: + area, x, y, w, h = blobs[0] + if area <= 420 and w <= 30 and h <= 30: + return float(x + w * 0.5), float(y + h * 0.5), float(area), "blob" + coaster = _coaster_centroid(image) + if coaster is not None: + cx, cy, area = coaster + return cx, max(0.0, cy - 4.0), float(area), "coaster" + return None + + +# --------------------------------------------------------------------------- +# policy +# --------------------------------------------------------------------------- + +class Policy: + """Deterministic scripted policy for turning the mug the right way up.""" + + def reset(self, obs, tools): + """Prepare a new episode.""" + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.phase = "settle" + self.phase_t = 0 + self.side = "L" # side of the head image the mug starts on + self.arm = "A" # "A": action slice 5..11, "B": slice 12..18 + self.start_mug = None + self._poses = [] + self._attempt = 0 + self._grasped = False + self._mug_before = None + self._sr0 = -0.6 + self._sy0 = 0.2 + + # -- helpers ---------------------------------------------------------- + def _look_action(self): + action = self.hold.copy() + action[4] = -0.2 # lean back a little: the mug is high + action[2] = 0.80 + return action + + def _set_arm(self, action, arm, sp, el, sr, sy, wp=0.0, wr=0.0, grip=None): + """Write an arm pose (and optionally a gripper command) into action.""" + base = 5 if arm == "A" else 12 + grip_idx = 19 if arm == "A" else 20 + action[base + 0] = sp + action[base + 1] = sr + action[base + 2] = sy + action[base + 3] = el + action[base + 4] = wr + action[base + 5] = wp + action[base + 6] = 0.0 + if grip is not None: + action[grip_idx] = grip + + def _mug_visible(self, image): + return _find_mug(image) + + # -- main control loop ------------------------------------------------- + def act(self, obs, tools): + """Return the 21-float physical action for the current step.""" + self.t += 1 + self.phase_t += 1 + + if obs.get("fell", False): + return self.hold.astype(np.float32) + + # ---- settle and locate the mug --------------------------------- + if self.phase == "settle": + action = self._look_action() + if self.phase_t >= 12: + mug = self._mug_visible(np.asarray(tools.image("head"))) + if mug is not None: + self.start_mug = mug + self.side = "L" if mug[0] < 42.0 else "R" + # After strafing towards the mug it crosses the image, so + # the arm that ends up next to it is the opposite one. + self.arm = "A" if self.side == "L" else "B" + self.phase = "strafe" + self.phase_t = 0 + return action.astype(np.float32) + + # ---- strafe to the mug's side of the counter -------------------- + if self.phase == "strafe": + action = self._look_action() + direction = 1.0 if self.side == "L" else -1.0 + target = 72.0 if self.side == "L" else 12.0 + if self.phase_t % 4 == 0: + mug = self._mug_visible(np.asarray(tools.image("head"))) + if mug is not None: + self.start_mug = mug + err = target - mug[0] + if abs(err) <= 5.0: + self.phase = "walk" + self.phase_t = 0 + return action.astype(np.float32) + action[1] = direction * (0.30 if abs(err) > 8.0 else 0.12) + else: + action[1] = direction * 0.22 + else: + action[1] = direction * 0.22 + if self.phase_t > 150: + self.phase = "walk" + self.phase_t = 0 + return action.astype(np.float32) + + # ---- walk up to the counter ------------------------------------- + if self.phase == "walk": + action = self.hold.copy() + action[0] = 0.35 + action[2] = 1.0 + action[4] = 0.55 + if self.phase_t >= 55: + self.phase = "look_again" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "look_again": + action = self._look_action() + if self.phase_t >= 16: + self._poses = self._grasp_poses() + self._attempt = 0 + self.phase = "reach" + self.phase_t = 0 + return action.astype(np.float32) + + # ---- reach / close / lift, several poses -------------------------- + if self.phase == "reach": + if self.phase_t == 1: + self._mug_before = self._mug_visible( + np.asarray(tools.image("head")) + ) + sp, el, sr, sy, wp = self._poses[self._attempt] + action = self._look_action() + self._set_arm(action, self.arm, sp, el, sr, sy, wp=wp, grip=0.0) + if self.phase_t >= 22: + self.phase = "close" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "close": + sp, el, sr, sy, wp = self._poses[self._attempt] + action = self._look_action() + self._set_arm(action, self.arm, sp, el, sr, sy, wp=wp, grip=1.0) + if self.phase_t >= 22: + self.phase = "lift" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "lift": + sp, el, sr, sy, wp = self._poses[self._attempt] + action = self._look_action() + self._set_arm( + action, + self.arm, + min(2.4, sp + 0.45), + min(1.8, el + 0.25), + sr, + sy, + wp=wp, + grip=1.0, + ) + if self.phase_t >= 26: + after = self._mug_visible(np.asarray(tools.image("head"))) + if self._mug_before is not None and after is None: + self._grasped = True + self.phase = "flip_ready" + self.phase_t = 0 + else: + self.phase = "release" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "release": + sp, el, sr, sy, wp = self._poses[self._attempt] + action = self._look_action() + self._set_arm(action, self.arm, sp, el, sr, sy, wp=wp, grip=0.0) + if self.phase_t >= 18: + self.phase = "back_off" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "back_off": + action = self._look_action() + if self.phase_t >= 16: + self._attempt += 1 + if self._attempt >= len(self._poses): + self.phase = "shove" + self.phase_t = 0 + else: + self.phase = "reach" + self.phase_t = 0 + return action.astype(np.float32) + + # ---- last resort: a broad sweep can tip the mug over --------------- + if self.phase == "shove": + t = min(1.0, self.phase_t / 60.0) + if self.arm == "A": + sp, el, sy, wp, wr = 1.9, 0.9, -0.2, 1.5, 0.0 + sp1, sy1, wr1 = 2.5, -1.5, 1.5 + else: + sp, el, sy, wp, wr = 1.9, 0.9, 0.2, -1.5, 0.0 + sp1, sy1, wr1 = 2.5, 1.5, -1.5 + action = self._look_action() + self._set_arm( + action, self.arm, + sp + (sp1 - sp) * t, + el, + self._sr0, + sy + (sy1 - sy) * t, + wp=wp, wr=wr + (wr1 - wr) * t, + ) + if self.phase_t >= 60: + self.phase = "shove_hold" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "shove_hold": + action = self._look_action() + if self.arm == "A": + self._set_arm(action, self.arm, 2.6, 1.5, self._sr0, -1.5, + wp=1.5, wr=1.5) + else: + self._set_arm(action, self.arm, 2.6, 1.5, self._sr0, 1.5, + wp=-1.5, wr=-1.5) + if self.phase_t >= 160: + self.phase = "done" + self.phase_t = 0 + return action.astype(np.float32) + + # ---- the mug is held: flip it and set it down --------------------- + if self.phase == "flip_ready": + action = self._look_action() + self._set_arm( + action, self.arm, 1.2, 0.8, self._sr0, self._sy0, + wp=0.0, grip=1.0, + ) + if self.phase_t >= 22: + self.phase = "flip" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "flip": + action = self._look_action() + self._set_arm( + action, self.arm, 1.2, 0.8, self._sr0, self._sy0, + wp=1.5, grip=1.0, + ) + if self.phase_t >= 30: + self.phase = "place" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "place": + action = self._look_action() + self._set_arm( + action, self.arm, 0.35, 0.2, self._sr0, self._sy0, + wp=1.5, grip=1.0, + ) + if self.phase_t >= 28: + self.phase = "open" + self.phase_t = 0 + return action.astype(np.float32) + + if self.phase == "open": + action = self._look_action() + self._set_arm( + action, self.arm, 0.35, 0.2, self._sr0, self._sy0, + wp=1.5, grip=0.0, + ) + if self.phase_t >= 18: + self.phase = "final" + self.phase_t = 0 + return action.astype(np.float32) + + # ---- stand still -------------------------------------------------- + return self._look_action().astype(np.float32) + + # -- pose library ------------------------------------------------------ + def _grasp_poses(self): + """Reach poses for the arm that ends up next to the mug. + + Each pose is ``(shoulder_pitch, elbow, shoulder_roll, shoulder_yaw, + wrist_pitch)``. The arm reaches up over the counter edge where the + mug sits; the wrist pitch aims the palm at the mug. + """ + if self.arm == "A": + self._sr0, self._sy0 = 0.6, -0.2 + sign = 1.0 + else: + self._sr0, self._sy0 = -0.6, 0.2 + sign = -1.0 + return [ + (1.4, 0.5, self._sr0, self._sy0, sign * 0.4), + (1.7, 0.6, self._sr0, self._sy0, sign * 0.6), + (2.0, 0.7, self._sr0, self._sy0, sign * 0.8), + (2.3, 0.8, self._sr0, self._sy0, sign * 1.0), + ] diff --git a/policies/flip_cup/gpt61sol-s1/episodes.csv b/policies/flip_cup/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..575ac691546c475d38d6462698c1e66ae56c0759 --- /dev/null +++ b/policies/flip_cup/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,1,1814,success,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,1,1815,success,0 +620008,0,1850,timeout,0 +620009,1,1721,success,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,1,1349,success,0 +620013,0,1850,timeout,0 +620014,1,1694,success,0 +620015,0,1850,timeout,0 +620016,1,1485,success,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,1,1727,success,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,1,1704,success,0 +620024,1,1210,success,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,1,1491,success,0 +620035,1,1712,success,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,1,1625,success,0 +620044,1,1450,success,0 +620045,1,1664,success,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,1,1668,success,0 +620055,0,1850,timeout,0 +620056,1,1373,success,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,1,1719,success,0 +620076,0,1850,timeout,0 +620077,1,1792,success,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,1,1546,success,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,1,1712,success,0 +620094,1,1802,success,0 +620095,0,1850,timeout,0 +620096,1,1350,success,0 +620097,0,1850,timeout,0 +620098,1,1433,success,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt61sol-s1/policy.py b/policies/flip_cup/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d2adb08183c2aa24d8323f70512241348934ca --- /dev/null +++ b/policies/flip_cup/gpt61sol-s1/policy.py @@ -0,0 +1,137 @@ +"""Hand-written visual alignment and a smooth cup-flipping sequence.""" +import numpy as np +import cv2 + +class Policy: + """Visual feedback for approach, followed by smooth deterministic motions.""" + + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float) + self.a[19:21] = 0 + self.initial = self.a.copy() + self.phase = 'raise' + self.tick = 0 + self.align_tick = 0 + self.goal = None + self.wait = 0 + self.stage = 0 + self.start = self.a.copy() + self.stages = [ + ([-0.5, 0.25, 0, 0, -0.8, 0, 0], 0, 80, 60), + ([-0.8, 0.25, 0, 0.6, -0.8, 0, 0], 0, 100, 60), + ([-0.8, 0.25, 0, 0.6, -0.8, 0, 0], 1, 80, 60), + ([-1.05, 0.25, 0, 0.35, -0.8, 0, 0], 1, 100, 60), + ([-1.05, 0.65, 0, 0.35, 1.95, 0, 0], 1, 180, 120), + ([-0.8, 0.65, 0, 0.6, 1.95, 0, 0], 1, 100, 60), + ([-0.8, 0.65, 0, 0.8, 1.95, 0, 0], 1, 100, 60), + ([-0.8, 0.65, 0, 0.8, 1.95, 0, 0], 0, 100, 60), + ([-1.05, 0.65, 0, 0.35, 1.95, 0, 0], 0, 100, 60), + ([-0.5, 0.25, 0, 0, 0, 0, 0], 0, 200, 60), + ] + + def cup(self, im, head=False): + im = im.astype(np.int16) + v = im.max(2) + mi = im.min(2) + mask = ((v - mi < 30) & (v > 75) & (v < 225) & (mi > 60)).astype(np.uint8) + if head: + mask[20:] = 0 + mask[:, :14] = 0 + mask[:, 77:] = 0 + else: + mask[78:] = 0 + n, l, stats, cen = cv2.connectedComponentsWithStats(mask) + valid = [i for i in range(1, n) if stats[i, 4] > (8 if head else 100)] + if not valid: + return None + i = max(valid, key=lambda j: stats[j, 4]) + return np.r_[stats[i, :4], cen[i]] + + def act(self, obs, tools): + ld = obs['low_dim_obs'] + self.tick += 1 + if self.phase == 'raise': + end = self.initial.copy() + end[5:12] = [-0.5, 0.25, 0, 0, 0, 0, 0] + self.a = self.initial + (end - self.initial) * min(1, self.tick / 60) + if self.tick >= 100: + self.phase = 'align' + self.tick = 0 + self.wait = 0 + return self.a + if self.phase == 'align': + self.a[0:2] = 0 + self.a[3] = 0 + self.align_tick += 1 + if self.goal is not None: + delta = self.goal - ld[21:23] + yaw = ld[24] + local = np.array([[np.cos(yaw), np.sin(yaw)], [-np.sin(yaw), np.cos(yaw)]]) @ delta + if np.linalg.norm(delta) < 0.004 or self.tick > 120: + self.goal = None + self.wait = 60 + self.tick = 0 + else: + self.a[0:2] = local / max(np.linalg.norm(local), 1e-06) * 0.09 + elif self.wait > 0: + self.wait -= 1 + else: + box = self.cup(tools.image('left_wrist')) + if box is not None and box[2] < 80: + x, y, w, h, cx, cy = box + dx = float(np.clip(0.004 * (59 - cy), -0.06, 0.06)) + dy = float(np.clip((40.4 - cx) * 0.003, -0.09, 0.09)) + if abs(dx) < 0.008 and abs(dy) < 0.008: + self.phase = 'motion' + self.tick = 0 + self.start = self.a.copy() + return self.a + else: + head = self.cup(tools.image('head'), True) + dx = 0 + dy = 0.06 if head is None else float(np.clip((31.0 - head[4]) * 0.007, -0.12, 0.12)) + yaw = ld[24] + world = np.array([[np.cos(yaw), -np.sin(yaw)], [np.sin(yaw), np.cos(yaw)]]) @ np.array([dx, dy]) + self.goal = ld[21:23].copy() + world + self.tick = 0 + if self.align_tick > 600: + self.phase = 'motion' + self.tick = 0 + self.a[0:2] = 0 + self.start = self.a.copy() + return self.a + if self.phase == 'carry': + self.a[0:2] = 0 + self.a[3] = float(np.clip(-ld[24], -0.15, 0.15)) + delta = self.transport_goal - ld[21:23] + predicted = delta - ld[46:48] * 0.35 + if self.tick < 145 and np.linalg.norm(predicted) > 0.014: + yaw = ld[24] + local = np.array([[np.cos(yaw), np.sin(yaw)], [-np.sin(yaw), np.cos(yaw)]]) @ predicted + self.a[0:2] = local / np.linalg.norm(local) * 0.075 + if self.tick >= 205: + self.phase = 'motion' + self.tick = 0 + self.a[0:2] = 0 + self.a[3] = 0 + self.start = self.a.copy() + return self.a + if self.stage >= len(self.stages): + return self.a + p, g, n, ramp = self.stages[self.stage] + end = self.start.copy() + end[0:2] = 0 + end[3] = 0 + end[5:12] = p + end[19] = g + end[2] = 0.7 if 5 <= self.stage <= 7 else 0.74 + f = min(1, self.tick / ramp) + self.a = self.start + (end - self.start) * f + if self.tick >= n: + self.stage += 1 + self.tick = 0 + self.start = self.a.copy() + if self.stage == 4: + self.phase = 'carry' + self.transport_goal = np.array([0.24, float(ld[22])]) + return self.a diff --git a/policies/flip_cup/gpt61sol-s2/episodes.csv b/policies/flip_cup/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f2b9b676583112d1510158e16ec422c242acd80d --- /dev/null +++ b/policies/flip_cup/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,1,1385,success,0 +620002,0,1850,timeout,0 +620003,1,1231,success,0 +620004,1,1494,success,0 +620005,1,1255,success,0 +620006,1,1386,success,0 +620007,1,1193,success,0 +620008,1,1269,success,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,1,1403,success,0 +620012,1,1350,success,0 +620013,1,1236,success,0 +620014,0,1850,timeout,0 +620015,1,1267,success,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,1,1682,success,0 +620022,1,1276,success,0 +620023,0,1850,timeout,0 +620024,1,1248,success,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,1,1378,success,0 +620028,0,1850,timeout,0 +620029,1,1224,success,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,1,1183,success,0 +620034,0,1850,timeout,0 +620035,1,1447,success,0 +620036,1,1203,success,0 +620037,1,1436,success,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,1,1261,success,0 +620044,1,1393,success,0 +620045,1,1430,success,0 +620046,1,1203,success,0 +620047,0,1850,timeout,0 +620048,1,1250,success,0 +620049,0,1850,timeout,0 +620050,1,1191,success,0 +620051,1,1246,success,0 +620052,0,1850,timeout,0 +620053,1,1360,success,0 +620054,1,1294,success,0 +620055,1,1244,success,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,1,1421,success,0 +620060,1,1471,success,0 +620061,1,1414,success,0 +620062,1,1334,success,0 +620063,1,1303,success,0 +620064,1,1295,success,0 +620065,1,1215,success,0 +620066,1,1198,success,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,1,1388,success,0 +620071,1,1253,success,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,1,1231,success,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,1,1389,success,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,1,1518,success,0 +620083,0,1850,timeout,0 +620084,1,1387,success,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,1,1326,success,0 +620088,1,1239,success,0 +620089,0,1850,timeout,0 +620090,1,1537,success,0 +620091,0,1850,timeout,0 +620092,1,1206,success,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,1,1259,success,0 +620096,1,1370,success,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,1,1260,success,0 diff --git a/policies/flip_cup/gpt61sol-s2/policy.py b/policies/flip_cup/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..772dd7ea770aa50bf7b994cf4cfb2b4ea72c716e --- /dev/null +++ b/policies/flip_cup/gpt61sol-s2/policy.py @@ -0,0 +1,100 @@ +"""Deterministic colour servo and phased cup manipulation.""" +import numpy as np +import cv2 + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=float) + self.a[19]=0 + self.a[5:12]=[-.85,.28,0,0,0,.85,0] + self.phase='settle';self.start=0;self.retries=0 + # Choose the arm from the cup's visible silhouette on the table. + im=tools.image('head').astype(np.int16) + m=((im.max(2)-im.min(2)<35)&(im.mean(2)>25)&(im.mean(2)<225)).astype(np.uint8) + m[10:]=0 + n,l,st,cs=cv2.connectedComponentsWithStats(m) + ids=[i for i in range(1,n) if st[i,4]>=2 and st[i,2]<22] + self.right=bool(ids and cs[max(ids,key=lambda i:st[i,4]),0]>42) + def detect(self,im): + f=im.astype(np.int16) + mask=((f.max(2)-f.min(2)<30)&(f.mean(2)>65)&(f.mean(2)<245)).astype(np.uint8) + mask[70:]=0 + n,l,st,cs=cv2.connectedComponentsWithStats(mask) + ids=[i for i in range(1,n) if st[i,4]>60 and cs[i,1]<60] + if not ids:return None + i=max(ids,key=lambda i:st[i,4]);return cs[i],st[i] + def enter(self,p,t):self.phase=p;self.start=t + def act(self,obs,tools): + t=obs['t'];q=obs['low_dim_obs'];a=self.a + age=t-self.start + if self.phase=='settle' and age>=80:self.enter('approach',t) + elif self.phase=='approach': + if age>150:a[4]=min(.4,a[4]+.002) + if t%10==0: + im=tools.image('right_wrist' if self.right else 'left_wrist') + if self.right:im=im[:,::-1] + z=self.detect(im) + if z: + c,b=z + a[6]+=np.clip((42-c[0])*.002,-.035,.035) + a[5]+=np.clip((c[1]-25)*.002,-.035,.035) + a[5]=np.clip(a[5],-1.2,-.35);a[6]=np.clip(a[6],-.12,.65) + a[10]=-a[5] + a[0]=.08 if b[4]<(1800+min(900,300*self.retries)) else 0 + a[3]=np.clip(-q[24]*2,-.3,.3) + if b[4]>(1800+min(900,300*self.retries)) and abs(c[0]-42)<8 and abs(c[1]-25)<10: + a[0]=a[3]=0;a[19]=1;self.enter('grasp',t) + else:a[0]=0 + elif self.phase=='grasp': + if age>=60: + if np.mean(q[19:21] if self.right else q[10:12])>-.018: + self.enter('lift',t) + else: + a[19]=0;self.retries+=1;a[4]=min(.4,a[4]+.08);self.enter('retry',t) + elif self.phase=='retry': + if age>=35:self.enter('approach',t) + elif self.phase=='lift': + a[4]=max(0,a[4]-.002) + a[2]=min(.78,a[2]+.001) + a[5]=max(-1.75,a[5]-.006) + a[10]=min(1.57,-a[5]) + if age>=250:self.enter('prepare',t) + elif self.phase=='prepare': + # Redistribute wrist rotation before turning around the extended arm. + if age<130: + a[9]=max(-1.57,a[9]-.013) + a[11]=-a[9] + else: + a[7]=max(-.55,a[7]-.010) + a[10]=1.57+a[7] + if age>=220:self.enter('flip',t) + elif self.phase=='flip': + a[7]=min(2.59,a[7]+.010) + if age>=340: + self.wref=(q[16:19]*[-1,1,-1] if self.right else q[7:10]).copy() + self.enter('lower',t) + elif self.phase=='lower': + # Wrist tracking error marks contact; stop descending and release. + a[5]=min(-1.57,a[5]+.004) + if age>50:a[2]=max(.50,a[2]-.001) + wrists=q[16:19]*[-1,1,-1] if self.right else q[7:10] + contact=(np.linalg.norm(wrists-self.wref)>.07 or np.linalg.norm(wrists-a[9:12])>.10) + if (age>50 and contact) or age>=270: + a[19]=0;self.enter('release',t) + elif self.phase=='release': + if age>=110:self.enter('withdraw',t) + elif self.phase=='withdraw': + if age<140: + a[2]=max(.4,a[2]-.001) + elif age<240: + a[6]=min(.7,a[6]+.004) + else: + a[2]=min(.74,a[2]+.0015) + out=a.copy() + out[5]-=a[4] + if self.right: + # Reflect the same controller for the right arm. + out[12:19]=out[5:12]*np.array([1,-1,-1,1,-1,1,-1]) + out[5:12]=0 + out[20]=out[19];out[19]=.6 + return out diff --git a/policies/flip_cup/gpt61sol-s3/episodes.csv b/policies/flip_cup/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4630ec7a9d6307464d77eb14cb63ebfab51fe84d --- /dev/null +++ b/policies/flip_cup/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1459,fell,1 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1459,fell,1 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1450,fell,1 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt61sol-s3/policy.py b/policies/flip_cup/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2b98236cd53d8b940358b528c0a8f6bf23647f89 --- /dev/null +++ b/policies/flip_cup/gpt61sol-s3/policy.py @@ -0,0 +1,70 @@ +"""Deterministic visual cup manipulation controller.""" +import numpy as np +import cv2 + +class Policy: + place_yaw=.4 + place_roll=0. + place_pitch=-1.57 + place_height=.74 + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=float) + self.a[19:]=0 + self.phase='raise';self.tick=0;self.start=self.a.copy() + self.base_target=float(obs['low_dim_obs'][21])+.14 + self.target=self.a.copy();self.target[5:12]=[-.9,0,0,-.5,0,0,0];self.target[12:19]=self.target[5:12] + self.duration=80 + def transition(self,name,target,duration): + self.phase=name;self.tick=0;self.start=self.a.copy();self.target=target.copy();self.duration=duration + @staticmethod + def cup(im): + a=im.astype(float) + m=((a.max(2)-a.min(2)<24)&(a.mean(2)>55)&(a.mean(2)<248)).astype(np.uint8) + m[:3]=0;m[:,:5]=0;m[:,-5:]=0 + n,lab,st,c=cv2.connectedComponentsWithStats(m) + ids=[i for i in range(1,n) if st[i,4]>12 and st[i,2]>3 and st[i,3]>8 and st[i,2]<1.7*st[i,3]] + if not ids:return None + i=max(ids,key=lambda i:st[i,4]);return c[i],st[i] + def act(self,obs,tools): + q=obs['low_dim_obs'];self.tick+=1 + if self.phase=='walk': + err=self.base_target-q[21] + self.a[0]=.12 if err>.012 else (-.07 if err<-.025 else 0) + if self.tick>=150: + self.a[0]=0;b=self.a.copy();b[5:12]=[-.3,0,.25,-1.,0,1.05,0];self.transition('prepare',b,80) + elif self.phase=='servo': + if self.tick%5==0: + f=self.cup(tools.image('left_wrist')) + if f: + xy,st=f + self.a[7]=np.clip(self.a[7]+(42-xy[0])*.002,-1,1) + self.a[10]=np.clip(self.a[10]+(xy[1]-42)*.002,0,1.6) + if abs(xy[0]-42)<7 and abs(xy[1]-42)<7: + self.a[5]=max(-1.3,self.a[5]-.007);self.a[8]=-1.3-self.a[5] + if st[4]>2100: + b=self.a.copy();b[19]=1;self.transition('grip',b,100) + if self.phase=='servo' and self.tick>470: + b=self.a.copy();b[19]=1;self.transition('grip',b,100) + elif self.phase=='hold':pass + else: + f=min(1,self.tick/(self.duration*.8));self.a=self.start+(self.target-self.start)*f + if self.phase=="reach":self.a[0]=.1 if q[21]=self.duration: + b=self.a.copy() + if self.phase=='raise':self.transition('walk',b,150) + elif self.phase=='prepare':self.transition('servo',b,470) + elif self.phase=='grip': + b[5]-=.65;b[8]+=.65;self.transition('lift',b,160) + elif self.phase=='lift': + b[10]=-1.6;self.transition('flip',b,240) + elif self.phase=='flip': + b[4]=.6;b[5:12]=[-1.1,0,self.place_yaw,-1.,self.place_roll,self.place_pitch,0];self.transition('reach',b,180) + elif self.phase=='reach': + b[2]=self.place_height;self.transition('lower',b,180) + elif self.phase=='lower': + b[19]=0;self.transition('release',b,80) + elif self.phase=='release': + b[2]=.74;b[4]=0;b[5:12]=[-.9,0,0,-.5,0,0,0];self.transition('retreat',b,100) + elif self.phase=='retreat':self.transition('hold',b,1) + return self.a.copy() diff --git a/policies/flip_cup/gpt61terra-s1/episodes.csv b/policies/flip_cup/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt61terra-s1/policy.py b/policies/flip_cup/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..189bee022b4f1c6010d3e65d0519682abb777bcb --- /dev/null +++ b/policies/flip_cup/gpt61terra-s1/policy.py @@ -0,0 +1,61 @@ +import cv2 +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.roll = .15 + self.reach = .7 + + def act(self, obs, tools): + t = int(obs['t']) + a = self.hold.copy() + a[:2] = 0 + a[2] = .9 + a[3:5] = 0 + a[19] = 0 + if t == 220: + im = tools.image('left_wrist') + high = im.max(axis=2).astype(np.int16) + low = im.min(axis=2).astype(np.int16) + mask = ((high-low < 24) & (low > 85) & (high < 250)).astype(np.uint8) + mask[:8,:] = 0 + mask[:,75:] = 0 + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + candidates = [i for i in range(1,n) if stats[i,4] > 200 and stats[i,1] < 42 and stats[i,3] > 10 and stats[i,1]+stats[i,3] < 82] + if candidates: + i = max(candidates, key=lambda j: stats[j,4]) + cx, cy = centers[i] + # Small departures from the nominal view reflect placement. + if abs(cx-34.5) > 3: + self.roll = float(np.clip(.15-.003*(cx-34.5), -.25, .35)) + if cy < 40: + self.reach = float(np.clip(.7-.003*(43.4-cy), .65, .7)) + if t >= 100: + f = min(1., (t-100)/100.) + a[5:12] = [-.7*f, .15*f, 0, .7*f, 0, -.3*f, 0] + if t >= 220: + f = min(1., (t-220)/30.) + a[5] = -.7+( .7-self.reach)*f + a[6] = .15+(self.roll-.15)*f + a[8] = .7+(self.reach-.7)*f + if t >= 250: + a[19] = 1 + if t >= 350: + f = min(1., (t-350)/150.) + a[5] = -self.reach+(-1.2+self.reach)*f + if t >= 520: + f = min(1., (t-520)/200.) + a[5] = -1.2-.6*f + a[8] = self.reach*(1-f) + a[10] = -.3-1.3*f + if t >= 750: + f = min(1., (t-750)/150.) + a[5] = -1.8+.3*f + a[2] = .9-.43*f + if t >= 930: + a[19] = 0 + if t >= 1000: + f = min(1., (t-1000)/100.) + a[6] = self.roll+.5*f + return a diff --git a/policies/flip_cup/gpt61terra-s2/episodes.csv b/policies/flip_cup/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt61terra-s2/policy.py b/policies/flip_cup/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4afffdba5e170770836ba354e3863ec56c74f386 --- /dev/null +++ b/policies/flip_cup/gpt61terra-s2/policy.py @@ -0,0 +1,65 @@ +import cv2 +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.roll = 0.25 + self.last_seen = None + + def cup(self, im): + # The porcelain is grey and nearly achromatic; the tabletop is cream + # and the background is blue. Ignore the dark edges of the gripper. + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + m = ((hsv[:,:,1] < 55) & (hsv[:,:,2] > 75) & (hsv[:,:,2] < 225)).astype(np.uint8) + m[:4,:] = 0; m[:, :3] = 0; m[:, 81:] = 0 + n, labels, stats, centers = cv2.connectedComponentsWithStats(m, 8) + candidates = [] + for i in range(1,n): + x,y,w,h,area = stats[i] + if area >= 25 and h >= 8 and w >= 5 and y < 75: + candidates.append((area, centers[i][0], centers[i][1])) + if not candidates: return None + return max(candidates) + + def act(self, obs, tools): + t = obs['t'] + a = self.base.copy() + a[0:5] = [0,0,.74,0,0] + a[19] = 0 + a[5:12] = [-.45,self.roll,0,0,0,0,0] + if 90 <= t < 200 and t % 5 == 0: + c = self.cup(tools.image('left_wrist')) + if c is not None: + self.last_seen = c + self.roll = float(np.clip(self.roll + np.clip((42-c[1])*.0009, -.012, .012), -.25, .65)) + if t >= 200: + # Move the hand towards the side of the cup with a gentle torso lean. + f = min(1., (t-200)/100.) + a[5] = -.45 - .10*f + a[8] = .13*f + a[4] = .15*f + a[10] = -.17*f + if t >= 310: + a[19] = 1 + if t >= 390: + f = min(1., (t-390)/90.) + a[5] -= .25*f + a[8] += .25*f + a[4] *= 1-f + if t >= 500: + f = min(1., (t-500)/150.) + a[9] = 1.9*f + a[7] = .95*f + if t >= 690: + f = min(1., (t-690)/120.) + a[5] += .25*f + a[8] -= .25*f + a[4] = .15*f + if t >= 830: + a[19] = 0 + if t >= 900: + a[5] = -.8 + a[8] = .4 + a[4] = 0 + return a diff --git a/policies/flip_cup/gpt61terra-s3/episodes.csv b/policies/flip_cup/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..25014eed658d6f02852fe77e031abf3ada1cc0b5 --- /dev/null +++ b/policies/flip_cup/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,1,1181,success,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,1,1192,success,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,1,1199,success,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,1,1178,success,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,1,1206,success,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,1,1209,success,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,1,1185,success,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,1,1178,success,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,1,1197,success,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,1,1179,success,0 +620092,1,1207,success,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt61terra-s3/policy.py b/policies/flip_cup/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..87a0efbc3ad8f08579d6886af34a7b88f15b988d --- /dev/null +++ b/policies/flip_cup/gpt61terra-s3/policy.py @@ -0,0 +1,62 @@ +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.a[19] = 0 + self.pitch = -1.15 + self.roll = .3 + self.target_x = 42.0 + + def act(self, obs, tools): + t = int(obs['t']); a = self.a + a[0] = 0 + if t < 55: + a[0] = -.3 + elif t < 115: + a[5:12] = [-.5,.1,0,2,0,0,0] + elif t < 175: + a[5:12] = [-1.5,.1,0,2,0,0,0] + elif t < 255: + a[5:12] = [-1.3,.3,0,1,0,0,0] + elif t < 355: + a[0] = .15 + elif t < 435: + a[5:12] = [-1.15,.3,0,1,0,0,0] + elif t < 610: + if (t-435)%5 == 0: + im = tools.image('left_wrist').astype(np.int16) + r,g,b = im[:,:,0], im[:,:,1], im[:,:,2] + mask = (abs(r-g)<12)&(abs(g-b)<12)&(r>75)&(r<220) + n,labels,stats,centers=cv2.connectedComponentsWithStats(mask.astype(np.uint8)) + valid=[k for k in range(1,n) if stats[k,4]>60] + if valid: + k=max(valid,key=lambda k:stats[k,4]); x,y,w,h,area=stats[k]; cx=centers[k,0] + if t == 435 and x == 0 and y+h >= 65: + white=(abs(r-g)<14)&(abs(g-b)<14)&(r>195) + white[:4]=0 + wn,wl,ws,wc=cv2.connectedComponentsWithStats(white.astype(np.uint8)) + options=[q for q in range(1,wn) if ws[q,4]>30 and 7<=ws[q,2]<=25 and ws[q,3]>=9 and wc[q,1]>14 and wc[q,1] 88) & (hi < 245) + grey[:, :4] = False + grey[:, 80:] = False + if head: + grey[31:] = False + else: + grey[:3] = False + grey[78:] = False + n, labels, stats, cents = cv2.connectedComponentsWithStats(grey.astype(np.uint8), 8) + best = None + best_score = -1 + for i in range(1, n): + x, y, w, h, area = [int(v) for v in stats[i]] + if head: + if area < 10 or w < 4 or h < 3 or y > 20: + continue + score = area - 1.5*y + else: + if area < 35 or w < 6 or h < 6 or y > 65 or x > 68: + continue + score = area - 2*max(0, y-30) + if score > best_score: + best = (float(cents[i, 0]), float(cents[i, 1]), w, h) + best_score = score + return best + + +class Policy: + def reset(self, obs, tools): + self.home = np.asarray(tools.hold_action(), dtype=np.float32) + self.start = np.asarray(obs['low_dim_obs'][21:25], dtype=np.float32) + blob = _cup_blob(tools.image('head'), head=True) + self.side = 1 if blob is None or blob[0] < 43 else -1 + self.roll = 0.0 + self.wp = 0.35 + self.last_image_step = -100 + self.last_seen = None + + def _nav(self, obs, action): + x, y, _, yaw = obs['low_dim_obs'][21:25] + target_x = self.start[0] + 0.43 + target_y = self.start[1] + self.side*0.49 + target_yaw = -self.side*1.57 + dx, dy = target_x-x, target_y-y + f = np.cos(yaw)*dx + np.sin(yaw)*dy + l = -np.sin(yaw)*dx + np.cos(yaw)*dy + action[0] = np.clip(1.5*f, -.17, .17) if abs(f) > .035 else 0 + action[1] = np.clip(1.5*l, -.17, .17) if abs(l) > .035 else 0 + err = (target_yaw-yaw+np.pi) % (2*np.pi)-np.pi + action[3] = np.clip(1.5*err, -.5, .5) if abs(err) > .06 else 0 + + def _servo(self, obs, tools): + if obs['t'] - self.last_image_step < 10: + return + self.last_image_step = obs['t'] + camera = 'left_wrist' if self.side == 1 else 'right_wrist' + blob = _cup_blob(tools.image(camera)) + if blob is None: + return + self.last_seen = blob + cx, cy, _, _ = blob + self.roll = float(np.clip(self.roll + self.side*.005*(42-cx), -.4, .45)) + self.wp = float(np.clip(self.wp + .004*(cy-24), -.3, 1.45)) + + def act(self, obs, tools): + t = int(obs['t']) + a = self.home.copy() + a[0:2] = 0 + a[3] = 0 + a[19:21] = .6 + if t < 220: + a[1] = self.side*.20 + return a + if t < 340: + a[0] = .20 + return a + if t < 580: + a[3] = -self.side*.5 + return a + if t < 740: + self._nav(obs, a) + return a + + a[2] = .85 + a[4] = -.1 + start = 5 if self.side == 1 else 12 + grip = 19 if self.side == 1 else 20 + a[grip] = 0 + if t < 850: + self._servo(obs, tools) + a[start:start+7] = [-.2, self.roll, 0, -.3, 0, self.wp, 0] + if self.side == -1: + a[start+1] *= -1 + return a + if t < 1000: + self._servo(obs, tools) + u = (t-850)/150 + a[start:start+7] = [-.2-.34*u, self.roll, 0, -.3, 0, self.wp, 0] + if self.side == -1: + a[start+1] *= -1 + return a + a[grip] = 1 + grasp_wp = min(self.wp, 1.05) + if t < 1090: + a[start:start+7] = [-.54, self.roll, 0, -.3, 0, grasp_wp, 0] + elif t < 1200: + a[start:start+7] = [-.72, self.roll, 0, -.65, 0, grasp_wp, 0] + elif t < 1300: + u = (t-1200)/100 + a[start:start+7] = [-.72, self.roll, 0, -.65, 1.6*u, grasp_wp-.7*u, 0] + elif t < 1410: + a[2] = .7 + a[start:start+7] = [-.35, self.roll, 0, -.35, 1.6, grasp_wp-.7, 0] + else: + a[2] = .74 + a[grip] = 0 + a[start:start+7] = [-.25, 0, 0, -.3, 0, .2, 0] + if self.side == -1: + a[start+1] *= -1 + a[start+4] *= -1 + return a diff --git a/policies/flip_cup/gpt6sol-s2/episodes.csv b/policies/flip_cup/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..62662c9e156e5cab084511969c5f1a4f85ca8b74 --- /dev/null +++ b/policies/flip_cup/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,1,605,success,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt6sol-s2/policy.py b/policies/flip_cup/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..fc1c41dbc48df87dd4785a27d077871eacfc6c57 --- /dev/null +++ b/policies/flip_cup/gpt6sol-s2/policy.py @@ -0,0 +1,109 @@ +"""Hand-written visual servo and arm sequence for the inverted cup.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.home = np.asarray(tools.hold_action(), dtype=np.float32) + self.home[0] = self.home[1] = self.home[3] = 0.0 + self.home[2] = 0.74 + self.home[4] = 0.0 + self.home[19:21] = 0.0 + self.state = "align" + self.state_t = 0 + self.cup_x = None + self.good_align = 0 + self.search_direction = 1.0 + self.last_image_step = -100 + self.origin_x = float(obs["low_dim_obs"][21]) + self.stage_index = 0 + self.stages = [ + ("settle", 45, 0.0, -0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.74), + ("approach", 85, 0.0, -1.0, 0.35, 0.0, 0.0, 0.7, 0.0, 0.0, 0.74), + ("lean", 65, 0.4, -1.0, 0.35, 0.0, 0.0, 0.7, 0.0, 0.0, 0.74), + ("tip", 45, 0.4, -1.2, 0.35, 0.0, 0.0, 0.7, 0.0, 0.0, 0.74), + ("handle", 55, 0.4, -1.3, 0.53, 0.3, 0.0, 0.7, 0.0, 0.0, 0.74), + ("close", 70, 0.4, -1.3, 0.53, 0.3, 0.0, 0.7, 1.0, 0.0, 0.74), + ("first_turn", 80, 0.4, -1.3, 0.53, 0.3, 0.0, -1.5, 1.0, 0.0, 0.74), + ("first_release", 60, 0.4, -1.3, 0.53, 0.3, 0.0, -1.5, 0.0, 0.0, 0.74), + ("side_approach", 90, 0.0, -0.95, 0.55, 0.0, 0.0, 0.7, 0.0, 0.0, 0.74), + ("side_grasp", 80, 0.0, -0.95, 0.55, 0.0, 0.0, 0.7, 1.0, 0.0, 0.74), + ("side_lift", 70, 0.0, -1.4, 0.55, 0.0, 0.0, 0.7, 1.0, 0.0, 0.74), + ("move_over_table", 70, 0.8, -1.4, -1.0, 0.0, 0.0, 0.7, 1.0, 0.18, 0.74), + ("second_turn", 80, 0.8, -1.4, -1.0, 0.0, 0.0, -1.5, 1.0, 0.0, 0.74), + ("lower", 80, 0.8, -1.1, -1.0, 0.0, 0.0, -1.5, 1.0, 0.0, 0.74), + ("second_release", 35, 0.8, -1.1, -1.0, 0.0, 0.0, -1.5, 0.0, 0.0, 0.74), + ("withdraw", 120, 0.0, -0.65, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.74), + ] + + @staticmethod + def _cup_in_head(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + mask = ((hsv[:, :, 1] < 55) & (gray > 45) & (gray < 210)).astype(np.uint8) + mask[25:, :] = 0 + mask[:, :3] = 0 + n, _, stats, centers = cv2.connectedComponentsWithStats(mask, 8) + best_area = 34 + best_x = None + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + if area > best_area: + best_area = area + best_x = float(centers[i, 0]) + return best_x + + def _advance(self): + self.stage_index += 1 + self.state_t = 0 + + def act(self, obs, tools): + raw = self.home.copy() + body = obs["low_dim_obs"] + yaw = float(body[24]) + if self.state == "align": + raw[4] = -0.2 + raw[3] = float(np.clip(-1.8 * yaw, -0.3, 0.3)) + if obs["t"] - self.last_image_step >= 5: + self.cup_x = self._cup_in_head(tools.image("head")) + self.last_image_step = obs["t"] + if self.state_t >= 35: + if self.cup_x is not None: + error = self.cup_x - 22.0 + if abs(error) > 2.5: + raw[1] = -float(np.clip(abs(error) * 0.009, 0.08, 0.25)) * np.sign(error) + self.good_align = 0 + elif abs(yaw) < 0.08: + self.good_align += 1 + if self.good_align > 18: + self.state = "sequence" + self.state_t = 0 + else: + # Traverse the table if the cup is outside the head view. + y = float(body[22]) + if y > 0.30: + self.search_direction = -1.0 + if y < -0.45: + self.search_direction = 1.0 + raw[1] = 0.16 * self.search_direction + if self.state_t > 340: + self.state = "sequence" + self.state_t = 0 + else: + self.state_t += 1 + return raw + if self.stage_index >= len(self.stages): + raw[5] = -0.65 + return raw + _, duration, pitch, sp, sy, elbow, wr, wp, grip, vx, height = self.stages[self.stage_index] + raw[0] = vx + raw[2] = height + raw[4] = pitch + raw[5:12] = (sp, 0.0, sy, elbow, wr, wp, 0.0) + raw[19] = grip + self.state_t += 1 + if self.state_t >= duration: + self._advance() + return raw diff --git a/policies/flip_cup/gpt6sol-s3/episodes.csv b/policies/flip_cup/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c2dcf166cc5fa0c5b4eb0b201022a61eb6228d7 --- /dev/null +++ b/policies/flip_cup/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,1,1088,success,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/gpt6sol-s3/policy.py b/policies/flip_cup/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..635fbb741c165497b50be96b0deaf99f064d5691 --- /dev/null +++ b/policies/flip_cup/gpt6sol-s3/policy.py @@ -0,0 +1,34 @@ +"""Deterministic cup-turning controller for the G1.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = int(obs['t']) + a = self.hold.copy() + a[10] = 0.9 + if t < 500: + # Reach the cup from the left, tip it, then roll it onto its base. + a[0] = 0.3 if 50 <= t < 85 else 0.0 + a[2] = 0.63 if 85 <= t < 345 else 0.74 + a[5] = -1.2 if t >= 345 else -0.8 + a[6] = -0.2 if t >= 235 else (0.6 if t >= 85 else 0.4) + a[19] = 1.0 if 165 <= t < 345 else 0.0 + elif t < 950: + # Sweep again if the first turn did not settle upright. + u = t - 500 + a[2] = 0.63 if 50 <= u < 310 else 0.74 + a[5] = -1.2 if u >= 310 else -0.8 + a[6] = -0.2 if u >= 200 else (0.7 if u >= 50 else 0.2) + a[19] = 1.0 if 130 <= u < 310 else 0.0 + else: + u = t - 950 + a[2] = 0.58 if 50 <= u < 310 else 0.74 + a[5] = -1.2 if u >= 310 else -0.8 + a[6] = -0.2 if u >= 200 else (0.8 if u >= 50 else 0.5) + a[19] = 1.0 if 130 <= u < 310 else 0.0 + return a diff --git a/policies/flip_cup/kimi31pro-s1/episodes.csv b/policies/flip_cup/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ee37bd029c2d8e699d4543daba1fdfdb1592cba3 --- /dev/null +++ b/policies/flip_cup/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,1,1038,success,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,1,1027,success,0 +620005,1,1026,success,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,1,1027,success,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,1,1363,success,0 +620013,1,1607,success,0 +620014,0,1850,timeout,0 +620015,1,1033,success,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,1,1027,success,0 +620025,1,1028,success,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,1,1045,success,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,1,1240,success,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,1,1028,success,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,1,1026,success,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,1,1026,success,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,1,1026,success,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,1,1026,success,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/kimi31pro-s1/policy.py b/policies/flip_cup/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f373c5f27789b813c266fad6d09880d7438a3af8 --- /dev/null +++ b/policies/flip_cup/kimi31pro-s1/policy.py @@ -0,0 +1,251 @@ +"""Deterministic visual-servo policy for turning the cup upright.""" + +import cv2 +import numpy as np + + +class Policy: + """Hand-written joint-space control with a wrist-camera grasp servo.""" + + def reset(self, obs, tools): + self.raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.raw[2] = 0.74 + self.raw[20] = 0.6 + head_x = self._head_cup_x(tools.image("head")) + if head_x is None: + head_x = 13.5 + self.right_cup = head_x > 25.0 + self.use_right = False + self.base_y = float(np.clip(0.01 * (21.5 - head_x), -0.25, 0.18)) + if self.use_right: + self.base_y = -self.base_y + self.place_y = 0.35 if self.use_right else -0.35 + self.mirror = np.array([1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0]) + self.raw[19] = 0.6 + self.left = np.zeros(7, dtype=np.float64) + self.right = np.zeros(7, dtype=np.float64) + self.torso = 0.0 + self.attempt = 0 + self._set_stage("pre", obs) + + def _set_stage(self, name, obs): + self.stage = name + self.j = 0 + self.start_left = self.left.copy() + self.start_right = self.right.copy() + self.start_torso = self.torso + self.target_right = None + sy = float(self.left[2]) + self.target_left = self.left.copy() + self.target_torso = self.torso + self.grip = 0.0 + self.mode = "hold" + + if name == "pre": + self.duration = 130 + self.target_left = np.array([-0.3, 0, 0, 0, 0, -0.25, 0]) + self.target_right = np.zeros(7) + self.target_torso = 0.0 + self.mode = "pre" + elif name == "grasppose": + self.duration = 75 + self.target_left = np.array([-0.45, 0, sy, 0, 0, 0, 0]) + self.target_torso = 0.2 + self.mode = "forward" + self.filtered = None + elif name == "servo": + self.duration = 125 + self.sy = sy + self.sp = float(self.left[0]) + self.target_torso = 0.2 + self.torso = 0.2 + self.mode = "forward" + elif name == "close": + self.duration = 45 + self.place_x = float(np.clip(0.45 + 0.7 * (self.left[0] + 0.45), 0.25, 0.55)) + self.grip = 1.0 + elif name == "lift": + self.duration = 85 + self.target_left = np.array([-0.55, 0, sy, 0, 0, 0.3, 0]) + self.target_torso = 0.0 + self.grip = 1.0 + elif name == "return": + self.duration = 75 + self.target_left = np.array([-0.45, 0, sy, 0, 0, 0, 0]) + self.target_torso = 0.2 + self.grip = 1.0 + self.mode = "forward" + elif name == "turn": + self.duration = 125 + self.target_left = np.array([-0.45, 1.0, sy, 0, 1.97, 0, 0]) + self.target_torso = 0.2 + self.grip = 1.0 + self.mode = "forward" + elif name == "open": + self.duration = 25 + self.target_torso = 0.2 + self.grip = 1.0 + elif name == "rightplace": + self.duration = 110 + self.target_torso = 0.2 + self.grip = 1.0 + self.mode = "rightplace" + elif name == "forwardplace": + self.duration = 100 + self.target_torso = 0.2 + self.grip = 1.0 + self.mode = "forwardplace" + elif name == "lower": + self.duration = 80 + self.target_left = self.left.copy() + self.target_left[5] = -0.4 + self.target_torso = 0.6 + self.grip = 1.0 + self.mode = "lower" + self.raw[2] = 0.55 + elif name == "settle": + self.duration = 10**9 + self.target_torso = 0.6 + self.grip = 0.0 + self.mode = "settle" + else: + raise ValueError(name) + + def _next_stage(self, obs): + transitions = { + "pre": "grasppose", + "grasppose": "servo", + "servo": "close", + "close": "lift", + "return": "turn", + "turn": "open", + "open": "rightplace", + "rightplace": "forwardplace", + "forwardplace": "lower", + "lower": "settle", + } + if self.stage == "lift": + finger_slice = slice(19, 21) if self.use_right else slice(10, 12) + fingers = obs["low_dim_obs"][finger_slice] + grasped = bool(np.mean(fingers) > -0.017) + if not grasped and self.attempt < 2: + self.attempt += 1 + self._set_stage("grasppose", obs) + else: + self._set_stage("return", obs) + return + self._set_stage(transitions[self.stage], obs) + + def _base(self, obs): + raw = self.raw + mode = self.mode + if mode in ("lower", "settle"): + raw[0] = raw[1] = raw[3] = 0.0 + return + p = obs["low_dim_obs"][21:25] + yaw = float(p[3]) + if mode == "rightplace": + target, gain, cap = np.array([0.23, self.place_y]), 3.0, 0.25 + elif mode == "forwardplace": + target, gain, cap = np.array([0.45, self.place_y]), 3.0, 0.25 + else: + target = np.array([0.21, self.base_y]) if mode == "pre" else np.array([0.25, self.base_y]) + gain, cap = 2.0, 0.12 + dx, dy = target - p[:2] + c, s = np.cos(yaw), np.sin(yaw) + if mode == "forward": + raw[0] = 0.12 + else: + raw[0] = float(np.clip(gain * (c * dx + s * dy), -cap, cap)) + raw[1] = float(np.clip(gain * (-s * dx + c * dy), -cap, cap)) + raw[3] = float(np.clip(-3.0 * yaw, -0.35, 0.35)) + for b in (0, 1): + if abs(raw[b]) < 0.025: + raw[b] = 0.0 + elif abs(raw[b]) < 0.06: + raw[b] = np.sign(raw[b]) * 0.06 + + @staticmethod + def _head_cup_x(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + _, saturation, value = cv2.split(hsv) + mask = ((saturation < 65) & (value > 65) & (value < 245)).astype(np.uint8) + mask[20:] = 0 + count, _, stats, cents = cv2.connectedComponentsWithStats(mask) + best = None + for index in range(1, count): + x, y, w, h, area = stats[index] + if area > 15 and w > 3 and h > 3: + if best is None or area > best[0]: + best = (area, float(cents[index, 0])) + return None if best is None else best[1] + + @staticmethod + def _cup_features(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + _, saturation, value = cv2.split(hsv) + mask = ((saturation < 60) & (value > 70) & (value < 248)).astype(np.uint8) + mask[78:] = 0 + count, _, stats, cents = cv2.connectedComponentsWithStats(mask) + best = None + for index in range(1, count): + x, y, w, h, area = stats[index] + if area > 20 and h > 5 and w > 2 and y < 70: + candidate = (area, float(cents[index, 0]), float(cents[index, 1]), int(w)) + if best is None or candidate[0] > best[0]: + best = candidate + return None if best is None else best[1:] + + def act(self, obs, tools): + if self.j >= self.duration: + self._next_stage(obs) + + name = self.stage + if name == "servo": + camera = "right_wrist" if self.use_right else "left_wrist" + image = tools.image(camera) + features = self._cup_features(image) + if features is not None: + cx, cy, width = features + if self.filtered is None: + self.filtered, self.filtered_y, self.filtered_width = cx, cy, float(width) + else: + self.filtered = 0.7 * self.filtered + 0.3 * cx + self.filtered_y = 0.7 * self.filtered_y + 0.3 * cy + self.filtered_width = 0.7 * self.filtered_width + 0.3 * width + correction = np.clip(0.0005 * (42.0 - self.filtered), -0.005, 0.005) + self.sy = float(np.clip(self.sy + correction, -0.8, 0.4)) + if self.filtered_width < 70.0: + self.torso += min(0.0015, 0.00015 * (70.0 - self.filtered_width)) + elif self.filtered_width > 79.0: + self.torso -= min(0.0015, 0.00015 * (self.filtered_width - 79.0)) + if self.filtered_y < 52.0: + self.sp -= min(0.002, 0.0008 * (52.0 - self.filtered_y)) + elif self.filtered_y > 58.0: + self.sp += min(0.002, 0.0008 * (self.filtered_y - 58.0)) + self.torso = float(np.clip(self.torso, 0.1, 0.45)) + self.sp = float(np.clip(self.sp, -0.75, -0.25)) + self.left[0] = self.sp + self.left[2] = self.sy + self.left[5] = 0.2 - self.torso - self.sp + else: + alpha = min(1.0, (self.j + 1) / min(55.0, float(self.duration))) + self.torso = self.start_torso * (1.0 - alpha) + self.target_torso * alpha + self.left = self.start_left * (1.0 - alpha) + self.target_left * alpha + if self.target_right is not None: + self.right = self.start_right * (1.0 - alpha) + self.target_right * alpha + + self.raw[4] = self.torso + if self.use_right: + self.raw[5:12] = 0.0 + self.raw[12:19] = self.left * self.mirror + self.raw[19] = 0.6 + self.raw[20] = self.grip + else: + self.raw[5:12] = self.left + self.raw[12:19] = self.right + self.raw[19] = self.grip + self.raw[20] = 0.6 + self._base(obs) + self.j += 1 + return self.raw.copy() diff --git a/policies/flip_cup/kimi31pro-s2/episodes.csv b/policies/flip_cup/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/kimi31pro-s2/policy.py b/policies/flip_cup/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2d1c30b4c7e5a9f18c0f1bb6d22c747acf690776 --- /dev/null +++ b/policies/flip_cup/kimi31pro-s2/policy.py @@ -0,0 +1,119 @@ +"""Deterministic joint-space controller for the flip-cup task. + +The approach first raises the hand, then descends with a fixed hand orientation. +The grasp is on the cup body rather than its handle. The flip is measured from +the initial arm configuration and corrected using proprioception, since contact +can otherwise leave the wrist short of its target. +""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.tick = 0 + self.previous = np.zeros(7, dtype=np.float32) + self.qflip = np.array( + [-1.6, 0.28, 0.0, 0.1, 0.0, -1.55, 0.0], dtype=np.float32 + ) + self.safe = np.array( + [-1.1, 0.1, 0.0, 0.1, 0.0, 0.5, 0.0], dtype=np.float32 + ) + self.high = np.array( + [-1.45, 0.28, 0.0, 0.8, 0.0, 0.85, 0.0], dtype=np.float32 + ) + self.pre = np.array( + [-1.45, 0.28, 0.0, 1.15, 0.0, 0.50, 0.0], dtype=np.float32 + ) + self.lift = np.array( + [-1.65, 0.28, 0.0, 1.15, 0.0, 0.70, 0.0], dtype=np.float32 + ) + self.initial_angle = None + self.desired_angle = None + self.forward_target = None + + @staticmethod + def _pitch_angle(obs): + q = obs["low_dim_obs"] + return float(q[3] + q[6] + q[8]) + + def _advance(self): + self.phase += 1 + # act() increments tick on exit; zero is the next phase's first step. + self.tick = -1 + + def act(self, obs, tools): + t = self.tick + phase = self.phase + raw = self.hold.copy() + raw[0:2] = 0.0 + raw[3] = 0.0 + raw[4] = 0.0 + raw[12:19] = 0.0 + raw[20] = 0.0 + + # phase, duration, target, gripper, pelvis height + specs = { + 0: (50, self.safe, 0.0, 0.74), + 1: (80, self.high, 0.0, 0.74), + 2: (90, self.pre, 0.0, 0.74), + 3: (100, self.pre, 1.0, 0.74), + 4: (100, self.lift, 1.0, 0.78), + 5: (180, self.qflip, 1.0, 0.78), + 6: (70, self.qflip, 1.0, 0.78), + 7: (70, self.qflip, 1.0, 0.78), + 9: (100, self.qflip, 1.0, 0.58), + 10: (50, self.qflip, 0.0, 0.58), + 11: (140, self.safe, 0.0, 0.74), + 12: (100, self.safe, 0.0, 0.74), + } + + if phase in (0, 1, 2, 3, 4, 5, 9, 10, 11, 12): + duration, target, grip, height = specs[phase] + u = min(1.0, t / max(1.0, duration * 0.75)) + raw[2] = height + raw[5:12] = (1.0 - u) * self.previous + u * target + raw[19] = grip + if phase == 3 and t == duration - 1: + self.initial_angle = self._pitch_angle(obs) + self.desired_angle = self.initial_angle - np.pi + if t >= duration - 1: + self.previous = target.copy() + self._advance() + + elif phase in (6, 7): + # Correct contact-induced tracking error at the start of each hold. + if t == 0: + error = self.desired_angle - self._pitch_angle(obs) + self.qflip[0] = np.clip(self.qflip[0] + error, -2.6, 1.0) + duration, target, grip, height = specs[phase] + raw[2] = height + raw[5:12] = target + raw[19] = grip + if t >= duration - 1: + self.previous = target.copy() + self._advance() + + elif phase == 8: + # The flip brings the hand toward the torso. Move slightly forward + # before release so the cup is above the cabinet, not the robot's feet. + if t == 0: + self.forward_target = min(0.22, float(obs["low_dim_obs"][21]) + 0.06) + raw[2] = 0.78 + raw[5:12] = self.qflip + raw[19] = 1.0 + if float(obs["low_dim_obs"][21]) < self.forward_target: + raw[0] = 0.12 + if t >= 99: + self.previous = self.qflip.copy() + self._advance() + + else: + raw[2] = 0.74 + raw[5:12] = self.safe + raw[19] = 0.0 + + self.tick += 1 + return raw diff --git a/policies/flip_cup/kimi31pro-s3/episodes.csv b/policies/flip_cup/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b902163d004927c3c7bc9b16fc318965522d8920 --- /dev/null +++ b/policies/flip_cup/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1850,timeout,0 +620001,0,1850,timeout,0 +620002,0,1850,timeout,0 +620003,0,1850,timeout,0 +620004,0,1850,timeout,0 +620005,0,1850,timeout,0 +620006,0,1850,timeout,0 +620007,0,1850,timeout,0 +620008,0,1850,timeout,0 +620009,0,1850,timeout,0 +620010,0,1850,timeout,0 +620011,0,1850,timeout,0 +620012,0,1850,timeout,0 +620013,0,1850,timeout,0 +620014,0,1850,timeout,0 +620015,0,1850,timeout,0 +620016,0,1850,timeout,0 +620017,0,1850,timeout,0 +620018,0,1850,timeout,0 +620019,0,1850,timeout,0 +620020,0,1850,timeout,0 +620021,0,1850,timeout,0 +620022,0,1850,timeout,0 +620023,0,1850,timeout,0 +620024,0,1850,timeout,0 +620025,0,1850,timeout,0 +620026,0,1850,timeout,0 +620027,0,1850,timeout,0 +620028,0,1850,timeout,0 +620029,0,1850,timeout,0 +620030,0,1850,timeout,0 +620031,0,1850,timeout,0 +620032,0,1850,timeout,0 +620033,0,1850,timeout,0 +620034,0,1850,timeout,0 +620035,0,1850,timeout,0 +620036,0,1850,timeout,0 +620037,0,1850,timeout,0 +620038,0,1850,timeout,0 +620039,0,1850,timeout,0 +620040,0,1850,timeout,0 +620041,0,1850,timeout,0 +620042,0,1850,timeout,0 +620043,0,1850,timeout,0 +620044,0,1850,timeout,0 +620045,0,1850,timeout,0 +620046,0,1850,timeout,0 +620047,0,1850,timeout,0 +620048,0,1850,timeout,0 +620049,0,1850,timeout,0 +620050,0,1850,timeout,0 +620051,0,1850,timeout,0 +620052,0,1850,timeout,0 +620053,0,1850,timeout,0 +620054,0,1850,timeout,0 +620055,0,1850,timeout,0 +620056,0,1850,timeout,0 +620057,0,1850,timeout,0 +620058,0,1850,timeout,0 +620059,0,1850,timeout,0 +620060,0,1850,timeout,0 +620061,0,1850,timeout,0 +620062,0,1850,timeout,0 +620063,0,1850,timeout,0 +620064,0,1850,timeout,0 +620065,0,1850,timeout,0 +620066,0,1850,timeout,0 +620067,0,1850,timeout,0 +620068,0,1850,timeout,0 +620069,0,1850,timeout,0 +620070,0,1850,timeout,0 +620071,0,1850,timeout,0 +620072,0,1850,timeout,0 +620073,0,1850,timeout,0 +620074,0,1850,timeout,0 +620075,0,1850,timeout,0 +620076,0,1850,timeout,0 +620077,0,1850,timeout,0 +620078,0,1850,timeout,0 +620079,0,1850,timeout,0 +620080,0,1850,timeout,0 +620081,0,1850,timeout,0 +620082,0,1850,timeout,0 +620083,0,1850,timeout,0 +620084,0,1850,timeout,0 +620085,0,1850,timeout,0 +620086,0,1850,timeout,0 +620087,0,1850,timeout,0 +620088,0,1850,timeout,0 +620089,0,1850,timeout,0 +620090,0,1850,timeout,0 +620091,0,1850,timeout,0 +620092,0,1850,timeout,0 +620093,0,1850,timeout,0 +620094,0,1850,timeout,0 +620095,0,1850,timeout,0 +620096,0,1850,timeout,0 +620097,0,1850,timeout,0 +620098,0,1850,timeout,0 +620099,0,1850,timeout,0 diff --git a/policies/flip_cup/kimi31pro-s3/policy.py b/policies/flip_cup/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..582cfc50cfc53c2086fa89745bd235e6bb473122 --- /dev/null +++ b/policies/flip_cup/kimi31pro-s3/policy.py @@ -0,0 +1,171 @@ +"""Hand-written, deterministic controller for the cup-flipping task. + +The motion uses only proprioception and the robot's head camera. A short +initial alignment compensates for the cup's lateral placement; the remainder +is a joint-space pick, rotate, lower, and release sequence. +""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.k = 0 + self.cup_u = 12.0 + self.original_u = None + self.side_vy = 0.0 + self.last_yaw = 0.52 + self.start_arm = np.zeros(7, dtype=np.float32) + self.retract_arm = np.zeros(7, dtype=np.float32) + self.grasp = np.array([-1.30, 0.0, 0.52, 0.0, 0.0, 0.80, 0.0]) + self.raised = np.array([-1.55, 0.0, 0.52, 0.0, 0.0, 1.55, 0.0]) + self.flipped = self.raised.copy() + self.flipped[5] = -np.pi / 2.0 + + @staticmethod + def _cup_column(image): + """Locate the gray cup against the bright yellow tabletop.""" + hsv = cv2.cvtColor(image[:17], cv2.COLOR_RGB2HSV) + mask = ((hsv[:, :, 1] < 72) & + (hsv[:, :, 2] > 45) & + (hsv[:, :, 2] < 218)).astype(np.uint8) + n, _, stats, centers = cv2.connectedComponentsWithStats(mask, 8) + candidates = [] + for i in range(1, n): + x, y, w, h, area = stats[i] + if area >= 4 and w <= 42: + candidates.append((area, centers[i, 0])) + if not candidates: + return None + return float(max(candidates)[1]) + + def _base_action(self): + a = self.hold.copy() + a[0:2] = 0.0 + a[3] = 0.0 + a[19] = 1.0 + return a + + def act(self, obs, tools): + k = self.k + self.k += 1 + + # Normalize lateral placement while the cup is unobstructed. + if k < 50: + a = self.hold.copy() + u = self._cup_column(tools.image("head")) + if u is not None: + if self.original_u is None: + self.original_u = u + self.cup_u = 0.65 * self.cup_u + 0.35 * u + error = self.cup_u - 12.0 + vy = float(np.clip(-0.010 * error, -0.25, 0.25)) + if 0.0 < abs(vy) < 0.06: + vy = np.sign(vy) * 0.06 + if abs(error) < 1.5 or abs(obs["low_dim_obs"][22]) > 0.48: + vy = 0.0 + a[1] = vy + return a + + if k == 50: + yaw = float(np.clip(0.52 + 0.015 * (12.0 - self.cup_u), -0.20, 1.0)) + self.grasp[2] = yaw + self.raised[2] = yaw + self.flipped[2] = yaw + if self.original_u is not None: + if self.original_u < 30.0: + self.side_vy = -0.30 + elif self.original_u > 54.0: + self.side_vy = 0.30 + self.start_arm = obs["low_dim_obs"][3:10].astype(np.float32).copy() + + # Approach the inverted cup with a level, forward-facing left gripper. + if k < 175: + s = (k - 49) / 125.0 + a = self.hold.copy() + a[2] = 0.85 + a[4] = 0.50 * s + a[5:12] = self.start_arm + (self.grasp - self.start_arm) * s + a[19] = 0.0 + return a + + # Close securely around the cup body. + if k < 245: + a = self._base_action() + a[2] = 0.85 + a[4] = 0.50 + a[5:12] = self.grasp + a[19] = (k - 174) / 70.0 + return a + + # Raise the cup while keeping its world orientation unchanged. + if k < 485: + s = (k - 244) / 240.0 + a = self._base_action() + a[2] = 0.85 + a[4] = 0.50 * (1.0 - s) + a[5:12] = self.grasp + (self.raised - self.grasp) * s + return a + + # Turn the cup upside-up with a slow, full wrist-pitch rotation. + if k < 685: + s = (k - 484) / 200.0 + a = self._base_action() + a[2] = 0.85 + a[4] = 0.0 + a[5:12] = self.raised + a[10] = 1.55 - np.pi * s + return a + + if k == 685: + self.flipped = obs["low_dim_obs"][3:10].astype(np.float32).copy() + self.flipped[5] = 1.55 - np.pi + + # Carry the upright cup slightly toward the table center. + if k < 705: + a = self._base_action() + a[1] = self.side_vy + a[2] = 0.85 + a[4] = 0.0 + a[5:12] = self.flipped + return a + if k < 745: + a = self._base_action() + a[2] = 0.85 + a[4] = 0.0 + a[5:12] = self.flipped + return a + + # Lower close to the tabletop before disengaging. + if k < 895: + s = (k - 744) / 150.0 + a = self._base_action() + a[2] = 0.85 - 0.30 * s + a[4] = 0.0 + a[5:12] = self.flipped + return a + + if k == 895: + self.retract_arm = obs["low_dim_obs"][3:10].astype(np.float32).copy() + + # Open and immediately retract upward so the cup is not dragged. + if k < 1056: + s = (k - 894) / 160.0 + a = self.hold.copy() + a[2] = 0.55 + 0.30 * s + a[4] = 0.0 + a[5:12] = self.retract_arm * (1.0 - s) + a[19] = 0.0 + a[20] = 0.6 + return a + + a = self.hold.copy() + a[2] = 0.85 + a[4] = 0.0 + a[5:12] = 0.0 + a[12:19] = 0.0 + a[19] = 0.0 + a[20] = 0.6 + return a diff --git a/policies/flip_cup/opus-s1/episodes.csv b/policies/flip_cup/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7f04346171421b8490fb57350e1a8f2f26176b33 --- /dev/null +++ b/policies/flip_cup/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1069,success,0 +620001,1,1061,success,0 +620002,0,1850,timeout,0 +620003,1,1135,success,0 +620004,1,1046,success,0 +620005,1,985,success,0 +620006,1,1144,success,0 +620007,1,1172,success,0 +620008,1,1061,success,0 +620009,1,1063,success,0 +620010,1,1406,success,0 +620011,1,1058,success,0 +620012,1,1036,success,0 +620013,1,1098,success,0 +620014,1,1279,success,0 +620015,1,1285,success,0 +620016,1,1119,success,0 +620017,1,1092,success,0 +620018,1,1150,success,0 +620019,1,1051,success,0 +620020,1,1044,success,0 +620021,1,1076,success,0 +620022,1,1045,success,0 +620023,1,1082,success,0 +620024,1,1205,success,0 +620025,1,1073,success,0 +620026,1,1090,success,0 +620027,1,1043,success,0 +620028,0,1850,timeout,0 +620029,1,1047,success,0 +620030,1,1245,success,0 +620031,1,1046,success,0 +620032,1,1061,success,0 +620033,1,1077,success,0 +620034,1,1319,success,0 +620035,1,1073,success,0 +620036,1,1486,success,0 +620037,1,1058,success,0 +620038,1,1052,success,0 +620039,0,1850,timeout,0 +620040,1,1087,success,0 +620041,1,1064,success,0 +620042,1,1093,success,0 +620043,1,1290,success,0 +620044,1,1047,success,0 +620045,1,1037,success,0 +620046,1,1334,success,0 +620047,1,1138,success,0 +620048,1,1067,success,0 +620049,1,1353,success,0 +620050,1,1086,success,0 +620051,1,1015,success,0 +620052,1,1307,success,0 +620053,0,1850,timeout,0 +620054,1,1048,success,0 +620055,1,1275,success,0 +620056,1,1044,success,0 +620057,1,1111,success,0 +620058,1,1247,success,0 +620059,1,1269,success,0 +620060,0,1850,timeout,0 +620061,1,1314,success,0 +620062,1,1126,success,0 +620063,1,1044,success,0 +620064,1,1110,success,0 +620065,1,1374,success,0 +620066,1,1035,success,0 +620067,0,1850,timeout,0 +620068,1,1077,success,0 +620069,1,1160,success,0 +620070,1,1158,success,0 +620071,1,1252,success,0 +620072,1,1256,success,0 +620073,0,1850,timeout,0 +620074,1,1044,success,0 +620075,1,1218,success,0 +620076,1,1076,success,0 +620077,1,1066,success,0 +620078,1,1014,success,0 +620079,1,1043,success,0 +620080,1,1044,success,0 +620081,1,1199,success,0 +620082,0,1850,timeout,0 +620083,1,1361,success,0 +620084,1,1449,success,0 +620085,0,1850,timeout,0 +620086,1,1089,success,0 +620087,1,1068,success,0 +620088,1,982,success,0 +620089,1,1052,success,0 +620090,1,1043,success,0 +620091,1,1066,success,0 +620092,1,1044,success,0 +620093,1,1028,success,0 +620094,1,1053,success,0 +620095,1,1112,success,0 +620096,1,1078,success,0 +620097,1,1518,success,0 +620098,1,1253,success,0 +620099,1,1135,success,0 diff --git a/policies/flip_cup/opus-s1/g1kin.py b/policies/flip_cup/opus-s1/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..75de4d5f750e1a2b0e90e3cb4c7762b1ec27229c --- /dev/null +++ b/policies/flip_cup/opus-s1/g1kin.py @@ -0,0 +1,108 @@ +"""Kinematics helpers for policy.py: G1 arm forward kinematics and a small IK solver. + +Link offsets follow the public Unitree G1 (29 dof) description. Frames are expressed +in the pelvis frame (x forward, y left, z up); the gripper tip frame has x along the +approach direction, y along the finger closing axis. +""" + +import numpy as np +from scipy.optimize import least_squares + + +def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _T(R=None, p=(0, 0, 0)): + M = np.eye(4) + if R is not None: + M[:3, :3] = R + M[:3, 3] = p + return M + + +def torso_T(waist): + M = _T(rz(waist[0])) + M = M @ _T(p=(-0.0039635, 0, 0.035)) @ _T(rx(waist[1])) + M = M @ _T(p=(0, 0, 0.019)) @ _T(ry(waist[2])) + return M + + +def tip_pose(side, q, waist=(0, 0, 0.08), hand_len=0.12): + s = 1 if side == 'L' else -1 + M = torso_T(waist) + M = M @ _T(rz(s * -0.00019159) @ ry(5.4949e-05) @ rx(s * 0.27931), (0.0039563, s * 0.10022, 0.24778)) + M = M @ _T(ry(q[0])) + M = M @ _T(rx(s * -0.27925), (0, s * 0.038, -0.013831)) @ _T(rx(q[1])) + M = M @ _T(p=(0, s * 0.00624, -0.1032)) @ _T(rz(q[2])) + M = M @ _T(p=(0.015783, 0, -0.080518)) @ _T(ry(q[3])) + M = M @ _T(p=(0.100, s * 0.00188791, -0.010)) @ _T(rx(q[4])) + M = M @ _T(p=(0.038, 0, 0)) @ _T(ry(q[5])) + M = M @ _T(p=(0.046, 0, 0)) @ _T(rz(q[6])) + return M @ _T(p=(hand_len, 0, 0)) + + +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def limits(side): + if side == 'L': + return LO.copy(), HI.copy() + lo, hi = LO.copy(), HI.copy() + lo[1], hi[1] = -HI[1], -LO[1] + return lo, hi + + +def ik(side, pos, R, q0, waist=(0, 0, 0.08), wrot=0.3, reg=0.02, margin=0.0, hand_len=0.12): + """Least-squares IK for tip position + full orientation, warm-started at q0.""" + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-3, hi - 1e-3) + pos = np.asarray(pos, float) + + def res(q): + M = tip_pose(side, q, waist, hand_len) + r = list(M[:3, 3] - pos) + list(wrot * (M[:3, :3] - R).ravel()) + if margin > 0: + r += list(0.3 * np.maximum(0, (lo + margin) - q)) + list(0.3 * np.maximum(0, q - (hi - margin))) + r += list(reg * (q - q0)) + return r + + s = least_squares(res, q0, bounds=(lo, hi)) + M = tip_pose(side, s.x, waist, hand_len) + return s.x, float(np.linalg.norm(M[:3, 3] - pos)) + + +def axis_rot(h, th): + h = np.asarray(h, float) + h = h / np.linalg.norm(h) + K = np.array([[0, -h[2], h[1]], [h[2], 0, -h[0]], [-h[1], h[0], 0]]) + return np.eye(3) + np.sin(th) * K + (1 - np.cos(th)) * K @ K + + +def flip_path(side, q0, h, sgn, n=30, waist=(0, 0, 0.08)): + """Joint waypoints rotating the tip by sgn*pi about axis h, tip position fixed.""" + M0 = tip_pose(side, q0, waist) + P0, R0 = M0[:3, 3], M0[:3, :3] + q = np.array(q0, float) + out = [q.copy()] + worst = 0.0 + for th in np.linspace(0, sgn * np.pi, n + 1)[1:]: + R = axis_rot(h, th) @ R0 + qn, pe = ik(side, P0, R, q, waist, wrot=0.5, reg=0.02, margin=0.25) + M = tip_pose(side, qn, waist) + worst = max(worst, pe * 10 + np.linalg.norm(M[:3, :3] - R) + max(0, np.abs(qn - q).max() - 0.25)) + q = qn + out.append(q.copy()) + return np.array(out), worst diff --git a/policies/flip_cup/opus-s1/policy.py b/policies/flip_cup/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f46e7b2940cabef77d5da025836976324784b84b --- /dev/null +++ b/policies/flip_cup/opus-s1/policy.py @@ -0,0 +1,348 @@ +"""Flip the upside-down cup on the counter and set it back down (Unitree G1). + +Strategy (hand-written, camera driven): + 1. Lean back, find the cup in the head camera, step so the cup sits in front + of the left arm at a comfortable reach. + 2. Bring the left gripper to the counter at handle height and visually servo + with the left wrist camera onto the cup handle: the handle's dark shadow + streak on the counter gives its lateral offset (centre it) and its direction + (align the approach heading with it); the cup's lowest image row gives depth. + 3. Push the open gripper over the handle, close, lift. + 4. Rotate the gripper half a turn about its horizontal approach axis (an IK + path keeping the tip fixed), which turns the cup the right way up. + 5. Lower it onto the counter, open, retract. +""" + +import os +import sys + +import cv2 +import numpy as np + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +from g1kin import _T, flip_path, ik, ry, rz, tip_pose, torso_T # noqa: E402 + +WP = (0, 0, 0.08) # nominal waist used for arm kinematics +Z_GRASP = 0.21 # tip height (pelvis frame) for the handle grasp +Y_CUP = 0.14 # desired lateral cup-centre offset (pelvis frame) +X_CUP = 0.55 # desired forward cup-centre offset (pelvis frame) +X_STAND_MAX = 0.205 # the counter stops the pelvis at ~0.22 +Q_UP = np.array([-1.5, 0.3, 0.0, -1.0, 0.0, 0.0, 0.0]) # arm raised clear of the counter +Q_PRE = np.array([-0.541, 0.483, -0.429, -0.223, -0.688, 0.395, 0.683]) # IK seed near the cup +FLIP_START = np.array([0.45, 0.14, 0.31]) +# head camera model at the look pose (field of view / pitch / yaw offsets tuned on dev episodes) +HEAD_FOVY, HEAD_DPITCH, HEAD_DYAW, HEAD_WAIST = 63.2, 0.295, -0.011, -0.126 +TABLE_Z = 0.155 # counter top, pelvis frame +CUP_R = 0.035 + + +# ----------------------------------------------------------------------------- vision + +def edge_rows(im): + """(top, bottom) image rows of the counter's brown front edge, or None.""" + im = im.astype(np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + br = (r - b > 35) & (r < 210) & (r > g) & (g > b) + idx = np.nonzero(br.mean(1) > 0.5)[0] + return (int(idx.min()), int(idx.max())) if len(idx) else None + + +def grey_mask(im, lo=80, hi=247, sat=22): + im16 = im.astype(np.int16) + mx, mn = im16.max(2), im16.min(2) + return ((mx - mn) < sat) & (mx > lo) & (mx < hi) + + +def largest(mask): + n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), 8) + if n <= 1: + return None + k = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]) + return lab == k + + +def brown_mask(im): + im16 = im.astype(np.int16) + r, g, b = im16[..., 0], im16[..., 1], im16[..., 2] + return (r - b > 35) & (r < 210) & (r > g) & (g > b) + + +def below_brown(im, pad=2): + """Per column, everything from the first brown (counter edge / shadow) pixel down.""" + br = brown_mask(im) + br = br & np.roll(br, 1, axis=0) # runs of at least two pixels + has = br.any(0) + first = np.where(has, br.argmax(0), 84) + rows = np.arange(im.shape[0])[:, None] + return rows >= (first[None, :] - pad) + + +def wrist_cup(im): + m = grey_mask(im) + m &= ~below_brown(im) + blob = largest(m) + if blob is None or blob.sum() < 15: + return None + ys, xs = np.nonzero(blob) + return dict(u=xs.mean(), v=ys.mean(), umin=xs.min(), umax=xs.max(), vmax=ys.max(), area=len(xs)) + + +def streak_near(im, f): + """Dark-brown handle shadow just below the cup blob: top u, top v, slope du/dv.""" + im16 = im.astype(np.int16) + r, g, b = im16[..., 0], im16[..., 1], im16[..., 2] + m = (r - b > 30) & (r < 175) & (r > g) & (g > b) & (r > 60) + er = edge_rows(im) + if er is not None: + m[er[0] - 3:] = False + n, lab, stats, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8), 8) + best = None + for k in range(1, n): + if stats[k, cv2.CC_STAT_AREA] < 6 or stats[k, cv2.CC_STAT_WIDTH] > 22: + continue + ys, xs = np.nonzero(lab == k) + vt = ys.min() + if abs(vt - f['vmax']) > 10: + continue + ut = xs[ys <= vt + 2].mean() + if ut < f['umin'] - 5 or ut > f['umax'] + 5: + continue + sl = np.polyfit(ys, xs, 1)[0] if ys.max() - ys.min() >= 3 else 0.0 + if best is None or len(xs) > best['area']: + best = dict(utop=ut, vtop=vt, slope=sl, area=len(xs)) + return best + + +def head_cup(im): + """Cup blob on the counter top in the head image: bottom-centre pixel.""" + m = grey_mask(im, lo=60, hi=245, sat=25) + er = edge_rows(im) + top = er[0] if er is not None else 84 + m[top - 1:] = False + blob = largest(m) + if blob is None or blob.sum() < 20: + return None + ys, xs = np.nonzero(blob) + vb = ys.max() + return dict(ub=xs[ys >= vb - 2].mean(), vb=vb, u=xs.mean()) + + +def head_to_table(u, v): + """Pixel of the head camera (look pose) -> point on the counter plane, pelvis frame.""" + Cm = torso_T((0, 0, HEAD_WAIST + HEAD_DPITCH)) @ _T(rz(HEAD_DYAW) @ ry(0.8307767), (0.0576235, 0.01753, 0.42987)) + f = 42.0 / np.tan(np.radians(HEAD_FOVY) / 2) + d = Cm[:3, :3] @ np.array([1.0, -(u - 42) / f, -(v - 42) / f]) + o = Cm[:3, 3] + t = (TABLE_Z - o[2]) / d[2] + return o + t * d + + +# ----------------------------------------------------------------------------- policy + +class Policy: + """Scripted state machine, written as a generator of actions.""" + + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.a = np.asarray(tools.hold_action(), dtype=np.float64) + self.a[5:19] = 0.0 + self.a[19:21] = 0.0 + self.tgt = None # base target (x, y, yaw) in world frame + self.gen = self.script() + self.log = [] + self.phase = '' + + # --- low level helpers + def lo(self): + return self.obs['low_dim_obs'] + + def pelvis(self): + o = self.lo() + return float(o[21]), float(o[22]), float(o[24]) + + def fingers(self): + return float(np.mean(self.lo()[10:12])) + + def base_cmd(self): + a = self.a + if self.tgt is None: + a[0] = a[1] = a[3] = 0.0 + return 0.0 + x, y, yaw = self.pelvis() + tx, ty, tyaw = self.tgt + ex, ey = tx - x, ty - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + vx, vy = np.clip(1.5 * bx, -0.3, 0.3), np.clip(1.5 * by, -0.3, 0.3) + sp = np.hypot(vx, vy) + dist = np.hypot(bx, by) + if sp < 0.06: + if dist > 0.015: + vx, vy = vx / (sp + 1e-9) * 0.06, vy / (sp + 1e-9) * 0.06 + else: + vx = vy = 0.0 + a[0], a[1] = vx, vy + a[3] = np.clip(2.0 * (tyaw - yaw), -0.5, 0.5) + return dist + + def act(self, obs, tools): + self.obs = obs + try: + next(self.gen) + except StopIteration: + pass + except Exception as exc: # never crash an episode: freeze in place instead + self.log.append(('error', repr(exc))) + self.gen = iter(()) + self.base_cmd() + return self.a.astype(np.float32).tolist() + + def wait(self, n): + for _ in range(n): + yield + + def move_arm(self, q, n): + q0 = self.a[5:12].copy() + q = np.asarray(q, float) + for i in range(n): + f = 0.5 - 0.5 * np.cos(np.pi * (i + 1) / n) + self.a[5:12] = q0 + f * (q - q0) + yield + + def set_grip(self, g, n): + g0 = self.a[19] + for i in range(n): + self.a[19] = g0 + (g - g0) * (i + 1) / n + yield + + def ikL(self, pos, R, q0, lean=0.0): + # when leaning, use the measured torso pitch so the wrist camera keeps its attitude + wp = WP[2] if lean <= 0 else float(self.lo()[2]) + q, err = ik('L', pos, R, q0, (0, 0, wp)) + return q + + def set_lean(self, lean, n): + p0 = self.a[4] + for i in range(n): + self.a[4] = p0 + (lean - p0) * (i + 1) / n + yield + + # --- the task + def script(self): + a = self.a + # 1. look: lean back and find the cup + a[4] = -0.2 + yield from self.wait(55) + hc = head_cup(self.tools.image('head')) + x0, y0, yaw0 = self.pelvis() + if hc is not None: + p = head_to_table(hc['ub'], hc['vb']) + cx, cy = p[0] + CUP_R, p[1] + else: + cx, cy = X_CUP, Y_CUP + cup_w = np.array([x0 + cx, y0 + cy]) # world (yaw ~ 0 at start) + self.log.append(('look', hc and (round(hc['ub'], 1), int(hc['vb'])), np.round(cup_w, 3))) + # 2. step to the counter, cup in front of the left arm + a[4] = 0.0 + self.tgt = (min(X_STAND_MAX, cup_w[0] - X_CUP), cup_w[1] - Y_CUP, 0.0) + for i in range(160): + d = self.base_cmd() + yield + if i > 30 and d < 0.015: + break + px, py, _ = self.pelvis() + C = np.array([cup_w[0] - px, cup_w[1] - py, Z_GRASP]) + self.log.append(('stand', np.round([px, py], 3), np.round(C[:2], 3))) + # far cups: lean the torso forward while reaching for the handle + lean = float(np.clip(3.0 * (C[0] - 0.50), 0.0, 0.4)) + # 3. raise the arm over the counter, go to the pre-grasp pose + yield from self.move_arm(Q_UP, 40) + psi = 0.0 + d = 0.26 + P = C - [d, 0, 0] + a[4] = lean + yield from self.wait(25 if lean > 0 else 0) + q = self.ikL(P + [0, 0, 0.05], rz(psi), Q_PRE, lean) + yield from self.move_arm(q, 40) + for attempt in range(3): + # 4. servo onto the handle + for it in range(32): + dirv = np.array([np.cos(psi), np.sin(psi), 0.0]) + perp = np.array([-np.sin(psi), np.cos(psi), 0.0]) + P = C - d * dirv + P[2] = Z_GRASP + q = self.ikL(P, rz(psi), q, lean) + yield from self.move_arm(q, 10 if it else 25) + yield from self.wait(5) + im = self.tools.image('left_wrist') + f = wrist_cup(im) + if f is None: + self.log.append(('servo', it, 'no cup')) + d += 0.02 + continue + s = streak_near(im, f) + uh = s['utop'] if s else f['u'] + sl = s['slope'] if s else 0.0 + self.log.append(('servo', it, round(d, 3), round(np.degrees(psi), 1), np.round(C[:2], 3), + round(f['u'], 1), int(f['vmax']), s and round(s['utop'], 1), round(sl, 2))) + eu = uh - 42 + C = C - np.clip(0.0045 * (d - 0.02), 0.0004, 0.0011) * eu * perp + if abs(sl) > 0.15 and d > 0.15 and abs(eu) < 12: + psi = psi + np.clip(0.35 * sl, -0.2, 0.2) + if abs(eu) < 6 and abs(sl) < 0.3: + if f['vmax'] < 50: + d -= 0.015 + else: + break + # 5. push over the handle and grasp + dirv = np.array([np.cos(psi), np.sin(psi), 0.0]) + for k in range(4): + P = P + 0.01 * dirv + q = self.ikL(P, rz(psi), q, lean) + yield from self.move_arm(q, 10) + yield from self.set_grip(1.0, 25) + yield from self.wait(10) + self.log.append(('grasp', attempt, np.round(P, 3), round(np.degrees(psi), 1), round(self.fingers(), 4))) + if self.fingers() > -0.017: + break + # missed: open, back off and look again + yield from self.set_grip(0.0, 12) + d = float(np.dot(C - P, dirv)) + 0.08 + q = self.ikL(C - d * dirv + [0, 0, 0.03], rz(psi), q, lean) + yield from self.move_arm(q, 20) + # 6. lift, square up, flip + q = self.ikL(P + [0, 0, 0.10], rz(psi), q, lean) + yield from self.move_arm(q, 40) + self.phase = 'lifted' + q = self.ikL(FLIP_START, np.eye(3), q) + if lean > 0: + yield from self.set_lean(0.0, 30) + yield from self.move_arm(q, 40) + yield from self.wait(5) + self.log.append(('lifted', round(self.fingers(), 4))) + path, w = flip_path('L', q, np.array([1.0, 0, 0]), +1) + for qq in path[1:]: + yield from self.move_arm(qq, 8) + yield from self.wait(10) + self.log.append(('flipped', round(self.fingers(), 4), round(w, 3))) + # 7. set it down + M = tip_pose('L', a[5:12], WP) + Pc, Rc = M[:3, 3].copy(), M[:3, :3].copy() + for z in np.arange(Pc[2] - 0.01, TABLE_Z, -0.01): + Pt = Pc.copy() + Pt[2] = z + q, _ = ik('L', Pt, Rc, q, WP, wrot=0.5) + yield from self.move_arm(q, 8) + yield from self.wait(60) + yield from self.set_grip(0.0, 15) + yield from self.wait(10) + for k in range(8): + Pt = Pc.copy() + Pt[2] = TABLE_Z + 0.005 * k + Pt[0] -= 0.012 * (k + 1) + q, _ = ik('L', Pt, Rc, q, WP, wrot=0.5) + yield from self.move_arm(q, 8) + self.log.append(('released',)) + while True: + yield diff --git a/policies/flip_cup/opus-s2/episodes.csv b/policies/flip_cup/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..1def8ad6e3b36d61d04ecb3f6ca8a4e82931f1e5 --- /dev/null +++ b/policies/flip_cup/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,720,success,0 +620001,0,1850,timeout,0 +620002,1,726,success,0 +620003,1,730,success,0 +620004,1,1568,success,0 +620005,1,713,success,0 +620006,1,728,success,0 +620007,1,721,success,0 +620008,1,712,success,0 +620009,1,720,success,0 +620010,1,718,success,0 +620011,1,718,success,0 +620012,1,713,success,0 +620013,1,715,success,0 +620014,1,713,success,0 +620015,1,715,success,0 +620016,1,725,success,0 +620017,1,720,success,0 +620018,1,728,success,0 +620019,1,718,success,0 +620020,1,720,success,0 +620021,1,718,success,0 +620022,1,715,success,0 +620023,1,718,success,0 +620024,1,714,success,0 +620025,1,713,success,0 +620026,1,713,success,0 +620027,1,713,success,0 +620028,1,720,success,0 +620029,1,725,success,0 +620030,1,720,success,0 +620031,0,1850,timeout,0 +620032,1,723,success,0 +620033,1,718,success,0 +620034,1,713,success,0 +620035,1,730,success,0 +620036,1,713,success,0 +620037,1,714,success,0 +620038,1,723,success,0 +620039,1,718,success,0 +620040,1,744,success,0 +620041,1,718,success,0 +620042,1,722,success,0 +620043,1,722,success,0 +620044,1,715,success,0 +620045,1,720,success,0 +620046,1,722,success,0 +620047,1,718,success,0 +620048,1,714,success,0 +620049,1,718,success,0 +620050,1,720,success,0 +620051,1,713,success,0 +620052,1,714,success,0 +620053,1,716,success,0 +620054,1,726,success,0 +620055,1,714,success,0 +620056,1,714,success,0 +620057,1,720,success,0 +620058,1,718,success,0 +620059,1,714,success,0 +620060,1,713,success,0 +620061,1,713,success,0 +620062,1,722,success,0 +620063,1,720,success,0 +620064,1,723,success,0 +620065,1,718,success,0 +620066,1,807,success,0 +620067,1,723,success,0 +620068,1,722,success,0 +620069,1,720,success,0 +620070,1,715,success,0 +620071,1,715,success,0 +620072,1,721,success,0 +620073,1,726,success,0 +620074,1,713,success,0 +620075,1,720,success,0 +620076,1,724,success,0 +620077,1,720,success,0 +620078,1,744,success,0 +620079,1,721,success,0 +620080,1,729,success,0 +620081,1,718,success,0 +620082,1,715,success,0 +620083,0,1850,timeout,0 +620084,1,715,success,0 +620085,1,739,success,0 +620086,1,720,success,0 +620087,1,718,success,0 +620088,1,715,success,0 +620089,1,721,success,0 +620090,1,722,success,0 +620091,1,720,success,0 +620092,1,720,success,0 +620093,1,718,success,0 +620094,1,720,success,0 +620095,1,722,success,0 +620096,1,716,success,0 +620097,1,721,success,0 +620098,1,722,success,0 +620099,1,714,success,0 diff --git a/policies/flip_cup/opus-s2/policy.py b/policies/flip_cup/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5f9ebf7753519f1e1c7e7a63a7fc6202846e4049 --- /dev/null +++ b/policies/flip_cup/opus-s2/policy.py @@ -0,0 +1,379 @@ +"""Flip-cup policy for the G1: one-arm side grasp, 180 degree roll, set down. + +Pipeline + 1. lean back, find the cup in the head camera, intersect the ray through + its foot with the counter plane -> cup position (world frame). + 2. lean the torso forward in proportion to the cup distance (reach), pick + the arm on the cup's side, open the gripper and approach the cup + horizontally from the robot side (this usually catches the handle), + close; if the gripper closed on nothing, reopen, push 2.5 cm further and + close again (up to 3 times). + 3. lift, bring the cup in to a comfortable spot, rotate the hand by pi about + the (horizontal) approach axis, lower, open and pull the hand back. + 4. if the hand turns out to be empty after lifting, back off, re-home the + arm and run the whole thing once more. +Arm motions are Cartesian (hand pose, world frame, converted to the pelvis +frame every step) solved with a small numerical IK on a hand-written G1 +kinematic model; a joint-space integral term removes gravity sag. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +# ----------------------------------------------------------------- kinematics + + +def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def rpy(r, p, y): + return rz(y) @ ry(p) @ rx(r) + + +def rot_axis(axis, th): + axis = np.asarray(axis, float) + axis = axis / np.linalg.norm(axis) + K = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]]) + return np.eye(3) + np.sin(th) * K + (1 - np.cos(th)) * K @ K + + +def torso(waist): + R = rz(waist[0]) + p = R @ np.array([-0.0039635, 0, 0.035]) + R = R @ rx(waist[1]) + p = p + R @ np.array([0, 0, 0.019]) + R = R @ ry(waist[2]) + return R, p + + +ARM = [ + ((0.0039563, 0.10022, 0.24778), (0.27931, 5.4949e-05, -0.00019159), 'y'), + ((0, 0.038, -0.013831), (-0.27925, 0, 0), 'x'), + ((0, 0.00624, -0.1032), (0, 0, 0), 'z'), + ((0.015783, 0, -0.080518), (0, 0, 0), 'y'), + ((0.100, 0.00188791, -0.010), (0, 0, 0), 'x'), + ((0.038, 0, 0), (0, 0, 0), 'y'), + ((0.046, 0, 0), (0, 0, 0), 'z'), +] +AX = {'x': rx, 'y': ry, 'z': rz} +TOOL = 0.14 + +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def arm_fk(q, side, waist, tool=TOOL, frames=False): + R, p = torso(waist) + s = 1 if side == 'left' else -1 + fr = [] + for (xyz, r, ax), qi in zip(ARM, q): + p = p + R @ np.array([xyz[0], s * xyz[1], xyz[2]]) + R = R @ rpy(s * r[0], r[1], s * r[2]) @ AX[ax](qi) + fr.append(p) + pt = p + R @ np.array([tool, 0, 0]) + if frames: + return R, pt, fr + return R, pt + + +def limits(side): + if side == 'left': + return LO.copy(), HI.copy() + lo, hi = LO.copy(), HI.copy() + lo[1], hi[1] = -HI[1], -LO[1] + return lo, hi + + +def ik(p_t, R_t, side, q0, waist, qref=None, w_rot=0.5, reg=0.01): + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-4, hi - 1e-4) + qref = q0 if qref is None else qref + + def res(q): + R, p = arm_fk(q, side, waist) + return np.concatenate([p - p_t, w_rot * (R - R_t).ravel(), reg * (q - qref)]) + + sol = least_squares(res, q0, bounds=(lo, hi), max_nfev=60) + R, p = arm_fk(sol.x, side, waist) + return sol.x, float(np.linalg.norm(p - p_t)) + + +# ----------------------------------------------------------------- head camera + +CAM_OFF = np.array([0.0197, -0.0037, 0.4408]) +CAM_PITCH = 1.0371 +CAM_FOVY = 50.0 +COUNTER_Z = 0.16 # counter top above the pelvis origin (m) +CUP_R = 0.04 +PELVIS_PITCH_GAIN = -0.138 # pelvis pitch (rad) per rad of torso-pitch command above -0.2 + + +def head_cam(waist): + Rt, pt = torso(waist) + return Rt @ ry(CAM_PITCH), pt + Rt @ CAM_OFF + + +def pix_ray(uv, R): + f = 42.0 / np.tan(np.radians(CAM_FOVY) / 2) + d = np.array([1.0, (42.0 - uv[0]) / f, (42.0 - uv[1]) / f]) + d = R @ d + return d / np.linalg.norm(d) + + +def detect_cup(im): + """Return (u_center, v_bottom) of the cup in the head image, or None.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + s = hsv[..., 1].astype(int) + v = hsv[..., 2].astype(int) + m = (s < 40) & (v < 235) & (v > 60) + m[27:] = False + n, lab, st, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8)) + if n <= 1: + return None + k = 1 + int(np.argmax(st[1:, 4])) + if st[k, 4] < 20: + return None + ys, xs = np.where(lab == k) + vb = ys.max() + # centre column from the lower part of the blob (handle side bias is small) + low = ys >= vb - 4 + return float(xs[low].mean()), float(vb) + 0.5 + + +# ----------------------------------------------------------------- policy + + +class Policy: + GRASP_DEPTH = 0.0 # extra push past the estimated cup centre along the approach + LEAN_GAIN = 5.0 + LEAN_MAX = 0.35 + BRING_X = 0.43 + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.a = self.hold.copy() + self.a[4] = -0.2 + self.phase = 'look' + self.phase_t = 0 + self.cup_w = None + self.side = None + self.q = None + self.integ = np.zeros(7) + self.segs = [] + self.debug = [] + self.cup_hist = [] + self.retries = 0 + self.attempt = 0 + self.seg_i = 0 + self.seg_t = 0 + + # -- frames + @staticmethod + def pelvis(o): + return o[21:24].astype(float), float(o[24]) + + def Rpw(self, o): + """Pelvis->world rotation: measured yaw plus the (unobserved) pelvis + pitch the controller adds when the torso leans, relative to the + lean-back pose the camera was calibrated in.""" + th = PELVIS_PITCH_GAIN * (self.a[4] + 0.2) + return rz(self.pelvis(o)[1]) @ ry(th) + + def w2p(self, o, pw): + p, _ = self.pelvis(o) + return self.Rpw(o).T @ (np.asarray(pw) - p) + + def p2w(self, o, pp): + p, _ = self.pelvis(o) + return p + self.Rpw(o) @ np.asarray(pp) + + def arm_sl(self): + return (slice(5, 12), slice(3, 10)) if self.side == 'left' else (slice(12, 19), slice(12, 19)) + + def estimate_cup(self, o): + u, v = np.median(np.array(self.cup_hist), axis=0) + Rc, pc = head_cam(o[0:3]) + r = pix_ray((u, v), Rc) + tt = (COUNTER_Z - pc[2]) / r[2] + pf = pc + tt * r + hd = np.array([r[0], r[1], 0.0]) + hd /= np.linalg.norm(hd) + cup = pf + CUP_R * hd + cup[2] = COUNTER_Z + return cup, (u, v) + + # -- motion segments, all targets in the world frame + def plan(self, o): + pb, yawb = self.pelvis(o) + c = rz(-yawb) @ (self.cup_w - pb) # level, yaw-aligned body frame + s = 1 if self.side == 'left' else -1 + sh = np.array([0.0, s * 0.15, 0.29]) + d = c - sh + yaw = np.arctan2(d[1], d[0]) + R0 = rz(yaw) + ax = R0[:, 0] + zg = COUNTER_Z + 0.045 + cg = np.array([c[0], c[1], zg]) + self.GRASP_DEPTH * ax + pre = cg - 0.14 * ax + lift = cg + np.array([0, 0, 0.08]) + # flip and set down at a comfortable spot closer to the body + cb = cg.copy() + if cb[0] > self.BRING_X: + cb = cb - (cb[0] - self.BRING_X) / ax[0] * ax + bring = cb + np.array([0, 0, 0.08]) + Rf = rot_axis(ax, s * np.pi) @ R0 + P = lambda x: pb + rz(yawb) @ np.asarray(x) + Rw = lambda R: rz(yawb) @ R + self.ax_w = rz(yawb) @ ax + self.flip_sign = s + return [ + dict(n=60, p=P([0.22, s * 0.20, zg]), R=Rw(R0), g=0.0, tag='raise'), + dict(n=50, p=P(pre), R=Rw(R0), g=0.0, tag='pre'), + dict(n=20, p=P(pre), R=Rw(R0), g=0.0, tag='settle'), + dict(n=70, p=P(cg), R=Rw(R0), g=0.0, tag='approach'), + dict(n=40, p=P(cg), R=Rw(R0), g=1.0, tag='close'), + dict(n=50, p=P(lift), R=Rw(R0), g=1.0, tag='lift'), + dict(n=50, p=P(bring), R=Rw(R0), g=1.0, tag='bring'), + dict(n=150, p=P(bring), R=('rot', self.ax_w, s * np.pi), g=1.0, tag='flip'), + dict(n=60, p=P(cb + np.array([0, 0, 0.012])), R=Rw(Rf), g=1.0, tag='lower'), + dict(n=40, p=P(cb + np.array([0, 0, 0.012])), R=Rw(Rf), g=0.0, tag='open'), + dict(n=60, p=P(cb - 0.16 * ax + np.array([0, 0, 0.012])), R=Rw(Rf), g=0.0, tag='retreat'), + dict(n=60, p=P([0.20, s * 0.22, zg + 0.05]), R=Rw(Rf), g=0.0, tag='away'), + dict(n=10 ** 6, p=P([0.20, s * 0.22, zg + 0.05]), R=Rw(Rf), g=0.0, tag='wait'), + ] + + def start_move(self, o): + self.segs = self.plan(o) + sl, ml = self.arm_sl() + self.q = o[ml].copy() + R, p = arm_fk(self.q, self.side, o[0:3]) + self.p_start = self.p2w(o, p) + self.R_start = self.Rpw(o) @ R + self.seg_i = 0 + self.seg_t = 0 + self.phase = 'move' + + def act(self, obs, tools): + try: + return self._act(obs, tools) + except Exception: # never crash an episode: hold the last command + self.phase = 'idle' + return self.a.astype(np.float32) + + def _act(self, obs, tools): + o = np.asarray(obs['low_dim_obs'], dtype=np.float64) + t = int(obs['t']) + a = self.a + a[0] = a[1] = a[3] = 0.0 + self.phase_t += 1 + if self.phase == 'look': + if self.phase_t >= 45: + det = detect_cup(tools.image('head')) + if det is not None: + self.cup_hist.append(det) + if self.phase_t >= 52 and self.cup_hist: + cup, uv = self.estimate_cup(o) + self.cup_w = self.p2w(o, cup) + self.side = 'left' if cup[1] > 0 else 'right' + self.debug.append(dict(t=t, phase=self.phase, det=uv, cup_p=cup.copy(), side=self.side)) + self.pitch_cmd = float(np.clip(-0.2 + (cup[0] - 0.40) * self.LEAN_GAIN, -0.2, self.LEAN_MAX)) + a[4] = self.pitch_cmd + self.phase, self.phase_t = 'lean', 0 + elif self.phase_t > 120: # nothing seen: give up gracefully + self.phase = 'idle' + return a.astype(np.float32) + + if self.phase == 'lean': + if self.phase_t >= 60: + self.start_move(o) + return a.astype(np.float32) + + if self.phase == 'idle': + return a.astype(np.float32) + + if self.phase == 'home': + sl, _ = self.arm_sl() + s = min(1.0, self.phase_t / 80.0) + a[sl] = (1 - s) * self.q_from + s * self.q_home + a[19 if self.side == 'left' else 20] = 0.6 + a[4] = -0.2 + if self.phase_t >= 80: + self.phase, self.phase_t = 'look', 0 + self.cup_hist = [] + self.retries = 0 + self.integ = np.zeros(7) + return a.astype(np.float32) + + # ---- execute arm segments + seg = self.segs[self.seg_i] + self.seg_t += 1 + s = min(1.0, self.seg_t / seg['n']) + s_smooth = 0.5 - 0.5 * np.cos(np.pi * s) + pw = (1 - s_smooth) * self.p_start + s_smooth * seg['p'] + if isinstance(seg['R'], tuple): + _, ax, ang = seg['R'] + Rw = rot_axis(ax, ang * s_smooth) @ self.R_start + else: + Rw = self.interp_R(self.R_start, seg['R'], s_smooth) + p = self.w2p(o, pw) + R = self.Rpw(o).T @ Rw + sl, ml = self.arm_sl() + self.q, err = ik(p, R, self.side, self.q, o[0:3]) + self.integ = np.clip(self.integ + 0.05 * (self.q - o[ml]), -0.15, 0.15) + a[sl] = self.q + self.integ + gi = 19 if self.side == 'left' else 20 + a[gi] = seg['g'] if seg['tag'] != 'close' else min(1.0, self.seg_t / 15.0) + if self.seg_t % 10 == 0: + self.debug.append(dict(t=t, tag=seg['tag'], p=p.copy(), err=err)) + if self.seg_t >= seg['n'] and self.seg_i < len(self.segs) - 1: + self.p_start = seg['p'] + self.R_start = Rw + if seg['tag'] == 'close' and o[50 if self.side == 'left' else 51] > 0.95 and self.retries < 3: + # closed on nothing: reopen, push 2.5 cm further, close again + self.retries += 1 + p2 = seg['p'] + 0.025 * self.ax_w + extra = [dict(n=20, p=seg['p'], R=seg['R'], g=0.0, tag='reopen'), + dict(n=25, p=p2, R=seg['R'], g=0.0, tag='advance'), + dict(n=40, p=p2, R=seg['R'], g=1.0, tag='close')] + self.segs[self.seg_i + 1:self.seg_i + 1] = extra + self.debug.append(dict(t=t, retry=self.retries)) + if seg['tag'] == 'bring' and o[50 if self.side == 'left' else 51] > 0.95 and self.attempt == 0: + # nothing in the hand: back off, re-home the arm and start over + up = np.array([0.0, 0.0, 0.03]) + self.segs = self.segs[:self.seg_i + 1] + [ + dict(n=15, p=seg['p'], R=Rw, g=0.0, tag='reopen'), + dict(n=50, p=seg['p'] - 0.15 * self.ax_w + up, R=Rw, g=0.0, tag='backoff'), + dict(n=1, p=seg['p'] - 0.15 * self.ax_w + up, R=Rw, g=0.0, tag='abort_end'), + ] + self.debug.append(dict(t=t, abort=True)) + if self.segs[self.seg_i + 1]['tag'] == 'abort_end': + self.attempt += 1 + self.q_from = a[sl].copy() + self.q_home = self.hold[sl].copy() + self.phase, self.phase_t = 'home', 0 + return a.astype(np.float32) + self.seg_i += 1 + self.seg_t = 0 + return a.astype(np.float32) + + @staticmethod + def interp_R(R0, R1, s): + Rd = R0.T @ R1 + ang = np.arccos(np.clip((np.trace(Rd) - 1) / 2, -1, 1)) + if ang < 1e-6: + return R1 if s >= 1 else R0 + ax = np.array([Rd[2, 1] - Rd[1, 2], Rd[0, 2] - Rd[2, 0], Rd[1, 0] - Rd[0, 1]]) / (2 * np.sin(ang)) + return R0 @ rot_axis(ax, ang * s) diff --git a/policies/flip_cup/opus-s3/episodes.csv b/policies/flip_cup/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2cf5707616ad0e1533276fb8132ead6912482b57 --- /dev/null +++ b/policies/flip_cup/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,691,success,0 +620001,1,990,success,0 +620002,1,695,success,0 +620003,1,693,success,0 +620004,1,779,success,0 +620005,1,693,success,0 +620006,1,692,success,0 +620007,1,699,success,0 +620008,1,691,success,0 +620009,1,886,success,0 +620010,1,705,success,0 +620011,1,729,success,0 +620012,1,692,success,0 +620013,1,695,success,0 +620014,1,751,success,0 +620015,1,692,success,0 +620016,1,695,success,0 +620017,1,695,success,0 +620018,0,1850,timeout,0 +620019,1,717,success,0 +620020,1,707,success,0 +620021,1,692,success,0 +620022,1,693,success,0 +620023,1,731,success,0 +620024,1,697,success,0 +620025,1,692,success,0 +620026,1,886,success,0 +620027,1,711,success,0 +620028,1,726,success,0 +620029,1,694,success,0 +620030,1,728,success,0 +620031,0,1850,timeout,0 +620032,1,694,success,0 +620033,1,700,success,0 +620034,1,693,success,0 +620035,1,705,success,0 +620036,1,692,success,0 +620037,1,742,success,0 +620038,1,694,success,0 +620039,1,706,success,0 +620040,1,693,success,0 +620041,1,709,success,0 +620042,1,694,success,0 +620043,1,1082,success,0 +620044,1,747,success,0 +620045,1,719,success,0 +620046,1,697,success,0 +620047,0,1850,timeout,0 +620048,1,692,success,0 +620049,1,694,success,0 +620050,1,694,success,0 +620051,1,693,success,0 +620052,0,1850,timeout,0 +620053,1,1182,success,0 +620054,1,714,success,0 +620055,1,707,success,0 +620056,1,691,success,0 +620057,1,694,success,0 +620058,1,718,success,0 +620059,0,1850,timeout,0 +620060,1,706,success,0 +620061,1,702,success,0 +620062,1,693,success,0 +620063,1,693,success,0 +620064,1,694,success,0 +620065,1,702,success,0 +620066,1,886,success,0 +620067,0,1850,timeout,0 +620068,1,696,success,0 +620069,1,693,success,0 +620070,1,706,success,0 +620071,1,693,success,0 +620072,1,692,success,0 +620073,1,886,success,0 +620074,1,693,success,0 +620075,1,695,success,0 +620076,1,692,success,0 +620077,1,691,success,0 +620078,1,691,success,0 +620079,1,707,success,0 +620080,1,691,success,0 +620081,1,708,success,0 +620082,1,730,success,0 +620083,1,787,success,0 +620084,1,730,success,0 +620085,1,779,success,0 +620086,1,694,success,0 +620087,1,694,success,0 +620088,1,703,success,0 +620089,1,694,success,0 +620090,1,717,success,0 +620091,1,694,success,0 +620092,1,698,success,0 +620093,1,716,success,0 +620094,1,696,success,0 +620095,1,701,success,0 +620096,1,691,success,0 +620097,1,692,success,0 +620098,1,695,success,0 +620099,1,705,success,0 diff --git a/policies/flip_cup/opus-s3/policy.py b/policies/flip_cup/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..36057c276ffc092e053ed6d1d8636aa341c83a34 --- /dev/null +++ b/policies/flip_cup/opus-s3/policy.py @@ -0,0 +1,348 @@ +"""Flip-cup policy for the G1: grab the cup by its handle, roll it 180 degrees, set it down. + +Pipeline (all hand-written; constants tuned by running episodes): + 1. Lean the torso back and take one head-camera snapshot. The cup (grey) is segmented + against the bright counter. The lowest point of the cup blob is back-projected through + a pinhole model of the head camera onto the counter plane (cup position); the bright + handle stripe relative to the body gives the handle direction. Together they give the + handle grasp point and the approach yaw. + 2. Pick the arm on the cup's / handle's side, raise it, lean forward for reach, hover + behind the handle with the gripper horizontal (fingers closing sideways), advance + slowly so the handle slides between the fingers, close. If the gripper closed on + nothing (or on the wide body), back off and retry with a shifted target. + 3. Lift, roll the wrist 180 degrees about the (horizontal) gripper axis -> the cup is + the right way up, lower it onto the counter, open, retreat. +Arm targets are Cartesian (world frame, re-expressed in the measured pelvis frame every +step); joint angles come from a small numerical IK on the G1 arm chain, with an integral +term that removes the steady-state sag of the position-controlled arm. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +# ----------------------------------------------------------------------------- kinematics + + +def Rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def Ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def Rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +GRIP = 0.13 # wrist-yaw joint to grasp centre +Q_LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +Q_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +MIR = np.array([1, -1, -1, 1, -1, 1, -1]) # left <-> right arm joint mirroring + + +def arm_fk(q, side="L", torso_pitch=0.0): + """Grasp-centre position and rotation in the (yaw-aligned) pelvis frame (G1 arm chain).""" + sg = 1 if side == "L" else -1 + p = np.array([-0.0039635, 0, 0.044]) + R = Ry(torso_pitch) + p = p + R @ np.array([0.0039563, sg * 0.10022, 0.24778]) + R = R @ Rx(sg * 0.27931) @ Ry(q[0]) + p = p + R @ np.array([0, sg * 0.038, -0.013831]) + R = R @ Rx(-sg * 0.27925) @ Rx(q[1]) + p = p + R @ np.array([0, sg * 0.00624, -0.1032]) + R = R @ Rz(q[2]) + p = p + R @ np.array([0.015783, 0, -0.080518]) + R = R @ Ry(q[3]) + p = p + R @ np.array([0.100, sg * 0.00188791, -0.010]) + R = R @ Rx(q[4]) + p = p + R @ np.array([0.038, 0, 0]) + R = R @ Ry(q[5]) + p = p + R @ np.array([0.046, 0, 0]) + R = R @ Rz(q[6]) + p = p + R @ np.array([GRIP, 0, 0]) + return p, R + + +def joint_limits(side): + lo, hi = Q_LO.copy(), Q_HI.copy() + if side == "R": + lo[1], hi[1] = max(-Q_HI[1], Q_LO[1]), min(-Q_LO[1], Q_HI[1]) + return lo, hi + + +def ik(target_p, target_R, side, q0, torso_pitch, w_ori=0.5, reg=0.01): + """Least-squares IK: grasp-centre position + gripper direction (x) + finger axis (y).""" + lo, hi = joint_limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-6, hi - 1e-6) + + def res(q): + p, R = arm_fk(q, side, torso_pitch) + return np.concatenate([ + p - target_p, + w_ori * (R[:, 0] - target_R[:, 0]), + w_ori * (R[:, 1] - target_R[:, 1]), + reg * (q - q0), + ]) + + return least_squares(res, q0, bounds=(lo, hi), xtol=1e-6, ftol=1e-8).x + + +def grip_R(yaw, pitch=0.0, roll=0.0): + """Gripper frame: x = pointing direction, y = finger-closing axis.""" + return Rz(yaw) @ Ry(pitch) @ Rx(roll) + + +def world_to_pelvis(pw, lo): + return Rz(-lo[24]) @ (np.asarray(pw, float) - lo[21:24]) + + +# ----------------------------------------------------------------------------- vision + + +def head_cup(im): + """Cup blob in the lean-back head image: bottom point, body extent, handle column.""" + a = im.astype(int) + R, G, B = a[..., 0], a[..., 1], a[..., 2] + mx = np.maximum(np.maximum(R, G), B) + mn = np.minimum(np.minimum(R, G), B) + brown = (R - B > 25) & (R < 220) & (R > 80) & (G > B) # counter front edge + rows = np.nonzero(brown.sum(1) > 40)[0] + edge = int(rows.min()) if len(rows) else 30 + gray = (mx - mn < 22) & (mx > 50) & (mx < 235) + gray[edge - 1:] = False + n, lab, st, _ = cv2.connectedComponentsWithStats(gray.astype(np.uint8)) + if n <= 1: + return None + i = 1 + int(np.argmax(st[1:, 4])) + m = lab == i + if m.sum() < 20: + return None + ys, xs = np.nonzero(m) + bot = int(ys.max()) + top = int(ys.min()) + bx = float(xs[ys >= bot - 2].mean()) + dark = m & (mx < 165) + lefts, rights = [], [] + for y in range(max(top, bot - 10), bot - 1): + c = np.nonzero(dark[y])[0] + if len(c) >= 4: + lefts.append(c.min()) + rights.append(c.max()) + if lefts: + bl, br = float(np.median(lefts)), float(np.median(rights)) + else: + bl, br = float(xs.min()), float(xs.max()) + bc = 0.5 * (bl + br) + hw = max(3.0, 0.5 * (br - bl)) + y0 = top + (3 if top > 0 else 0) + cand = np.zeros_like(m) + xa, xb = int(max(0, bl - 0.9 * hw)), int(min(83, br + 0.9 * hw)) + cand[y0:bot - 2, xa:xb + 1] = True + hand = cand & (mx >= 175) & (mx < 250) & (mx - mn < 30) + hy, hx = np.nonzero(hand) + hu = float(np.median(hx)) if len(hx) >= 3 else bc + return dict(bot=bot, bx=bx, bc=bc, hw=hw, hu=hu) + + +# head camera at the lean-back snapshot (world frame; the start pose is the same every seed) +CAM = np.array([0.1297, -0.0376, 1.2611, 0.8392, 0.0715]) # x, y, z, pitch, yaw +FOC, CPIX = 101.4, 41.5 # 45 deg fov, 84 px +Z_COUNTER = 0.895 + + +def ground_point(u, v): + cx, cy, cz, th, ps = CAM + d = Rz(ps) @ Ry(th) @ np.array([1.0, -(u - CPIX) / FOC, -(v - CPIX) / FOC]) + t = (Z_COUNTER - cz) / d[2] + return np.array([cx, cy, cz]) + t * d + + +# ----------------------------------------------------------------------------- task constants +R_CUP = 0.04 # cup radius +R_GRASP = R_CUP + 0.0156 # cup axis -> handle grasp point +HANDLE_K = 1.6 # handle-centre radius / body radius (handle angle from the image) +PHI_DEAD = 0.45 # treat nearly frontal handles as frontal +PSI_MAX = 0.55 # largest inward approach yaw +Z_GRASP = 0.92 +Z_LIFT = Z_GRASP + 0.12 +Z_PLACE = 0.93 +D_HOVER = 0.08 +Q_RAISE = np.array([-1.4, 0.3, 0.0, -0.5, 0.0, 0.0, 0.0]) +Q_IDLE = np.array([0.3, 0.15, 0.0, 0.2, 0.0, 0.0, 0.0]) +SNAP_T = 40 +G_MISS = 0.93 # gripper state above this after closing: nothing between the fingers +G_WIDE = 0.25 # below this: closed on the wide cup body instead of the handle +MAX_RETRY = 2 + + +class Policy: + def reset(self, obs, tools): + self.raw = np.asarray(tools.hold_action(), dtype=np.float64).copy() + self.t = 0 + self.plan = None + self.seg_i = 0 + self.seg_t = 0 + self.qik = {"L": np.zeros(7), "R": np.zeros(7)} + self.bias = {"L": np.zeros(7), "R": np.zeros(7)} + self.prev_pw = {} + self.seg_start = None + self.q_start = None + self.retries = 0 + + # ------------------------------------------------------------------ planning + def locate(self, r): + """Handle grasp point (world) and the handle's yaw deviation from facing the camera.""" + Pb = ground_point(r["bx"], r["bot"]) + dv = Pb[:2] - CAM[:2] + dv /= np.linalg.norm(dv) + vr = np.array([dv[1], -dv[0]]) # image-right direction on the counter + C = Pb[:2] + R_CUP * dv + phi = float(np.arcsin(np.clip((r["hu"] - r["bc"]) / (HANDLE_K * r["hw"]), -1.0, 1.0))) + if abs(phi) < PHI_DEAD: + phi = 0.0 + uh = np.cos(phi) * (-dv) + np.sin(phi) * vr + G = np.array([*(C + R_GRASP * uh), Z_GRASP]) + psi_dev = float(np.arctan2(-uh[1], -uh[0]) - np.arctan2(dv[1], dv[0])) + return G, psi_dev + + def P(self, G, d, z): + return np.array([G[0] - d * np.cos(self.psi), G[1] - d * np.sin(self.psi), z]) + + def approach_segs(self, G, d0): + side, H = self.side, grip_R(self.psi) + segs = [dict(n=15, side=side, pw=self.P(G, max(d, 0.0), Z_GRASP), R=H) + for d in np.arange(d0 - 0.01, -0.001, -0.01)] + segs.append(dict(n=30, side=side, pw=self.P(G, 0, Z_GRASP), R=H, grip=1.0, check=True)) + return segs + + def tail_segs(self, G): + side, psi, sgn = self.side, self.psi, self.sgn + H, R2 = grip_R(psi), grip_R(psi, 0, sgn * np.pi) + segs = [dict(n=40, side=side, pw=self.P(G, 0, Z_LIFT), R=H, grip=1.0)] + for phi in np.linspace(0, np.pi, 9)[1:]: + segs.append(dict(n=20, side=side, pw=self.P(G, 0, Z_LIFT), R=grip_R(psi, 0, sgn * phi), grip=1.0, w=1.0)) + segs += [ + dict(n=30, side=side, pw=self.P(G, 0, Z_LIFT), R=R2, grip=1.0, w=1.0), + dict(n=60, side=side, pw=self.P(G, 0, Z_PLACE), R=R2, grip=1.0, w=1.0), + dict(n=30, side=side, pw=self.P(G, 0, Z_PLACE), R=R2, grip=0.0, w=1.0), + dict(n=40, side=side, pw=self.P(G, 0.12, Z_PLACE), R=R2, grip=0.0, w=1.0), + dict(n=40, side=side, pw=self.P(G, 0.12, Z_LIFT), R=R2, grip=0.0, w=1.0), + dict(n=10 ** 6, side=side, pw=self.P(G, 0.12, Z_LIFT), R=R2, grip=0.0, w=1.0), + ] + return segs + + def make_plan(self, G, psi_dev=0.0): + X1, Y1 = float(G[0]), float(G[1]) + if psi_dev < -0.35: + side = "L" + elif psi_dev > 0.35: + side = "R" + else: + side = "L" if Y1 >= 0.0 else "R" + if side == "L": + base = float(np.clip(1.5 * (Y1 - 0.15), -0.35, 0.1)) + psi = float(np.clip(base + psi_dev, -PSI_MAX, 0.15)) + self.sgn = 1.0 + else: + base = float(np.clip(1.5 * (Y1 + 0.15), -0.1, 0.35)) + psi = float(np.clip(base + psi_dev, -0.15, PSI_MAX)) + self.sgn = -1.0 + pitch0 = float(np.clip(0.2 + (X1 - 0.65) * 3.0, 0.2, 0.4)) + pitch = max(pitch0, 0.35) if abs(psi) > 0.5 else pitch0 + # the extra lean carries the hand further than the model says: grasp less deep + back = 0.025 * min(1.0, (pitch - pitch0) / 0.15) + G = np.array([X1 - back * np.cos(psi), Y1 - back * np.sin(psi), G[2]]) + self.side, self.psi, self.G = side, psi, G + other = "R" if side == "L" else "L" + H = grip_R(psi) + segs = [ + dict(n=40, side=side, q=Q_RAISE * (MIR if side == "R" else 1), pitch=0.0, grip=0.0), + dict(n=30, side=other, q=Q_IDLE * (MIR if other == "R" else 1), pitch=pitch), + dict(n=60, side=side, pw=self.P(G, D_HOVER, Z_GRASP + 0.07), R=H, jblend=True), + dict(n=30, side=side, pw=self.P(G, D_HOVER, Z_GRASP), R=H), + ] + self.plan = segs + self.approach_segs(G, D_HOVER) + self.tail_segs(G) + + def grasp_check(self, lo): + """After closing: keep going, or replace the rest of the plan with a retry.""" + g = float(lo[50] if self.side == "L" else lo[51]) + self.glog = getattr(self, "glog", []) + [round(g, 2)] + if G_WIDE <= g <= G_MISS or self.retries >= MAX_RETRY: + return + self.retries += 1 + c, s = np.cos(self.psi), np.sin(self.psi) + if g < G_WIDE: # fingers around the body: the handle is nearer than assumed + shift = np.array([-0.025 * c, -0.025 * s, 0.0]) + else: # missed: try beside the first guess, one side then the other + k = 0.015 if self.retries == 1 else -0.03 + shift = np.array([-s * k, c * k, 0.0]) + G = self.G + shift + self.G = G + side, H = self.side, grip_R(self.psi) + retry = [ + dict(n=25, side=side, pw=self.P(G - shift, 0, Z_GRASP), R=H, grip=0.0), + dict(n=25, side=side, pw=self.P(G - shift, 0.06, Z_GRASP), R=H, grip=0.0), + dict(n=25, side=side, pw=self.P(G, 0.06, Z_GRASP), R=H, grip=0.0), + ] + self.plan = self.plan[: self.seg_i + 1] + retry + self.approach_segs(G, 0.06) + self.tail_segs(G) + + # ------------------------------------------------------------------ control + def act(self, obs, tools): + lo = np.asarray(obs["low_dim_obs"], dtype=np.float64) + self.t += 1 + raw = self.raw + if self.plan is None: + raw[4] = -0.2 # lean back with arms at rest and look at the counter + if self.t >= SNAP_T: + r = head_cup(np.asarray(tools.image("head"))) + if r is None: + self.make_plan(np.array([0.64, 0.10, Z_GRASP]), 0.0) + else: + self.make_plan(*self.locate(r)) + return raw.astype(np.float32) + + sg = self.plan[self.seg_i] + side = sg["side"] + sl = slice(5, 12) if side == "L" else slice(12, 19) + mo = slice(3, 10) if side == "L" else slice(12, 19) + n = sg["n"] + i = self.seg_t + if i == 0: + self.q_start = raw[sl].copy() + self.seg_start = self.prev_pw.get(side) + if "pitch" in sg: + raw[4] = sg["pitch"] + if "grip" in sg: + raw[19 if side == "L" else 20] = sg["grip"] + a = min(1.0, (i + 1) / max(1, n * 2 // 3)) + if "q" in sg: + tgt = self.q_start + (sg["q"] - self.q_start) * a + self.qik[side] = tgt + self.bias[side] = np.zeros(7) + raw[sl] = tgt + self.prev_pw.pop(side, None) + else: + pw = sg["pw"] + start = self.seg_start if self.seg_start is not None else pw + pp = world_to_pelvis(start + (pw - start) * a, lo) + q = ik(pp, Rz(-lo[24]) @ sg["R"], side, self.qik[side], float(raw[4]), w_ori=sg.get("w", 0.5)) + self.qik[side] = q + if sg.get("jblend") and a < 1.0: + raw[sl] = self.q_start + (q - self.q_start) * a # smooth first move in joint space + else: + self.bias[side] = np.clip(self.bias[side] + 0.05 * (q - lo[mo]), -0.25, 0.25) + raw[sl] = q + self.bias[side] + self.seg_t += 1 + if self.seg_t >= n: + if "pw" in sg: + self.prev_pw[side] = sg["pw"] + if sg.get("check"): + self.grasp_check(lo) + self.seg_i = min(self.seg_i + 1, len(self.plan) - 1) + self.seg_t = 0 + return raw.astype(np.float32) diff --git a/policies/flip_cutlery/astra-s1/episodes.csv b/policies/flip_cutlery/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..9df0e5a2681bb1b2313332fe38c2836bbf158899 --- /dev/null +++ b/policies/flip_cutlery/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,1,1698,success,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,1,1809,success,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,1,722,success,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/astra-s1/policy.py b/policies/flip_cutlery/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c1978f6ec4fc8480421003b3279f15432493b3c4 --- /dev/null +++ b/policies/flip_cutlery/astra-s1/policy.py @@ -0,0 +1,120 @@ +"""Deterministic visual alignment and joint-space spoon manipulation.""" +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float).copy() + self.phase = 0 + self.age = 0 + self.start = self.a.copy() + self.goal = self.a.copy() + self.goal[4] = -.2 + self.xy = np.array([.26, 0.]) + self.grasp_roll = .45 + self.retries = 0 + self.search = 0 + + def transition(self, phase, goal=None): + self.phase = phase + self.age = 0 + self.start = self.a.copy() + self.goal = self.a.copy() if goal is None else goal.copy() + self.goal[0:2] = 0 + self.goal[3] = 0 + + def pose(self, left=None, right=None, height=None, pitch=None, grip=None): + g = self.a.copy() + g[:2] = 0 + g[3] = 0 + if left is not None: g[5:12] = left + if right is not None: g[12:19] = right + if height is not None: g[2] = height + if pitch is not None: g[4] = pitch + if grip is not None: g[19] = grip + return g + + @staticmethod + def locate_mug(im): + rgb = im.astype(float) + mask = ((np.ptp(rgb, axis=2) < 28) & (rgb.mean(2) < 215) + & (rgb.mean(2) > 35)).astype(np.uint8) + mask[23:] = 0 + n, lab, st, ce = cv2.connectedComponentsWithStats(mask) + ids = [k for k in range(1,n) if st[k,4] > 5 and st[k,2] < 35] + if not ids: return None + k = max(ids, key=lambda j: st[j,4]) + return ce[k,0], st[k,1] + st[k,3] + + def act(self, obs, tools): + q = obs['low_dim_obs'] + self.age += 1 + # Smooth arm and posture motion; gripper closing has its own dwell. + u = min(1., self.age / 60.) + self.a = self.start + u * (self.goal - self.start) + p, t = self.phase, self.age + if p in (0,4): + self.a = self.goal.copy() + if p == 0 and t >= 45: + mug = self.locate_mug(tools.image('head')) + if mug is not None: + cx, bottom = mug + self.xy = np.array([.26 + np.clip((12-bottom)*.0055,-.10,.08), + np.clip((22.64-cx)*.0055,-.30,.22)]) + g = self.pose(left=[-1.7,.3,0,-.8,0,0,0], + right=[-1.7,-.3,0,-.8,0,0,0],pitch=.2,grip=0) + g[20] = 0 + self.transition(1,g) + elif p == 1 and t >= 65: + self.transition(2,self.pose(left=[-1.65,.45,0,.9,0,.2,0], + right=[-1.8,-.3,0,1.1,0,0,0])) + elif p == 2 and t >= 70: + self.transition(3) + elif p == 3: + x,y,z,yaw=q[21:25] + ex,ey=self.xy-[x,y] + world=np.array([.13 if ex > 0 else (-.09 if ex < -.035 else 0), + np.clip(3*ey,-.16,.16) if abs(ey)>.015 else 0]) + if abs(ey) > .025 and 0 < abs(world[1]) < .06: world[1]=np.sign(world[1])*.06 + c,s=np.cos(yaw),np.sin(yaw) + self.a[0:2]=[c*world[0]+s*world[1],-s*world[0]+c*world[1]] + self.a[3]=np.clip(-3*yaw,-.35,.35) + if t >= 130 + int(min(.30,abs(self.xy[1]))*350): + self.transition(4,self.pose(left=[-1.35,self.grasp_roll,0,.9,0,.2,0],grip=0)) + elif p == 4 and t >= 75: + g=self.pose(grip=1) + self.transition(5,g) + elif p == 5: + self.a[19]=1 + if t>=50: + self.transition(6,self.pose(left=[-1.9,self.grasp_roll,0,.9,0,.2,0],grip=1)) + elif p == 6 and t >= 85: + if q[10]+q[11] < -.035 and self.retries < 2: + self.retries += 1 + self.grasp_roll += .055 if self.retries==1 else -.11 + self.transition(4,self.pose(left=[-1.32,self.grasp_roll,0,.9,0,.2,0],grip=0)) + else: + self.transition(7,self.pose(left=[-1.9,self.grasp_roll,0,.9,1.96,.2,0],grip=1)) + elif p == 7 and t>=120: + self.transition(8,self.pose(left=[-1.35,.405,0,.95,1.96,.15,0],grip=1)) + elif p == 8 and t>=100: + self.search=0 + self.transition(9) + elif p == 9 and t>=80: + # Small insertion adjustments, keeping each pose long enough to settle. + self.search += 1 + j=self.search + if j <= 9 and obs['t'] < obs['time_limit']-180: + angle=(j-1)*2.399963229728653 + radius=.025+.007*j + sr=.405+radius*np.sin(angle) + sp=-1.35+radius*np.cos(angle) + elbow=.95+.035*j + yaw=.12*j + g=self.pose(left=[sp,sr,0,elbow,1.96,.15-.035*j,yaw],grip=1) + self.transition(9,g) + else: + self.transition(10,self.pose(grip=0)) + elif p == 10 and t>=70: + self.transition(11,self.pose(left=[-1.9,.45,0,.9,1.9,.2,0],grip=0)) + return self.a.astype(np.float32) diff --git a/policies/flip_cutlery/astra-s2/episodes.csv b/policies/flip_cutlery/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/astra-s2/policy.py b/policies/flip_cutlery/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..60aa4de017c56c2ec8b4632a07dfcbd4ff511141 --- /dev/null +++ b/policies/flip_cutlery/astra-s2/policy.py @@ -0,0 +1,140 @@ +"""Deterministic visual alignment and geometric manipulation controller.""" +import cv2 +import numpy as np +from scipy.spatial.transform import Rotation +from scipy.optimize import least_squares + +OFF=np.array([[0,0,0],[0,.038,-.014],[0,.006,-.103],[.016,0,-.081],[.100,0,0],[.038,0,0],[.046,0,0],[.110,0,0]]) +AX=[1,0,2,1,0,1,2] +LO=np.array([-3,-.162,-2.5,-1.,-1.97,-1.6,-1.6]);HI=np.array([1.8,2.1,2.5,2.09,1.97,1.6,1.6]) +def rot(axis,a): + v=np.zeros(3);v[axis]=a;return Rotation.from_rotvec(v).as_matrix() +def fk(q): + p=np.zeros(3);r=np.eye(3) + for i,a in enumerate(q):p+=r@OFF[i];r=r@rot(AX[i],a) + return p+r@OFF[7],r +def ik(p,r,q,roll_min=.02): + lo=LO.copy();lo[1]=roll_min + def loss(x): + pp,rr=fk(x) + return np.r_[15*(pp-p),Rotation.from_matrix(r.T@rr).as_rotvec(),.003*(x-q)] + return least_squares(loss,np.clip(q,lo+.001,HI-.001),bounds=(lo,HI),max_nfev=150).x + +def mug(im): + mx=im.max(2);mn=im.min(2) + mask=((mx.astype(int)-mn<20)&(mx<215)&(mn>25)).astype('uint8') + white=(im[:,:,0]>220)&(im[:,:,1]>210)&(im[:,:,2]>170) + rows=np.where(white[:65].sum(1)>35)[0] + cut=int(rows.max()+1) if len(rows) else 28 + mask[cut:]=0 + n,l,stats,_=cv2.connectedComponentsWithStats(mask) + candidates=[j for j in range(1,n) if 354] + if not candidates:return None + j=max(candidates,key=lambda j:stats[j,4]);yy,xx=np.where(l==j);yb=max(yy);sel=yy>=yb-8 + return np.array([np.mean(xx[sel]),yb],float) +def projection(uv): + f=55.;th=np.deg2rad(55);h=.35;up=(41.5-uv[1])/f;den=np.sin(th)-np.cos(th)*up + return np.array([h*(np.cos(th)+np.sin(th)*up)/den,-h*(uv[0]-41.5)/f/den]) + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),np.float32);self.stage='view';self.start=0;self.queue=[];self.segment=None;self.uv=None;self.align_good=0;self.walked=False + self.refuv=np.array([46.5825,25.]);self.nom=np.array([-.872,-.162,-.001,.222,-.007,.425,-.004]);self.bias=np.array([-1,-.3,0,.2,0,.4,0])-self.nom + self.initial_uv=mug(tools.image('head'));self.original=False + if self.initial_uv is not None and np.linalg.norm(self.initial_uv-[46.4811,16])<1.5: + self.original=True;self.stage='approach';self.base_goal=obs['low_dim_obs'][21:23]+[-.006,0] + self.enqueue({5:-.9,19:0},80);self.enqueue({6:-.3,10:.4},80) + def enqueue(self,vals,n,ramp=1):self.queue.append((vals,n,ramp)) + def setup_grasp(self,obs,tools): + uv=mug(tools.image('head'));pose=obs['low_dim_obs'][21:25] + delta=np.zeros(2) if uv is None else projection(uv)-projection(self.refuv) + cy=np.cos(pose[3]);sy=np.sin(pose[3]);rr=np.array([[cy,-sy],[sy,cy]]) + self.base_goal=pose[:2]+rr@(delta+[-.024,0]) + self.stage='approach';self.segment=None;self.queue=[] + self.enqueue({4:0,5:-.9,6:0,7:0,8:0,9:0,10:0,11:0,19:0},80) + self.enqueue({6:-.3,10:.4},80) + def setup_manip(self,obs): + q=obs['low_dim_obs'][3:10].astype(float).copy();p,r=fk(q);self.p=p;self.r=r + self.stage='manip';self.segment=None;self.queue=[] + for h in [.04,.08,.14]: + q=ik(p+[0,0,h],r,q);self.enqueue(dict(zip(range(5,12),q)),50,40) + for ang in np.linspace(0,np.pi,13)[1:]: + q=ik(p+[0,0,.14],rot(0,ang)@r,q);self.enqueue(dict(zip(range(5,12),q)),35,30) + if self.original: + q=ik(p+[.08,.04,.12],rot(0,np.pi)@r,q);self.enqueue(dict(zip(range(5,12),q)),100,80) + else:self.enqueue({'cartesian':[.08,.04,.12]},100,80) + self.enqueue({19:0},60) + if self.original: + q=ik(p+[.08,.04,.24],rot(0,np.pi)@r,q);self.enqueue(dict(zip(range(5,12),q)),80,60) + self.enqueue({5:0,6:0,7:0,8:0,9:0,10:0,11:0,4:-.2},150,100) + else: + self.enqueue({'cartesian':[.08,.04,.24]},100,80);self.enqueue({},150) + def act(self,obs,tools): + t=obs['t'];ld=obs['low_dim_obs'];finished_goal=None + if self.stage=='view': + self.a[4]=-.2 + if t>=80: + self.uv=mug(tools.image('head')) + if self.uv is not None and np.linalg.norm(self.uv-self.refuv)<2: + self.setup_grasp(obs,tools) + else: + self.walked=True;self.stage='align';self.start=t + # Raise the working arm clear of the cabinet before translating. + self.a[5]=-.9;self.a[8]=0;self.a[19]=0 + self.a[12]=.3;self.a[15]=1.3 + return self.a.copy() + if self.stage=='align': + if (t-self.start)%8==0:self.uv=mug(tools.image('head')) + self.a[:2]=0;self.a[3]=np.clip(-2.5*ld[24]-.2*ld[49],-.35,.35) + if t-self.start>60: + if self.uv is None:self.a[0]=-.06;self.align_good=0 + else: + er=self.refuv-self.uv + v=np.array([.009*er[1],.006*er[0]]) + if abs(er[0])<2 and abs(er[1])<1.5:self.align_good+=1 + else: + self.align_good=0;v=np.clip(v,-.15,.15);vn=np.linalg.norm(v) + if vn>0 and vn<.065:v*=.065/vn + self.a[:2]=v + if self.align_good>=40 or t-self.start>=380: + self.a[:2]=0;self.a[3]=0;self.setup_grasp(obs,tools) + return self.a.copy() + if self.segment is None: + if not self.queue: + if self.stage=='approach': + pn,rn=fk(self.nom);pose=ld[21:25];sh=np.array([.004,.144,.30]);goal=pn+sh;goal[:2]+=self.base_goal-pose[:2] + goal=rot(2,-pose[3])@goal-sh;goal[2]+=.746-pose[2] + # Small residual correction after base alignment. + shift=np.clip(goal-pn,[-.07,-.10,-.025],[.07,.10,.025]) + if not self.walked:shift[:]=0 + q=ik(pn+shift,rn,self.nom,roll_min=-.162) + cmd=q+self.bias if not self.original else np.array([-1,-.3,0,.2,0,.4,0]) + self.enqueue(dict(zip(range(5,12),cmd)),80) + self.enqueue({19:1},50);self.stage='close' + elif self.stage=='close':self.setup_manip(obs) + elif self.stage=='manip':self.stage='done' + if self.queue: + vals,n,ramp=self.queue.pop(0);goal=self.a.copy() + if 'cartesian' in vals: + pn,rn=fk(self.nom);pose=ld[21:25];sh=np.array([.004,.144,.30]) + dest=rot(2,.032)@(pn+sh+vals['cartesian']);dest[:2]+=self.base_goal+[.013,-.003]-pose[:2] + dest[2]+=.746-pose[2];dest=rot(2,-pose[3])@dest-sh + q=ik(dest,rot(2,.032-pose[3])@rot(0,np.pi)@rn,ld[3:10].astype(float)) + goal[5:12]=q + else: + for k,v in vals.items():goal[k]=v + self.segment=(t,self.a.copy(),goal,n,ramp) + if self.segment is not None: + tt,old,goal,n,ramp=self.segment;self.a=old+(goal-old)*min(1,(t-tt+1)/ramp) + if t-tt+1>=n:self.segment=None;finished_goal=goal.copy() + self.a[0:2]=0;self.a[3]=0 + if self.walked: + er=self.base_goal-ld[21:23];v=np.clip(1.5*er-.35*ld[46:48],-.16,.16) + if np.linalg.norm(er)>.018: + vn=np.linalg.norm(v) + if 0 35) + & (hsv[:, :, 2] < 210)).astype(np.uint8) + mask[22:, :] = 0 + n, labels, stats, centres = cv2.connectedComponentsWithStats(mask) + candidates = [i for i in range(1, n) + if stats[i, 4] >= 15 and 15 < centres[i, 0] < 72 + and stats[i, 1] < 10] + if candidates: + i = max(candidates, key=lambda j: stats[j, 4]) + self.lateral = float(np.clip(-.012 * (centres[i, 0] - 47.1081), -.12, .12)) + bottom = stats[i, 1] + stats[i, 3] + self.reach = float(np.clip(-.008 * (bottom - 17), -.055, .055)) + self.grasp_roll = float(np.clip(.08 + self.lateral, -.12, .3)) + self.grasp_pitch = float(np.clip(.3 + self.reach, .23, .37)) + self.grasp = [-1.3, self.grasp_roll, 0, -.2, 0, 1.5, 0] + self.lift = [-2.55, self.grasp_roll, 0, 1.05, 0, 1.5, 0] + self.turned = self.lift.copy() + self.turned[5] = .3 + self.place = [-1.4, float(np.clip(.025 + self.lateral, -.15, .3)), + 0, -.1, 0, .3, 0] + self.place_pitch = float(np.clip(.5 + self.reach, .35, .55)) + self.queue = [ + ("raise", 80, 60, [-2, 0, 0, 0, 0, 0, 0], 0, .5), + ("approach", 100, 80, self.grasp, self.grasp_pitch, .5), + ("close", 80, 40, self.grasp, self.grasp_pitch, 1), + ("lift", 160, 140, self.lift, self.grasp_pitch, 1), + ("turn", 110, 90, self.turned, self.grasp_pitch, 1), + ("insert", 110, 90, self.place, self.place_pitch, 1), + ("release", 160, 35, self.place, self.place_pitch, 0), + ("withdraw", 130, 100, [-2.3, 0, 0, .8, 0, 1.5, 0], 0, 0), + ] + self.index = 0 + self.start = int(obs["t"]) + self.previous = self.home.copy() + self.previous[19] = .5 + self.retries = 0 + + def target(self, stage): + a = self.home.copy() + a[5:12] = stage[3] + a[4] = stage[4] + a[19] = stage[5] + return a + + def act(self, obs, tools): + t = int(obs["t"]) + while self.index < len(self.queue) and t - self.start >= self.queue[self.index][1]: + stage = self.queue[self.index] + self.previous = self.target(stage) + self.start += stage[1] + self.index += 1 + # A fully closed empty hand can retry its approach before lifting. + fingers = np.asarray(obs["low_dim_obs"])[10:12] + if stage[0] == "close" and np.max(fingers) < -.0195 and self.retries < 1: + self.retries += 1 + self.grasp[1] = float(np.clip(self.grasp[1] - .035, -.15, .3)) + self.grasp_pitch = min(.39, self.grasp_pitch + .025) + self.queue[self.index:self.index] = [ + ("retry_open", 60, 40, self.grasp, self.grasp_pitch, .25), + ("close", 80, 40, self.grasp, self.grasp_pitch, 1), + ] + if self.index >= len(self.queue): + return self.previous.astype(np.float32) + stage = self.queue[self.index] + goal = self.target(stage) + fraction = np.clip((t - self.start) / stage[2], 0, 1) + a = self.previous + fraction * (goal - self.previous) + return a.astype(np.float32) diff --git a/policies/flip_cutlery/deepseek1017-s1/episodes.csv b/policies/flip_cutlery/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/deepseek1017-s1/policy.py b/policies/flip_cutlery/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ec8b3a190feec42b1c55056f9dfe664fdcbd4a23 --- /dev/null +++ b/policies/flip_cutlery/deepseek1017-s1/policy.py @@ -0,0 +1,123 @@ +"""Hand-written control policy for the G1 flip-cutlery task. + +Deterministic keyframe controller. It walks up to the table, leans the torso +over it, and then makes several attempts to grasp and flip the spoon with the +left hand, with a right-hand fallback. The poses were tuned from episodes on +the development seeds and from the demonstration. + +Contract: reset(obs, tools) once, act(obs, tools) -> 21 floats every control +step. See docs/api.md. +""" + +import numpy as np + + +def _pose(sp=0.0, roll=0.0, yaw=0.0, elbow=0.0, wr=0.0, wp=0.0, wy=0.0): + return [sp, roll, yaw, elbow, wr, wp, wy] + + +# (first_step, height, pitch, vx, left_arm, right_arm, l_grip, r_grip) +_KEYS = [ + # settle, tuck the arms + (0, 0.74, 0.00, 0.0, _pose(0.5, 0.0, 0.0, 1.4), _pose(0.5, 0.0, 0.0, 1.4), 0.0, 0.0), + # walk up to the table + (5, 0.74, 0.00, 0.6, _pose(0.5, 0.0, 0.0, 1.4), _pose(0.5, 0.0, 0.0, 1.4), 0.0, 0.0), + # lean the torso over the table + (60, 0.74, 0.60, 0.0, _pose(0.5, 0.0, 0.0, 1.4), _pose(0.5, 0.0, 0.0, 1.4), 0.0, 0.0), + # left hand to the mug / spoon handle + (88, 0.74, 0.60, 0.0, _pose(1.2, 0.0, 0.0, 0.0, 0.0, -0.5, -1.5), + _pose(0.5, 0.0, 0.0, 1.4), 0.0, 0.0), + # edge the body forward so the handle sits between the fingers + (108, 0.74, 0.60, 0.35, _pose(1.2, 0.0, 0.0, 0.0, 0.0, -0.5, -1.5), + _pose(0.5, 0.0, 0.0, 1.4), 0.0, 0.0), + # close on the handle + (130, 0.74, 0.60, 0.0, _pose(1.2, 0.0, 0.0, 0.0, 0.0, -0.5, -1.5), + _pose(0.5, 0.0, 0.0, 1.4), 1.0, 0.0), + # pull the spoon up and out toward the body, then twist it over + (148, 0.74, 0.60, 0.0, _pose(0.7, 0.0, 0.0, 0.6, 0.0, -1.0, -1.5), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 1.0, 0.0), + (168, 0.74, 0.60, 0.0, _pose(0.8, 0.0, 0.0, 0.8, 1.5, -0.8, -1.5), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 1.0, 0.0), + # lower the flipped spoon back toward the mug and release + (186, 0.74, 0.60, 0.0, _pose(1.2, 0.0, 0.0, 0.0, 1.5, -0.5, -1.5), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 1.0, 0.0), + (212, 0.74, 0.60, 0.0, _pose(1.2, 0.0, 0.0, 0.0, 1.5, -0.5, -1.5), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 0.0, 0.0), + # second left-hand attempt: a little deeper, other twist + (240, 0.74, 0.60, 0.0, _pose(1.35, 0.0, 0.0, 0.1, 0.0, -0.5, -1.5), + _pose(0.5, 0.0, 0.0, 1.4), 0.0, 0.0), + (270, 0.74, 0.60, 0.0, _pose(1.35, 0.0, 0.0, 0.1, 0.0, -0.5, -1.5), + _pose(0.5, 0.0, 0.0, 1.4), 1.0, 0.0), + (290, 0.74, 0.60, 0.0, _pose(1.6, 0.0, 0.0, 0.3, -1.4, -0.5, -1.5), + _pose(1.45, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 1.0, 0.0), + (330, 0.74, 0.60, 0.0, _pose(1.2, 0.0, 0.0, 0.0, -1.4, -0.5, -1.5), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 1.0, 0.0), + (355, 0.74, 0.60, 0.0, _pose(1.2, 0.0, 0.0, 0.0, -1.4, -0.5, -1.5), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 0.0, 0.0), + # right-hand fallback + (385, 0.74, 0.60, 0.0, _pose(0.5, 0.0, 0.0, 1.4), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 0.0, 0.0), + (415, 0.74, 0.60, 0.0, _pose(0.5, 0.0, 0.0, 1.4), + _pose(1.2, 0.0, 0.0, 0.2, 0.0, -0.8, 0.0), 0.0, 1.0), + (435, 0.74, 0.60, 0.0, _pose(0.5, 0.0, 0.0, 1.4), + _pose(1.5, 0.0, 0.0, 0.2, 1.5, -0.8, 0.0), 0.0, 1.0), + (475, 0.74, 0.60, 0.0, _pose(0.5, 0.0, 0.0, 1.4), + _pose(1.2, 0.0, 0.0, 0.2, 1.5, -0.8, 0.0), 0.0, 1.0), + (505, 0.74, 0.60, 0.0, _pose(0.5, 0.0, 0.0, 1.4), + _pose(1.2, 0.0, 0.0, 0.2, 1.5, -0.8, 0.0), 0.0, 0.0), + # retract and hold safely + (545, 0.74, 0.00, 0.0, _pose(0.3, 0.0, 0.0, 0.8), _pose(0.3, 0.0, 0.0, 0.8), 0.0, 0.0), +] + +_BLEND = 0.16 + + +class Policy: + """Deterministic scripted manipulation policy.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.arm_l = self.hold[5:12].copy() + self.arm_r = self.hold[12:19].copy() + self.grip_l = float(self.hold[19]) + self.grip_r = float(self.hold[20]) + + @staticmethod + def _key(t): + cur = _KEYS[0] + for k in _KEYS: + if t >= k[0]: + cur = k + else: + break + return cur + + def act(self, obs, tools): + t = int(obs.get("t", 0)) + raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + + if obs.get("fell", False): + return raw + + _, height, pitch, vx, la, ra, gl, gr = self._key(t) + + base_x = float(obs["low_dim_obs"][21]) + raw[0] = vx if (vx != 0.0 and base_x < 0.54) else 0.0 + raw[2] = height + raw[4] = pitch + + self.arm_l += _BLEND * (np.asarray(la, dtype=np.float32) - self.arm_l) + self.arm_r += _BLEND * (np.asarray(ra, dtype=np.float32) - self.arm_r) + raw[5:12] = self.arm_l + raw[12:19] = self.arm_r + + # The gripper command is applied directly (0 open, 1 closed); the + # physical fingers take a few steps to travel. + self.grip_l = gl + self.grip_r = gr + raw[19] = self.grip_l + raw[20] = self.grip_r + return raw diff --git a/policies/flip_cutlery/deepseek1017-s2/episodes.csv b/policies/flip_cutlery/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/deepseek1017-s2/policy.py b/policies/flip_cutlery/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..359e820afe5b068e5ecc32b0fd788e05a99333ff --- /dev/null +++ b/policies/flip_cutlery/deepseek1017-s2/policy.py @@ -0,0 +1,376 @@ +"""Control policy for the Unitree G1 task "take the spoon from the mug, flip +it, and place it back". + +The policy is hand-written, deterministic control logic: no learned components, +no stored data, no randomness and no wall-clock dependence. Only the robot's +own cameras and the proprioceptive vector are used. + +Scene understanding used by the controller (from the demonstration and from +development episodes): + + * The robot stands in front of a table. The mug stands on the top surface + beyond a wooden strip; the spoon leans out of the mug. + * Walking forward stops against the table, so pressing forward makes the base + pose repeatable. + * The mug is the largest low-saturation blob above the wood-coloured strip in + the 84x84 head image; its placement varies per episode mostly laterally, so + strafing until it sits at a fixed image column removes most of the + variation. + * The arm is position controlled and its measured joint angles are in the + observation, so contact can be detected from the tracking error: while the + hand is in free space the measured shoulder angle follows the command; as + soon as the hand meets the mug (or the table edge next to it) the measured + angle stalls even though the command keeps advancing. The pinch is made at + that moment, which makes the grasp independent of the exact mug position. + +Episode structure +----------------- + A. press forward against the table with a small torso lean (repeatable base); + B. settle; + C. find the mug in the head image and strafe so that it sits at the working + image column; + D. grasp cycles: move the arm to a pre-grasp over the table, advance the + shoulder slowly while watching for the contact stall, pinch and squeeze at + the contact, lift/pull the spoon out by folding the elbow, roll the wrist + to flip the spoon, move the gripper back down over the mug, release and + retract. Cycles differ in lateral offset and start height so that the + unobservable depth/height of the mug is covered; + E. two slower half-closed "rake" passes that sweep the gripper laterally + through the mug region at two heights, each followed by a lift/flip/place; + F. hold a neutral pose so that a satisfied condition can hold for the + required second. +""" + +import numpy as np +import cv2 + + +LEAN = 0.34 # torso pitch command used while working +HOME_HEIGHT = 0.7465 # normal stance pelvis height (m) + + +# ------------------------------------------------------------------ helpers + +def find_mug(img): + """Locate the mug in an 84x84 RGB head image. + + The mug is a mid/dark grey object standing on the white top beyond the + wooden strip. The strip is found by its wood colour (a full-width band); + everything below it (the grey metal tray) is discarded, then the largest + low-saturation blob above it is taken as the mug. + + Args: + img: uint8 RGB image of shape (84, 84, 3). + + Returns: + (u, v, area) of the mug blob in pixels, or None if not found. + """ + hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV).astype(np.int32) + hue, sat, val = hsv[..., 0], hsv[..., 1], hsv[..., 2] + wood = (hue >= 8) & (hue <= 35) & (sat >= 70) & (val >= 80) & (val <= 215) + rows = wood.mean(axis=1) + band = np.where(rows > 0.35)[0] + limit = int(band.min()) - 1 if len(band) else 30 + limit = int(np.clip(limit, 5, 62)) + grey = (sat < 78) & (val >= 68) & (val < 208) + grey[limit:, :] = False + grey[:, :3] = False + grey[:, -3:] = False + mask = cv2.morphologyEx(grey.astype(np.uint8), cv2.MORPH_OPEN, + np.ones((2, 2), np.uint8)) + n, _lab, stats, cent = cv2.connectedComponentsWithStats(mask, 8) + best = None + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + w = int(stats[i, cv2.CC_STAT_WIDTH]) + h = int(stats[i, cv2.CC_STAT_HEIGHT]) + if area < 28 or w < 4 or h < 3: + continue + score = area + 2.0 * w + if best is None or score > best[0]: + best = (score, float(cent[i][0]), float(cent[i][1]), area) + if best is None: + return None + return best[1], best[2], best[3] + + +# Grasp cycle table: (lateral offset from the centred mug [m], +# shoulder pitch at the pre-grasp, +# elbow angle at the pre-grasp) +CYCLES = ( + (0.00, 0.60, 0.06), + (+0.06, 0.70, 0.05), + (-0.06, 0.50, 0.14), + (+0.10, 0.80, 0.05), + (-0.10, 0.42, 0.24), + (0.00, 0.90, 0.08), + (+0.03, 1.00, 0.12), + (-0.03, 0.75, 0.30), +) + +# Rake passes: (shoulder pitch, elbow angle, lateral half-amplitude [m]) +RAKES = ( + (0.66, 0.10, 0.09), + (0.86, 0.06, 0.09), +) + + +class Policy: + """Deterministic reach / grasp / flip / place controller.""" + + # -- lifecycle --------------------------------------------------------- + def reset(self, obs, tools): + """Initialise per-episode state.""" + self.arm = np.zeros(7, dtype=np.float32) + self.grip = 0.6 + self.base = np.zeros(5, dtype=np.float32) + self.base[2] = HOME_HEIGHT + self.base[4] = LEAN + self.phase = 0 + self.pt = 0 + self.cyc = 0 + self.cyc_stage = 0 + self.stage_t = 0 + self.align_round = 0 + self.base_y0 = float(obs["low_dim_obs"][53]) + self.mug_u = None + self.rake = 0 + self.off = 0.0 + self.cmd_sp = 0.0 + self.cmd_el = 0.0 + self.act_sp = 0.0 + self.act_el = 0.0 + self.act_hist = [] + self.blocked = False + + # -- action assembly --------------------------------------------------- + def _raw(self, tools): + raw = np.asarray(tools.hold_action(), dtype=np.float32) + raw[0:5] = self.base + raw[5:12] = self.arm + raw[19] = self.grip + return raw + + def _tick(self, tools): + self.pt += 1 + self.stage_t += 1 + return self._raw(tools) + + def _read_mug(self, tools): + """Run the mug detector; returns the image column or None.""" + try: + img = tools.image("head") + m = find_mug(np.asarray(img)) + except Exception: + return None + if m is None: + return None + self.mug_u = m[0] + return m[0] + + # -- main step --------------------------------------------------------- + def act(self, obs, tools): + """Return the 21-float action for this control step.""" + ld = np.asarray(obs["low_dim_obs"], dtype=np.float32) + pelvis_y = float(ld[53]) + self.act_sp = float(ld[3]) + self.act_el = float(ld[6]) + + # ------------------------------------------------- A: press forward + if self.phase == 0: + self.base[0] = 0.32 + self.base[1] = 0.0 + self.base[4] = LEAN + if self.pt < 26: + return self._tick(tools) + self.phase, self.pt = 1, 0 + return self._tick(tools) + + # ------------------------------------------------- B: settle + if self.phase == 1: + self.base[0] = 0.0 + self.base[1] = 0.0 + if self.pt < 24: + return self._tick(tools) + self.phase, self.pt = 2, 0 + return self._tick(tools) + + # ------------------------------------------------- C: centre the mug + if self.phase == 2: + self.base[0] = 0.0 + if self.pt % 10 != 0: + return self._tick(tools) + u = self._read_mug(tools) + if u is not None and abs(u - 30.0) > 4.0 and self.align_round < 5: + self.base[1] = float(np.clip(-(u - 30.0) * 0.017, -0.28, 0.28)) + self.align_round += 1 + return self._tick(tools) + self.base[1] = 0.0 + if self.pt < 12: + return self._tick(tools) + self.base_y0 = pelvis_y + self.phase, self.pt = 3, 0 + return self._tick(tools) + + # ------------------------------------------------- lateral hold + if self.phase == 3: + self.off = CYCLES[min(self.cyc, len(CYCLES) - 1)][0] + else: + amp = RAKES[min(self.rake, len(RAKES) - 1)][2] + # slow triangular sweep, ~1.2 s per half period + self.off = amp if (self.stage_t // 15) % 2 == 0 else -amp + y_err = (self.base_y0 + self.off) - pelvis_y + if abs(y_err) > 0.010: + self.base[1] = float(np.clip(1.5 * y_err, -0.24, 0.24)) + else: + self.base[1] = 0.0 + self.base[0] = 0.0 + self.base[4] = LEAN + + if self.phase == 3: + return self._grasp_cycle(tools) + return self._rake_cycle(tools) + + # ---------------------------------------------------------- grasp cycle + def _grasp_cycle(self, tools): + """One grasp cycle: reach, probe for contact, pinch, lift, flip, replace.""" + _off, sp, el = CYCLES[min(self.cyc, len(CYCLES) - 1)] + st = self.cyc_stage + + if st == 0: # go to the pre-grasp + self.arm[:] = (sp, 0.0, 0.0, el, 0.0, 0.0, 0.0) + self.grip = 0.6 + self.cmd_sp = sp + self.cmd_el = el + self.act_hist = [] + self.blocked = False + if self.stage_t >= 14: + self.cyc_stage, self.stage_t = 1, 0 + return self._tick(tools) + + if st == 1: # probe until blocked + # Advance the shoulder slowly and watch the measured shoulder + # angle: while the arm follows the command the hand is still in + # free space; once it stops following, the hand has reached the + # mug / the table edge, which is where the pinch is made. + self.cmd_sp = min(1.05, self.cmd_sp + 0.012) + self.cmd_el = max(0.02, self.cmd_el - 0.004) + self.arm[:] = (self.cmd_sp, 0.0, 0.0, self.cmd_el, 0.0, 0.0, 0.0) + self.grip = 0.6 + self.act_hist.append(self.act_sp) + if len(self.act_hist) > 7: + self.act_hist.pop(0) + stalled = False + if len(self.act_hist) == 7 and self.stage_t > 7: + stalled = (self.act_hist[-1] - self.act_hist[0]) < 0.018 + if stalled or self.stage_t >= 30: + self.blocked = True + self.cyc_stage, self.stage_t = 2, 0 + return self._tick(tools) + + if st == 2: # pinch against contact + k = min(self.stage_t, 9) + self.cmd_sp = min(1.15, self.cmd_sp + 0.006) + self.arm[:] = (self.cmd_sp, 0.0, 0.0, self.cmd_el, 0.0, 0.0, 0.0) + self.grip = min(1.0, 0.6 + 0.05 * k) + if self.stage_t >= 9: + self.cyc_stage, self.stage_t = 102, 0 + return self._tick(tools) + + if st == 102: # squeeze + self.grip = 1.0 + if self.stage_t >= 4: + self.cyc_stage, self.stage_t = 103, 0 + return self._tick(tools) + + if st == 103: # lift / pull it out + self.arm[0] = 0.34 + self.arm[3] = 1.16 + if self.stage_t >= 15: + self.cyc_stage, self.stage_t = 104, 0 + return self._tick(tools) + + if st == 104: # flip the wrist + self.arm[4] = 1.6 + if self.stage_t >= 12: + self.cyc_stage, self.stage_t = 105, 0 + return self._tick(tools) + + if st == 105: # back over the mug + self.arm[0] = self.cmd_sp + self.arm[3] = max(0.04, self.cmd_el) + if self.stage_t >= 14: + self.cyc_stage, self.stage_t = 106, 0 + return self._tick(tools) + + if st == 106: # release + self.grip = 0.25 + if self.stage_t >= 6: + self.cyc_stage, self.stage_t = 107, 0 + return self._tick(tools) + + # st == 107: retract and start the next cycle + self.arm[0] = 0.44 + self.arm[3] = 1.10 + self.arm[4] = 0.0 + self.grip = 0.6 + if self.stage_t >= 10: + self.cyc_stage, self.stage_t = 0, 0 + self.cyc += 1 + if self.cyc >= len(CYCLES): + self.phase, self.pt = 4, 0 + self.cyc_stage, self.stage_t = 0, 0 + return self._tick(tools) + + # ----------------------------------------------------------- rake cycles + def _rake_cycle(self, tools): + """Sweep the half-closed gripper laterally through the mug region.""" + if self.rake >= len(RAKES): + self.arm[:] = (0.45, 0.0, 0.0, 1.10, 0.0, 0.0, 0.0) + self.arm[4] = 0.0 + self.grip = 0.6 + return self._tick(tools) + + sp, el, _amp = RAKES[self.rake] + st = self.cyc_stage + self.grip = 0.9 + + if st == 0: # set the height + self.arm[:] = (sp, 0.0, 0.0, el, 0.0, 0.0, 0.0) + if self.stage_t >= 12: + self.cyc_stage, self.stage_t = 1, 0 + return self._tick(tools) + + if st == 1: # sweep (base motion) + self.arm[3] = el + 0.002 * min(self.stage_t, 30) + if self.stage_t >= 30: + self.cyc_stage, self.stage_t = 2, 0 + return self._tick(tools) + + if st == 2: # close on anything held + self.grip = 1.0 + if self.stage_t >= 6: + self.cyc_stage, self.stage_t = 103, 0 + return self._tick(tools) + + if st == 103: # lift, flip, come back + self.arm[0] = 0.36 + self.arm[3] = 1.14 + self.arm[4] = 1.6 if self.stage_t > 12 else 0.0 + if self.stage_t >= 26: + self.cyc_stage, self.stage_t = 104, 0 + return self._tick(tools) + + if st == 104: # down, release + self.arm[0] = sp + self.arm[3] = el + self.arm[4] = 1.6 + self.grip = 0.25 if self.stage_t > 12 else 1.0 + if self.stage_t >= 20: + self.cyc_stage, self.stage_t = 0, 0 + self.rake += 1 + return self._tick(tools) + + self.arm[:] = (0.45, 0.0, 0.0, 1.10, 0.0, 0.0, 0.0) + self.grip = 0.6 + return self._tick(tools) diff --git a/policies/flip_cutlery/deepseek1017-s3/episodes.csv b/policies/flip_cutlery/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/deepseek1017-s3/policy.py b/policies/flip_cutlery/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2503b36e69674820a4c925a80e7ef27dbb1f093d --- /dev/null +++ b/policies/flip_cutlery/deepseek1017-s3/policy.py @@ -0,0 +1,275 @@ +"""Hand-written control policy for the G1 'flip_cutlery' task. + +The robot leans over the table, places the left gripper above the mug, tries a +ladder of nearby arm poses (verified through the finger joints), and when the +spoon is held it lifts it out, rotates the wrist over to flip it, sets it back +into the mug and lets go. + +Only the robot's own cameras and proprioception are used. Nothing is learned +and all constants were tuned by running episodes. +""" + +import numpy as np + +try: # scipy ships with the sandbox; degrade gracefully if it is missing + from scipy import ndimage +except Exception: # pragma: no cover + ndimage = None + +# ------------------------------------------------------------------ constants +HOME_ARM = np.array([-1.40, 0.40, 0.0, 0.60, 0.0, 0.70, 0.0]) +# pose from which the mug sits inside the left wrist camera's view +AIM_ARM = np.array([-1.20, 0.45, 0.0, 0.45, 0.0, 0.50, 0.0]) +HOME_H = 0.74 +WORK_H = 0.72 +PITCH = 0.35 + + +# ------------------------------------------------------------------ detection +def neutral_mask(im): + f = im.astype(np.float32) + mx = f.max(axis=2) + mn = f.min(axis=2) + return (mx - mn < 14) & (mx > 125) & (mx < 242) + + +def mug_blobs(im, ymax=82, minpix=18): + """Compact neutral-grey blobs (mug / spoon) seen by a wrist camera.""" + if ndimage is None: + return [] + m = neutral_mask(im) + m[ymax:, :] = False + lab, n = ndimage.label(m) + out = [] + for i in range(1, n + 1): + ys, xs = np.nonzero(lab == i) + a = len(xs) + if a < minpix: + continue + x0, x1 = int(xs.min()), int(xs.max()) + y0, y1 = int(ys.min()), int(ys.max()) + w = x1 - x0 + 1 + h = y1 - y0 + 1 + if max(w, h) > 55 or min(w, h) < 3: + continue + if a / float(w * h) < 0.28: + continue + out.append(dict(n=a, cx=(x0 + x1) / 2.0, cy=(y0 + y1) / 2.0, + size=float(np.sqrt(a)))) + return out + + +class Policy: + """Finite-state controller for the flip-cutlery task.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.height = HOME_H + self.pitch = 0.0 + self.arm = HOME_ARM.copy() + self.grip = 0.0 + self.phase = "walk" + self.mark = 0 + self.attempt = 0 + self.grasp_arm = None + self.grasp_h = WORK_H + self.fing_closed = None + self.released = False + + # ------------------------------------------------------------- kinematics + def trial_arm(self): + """Arm target for the current grasp attempt.""" + a = AIM_ARM.copy() + step = self.attempt % 8 + cycle = self.attempt // 8 + a[0] += 0.06 * (step - 3) # sweep the reach + a[1] += 0.05 * (1 if step % 2 else -1) # small lateral dither + a[3] += 0.08 * ((step // 2) - 1) # elbow raise/lower + a[5] += 0.12 * ((step // 4) - 0.5) * 2 # wrist pitch + a[0] += 0.05 * cycle + a[0] = float(np.clip(a[0], -1.9, -0.8)) + a[1] = float(np.clip(a[1], -0.3, 0.9)) + a[3] = float(np.clip(a[3], 0.2, 1.3)) + a[5] = float(np.clip(a[5], -0.3, 1.5)) + return a + + def trial_height(self): + return WORK_H - 0.04 * ((self.attempt // 3) % 2) + + def trial_pitch(self): + return PITCH + 0.12 * ((self.attempt // 6) % 3) + + # ------------------------------------------------------------------ utils + def _action(self, obs): + ld = obs["low_dim_obs"] + yaw = float(ld[24]) + wz = float(np.clip(-1.2 * yaw, -0.4, 0.4)) + if abs(wz) < 0.055: + wz = 0.0 if abs(yaw) < 0.006 else 0.06 * np.sign(wz) + a = self.hold.copy() + a[0] = 0.0 + a[1] = 0.0 + a[2] = float(np.clip(self.height, 0.4, 1.0)) + a[3] = wz + a[4] = float(np.clip(self.pitch, -0.2, 0.8)) + a[5:12] = self.arm.astype(np.float32) + a[19] = float(np.clip(self.grip, 0.0, 1.0)) + a[20] = 0.6 + return a + + @staticmethod + def _fing(obs): + return np.asarray(obs["low_dim_obs"][10:12], dtype=float) + + @staticmethod + def _thin(f): + # the spoon (handle or bowl) stops the fingers close to closed; a fully + # closed gripper parks both finger joints near -0.02 + return (f.max() < 0.021) and (f.min() > -0.011) + + def _go(self, phase): + self.phase = phase + self.mark = self.t + + # ------------------------------------------------------------------- loop + def act(self, obs, tools): + self.t += 1 + dt = self.t - self.mark + + if self.phase == "walk": + self.arm = HOME_ARM.copy() + self.height = HOME_H + self.pitch = 0.0 + self.grip = 0.0 + a = self._action(obs) + if dt <= 30: + a[0] = 0.45 + return a + self._go("settle_in") + + elif self.phase == "settle_in": + self.arm = HOME_ARM.copy() + self.grip = 0.0 + if dt < 20: + self.pitch = 0.0 + self.height = HOME_H + else: + self.pitch = PITCH + self.height = WORK_H + if dt > 55: + self._go("aim") + + elif self.phase == "aim": + self.pitch = PITCH + self.height = WORK_H + self.arm = AIM_ARM.copy() + self.grip = 0.0 + if dt > 45: + self._go("search") + + elif self.phase == "search": + self.pitch = self.trial_pitch() + a = self.trial_arm() + self.arm = a + self.height = self.trial_height() + if dt <= 10: + self.grip = 0.0 + elif dt <= 24: + self.grip = 1.0 + elif dt == 25: + self.fing_closed = self._fing(obs) + self.grip = 0.0 + self._go("verify") + else: + self.grip = 0.0 + + elif self.phase == "verify": + self.pitch = self.trial_pitch() + a = self.trial_arm() + h = self.trial_height() + self.arm = a + if dt <= 6: + self.height = h + self.grip = 0.0 + else: + self.height = h + 0.045 + self.grip = 1.0 + if dt >= 24: + f = self._fing(obs) + if self.fing_closed is not None and \ + self._thin(self.fing_closed) and f.max() < 0.023: + self.grasp_arm = a.copy() + self.grasp_h = h + 0.045 + self._go("lift") + else: + self.attempt += 1 + if self.attempt >= 32: + self._go("park") + else: + self._go("search") + + elif self.phase == "lift": + self.pitch = PITCH + a = self.grasp_arm.copy() + self.grip = 1.0 + if dt <= 12: + self.arm = a + self.height = self.grasp_h + else: + a3 = a.copy() + a3[0] += 0.15 + a3[3] += 0.25 + self.arm = a3 + self.height = self.grasp_h + 0.02 + if dt > 45: + self._go("flip") + + elif self.phase == "flip": + self.pitch = PITCH + a3 = self.grasp_arm.copy() + a3[0] += 0.15 + a3[3] += 0.25 + if dt <= 35: + a4 = a3.copy() + a4[4] = -1.60 + a4[1] -= 0.60 + a4[5] = -0.60 + self.arm = a4 + else: + a5 = a3.copy() + a5[4] = 0.60 + a5[1] += 0.30 + a5[5] = 0.60 + self.arm = a5 + self.height = self.grasp_h + 0.03 + self.grip = 1.0 + if dt > 90: + self._go("back") + + elif self.phase == "back": + self.pitch = PITCH + self.arm = self.grasp_arm.copy() + self.height = self.grasp_h + 0.01 + self.grip = 1.0 + if dt > 40: + self._go("release") + + elif self.phase == "release": + self.pitch = PITCH + self.arm = self.grasp_arm.copy() + self.height = self.grasp_h - 0.01 + self.grip = 0.0 + if dt > 50: + self._go("park") + + elif self.phase == "park": + # done or out of tries: back off slightly and wait quietly + self.pitch = PITCH + self.height = WORK_H + self.arm = AIM_ARM.copy() + self.grip = 0.0 + if self.attempt < 32 and dt > 60 and dt % 60 == 0: + self._go("search") + + return self._action(obs) diff --git a/policies/flip_cutlery/gpt61sol-s1/episodes.csv b/policies/flip_cutlery/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..40243bac4a3945d30f017e37c1084f0072b0b0b1 --- /dev/null +++ b/policies/flip_cutlery/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,1,1653,success,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt61sol-s1/policy.py b/policies/flip_cutlery/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..45259b2deeffe6de3ad2dc065ff09f14c1c9c8fe --- /dev/null +++ b/policies/flip_cutlery/gpt61sol-s1/policy.py @@ -0,0 +1,115 @@ +"""Hand-written, deterministic camera and proprioception control. No learned components.""" +import numpy as np +import cv2 + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),float);self.a[19:21]=0 + self.events=[ + (0,{'0':-.2}), (50,{'0':0,'5':-1.8,'6':.2,'8':.2,'10':1.5}), + (120,{'5':-1.2,'6':0,'8':1.5,'10':-.45}), + (190,{'5':-1.45,'10':-.2}), + (250,{'5':-1.72,'8':1.5,'10':.12,'6':.025}), + (310,{'0':.1}), (355,{'0':0}), + (395,{'6':-.04,'10':.05,'0':.1}), (455,{'0':0}), + (495,{'6':.02,'10':.2}), (545,{'0':.1}), (595,{'0':0}), + (635,{'19':1}), + (670,{'5':-2.05,'8':1.3,'10':.6}), + (810,{'12':-1.8,'13':-.4,'15':.2,'17':1.5}), + (1030,{'5':-1.72,'6':.02,'8':1.5,'10':.2,'2':.74}), + (1130,{'19':0}), + (1160,{'5':-2.,'6':.2,'8':.3,'10':1.5,'2':.74})] + self.i=0;self.offset=0;self.norm='measure';self.ns=0;self.ng=None;self.cycle=0;self.fine=None;self.fine_start=0;self.extra=0;self.fine_arm=None + ob=self.head_mug(tools.image('head')) + if ob is not None and abs(ob[0]-47)<3 and abs(ob[1]-17)<3:self.norm='done' + def head_mug(self,im): + v=im.max(2);m=((v-im.min(2)<25)&(v>30)&(v<160)).astype(np.uint8);m[20:]=0 + n,l,s,c=cv2.connectedComponentsWithStats(m) + opts=[(ss[4],cc[0],ss[1]+ss[3],ss[2]) for ss,cc in zip(s[1:],c[1:]) if ss[4]>25 and ss[2]<40] + if not opts:return None + _,cx,bt,w=max(opts);return cx,bt,w + def navigate(self,a,q,g): + er=g[:2]-q[21:23];cy=np.cos(q[24]);sy=np.sin(q[24]);vel=np.array([cy*er[0]+sy*er[1],-sy*er[0]+cy*er[1]])*1.8 + sp=np.linalg.norm(vel) + if np.linalg.norm(er)<.015:vel*=0 + elif sp<.06:vel*=.06/max(sp,1e-5) + a[:2]=np.clip(vel,-.16,.16);a[3]=np.clip(2*(g[3]-q[24]),-.3,.3) + + def act(self,obs,tools): + q=obs['low_dim_obs'];now=obs['t'] + if self.norm!='done': + a=self.a.copy();a[:2]=0;a[3]=0 + if self.norm=='measure': + ob=self.head_mug(tools.image('head')) + if ob is None:dx=0;dy=.12 + else: + cx,bt,w=ob;dx=np.clip(.005*(17-bt),-.05,.07);dy=np.clip((47-cx)*.09/max(w,12),-.15,.15) + if abs(cx-47)<3 and abs(bt-17)<3:self.norm='done';self.offset=now;return a + self.ng=q[21:25].copy();self.ng[0]=min(.22,q[21]+dx);self.ng[1]+=dy;self.ng[3]=0;self.norm='walk';self.ns=now + elif self.norm=='walk': + self.navigate(a,q,self.ng) + if now-self.ns>=100:self.norm='settle';self.ns=now;a[:2]=0;a[3]=0 + elif self.norm=='settle': + if now-self.ns>=65:self.norm='measure' + if now>=330:self.norm='done';self.offset=now + return a + t=now-self.offset-self.extra + if t==635 and self.fine is None: + frame=tools.image('left_wrist');ob=self.wrist_mug(frame);bowl=self.bowl(frame) + if bowl is not None and abs(bowl[0]-16)<4 and abs(bowl[1]-43)<5 and ob is not None and abs(ob[0]-62)<5 and abs(ob[1]-41)<5 and abs(ob[2]-44)<5:self.fine='done' + else: + self.fine='depth';self.fine_start=now + w=ob[2] if ob is not None else 44 + depth=(44-w)*4 + if bowl is not None:depth=max(depth,(30-bowl[2])*8) + self.depth_n=int(np.clip(depth,0,90)) + if self.fine not in [None,'done']: + elapsed=now-self.fine_start;a=self.a.copy();a[:2]=0;a[3]=0 + if elapsed=self.depth_n+45 and elapsed%10==0: + frame=tools.image('left_wrist');ob=self.wrist_mug(frame);bowl=self.bowl(frame) + if ob is not None: + cx,cy,w=ob + ex=62-cx;ey=cy-41 + if bowl is not None:ex=16-bowl[0];ey=bowl[1]-43 + self.a[6]=np.clip(self.a[6]+np.clip(.0015*ex,-.02,.02),-.14,.25) + self.a[10]=np.clip(self.a[10]+np.clip(.003*ey,-.025,.025),.05,.35) + else:self.a[6]=min(.25,self.a[6]+.02) + a=self.a.copy();a[:2]=0;a[3]=0 + self.extra+=1 + if elapsed>=self.depth_n+90: + self.fine='done';self.fine_arm=self.a[5:12].copy() + return a + while self.i=self.events[self.i][0]: + for k,v in self.events[self.i][1].items():self.a[int(k)]=v + self.i+=1 + if self.fine_arm is not None: + if t<670 or t>=1030 and t<1160:self.a[5:12]=self.fine_arm + elif t<1030:self.a[10]=self.fine_arm[5]+.4 + a=self.a.copy() + if t==670: + self.goal=q[21:25].copy();self.goal[1]-=.03 + if 810<=t<1030: + er=self.goal[:2]-q[21:23];cy=np.cos(q[24]);sy=np.sin(q[24]) + vel=np.array([cy*er[0]+sy*er[1],-sy*er[0]+cy*er[1]])*1.8 + speed=np.linalg.norm(vel) + if np.linalg.norm(er)<.012:vel*=0 + elif speed<.06:vel*=.06/max(speed,1e-5) + a[:2]=np.clip(vel,-.16,.16);a[3]=np.clip(2*(self.goal[3]-q[24]),-.3,.3) + return a + + def wrist_mug(self,im): + v=im.max(2);m=((v-im.min(2)<22)&(v>35)&(v<160)).astype(np.uint8)*255 + m=cv2.morphologyEx(m,cv2.MORPH_OPEN,np.ones((3,3),np.uint8));m[:,:2]=0;m[:,-2:]=0 + n,l,s,c=cv2.connectedComponentsWithStats(m) + opts=[(ss[4],cc[0],cc[1],ss[2]) for ss,cc in zip(s[1:],c[1:]) if ss[4]>40 and ss[2]>10 and ss[2]/ss[3]>1.15] + if not opts:return None + _,cx,cy,w=max(opts);return cx,cy,w + + def bowl(self,im): + v=im.max(2);m=((v-im.min(2)<22)&(v>35)&(v<160)).astype(np.uint8)*255 + m=cv2.morphologyEx(m,cv2.MORPH_OPEN,np.ones((3,3),np.uint8));m[:,:2]=0;m[:,-2:]=0 + n,l,s,c=cv2.connectedComponentsWithStats(m) + opts=[(ss[4],cc[0],cc[1],ss[3]) for ss,cc in zip(s[1:],c[1:]) if ss[4]>60 and cc[0]<33 and cc[1]<60 and ss[2]>7 and ss[3]>7] + if not opts:return None + _,cx,cy,h=max(opts);return cx,cy,h diff --git a/policies/flip_cutlery/gpt61sol-s2/episodes.csv b/policies/flip_cutlery/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..30344f2b379e6de59963b64cd158cb3d51ca4f51 --- /dev/null +++ b/policies/flip_cutlery/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1177,success,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,1,1407,success,0 +620009,1,1423,success,0 +620010,1,1111,success,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,1,1133,success,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,1,1124,success,0 +620041,0,1950,timeout,0 +620042,1,1102,success,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,1,1166,success,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,1,1057,success,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,1,1190,success,0 +620079,1,700,success,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,1,1173,success,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt61sol-s2/policy.py b/policies/flip_cutlery/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6e1a4e581dc4eecbf0b40dd1d26265b8e291a3ba --- /dev/null +++ b/policies/flip_cutlery/gpt61sol-s2/policy.py @@ -0,0 +1,95 @@ +"""Hand-written deterministic visual servoing and joint-space manipulation.""" +import numpy as np +import cv2 + +class Policy: + @staticmethod + def mug(im): + rgb=im.astype(np.int16) + mask=((rgb.max(2)-rgb.min(2)<35)&(rgb.mean(2)>55)&(rgb.mean(2)<220)).astype(np.uint8) + mask[40:]=0 + n,labels,stats,centers=cv2.connectedComponentsWithStats(mask,8) + candidates=[] + for i in range(1,n): + x,y,w,h,area=stats[i] + if 5=6 and y<18 and area>40: + bottom=y+h-1 + yy,xx=np.where((labels==i)&(np.arange(84)[:,None]>=bottom-8)) + candidates.append((area,float(np.median(xx)),float(bottom))) + if not candidates:return None + _,x,y=max(candidates) + return x,y + + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float64) + self.phase=-1;self.elapsed=0;self.dx=self.dy=0.;self.good=0;self.seen=None + self.phases=[ + (80,60,{4:-.2,6:.6,13:-.6,8:-.7,15:-.7,10:.25,17:.25,19:0,20:0}), + (400,1,{}), + (100,80,{4:0,6:0,7:-.23,8:-.7,10:.25,12:0,13:0,14:0,15:0,16:0,17:0,18:0,0:0,1:0,3:0}), + (40,1,{}), + (80,60,{5:-.7,8:0,7:-.16,10:.12,4:.15}), + (60,20,{19:1}), + (120,100,{5:-1.7,8:1.,10:.12}), + (100,80,{9:1.97,11:-.7,12:.7,13:-.5,15:-1}), + (180,1,{}), + (40,60,{0:0,1:0,3:0}), + (100,80,{5:-2.2,8:1.5,6:-.6,7:-.95,10:.12,4:.15}), + (50,15,{19:0}), + (100,80,{4:-.2,6:.6,7:0}), + (100,80,{5:0,8:-.7,7:0,6:.6,10:.25,9:0,11:0,4:-.2}), + (10000,1,{})] + self._advance(obs) + + def _advance(self,obs): + if self.phase in (1,8):self.a[0]=self.a[1]=self.a[3]=0 + if self.phase==1: + p=obs['low_dim_obs'][21:25] + self.dx=float(p[0]-.2425);self.dy=float(p[1]+.0078+.5*(p[3]+.047));self.canonical_y=float(p[1]);self.canonical_x=float(p[0]) + self.phase+=1;self.elapsed=0;self.start=self.a.copy() + for k,v in self.phases[self.phase][2].items():self.a[k]=v + if self.phase==4: + p=obs['low_dim_obs'][21:25] + self.a[7]=float(np.clip(-.16-1.2*p[3]-(p[1]-self.canonical_y)/.3,-.6,.5)) + correction=float(np.clip((p[0]-self.canonical_x+.0305)/.14,-.15,.15)) + if abs(p[0]-self.canonical_x+.0305)<.001:correction=0. + self.a[5]=-.7+correction;self.a[8]=-correction + self.grasp_delta=float(self.a[7]+.16) + if abs(self.grasp_delta)<.01:self.grasp_delta=0. + + def act(self,obs,tools): + n,ramp,updates=self.phases[self.phase] + if self.elapsed>=n or (self.phase==1 and self.good>=30):self._advance(obs) + p=obs['low_dim_obs'][21:25] + if self.phase==1: + if self.elapsed%5==0: + self.seen=self.mug(tools.image('head')) + if self.seen is None: + vel=np.array([.12,0.]);self.good=0 + else: + x,y=self.seen + ex=43.-x;ey=34.-y + vel=np.array([np.clip(.009*ey,-.18,.18),np.clip(.007*ex,-.18,.18)]) + if abs(ex)<2.5 and abs(ey)<2.5: + vel[:]=0;self.good+=1 + else:self.good=0 + sp=np.linalg.norm(vel) + if .01.015 and sp<.07:vel*=.07/sp + if abs(dx)<.008 and abs(dy)<.008:vel[:]=0 + c,s=np.cos(p[3]),np.sin(p[3]) + self.a[0]=c*vel[0]+s*vel[1];self.a[1]=-s*vel[0]+c*vel[1] + self.a[3]=np.clip(-1.5*p[3]-.25*obs['low_dim_obs'][49],-.4,.4) + raw=self.a.copy() + else: + raw=self.start+(self.a-self.start)*min(1,(self.elapsed+1)/ramp) + self.elapsed+=1 + return raw diff --git a/policies/flip_cutlery/gpt61sol-s3/episodes.csv b/policies/flip_cutlery/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4a846fdac68d8cc1074d17d63d5f11690db0d898 --- /dev/null +++ b/policies/flip_cutlery/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,1,1249,success,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt61sol-s3/policy.py b/policies/flip_cutlery/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4703fca2648b6d097ac924a682dcd2c8b614c3cb --- /dev/null +++ b/policies/flip_cutlery/gpt61sol-s3/policy.py @@ -0,0 +1,305 @@ +import numpy as np +import cv2 + +class RightApproach: + def reset(self, obs, tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float64) + self.a[19:]=.5 + self.phase=0;self.age=0;self.stable=0;self.tries=0 + self.goal=np.array([.19,0.]);self.yaw=.15;self.wp=-.65 + self.start=self.a.copy();self.found=False + def advance(self,p): + self.phase=p;self.age=0;self.stable=0;self.start=self.a.copy() + @staticmethod + def cup(im): + a=im.astype(float);v=a.mean(2);sat=a.max(2)-a.min(2) + white=(a[:,:,0]>205)&(a[:,:,1]>190)&(a[:,:,2]>130) + counts=white.sum(1);rows=np.flatnonzero(counts[:50]>25) + if not len(rows):return None + edge=int(rows[-1]);m=(sat<45)&(v>35)&(v<205) + m[max(0,edge-1):]=False;m[:, :8]=False;m[:,76:]=False + n,lab,stats,cent=cv2.connectedComponentsWithStats(m.astype('uint8')) + if n<2:return None + k=1+np.argmax(stats[1:,4]);x,y,w,h,area=stats[k] + if area<20:return None + yy,xx=np.where(lab==k);low=yy>y+h*.45 + return (float(np.mean(xx[low])) if low.any() else float(cent[k,0]),float(y+h-1)) + @staticmethod + def spoon(im): + a=im.astype(float);v=a.mean(2);sat=a.max(2)-a.min(2) + m=(sat<38)&(v>55)&(v<215)&(a[:,:,0]>a[:,:,2]-7) + m[:12]=False;m[76:]=False;m[:,:24]=False;m[:,61:]=False + n,lab,stats,cen=cv2.connectedComponentsWithStats(m.astype('uint8')) + choices=[] + for k in range(1,n): + x,y,w,h,area=stats[k] + if area<8:continue + yy,xx=np.where(lab==k) + # A shaft crosses the middle of the space between the fingers. + band=(yy>=45)&(yy<=62) + if band.sum()>4:cx=np.mean(xx[band]);cy=54. + else:cx=np.mean(xx);cy=np.mean(yy) + score=area-3*abs(cx-42)-2*abs(cy-54) + choices.append((score,float(cx),float(cy),int(area),int(y),int(y+h))) + return max(choices)[1:] if choices else None + def walk(self,obs,target,cap=.22): + p=obs['low_dim_obs'][21:25];err=np.asarray(target)-p[:2] + vel=np.clip(err*2.5,-cap,cap);norm=np.linalg.norm(vel) + if np.linalg.norm(err)<.012:vel[:]=0 + elif norm<.065:vel*=.065/max(norm,1e-6) + c,s=np.cos(p[3]),np.sin(p[3]);self.a[0:2]=[c*vel[0]+s*vel[1],-s*vel[0]+c*vel[1]] + self.a[3]=np.clip(-p[3]*3,-.35,.35) + return np.linalg.norm(err)<.02 + def arm(self,q,duration=60): + f=min(1.,self.age/duration);f=f*f*(3-2*f) + self.a[5:12]=self.start[5:12]*(1-f)+np.asarray(q)*f + def act(self,obs,tools): + self.age+=1;self.a[0:2]=0;self.a[3]=0;self.a[4]=-.2;self.a[2]=.74 + if self.phase==0: + if self.age>=90:self.advance(1) + elif self.phase==1: + if self.age%5==0: + cup=self.cup(tools.image('head')) + if cup: + cx,bot=cup;err=np.array([32-bot,42-cx]);vel=np.clip(err*np.array([.008,.006]),-.20,.20) + norm=np.linalg.norm(vel) + if np.linalg.norm(err)<2.5:vel[:]=0;self.stable+=5 + else: + self.stable=0 + if norm<.065:vel*=.065/max(norm,1e-6) + self.visual_v=vel + else:self.visual_v=np.zeros(2) + self.a[:2]=getattr(self,'visual_v',np.zeros(2));self.a[3]=np.clip(-obs['low_dim_obs'][24]*3,-.3,.3) + if self.stable>=25 or self.age>=200: + self.goal=obs['low_dim_obs'][21:23].astype(float).copy();self.advance(2) + elif self.phase==2: + reached=self.walk(obs,self.goal+[-.23,0]) + if (reached and self.age>60) or self.age>140:self.advance(3) + elif self.phase==3: + self.arm([-.9,0,.20,1,0,-.65,0],75) + if self.age>=90:self.advance(4) + elif self.phase==4: + reached=self.walk(obs,self.goal) + if (reached and self.age>90) or self.age>210:self.advance(5) + elif self.phase==5: + if self.age<35: + self.yaw=float(self.a[7]);self.wp=-.65 + elif self.age%5==0: + sp=self.spoon(tools.image('left_wrist')) + if sp: + cx,cy,area,y0,y1=sp + self.yaw+=np.clip((42-cx)*.0015,-.012,.012) + if cy!=54:self.wp+=np.clip((cy-54)*.001,-.012,.012) + if abs(cx-42)<3 and y0<53 and y1>58 and area>40:self.stable+=5 + else:self.stable=0 + else:self.yaw-=.009;self.stable=0 + self.yaw=float(np.clip(self.yaw,-.45,.35));self.wp=float(np.clip(self.wp,-.9,-.35)) + self.a[5:12]=[-.9,0,self.yaw,1,0,self.wp,0] + if self.stable>=25 or self.age>230:self.advance(6) + elif self.phase==6: + self.a[19]=1 + if self.age>45:self.advance(7) + elif self.phase==7: + self.arm([-1.4,0,self.yaw,1,0,self.wp,0],65) + if self.age>85: + fingers=obs['low_dim_obs'][10:12] + self.held=float(fingers.sum())>-.035 + if not self.held and self.tries<2: + self.tries+=1;self.a[19]=.5;self.advance(15) + else:self.advance(8) + elif self.phase==15: + self.arm([-.9,0,self.yaw,1,0,self.wp,0],60) + if self.age>70: + self.yaw+=.04;self.wp-=.04;self.advance(5) + elif self.phase==8: + self.a[2]=.82 + self.arm([-1.42,0,self.yaw,np.pi/2,0,0,0],90) + reached=self.walk(obs,self.goal+[-.07,0],.12) + if self.age>=110: + self.flip_yaw=min(2.6,self.yaw+np.pi) + self.flip_roll=-(np.pi-(self.flip_yaw-self.yaw));self.advance(9) + elif self.phase==9: + self.a[2]=.82 + self.arm([-1.42,0,self.flip_yaw,np.pi/2,self.flip_roll,0,0],120) + if self.age>145:self.advance(10) + elif self.phase==10: + self.a[2]=.82 + reached=self.walk(obs,self.goal+[-.04,0],.10) + if (reached and self.age>70) or self.age>140:self.advance(11) + elif self.phase==11: + self.a[2]=.82-.15*min(1,self.age/100) + if self.age>115:self.advance(12) + elif self.phase==12: + self.a[2]=.67;self.a[19]=.4 + if self.age>70:self.advance(13) + elif self.phase==13: + self.a[2]=.74 + self.arm([-1.6,.25,self.flip_yaw,np.pi/2,self.flip_roll,0,0],60) + return self.a.astype(np.float32) + +import numpy as np +import cv2 + +class LeftApproach: + def reset(self, obs, tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float64) + self.a[19:]=.5 + self.phase=0;self.age=0;self.stable=0;self.tries=0 + self.goal=np.array([.19,0.]);self.yaw=.15;self.wp=-.65 + self.start=self.a.copy();self.found=False;self.reach=0.;self.last_cup=None;self.retry=False + def advance(self,p): + self.phase=p;self.age=0;self.stable=0;self.start=self.a.copy() + @staticmethod + def cup(im): + a=im.astype(float);v=a.mean(2);sat=a.max(2)-a.min(2) + white=(a[:,:,0]>205)&(a[:,:,1]>190)&(a[:,:,2]>130) + counts=white.sum(1);rows=np.flatnonzero(counts[:50]>25) + if not len(rows):return None + edge=int(rows[-1]);m=(sat<45)&(v>35)&(v<205) + m[max(0,edge-1):]=False;m[:, :8]=False;m[:,76:]=False + n,lab,stats,cent=cv2.connectedComponentsWithStats(m.astype('uint8')) + if n<2:return None + k=1+np.argmax(stats[1:,4]);x,y,w,h,area=stats[k] + if area<20:return None + yy,xx=np.where(lab==k);low=yy>y+h*.45 + return (float(np.mean(xx[low])) if low.any() else float(cent[k,0]),float(y+h-1)) + @staticmethod + def spoon(im): + a=im.astype(float);v=a.mean(2);sat=a.max(2)-a.min(2) + m=(sat<38)&(v>55)&(v<215)&(a[:,:,0]>a[:,:,2]-7) + m[:12]=False;m[76:]=False;m[:,:24]=False;m[:,61:]=False + n,lab,stats,cen=cv2.connectedComponentsWithStats(m.astype('uint8')) + choices=[] + for k in range(1,n): + x,y,w,h,area=stats[k] + if area<8:continue + yy,xx=np.where(lab==k) + # A shaft crosses the middle of the space between the fingers. + if area>450: + rows=np.bincount(yy,minlength=84) + thick=np.flatnonzero(rows>15) + if len(thick): + top=yy5:yy,xx=yy[top],xx[top];area=len(xx) + cx=np.mean(xx);cy=np.mean(yy) + score=min(area,300)-3*abs(cx-42)-abs(cy-54) + choices.append((score,float(cx),float(cy),int(area),int(y),int(y+h))) + return max(choices)[1:] if choices else None + def walk(self,obs,target,cap=.22): + p=obs['low_dim_obs'][21:25];err=np.asarray(target)-p[:2] + vel=np.clip(err*2.5,-cap,cap);norm=np.linalg.norm(vel) + if np.linalg.norm(err)<.012:vel[:]=0 + elif norm<.065:vel*=.065/max(norm,1e-6) + c,s=np.cos(p[3]),np.sin(p[3]);self.a[0:2]=[c*vel[0]+s*vel[1],-s*vel[0]+c*vel[1]] + self.a[3]=np.clip(-p[3]*3,-.35,.35) + return np.linalg.norm(err)<.02 + def arm(self,q,duration=60): + f=min(1.,self.age/duration);f=f*f*(3-2*f) + self.a[5:12]=self.start[5:12]*(1-f)+np.asarray(q)*f + def act(self,obs,tools): + self.age+=1;self.a[0:2]=0;self.a[3]=0;self.a[4]=-.2+self.reach;self.a[2]=.74 + if self.phase==0: + if self.age>=65:self.advance(1) + elif self.phase==1: + if self.age%5==0: + cup=self.cup(tools.image('head')) + if cup: + self.last_cup=cup + cx,bot=cup;err=np.array([32-bot,42-cx]);vel=np.clip(err*np.array([.008,.006]),-.20,.20) + if abs(42-cx)>4:vel[0]=0 + norm=np.linalg.norm(vel) + if np.linalg.norm(err)<2.5:vel[:]=0;self.stable+=5 + else: + self.stable=0 + if norm<.065:vel*=.065/max(norm,1e-6) + self.visual_v=vel + else:self.visual_v=np.zeros(2) + self.a[:2]=getattr(self,'visual_v',np.zeros(2));self.a[3]=np.clip(-obs['low_dim_obs'][24]*3,-.3,.3) + if self.stable>=25 or self.age>=180: + self.goal=obs['low_dim_obs'][21:23].astype(float).copy() + if self.last_cup:self.reach=float(np.clip((28-self.last_cup[1])*.035,0,.6)) + self.advance(2) + elif self.phase==2: + reached=self.walk(obs,self.goal+[-.23,0]) + if (reached and self.age>60) or self.age>140:self.advance(3) + elif self.phase==3: + self.arm([-.9-self.reach,0,.20,1,0,-.65,0],75) + if self.age>=90:self.advance(4) + elif self.phase==4: + reached=self.walk(obs,self.goal) + if (reached and self.age>90) or self.age>210:self.advance(5) + elif self.phase==5: + if self.age<35: + self.yaw=float(self.a[7]);self.wp=float(self.a[10]) + elif self.age%5==0: + sp=self.spoon(tools.image('left_wrist')) + if sp: + cx,cy,area,y0,y1=sp + self.yaw+=np.clip((42-cx)*.0015,-.012,.012) + self.wp+=np.clip((cy-54)*.0015,-.015,.015) + if abs(cx-42)<3 and abs(cy-54)<6 and area>35:self.stable+=5 + else:self.stable=0 + else:self.yaw+=(.009 if self.reach>.2 else -.009);self.stable=0 + self.yaw=float(np.clip(self.yaw,-.55,.7));self.wp=float(np.clip(self.wp,-.9,-.35)) + self.a[5:12]=[-.9-self.reach,0,self.yaw,1,0,self.wp,0] + if self.stable>=25 or self.age>(90 if self.retry else 180):self.advance(6) + elif self.phase==6: + self.a[19]=1 + if self.age>35: + self.grab_body=obs['low_dim_obs'][21:23].astype(float).copy() + self.advance(7) + elif self.phase==7: + self.arm([-1.4-self.reach,0,self.yaw,1,0,self.wp,0],65) + if self.age>70: + fingers=obs['low_dim_obs'][10:12] + self.held=float(fingers.sum())>-.035 + if not self.held and self.tries<2: + self.tries+=1;self.a[19]=.5;self.reach+=.12;self.retry=True;self.advance(15) + else:self.advance(8) + elif self.phase==15: + self.arm([-.9-self.reach,0,self.yaw,1,0,self.wp,0],60) + if self.age>55: + self.advance(5) + elif self.phase==8: + self.a[2]=.82 + self.flip_wp=self.wp+.2 + self.arm([-1.72-self.reach,0,self.yaw,np.pi/2,0,self.flip_wp,0],75) + reached=self.walk(obs,self.grab_body+[-.17,0],.16) + if (reached and self.age>=100) or self.age>=160: + self.flip_yaw=min(2.6,self.yaw+np.pi) + self.flip_roll=-(np.pi-(self.flip_yaw-self.yaw));self.advance(9) + elif self.phase==9: + self.a[2]=.82 + self.arm([-1.72-self.reach,0,self.flip_yaw,np.pi/2,self.flip_roll,self.flip_wp,0],100) + if self.age>120:self.advance(10) + elif self.phase==10: + self.a[2]=.82 + reached=self.walk(obs,self.grab_body+[-.03,.01],.10) + if (reached and self.age>70) or self.age>140:self.advance(11) + elif self.phase==11: + self.a[2]=.82 + self.arm([-1.42-self.reach,0,self.flip_yaw,np.pi/2,self.flip_roll,self.flip_wp,0],80) + if self.age>90:self.advance(17) + elif self.phase==17: + self.a[2]=.82-.10*min(1,self.age/65) + if self.age>75:self.advance(12) + elif self.phase==12: + self.a[2]=.72;self.a[19]=.4 + if self.age>70:self.advance(13) + elif self.phase==13: + self.a[2]=.74 + self.arm([-1.8-self.reach,.25,self.flip_yaw,np.pi/2,self.flip_roll,self.flip_wp,0],60) + return self.a.astype(np.float32) + + + +class Policy: + """Deterministic visual control with approaches for either side of the mug.""" + def reset(self, obs, tools): + location=RightApproach.cup(tools.image('head')) + # The leftward approach spends more time aligning the lateral reach; + # a mug on the right permits simultaneous forward and lateral motion. + self.controller=LeftApproach() if location is None or location[0]<42 else RightApproach() + self.controller.reset(obs,tools) + def act(self,obs,tools): + return self.controller.act(obs,tools) diff --git a/policies/flip_cutlery/gpt61terra-s1/episodes.csv b/policies/flip_cutlery/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..92bddc197cd56a50481ba633bee8a93df2139320 --- /dev/null +++ b/policies/flip_cutlery/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,1,964,success,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,1,968,success,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,1,1010,success,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt61terra-s1/policy.py b/policies/flip_cutlery/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..96747aaa6d252a054fd0ac8806d018f17fae292f --- /dev/null +++ b/policies/flip_cutlery/gpt61terra-s1/policy.py @@ -0,0 +1,80 @@ +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32) + self.a[19] = 0 + self.phase = 0 + self.start = 0 + self.scan = 0 + self.best = None + self.rolls = [0.4, 0.2, 0.0, -0.15, 0.6] + self.grasp_roll = .66 + + def next(self, t): + self.phase += 1 + self.start = t + + def act(self, obs, tools): + t = int(obs['t']); elapsed = t-self.start + a = self.a + a[0:2] = 0; a[3]=0 + if self.phase == 0: + if obs['low_dim_obs'][21] > -0.075 and elapsed < 80: + a[0] = -.25 + else: + self.next(t) + elif self.phase == 1: + a[5:12] = [-1.8,.2,0,1.5,0,.15,.2] + if elapsed >= 140: self.next(t) + elif self.phase == 2: + if obs['low_dim_obs'][21] < .18 and elapsed < 210: + a[0] = .12 + else: self.next(t) + elif self.phase == 3: + if elapsed >= 65: self.next(t) + elif self.phase == 4: + a[6] = self.rolls[self.scan] + if elapsed >= 55: + im = tools.image('left_wrist').astype(np.int16) + mx = im.max(axis=2); mn = im.min(axis=2) + mask = ((mx-mn < 18) & (mn > 55) & (mx < 225)).astype(np.uint8) + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + for i in range(1,n): + area = int(stats[i,4]); x,y = centers[i] + if area < 100 or y < 20: continue + score = area - 5*abs(x-55) - 4*max(0,y-70) + if self.best is None or score > self.best[0]: + self.best = (score, float(self.rolls[self.scan]), float(x), float(y)) + self.scan += 1; self.start = t + if self.scan >= len(self.rolls): + if self.best is not None: + _, roll, x, y = self.best + self.grasp_roll = float(np.clip(roll + (60-x)/145 + .24, -.12, 1.05)) + self.next(t) + elif self.phase == 5: + a[4] = .75; a[5:12] = [-1.8,self.grasp_roll,0,1.5,0,-.4,.4] + if elapsed >= 150: self.next(t) + elif self.phase == 6: + a[19] = 1 + if elapsed >= 90: self.next(t) + elif self.phase == 7: + f = min(elapsed/160,1) + a[5] = -1.8-.35*f; a[10] = -.4+.35*f + if elapsed >= 180: self.next(t) + elif self.phase == 8: + f = min(elapsed/180,1) + a[10] = -.05+1.65*f + if elapsed >= 200: self.next(t) + elif self.phase == 9: + f = min(elapsed/120,1) + a[5] = -2.15+.3*f + if elapsed >= 140: self.next(t) + elif self.phase == 10: + a[19] = 0 + if elapsed >= 70: self.next(t) + elif self.phase == 11: + a[5]=-2.15; a[4]=.3 + self.a = a + return a.copy() diff --git a/policies/flip_cutlery/gpt61terra-s2/episodes.csv b/policies/flip_cutlery/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt61terra-s2/policy.py b/policies/flip_cutlery/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3043f3e64e7533b61d1e2b5e49f6bc4f3a17f267 --- /dev/null +++ b/policies/flip_cutlery/gpt61terra-s2/policy.py @@ -0,0 +1,90 @@ +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.y0 = float(obs['low_dim_obs'][22]) + self.target_y = self.y0 + self.phase = 0 + self.start = 0 + self.prev = self.base.copy() + self.grip = 0.0 + + def change(self, t, phase): + self.phase = phase + self.start = t + + def act(self, obs, tools): + t = int(obs['t']) + v = obs['low_dim_obs'] + a = self.base.copy() + a[19] = 0 + if self.phase == 0: + a[4] = -0.2 + if t >= 70: + im = tools.image('head') + mx = im.max(axis=2).astype(np.int16) + mn = im.min(axis=2).astype(np.int16) + mean = im.mean(axis=2) + mask = ((mx-mn < 35) & (mean > 35) & (mean < 205)).astype(np.uint8) + mask[30:] = 0 + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + candidates = [i for i in range(1,n) if stats[i,4] > 20] + x = float(centers[max(candidates, key=lambda i: stats[i,4]),0]) if candidates else 42.0 + self.target_y = float(v[22]) + np.clip((45.0-x)*0.0062, -0.24, 0.24) + self.change(t,1) + elif self.phase == 1: + a[4] = 0 + err = self.target_y - float(v[22]) + if abs(err) > .015 and t-self.start < 180: + a[1] = np.clip(2.0*err, -.22, .22) + if abs(a[1]) < .07: a[1] = .07 if err > 0 else -.07 + elif t-self.start > 20: + self.change(t,2) + else: + dt = t-self.start + if self.phase == 2: + a[5:12] = [0,1,0,0,0,0,0] + if dt >= 65: self.change(t,3) + elif self.phase == 3: + a[5:12] = [-2,1,0,0,0,0,0] + if dt >= 65: self.change(t,4) + elif self.phase == 4: + a[5:12] = [-2,1,0,1,0,0,0] + if dt >= 65: self.change(t,5) + elif self.phase == 5: + a[5:12] = [-2,.20,0,1,0,0,0] + if dt >= 65: self.change(t,6) + elif self.phase == 6: + a[5:12] = [-1.5,.20,0,1,0,.3,0] + if dt >= 65: self.change(t,7) + elif self.phase == 7: + a[4] = .6 + a[5:12] = [-1.5,.20,0,1,0,-.5,0] + if dt >= 90: self.change(t,8) + elif self.phase == 8: + a[4] = .6 + a[5:12] = [-1.5,.20,0,1,0,-.5,0] + a[19] = 1 + if dt >= 70: self.change(t,9) + elif self.phase == 9: + a[4] = .2 + a[5:12] = [-1.9,.20,0,1,0,-.5,0] + a[19] = 1 + if dt >= 100: self.change(t,10) + elif self.phase == 10: + a[4] = .2 + a[5:12] = [-1.9,.20,1.3,1,1.7,.8,0] + a[19] = 1 + if dt >= 120: self.change(t,11) + elif self.phase == 11: + a[4] = .6 + a[5:12] = [-1.5,.20,1.3,1,1.7,.8,0] + a[19] = 1 + if dt >= 100: self.change(t,12) + else: + a[4] = .6 + a[5:12] = [-1.5,.20,1.3,1,1.7,.8,0] + a[19] = 0 + return a diff --git a/policies/flip_cutlery/gpt61terra-s3/episodes.csv b/policies/flip_cutlery/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt61terra-s3/policy.py b/policies/flip_cutlery/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7bbcbdbeec4b20c24ff8a3fffe9696c7058cc997 --- /dev/null +++ b/policies/flip_cutlery/gpt61terra-s3/policy.py @@ -0,0 +1,37 @@ +"""Deterministic open-loop manipulation of the spoon.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = int(obs['t']) + a = self.initial.copy() + a[0:5] = [0, 0, .74, 0, 0] + a[19] = 0 + if t < 70: + a[5:12] = [-1.3, 0, 0, 0, 0, .8, 0] + elif t < 160: + a[5:12] = [-1.3, 0, .05, 0, 0, .8, 0] + a[4] = .4 + elif t < 210: + a[5:12] = [-1.3, 0, .05, 0, 0, .8, 0] + a[4] = .4 + a[19] = 1 + elif t < 290: + a[5:12] = [-1.3, 0, .05, 0, 0, .8, 0] + a[19] = 1 + elif t < 390: + a[5:12] = [-1.3, 0, .05, 0, 0, -1.6, 0] + a[19] = 1 + elif t < 500: + a[5:12] = [-1.6, 0, -.15, 0, 0, -1.6, 0] + a[4] = .8 + a[19] = 1 + elif t < 540: + a[5:12] = [-1.6, 0, -.15, 0, 0, -1.6, 0] + a[4] = .8 + else: + a[5:12] = [-1.8, .3, -.15, 0, 0, -1.6, 0] + return a diff --git a/policies/flip_cutlery/gpt6sol-s1/episodes.csv b/policies/flip_cutlery/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt6sol-s1/policy.py b/policies/flip_cutlery/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3d42152fd0572dcbb2d20c753c1140f145f5858b --- /dev/null +++ b/policies/flip_cutlery/gpt6sol-s1/policy.py @@ -0,0 +1,119 @@ +"""Deterministic hand-written controller for the spoon and mug task.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.stage = "back" + self.age = 0 + self.trial = 0 + self.used_fallback = False + self.candidates = [ + (-.20, 1.52, -1.50, -.10), + (0.00, 1.58, -1.50, -.10), + (.22, 1.58, -1.50, -.10), + (.40, 1.58, -1.50, -.10), + (0.00, 1.42, -1.30, -.10), + (-.12, 1.42, -1.30, -.18), + ] + + def _advance(self, obs): + stages = { + "back": "curl", "curl": "raise", "raise": "straighten", + "straighten": "center", "center": "approach", "approach": "reach", + "reach": "close", "close": "lift", "fallback": "fallback_close", + "fallback_close": "fallback_lift", "fallback_lift": "flip", + "flip": "replace", "replace": "release", "release": "retreat", + "retreat": "hold", + } + if self.stage == "lift": + q = obs["low_dim_obs"] + held = max(float(q[10]), float(q[11])) > -.017 + if held: + self.stage = "flip" + elif self.trial + 1 < len(self.candidates): + self.trial += 1 + self.stage = "reach" + else: + self.stage = "fallback" + elif self.stage == "fallback_lift": + self.used_fallback = True + self.stage = "flip" + else: + self.stage = stages.get(self.stage, "hold") + self.age = 0 + + def act(self, obs, tools): + durations = { + "back": 60, "curl": 60, "raise": 60, "straighten": 60, + "center": 50, "approach": 100, "reach": 60, "close": 45, + "lift": 65, "fallback": 80, "fallback_close": 50, + "fallback_lift": 70, "flip": 80, "replace": 75, + "release": 70, "retreat": 70, + } + if self.age >= durations.get(self.stage, 100000): + self._advance(obs) + a = np.asarray(tools.hold_action(), dtype=np.float32) + a[0] = a[1] = a[3] = 0.0 + a[2] = .74 + a[4] = 0.0 + a[12:19] = 0.0 + a[20] = .6 + arm = [0, 0, 0, 0, 0, 0, 0] + grip = 0.0 + s = self.stage + if s == "back": + a[0] = -.30 + elif s == "curl": + arm = [0, .2, 0, 1.5, 0, 0, 0] + elif s == "raise": + arm = [-1.5, .2, 0, 1.5, 0, 0, 0] + elif s == "straighten": + arm = [-1.5, .2, 0, .7, 0, 0, 0] + elif s == "center": + arm = [-1.5, -.1, 0, .7, 0, 0, 0] + elif s == "approach": + a[0] = .30 + arm = [-1.5, -.1, 0, .7, 0, 0, 0] + elif self.used_fallback and s in ("flip", "replace", "release"): + if s == "flip": + arm = [-1.5, .2, -.2, 1.5, 1.9, 0, 0] + grip = 1.0 + elif s == "replace": + arm = [-1.0, -.6, -.2, .7, 1.9, 0, 0] + grip = 1.0 + else: + arm = [-1.0, -.6, -.2, .7, 1.9, 0, 0] + elif s in ("reach", "close", "lift", "flip", "replace", "release"): + yaw, elbow, pitch, roll = self.candidates[self.trial] + if s == "reach": + arm = [pitch, roll, yaw, elbow, 0, 0, 0] + elif s == "close": + arm = [pitch, roll, yaw, elbow, 0, 0, 0] + grip = 1.0 + elif s == "lift": + arm = [-1.5, roll, yaw, .7, 0, 0, 0] + grip = 1.0 + elif s == "flip": + arm = [-1.5, roll, yaw, .7, 1.9, 0, 0] + grip = 1.0 + elif s == "replace": + arm = [pitch, roll, yaw, elbow, 1.9, 0, 0] + grip = 1.0 + else: + arm = [pitch, roll, yaw, elbow, 1.9, 0, 0] + elif s == "fallback": + arm = [-1.0, -.6, -.2, .7, 0, 0, 0] + elif s == "fallback_close": + arm = [-1.0, -.6, -.2, .7, 0, 0, 0] + grip = 1.0 + elif s == "fallback_lift": + arm = [-1.5, .2, -.2, 1.5, 0, 0, 0] + grip = 1.0 + else: + arm = [-1.5, -.1, 0, .7, 0, 0, 0] + a[5:12] = arm + a[19] = grip + self.age += 1 + return a diff --git a/policies/flip_cutlery/gpt6sol-s2/episodes.csv b/policies/flip_cutlery/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..bda1b00f2958755540d39c7c54272eb7f208ce0a --- /dev/null +++ b/policies/flip_cutlery/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,1,935,success,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,1,765,success,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt6sol-s2/policy.py b/policies/flip_cutlery/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..bf6a470d351b9df43bdb3d6d95cddd2877fe40db --- /dev/null +++ b/policies/flip_cutlery/gpt6sol-s2/policy.py @@ -0,0 +1,109 @@ +"""Deterministic visual servo and staged arm control for the spoon task.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.action = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.action[19] = 0.0 + self.phase = 0 + self.k = 0 + self.phase_start = self.action.copy() + self.mug_x = 48.0 + + def _advance(self): + self.phase += 1 + self.k = 0 + self.phase_start = self.action.copy() + + @staticmethod + def _cup_x(rgb): + """Find the gray mug above the bright tabletop in the head image.""" + im = rgb[:28].astype(np.int16) + spread = im.max(axis=2) - im.min(axis=2) + level = im.mean(axis=2) + mask = ((spread < 34) & (level > 57) & (level < 206)).astype(np.uint8) + mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)) + count, labels, stats, centers = cv2.connectedComponentsWithStats(mask, 8) + if count <= 1: + return None + candidates = [(int(stats[i, cv2.CC_STAT_AREA]), i) for i in range(1, count) + if stats[i, cv2.CC_STAT_AREA] >= 20 + and stats[i, cv2.CC_STAT_WIDTH] >= 5] + if not candidates: + return None + _, i = max(candidates) + return float(centers[i, 0]) + + def _set_arm(self, values): + self.action[5:12] = values + + def _blend_arm(self, values, duration): + u = min(1.0, (self.k + 1) / duration) + self.action[5:12] = self.phase_start[5:12] + u * ( + np.asarray(values, dtype=np.float32) - self.phase_start[5:12] + ) + + def act(self, obs, tools): + while True: + p = self.phase + k = self.k + self.action[0] = 0.0 + self.action[1] = 0.0 + self.action[3] = 0.0 + self.action[2] = 0.74 + self.action[4] = 0.0 + if p == 0: + self._set_arm([-1.1, .2, 0, 0, 0, 0, 0]) + self.action[19] = 0.0 + duration = 60 + elif p == 1: + self.action[0] = .2 + duration = 100 + elif p == 2: + if k % 5 == 0: + x = self._cup_x(tools.image('head')) + if x is not None: + self.mug_x = x + error = 48.0 - self.mug_x + if abs(error) <= 4.0 or k >= 130: + self._advance() + continue + self.action[1] = .16 if error > 0 else -.16 + duration = 131 + elif p == 3: + self._set_arm([-.6, .2, -.15, 0, 0, 0, -.3]) + self.action[19] = 0.0 + duration = 80 + elif p == 4: + self.action[19] = 1.0 + duration = 60 + elif p == 5: + self._blend_arm([-1.1, .2, -.15, 0, 0, 0, -.3], 100) + duration = 100 + elif p == 6: + self._blend_arm([-1.3, .2, -.4, 0, 0, 0, -.3], 100) + duration = 100 + elif p == 7: + self._blend_arm([-1.3, .2, -.4, 0, 1.7, 0, -.3], 200) + duration = 200 + elif p == 8: + self._blend_arm([-.85, .2, -.55, 0, 1.7, 0, -.3], 160) + duration = 160 + elif p == 9: + self._blend_arm([-.7, .2, -.55, 0, 1.7, 0, -.3], 100) + duration = 100 + elif p == 10: + self.action[19] = 0.0 + duration = 80 + elif p == 11: + self._blend_arm([-1.3, .2, -.4, 0, 1.7, 0, -.3], 120) + duration = 120 + else: + return self.action.copy() + self.k += 1 + if self.k >= duration: + self._advance() + return self.action.copy() diff --git a/policies/flip_cutlery/gpt6sol-s3/episodes.csv b/policies/flip_cutlery/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..bb64a87004eb4bae001df7ddcbb5c2739dea1b93 --- /dev/null +++ b/policies/flip_cutlery/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,821,success,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/gpt6sol-s3/policy.py b/policies/flip_cutlery/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f244734a6cedb83047e69725c24229108e118160 --- /dev/null +++ b/policies/flip_cutlery/gpt6sol-s3/policy.py @@ -0,0 +1,108 @@ +"""Hand-written visual and proprioceptive control for the spoon task.""" +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.stage = 'walk' + self.count = 0 + self.attempt = 0 + self.held = False + # The mug is the broad gray object at the top of the starting head view. + im = tools.image('head')[:14].astype(np.int16) + lo = im.min(axis=2) + hi = im.max(axis=2) + mean = im.mean(axis=2) + mask = (mean > 55) & (mean < 205) & ((hi - lo) < 45) + counts = mask.sum(axis=0) + cols = np.flatnonzero(counts > 3) + center = float(np.average(cols, weights=counts[cols])) if cols.size else 23.0 + self.yaw_bias = float(np.clip(0.012 * (47.0 - center), -0.20, 0.42)) + + def _pose(self): + b = self.yaw_bias + poses = [ + (0.70, -1.10, -0.05 + b, -0.40, 1.50, 0.0), + (0.70, -1.10, 0.05 + b, -0.40, 1.50, 0.0), + (0.70, -1.20, -0.10 + b, -0.40, 1.45, 0.0), + (0.68, -0.97, 0.04 + b, -0.45, 1.40, -0.15), + (0.72, -1.15, 0.10 + b, -0.40, 1.55, 0.0), + (0.68, -1.00, 0.15 + b, -0.40, 1.40, 0.0), + (0.72, -1.20, 0.25 + b, -0.40, 1.60, 0.0), + (0.68, -0.90, 0.25 + b, -0.50, 1.40, 0.0), + ] + return poses[min(self.attempt, len(poses) - 1)] + + def _advance(self, tools): + if self.stage == 'walk': + self.stage = 'settle' + elif self.stage == 'settle': + self.stage = 'approach' + elif self.stage == 'approach': + self.stage = 'grasp' + elif self.stage == 'grasp': + self.stage = 'lift' + elif self.stage == 'lift': + im = tools.image('left_wrist') + brightness = float(im[3:23, 35:49].mean()) + self.held = 101.0 < brightness < 170.0 + if self.held or self.attempt >= 7: + self.stage = 'flip' + else: + self.attempt += 1 + self.stage = 'approach' + elif self.stage == 'flip': + self.stage = 'replace' + elif self.stage == 'replace': + self.stage = 'release' + elif self.stage == 'release': + self.stage = 'retreat' + elif self.stage == 'retreat': + self.stage = 'hold' + self.count = 0 + + def act(self, obs, tools): + durations = {'walk': 65, 'settle': 45, 'approach': 65, + 'grasp': 45, 'lift': 70, 'flip': 100, + 'replace': 110, 'release': 80, 'retreat': 120} + if self.stage in durations and self.count >= durations[self.stage]: + self._advance(tools) + a = self.base.copy() + a[0:2] = 0 + a[19] = 0 + if self.stage == 'walk': + x = float(obs['low_dim_obs'][21]) + a[0] = 0.14 if x < 0.225 else 0.0 + elif self.stage == 'settle': + a[2] = 0.70 + elif self.stage in ('approach', 'grasp'): + h, sp, sy, el, wp, wy = self._pose() + a[2] = h + a[5:12] = [sp, 0, sy, el, 0, wp, wy] + if self.stage == 'grasp': + a[19] = min(1.0, self.count / 30.0) + elif self.stage == 'lift': + h, sp, sy, el, wp, wy = self._pose() + a[2] = 0.74 + a[5:12] = [-1.35, 0, sy, -0.55, 0, 1.5, wy] + a[19] = 1.0 + elif self.stage == 'flip': + _, _, sy, _, _, wy = self._pose() + u = min(1.0, self.count / 80.0) + a[2] = 0.74 + a[5:12] = [-1.35, 0, sy, -0.55, 0, 1.5 - 2.8*u, wy] + a[19] = 1.0 + elif self.stage in ('replace', 'release'): + _, _, sy, _, _, wy = self._pose() + a[2] = 0.70 + a[5:12] = [-1.05, 0, sy - 0.18, -0.25, 0, -1.30, wy] + a[19] = 1.0 if self.stage == 'replace' else 0.0 + elif self.stage == 'retreat': + a[2] = 0.74 + a[5:12] = [-0.7, 0, 0, -0.5, 0, 0.3, 0] + else: + a[2] = 0.74 + a[5:12] = [-0.7, 0, 0, -0.5, 0, 0.3, 0] + self.count += 1 + return a diff --git a/policies/flip_cutlery/kimi31pro-s1/episodes.csv b/policies/flip_cutlery/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/kimi31pro-s1/policy.py b/policies/flip_cutlery/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e0f97cbc768b8f71dd9c553107018e4bc08eeb --- /dev/null +++ b/policies/flip_cutlery/kimi31pro-s1/policy.py @@ -0,0 +1,77 @@ +"""Deterministic hand-written controller for the spoon flip task.""" + +import numpy as np + + +class Policy: + """Joint-space pick, overhead flip, and insertion controller.""" + + def reset(self, obs, tools): + self.raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.raw[:5] = (0.0, 0.0, 0.78, 0.0, -0.2) + self.raw[19:21] = 0.0 + self.phase = 0 + self.k = 0 + self.start = self.raw.copy() + + # Durations and targets are hand-tuned control constants, not a learned + # trajectory. The final two poses bracket the inverted wrist approach. + self.stages = [ + (70, "settle", None, 0.0, 0.78), + (80, "move", [-.76, -.12, 0., .56, -1., 0., 0.], 0.0, 0.78), + (15, "settle", None, 0.0, 0.78), + (35, "move", None, 1.0, 0.78), + (90, "move", [-1.10, -.12, 0., 1.65, -1., -.55, 0.], 1.0, 0.78), + (70, "move", [-1.10, .50, 0., 1.65, -1., -.55, 0.], 1.0, 0.78), + (140, "move", [-2.35, .50, 0., .10, -1., -.85, 0.], 1.0, 0.78), + (40, "settle", None, 1.0, 0.78), + (240, "move", [-.76, -.12, 0., .56, -1.972, 0., 1.614], 1.0, 0.78), + (40, "settle", None, 1.0, 0.78), + (60, "settle", None, 1.0, 0.70), + (40, "move", None, 0.0, 0.70), + (100, "settle", None, 0.0, 0.70), + # If the spoon remains at the grasp point, try the opposite wrist + # roll as a second deterministic placement attempt. + (35, "move", None, 1.0, 0.70), + (80, "move", [-.76, -.12, 0., .56, 1.972, -.18, 1.614], 1.0, 0.70), + (40, "move", None, 0.0, 0.70), + (200, "settle", None, 0.0, 0.70), + ] + + def _begin_stage(self): + self.start = self.raw.copy() + self.k = 0 + + def act(self, obs, tools): + while self.phase < len(self.stages) and self.k >= self.stages[self.phase][0]: + self.phase += 1 + self._begin_stage() + + if self.phase >= len(self.stages): + duration, mode, target, grip, height = self.stages[-1] + else: + duration, mode, target, grip, height = self.stages[self.phase] + + u = min(1.0, (self.k + 1) / float(duration)) + s = u * u * (3.0 - 2.0 * u) + raw = self.start.copy() + if target is not None: + target = np.asarray(target, dtype=np.float32) + raw[5:12] = self.start[5:12] * (1.0 - s) + target * s + raw[2] = self.start[2] * (1.0 - s) + height * s + raw[19] = self.start[19] * (1.0 - s) + grip * s + raw[20] = 0.0 + raw[4] = -0.2 + + # Keep the pelvis near the measured approach pose throughout the arm + # sequence; this removes slow drift during the flip and insertion. + b = np.asarray(obs["low_dim_obs"]) + x, y, _, yaw = b[21:25] + dx = 0.185 - x + raw[0] = np.clip(2.0 * dx, -0.1, 0.1) if abs(dx) > 0.015 else 0.0 + raw[1] = np.clip(-2.0 * y, -0.08, 0.08) if abs(y) > 0.015 else 0.0 + raw[3] = np.clip(-1.5 * yaw, -0.15, 0.15) if abs(yaw) > 0.02 else 0.0 + + self.raw = raw + self.k += 1 + return raw.copy() diff --git a/policies/flip_cutlery/kimi31pro-s2/episodes.csv b/policies/flip_cutlery/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/kimi31pro-s2/policy.py b/policies/flip_cutlery/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..668263a61896f2e3576ce56987558f1d1075a0f1 --- /dev/null +++ b/policies/flip_cutlery/kimi31pro-s2/policy.py @@ -0,0 +1,157 @@ +"""Deterministic hand-written controller for the spoon flipping task. + +The motion uses joint-space waypoints. In particular, the right hand supports +and then holds the spoon while the left hand withdraws; no learned models or +recorded demonstration data are used by this file. +""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.cur = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.cur[:5] = [0.0, 0.0, 0.74, 0.0, 0.0] + self.cur[5:19] = 0.0 + self.cur[19:21] = 0.0 + self.start = self.cur.copy() + self.target = None + self.stage_index = 0 + self.k = 0 + self.pending_hook = False + self.final_hook = False + + edge_l = np.array([-0.8, 0, 0, 0.6, 0, 0.2, 0], dtype=float) + edge_r = edge_l.copy() + + def s(name, n, hold=0, left=None, right=None, base=None, + lg=None, rg=None, hook=False): + return { + "name": name, "n": n, "hold": hold, + "left": left, "right": right, "base": base, + "lg": lg, "rg": rg, "hook": hook, + } + + # The two hands first rise clear of the table. The left wrist then + # approaches the exposed spoon with a small outward shoulder offset. + self.stages = [ + s("edge", 40, 10, edge_l, edge_r), + s("m10", 35, 10, [-1.0, 0, 0, 0.7, 0, 0.2, 0], edge_r), + s("align", 35, 10, [-1.2, 0.10, 0, 0.7, -0.6, 0.4, 0], edge_r), + s("grasp", 35, 20, [-1.3, 0.18, 0, 0.7, -0.6, 0.5, 0], edge_r, hook=True), + s("close", 40, 20, lg=1.0, hook=True), + s("lift", 50, 20, [-1.6, 0.18, 0, 1.3, -0.6, 0.2, 0], edge_r, hook=True), + s("lift2", 60, 20, [-1.9, 0.18, 0, 1.8, -0.6, 0.0, 0], edge_r, hook=True), + s("lift3", 70, 20, [-2.3, 0.18, 0, 2.05, -0.6, 0.15, 0], edge_r, hook=True), + s("rhigh", 70, 20, right=[-1.9, 0, 0, 1.8, 0.6, 0, 0], hook=True), + ] + + # Aim the right wrist without swinging the raised elbow through the + # spoon. The final pose gives a two-handed grasp before left release. + for wy, wp in [(0.0, 0.15), (0.0, -0.4), (0.5, -0.4), + (-0.5, -0.4), (1.0, -0.4)]: + self.stages.append(s( + "aim", 60, 20, + right=[-2.3, 0, 0, 2.05, 0.6, wp, wy], hook=True, + )) + + self.stages += [ + s("rightclose", 50, 20, rg=1.0, hook=True), + s("leftopen", 40, 20, lg=0.0, hook=True), + s("leftclear", 70, 20, + left=[-2.3, 0.6, 0, 2.05, -0.6, 0.15, 0], hook=True), + s("leftsafe", 80, 20, + left=[-0.8, 0.3, 0, 0.6, 0, 0.2, 0], hook=True), + s("rightflip", 130, 20, + right=[-2.3, 0, 0, 2.05, -1.97, -0.4, 1.0], hook=True), + s("walk", 170), + s("stop", 1, 19, base=[0, 0, 0.74, 0, 0], hook=True), + s("returnmid", 70, 10, + left=[-0.8, 0.3, 0, 0.6, 0, 0.2, 0], + right=[-1.9, 0, 0, 1.8, -1.97, 0.0, 1.0], + base=[0, 0, 0.68, 0, -0.2], hook=True), + s("return", 70, 10, + left=[-0.8, 0.3, 0, 0.6, 0, 0.2, 0], + right=[-1.3, 0, -0.7, 0.7, -1.97, 1.0, 0.4], + base=[0, 0, 0.68, 0, -0.2], hook=True), + s("release", 40, 20, rg=0.0, hook=True), + ] + + def _camera_hook(self, tools): + # Keep all three robot-camera views updated at the same phase + # boundaries used while calibrating the controller. + for camera in ("head", "left_wrist", "right_wrist"): + tools.image(camera) + + def _make_target(self, stage): + target = self.cur.copy() + if stage["base"] is not None: + target[:5] = stage["base"] + if stage["left"] is not None: + target[5:12] = stage["left"] + if stage["right"] is not None: + target[12:19] = stage["right"] + if stage["lg"] is not None: + target[19] = stage["lg"] + if stage["rg"] is not None: + target[20] = stage["rg"] + return target + + def _walk_action(self, obs): + q = obs["low_dim_obs"] + px, py, yaw = float(q[21]), float(q[22]), float(q[24]) + ex, ey = 0.44 - px, 0.26 - py + distance = float(np.hypot(ex, ey)) + yaw_error = (-0.09 - yaw + np.pi) % (2.0 * np.pi) - np.pi + cs, sn = np.cos(yaw), np.sin(yaw) + if distance > 0.025: + speed = 0.35 if distance > 0.06 else 0.09 + wx, wy = ex / distance * speed, ey / distance * speed + vx = cs * wx + sn * wy + vy = -sn * wx + cs * wy + else: + vx, vy = 0.0, 0.0 + raw = self.cur.copy() + raw[:5] = [vx, vy, 0.74, float(np.clip(3.0 * yaw_error, -0.8, 0.8)), 0.0] + return raw, distance, yaw_error + + def act(self, obs, tools): + if self.pending_hook: + self._camera_hook(tools) + self.pending_hook = False + + if self.stage_index >= len(self.stages): + if not self.final_hook and int(obs["t"]) >= 1900: + self._camera_hook(tools) + self.final_hook = True + return self.cur.copy() + + stage = self.stages[self.stage_index] + if self.target is None: + self.start = self.cur.copy() + self.target = self._make_target(stage) + + if stage["name"] == "walk": + raw, distance, yaw_error = self._walk_action(obs) + self.cur = raw.copy() + self.k += 1 + finished = ( + self.k >= stage["n"] + or (distance < 0.012 and abs(yaw_error) < 0.025) + ) + else: + n = stage["n"] + alpha = min(1.0, (self.k + 1) / n) + raw = self.start + (self.target - self.start) * alpha + self.cur = raw.copy() + self.k += 1 + finished = self.k >= n + stage["hold"] + + if finished: + self.stage_index += 1 + self.k = 0 + self.target = None + self.start = self.cur.copy() + self.pending_hook = bool(stage["hook"]) + + return self.cur.copy() diff --git a/policies/flip_cutlery/kimi31pro-s3/episodes.csv b/policies/flip_cutlery/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f545430cb1615087e7e7179ddf5c5dfded6cd431 --- /dev/null +++ b/policies/flip_cutlery/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,0,1950,timeout,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,0,1950,timeout,0 +620025,0,1950,timeout,0 +620026,0,1950,timeout,0 +620027,0,1950,timeout,0 +620028,0,1950,timeout,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,0,1950,timeout,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,0,1950,timeout,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,0,1950,timeout,0 +620047,0,1950,timeout,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,0,1950,timeout,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,0,1950,timeout,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,0,1950,timeout,0 +620083,0,1950,timeout,0 +620084,0,1950,timeout,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,0,1950,timeout,0 diff --git a/policies/flip_cutlery/kimi31pro-s3/policy.py b/policies/flip_cutlery/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cf4629cd3fd449c04eb8671cf9a62236b9a4d4b7 --- /dev/null +++ b/policies/flip_cutlery/kimi31pro-s3/policy.py @@ -0,0 +1,213 @@ +"""Deterministic, hand-written spoon flip controller. + +The controller uses the head camera to center the mug, a joint-space reach + calibrated from the demonstration, and wrist-camera corrections before the + pinch. The later phases are alternative ways of turning the spoon over and + returning it to the mug. No models, data files, or learned components are + used at run time. +""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.yaw_correction = 0.0 + self.pitch_correction = 0.0 + self.last_head_x = 42.0 + self.have_head_target = False + self.attempt_starts = (0, 400, 800, 1200, 1600) + self.attempt_yaws = (-0.45, -0.45, -0.42, -0.48, -0.45) + + @staticmethod + def _components(image, dark=False): + """Return neutral-gray connected components, excluding colored scenery.""" + im = np.asarray(image) + if im.ndim != 3: + return [] + a = im.astype(np.int16) + span = a.max(axis=2) - a.min(axis=2) + mean = a.mean(axis=2) + if dark: + mask = ((span < 30) & (mean > 30) & (mean < 135)).astype(np.uint8) + else: + mask = ((span < 36) & (mean > 65) & (mean < 225)).astype(np.uint8) + n, labels, stats, centroids = cv2.connectedComponentsWithStats(mask, 8) + out = [] + for i in range(1, n): + x, y, w, h, area = stats[i] + out.append((int(area), int(x), int(y), int(w), int(h), + float(centroids[i, 0]), float(centroids[i, 1]))) + return out + + def _head_mug(self, image): + # The cabinet and the robot occupy the lower half. The mug is the + # compact neutral object in the upper part of the head view. + candidates = [] + for area, x, y, w, h, cx, cy in self._components(image): + if y > 42 or x <= 1 or x + w >= 83: + continue + if area < 7 or w < 3 or h < 3 or w > 38 or h > 42: + continue + if cy > 43 or w * h > 1000: + continue + candidates.append((area, cx, cy, w, h)) + if not candidates: + return None + candidates.sort(key=lambda c: (c[0], -abs(c[1] - 42.0)), reverse=True) + return candidates[0] + + def _wrist_mug(self, image): + candidates = [] + for area, x, y, w, h, cx, cy in self._components(image): + if area < 22 or w < 5 or h < 6 or y < 8: + continue + if x <= 2 or x + w >= 83 or cy < 18: + continue + # Prefer the large mug body/rim, not the thin spoon or fingers. + candidates.append((area, cx, cy, w, h)) + if not candidates: + return None + candidates.sort(key=lambda c: c[0], reverse=True) + return candidates[0] + + def _approach(self, tools): + image = tools.image("head") + mug = self._head_mug(image) + if mug is None: + self.have_head_target = False + # A deterministic search, without dead-reckoning the base pose. + direction = 1.0 if self.last_head_x >= 42.0 else -1.0 + return 0.10, 0.0, 0.22 * direction + _, cx, cy, w, h = mug + self.last_head_x = cx + self.have_head_target = True + err = cx - 42.0 + # Object on the right: move/turn right; object on the left: left. + vx = 0.35 if abs(err) < 24.0 else 0.18 + vy = float(np.clip(-0.004 * err, -0.12, 0.12)) + wz = float(np.clip(-0.018 * err, -0.24, 0.24)) + return vx, vy, wz + + def _visual_update(self, tools): + mug = self._wrist_mug(tools.image("left_wrist")) + if mug is None: + return + _, cx, cy, _, _ = mug + # These are small corrections around the demonstrated grasp, not a + # learned image-to-action mapping. Their signs come from the joint + # probes: +yaw moves the viewed object right, -pitch moves it down. + self.yaw_correction = float(np.clip(0.012 * (58.0 - cx), -0.22, 0.22)) + self.pitch_correction = float(np.clip(0.004 * (cy - 58.0), -0.10, 0.10)) + + @staticmethod + def _blend(a, b, u): + u = float(np.clip(u, 0.0, 1.0)) + # Smooth endpoints reduce the impulse to the light spoon and to balance. + s = u * u * (3.0 - 2.0 * u) + return (1.0 - s) * np.asarray(a) + s * np.asarray(b) + + def act(self, obs, tools): + raw = self.hold.copy() + raw[2] = 0.74 + raw[4] = 0.0 + raw[12:19] = 0.0 + raw[20] = 0.6 + + attempt = 0 + for i, start in enumerate(self.attempt_starts): + if self.t >= start: + attempt = i + start = self.attempt_starts[attempt] + u = self.t - start + if u == 0: + self.yaw_correction = 0.0 + self.pitch_correction = 0.0 + zero = np.zeros(7, dtype=float) + grasp = np.array([-1.0, 0.0, self.attempt_yaws[attempt], + 0.5, -0.5, 0.0, 0.0], dtype=float) + + # Initial approach. Later attempts keep the base still and use the + # already acquired scene alignment. + if u < 45 and attempt == 0: + vx, vy, wz = self._approach(tools) + raw[0], raw[1], raw[3] = vx, vy, wz + else: + raw[0] = raw[1] = raw[3] = 0.0 + + if u < 50: + arm = zero + elif u < 110: + arm = self._blend(zero, grasp, (u - 50) / 60.0) + else: + arm = grasp.copy() + if u < 140 and (u % 4 == 0): + self._visual_update(tools) + arm[0] += self.pitch_correction + arm[2] += self.yaw_correction + + grip = 0.0 if u < 140 else 1.0 + # A short settling interval is important: at 140 the bowl is between + # the pads, whereas earlier closures pass in front of it. + if u >= 160: + arm = arm.copy() + if attempt == 0: + # Use the mug rim as a fulcrum and guide the bowl down into it. + if u < 205: + pressed = arm.copy() + pressed[0] = -1.32 + pressed[3] = 0.55 + arm = self._blend(arm, pressed, (u - 160) / 45.0) + grip = 1.0 if u < 220 else 0.0 + elif attempt == 1: + # Roll, then swing the bowl downward, and release over the mug. + if u < 195: + flipped = arm.copy() + flipped[4] = 1.5 + arm = self._blend(arm, flipped, (u - 160) / 35.0) + elif u < 230: + flipped = arm.copy() + flipped[5] = -1.2 + arm = self._blend(arm, flipped, (u - 195) / 35.0) + grip = 0.9 if u < 240 else 0.0 + elif attempt == 2: + # A quicker alternative imparts the turn before the bowl can + # squeeze out of a precision pinch. + if u < 180: + flipped = arm.copy() + flipped[4] = 1.9 + arm = self._blend(arm, flipped, (u - 160) / 20.0) + elif u < 210: + flipped = arm.copy() + flipped[5] = -1.5 + arm = self._blend(arm, flipped, (u - 180) / 30.0) + grip = 0.9 if u < 225 else 0.0 + elif attempt == 3: + # Arm-level turning arc, distinct from the wrist-only attempts. + if u < 205: + flipped = arm.copy() + flipped[0] = 0.35 + flipped[5] = 1.2 + arm = self._blend(arm, flipped, (u - 160) / 45.0) + elif u < 235: + returned = arm.copy() + returned[0] = -1.0 + arm = self._blend(arm, returned, (u - 205) / 30.0) + grip = 0.9 if u < 245 else 0.0 + else: + if u < 205: + flipped = arm.copy() + flipped[0] = -0.75 + flipped[6] = 1.5 + arm = self._blend(arm, flipped, (u - 160) / 45.0) + grip = 0.9 if u < 240 else 0.0 + + # After release, open the hand and leave the spoon undisturbed for the + # one-second task-success check. The next attempt starts from neutral. + raw[5:12] = np.clip(arm, -3.0892, 2.6704) + raw[19] = grip + self.t += 1 + return np.asarray(raw, dtype=np.float32) diff --git a/policies/flip_cutlery/opus-s1/episodes.csv b/policies/flip_cutlery/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..fd560831dc96a5ae4dc3d03cbbc16966f2efd62b --- /dev/null +++ b/policies/flip_cutlery/opus-s1/episodes.csv @@ -0,0 +1,62 @@ +seed,success,length,termination,fell +620001,1,984,success,0 +620002,1,1003,success,0 +620000,1,929,success,0 +620005,1,975,success,0 +620003,1,985,success,0 +620004,0,1950,timeout,0 +620006,1,948,success,0 +620007,1,960,success,0 +620008,1,960,success,0 +620010,1,973,success,0 +620011,1,960,success,0 +620013,1,985,success,0 +620014,0,1950,timeout,0 +620016,1,953,success,0 +620017,0,1950,timeout,0 +620019,1,930,success,0 +620020,1,955,success,0 +620023,1,938,success,0 +620022,1,985,success,0 +620026,0,1950,timeout,0 +620025,1,980,success,0 +620029,1,949,success,0 +620028,0,1950,timeout,0 +620032,1,969,success,0 +620031,1,971,success,0 +620035,0,1950,timeout,0 +620034,1,963,success,0 +620038,0,1950,timeout,0 +620037,1,986,success,0 +620041,1,949,success,0 +620040,1,935,success,0 +620043,1,989,success,0 +620044,0,1950,timeout,0 +620046,1,967,success,0 +620047,1,963,success,0 +620049,1,958,success,0 +620050,1,931,success,0 +620052,0,1950,timeout,0 +620053,0,1950,timeout,0 +620055,1,973,success,0 +620056,1,977,success,0 +620058,1,951,success,0 +620059,1,976,success,0 +620061,1,1012,success,0 +620062,1,984,success,0 +620064,1,961,success,0 +620065,1,913,success,0 +620067,1,931,success,0 +620068,0,1950,timeout,0 +620070,0,1950,timeout,0 +620071,0,1950,timeout,0 +620073,1,983,success,0 +620076,1,943,success,0 +620074,1,945,success,0 +620079,1,972,success,0 +620082,1,1000,success,0 +620085,1,991,success,0 +620088,0,1950,timeout,0 +620091,1,933,success,0 +620094,1,992,success,0 +620097,0,1950,timeout,0 diff --git a/policies/flip_cutlery/opus-s1/g1lib.py b/policies/flip_cutlery/opus-s1/g1lib.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bb366891e2d36f9c653098670f4ab8224f9edf --- /dev/null +++ b/policies/flip_cutlery/opus-s1/g1lib.py @@ -0,0 +1,587 @@ +"""Geometry helpers for the G1 policy: arm kinematics, calibrated cameras, IK, perception. + +All poses are expressed in the pelvis frame (x forward, y left, z up) unless noted. +Camera constants were calibrated against the floor checkerboard seen by the robot's +own cameras; the arm geometry is the G1 URDF. +""" + +import numpy as np +import cv2 + + +# ----------------------------------------------------------------------------- rotations +def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def rotvec(v): + v = np.asarray(v, float) + th = np.linalg.norm(v) + if th < 1e-12: + return np.eye(3) + k = v / 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 axis_angle(R): + """Rotation vector of R.""" + c = (np.trace(R) - 1) / 2 + c = min(1.0, max(-1.0, c)) + th = np.arccos(c) + if th < 1e-9: + return np.zeros(3) + if th > np.pi - 1e-6: + # near pi: axis from the symmetric part + M = (R + np.eye(3)) / 2 + k = np.sqrt(np.maximum(np.diag(M), 0)) + i = np.argmax(k) + k = M[i] / np.sqrt(M[i, i]) + return k * th + w = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) / (2 * np.sin(th)) + return w * th + + +def _T(R, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +# ----------------------------------------------------------------------------- arm kinematics +def _chain(side): + s = 1.0 if side == 'left' else -1.0 + j = [((0.0039563, s * 0.10022, 0.24778), rx(s * 0.27931), 1), + ((0, s * 0.038, -0.013831), rx(-s * 0.27925), 0), + ((0, s * 0.00624, -0.1032), np.eye(3), 2), + ((0.015783, 0, -0.080518), np.eye(3), 1), + ((0.100, s * 0.00188791, -0.010), np.eye(3), 0), + ((0.038, 0, 0), np.eye(3), 1), + ((0.046, 0, 0), np.eye(3), 2)] + return [(_T(R, p), ax) for p, R, ax in j] + + +CHAIN = {'left': _chain('left'), 'right': _chain('right')} +AXROT = [rx, ry, rz] + + +def torso_T(waist): + M = _T(rz(waist[0]), (0, 0, 0)) + M = M @ _T(rx(waist[1]), (-0.0039635, 0, 0.035)) + M = M @ _T(ry(waist[2]), (0, 0, 0.019)) + return M + + +def arm_fk(q, side, waist, frames=False): + M = torso_T(waist) + out = [] + for (F, ax), qi in zip(CHAIN[side], q): + M = M @ F + out.append((M[:3, 3].copy(), M[:3, ax].copy())) + R = AXROT[ax](qi) + M = M @ _T(R, (0, 0, 0)) + if frames: + return M, out + return M + + +# ----------------------------------------------------------------------------- cameras / tool +WRIST_T = np.array([0.123794, -0.007767, 0.009971]) +WRIST_R = rotvec([-0.001718, 0.691471, 0.004887]) +WRIST_F = 72.292 +HEAD_T = np.array([0.08114, -0.01431, 0.346961]) +HEAD_R = rotvec([0.016517, 1.025518, 0.012422]) +HEAD_F = 72.8 +# pelvis tilt at the reference posture (height 0.8, pitch -0.2) +PELVIS_ROLL, PELVIS_PITCH = -0.012116, 0.04783 +UP_P0 = (ry(PELVIS_PITCH) @ rx(PELVIS_ROLL)).T @ np.array([0, 0, 1.0]) +# closed fingertip direction in the camera frame (pixel 42,19) and distance +_d = np.array([1.0, 0.0, 23.0 / WRIST_F]) +_d /= np.linalg.norm(_d) + + +def mirror_R(R): + S = np.diag([1, -1, 1]) + return S @ R @ S + + +def hand_cam(side): + """camera position and rotation in the hand (wrist_yaw_link) frame.""" + if side == 'left': + return WRIST_T, WRIST_R + return WRIST_T * np.array([1, -1, 1]), mirror_R(WRIST_R) + + +def tool_point(side, depth=0.05): + """A point along the fingertip ray, 'depth' metres from the camera (hand frame).""" + t, R = hand_cam(side) + return t + R @ (_d * depth) + + +TOOL_TIP = 0.065 # closed fingertip +TOOL_GRASP = 0.05 # centre of the finger pads + + +def wrist_cam(q, side, waist): + M = arm_fk(q, side, waist) + t, R = hand_cam(side) + return M[:3, :3] @ t + M[:3, 3], M[:3, :3] @ R, WRIST_F + + +def head_cam(waist): + M = torso_T(waist) + return M[:3, :3] @ HEAD_T + M[:3, 3], M[:3, :3] @ HEAD_R, HEAD_F + + +def project(P, cam): + c, R, f = cam + pc = np.atleast_2d(np.asarray(P) - c) @ R + u = 42 - f * pc[:, 1] / pc[:, 0] + v = 42 - f * pc[:, 2] / pc[:, 0] + return np.stack([u, v], -1), pc[:, 0] + + +def pixel_ray(cam, u, v): + c, R, f = cam + d = R @ np.array([1.0, -(u - 42) / f, -(v - 42) / f]) + return c, d / np.linalg.norm(d) + + +_U, _V = np.meshgrid(np.arange(84) + 0.5, np.arange(84) + 0.5) + + +def rays(cam): + c, R, f = cam + d = np.stack([np.ones_like(_U), -(_U - 42) / f, -(_V - 42) / f], -1) @ R.T + return c, d + + +# ----------------------------------------------------------------------------- IK +LO = np.array([-3.0892, -0.25, -2.618, -1.0472, -1.9, -1.5, -1.5]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.9, 1.5, 1.5]) + + +def limits(side): + if side == 'left': + return LO, HI + lo, hi = -HI.copy(), -LO.copy() + for j in (0, 3, 5): + lo[j], hi[j] = LO[j], HI[j] + return lo, hi + + +def mirror_q(q): + q = np.array(q, float) + q[[1, 2, 4, 6]] *= -1 + return q + + +def tcp_pose(q, side, waist, tool): + M = arm_fk(q, side, waist) + return M[:3, :3] @ tool + M[:3, 3], M[:3, :3] + + +def jac(q, side, waist, tool): + M, fr = arm_fk(q, side, waist, frames=True) + pe = M[:3, :3] @ tool + M[:3, 3] + J = np.zeros((6, 7)) + for i, (p, a) in enumerate(fr): + J[:3, i] = np.cross(a, pe - p) + J[3:, i] = a + return pe, M[:3, :3], J + + +def ik1(p_t, R_t, q0, side, waist, tool, iters=150, wrot=0.4, qref=None, wref=0.05, damp=0.01, tol=1e-4): + q = np.asarray(q0, float).copy() + lo, hi = limits(side) + e = None + for _ in range(iters): + pe, Re, J = jac(q, side, waist, tool) + e = np.asarray(p_t) - pe + Jw = J[:3] + if R_t is not None: + dR = R_t @ Re.T + ang = 0.5 * np.array([dR[2, 1] - dR[1, 2], dR[0, 2] - dR[2, 0], dR[1, 0] - dR[0, 1]]) + if np.trace(dR) < -0.5: + ang = axis_angle(dR) + e = np.concatenate([e, ang * wrot]) + Jw = np.vstack([J[:3], J[3:] * wrot]) + if np.linalg.norm(e) < tol: + break + JJ = Jw @ Jw.T + damp ** 2 * np.eye(len(e)) + dq = Jw.T @ np.linalg.solve(JJ, e) + if qref is not None and wref > 0: + N = np.eye(7) - Jw.T @ np.linalg.solve(JJ, Jw) + dq += N @ (wref * (np.asarray(qref) - q)) + n = np.abs(dq).max() + if n > 0.3: + dq *= 0.3 / n + q = np.clip(q + dq, lo, hi) + return q, float(np.linalg.norm(e)) + + +SEEDS_L = [np.array(s, float) for s in [ + [-0.8, 0.3, 0, -0.3, 0, 0.5, 0], [-0.5, 0.2, 0, 0.3, 0, 0, 0], [-1.2, 0.4, 0, -0.6, 0, 0.8, 0], + [-1.0, 0.6, -0.5, -0.4, 0.5, 0.5, 0], [-1.0, 0.2, 0.5, 0.4, -0.5, 0.5, 0], [-1.4, 0.3, 0.3, 1.0, 0, 0.8, 0]]] + + +def ik(p_t, R_t, q0, side, waist, tool, qref=None, tol=2e-3, extra=(), iters=150): + """Multi-start IK. Returns (q, err) of the acceptable solution closest to q0.""" + seeds = [np.asarray(q0, float)] + list(extra) + first = True + best = None + for s in seeds + [x if side == 'left' else mirror_q(x) for x in SEEDS_L]: + q, e = ik1(p_t, R_t, s, side, waist, tool, iters=iters, qref=qref if qref is not None else q0) + if e < tol: + d = np.linalg.norm(q - q0) + if best is None or best[1] >= tol or d < best[2]: + best = (q, e, d) + if first: + return q, e + elif best is None or (best[1] >= tol and e < best[1]): + best = (q, e, np.linalg.norm(q - q0)) + first = False + return best[0], best[1] + + +def interp_pose(p0, R0, p1, R1, s): + w = axis_angle(R1 @ R0.T) + return p0 + (p1 - p0) * s, rotvec(w * s) @ R0 + + +def ik_path(poses, q0, side, waist, tool, step_pos=0.015, step_rot=0.12, qref=None, tol=2e-3, want_dense=False): + """Track a sequence of (p, R) poses from q0 with local IK only. + + Returns (list of q at each pose, max error, max joint jump between substeps). + """ + q = np.asarray(q0, float).copy() + out = [] + dense = [] + emax = 0.0 + jump = 0.0 + prev_p, prev_R = None, None + for p, R in poses: + if prev_p is None: + subs = [(p, R)] + else: + ang = np.linalg.norm(axis_angle(R @ prev_R.T)) + n = int(max(1, np.ceil(max(np.linalg.norm(p - prev_p) / step_pos, ang / step_rot)))) + subs = [interp_pose(prev_p, prev_R, p, R, (k + 1) / n) for k in range(n)] + seg = [] + for ps, Rs in subs: + qn, e = ik1(ps, Rs, q, side, waist, tool, iters=60, qref=qref if qref is not None else q, wref=0.02) + jump = max(jump, float(np.abs(qn - q).max())) + q = qn + seg.append(q.copy()) + emax = max(emax, e) + out.append(q.copy()) + dense.append(seg) + prev_p, prev_R = p, R + if want_dense: + return out, emax, jump, dense + return out, emax, jump + + +def servo_step(q_cmd, q_meas, waist, side, tool, p_t, R_t, gain=0.5, wrot=0.4, max_dq=0.05, qref=None): + """One resolved-rate correction of the joint command so that the measured TCP reaches (p_t, R_t).""" + pe, Re, J = jac(q_meas, side, waist, tool) + e = p_t - pe + Jw = J[:3] + if R_t is not None: + dR = R_t @ Re.T + ang = axis_angle(dR) + e = np.concatenate([e, ang * wrot]) + Jw = np.vstack([J[:3], J[3:] * wrot]) + JJ = Jw @ Jw.T + 0.01 ** 2 * np.eye(len(e)) + dq = Jw.T @ np.linalg.solve(JJ, gain * e) + if qref is not None: + N = np.eye(7) - Jw.T @ np.linalg.solve(JJ, Jw) + dq += N @ (0.02 * (qref - q_meas)) + n = np.abs(dq).max() + if n > max_dq: + dq *= max_dq / n + lo, hi = limits(side) + return np.clip(q_cmd + dq, lo - 0.2, hi + 0.2), float(np.linalg.norm(e[:3])) + + +# ----------------------------------------------------------------------------- grasp geometry +_tc, _Rc = hand_cam('left') +A_H = _Rc @ _d +C_H = np.array([0, 1.0, 0]) +C_H = C_H - (C_H @ A_H) * A_H +C_H /= np.linalg.norm(C_H) +B_H = np.cross(A_H, C_H) +FH = np.stack([A_H, C_H, B_H], 1) +UPZ = np.array([0, 0, 1.0]) + + +def hand_R(a, c): + a = a / np.linalg.norm(a) + c = c - (c @ a) * a + c /= np.linalg.norm(c) + return np.stack([a, c, np.cross(a, c)], 1) @ FH.T + + +def rot_about(axis, ang): + return rotvec(np.asarray(axis, float) / np.linalg.norm(axis) * ang) + + +SPOON_AZ = np.radians(104) # bowl direction from the mug axis (pelvis/world frame, yaw ~ 0) +SPOON_ELEV = np.radians(50) +BOWL_R = 0.072 +RELEASE_DROP = 0.03 # release TCP height = rim + 0.07 - RELEASE_DROP + + +def cart_plan(B, rhat, M, csign=1, psi=0.0, lift=0.20, elev=SPOON_ELEV): + zr = COUNTER_Z + MUG_H + d = np.cos(elev) * rhat + np.sin(elev) * UPZ + a = np.cross(rhat, UPZ) + c = csign * np.cross(a, d) + R0 = hand_R(a, c) + pre = B - 0.08 * a + 0.02 * UPZ + wps = [('hover', pre + 0.12 * UPZ, R0), ('pre', pre, R0), ('grasp', B, R0)] + P1 = B + lift * d + wps.append(('lifted', P1, R0)) + ang = np.arccos(np.clip(d @ -UPZ, -1, 1)) + Rr = None + for sgn in [1, -1]: + Rr = rot_about(a, sgn * ang) + if (Rr @ d) @ -UPZ > 0.99: + break + Rf = rot_about(UPZ, psi) @ Rr @ R0 + wps.append(('rotated', P1 + 0.02 * UPZ, Rf)) + above = np.array([M[0], M[1], zr + 0.07]) + wps.append(('above', above, Rf)) + wps.append(('release', above - RELEASE_DROP * UPZ, Rf)) + return wps, a + + +def plan_grasp(B, rhat, M, waist, q_start, tool, csigns=(1, -1), psis=(0, -30, 30, -60, 60)): + best = None + for csign in csigns: + for psi in np.radians(psis): + wps, a = cart_plan(B, rhat, M, csign=csign, psi=psi) + for s in [q_start] + SEEDS_L: + q0, e0 = ik1(wps[0][1], wps[0][2], s, 'left', waist, tool, iters=200, qref=s) + if e0 > 2e-3: + continue + qs, emax, jump = ik_path([(p, R) for _, p, R in wps], q0, 'left', waist, tool) + travel = sum(np.abs(qs[i + 1] - qs[i]).sum() for i in range(len(qs) - 1)) + ok = emax < 3e-3 and jump < 0.25 + cost = travel + (0 if ok else 100 + 100 * emax) + if best is None or cost < best[0]: + best = (cost, ok, wps, qs, a) + if best is not None and best[1] and best[0] < 12: + return best[1], best[2], best[3], best[4] + return best[1], best[2], best[3], best[4] + + +# ----------------------------------------------------------------------------- perception +def hsv(im): + return cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + + +def cyl_mask(cam, base, r, h, up): + o, d = rays(cam) + oc = o - base + d_ax = d @ up + o_ax = oc @ up + d_r = d - d_ax[..., None] * up + o_r = oc - o_ax * up + a = np.sum(d_r * d_r, -1) + b = 2 * np.sum(d_r * o_r, -1) + cc = np.sum(o_r * o_r) - r * r + disc = b * b - 4 * a * cc + ok = disc > 0 + sq = np.sqrt(np.where(ok, disc, 0)) + hit = np.zeros(d.shape[:2], bool) + for t in [(-b - sq) / (2 * a), (-b + sq) / (2 * a)]: + z = o_ax + t * d_ax + hit |= ok & (t > 0) & (z >= 0) & (z <= h) + t = (h - o_ax) / np.where(np.abs(d_ax) > 1e-9, d_ax, 1e-9) + p = oc + t[..., None] * d + rr = np.linalg.norm(p - (p @ up)[..., None] * up, axis=-1) + hit |= (t > 0) & (rr <= r) + return hit + + +COUNTER_Z = 0.058 # counter top (pelvis frame, reference posture) +COUNTER_X = 0.404 # counter front edge +MUG_R, MUG_H = 0.042, 0.115 + + +BOWL_H = 0.15 # bowl centre height above the counter top (along up) + + +def plane_hit(cam, u, v, h, up): + o, d = pixel_ray(cam, u, v) + t = (h - o @ up) / (d @ up) + return o + t * d + + +def detect_bowl(im, cam, mug_xy, up=UP_P0, h=None): + """Find the spoon bowl outside the mug in a wrist view from above. + + Returns (B, rhat, blob) with B the bowl centre (pelvis frame, at the assumed + height) and rhat the horizontal direction from the mug axis to the bowl. + """ + if h is None: + h = COUNTER_Z + BOWL_H + H = hsv(im) + m = (H[..., 1] < 15) & (H[..., 2] < 232) & (H[..., 2] > 30) + base = np.array([mug_xy[0], mug_xy[1], 0.0]) + base = base + (COUNTER_Z - base @ up) * up + mm = cyl_mask(cam, base, MUG_R + 0.008, MUG_H + 0.01, up) + rest = m & ~cv2.dilate(mm.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool) + n, lab, st, cen = cv2.connectedComponentsWithStats(rest.astype(np.uint8)) + best = None + for j in range(1, n): + area = st[j, cv2.CC_STAT_AREA] + if area < 25: + continue + P = plane_hit(cam, cen[j][0], cen[j][1], h, up) + rr = np.hypot(P[0] - mug_xy[0], P[1] - mug_xy[1]) + if rr > 0.14: + continue + sc = area - 2000 * abs(rr - 0.075) + if best is None or sc > best[0]: + best = (sc, j, P) + if best is None: + return None + _, j, B = best + blob = lab == j + ys, xs = np.nonzero(blob) + pts = np.array([plane_hit(cam, u + 0.5, v + 0.5, h, up)[:2] for u, v in zip(xs, ys)]) + mu = pts.mean(0) + w, V = np.linalg.eigh(np.cov((pts - mu).T)) + ax = V[:, -1] + # orient away from the mug + if ax @ (mu - np.asarray(mug_xy)) < 0: + ax = -ax + B = np.array([mu[0], mu[1], B[2]]) + return B, np.array([ax[0], ax[1], 0.0]), blob + + +def spoon_measure(im, v0=12): + """Spoon (metal) pixels in the approach view of the left wrist camera. + + Returns (max row width, centroid u, centroid v of the widest part, area) or None. + """ + H = hsv(im) + m = (H[..., 1] < 30) & (H[..., 2] > 60) & (H[..., 2] < 236) + m[:v0] = False + n, lab, st, cen = cv2.connectedComponentsWithStats(m.astype(np.uint8)) + best = None + for j in range(1, n): + area = st[j, cv2.CC_STAT_AREA] + if area < 12: + continue + cu = cen[j][0] + sc = area - 3.0 * abs(cu - 42) * 0 + if st[j, cv2.CC_STAT_HEIGHT] < 6: + continue + if best is None or sc > best[0]: + best = (sc, j) + if best is None: + return None + blob = lab == best[1] + w = blob.sum(1) + vmax = int(np.argmax(w)) + rows = np.nonzero(w >= 0.6 * w[vmax])[0] + ys, xs = np.nonzero(blob[rows.min():rows.max() + 1]) + return float(w[vmax]), float(xs.mean() + 0.5), float(rows.mean() + 0.5), int(blob.sum()) + + +def detect_bowl_iter(im, cam, mug_xy, rhat, n=3): + """detect_bowl with the mug mask re-centred from the bowl estimate.""" + r = None + M = np.asarray(mug_xy, float) + for _ in range(n): + r2 = detect_bowl(im, cam, M) + if r2 is None: + break + r = r2 + M = r[0][:2] - BOWL_R * rhat[:2] + return r + + +def blob_ray(cam, blob): + ys, xs = np.nonzero(blob) + return pixel_ray(cam, xs.mean() + 0.5, ys.mean() + 0.5) + + +def triangulate(rays): + A = sum(np.eye(3) - np.outer(d, d) for o, d in rays) + b = sum((np.eye(3) - np.outer(d, d)) @ o for o, d in rays) + X = np.linalg.solve(A, b) + res = max(np.linalg.norm((np.eye(3) - np.outer(d, d)) @ (X - o)) for o, d in rays) + return X, res + + +def head_mug_mask(im): + H = hsv(im) + m = (H[..., 1] < 7) & (H[..., 2] > 40) & (H[..., 2] < 235) + return m + + +def fit_mug_head(im, waist, up=UP_P0, vmax=None): + """Locate the mug on the counter from the head image. Returns (x, y) pelvis frame or None.""" + cam = head_cam(waist) + m = head_mug_mask(im) + # counter region only: pixels whose ray hits the counter top beyond the edge + o, d = rays(cam) + du = d @ up + t = (COUNTER_Z - o @ up) / np.where(np.abs(du) > 1e-9, du, 1e-9) + p = o + t[..., None] * d + region = (t > 0) & (p[..., 0] > COUNTER_X + 0.005) + m &= region + n, lab, st, cen = cv2.connectedComponentsWithStats(m.astype(np.uint8)) + if n < 2: + return None + k = 1 + np.argmax(st[1:, cv2.CC_STAT_AREA]) + if st[k, cv2.CC_STAT_AREA] < 30: + return None + blob = lab == k + ys, xs = np.nonzero(blob) + # initial guess: ray through the blob bottom hits the counter plane, push back by r + vb = ys.max() + 0.5 + ub = xs[ys >= ys.max() - 1].mean() + 0.5 + oc, dc = pixel_ray(cam, ub, vb) + t = (COUNTER_Z - oc @ up) / (dc @ up) + p0 = oc + t * dc + hd = dc - (dc @ up) * up + hd /= np.linalg.norm(hd) + p0 = p0 + MUG_R * hd + reg = region | blob + + def score(x, y): + base = np.array([x, y, 0.0]) + base = base + (COUNTER_Z - base @ up) * up + mm = cyl_mask(cam, base, MUG_R, MUG_H, up) + return np.sum((mm != blob) & (reg | mm)) + + best = (score(p0[0], p0[1]), p0[0], p0[1]) + step = 0.02 + while step > 0.0015: + improved = True + while improved: + improved = False + for dx, dy in [(step, 0), (-step, 0), (0, step), (0, -step)]: + s = score(best[1] + dx, best[2] + dy) + if s < best[0]: + best = (s, best[1] + dx, best[2] + dy) + improved = True + step /= 2 + return np.array([best[1], best[2]]), blob diff --git a/policies/flip_cutlery/opus-s1/policy.py b/policies/flip_cutlery/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1847eeafb0f93038bc363d60192e69192ee0a73a --- /dev/null +++ b/policies/flip_cutlery/opus-s1/policy.py @@ -0,0 +1,304 @@ +"""Flip the spoon in the mug with the left arm of the G1. + +Pipeline (all perception from the robot's own cameras): + 1. look: lean back, find the mug with the head camera (calibrated pinhole + cylinder fit). + 2. walk: step so that the mug sits at a fixed spot in front of the left arm. + 3. view: look down at the mug with the left wrist camera and find the spoon bowl. + 4. grasp: side-grasp the bowl (fingers tangential to the mug), close. + 5. flip: pull the spoon out along its axis, roll it bowl-down, carry it over the mug. + 6. place: lower until the bowl is in the opening, open, back away. +""" + +import numpy as np + +import g1lib as G + +P0_HEIGHT, P0_PITCH = 0.80, -0.20 # reference posture (cameras calibrated here) +WALK_HEIGHT = 0.74 +MSTAR = np.array([0.40, 0.12]) # mug position in the pelvis frame we walk to +QUP = np.array([-0.6, 0.15, 0, -0.9, 0, 0, 0]) +QREF = np.array([-0.8, 0.3, 0, -0.3, 0, 0, 0]) +TOOL = G.tool_point('left', G.TOOL_GRASP) +RELEASE_GRIP = 0.4 +USE_TRI = False + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.cmd = self.hold.copy() + self.cmd[2], self.cmd[4] = P0_HEIGHT, P0_PITCH + self.cmd[19] = self.cmd[20] = 0.0 + self.phase = 'look' + self.t_phase = 0 + self.corr = np.zeros(7) + self.log = [] + self.mug_w = None + self.seg = None + + # ------------------------------------------------------------------ helpers + def set_phase(self, name): + self.phase = name + self.t_phase = 0 + + def ld(self, obs): + return np.asarray(obs['low_dim_obs'], dtype=np.float64) + + def joint_move(self, q_from, q_to, n): + return [q_from + (q_to - q_from) * (0.5 - 0.5 * np.cos(np.pi * (k + 1) / n)) for k in range(n)] + + def to_world(self, lo, p, R): + pel = lo[21:25] + Rz = G.rz(pel[3]) + pw = Rz @ p + pw[:2] += pel[:2] + return pw, Rz @ R + + def from_world(self, lo, pw, Rw): + pel = lo[21:25] + Rz = G.rz(-pel[3]) + d = pw.copy() + d[:2] -= pel[:2] + return Rz @ d, Rz @ Rw + + def ray_to_world(self, lo, o, d): + pw, Rw = self.to_world(lo, o, np.eye(3)) + return pw, Rw @ d + + def ray_from_world(self, lo, o, d): + p, R = self.from_world(lo, o, np.eye(3)) + return p, R @ d + + def start_cart(self, wposes, qs, steps=3, hold=15): + """Follow dense world-frame poses with live IK + integral joint correction.""" + self.seg = dict(poses=wposes, qs=qs, steps=steps, hold=hold, k=0) + + def run_cart(self, lo): + s = self.seg + n = len(s['qs']) + idx = min(n - 1, s['k'] // s['steps']) + s['k'] += 1 + pw, Rw = s['poses'][idx] + p_t, R_t = self.from_world(lo, pw, Rw) + # live IK from the previous nominal command (planned joints used as posture reference) + q, e = G.ik1(p_t, R_t, self.qn, 'left', lo[0:3], TOOL, iters=8, qref=s['qs'][idx], wref=0.05) + self.qn = q + self.corr = np.clip(self.corr + 0.1 * (self.qn - lo[3:10]), -0.3, 0.3) + self.cmd[5:12] = self.qn + self.corr + done = s['k'] >= n * s['steps'] + s['hold'] + return done, e + + def camera_q(self, lo, cp, tg): + """Joint target putting the left wrist camera at cp looking at tg.""" + q_best, e_best = None, 1e9 + for roll in (0.0, 0.4, -0.4, 0.8, -0.8): + Rcam = lookat_R(cp, tg, roll) + tc, Rc = G.hand_cam('left') + Rh = Rcam @ Rc.T + ph = cp - Rh @ tc + q, e = G.ik(ph, Rh, lo[3:10], 'left', lo[0:3], np.zeros(3), qref=QREF) + if e < 3e-3: + return q + if e < e_best: + q_best, e_best = q, e + return q_best + + def joint_servo(self, lo, q_t, ki=0.1): + self.corr = np.clip(self.corr + ki * (q_t - lo[3:10]), -0.3, 0.3) + self.cmd[5:12] = q_t + self.corr + + # ------------------------------------------------------------------ main + def act(self, obs, tools): + lo = self.ld(obs) + self.t_phase += 1 + t = self.t_phase + a = self.cmd + a[0] = a[1] = a[3] = 0.0 + + if self.phase == 'look': + if t >= 40: + im = tools.image('head') + r = G.fit_mug_head(im, lo[0:3]) + pel = lo[21:25] + if r is None: + mug = np.array([0.47, 0.0]) + else: + mug = r[0] + self.mug_p0 = mug + self.mug_w = pel[:2] + G.rz(pel[3])[:2, :2] @ mug + self.walk_target = self.mug_w - MSTAR + self.q_start = a[5:12].copy() + self.set_phase('raise') + + elif self.phase == 'raise': + frac = min(1.0, t / 40) + s = 0.5 - 0.5 * np.cos(np.pi * frac) + a[5:12] = self.q_start + (QUP - self.q_start) * s + a[12:19] = G.mirror_q(QUP) * s + a[2] = P0_HEIGHT + (WALK_HEIGHT - P0_HEIGHT) * s + a[4] = P0_PITCH * (1 - s) + if t >= 50: + self.set_phase('walk') + + elif self.phase == 'walk': + p = lo[21:25] + e = self.walk_target - p[:2] + eb = G.rz(-p[3])[:2, :2] @ e + v = 1.2 * eb + nv = np.linalg.norm(v) + if np.linalg.norm(e) < 0.01: + v = np.zeros(2) + elif nv < 0.07: + v = v / nv * 0.07 + elif nv > 0.2: + v = v / nv * 0.2 + a[0], a[1] = v + a[3] = float(np.clip(-1.5 * p[3], -0.3, 0.3)) if abs(p[3]) > 0.02 else 0.0 + if (np.linalg.norm(e) < 0.01 and t > 20) or t > 400: + a[0] = a[1] = a[3] = 0.0 + self.set_phase('settle') + + elif self.phase == 'settle': + frac = min(1.0, max(0, t - 30) / 40) + s = 0.5 - 0.5 * np.cos(np.pi * frac) + a[2] = WALK_HEIGHT + (P0_HEIGHT - WALK_HEIGHT) * s + a[4] = P0_PITCH * s + if t >= 100: + pel = lo[21:25] + self.M_odo = G.rz(-pel[3])[:2, :2] @ (self.mug_w - pel[:2]) + # top view of the mug with the left wrist camera + zc = G.COUNTER_Z + M = self.M_odo + cp = np.array([M[0] - 0.10, M[1] + 0.06, zc + 0.30]) + tg = np.array([M[0], M[1] + 0.04, zc + 0.10]) + self.q_view = self.camera_q(lo, cp, tg) + self.traj = self.joint_move(a[5:12] - self.corr, self.q_view, 60) + self.set_phase('to_view') + + elif self.phase == 'to_view': + k = min(t - 1, len(self.traj) - 1) + self.joint_servo(lo, self.traj[k]) + if t >= len(self.traj) + 30: + im = tools.image('left_wrist') + cam = G.wrist_cam(lo[3:10], 'left', lo[0:3]) + rh = np.array([np.cos(G.SPOON_AZ), np.sin(G.SPOON_AZ), 0.0]) + r = G.detect_bowl_iter(im, cam, self.M_odo, rh) + self.ray1 = None + if r is not None: + B = r[0] + self.ray1 = self.ray_to_world(lo, *G.blob_ray(cam, r[2])) + else: + B = np.array([self.M_odo[0], self.M_odo[1], 0]) + G.BOWL_R * rh + B[2] = (G.COUNTER_Z + G.BOWL_H) + self.B1 = B + # second, near-vertical look at the bowl: horizontal position insensitive to its height + cp = B + np.array([-0.05, 0.0, 0.20]) + self.q_view2 = self.camera_q(lo, cp, B) + self.traj = self.joint_move(a[5:12] - self.corr, self.q_view2, 40) + self.set_phase('to_view2') + + elif self.phase == 'to_view2': + k = min(t - 1, len(self.traj) - 1) + self.joint_servo(lo, self.traj[k]) + if t >= len(self.traj) + 25: + rh = np.array([np.cos(G.SPOON_AZ), np.sin(G.SPOON_AZ), 0.0]) + im = tools.image('left_wrist') + cam = G.wrist_cam(lo[3:10], 'left', lo[0:3]) + B1 = self.B1 + r = G.detect_bowl_iter(im, cam, B1[:2] - G.BOWL_R * rh[:2], rh) + B = B1 + self.tri = None + if r is not None and np.linalg.norm(r[0][:2] - B1[:2]) < 0.06: + B = r[0] + if self.ray1 is not None: + o1, d1 = self.ray_from_world(lo, *self.ray1) + X, res = G.triangulate([(o1, d1), G.blob_ray(cam, r[2])]) + self.tri = (X, res) + if USE_TRI and res < 0.008 and abs(X[2] - B[2]) < 0.05 and np.linalg.norm(X[:2] - B[:2]) < 0.04: + B = X + self.B2 = B + M = B[:2] - G.BOWL_R * rh[:2] + self.B, self.M = B, M + ok, wps, qs, axis_a = G.plan_grasp(B, rh, M, lo[0:3], lo[3:10], TOOL) + self.plan_ok = ok + self.wps, self.axis_a = wps, axis_a + _, emax, jump, dense = G.ik_path([(p, R) for _, p, R in wps], qs[0], 'left', lo[0:3], TOOL, want_dense=True) + # dense poses for servoing + poses = [] + prev = None + for (lab, p, R), seg in zip(wps, dense): + if prev is None: + poses.append([(p, R)]) + else: + nn = len(seg) + poses.append([G.interp_pose(prev[0], prev[1], p, R, (k + 1) / nn) for k in range(nn)]) + prev = (p, R) + self.dense = dense + self.dposes = [[self.to_world(lo, p, R) for p, R in seg] for seg in poses] + self.release_w = self.to_world(lo, wps[-1][1], wps[-1][2]) + self.traj = self.joint_move(a[5:12] - self.corr, qs[0], 60) + self.set_phase('to_hover') + + elif self.phase == 'to_hover': + k = min(t - 1, len(self.traj) - 1) + self.joint_servo(lo, self.traj[k]) + if t >= len(self.traj) + 20: + self.wi = 1 + self.qn = self.traj[-1].copy() + self.start_cart(self.dposes[1], self.dense[1], steps=3, hold=15) + self.set_phase('cart') + + elif self.phase == 'cart': + done, err = self.run_cart(lo) + lab = self.wps[self.wi][0] + if done: + if lab == 'grasp' and a[19] < 0.5: + a[19] = 1.0 + self.set_phase('close') + return a.astype(np.float32) + if lab == 'release': + a[19] = RELEASE_GRIP + self.set_phase('open') + return a.astype(np.float32) + self.wi += 1 + self.start_cart(self.dposes[self.wi], self.dense[self.wi], steps=3, hold=15) + + elif self.phase == 'close': + # keep servoing at the grasp pose + self.seg['k'] = len(self.seg['qs']) * self.seg['steps'] + self.run_cart(lo) + if t >= 30: + self.grip_state = lo[50] + self.wi += 1 + self.start_cart(self.dposes[self.wi], self.dense[self.wi], steps=4, hold=10) + self.set_phase('cart') + + elif self.phase == 'open': + if t >= 25: + p, R = self.from_world(lo, *self.release_w) + p_up = p + 0.14 * G.UPZ + p_back = p_up - 0.08 * (R @ G.A_H) + qs, emax, jump, dense = G.ik_path([(p, R), (p_up, R), (p_back, R)], self.qn, 'left', lo[0:3], TOOL, want_dense=True) + poses = [G.interp_pose(p, R, p_up, R, (k + 1) / len(dense[1])) for k in range(len(dense[1]))] + \ + [G.interp_pose(p_up, R, p_back, R, (k + 1) / len(dense[2])) for k in range(len(dense[2]))] + self.start_cart([self.to_world(lo, pp, RR) for pp, RR in poses], dense[1] + dense[2], steps=4, hold=10) + self.set_phase('retreat') + + elif self.phase == 'retreat': + done, err = self.run_cart(lo) + if done: + self.set_phase('done') + + elif self.phase == 'done': + pass + + return a.astype(np.float32) + + +def lookat_R(cam_pos, target, roll=0.0): + x = np.asarray(target, float) - cam_pos + x /= np.linalg.norm(x) + y = np.cross(np.array([0, 0, 1.0]), x) + y /= np.linalg.norm(y) + z = np.cross(x, y) + return np.stack([x, y, z], 1) @ G.rx(roll) diff --git a/policies/flip_cutlery/opus-s2/episodes.csv b/policies/flip_cutlery/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7162d2044b9d9f11d019760a3ed7c1a435acb1e0 --- /dev/null +++ b/policies/flip_cutlery/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1419,success,0 +620001,1,1439,success,0 +620002,1,1525,success,0 +620003,0,1950,timeout,0 +620004,1,1442,success,0 +620005,1,1440,success,0 +620006,1,1476,success,0 +620007,0,1950,timeout,0 +620008,1,1432,success,0 +620009,1,1427,success,0 +620010,1,1369,success,0 +620011,1,1432,success,0 +620012,1,1430,success,0 +620013,1,1400,success,0 +620014,0,1950,timeout,0 +620015,1,1442,success,0 +620016,1,1494,success,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,1,1431,success,0 +620020,1,1415,success,0 +620021,0,1950,timeout,0 +620022,1,1370,success,0 +620023,1,1413,success,0 +620024,1,1401,success,0 +620025,1,1440,success,0 +620026,1,1724,success,0 +620027,1,1446,success,0 +620028,1,1562,success,0 +620029,1,1410,success,0 +620030,0,1950,timeout,0 +620031,0,1950,timeout,0 +620032,1,1379,success,0 +620033,0,1950,timeout,0 +620034,1,1457,success,0 +620035,1,1389,success,0 +620036,1,1495,success,0 +620037,1,1454,success,0 +620038,0,1950,timeout,0 +620039,1,1474,success,0 +620040,1,1425,success,0 +620041,0,1950,timeout,0 +620042,1,1446,success,0 +620043,1,1467,success,0 +620044,1,1455,success,0 +620045,0,1950,timeout,0 +620046,1,1451,success,0 +620047,1,1422,success,0 +620048,1,1477,success,0 +620049,1,1424,success,0 +620050,1,1412,success,0 +620051,0,1950,timeout,0 +620052,1,1461,success,0 +620053,0,1950,timeout,0 +620054,0,1950,timeout,0 +620055,1,1445,success,0 +620056,0,1950,timeout,0 +620057,1,1484,success,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,0,1950,timeout,0 +620061,1,1727,success,0 +620062,1,1731,success,0 +620063,1,1465,success,0 +620064,0,1950,timeout,0 +620065,1,1370,success,0 +620066,1,1455,success,0 +620067,1,1415,success,0 +620068,1,1668,success,0 +620069,1,1358,success,0 +620070,1,1465,success,0 +620071,1,1550,success,0 +620072,0,1950,timeout,0 +620073,0,1950,timeout,0 +620074,1,1442,success,0 +620075,0,1950,timeout,0 +620076,1,1548,success,0 +620077,1,1471,success,0 +620078,1,1413,success,0 +620079,1,1405,success,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,1,1713,success,0 +620083,1,1447,success,0 +620084,1,1483,success,0 +620085,1,1554,success,0 +620086,0,1950,timeout,0 +620087,1,1457,success,0 +620088,1,1422,success,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,1,1432,success,0 +620092,1,1463,success,0 +620093,0,1950,timeout,0 +620094,1,1490,success,0 +620095,1,1410,success,0 +620096,1,1446,success,0 +620097,1,1386,success,0 +620098,0,1950,timeout,0 +620099,1,1402,success,0 diff --git a/policies/flip_cutlery/opus-s2/policy.py b/policies/flip_cutlery/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d0133989b73166c40878d077490cc2c8eb702f6c --- /dev/null +++ b/policies/flip_cutlery/opus-s2/policy.py @@ -0,0 +1,514 @@ +"""Flip-cutlery policy for the G1: take the spoon out of the mug, flip it, put it back. + +Hand-written pipeline (no learned parts): + 1. head camera: find the mug (white blob on the counter), estimate its position + 2. walk to a stance fixed relative to the mug + 3. left wrist camera from above: refine the mug centre + 4. left hand: pinch the spoon bowl (spoon leans the same way in every scene), + lift it out, roll the wrist 180 deg so the bowl points down + 5. lower the bowl into the mug, release gently, retreat and hold still + +Kinematics: forward kinematics from the G1 description, numeric IK (scipy). +Camera models were calibrated against the robot's own body during development. +""" + +import cv2 +import numpy as np +from scipy import ndimage +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation as Rot, Slerp + +# ----------------------------------------------------------------------------- kinematics + + +def rot(axis, a): + c, s = np.cos(a), np.sin(a) + if axis == 'x': + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + if axis == 'y': + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def rpy(r, p, y): + return rot('z', y) @ rot('y', p) @ rot('x', r) + + +def T(R=np.eye(3), p=(0, 0, 0)): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +def axis_rot(k, th): + k = k / np.linalg.norm(k) + 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 _chain(side): + s = 1 if side == 'L' else -1 + return [ + (T(p=(0, 0, 0)), 'z'), + (T(p=(-0.0039635, 0, 0.035)), 'x'), + (T(p=(0, 0, 0.019)), 'y'), + (T(rpy(s * 0.27931, 0, 0), (0.0039563, s * 0.10022, 0.24778)), 'y'), + (T(rpy(-s * 0.27925, 0, 0), (0, s * 0.038, -0.013831)), 'x'), + (T(p=(0, s * 0.00624, -0.1032)), 'z'), + (T(p=(0.015783, 0, -0.080518)), 'y'), + (T(p=(0.100, s * 0.00188791, -0.010)), 'x'), + (T(p=(0.038, 0, 0)), 'y'), + (T(p=(0.046, 0, 0)), 'z'), + ] + + +CHAINS = {'L': _chain('L'), 'R': _chain('R')} + + +def fk(q7, side, waist): + M = np.eye(4) + for (F, ax), q in zip(CHAINS[side], list(waist) + list(q7)): + M = M @ F @ T(rot(ax, q)) + return M + + +JLO = np.array([-3.0892, 0.05, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +JHI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +QNAT = np.array([-1.0, 0.25, 0.0, 0.6, 0.0, 0.0, 0.0]) + + +def mirror_q(q): + q = np.array(q, dtype=float) + q[[1, 2, 4, 6]] *= -1 + return q + + +def lims(side): + if side == 'L': + return JLO, JHI + lo, hi = JLO.copy(), JHI.copy() + for i in (1, 2, 4, 6): + lo[i], hi[i] = -JHI[i], -JLO[i] + return lo, hi + + +IK_SEEDS = [ + [-1.2, 0.2, 0.0, 0.8, 0.0, 0.3, 0.0], + [-1.0, 0.5, 0.3, 0.3, 0.0, 0.0, 0.0], + [-1.5, 0.1, -0.3, 1.0, 0.0, -0.3, 0.0], + [-0.8, 0.3, 0.0, 0.0, 1.2, 0.5, 0.0], + [-0.8, 0.3, 0.0, 0.0, -1.2, 0.5, 0.0], + [-1.4, 1.0, 0.5, 0.5, -1.0, 0.0, 0.0], + [-1.4, 1.0, 0.5, 0.5, 1.0, 0.0, 0.0], + [-0.5, 0.0, 0.0, -0.5, 0.0, 1.0, 0.0], +] + + +def ik(pos, side, waist, axes, tool=(0, 0, 0), q0=None, multistart=True, reg=0.005, wrot=0.5): + lo, hi = lims(side) + tvec = np.r_[np.asarray(tool, float), 1.0] + qref = QNAT if side == 'L' else mirror_q(QNAT) + + def res(q): + M = fk(q, side, waist) + r = list((M @ tvec)[:3] - pos) + for la, wd, w in axes: + r += list(wrot * w * (M[:3, :3] @ la - wd)) + r += list(reg * (q - qref)) + return np.array(r) + + starts = [] + if q0 is not None: + starts.append(np.asarray(q0, float)) + if multistart or q0 is None: + starts += [np.array(s) if side == 'L' else mirror_q(s) for s in IK_SEEDS] + best = None + for k, s0 in enumerate(starts): + sol = least_squares(res, np.clip(s0, lo + 1e-3, hi - 1e-3), bounds=(lo, hi), max_nfev=200) + if best is None or sol.cost < best.cost - 1e-9: + best = sol + if k == 0 and q0 is not None and sol.cost < 1e-5: + break + M = fk(best.x, side, waist) + return best.x, float(np.linalg.norm((M @ tvec)[:3] - pos)) + + +# ----------------------------------------------------------------------------- cameras + +HEAD = np.array([0.037855, -0.0025, 0.51608, 1.056374, -0.043605, -0.100081, 102.313833]) +WRIST = np.array([0.096, -0.018, 0.08, 0.061, 0.737, 0.081, 89.1]) +T_WCAM_L = T(rot('z', WRIST[5]) @ rot('y', WRIST[4]) @ rot('x', WRIST[3]), WRIST[0:3]) + + +def world_T(lo): + return T(rot('z', lo[24]), lo[21:24]) + + +def torso_world(lo): + M = world_T(lo) + for (F, ax), q in zip(CHAINS['L'][:3], lo[0:3]): + M = M @ F @ T(rot(ax, q)) + return M + + +def head_ray(lo, u, v): + p = HEAD + C = torso_world(lo) @ T(rot('z', p[4]) @ rot('y', p[3]) @ rot('x', p[5]), p[0:3]) + d = C[:3, :3] @ np.array([1.0, -(u - 41.5) / p[6], -(v - 41.5) / p[6]]) + return C[:3, 3], d / np.linalg.norm(d) + + +def lwrist_ray(lo, u, v): + C = world_T(lo) @ fk(lo[3:10], 'L', lo[0:3]) @ T_WCAM_L + d = C[:3, :3] @ np.array([1.0, -(u - 41.5) / WRIST[6], -(v - 41.5) / WRIST[6]]) + return C[:3, 3], d / np.linalg.norm(d) + + +def plane_hit(o, d, z): + return o + (z - o[2]) / d[2] * d + + +Z_COUNTER = 0.845 +Z_RIM = 0.963 +MUG_R = 0.035 + + +def find_mug_head(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + m = (hsv[..., 1] < 40) & (hsv[..., 2] > 60) & (hsv[..., 2] < 235) + br = (hsv[..., 0] >= 5) & (hsv[..., 0] <= 25) & (hsv[..., 1] > 80) & (hsv[..., 2] < 200) + rows = np.nonzero(br[:, 20:64])[0] + edge = int(np.median(rows)) if len(rows) else 84 + m[max(edge - 1, 0):, :] = False + lab, n = ndimage.label(m) + if n == 0: + return None + sizes = ndimage.sum(m, lab, range(1, n + 1)) + k = int(np.argmax(sizes)) + 1 + if sizes[k - 1] < 30: + return None + ys, xs = np.nonzero(lab == k) + vb = ys.max() + 0.5 + ub = xs[ys >= ys.max() - 1].mean() + return ub, vb + + +def find_opening(im): + """Dark interior of the mug seen from above in the wrist camera -> (u, v) centroid.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] + blue = (h > 90) & (h < 130) & (s > 60) + m = (v < 150) & (v > 20) & (s < 50) & ~blue + m = ndimage.binary_opening(m, iterations=1) + lab, n = ndimage.label(m) + if n == 0: + return None + best, bscore = None, 0 + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + if len(xs) < 40: + continue + # prefer compact blobs near the expected location (image centre) + score = len(xs) / (1.0 + 0.02 * ((xs.mean() - 42) ** 2 + (ys.mean() - 36) ** 2)) + if score > bscore: + best, bscore = k, score + if best is None: + return None + blob = lab == best + rows = np.nonzero(blob.any(axis=1))[0] + top = rows.min() + widths, mids = [], [] + for r in range(top, min(top + 14, 84)): + xs = np.nonzero(blob[r])[0] + if len(xs): + widths.append(xs.max() - xs.min() + 1) + mids.append(0.5 * (xs.max() + xs.min())) + widths = np.array(widths, float) + mids = np.array(mids) + # the far rim (top rows) is never covered by the spoon bowl, which hangs out on the near side + u = float(np.median(mids[1:6])) if len(mids) > 3 else float(mids.mean()) + v = top + 7.4 + return u, v, widths.max() + + +# ----------------------------------------------------------------------------- task constants +# Everything below is relative to the mug centre (rim height), tuned on seed 56. +SPOON_DIR = np.array([0.0, 0.22, 0.975]) / np.linalg.norm([0.0, 0.22, 0.975]) +TIP_OFF = np.array([0.023, 0.069, 0.075]) # bowl tip relative to rim centre +RETRIES = ((0, 0, 0), (0, -0.015, 0), (0, 0.015, 0), (0.025, 0, 0), (-0.025, 0, 0), + (0, 0, -0.015), (0, -0.03, 0), (0, 0.03, 0)) +GRASP_BELOW = 0.04 # pinch point below the tip along the spoon +BASE_OFF = np.array([-0.41, -0.06]) # stance relative to the mug centre +LOOK_CAM = np.array([-0.08, -0.014, 0.287]) # left wrist camera position relative to mug centre +TOOL = np.array([0.17, 0.0, 0.0]) # pinch point in the hand frame +UP_L = np.array([-0.3, 0.2, 0, -1.0, 0, 0, 0]) +UP_R = np.array([-0.3, -0.2, 0, -1.0, 0, 0, 0]) + + +def grasp_frame(): + """Hand points forward and slightly down, jaw closes sideways: pinches the bowl across its thickness.""" + s = SPOON_DIR + a = np.array([np.cos(0.35), 0, -np.sin(0.35)]) + a -= (a @ s) * s + a /= np.linalg.norm(a) + j = np.cross(s, a) + j /= np.linalg.norm(j) + R = np.stack([a, j, np.cross(a, j)], 1) + if R[2, 2] < 0: + j = -j + R = np.stack([a, j, np.cross(a, j)], 1) + return R + + +def align_down(Rh, s_h): + v = Rh @ s_h + tgt = np.array([0, 0, -1.0]) + ax = np.cross(v, tgt) + sn = np.linalg.norm(ax) + if sn < 1e-6: + return Rh + return axis_rot(ax / sn, np.arctan2(sn, v @ tgt)) @ Rh + + +# ----------------------------------------------------------------------------- policy + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.A = np.asarray(tools.hold_action(), dtype=np.float64) + self.hold_xy = None + self.hold_yaw = 0.0 + self.qcmd = {'L': None, 'R': None} + self.bias = {'L': np.zeros(7), 'R': np.zeros(7)} + self.gen = self.script() + self.log = [] + + def act(self, obs, tools): + self.obs = obs + try: + a = next(self.gen) + except StopIteration: + a = None + if a is None: + a = self.base_hold(self.A.copy()) + return np.asarray(a, dtype=np.float32) + + # ---- helpers + @property + def lo(self): + return self.obs['low_dim_obs'].astype(np.float64) + + def base_cmd(self, tx, ty, tyaw, kp=1.2, vmax=0.3, tol=0.015): + lo = self.lo + x, y, yaw = lo[21], lo[22], lo[24] + ex, ey = tx - x, ty - y + c, s = np.cos(yaw), np.sin(yaw) + v = np.array([c * ex + s * ey, -s * ex + c * ey]) * kp + if np.hypot(ex, ey) < tol: + v[:] = 0 + else: + n = np.linalg.norm(v) + if n > vmax: + v *= vmax / n + if np.linalg.norm(v) < 0.07: + v *= 0.07 / max(np.linalg.norm(v), 1e-6) + eyaw = (tyaw - yaw + np.pi) % (2 * np.pi) - np.pi + wz = 0.0 if abs(eyaw) < 0.02 else float(np.clip(1.5 * eyaw, -0.5, 0.5)) + return v[0], v[1], wz + + def base_hold(self, a): + if self.hold_xy is not None: + a[0], a[1], a[3] = self.base_cmd(self.hold_xy[0], self.hold_xy[1], self.hold_yaw, tol=0.02) + else: + a[0] = a[1] = a[3] = 0.0 + return a + + def wait(self, n): + for _ in range(n): + yield self.base_hold(self.A.copy()) + + def to_pel(self, P): + lo = self.lo + c, s = np.cos(lo[24]), np.sin(lo[24]) + r = np.asarray(P) - lo[21:24] + return np.array([c * r[0] + s * r[1], -s * r[0] + c * r[1], r[2]]) + + def to_pel_dir(self, d): + lo = self.lo + c, s = np.cos(lo[24]), np.sin(lo[24]) + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + def cur_pose(self, side, off=TOOL): + lo = self.lo + q = lo[3:10] if side == 'L' else lo[12:19] + M = world_T(lo) @ fk(q, side, lo[0:3]) + return M[:3, :3] @ off + M[:3, 3], M[:3, :3] + + def move(self, P, R, side='L', off=TOOL, speed=0.15, settle=15): + sl = slice(5, 12) if side == 'L' else slice(12, 19) + ol = slice(3, 10) if side == 'L' else slice(12, 19) + P0, R0 = self.cur_pose(side, off) + dist = np.linalg.norm(np.asarray(P) - P0) + ang = np.linalg.norm(Rot.from_matrix(R0.T @ R).as_rotvec()) + n = max(int(max(dist / speed, ang / 1.5) / 0.04) + 1, 1) + slerp = Slerp([0, 1], Rot.from_matrix([R0, R])) + q = self.qcmd[side] if self.qcmd[side] is not None else self.lo[ol].copy() + for i in range(1, n + 1): + t = i / n + t = 3 * t * t - 2 * t * t * t + Pi = P0 + t * (np.asarray(P) - P0) + Ri = slerp(t).as_matrix() + rel = self.to_pel(Pi - Ri @ off) + axes = [(np.array([1.0, 0, 0]), self.to_pel_dir(Ri[:, 0]), 1.0), + (np.array([0, 1.0, 0]), self.to_pel_dir(Ri[:, 1]), 1.0)] + q, _ = ik(rel, side, self.lo[0:3], axes, q0=q, multistart=False) + self.A[sl] = q + self.bias[side] + for _ in range(2): + yield self.base_hold(self.A.copy()) + for _ in range(2): + self.A[sl] = q + self.bias[side] + for _ in range(settle): + yield self.base_hold(self.A.copy()) + e = q - self.lo[ol] + self.bias[side] = np.clip(self.bias[side] + 0.7 * e, -0.15, 0.15) + self.A[sl] = q + self.bias[side] + self.qcmd[side] = q + + def walk_to(self, tx, ty, n=200): + for k in range(n): + vx, vy, wz = self.base_cmd(tx, ty, 0.0) + a = self.A.copy() + a[0], a[1], a[3] = vx, vy, wz + if vx == 0 and vy == 0 and wz == 0 and k > 20: + break + yield a + + def set_gripper(self, side, g, steps=25): + self.A[19 if side == 'L' else 20] = g + yield from self.wait(steps) + + # ---- the task + def script(self): + A = self.A + A[4] = -0.2 + A[5:12] = UP_L + A[12:19] = UP_R + A[19] = 0.0 + A[20] = 0.6 + yield from self.wait(40) + + # 1. mug from the head camera + ests = [] + for _ in range(3): + r = find_mug_head(self.tools.image('head')) + if r is not None: + o, d = head_ray(self.lo, r[0], r[1]) + P = plane_hit(o, d, Z_COUNTER) + dh = np.array([d[0], d[1], 0.0]) + dh /= np.linalg.norm(dh) + ests.append(P[:2] + MUG_R * dh[:2]) + yield from self.wait(3) + if not ests: + mug = np.array([0.72, 0.0]) + else: + mug = np.median(np.array(ests), axis=0) + self.log.append(('mug_head', mug.round(3))) + + # 2. walk to the stance + A[4] = 0.0 + base = mug + BASE_OFF + yield from self.walk_to(base[0], base[1], n=220) + self.hold_xy = (base[0], base[1]) + yield from self.wait(20) + self.log.append(('pelvis', self.lo[21:25].round(3), int(self.obs['t']))) + + # 3. refine with the left wrist camera from above + mugc = np.array([mug[0], mug[1], Z_RIM]) + for it in range(1): + cam = mugc + LOOK_CAM + lo = self.lo + look = mugc - cam + look /= np.linalg.norm(look) + q, pe = ik(self.to_pel(cam), 'L', lo[0:3], + [(T_WCAM_L[:3, 0], self.to_pel_dir(look), 2.0), + (T_WCAM_L[:3, 2], np.array([0, 0, 1.0]), 0.3)], tool=T_WCAM_L[:3, 3]) + Mh = world_T(lo) @ fk(q, 'L', lo[0:3]) + yield from self.move(Mh[:3, 3], Mh[:3, :3], 'L', off=np.zeros(3), speed=0.2, settle=10) + r = find_opening(self.tools.image('left_wrist')) + if r is None: + break + o, d = lwrist_ray(self.lo, r[0], r[1]) + P = plane_hit(o, d, Z_RIM) + if np.linalg.norm(P[:2] - mugc[:2]) > 0.08: + break + self.log.append(('wrist_raw', P[:2].round(3))) + hx, hy = mug[0] + 0.01, mug[1] + mugc = np.array([0.75 * hx + 0.25 * P[0], 0.75 * hy + 0.25 * P[1], Z_RIM]) + self.log.append(('mug_wrist', mugc.round(3))) + self.mugc = mugc + + # 4. grasp the bowl + R = grasp_frame() + a = R[:, 0] + tip = mugc + TIP_OFF + PG = tip - GRASP_BELOW * SPOON_DIR + A[5:12] = UP_L + self.qcmd['L'] = None + yield from self.wait(30) + got = False + for k, (dx, dy, dz) in enumerate(RETRIES): + P = PG + np.array([dx, dy, dz]) + if k == 0: + yield from self.move(P - 0.15 * a + np.array([0, 0, 0.04]), R, 'L') + else: + yield from self.move(P - 0.07 * a + np.array([0, 0, 0.03]), R, 'L', speed=0.1, settle=5) + yield from self.move(P - 0.05 * a, R, 'L', speed=0.08, settle=8) + yield from self.move(P, R, 'L', speed=0.04) + yield from self.set_gripper('L', 1.0, 25) + if self.lo[10] > -0.018: + got = True + # the spoon was where this attempt aimed: correct the mug estimate accordingly + mugc = mugc + np.array([dx, dy, 0.0]) + break + yield from self.set_gripper('L', 0.0, 12) + Pc, Rc = self.cur_pose('L') + yield from self.move(Pc - 0.06 * a + np.array([0, 0, 0.03]), R, 'L', speed=0.08, settle=5) + if self.obs['t'] > 1230: + break + self.log.append(('grasp', got, k, int(self.obs['t']))) + if not got: + A[5:12] = UP_L + yield from self.wait(10 ** 6) + + # 5. lift, flip, place + Pc, Rc = self.cur_pose('L') + s_h = Rc.T @ SPOON_DIR + yield from self.move(Pc + 0.15 * SPOON_DIR, Rc, 'L', speed=0.06) + Pb = Pc + 0.15 * SPOON_DIR + np.array([-0.06, 0, 0.02]) + yield from self.move(Pb, Rc, 'L', speed=0.08) + for ang in (60, 120, 180): + yield from self.move(Pb, Rc @ rot('x', np.radians(ang)), 'L', speed=0.08, settle=8) + RF = align_down(Rc @ rot('x', np.pi), s_h) + yield from self.move(Pb, RF, 'L', speed=0.08) + yield from self.move(mugc + np.array([0, 0, 0.10]), RF, 'L', speed=0.06) + yield from self.move(mugc + np.array([0, 0, REL_H]), RF, 'L', speed=0.03) + for g in np.linspace(1.0, G_OPEN, 6): + A[19] = g + yield from self.wait(4) + yield from self.wait(30) + for g in np.linspace(G_OPEN, 0.0, 5): + A[19] = g + yield from self.wait(4) + yield from self.wait(15) + Pc2, Rc2 = self.cur_pose('L') + yield from self.move(Pc2 + np.array([0, 0, 0.10]), Rc2, 'L', speed=0.04) + yield from self.wait(10 ** 6) + + +REL_H = 0.015 +G_OPEN = 0.45 diff --git a/policies/flip_cutlery/opus-s3/episodes.csv b/policies/flip_cutlery/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..02d52e024837286ee3a7bdc97ebc7fee14ec6aa5 --- /dev/null +++ b/policies/flip_cutlery/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1950,timeout,0 +620001,0,1950,timeout,0 +620002,0,1950,timeout,0 +620003,0,1950,timeout,0 +620004,0,1950,timeout,0 +620005,0,1950,timeout,0 +620006,1,1471,success,0 +620007,0,1950,timeout,0 +620008,0,1950,timeout,0 +620009,0,1950,timeout,0 +620010,0,1950,timeout,0 +620011,0,1950,timeout,0 +620012,0,1950,timeout,0 +620013,0,1950,timeout,0 +620014,0,1950,timeout,0 +620015,0,1950,timeout,0 +620016,0,1950,timeout,0 +620017,0,1950,timeout,0 +620018,0,1950,timeout,0 +620019,0,1950,timeout,0 +620020,0,1950,timeout,0 +620021,0,1950,timeout,0 +620022,0,1950,timeout,0 +620023,0,1950,timeout,0 +620024,1,1450,success,0 +620025,0,1950,timeout,0 +620026,1,1476,success,0 +620027,0,1950,timeout,0 +620028,1,1489,success,0 +620029,0,1950,timeout,0 +620030,0,1950,timeout,0 +620031,1,1467,success,0 +620032,0,1950,timeout,0 +620033,0,1950,timeout,0 +620034,0,1950,timeout,0 +620035,0,1950,timeout,0 +620036,1,1492,success,0 +620037,0,1950,timeout,0 +620038,0,1950,timeout,0 +620039,0,1950,timeout,0 +620040,0,1950,timeout,0 +620041,0,1950,timeout,0 +620042,0,1950,timeout,0 +620043,1,1501,success,0 +620044,0,1950,timeout,0 +620045,0,1950,timeout,0 +620046,1,1504,success,0 +620047,1,1464,success,0 +620048,0,1950,timeout,0 +620049,0,1950,timeout,0 +620050,0,1950,timeout,0 +620051,0,1950,timeout,0 +620052,0,1950,timeout,0 +620053,1,1507,success,0 +620054,0,1950,timeout,0 +620055,1,1450,success,0 +620056,0,1950,timeout,0 +620057,0,1950,timeout,0 +620058,0,1950,timeout,0 +620059,0,1950,timeout,0 +620060,1,1468,success,0 +620061,0,1950,timeout,0 +620062,0,1950,timeout,0 +620063,0,1950,timeout,0 +620064,0,1950,timeout,0 +620065,0,1950,timeout,0 +620066,0,1950,timeout,0 +620067,0,1950,timeout,0 +620068,0,1950,timeout,0 +620069,0,1950,timeout,0 +620070,1,1467,success,0 +620071,0,1950,timeout,0 +620072,0,1950,timeout,0 +620073,1,1471,success,0 +620074,0,1950,timeout,0 +620075,0,1950,timeout,0 +620076,0,1950,timeout,0 +620077,0,1950,timeout,0 +620078,1,1489,success,0 +620079,0,1950,timeout,0 +620080,0,1950,timeout,0 +620081,0,1950,timeout,0 +620082,1,1450,success,0 +620083,1,1513,success,0 +620084,1,1473,success,0 +620085,0,1950,timeout,0 +620086,0,1950,timeout,0 +620087,0,1950,timeout,0 +620088,0,1950,timeout,0 +620089,0,1950,timeout,0 +620090,0,1950,timeout,0 +620091,0,1950,timeout,0 +620092,0,1950,timeout,0 +620093,0,1950,timeout,0 +620094,0,1950,timeout,0 +620095,0,1950,timeout,0 +620096,0,1950,timeout,0 +620097,0,1950,timeout,0 +620098,0,1950,timeout,0 +620099,1,1470,success,0 diff --git a/policies/flip_cutlery/opus-s3/g1kin.py b/policies/flip_cutlery/opus-s3/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..49a465dda53f7fc075b5e73609fbbb663daaca36 --- /dev/null +++ b/policies/flip_cutlery/opus-s3/g1kin.py @@ -0,0 +1,213 @@ +"""Approximate G1 kinematics (pelvis frame) for the arms and the head camera.""" +import numpy as np + + +def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def rpy(r, p, y): + return rz(y) @ ry(p) @ rx(r) + + +def T(R=None, p=None): + M = np.eye(4) + if R is not None: + M[:3, :3] = R + if p is not None: + M[:3, 3] = p + return M + + +AX = {"x": rx, "y": ry, "z": rz} + +# (origin xyz, origin rpy, axis) per joint, from the G1 29-dof description +ARM = { + "left": [ + ((0.0039563, 0.10022, 0.24778), (0.27931, 5.4949e-05, -0.00019159), "y"), + ((0, 0.038, -0.013831), (-0.27925, 0, 0), "x"), + ((0, 0.00624, -0.1032), (0, 0, 0), "z"), + ((0.015783, 0, -0.080518), (0, 0, 0), "y"), + ((0.100, 0.00188791, -0.010), (0, 0, 0), "x"), + ((0.038, 0, 0), (0, 0, 0), "y"), + ((0.046, 0, 0), (0, 0, 0), "z"), + ], + "right": [ + ((0.0039563, -0.10021, 0.24778), (-0.27931, 5.4949e-05, 0.00019159), "y"), + ((0, -0.038, -0.013831), (0.27925, 0, 0), "x"), + ((0, -0.00624, -0.1032), (0, 0, 0), "z"), + ((0.015783, 0, -0.080518), (0, 0, 0), "y"), + ((0.100, -0.00188791, -0.010), (0, 0, 0), "x"), + ((0.038, 0, 0), (0, 0, 0), "y"), + ((0.046, 0, 0), (0, 0, 0), "z"), + ], +} + +HEAD_CAM = ((0.0576235, 0.01753, 0.42987), (0, 0.8307767, 0)) +# calibrated against the grippers seen by the head camera +HEAD_CAL = ((0.0576235 + 0.0608, 0.01753 - 0.0443, 0.42987 + 0.0355), + (0.0762, 0.8307767 + 0.2971, 0.0921)) +HEAD_F = 87.56 +# wrist camera mount in the wrist_yaw frame (left; right is mirrored) +WRIST_CAL = ((0.1398, -0.0003, 0.03), (0.0501, 0.6938, -0.0545)) +WRIST_F = 56.69 + + +def wrist_cam_offset(side): + sg = 1 if side == "left" else -1 + xyz, r = WRIST_CAL + return T(rpy(sg * r[0], r[1], sg * r[2]), (xyz[0], sg * xyz[1], xyz[2])) + + +def wrist_T(side, q, waist): + return arm_T(side, q, waist) @ wrist_cam_offset(side) + + +def torso_T(waist): + """Pelvis -> torso_link transform for waist (yaw, roll, pitch).""" + M = T(rz(waist[0])) + M = M @ T(None, (-0.0039635, 0, 0.044)) @ T(rx(waist[1])) + M = M @ T(ry(waist[2])) + return M + + +def arm_T(side, q, waist=(0, 0, 0), tool=(0.0, 0, 0)): + """Pelvis-frame transform of the wrist_yaw link (plus a tool offset).""" + M = torso_T(waist) + for (xyz, r, ax), qi in zip(ARM[side], q): + M = M @ T(rpy(*r), xyz) @ T(AX[ax](qi)) + return M @ T(None, tool) + + +def head_T(waist): + xyz, r = HEAD_CAL + return torso_T(waist) @ T(rpy(*r), xyz) + + +def pelvis_world(o): + """4x4 world transform of the pelvis from low_dim_obs (x, y, z, yaw).""" + return T(rz(o[24]), (o[21], o[22], o[23])) + + +def pixel_ray(Tcam, u, v, f, cx=41.5, cy=41.5): + """Origin and unit direction (frame of Tcam's parent) of the ray through pixel (u, v).""" + d = np.array([1.0, (cx - u) / f, (cy - v) / f]) + d = Tcam[:3, :3] @ d + return Tcam[:3, 3].copy(), d / np.linalg.norm(d) + + +def project(Tcam, P, f, cx=41.5, cy=41.5): + """Project pelvis-frame points with a camera whose link frame is x fwd, y left, z up.""" + P = np.atleast_2d(P) + inv = np.linalg.inv(Tcam) + Pc = (inv[:3, :3] @ P.T).T + inv[:3, 3] + u = cx - f * Pc[:, 1] / Pc[:, 0] + v = cy - f * Pc[:, 2] / Pc[:, 0] + return np.stack([u, v], 1), Pc[:, 0] + + +LIMITS = { + "lo": np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]), + "hi": np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]), +} + + +def side_limits(side): + lo, hi = LIMITS["lo"].copy(), LIMITS["hi"].copy() + if side == "right": # roll and yaw limits mirror + lo[1], hi[1] = -LIMITS["hi"][1], -LIMITS["lo"][1] + return lo, hi + + +def ik(side, pos, q0, waist=(0, 0, 0), tool=(0.1, 0, 0), xdir=None, zdir=None, + wdir=0.3, wreg=0.02, qref=None): + """Least-squares IK: tool point to pos, optional tool x / z axis directions.""" + from scipy.optimize import least_squares + lo, hi = side_limits(side) + lo = lo + 0.05 + hi = hi - 0.05 + qref = np.asarray(q0 if qref is None else qref, float) + + def res(q): + M = arm_T(side, q, waist, tool) + r = [M[:3, 3] - pos] + if xdir is not None: + r.append(wdir * (M[:3, 0] - xdir)) + if zdir is not None: + r.append(wdir * (M[:3, 2] - zdir)) + r.append(wreg * (q - qref)) + return np.concatenate(r) + + x0 = np.clip(np.asarray(q0, float), lo, hi) + sol = least_squares(res, x0, bounds=(lo, hi), xtol=1e-8, ftol=1e-10) + M = arm_T(side, sol.x, waist, tool) + return sol.x, np.linalg.norm(M[:3, 3] - pos) + + +def ik_multi(side, Tt, q0, waist=(0, 0, 0), tool=(0.1, 0, 0), n=20, bounds=None, seed=0, + wpref=0.02): + """Local IK from q0, then random restarts; returns (q, pos err, rot err).""" + rng = np.random.default_rng(seed) + lo, hi = side_limits(side) + if bounds is not None: + lo = np.maximum(lo, bounds[0]) + hi = np.minimum(hi, bounds[1]) + q0 = np.clip(np.asarray(q0, float), lo + 0.031, hi - 0.031) + best = None + starts = [q0] + [lo + (hi - lo) * rng.random(7) for _ in range(n)] + for k, qs in enumerate(starts): + q, e1, e2 = ik_pose(side, Tt, qs, waist, tool, qref=qs, wreg=0.0, bounds=bounds) + c = e1 + 0.1 * e2 + wpref * np.linalg.norm(q - q0) * 0.1 + if best is None or c < best[0]: + best = (c, q, e1, e2) + if k == 0 and e1 < 0.003 and e2 < 0.03: + break + return best[1], best[2], best[3] + + +def ik_pose(side, Tt, q0, waist=(0, 0, 0), tool=(0.1, 0, 0), wrot=0.15, wreg=0.003, + qref=None, bounds=None): + """IK for a full target pose (4x4, pelvis frame) of the tool frame.""" + from scipy.optimize import least_squares + lo, hi = side_limits(side) + lo = lo + 0.03 + hi = hi - 0.03 + if bounds is not None: + lo = np.maximum(lo, bounds[0]) + hi = np.minimum(hi, bounds[1]) + qref = np.asarray(q0 if qref is None else qref, float) + + def res(q): + M = arm_T(side, q, waist, tool) + r = [M[:3, 3] - Tt[:3, 3], wrot * (M[:3, :3] - Tt[:3, :3]).ravel(), + wreg * (q - qref)] + if ELBOW_MIN_Z is not None: + ez = elbow_pos(side, q, waist)[2] + r.append([3.0 * max(0.0, ELBOW_MIN_Z - ez)]) + return np.concatenate(r) + + x0 = np.clip(np.asarray(q0, float), lo, hi) + sol = least_squares(res, x0, bounds=(lo, hi), xtol=1e-8, ftol=1e-10) + M = arm_T(side, sol.x, waist, tool) + return sol.x, np.linalg.norm(M[:3, 3] - Tt[:3, 3]), np.linalg.norm(M[:3, :3] - Tt[:3, :3]) + + +ELBOW_MIN_Z = None # optional lower bound (pelvis frame) on the elbow height used by ik_pose + + +def elbow_pos(side, q, waist=(0, 0, 0)): + M = torso_T(waist) + for (xyz, r, ax), qi in zip(ARM[side][:4], q[:4]): + M = M @ T(rpy(*r), xyz) @ T(AX[ax](qi)) + return M[:3, 3] diff --git a/policies/flip_cutlery/opus-s3/policy.py b/policies/flip_cutlery/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..68b030c1c93a9f939c3f04f78de1ea589a661881 --- /dev/null +++ b/policies/flip_cutlery/opus-s3/policy.py @@ -0,0 +1,570 @@ +"""Flip-the-spoon policy for the G1: scripted phases with head-camera localisation. + +Phases: look at the counter, walk next to the mug, re-localise mug and spoon, +grasp the protruding end of the spoon with the left hand, pull it out, turn it +upside down, hand it to the right hand and lower the grasped end into the mug. +""" + +import os +import sys + +import numpy as np + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +import g1kin as K # noqa: E402 +import vision as V # noqa: E402 + +TOOL = (0.15, 0.0, 0.0) # pinch point of the gripper in the wrist_yaw frame +STAND_X = 0.35 # pelvis x (world) to stand at +TUCK = np.array([0.0, 0.3, 0.0, -0.9, 0.0, 0.0, 0.0]) # hands up in front of the chest +H_STAND = 0.74 +LOOK_ARM = np.array([0.5, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0]) # arms back, out of the head view +H_WORK = 0.9 # knees locked: pelvis ~3 cm higher while manipulating +ELBOW_MIN_Z = 0.17 # keep elbows above the counter (pelvis frame) +BIAS_MAX = 0.2 # max sag compensation per joint (rad) +GRASP_DY = 0.17 # stand this far right of the mug for the left-hand grasp +INSERT_DY = 0.12 # and this far left of it for the right-hand insertion +STATION_Y = 0.0 # handover point (pelvis frame y) +DROP_Z = 0.035 # grasp point height above the rim when releasing +BETA = 10.0 # downward tilt of the grasp approach (deg) +HANDOVER_DZ = 0.09 # right grasp this far above the left grasp +GRASP_S = 0.055 # grasp this far along the spoon from the rim + + +def mirror(q): + q = np.asarray(q, float) + return np.array([q[0], -q[1], -q[2], q[3], -q[4], q[5], -q[6]]) + + +def unit(v): + v = np.asarray(v, float) + return v / np.linalg.norm(v) + + +def rot_axis(axis, ang): + axis = unit(axis) + k = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]]) + return np.eye(3) + np.sin(ang) * k + (1 - np.cos(ang)) * k @ k + + +class Policy: + def reset(self, obs, tools): + self.obs = obs + self.tools = tools + self.a = np.asarray(tools.hold_action(), dtype=float) + o = obs["low_dim_obs"] + self.a[5:12] = o[3:10] + self.a[12:19] = o[12:19] + self.log = [] + self.debug = {} + self.snaps = [] + self.bias = {"left": np.zeros(7), "right": np.zeros(7)} + self.gen = self.main() + + def act(self, obs, tools): + self.obs = obs + try: + a = next(self.gen) + except StopIteration: + a = self.a + except Exception as exc: # never crash: freeze in place + self.note("error", repr(exc)) + if os.environ.get("POLICY_DEBUG"): + raise + self.gen = iter(()) + a = self.a.copy() + a[[0, 1, 3]] = 0 + self.a = np.asarray(a, dtype=float) + out = self.a.copy() + if np.linalg.norm(out[[0, 1]]) < 0.055: + out[[0, 1]] = 0.0 + return out + + # ------------------------------------------------------------------ utils + @property + def o(self): + return self.obs["low_dim_obs"] + + def note(self, *args): + self.log.append(" ".join(str(x) for x in args)) + + def snap(self, tag): + if os.environ.get("POLICY_DEBUG"): + self.snaps.append(dict(tag=tag, obs=self.o.copy(), t=self.obs["t"], + **{c: self.tools.image(c) for c in ("head", "left_wrist", "right_wrist")})) + + def go(self, n, qL=None, qR=None, gL=None, gR=None, height=None, pitch=None): + a0 = self.a.copy() + a1 = a0.copy() + if qL is not None: + a1[5:12] = np.asarray(qL) + self.bias["left"] + if qR is not None: + a1[12:19] = np.asarray(qR) + self.bias["right"] + if gL is not None: + a1[19] = gL + if gR is not None: + a1[20] = gR + if height is not None: + a1[2] = height + if pitch is not None: + a1[4] = pitch + a0[[0, 1, 3]] = 0 + a1[[0, 1, 3]] = 0 + for t in range(n): + s = (t + 1) / n + s = 0.5 - 0.5 * np.cos(np.pi * s) + yield a0 + (a1 - a0) * s + + def settle(self, side, n=12, iters=2): + """Cancel the steady-state tracking error (gravity sag) of one arm.""" + idx = slice(5, 12) if side == "left" else slice(12, 19) + midx = slice(3, 10) if side == "left" else slice(12, 19) + for _ in range(iters): + q_des = self.a[idx] - self.bias[side] + err = q_des - self.o[midx] + err = np.where(np.abs(err) > 0.25, 0.0, err) # blocked joint: do not push + self.bias[side] = np.clip(self.bias[side] + err, -BIAS_MAX, BIAS_MAX) + kw = {"qL": q_des} if side == "left" else {"qR": q_des} + yield from self.go(n, **kw) + yield from self.hold(6) + self.note("bias", side, np.round(self.bias[side], 3)) + + def hold(self, n): + a = self.a.copy() + a[[0, 1, 3]] = 0 + for _ in range(n): + yield a + + def pelvis(self): + return K.pelvis_world(self.o) + + def head_cam_world(self): + return self.pelvis() @ K.head_T(self.o[0:3]) + + def walk_to(self, goal, yaw_goal=0.0, maxn=500, tol=0.015): + yield from self.go(15, height=H_STAND, pitch=0.0) + for t in range(maxn): + o = self.o + e = goal - o[21:23] + yaw = o[24] + c, s = np.cos(yaw), np.sin(yaw) + eb = np.array([c * e[0] + s * e[1], -s * e[0] + c * e[1]]) + ey = (yaw_goal - yaw + np.pi) % (2 * np.pi) - np.pi + if np.linalg.norm(eb) < tol and abs(ey) < 0.03: + break + v = np.clip(1.5 * eb, -0.25, 0.25) + sp = np.linalg.norm(v) + if np.linalg.norm(eb) >= tol and sp < 0.07: + v = v / max(sp, 1e-6) * 0.07 + wz = np.clip(2.0 * ey, -0.4, 0.4) + a = self.a.copy() + a[0], a[1], a[3] = v[0], v[1], wz + yield a + a = self.a.copy() + a[[0, 1, 3]] = 0 + self.a = a + yield from self.hold(40) + self.note("walk", t, np.round(self.o[21:25], 3)) + + def ik_world(self, side, Tw, q0, tool=TOOL, qref=None): + Tp = np.linalg.inv(self.pelvis()) @ Tw + q, e1, e2 = K.ik_pose(side, Tp, q0, self.o[0:3], tool, qref=qref) + return q, e1, e2 + + def reach(self, side, poses, steps, tool=TOOL, grip=None): + """Cartesian moves through world-frame tool poses (IK seeded along the way).""" + idx = slice(5, 12) if side == "left" else slice(12, 19) + bias = self.bias[side] + q = self.a[idx].copy() - bias + Tp_inv = np.linalg.inv(self.pelvis()) + w = self.o[0:3] + Tcur = K.arm_T(side, q, w, tool) + Tcur = self.pelvis() @ Tcur + for Tgoal, n in zip(poses, steps): + # interpolate position linearly and orientation by axis-angle + R0, R1 = Tcur[:3, :3], Tgoal[:3, :3] + dR = R1 @ R0.T + ang = np.arccos(np.clip((np.trace(dR) - 1) / 2, -1, 1)) + ax = np.array([dR[2, 1] - dR[1, 2], dR[0, 2] - dR[2, 0], dR[1, 0] - dR[0, 1]]) + if ang < 1e-4 or np.linalg.norm(ax) < 1e-8: + ax = np.array([1.0, 0, 0]) + ang = 0.0 + elif ang > np.pi - 1e-3: + # 180 degrees: axis from the symmetric part + w_, v_ = np.linalg.eigh((dR + dR.T) / 2) + ax = v_[:, np.argmax(w_)] + else: + ax = ax / np.linalg.norm(ax) + qs = [] + k = max(1, n // 8) + for j in range(1, k + 1): + s = j / k + Ti = np.eye(4) + Ti[:3, :3] = rot_axis(ax, ang * s) @ R0 + Ti[:3, 3] = Tcur[:3, 3] + (Tgoal[:3, 3] - Tcur[:3, 3]) * s + q, e1, e2 = K.ik_pose(side, Tp_inv @ Ti, q, w, tool, qref=q) + qs.append(q.copy()) + self.note("reach err", side, round(e1, 4), round(e2, 4)) + # play the joint path + a0 = self.a.copy() + prev = a0[idx].copy() - bias + per = n / k + for j, qj in enumerate(qs): + m = int(round(per * (j + 1))) - int(round(per * j)) + for t in range(m): + s = (t + 1) / m + a = self.a.copy() + a[[0, 1, 3]] = 0 + a[idx] = prev + (qj - prev) * s + bias + if grip is not None: + a[19 if side == "left" else 20] = grip + yield a + prev = qj + Tcur = Tgoal + + # ------------------------------------------------------------- perception + def look(self, tag): + im = self.tools.image("head") + Tw = self.head_cam_world() + self.snap(tag) + return im, Tw + + def localize(self, views): + xs = [] + good = [] + for im, Tw in views: + xy, ft = V.locate_mug(im, Tw, K.HEAD_F) + if xy is None: + continue + m = V.mug_mask_head(im) + ys, xs_ = np.nonzero(m) + inside = xs_.min() > 1 and xs_.max() < 82 and ys.max() < 82 + self.note("view", np.round(xy, 3), "inside", inside) + if inside: + xs.append(xy) + good.append((im, Tw)) + if not xs: + for im, Tw in views: + xy, ft = V.locate_mug(im, Tw, K.HEAD_F) + if xy is not None: + xs.append(xy) + good.append((im, Tw)) + if not xs: + return None, None + mug = np.median(np.array(xs), axis=0) + phi, sc, _ = V.fit_spoon(good, mug, K.HEAD_F) + return mug, phi + + # ------------------------------------------------------------------ main + def main(self): + # 1. look at the counter + yield from self.go(40, height=0.9, pitch=-0.2) + yield from self.hold(20) + v0 = self.look("up0") + mug, phi = self.localize([v0]) + self.note("mug0", mug, phi) + if mug is None: + yield from self.hold(2000) + return + # 2. walk next to it with tucked arms + yield from self.go(40, height=H_STAND, pitch=0.0, qL=TUCK, qR=mirror(TUCK), gL=0.0, gR=0.0) + goal = np.array([STAND_X, mug[1] - GRASP_DY]) + yield from self.walk_to(goal) + # 3. re-localise from close (arms down, out of the head camera view) + yield from self.go(40, height=0.9, pitch=-0.2, qL=LOOK_ARM, qR=mirror(LOOK_ARM)) + yield from self.hold(20) + v1 = self.look("up1") + yield from self.go(40, height=H_WORK, pitch=0.0) + yield from self.hold(20) + v2 = self.look("stand") + mug, phi = self.localize([v0, v1, v2]) + K.ELBOW_MIN_Z = ELBOW_MIN_Z + self.debug["mug"] = mug + self.debug["phi"] = phi + self.note("mug1", mug, np.rad2deg(phi)) + yield from self.grasp(mug, phi) + yield from self.flip_drop(mug) + self.finished = True + yield from self.hold(3000) + + def pframe(self, x, z, p_pelvis): + """World pose with tool axes x, z (world directions) at a pelvis-frame point.""" + x = unit(x) + z = unit(np.asarray(z, float) - np.dot(z, x) * x) + T = np.eye(4) + T[:3, :3] = np.stack([x, np.cross(z, x), z], 1) + T[:3, 3] = (self.pelvis() @ np.r_[p_pelvis, 1.0])[:3] + return T + + def move_pose(self, side, Tw, n, grip=None, tool=TOOL, bounds="sp"): + """Joint-space move to a multi-start IK solution of a world tool pose.""" + idx = slice(5, 12) if side == "left" else slice(12, 19) + if bounds == "sp": + bounds = (np.array([-2.6, -9, -9, -9, -9, -9, -9]), np.array([0.3, 9, 9, 9, 9, 9, 9])) + Tp = np.linalg.inv(self.pelvis()) @ Tw + q, e1, e2 = K.ik_multi(side, Tp, self.a[idx] - self.bias[side], self.o[0:3], tool, + bounds=bounds) + self.note("move_pose", side, round(e1, 4), round(e2, 4), np.round(q, 2)) + kw = {"qL": q} if side == "left" else {"qR": q} + if grip is not None: + kw["gL" if side == "left" else "gR"] = grip + yield from self.go(n, **kw) + return q + + def tool_world(self, side, measured=True): + q = (self.o[3:10] if side == "left" else self.o[12:19]) if measured else \ + ((self.a[5:12] if side == "left" else self.a[12:19]) - self.bias[side]) + return self.pelvis() @ K.arm_T(side, q, self.o[0:3], TOOL) + + def flip_drop(self, mug): + """Turn the held end down, hold it over the mug and let the spoon drop in.""" + P = self.pelvis() + fwd = P[:3, 0] + up = np.array([0, 0, 1.0]) + rim = V.H_COUNTER + V.MUG_H + T1 = self.tool_world("left", measured=False) + T1[:3, 3] = (P @ np.array([0.25, 0.14, 0.32, 1.0]))[:3] + yield from self.reach("left", [T1], [50], grip=1.0) + T2 = self.pframe(fwd, -self.debug.get("zs", 1) * up, (0.25, 0.14, 0.32)) + yield from self.move_pose("left", T2, 90, grip=1.0) + yield from self.settle("left") + self.snap("flipped") + Ta = T2.copy() + Ta[:3, 3] = np.r_[mug, rim + DROP_Z + 0.06] + yield from self.reach("left", [Ta], [60], grip=1.0) + yield from self.servo("left", Ta) + yield from self.settle("left") + self.snap("above") + Tb = Ta.copy() + Tb[2, 3] = rim + DROP_Z + yield from self.reach("left", [Tb], [40], grip=1.0) + yield from self.servo("left", Tb, iters=1) + yield from self.settle("left", iters=1) + self.snap("lowered") + yield from self.go(15, gL=0.0) + yield from self.hold(20) + self.snap("released") + Tc = self.tool_world("left", measured=False) + Tc[:3, 3] += 0.08 * up - 0.06 * fwd + yield from self.reach("left", [Tc], [40], grip=0.0) + yield from self.go(40, height=0.9, pitch=-0.2) + yield from self.hold(30) + self.snap("final") + + def flip_handover(self): + P = self.pelvis() + fwd = P[:3, 0] + left = P[:3, 1] + up = np.array([0, 0, 1.0]) + # carry the spoon back towards the body, still hanging + T1 = self.tool_world("left", measured=False) + T1[:3, 3] = (P @ np.array([0.25, 0.12, 0.32, 1.0]))[:3] + yield from self.reach("left", [T1], [50], grip=1.0) + # turn it upside down: tool x to the right, tool z down + T2 = self.pframe(-left, -up, (0.25, STATION_Y, 0.30)) + yield from self.move_pose("left", T2, 90, grip=1.0) + T3 = self.pframe(-left, -up, (0.25, STATION_Y, 0.18)) + yield from self.reach("left", [T3], [40], grip=1.0) + yield from self.hold(25) + self.snap("flipped") + yield from self.settle("left") + # right hand takes the upper end + xr = unit(0.707 * fwd + 0.707 * left) + S = self.tool_world("left")[:3, 3] + Gr = S + HANDOVER_DZ * up + Tr = self.pframe(xr, up, (0, 0, 0)) + Tr_pre = Tr.copy() + Tr_pre[:3, 3] = Gr - 0.09 * xr + 0.02 * up + Tr_in = Tr.copy() + Tr_in[:3, 3] = Gr + 0.005 * xr + Tp = np.linalg.inv(self.pelvis()) @ Tr_in + bounds = (np.array([-2.6, -9, -9, -9, -9, -9, -9]), np.array([0.3, 9, 9, 9, 9, 9, 9])) + q_in, e1, e2 = K.ik_multi("right", Tp, np.array([-0.62, 0.28, 0.5, -0.84, 0.5, 1.4, -0.5]), + self.o[0:3], TOOL, bounds=bounds, n=30) + q_pre, f1, f2 = self.solve("right", Tr_pre, q_in, multi=False) + self.note("right station", round(e1, 4), round(f1, 4), np.round(q_in, 2)) + yield from self.go(80, qR=q_pre, gR=0.0) + yield from self.settle("right") + self.snap("r_pre") + yield from self.reach("right", [Tr_in], [40], grip=0.0) + yield from self.settle("right", iters=1) + yield from self.go(25, gR=1.0) + yield from self.hold(10) + self.note("rgrip", np.round(self.o[50:52], 3)) + yield from self.go(20, gL=0.0) + T4 = self.tool_world("left", measured=False) + T4[:3, 3] = T4[:3, 3] - 0.08 * T4[:3, 0] - 0.03 * up + yield from self.reach("left", [T4], [40], grip=0.0) + yield from self.go(50, qL=TUCK) + yield from self.hold(10) + self.snap("handed") + self.debug["S"] = S + self.debug["Gr"] = Gr + + def insert(self, mug): + up = np.array([0, 0, 1.0]) + # side-step so that the mug is in front of the right arm + K.ELBOW_MIN_Z = None + yield from self.walk_to(np.array([STAND_X, mug[1] + INSERT_DY])) + yield from self.go(40, height=H_WORK, pitch=-0.2) + yield from self.hold(20) + v = self.look("insert_view") + m2, _ = V.locate_mug(v[0], v[1], K.HEAD_F) + self.note("mug insert view", m2) + if m2 is not None and np.linalg.norm(m2 - mug) < 0.05: + mug = 0.5 * (mug + m2) + K.ELBOW_MIN_Z = ELBOW_MIN_Z + P = self.pelvis() + xr = np.r_[unit(mug - P[:2, 3]), 0.0] + rim = V.H_COUNTER + V.MUG_H + drop = HANDOVER_DZ + 0.025 # right grasp point to the lower tip of the spoon + T0 = self.tool_world("right", measured=False) + T0[:3, 3] += 0.08 * up + T1 = T0.copy() + T1[:3, 3] = np.r_[mug, rim + drop + 0.04] + Tmid = T0.copy() + Tmid[:3, 3] = 0.5 * (T0[:3, 3] + T1[:3, 3]) + Tmid[2, 3] = max(T0[2, 3], T1[2, 3]) + 0.02 + yield from self.reach("right", [T0, Tmid, T1], [30, 50, 50], grip=1.0) + yield from self.settle("right") + self.snap("above") + # visual correction: where does the lower end of the spoon hang? + for it in range(2): + im, Tw = self.look(f"tipview{it}") + Th = self.tool_world("right") + exp_tip = Th[:3, 3] - drop * up + tip = V.find_tip(im, Tw, K.HEAD_F, mug, exp_tip) + self.note("tip", it, None if tip is None else np.round(tip, 3), np.round(exp_tip, 3)) + if tip is None: + break + corr = mug - tip[:2] + if np.linalg.norm(corr) > 0.06: + break + T1 = self.tool_world("right", measured=False) + T1[:2, 3] += corr + yield from self.reach("right", [T1], [30], grip=1.0) + yield from self.settle("right", iters=1) + if np.linalg.norm(corr) < 0.008: + break + T2 = T1.copy() + T2[2, 3] = rim + drop - 0.05 + yield from self.reach("right", [T2], [50], grip=1.0) + yield from self.hold(10) + self.snap("lowered") + yield from self.go(20, gR=0.0) + yield from self.hold(10) + self.snap("released") + T3 = self.tool_world("right", measured=False) + T3[:3, 3] += 0.10 * up + yield from self.reach("right", [T3], [40], grip=0.0) + yield from self.hold(30) + self.snap("done") + yield from self.go(40, height=0.9, pitch=-0.2) + yield from self.hold(30) + self.snap("final") + + def grasp_frame(self, mug, phi, s=None, beta=BETA): + s = GRASP_S if s is None else s + a = V.spoon_axis(phi) + E = V.rim_exit(mug, phi) + G = E + s * a + d = unit(np.array([np.sin(phi), -np.cos(phi), 0.0])) + if d[0] < 0: + d = -d + b = np.deg2rad(beta) + x = np.cos(b) * d - np.sin(b) * a # approach, tilted down by BETA + z = unit(a - np.dot(a, x) * x) + y = np.cross(z, x) + Tg = np.eye(4) + Tg[:3, :3] = np.stack([x, y, z], 1) + Tg[:3, 3] = G + return Tg + + def solve(self, side, Tw, q0, multi=True): + Tp = np.linalg.inv(self.pelvis()) @ Tw + w = self.o[0:3] + q, e1, e2 = K.ik_pose(side, Tp, q0, w, TOOL, qref=q0, wreg=0.01) + if multi and (e1 > 0.006 or e2 > 0.05): + bounds = (np.array([-2.6, -9, -9, -9, -9, -9, -9]), np.array([0.3, 9, 9, 9, 9, 9, 9])) + q, e1, e2 = K.ik_multi(side, Tp, q0, w, TOOL, bounds=bounds, n=30) + return q, e1, e2 + + def plan_grasp(self, mug, phi): + P = self.pelvis() + Pi = np.linalg.inv(P) + w = self.o[0:3] + a = V.spoon_axis(phi) + G = V.rim_exit(mug, phi) + GRASP_S * a + d = unit(np.cross([0, 0, 1.0], a)) + e = np.cross(a, d) + out = np.array([np.cos(phi), np.sin(phi), 0.0]) + q0 = np.array([-0.7, -0.3, 0.1, -0.3, -0.3, 0.5, 0.5]) + cands = [] + for zs in (1, -1): + for psi in np.deg2rad(np.arange(0, 360, 20)): + x = np.cos(psi) * d + np.sin(psi) * e + if x[2] > 0.35 or abs(np.dot(x, out)) > 0.45: + continue + z = zs * a + Tg = np.eye(4) + Tg[:3, :3] = np.stack([x, np.cross(z, x), z], 1) + Tg[:3, 3] = G + q_g, e1, e2 = K.ik_pose("left", Pi @ Tg, q0, w, TOOL, wreg=0.0) + pen = 0.002 * max(0.0, x[2] + 0.2) + 0.006 * abs(np.dot(x, out)) + pen += 0.004 * np.linalg.norm(q_g - q0) + cands.append((e1 + 0.1 * e2 + pen, zs, psi, Tg, q_g)) + cands.sort(key=lambda c: c[0]) + best = None + for c0, zs, psi, Tg, q_g in cands[:6]: + x = Tg[:3, 0] + Tpre = Tg.copy() + Tpre[:3, 3] = Tg[:3, 3] - 0.10 * x + np.array([0, 0, 0.02]) + Traise = Tpre.copy() + Traise[:3, 3] = Tpre[:3, 3] - 0.08 * P[:3, 0] + np.array([0, 0, 0.06]) + q_pre, f1, f2 = self.solve("left", Tpre, q_g, multi=False) + q_raise, h1, h2 = self.solve("left", Traise, q_pre, multi=False) + cost = c0 + f1 + 0.3 * h1 + 0.1 * (f2 + 0.3 * h2) + self.note("plan", zs, round(np.rad2deg(psi)), round(cost, 4), round(f1, 4), round(h1, 4)) + if best is None or cost < best[0]: + best = (cost, Tg, Tpre, q_g, q_pre, q_raise, zs) + self.debug["zs"] = best[6] + return best[1:6] + + def servo(self, side, Tw, n=30, iters=2): + """Re-solve IK with the current waist and move; repeat (the torso reacts to the arm).""" + idx = slice(5, 12) if side == "left" else slice(12, 19) + for _ in range(iters): + q, e1, e2 = self.solve(side, Tw, self.a[idx] - self.bias[side], multi=False) + kw = {"qL": q} if side == "left" else {"qR": q} + yield from self.go(n, **kw) + yield from self.hold(15) + self.note("servo", side, round(e1, 4), np.round(self.o[0:3], 3)) + + def grasp(self, mug, phi): + yield from self.go(40, qL=TUCK, gL=0.0) + yield from self.hold(30) + Tg, Tpre, q_g, q_pre, q_raise = self.plan_grasp(mug, phi) + Tin = Tg.copy() + self.debug["Tg"] = Tg + yield from self.go(60, qL=q_raise, gL=0.0) + yield from self.hold(15) + q_pre, _, _ = self.solve("left", Tpre, q_pre, multi=False) + yield from self.go(50, qL=q_pre, gL=0.0) + yield from self.hold(15) + yield from self.servo("left", Tpre) + yield from self.settle("left") + self.snap("pre") + yield from self.reach("left", [Tin], [50], grip=0.0) + yield from self.settle("left", iters=1) + self.snap("in") + yield from self.go(25, gL=1.0) + yield from self.hold(15) + self.snap("closed") + self.note("grip", np.round(self.o[50:52], 3), np.round(self.o[10:12], 3)) + Tlift = Tin.copy() + Tlift[:3, 3] = Tin[:3, 3] + 0.08 * V.spoon_axis(phi) + Tlift2 = Tlift.copy() + Tlift2[:3, 3] += np.array([0, 0, 0.12]) + yield from self.reach("left", [Tlift, Tlift2], [60, 30], grip=1.0) + yield from self.hold(20) + self.snap("lifted") diff --git a/policies/flip_cutlery/opus-s3/vision.py b/policies/flip_cutlery/opus-s3/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..4677d5fb713ce061e61864303c00221766b5508a --- /dev/null +++ b/policies/flip_cutlery/opus-s3/vision.py @@ -0,0 +1,180 @@ +"""Image processing helpers for the head and wrist cameras.""" +import numpy as np +import cv2 +from scipy import ndimage + + +def hsv(im): + return cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + + +def edge_row(im): + """Per-column row of the brown counter front edge in the head image (or -1).""" + h = hsv(im) + brown = (h[..., 0] >= 8) & (h[..., 0] <= 25) & (h[..., 1] > 70) & (h[..., 2] > 60) & (h[..., 2] < 210) + lab, n = ndimage.label(brown) + if n > 1: + sz = ndimage.sum(brown, lab, range(1, n + 1)) + brown = lab == (int(np.argmax(sz)) + 1) + rows = np.full(im.shape[1], -1) + for c in range(im.shape[1]): + ys = np.nonzero(brown[:, c])[0] + if len(ys): + rows[c] = ys.min() + return rows, brown + + +def mug_mask_head(im): + """Mask of the mug (grey, unsaturated) above the counter edge in the head image.""" + h = hsv(im) + rows, brown = edge_row(im) + grey = (h[..., 1] < 45) & (h[..., 2] > 40) & (h[..., 2] < 238) + H, W = grey.shape + above = np.zeros_like(grey) + valid = rows[rows >= 0] + er = int(np.median(valid)) if len(valid) else H + for c in range(W): + r = rows[c] if rows[c] >= 0 else er + above[:r, c] = True + m = grey & above + m = ndimage.binary_opening(m, np.ones((2, 2))) + lab, n = ndimage.label(m) + if n == 0: + return None + sizes = ndimage.sum(m, lab, range(1, n + 1)) + k = int(np.argmax(sizes)) + 1 + if sizes[k - 1] < 15: + return None + return lab == k + + +H_COUNTER = 0.873 +MUG_R = 0.033 +MUG_H = 0.10 + + +def locate_mug(im, Tw, f, guess=None): + """Mug centre (world x, y) from one head image; Tw = world camera transform.""" + from scipy.optimize import least_squares + import g1kin as K + m = mug_mask_head(im) + if m is None: + return None, None + ft = mug_features(m) + if guess is None: + p, d = K.pixel_ray(Tw, ft["u_bot"], ft["v_bot"] + 0.5, f) + t = (H_COUNTER - p[2]) / d[2] + X = p + t * d + hd = d[:2] / np.linalg.norm(d[:2]) + guess = X[:2] + MUG_R * hd + + def res(xy): + c = np.array([xy[0], xy[1], H_COUNTER]) + dh = c[:2] - Tw[:2, 3] + dh /= np.linalg.norm(dh) + front = c - np.r_[MUG_R * dh, 0] + prc, _ = K.project(Tw, c, f) + prf, _ = K.project(Tw, front, f) + return [prc[0, 0] - ft["u_c"], prf[0, 1] - (ft["v_bot"] + 0.5)] + + s = least_squares(res, np.asarray(guess, float)) + return s.x, ft + + +def spoon_mask_head(im, mug_xy, Tw, f): + """Candidate spoon pixels: grey pixels outside the projected mug body.""" + import g1kin as K + h = hsv(im) + grey = (h[..., 1] < 50) & (h[..., 2] > 60) & (h[..., 2] < 245) + body = np.zeros(grey.shape, np.uint8) + pts = [] + for z in np.linspace(0, MUG_H, 6): + for a in np.linspace(0, 2 * np.pi, 24, endpoint=False): + pts.append([mug_xy[0] + (MUG_R + 0.004) * np.cos(a), mug_xy[1] + (MUG_R + 0.004) * np.sin(a), + H_COUNTER + z]) + uv, _ = K.project(Tw, np.array(pts), f) + hull = cv2.convexHull(np.round(uv).astype(np.int32)) + cv2.fillConvexPoly(body, hull, 1) + return grey & (body == 0), body + + +def spoon_axis(phi, theta=None): + """Unit axis (pointing out of the mug) of a spoon leaning towards azimuth phi.""" + if theta is None: + theta = np.arctan2(2 * MUG_R, MUG_H) + return np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]) + + +def rim_exit(mug_xy, phi): + return np.array([mug_xy[0] + MUG_R * np.cos(phi), mug_xy[1] + MUG_R * np.sin(phi), H_COUNTER + MUG_H]) + + +def fit_spoon(ims_Tw, mug_xy, f, plen=0.07): + """Score lean azimuths against the spoon pixels of one or more head views.""" + import g1kin as K + masks = [] + for im, Tw in ims_Tw: + sm, body = spoon_mask_head(im, mug_xy, Tw, f) + masks.append((ndimage.binary_dilation(sm, iterations=1), sm, Tw, body)) + best = None + scores = [] + for phi in np.deg2rad(np.arange(0, 360, 4)): + a = spoon_axis(phi) + E = rim_exit(mug_xy, phi) + sc = 0.0 + for dm, sm, Tw, body in masks: + P = np.array([E + s * a for s in np.linspace(0.005, plen, 15)]) + uv, z = K.project(Tw, P, f) + for (u, v), zz in zip(uv, z): + ui, vi = int(round(u)), int(round(v)) + if zz > 0 and 0 <= ui < 84 and 0 <= vi < 84 and not body[vi, ui]: + sc += 1.0 if dm[vi, ui] else -0.3 + scores.append(sc) + if best is None or sc > best[0]: + best = (sc, phi) + return best[1], best[0], np.array(scores) + + +def find_tip(im, Tw, f, mug_xy, exp_tip, win=14): + """World xy (at the expected height) of the lowest spoon pixel near the expected tip.""" + import g1kin as K + sm, body = spoon_mask_head(im, mug_xy, Tw, f) + uv, z = K.project(Tw, exp_tip, f) + u0, v0 = uv[0] + if z[0] <= 0: + return None + H, W = sm.shape + r0, r1 = int(max(0, v0 - win)), int(min(H, v0 + win + 1)) + c0, c1 = int(max(0, u0 - win)), int(min(W, u0 + win + 1)) + sub = np.zeros_like(sm) + sub[r0:r1, c0:c1] = sm[r0:r1, c0:c1] + lab, n = ndimage.label(sub) + if n == 0: + return None + best = None + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + if len(ys) < 3: + continue + dmin = np.min((xs - u0) ** 2 + (ys - v0) ** 2) + if best is None or dmin < best[0]: + best = (dmin, ys, xs) + if best is None: + return None + _, ys, xs = best + vb = ys.max() + ub = xs[ys >= vb - 1].mean() + p, d = K.pixel_ray(Tw, ub, vb + 0.5, f) + t = (exp_tip[2] - p[2]) / d[2] + return p + t * d + + +def mug_features(mask): + ys, xs = np.nonzero(mask) + vb = ys.max() + # body columns: use rows in the lower half of the blob to get the width + sel = ys >= (ys.min() + ys.max()) / 2 + u0, u1 = xs[sel].min(), xs[sel].max() + bot = xs[ys >= vb - 1] + return dict(u_c=(u0 + u1) / 2, u_bot=bot.mean(), v_bot=vb, v_top=ys.min(), width=u1 - u0 + 1, + n=len(ys)) diff --git a/policies/move_plate/astra-s1/episodes.csv b/policies/move_plate/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7c22b78376133e7a9f5418048fcb68bb906584d3 --- /dev/null +++ b/policies/move_plate/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,1,1599,success,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,1,1545,success,0 +620009,1,1564,success,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,1,1562,success,0 +620014,1,1511,success,0 +620015,1,1542,success,0 +620016,1,1617,success,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,1,1569,success,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,1,1550,success,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,1,1559,success,0 +620030,1,1512,success,0 +620031,1,1561,success,0 +620032,0,1700,timeout,0 +620033,1,1556,success,0 +620034,1,1579,success,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,1,1556,success,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,1,1581,success,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,1,1549,success,0 +620053,1,1469,success,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,1,1601,success,0 +620057,1,1573,success,0 +620058,1,1567,success,0 +620059,0,1700,timeout,0 +620060,1,1554,success,0 +620061,1,1663,success,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,1,1575,success,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,1,1548,success,0 +620075,0,1700,timeout,0 +620076,1,1515,success,0 +620077,1,1563,success,0 +620078,1,1550,success,0 +620079,0,1700,timeout,0 +620080,1,1589,success,0 +620081,0,1700,timeout,0 +620082,1,1578,success,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,1,1576,success,0 +620086,0,1700,timeout,0 +620087,1,1534,success,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,1,1589,success,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,1,1649,success,0 +620096,1,1551,success,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,1,1528,success,0 diff --git a/policies/move_plate/astra-s1/policy.py b/policies/move_plate/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3dc6b0705d3773923f2bc5ece045f4c0b26931ae --- /dev/null +++ b/policies/move_plate/astra-s1/policy.py @@ -0,0 +1,213 @@ +"""Deterministic, handwritten plate-transfer controller. + +Uses onboard RGB images and the robot's joint and pelvis observations only. +No demonstration files, trained components, or seed-specific state are needed. +""" +import numpy as np +from scipy.spatial.transform import Rotation as R + +def wrist_for(q, sp): + rot = R.from_euler('YXZ', q[:3]) * R.from_euler('Y', q[3]) * R.from_euler('XYZ', q[4:7]) + before = R.from_euler('YXZ', [sp, q[1], q[2]]) * R.from_euler('Y', q[3]) + out = q.copy() + out[0] = sp + out[4:7] = (before.inv() * rot).as_euler('XYZ') + return out + +def rim(im, lo=25, hi=60): + im = im.astype(float) + mask = (im.min(2) > 230) & (im.max(2) - im.min(2) < 15) + ys, xs = np.where(mask[lo:hi, 5:79]) + if len(xs) < 8: + return None + return float(np.median(xs + 5)) + +def brown(im): + a = im.astype(float) + r, g, b = (a[:, :, 0], a[:, :, 1], a[:, :, 2]) + m = (r > g + 12) & (g > b + 8) & (r > 70) + m[65:] = False + return m + +def project(u, v): + n = (v - 42) / 60.0 + den = 0.8660254 + 0.5 * n + return np.array([0.35 * (0.5 - 0.8660254 * n) / den, -(u - 42) * 0.35 / (60 * den)]) + +class NominalPolicy: + + def reset(self, obs, tools): + self.a = np.array(tools.hold_action(), float) + self.a[18] = 0 + self.q = np.array([-0.3, 0.1, 0.55, 0, -0.1, 0.15, -0.55]) + self.start = self.a[4:11].copy() + im = tools.image('head') + m = brown(im) + ys, xs = np.where(m[:, :40]) + v = float(np.max(ys)) if len(ys) else 18 + dx = float(np.clip(project(24, v)[0] - project(24, 18)[0], -0.1, 0.1)) + im = tools.image('left_wrist').astype(float) + yy, xx = np.where((im[:20].min(2) > 200) & (np.ptp(im[:20], axis=2) < 12)) + pu = float(np.median(xx)) if len(xx) else -25.0 + dy = float(np.clip((21 - pu) * 0.0035, -0.12, 0.16)) + im = tools.image('head')[:28, :38].astype(float) + yy, xx = np.where((im.min(2) > 200) & (np.ptp(im, axis=2) < 12)) + if len(xx): + dy = max(dy, float(np.clip((13 - float(np.median(xx))) * 0.007, -0.12, 0.16))) + self.pick = np.array([0.18 + dx, dy, 0.0]) + self.dest = np.array([0.1 + dx, dy - 0.45, 0.0]) + self.corner = np.array([34.0, 42.0]) + self.touch_sp = None + self.touch_t = None + self.touch_count = 0 + self.extra_depth = 0.0 + + def base(self, a, obs, target, speed=0.16): + b = obs['low_dim_obs'][18:22] + d = np.array(target[:2]) - b[:2] + v = np.clip(2 * d, -speed, speed) + v[np.abs(d) < 0.012] = 0 + n = np.linalg.norm(v) + if 0 < n < 0.075: + v *= 0.075 / n + a[0] = np.cos(b[3]) * v[0] + np.sin(b[3]) * v[1] + a[1] = -np.sin(b[3]) * v[0] + np.cos(b[3]) * v[1] + a[3] = np.clip(3 * (target[2] - b[3]), -0.4, 0.4) + + def servo(self, tools, gain=0.0008): + u = rim(tools.image('left_wrist')) + if u is not None: + self.q[2] = np.clip(self.q[2] + np.clip((42 - u) * gain, -0.02, 0.02), 0.15, 0.95) + self.q[6] = -self.q[2] + + def act(self, obs, tools): + t = obs['t'] + a = self.a.copy() + a[:2] = 0 + a[3] = 0 + a[14] = 0.8 * min(1, t / 100) + if t < 180: + a[4:11] = self.start + (self.q - self.start) * min(1, t / 100) + target = self.pick.copy() + target[0] -= 0.08 + self.base(a, obs, target) + elif t < 290: + if t % 10 == 0: + self.servo(tools) + a[4:11] = self.q + elif t < 430: + if t == 290: + self.extra_depth = 0.025 if self.q[2] > 0.65 else 0.0 + if t % 10 == 0: + self.servo(tools, 0.0005) + a[4:11] = self.q + target = self.pick.copy() + target[0] -= 0.08 + target[0] += (0.08 + self.extra_depth) * (t - 290) / 140 + self.base(a, obs, target, 0.08) + elif t < 470: + if t % 10 == 0: + self.servo(tools, 0.0005) + a[4:11] = self.q + elif t < 530: + a[4:11] = self.q + a[18] = min(1, (t - 470) / 40) + if t == 520: + m = brown(tools.image('head')) + cols = np.where(m.any(0))[0] + if len(cols) > 4: + gaps = np.diff(cols) + k = int(np.argmax(gaps)) + end = int(cols[k]) + 1 if gaps[k] > 8 else min(50, int(cols[-1]) + 1) + yy, xx = np.where(m[:, :end]) + if len(xx) > 12: + self.corner = np.array([float(xx.max()), float(yy.max()) - 2]) + self.dest[2] = float(obs['low_dim_obs'][21]) + elif t < 710: + a[4:11] = wrist_for(self.q, -0.3 - 0.65 * min(1, (t - 530) / 160)) + a[18] = 1 + elif t < 1210: + a[4:11] = wrist_for(self.q, -0.95) + a[18] = 1 + if t % 20 == 0 and obs['low_dim_obs'][19] < self.pick[1] - 0.19: + m = brown(tools.image('head')) + yy, xx = np.where(m) + if len(xx) > 30: + u = float(xx.max()) + yy2, xx2 = np.where(m[:, max(0, int(u) - 42):]) + v = float(yy2.max()) + if u < 80: + delta = project(u, v) - project(*self.corner) + b = obs['low_dim_obs'][18:22] + self.dest[:2] = 0.75 * self.dest[:2] + 0.25 * (b[:2] + np.clip(delta, -0.08, 0.08)) + self.base(a, obs, self.dest, 0.09) + elif t < 1390: + sp = -0.95 + 0.65 * min(1, (t - 1210) / 160) + a[4:11] = wrist_for(self.q, sp) + a[18] = 1 + qobs = obs['low_dim_obs'] + if t > 1270 and qobs[3] < 0.017 and (qobs[5] - a[9] < 0.024): + self.touch_count += 1 + else: + self.touch_count = 0 + if self.touch_count >= 5 and self.touch_sp is None: + self.touch_sp = sp + self.touch_t = t + elif t < 1460: + a[4:11] = wrist_for(self.q, -0.3) + a[18] = max(0, 1 - (t - 1390) / 40) + else: + a[4:11] = wrist_for(self.q, -0.3 - 0.4 * min(1, (t - 1460) / 120)) + a[18] = 0 + if self.touch_sp is not None and t >= self.touch_t: + elapsed = t - self.touch_t + a[4:11] = wrist_for(self.q, self.touch_sp - 0.4 * np.clip((elapsed - 75) / 110, 0, 1)) + a[18] = np.clip(1 - (elapsed - 10) / 40, 0, 1) + return a + +# Retry shallow pinches, then place near the center of the destination rack. +class Policy(NominalPolicy): + + def reset(self, obs, tools): + super().reset(obs, tools) + self.delay = 0 + self.recovered = False + self.recover_start = None + + def act(self, obs, tools): + local = dict(obs) + local['t'] = obs['t'] - self.delay + if local['t'] == 525 and (not self.recovered): + fingers = obs['low_dim_obs'][7:9] + if np.max(fingers) < 0.004 or np.sum(fingers) < -0.023: + self.recovered = True + self.recover_start = obs['t'] + self.recover_action = super().act(local, tools) + b = obs['low_dim_obs'][18:22] + self.recover_target = np.array([b[0] + 0.035, b[1], b[3]]) + if self.recover_start is not None: + elapsed = obs['t'] - self.recover_start + a = self.recover_action.copy() + a[0] = a[1] = a[3] = 0.0 + a[18] = float(np.clip((elapsed - 60) / 25, 0, 1)) + if 10 <= elapsed < 60: + self.base(a, obs, self.recover_target, 0.09) + if elapsed >= 100: + m = brown(tools.image('head')) + cols = np.where(m.any(0))[0] + if len(cols) > 4: + gaps = np.diff(cols) + k = int(np.argmax(gaps)) + end = int(cols[k]) + 1 if gaps[k] > 8 else min(50, int(cols[-1]) + 1) + yy, xx = np.where(m[:, :end]) + if len(xx) > 12: + self.corner = np.array([float(xx.max()), float(yy.max()) - 2]) + self.dest[2] = float(obs['low_dim_obs'][21]) + self.delay += 80 + self.recover_start = None + return a + a = super().act(local, tools) + if local['t'] >= 520: + self.corner = np.array([34.0 - 25.0 * (self.q[2] - 0.39), 42.0]) + self.dest[2] = 0.0 + return a diff --git a/policies/move_plate/astra-s2/episodes.csv b/policies/move_plate/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7490bc4f2f5fb5d764d51c4bc6873e0153ec78be --- /dev/null +++ b/policies/move_plate/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,871,terminated,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,844,terminated,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,731,terminated,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,800,terminated,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,813,terminated,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,789,terminated,0 +620055,0,859,terminated,0 +620056,0,1700,timeout,0 +620057,0,711,terminated,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,781,terminated,0 +620061,1,808,success,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,810,terminated,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,1,813,success,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,842,terminated,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,830,terminated,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,723,terminated,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/astra-s2/policy.py b/policies/move_plate/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..38c352bddf6fe0213c8a926ec68318933db097a4 --- /dev/null +++ b/policies/move_plate/astra-s2/policy.py @@ -0,0 +1,81 @@ +"""Hand-written, deterministic controller for transferring an upright plate. + +Only robot cameras and proprioception are used. Distances and gains are +physical control constants; no demonstration files are needed at runtime. +""" +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.pick = np.array([0.14, 0.10]) + self.place = np.array([0.04, -0.30]) + + # Locate the near edge and left end of the destination rack. Its + # wooden rails are warm brown against the neutral tabletop. + im = tools.image("head").astype(float) + wood = ((im[:, :, 0] > 1.12 * im[:, :, 1]) & + (im[:, :, 1] > 1.15 * im[:, :, 2]) & + (im[:, :, 0] > 90) & (im[:, :, 0] < 235)) + wood[:, :42] = False + yy, xx = np.where(wood) + if len(xx) > 10: + correction = np.array([0.008 * (23 - yy.max()), + 0.008 * (57 - xx.min())]) + self.place += np.clip(correction, -0.12, 0.12) + + # A plate at the outer end of the source rack can initially be + # clipped by the wrist view. Align laterally before reaching it. + im = tools.image("left_wrist").astype(float) + rim = ((im.min(axis=2) > 200) & + ((im.max(axis=2) - im.min(axis=2)) < 30)) + rim[30:] = False + yy, xx = np.where(rim) + if not len(xx): + self.pick[1] += 0.12 + elif np.median(xx) < 5: + self.pick[1] += 0.08 + + def act(self, obs, tools): + t = int(obs["t"]) + body = obs["low_dim_obs"] + action = self.hold.copy() + action[2] = 0.74 + action[18:] = 0 + target = self.pick.copy() + pitch = 0.0 + + # Approach with open fingers, close around the rim, and lift while + # counter-rotating the wrist to keep the plate standing vertically. + if t >= 200: + action[18] = 1 + if t >= 250: + pitch = -0.7 + if t >= 325: + target = self.place.copy() + if t >= 545: + pitch = 0.0 + if t >= 645: + action[18] = 0 + if t >= 745: + target = self.place + [-0.12, 0] + action[4] = pitch + action[9] = -pitch + + # Close the base loop using measured position and yaw. Respect the + # walking controller's minimum speed rather than dead-reckoning. + action[:2] = 0 + action[3] = np.clip(-3 * body[21], -0.3, 0.3) + if t < 835: + error = target - body[18:20] + velocity = np.clip(2 * error, -0.22, 0.22) + speed = np.linalg.norm(velocity) + if np.linalg.norm(error) < 0.012: + velocity *= 0 + elif speed < 0.065: + velocity *= 0.065 / max(speed, 1e-8) + c, s = np.cos(body[21]), np.sin(body[21]) + action[:2] = [c * velocity[0] + s * velocity[1], + -s * velocity[0] + c * velocity[1]] + return action diff --git a/policies/move_plate/astra-s3/episodes.csv b/policies/move_plate/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a46702fda2e82d78c2ea3efd97784e80fff7c366 --- /dev/null +++ b/policies/move_plate/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1010,success,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,1,1011,success,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1266,terminated,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,1,1011,success,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,669,terminated,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,1,1010,success,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/astra-s3/policy.py b/policies/move_plate/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2d8337d3ca8fb62b250c9c3db9638d268a162991 --- /dev/null +++ b/policies/move_plate/astra-s3/policy.py @@ -0,0 +1,135 @@ +"""Deterministic plate transfer with a guarded visual pickup recovery. + +Only proprioception and the robot-mounted cameras are used. Motion is divided +into approach, grasp, lift, transfer, lowering, release, and withdrawal phases. +The recovery uses neutral-color plate rims and brown rack supports as visual +features; it contains no learned parameters or stored demonstration frames. +""" +import cv2 +import numpy as np + +class _Primary: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action()).copy() + self.a[18:]=0 + def move(self,a,obs,x,y): + p=obs['low_dim_obs'][18:22];err=np.array([x-p[0],y-p[1]]) + v=np.clip(err*1.8,-.16,.16) + if np.linalg.norm(err)<.012:v[:]=0 + elif np.linalg.norm(v)<.065:v*=.065/max(1e-6,np.linalg.norm(v)) + a[:2]=[np.cos(p[3])*v[0]+np.sin(p[3])*v[1],-np.sin(p[3])*v[0]+np.cos(p[3])*v[1]] + a[3]=np.clip(-p[3]*2,-.25,.25) + def act(self,obs,tools): + t=obs['t'];a=self.a.copy();a[4]=-.15 + if t<260:self.move(a,obs,.08,.13) + elif t<300:pass + elif t<340:a[18]=1 + elif t<450:a[18]=1;a[4]=-.15-.50*(t-340)/110 + elif t<770: + a[18]=1;a[4]=-.65;self.move(a,obs,.025,-.31) + elif t<820:a[18]=1;a[4]=-.65 + elif t<890: + a[18]=1;a[4]=-.65+.50*(t-820)/70 + elif t<960:a[18]=1 + else: + a[18]=0 + if t>1010:self.move(a,obs,-.08,-.31) + if t>=770:a[8]=.15*np.clip((t-770)/120,0,1) + return a + + +class _Recovery: + def reset(self,o,e): + self.a=np.asarray(e.hold_action()).copy();self.a[18:]=0 + self.y=.13;self.roll=0;self.x=.08 + self.dx=.025;self.dy=-.31;self.delay=0;self.retries=0;self.retry_at=None + def move(self,a,obs,x,y): + p=obs['low_dim_obs'][18:22];err=np.array([x-p[0],y-p[1]]) + v=np.clip(err*1.8,-.16,.16) + if np.linalg.norm(err)<.012:v[:]=0 + elif np.linalg.norm(v)<.065:v*=.065/max(1e-6,np.linalg.norm(v)) + a[:2]=[np.cos(p[3])*v[0]+np.sin(p[3])*v[1],-np.sin(p[3])*v[0]+np.cos(p[3])*v[1]] + a[3]=np.clip(-p[3]*2,-.25,.25) + def detect(self,im): + f=im.astype(float);m=((f.min(2)>175)&(f.max(2)-f.min(2)<25)).astype('uint8');m[:,:2]=0;m[:,82:]=0 + n,l,stats,c=cv2.connectedComponentsWithStats(m) + ids=[i for i in range(1,n) if stats[i,4]>8 and stats[i,3]>12] + if not ids:return None + k=max(ids,key=lambda i:stats[i,3]);ys,xs=np.where(l==k) + return float(np.median(xs)),float(np.max(ys)) + def rack(self,im): + f=im.astype(float) + m=(f[:,:,0]>f[:,:,1]*1.10)&(f[:,:,1]>f[:,:,2]*1.13)&(f[:,:,0]>65) + m[60:]=False + ys,xs=np.where(m) + if len(xs)<20:return None + return float(np.max(xs)),float(np.max(ys)) + def act(self,o,e): + t=o['t']-self.delay;a=self.a.copy();a[4]=-.15;a[5]=self.roll + if t==650 and self.retry_at is None and self.retries<2 and max(o['low_dim_obs'][7:9])<-.0193: + self.retry_at=o['t'];self.retry_x=float(o['low_dim_obs'][18]+.032);self.retry_y=float(o['low_dim_obs'][19]);self.retries+=1 + if self.retry_at is not None: + k=o['t']-self.retry_at + if k<110: + if k>=15 and k<70:self.move(a,o,self.retry_x,self.retry_y) + if k>=70:a[18]=1 + return a + self.delay+=110;self.retry_at=None;t=o['t']-self.delay + if t==750:self.dy=-.31-.3*self.roll + if 900<=t<1100 and t%20==0: + r=self.rack(e.image('head')) + if r: + self.dx=float(np.clip(o['low_dim_obs'][18]+(31-r[1])*.006,-.12,.15)) + self.dy=float(np.clip(o['low_dim_obs'][19]+(50-40*self.roll-r[0])*.006,-.65,-.1)) + if t<480: + a[4]=-.25 if t<240 else -.15 + if t>=100 and t%15==0: + det=self.detect(e.image('left_wrist')) + if det: + target=o['low_dim_obs'][19]+np.clip((50-det[0])*.003,-.07,.07) + self.y=.3*self.y+.7*target + if t>310: + target=o['low_dim_obs'][18]+np.clip((82-det[1])*.002,-.025,.025) + self.x=float(np.clip(.5*self.x+.5*target,-.02,.18)) + self.move(a,o,-.07 if t<240 else self.x,self.y) + elif t<610:pass + elif t<650:a[18]=1 + elif t<750: + f=min(1,(t-650)/50);a[18]=1;a[4]=-.15-.50*f;a[9]=0 + elif t<1100: + a[18]=1;a[4]=-.65;a[9]=0;self.move(a,o,self.dx,self.dy) + elif t<1150:a[18]=1;a[4]=-.65;a[9]=0 + elif t<1250: + a[18]=1;a[4]=-.65+.5*(t-1150)/100;a[9]=0 + elif t<1300:a[18]=1 + else: + a[18]=0 + if t>1360:self.move(a,o,self.dx-.14,self.dy) + if 700<=t<750:a[8]=1.2*(t-700)/50 + elif 750<=t<1100:a[8]=1.2 + elif 1100<=t<1150:a[8]=1.2-.9*(t-1100)/50 + elif t>=1150:a[8]=.30 + return a + + +class Policy: + def reset(self, obs, tools): + self.primary = _Primary() + self.primary.reset(obs, tools) + self.recovery = None + self.recovery_start = 0 + + def act(self, obs, tools): + # A fully closed, unobstructed pair of fingers indicates a missed grip. + # Restart the visual approach early enough to retain time for release. + if obs["t"] == 340 and max(obs["low_dim_obs"][7:9]) < -0.0193: + self.recovery_start = int(obs["t"]) + self.recovery = _Recovery() + local = dict(obs) + local["t"] = 0 + self.recovery.reset(local, tools) + if self.recovery is not None: + local = dict(obs) + local["t"] = int(obs["t"]) - self.recovery_start + return self.recovery.act(local, tools) + return self.primary.act(obs, tools) diff --git a/policies/move_plate/deepseek1017-s1/episodes.csv b/policies/move_plate/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..04b2b4953b3e4f0822f177c9ca1e963a8abffd41 --- /dev/null +++ b/policies/move_plate/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/deepseek1017-s1/policy.py b/policies/move_plate/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ec83e6a049166a17eba86159bfd012a814243d57 --- /dev/null +++ b/policies/move_plate/deepseek1017-s1/policy.py @@ -0,0 +1,211 @@ +"""Control policy for the G1 plate-transfer task. + +Hand-written state machine: + 1. walk to the table (fixed base trajectory) + 2. strafe left into the left dish rack's working position + 3. raise the left(robot) arm, close the gripper on the plate, lift it + 4. carry the plate right in front of the right dish rack + 5. lower the plate into the rack and release + +Only the robot's own cameras and low_dim_obs are used. +""" + +import numpy as np + + +def _ang_diff(a, b): + return (a - b + np.pi) % (2.0 * np.pi) - np.pi + + +class Policy: + def __init__(self): + self.phase = 0 + self.t = 0 + self.hold = None + self.cur = None + self.grip_open = 0.2 + self.grip_closed = 1.0 + self.done_t = None + + # ------------------------------------------------------------------ utils + @staticmethod + def _arm(slot, arm): + a = slot.copy() + a[11:18] = arm + return a + + @staticmethod + def _base(slot, vx=0.0, vy=0.0, wz=0.0, height=0.74): + a = slot.copy() + a[0] = vx + a[1] = vy + a[2] = height + a[3] = wz + return a + + def _set(self, arm=None, grip=None, vx=0.0, vy=0.0, wz=0.0): + """Build an action from the current hold pose, overriding some fields.""" + a = self.cur.copy() + a[0] = vx + a[1] = vy + a[2] = 0.74 + a[3] = wz + if arm is not None: + a[11:18] = arm + if grip is not None: + a[18] = a[19] = grip + return a + + # ------------------------------------------------------------------ hooks + def reset(self, obs, tools): + self.phase = 0 + self.t = 0 + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.cur = self.hold.copy() + self.done_t = None + # flush the stale first frame after reset (rendering cache) + try: + tools.image("head") + except Exception: + pass + + def act(self, obs, tools): + self.t += 1 + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64) + x, y, z, yaw = ld[18], ld[19], ld[20], ld[21] + left = ld[0:7] + right = ld[9:16] + p = self.phase + + # ---------------- phase 0..1: walk forward to the table ----------- + if p == 0: + # walk forward with a fixed command; stop when base has advanced + if x >= 0.165 or self.t > 220: + self.phase = 1 + self.t = 0 + a = self._set(vx=0.0, vy=0.0, wz=0.0) + else: + a = self._set(vx=0.30, vy=0.0, wz=0.0) + self.cur = a + return a + + # ---------------- phase 1: strafe left into grasp position -------- + if p == 1: + if y >= 0.335 or self.t > 200: + self.phase = 2 + self.t = 0 + a = self._set(vy=0.0) + else: + a = self._set(vx=0.0, vy=0.25, wz=0.0) + self.cur = a + return a + + # ---------------- phase 2: reach pose ----------------------------- + if p == 2: + a = self._set(arm=[0.50, 0.0, -0.10, -0.50, 0.0, 0.10, 0.0], + grip=self.grip_open) + if self.t > 45: + self.phase = 3 + self.t = 0 + self.cur = a + return a + + # ---------------- phase 3: close gripper -------------------------- + if p == 3: + f = min(1.0, self.t / 18.0) + g = self.grip_open + f * (self.grip_closed - self.grip_open) + a = self._set(arm=[0.50, 0.0, -0.10, -0.50, 0.0, 0.10, 0.0], grip=g) + if self.t > 20: + self.phase = 4 + self.t = 0 + self.cur = a + return a + + # ---------------- phase 4: lift the plate ------------------------- + if p == 4: + a = self._set(arm=[1.05, 0.0, -0.10, -0.85, 0.0, 0.10, 0.0], + grip=1.0) + if self.t > 45: + self.phase = 5 + self.t = 0 + self.cur = a + return a + + # ---------------- phase 5: move in front of right rack ----------- + if p == 5: + ex = 0.17 - x + ey = 0.06 - y + eth = _ang_diff(-0.58, yaw) + vx = float(np.clip(1.5 * ex, -0.30, 0.30)) + vy = float(np.clip(1.2 * ey, -0.32, 0.32)) + wz = float(np.clip(1.2 * eth, -0.28, 0.28)) + if (abs(ex) < 0.025 and abs(ey) < 0.03 and abs(eth) < 0.05) or self.t > 300: + self.phase = 6 + self.t = 0 + a = self._set(arm=[1.05, 0.0, -0.10, -0.85, 0.0, 0.10, 0.0], + grip=1.0, vx=vx, vy=vy, wz=wz) + self.cur = a + return a + + # ---------------- phase 6: lower the plate toward the rack ------- + if p == 6: + seq = [ + (0.85, 0.00, 0.20, -0.60), + (0.70, 0.00, 0.45, -0.45), + (0.63, 0.00, 0.48, -0.36), + ] + idx = min(len(seq) - 1, self.t // 18) + arm = [seq[idx][0], seq[idx][1], seq[idx][2], seq[idx][3], 0.0, 0.10, 0.0] + a = self._set(arm=arm, grip=1.0) + if self.t > 18 * len(seq): + self.phase = 7 + self.t = 0 + self.cur = a + return a + + # ---------------- phase 7: fine lateral alignment ---------------- + if p == 7: + ex = 0.14 - x + ey = -0.175 - y + eth = _ang_diff(-0.57, yaw) + vx = float(np.clip(1.5 * ex, -0.25, 0.25)) + vy = float(np.clip(1.2 * ey, -0.30, 0.30)) + wz = float(np.clip(1.2 * eth, -0.25, 0.25)) + if (abs(ex) < 0.03 and abs(ey) < 0.025) or self.t > 90: + self.phase = 8 + self.t = 0 + a = self._set(arm=[0.62, 0.0, 0.70, -0.35, 0.0, 0.10, 0.0], + grip=1.0, vx=vx, vy=vy, wz=wz) + self.cur = a + return a + + # ---------------- phase 8: extend forward into the slot ---------- + if p == 8: + seq = [ + (0.72, 0.70, -0.18), + (0.80, 0.70, -0.05), + ] + idx = min(len(seq) - 1, self.t // 18) + arm = [seq[idx][0], 0.0, seq[idx][1], seq[idx][2], 0.0, 0.10, 0.0] + a = self._set(arm=arm, grip=1.0) + if self.t > 18 * len(seq): + self.phase = 9 + self.t = 0 + self.cur = a + return a + + # ---------------- phase 9: release and settle -------------------- + if p == 9: + f = min(1.0, self.t / 25.0) + g = 1.0 - f + a = self._set(arm=[0.80, 0.0, 0.70, -0.05, 0.0, 0.10, 0.0], grip=g) + if self.t > 30: + self.phase = 10 + self.t = 0 + self.cur = a + return a + + # ---------------- phase 10: hold still, let it settle ------------ + a = self._set(arm=[0.80, 0.0, 0.70, -0.05, 0.0, 0.10, 0.0], grip=0.0) + self.cur = a + return a diff --git a/policies/move_plate/deepseek1017-s2/episodes.csv b/policies/move_plate/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..04b2b4953b3e4f0822f177c9ca1e963a8abffd41 --- /dev/null +++ b/policies/move_plate/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/deepseek1017-s2/policy.py b/policies/move_plate/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5a1a5cab3589c66e346cca6e979cd87589d571f5 --- /dev/null +++ b/policies/move_plate/deepseek1017-s2/policy.py @@ -0,0 +1,182 @@ +"""Hand-written control policy for the G1 'move_plate' task. + +Deterministic scripted pick-and-place using only the robot's own cameras +and proprioception: + + * walk to the counter, + * bring the left arm into a pre-grasp pose in front of the plate, + * close the last centimetres while watching the plate grow in the left + wrist camera, + * close the gripper, pull the plate out by stepping backwards, + * lift it, swing it over the second dish rack and release it. +""" + +import cv2 +import numpy as np + + +def _plate_area(img): + """Return the area of the brightest blob in a wrist image.""" + hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) + v = hsv[:, :, 2] + s = hsv[:, :, 1] + mask = ((v > 175) & (s < 60)).astype(np.uint8) + mask[:4, :] = 0 + mask[-4:, :] = 0 + mask[:, :4] = 0 + mask[:, -4:] = 0 + n, _lab, stats, _cent = cv2.connectedComponentsWithStats(mask, 8) + best = 0 + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + h = int(stats[i, cv2.CC_STAT_HEIGHT]) + if area >= 20 and h >= 8 and area > best: + best = area + return best + + +class Policy: + """Scripted pick-and-place controller.""" + + def reset(self, obs, tools): + """Prepare for one episode. + + Args: + obs: The first observation. + tools: Tool handle (hold_action / image / render). + """ + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.k = 0 + self.yaw0 = None + self.yaw_place = None + self.area = 0 + self.arm = self.hold.copy() + + # -- helpers --------------------------------------------------------- + def _base(self, raw, obs, target=None): + """Overwrite the base yaw command with a hold controller.""" + a = raw.copy() + ref = self.yaw0 if target is None else target + if ref is not None: + yaw = float(obs["low_dim_obs"][21]) + err = (ref - yaw + np.pi) % (2.0 * np.pi) - np.pi + a[3] = float(np.clip(2.5 * err, -0.6, 0.6)) + return a + + def _step(self, n, nxt): + """Advance the phase counter after ``n`` control steps.""" + self.k += 1 + if self.k >= n: + self.phase = nxt + self.k = 0 + + # -- control --------------------------------------------------------- + def act(self, obs, tools): + """Return the action for this control step. + + Args: + obs: Current observation. + tools: Tool handle. + + Returns: + The physical action (20 floats). + """ + a = self.arm.copy() + yaw = float(obs["low_dim_obs"][21]) + + if self.phase == 0: # walk to the counter + a = self.hold.copy() + a[0] = 0.15 + self.arm = a.copy() + self._step(75, 1) + + elif self.phase == 1: # raise the arm in front of the plate + if self.k == 0: + a = self.hold.copy() + a[4] = 0.70 # shoulder pitch + a[5] = 0.0 # shoulder roll + a[6] = -0.20 # shoulder yaw + a[7] = -0.40 # elbow + a[8] = 0.0 # wrist roll + a[9] = -0.40 # wrist pitch + a[10] = 0.80 # wrist yaw + a[18] = 0.0 # open the left gripper + self.arm = a.copy() + self.yaw0 = yaw + self.yaw_place = yaw + 0.20 + self._step(24, 2) + + elif self.phase == 2: # close the last distance while watching the plate + a = self.arm.copy() + a[0] = 0.07 + if self.k % 2 == 0: + try: + self.area = _plate_area(tools.image("left_wrist")) + except Exception: + self.area = 0 + if self.area > 2500 or self.k > 150: + self.phase = 3 + self.k = 0 + else: + self.k += 1 + + elif self.phase == 3: # settle and nudge the shoulder yaw + a = self.arm.copy() + a[6] = -0.10 + self._step(22, 4) + + elif self.phase == 4: # close the gripper slowly + a = self.arm.copy() + a[18] = float(min(1.0, self.k / 24.0)) + self._step(30, 5) + + elif self.phase == 5: # let the fingers settle on the plate + a = self.arm.copy() + a[18] = 1.0 + self._step(12, 6) + + elif self.phase == 6: # pull the plate out by walking backwards + a = self.arm.copy() + a[18] = 1.0 + a[0] = -0.08 + self._step(45, 7) + + elif self.phase == 7: # lift the plate + a = self.arm.copy() + a[18] = 1.0 + a[0] = 0.0 + a[4] = float(0.70 + 0.20 * min(1.0, self.k / 40.0)) + self._step(41, 8) + + elif self.phase == 8: # swing towards the second rack and turn slightly + a = self.arm.copy() + a[18] = 1.0 + a[4] = 0.90 + a[5] = float(0.60 * min(1.0, self.k / 30.0)) + self._step(31, 9) + + elif self.phase == 9: # lower into the rack + a = self.arm.copy() + a[18] = 1.0 + a[4] = float(0.90 - 0.35 * min(1.0, self.k / 30.0)) + a[5] = 0.60 + self._step(31, 10) + + elif self.phase == 10: # release + a = self.arm.copy() + a[4] = 0.55 + a[5] = 0.60 + a[18] = float(max(0.0, 1.0 - self.k / 40.0)) + self._step(70, 11) + + else: # hold + a = self.arm.copy() + a[4] = 0.55 + a[5] = 0.60 + a[18] = 0.0 + self.k += 1 + + if self.phase >= 8 and self.yaw_place is not None: + return self._base(a, obs, self.yaw_place) + return self._base(a, obs) diff --git a/policies/move_plate/deepseek1017-s3/episodes.csv b/policies/move_plate/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8a463cf9bde425bdf78e6e217816266a4e908fb2 --- /dev/null +++ b/policies/move_plate/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,243,terminated,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,401,terminated,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,275,terminated,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,269,terminated,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,275,terminated,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,265,terminated,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,281,terminated,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,273,terminated,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,411,terminated,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/deepseek1017-s3/policy.py b/policies/move_plate/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..75700f4e33f58f440ef2896c5b50ed15de5cbf97 --- /dev/null +++ b/policies/move_plate/deepseek1017-s3/policy.py @@ -0,0 +1,133 @@ +"""Hand-written control policy for the G1 plate move task. + +The policy is a deterministic state machine. It walks up to the dish-rack +table, reaches the plate with the left hand, grips it, lifts it out of the +left rack, swings it to the right rack with a base rotation, lowers it and +releases it. + +Only the robot-mounted cameras / proprioception are used inside the policy; +all constants below were tuned by running development episodes. +""" + +import numpy as np + + +class Policy: + """Deterministic pick-and-place state machine.""" + + # Joint vectors: [shoulder_pitch, roll, yaw, elbow, wrist_roll, + # wrist_pitch, wrist_yaw] + PRE = np.array([0.30, 0.30, 0.50, 0.30, 0.0, 0.30, 0.0]) + LIFT = np.array([1.00, 0.30, 0.50, 0.00, 0.0, -0.60, 0.0]) + PLACE = np.array([0.35, 0.30, 0.50, 0.35, -0.80, 0.20, 0.0]) + REST = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + + # Stage durations, in control steps (50 Hz). + WALK_STEPS = 110 + RAISE_STEPS = 12 + PRE_STEPS = 25 + CLOSE_STEPS = 30 + LIFT_STEPS = 40 + ROTATE_STEPS = 130 + SQUAT_STEPS = 25 + PLACE_STEPS = 25 + OPEN_STEPS = 25 + SETTLE_STEPS = 100 + + def reset(self, obs, tools): + """Prepare for one episode.""" + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t0 = int(obs["t"]) + self.arm = np.array(self.REST, dtype=np.float32) + self.grip = 0.0 + self.wz = 0.0 + self.height = 0.74 + self.vx = 0.0 + self.vy = 0.0 + + def _timeline(self, t): + """Return the active stage for local step ``t``.""" + bounds = [ + (self.WALK_STEPS, "walk"), + (self.RAISE_STEPS, "raise"), + (self.PRE_STEPS, "pre"), + (self.CLOSE_STEPS, "close"), + (self.LIFT_STEPS, "lift"), + (self.ROTATE_STEPS, "rotate"), + (self.SQUAT_STEPS, "squat"), + (self.PLACE_STEPS, "place"), + (self.OPEN_STEPS, "open"), + (self.SETTLE_STEPS, "settle"), + ] + acc = 0 + for n, name in bounds: + acc += n + if t < acc: + return name + return "settle" + + def act(self, obs, tools): + """Return the 20-float physical action for this control step.""" + t = int(obs["t"]) - self.t0 + stage = self._timeline(t) + + # Defaults: hold the pose, stand at walking height. + self.vx = 0.0 + self.vy = 0.0 + self.wz = 0.0 + self.height = 0.74 + self.grip = 0.0 + + if stage == "walk": + self.vx = 0.2 + self.height = 0.74 + self.arm = self.REST.copy() + self.grip = 0.6 + elif stage == "raise": + self.height = 0.85 + self.arm = self.REST.copy() + self.grip = 0.0 + elif stage == "pre": + self.height = 0.85 + self.arm = self.PRE.copy() + self.grip = 0.0 + elif stage == "close": + self.height = 0.85 + self.arm = self.PRE.copy() + self.grip = 0.95 + elif stage == "lift": + self.height = 0.85 + self.arm = self.LIFT.copy() + self.grip = 0.95 + elif stage == "rotate": + # Swing the held plate towards the right dish rack. + self.height = 0.85 + self.arm = self.LIFT.copy() + self.grip = 0.95 + self.wz = -1.0 + elif stage == "squat": + self.height = 0.70 + self.arm = self.LIFT.copy() + self.grip = 0.95 + elif stage == "place": + self.height = 0.70 + self.arm = self.PLACE.copy() + self.grip = 0.95 + elif stage == "open": + self.height = 0.70 + self.arm = self.PLACE.copy() + self.grip = 0.0 + else: # settle / retreat + self.height = 0.74 + self.arm = self.REST.copy() + self.grip = 0.0 + + raw = self.hold.copy() + raw[0] = self.vx + raw[1] = self.vy + raw[2] = self.height + raw[3] = self.wz + raw[4:11] = self.arm + raw[18] = self.grip + raw[19] = 0.6 + return raw diff --git a/policies/move_plate/gpt61sol-s1/episodes.csv b/policies/move_plate/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..858afd5b0257d9fc8eb4154157308cf36f460ec2 --- /dev/null +++ b/policies/move_plate/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,1,1279,success,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,1,982,success,0 +620029,1,985,success,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,1,1267,success,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,1,937,success,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,1,959,success,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,1,971,success,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt61sol-s1/policy.py b/policies/move_plate/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9a97d090028d2764c61ff04678374e2bd4b3a211 --- /dev/null +++ b/policies/move_plate/gpt61sol-s1/policy.py @@ -0,0 +1,99 @@ +"""Deterministic camera-guided plate transfer with joint-space motions.""" +import cv2 +import numpy as np + +class Policy: + @staticmethod + def racks(im): + a=im.astype(np.float32);r,g,b=a[:,:,0],a[:,:,1],a[:,:,2] + m=((r>65)&(r>1.12*g)&(g>1.13*b)).astype(np.uint8) + m[45:]=0 + n,labels,stats,_=cv2.connectedComponentsWithStats(cv2.dilate(m,np.ones((3,3),np.uint8))) + out=[] + for i,(x,y,w,h,area) in enumerate(stats[1:],1): + if area<25 or w<8 or h<5:continue + q=m*(labels==i);rows=q.sum(axis=1) + ys=np.flatnonzero(rows>max(3,float(rows.max())*.5)) + xs=np.where(q)[1] + if len(xs) and len(ys):out.append(((float(xs.min())+float(xs.max()))*.5,float(ys[-1]),int(x),int(x+w))) + return sorted(out) + + def locate(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32).copy() + self.a[18:]=0 + self.start=np.asarray(obs['low_dim_obs'][18:22],dtype=float).copy() + im=tools.image('head');rs=self.racks(im) + src=rs[0] if rs else (12.,18.,0,26) + dst=rs[-1] if len(rs)>1 else (70.,24.,56,84) + v=im.astype(np.int16) + m=((v.min(axis=2)>155)&((v.max(axis=2)-v.min(axis=2))<24)).astype(np.uint8) + m[28:]=0;m[:,min(50,src[3]+5):]=0 + n,labels,stats,cent=cv2.connectedComponentsWithStats(m) + candidates=[] + for i,(x,y,w,h,area) in enumerate(stats[1:],1): + if 6<=h<=23 and w<=14 and y<4 and x0)&(np.abs(v)<.06);v[small]=np.sign(v[small])*.06 + yaw=float(b[3]);c,s=np.cos(yaw),np.sin(yaw) + self.a[0]=c*v[0]+s*v[1];self.a[1]=-s*v[0]+c*v[1] + self.a[3]=np.clip(-4*yaw,-.6,.6) + + def act(self,obs,tools): + if self.phase==-1: + self.age+=1 + self.a[3]=np.clip(-float(obs['low_dim_obs'][21])*3,-.5,.5) + if self.age>=60: + self.locate(obs,tools) + return self.a.copy() + self.age+=1;target=self.pick;arm=self.pose;grip=0.;height=.74 + p=self.phase + if p==0: + duration=210 + elif p==1: + duration=65;grip=min(1,self.age/40) + elif p==2: + duration=105;grip=1;arm=self.carry;target=self.pick+[-.08,0] + elif p==3: + duration=260;grip=1;arm=self.carry;target=self.place+[.015,0] + elif p==4: + duration=100;grip=1;target=self.place+[.015,0] + elif p==5: + duration=65;grip=1;target=self.place+[.015,0];height=.74-.035*min(1,self.age/60) + elif p==6: + duration=260;target=self.place+[.015,0];height=.705;grip=max(0,1-self.age/100) + elif p==7: + duration=100;target=self.rest;height=.705;arm=np.zeros(7) + elif p==8: + duration=180;target=self.place+[-.12,0];arm=np.zeros(7) + else: + duration=100000;target=self.rest;arm=np.zeros(7) + self.move(obs,target) + if p in (5,6,7,9):self.a[0:2]=0;self.a[3]=np.clip(-float(obs['low_dim_obs'][21])*2,-.2,.2) + self.last+=np.clip(arm-self.last,-.012,.012) + self.a[4:11]=self.last;self.a[11:18]=0 + self.a[2]=height;self.a[18]=grip;self.a[19]=0 + if self.age>=duration: + if p in (6,8):self.rest=np.asarray(obs['low_dim_obs'][18:20],float).copy() + self.phase+=1;self.age=0 + return self.a.copy() diff --git a/policies/move_plate/gpt61sol-s2/episodes.csv b/policies/move_plate/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..04b2b4953b3e4f0822f177c9ca1e963a8abffd41 --- /dev/null +++ b/policies/move_plate/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt61sol-s2/policy.py b/policies/move_plate/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f2507c1e8d128abe1d0fa87dfc79552a2197b605 --- /dev/null +++ b/policies/move_plate/gpt61sol-s2/policy.py @@ -0,0 +1,151 @@ +"""Deterministic visual alignment and slow, upright plate transfer.""" +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float64) + self.a[18] = 0.0 + self.phase = 0 + self.age = 0 + self.pick = np.array([.10, .15]) + self.place = np.array([.10, -.43]) + self.scan = np.array([0., .12]) + self.align_count = 0 + self.grasp_attempt = 0 + im = tools.image('head').astype(np.int16) + mask = self.wood(im) + mask[:,:40] = 0 + mask[27:,:] = 0 + ys, xs = np.where(mask) + if len(xs) > 12: + # Projection of the rack on the horizontal work surface. + self.place[1] -= np.clip((np.mean(xs)-69.)*.008, -.065, .065) + self.place[0] += np.clip((11.-np.mean(ys))*.006, -.045, .045) + + @staticmethod + def wood(im): + r,g,b = im[:,:,0], im[:,:,1], im[:,:,2] + return ((r-b>25)&(g-b>12)&(r>95)&(g>65)&(r-g<90)).astype(np.uint8) + + @staticmethod + def plate(im): + b = im.astype(np.int16) + m = ((b.max(2)-b.min(2)<6)&(b.mean(2)>60)&(b.mean(2)<245)).astype(np.uint8) + m[35:,:] = 0 + n, _, st, centers = cv2.connectedComponentsWithStats(m) + candidates = [i for i in range(1,n) if st[i,4]>65 and st[i,2]<31 and st[i,3]>8] + if not candidates: + return None + i = max(candidates,key=lambda k:st[k,4]) + return centers[i] + + def walk(self, obs, goal, speed=.12): + q = obs['low_dim_obs'] + err = goal-q[18:20] + cmd = np.clip(1.5*err,-speed,speed) + cmd[np.abs(err)<.009] = 0 + mag = np.linalg.norm(cmd) + if 0 < mag < .065: + cmd *= .065/mag + yaw = float(q[21]) + c,s = np.cos(yaw),np.sin(yaw) + self.a[:2] = [c*cmd[0]+s*cmd[1],-s*cmd[0]+c*cmd[1]] + + def advance(self): + self.phase += 1 + self.age = 0 + + def act(self, obs, tools): + q = obs['low_dim_obs'] + self.a[:2] = 0 + self.a[3] = np.clip(-3.*q[21],-.3,.3) + self.a[2] = .74 + pitch, elbow, wp, grip = -.2, 0., .4, 0. + phase = self.phase + if phase == 0: + self.walk(obs,self.scan) + if self.age >= 140 and self.age%20 == 0: + im = tools.image('left_wrist') + ctr = self.plate(im) + if ctr is None and self.align_count < 3: + self.scan[1] += .04 + self.align_count += 1 + else: + if ctr is not None: + self.pick[1] = float(q[19])+np.clip((64.-ctr[0])*.003,-.09,.09) + mask = self.wood(im.astype(np.int16)) + row = mask.sum(1) + row[:12] = 0 + row[60:] = 0 + if row.max()>12: + front = np.flatnonzero(row>max(12,row.max()*.55))[-1] + self.pick[0] = np.clip(float(q[18])+.10+(24.-front)*.005,.035,.17) + self.advance() + if self.age>240: + self.advance() + elif phase == 1: + self.walk(obs,self.pick) + if self.age >= 190: + self.advance() + elif phase == 2: + grip = 1. + if self.age >= 70: + if np.mean(q[7:9]) < -.019 and self.grasp_attempt < 1: + self.grasp_attempt += 1 + self.pick[0] += .025 + self.phase = 1 + self.age = 0 + else: + self.advance() + elif phase == 3: + pitch, wp, grip = -.9, 1.1, 1. + if self.age >= 170: + self.advance() + elif phase == 4: + pitch, wp, grip = -.9, 1.1, 1. + self.walk(obs,self.place) + if self.age >= 340: + self.advance() + elif phase == 5: + grip = 1. + if self.age >= 160: + self.advance() + elif phase == 6: + grip = 1. + # Align with a gap between the pegs while the plate remains held. + if self.age in (0,30): + im = tools.image('left_wrist').astype(np.int16) + m = self.wood(im) + m[:18,:] = 0 + m[72:,:] = 0 + hist = m.sum(0).astype(float) + peaks = [i for i in range(3,81) if hist[i]>5 and hist[i]>=hist[i-1] and hist[i]>=hist[i+1]] + spaced=[] + for i in sorted(peaks,key=lambda k:-hist[k]): + if all(abs(i-j)>5 for j in spaced): + spaced.append(i) + spaced.sort() + gaps=[(l+r)/2 for l,r in zip(spaced,spaced[1:]) if 7= 70: + self.advance() + elif phase == 7: + if self.age >= 160: + self.advance() + else: + # Free the hand from the pegs after the plate has settled. + pitch,wp = -.45,.65 + self.a[3] = 0. + if obs['fell']: + self.a[:4] = [0,0,.74,0] + targets = np.zeros(14) + targets[0],targets[3],targets[5] = pitch,elbow,wp + self.a[4:18] += np.clip(targets-self.a[4:18],-.008,.008) + self.a[18] += np.clip(grip-self.a[18],-.012,.025) + self.age += 1 + return self.a.astype(np.float32) diff --git a/policies/move_plate/gpt61sol-s3/episodes.csv b/policies/move_plate/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..34a4a5ff8cc0e48c9f976259fad6d27907b05513 --- /dev/null +++ b/policies/move_plate/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,1,1360,success,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,1,1356,success,0 +620008,1,1361,success,0 +620009,0,1700,timeout,0 +620010,0,1237,terminated,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,1,1360,success,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,1,1364,success,0 +620022,1,1363,success,0 +620023,1,1376,success,0 +620024,1,1359,success,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,1,1353,success,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,1,1370,success,0 +620032,0,955,terminated,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,1,1371,success,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,1,1339,success,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,1,1347,success,0 +620059,0,1700,timeout,0 +620060,1,1373,success,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,899,terminated,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,1,1367,success,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,1,1369,success,0 +620096,1,1383,success,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt61sol-s3/policy.py b/policies/move_plate/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..60f37693dc4e88222e9a5651c649d27206b07877 --- /dev/null +++ b/policies/move_plate/gpt61sol-s3/policy.py @@ -0,0 +1,38 @@ +"""Deterministic plate transfer with geometric camera alignment.""" +import cv2 +import numpy as np +class Policy: + def reset(self, obs, tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32);self.a[18:]=0 + self.pick_y=.10;self.place_x=.10;self.place_y=-.30 + h=cv2.cvtColor(tools.image('head'),cv2.COLOR_RGB2HSV) + m=((h[:,:,1]<50)&(h[:,:,2]>200)).astype(np.uint8);m[25:]=0;m[:,25:]=0 + n,l,st,cs=cv2.connectedComponentsWithStats(m) + kk=[k for k in range(1,n) if st[k,4]>15] + if kk: + k=max(kk,key=lambda k:st[k,4]);self.pick_y+=float(np.clip((13.3-cs[k,0])/170,-.08,.10)) + m=(h[:,:,0]>8)&(h[:,:,0]<30)&(h[:,:,1]>50)&(h[:,:,2]>60) + m[35:]=False;m[:,:42]=False;yy,xx=np.where(m) + if len(xx)>30: + self.place_y+=float(np.clip((49-np.min(xx))/170,-.10,.10)) + self.place_x+=float(np.clip((23-np.max(yy))/100,-.08,.08)) + def act(self, obs, tools): + t=int(obs['t']);p=obs['low_dim_obs'][18:22];a=self.a.copy();a[:2]=0;a[3]=0;a[4]=-.25;a[7]=.1 + target=None;gain=1.5;speed=.18;tol=.01 + if t<180:target=(-.05,self.pick_y);gain=2;speed=.15;a[4]=0;a[7]=0 + elif t<240:target=(-.05,self.pick_y);a[4]=-.25*min(1,(t-180)/40) + elif t<400:target=(.10,self.pick_y);speed=.09;tol=.008 + elif t<470:a[18]=1 + elif t<570:a[18]=1;a[4]=-.25-.45*min(1,(t-470)/70) + elif t<670:a[18]=1;a[4]=-.70;a[0]=-.12 + elif t<920:a[18]=1;a[4]=-.70;target=(-.08,self.place_y) + elif t<1070:a[18]=1;a[4]=-.70;target=(self.place_x,self.place_y) + elif t<1190:a[18]=1;a[4]=-.70+.66*min(1,(t-1070)/80);target=(self.place_x,self.place_y) + elif t<1290:a[4]=-.04;target=(self.place_x,self.place_y) + else:a[4]=-.04;target=(-.08,self.place_y) + if target is not None: + d=np.array(target)-p[:2];v=np.clip(d*gain,-speed,speed);n=np.linalg.norm(v) + if np.linalg.norm(d)= 355 else 0 + s = t - offset + if t < 75: + a[0] = .15 + if s >= 150: + a[4:11] = [-.85, .5, 0., 1.3, -.3, -.5, 0.] + if s >= 230: + a[18] = 1.0 + if s >= 300: + a[4] = -1.1 + if 400 <= s < 545: + a[1] = -.25 + if s >= 605: + a[4] = -.85 + if s >= 725: + a[18] = 0.0 + return a diff --git a/policies/move_plate/gpt61terra-s2/episodes.csv b/policies/move_plate/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..0be5deb3420deff42e978696034a5c5b69bae3f6 --- /dev/null +++ b/policies/move_plate/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,62,terminated,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt61terra-s2/policy.py b/policies/move_plate/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a73dedea219725fb9ca172a22c61901cf2f59366 --- /dev/null +++ b/policies/move_plate/gpt61terra-s2/policy.py @@ -0,0 +1,56 @@ +"""Deterministic control for transferring a plate between dish racks.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.tick = 0 + self.x0 = float(obs['low_dim_obs'][18]) + self.y0 = float(obs['low_dim_obs'][19]) + + def act(self, obs, tools): + a = self.hold.copy() + a[2] = .74 + a[18] = 0 + a[4:11] = [-1, .4, 0, 1, -.5, 0, 0] + t = self.tick + if self.phase == 0: + if t >= 120: self.phase, self.tick = 1, -1 + elif self.phase == 1: + a[0] = .08 + if t >= 60: self.phase, self.tick = 2, -1 + elif self.phase == 2: + if t >= 30: self.phase, self.tick = 3, -1 + elif self.phase == 3: + a[18] = 1 + if t >= 60: self.phase, self.tick = 4, -1 + elif self.phase == 4: + a[18] = 1 + a[8] = -.5 + .6 * min(t / 100., 1.) + if t >= 100: self.phase, self.tick = 5, -1 + elif self.phase == 5: + a[18] = 1; a[8] = .1 + f = min(t / 160., 1.) + a[4] = -1 - .45*f; a[7] = 1 + .45*f + if t >= 160: self.phase, self.tick = 6, -1 + elif self.phase == 6: + a[18] = 1; a[8] = .1; a[4] = -1.45; a[7] = 1.45 + pos = obs['low_dim_obs'] + a[1] = -.1 + a[3] = np.clip(-2*pos[21], -.2, .2) + dx = (self.x0 + .03) - float(pos[18]) + if abs(dx) > .035: a[0] = np.clip(2*dx, -.12, .12) + if pos[19] < self.y0 - .48: self.phase, self.tick = 7, -1 + elif self.phase == 7: + a[18] = 1; a[8] = .1; a[4] = -1.45; a[7] = 1.45 + if t >= 70: self.phase, self.tick = 8, -1 + elif self.phase == 8: + a[18] = 1; a[8] = .1 + f = min(t/160.,1.) + a[4] = -1.45 + .45*f; a[7] = 1.45 - .45*f + if t >= 160: self.phase, self.tick = 9, -1 + else: + a[8] = .1 + self.tick += 1 + return a diff --git a/policies/move_plate/gpt61terra-s3/episodes.csv b/policies/move_plate/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..42525923f8d1952734258dc0705b41aed1984828 --- /dev/null +++ b/policies/move_plate/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,834,terminated,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,1,811,success,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt61terra-s3/policy.py b/policies/move_plate/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..392b01248dc91ec210b8e29ef64a5cba013dac55 --- /dev/null +++ b/policies/move_plate/gpt61terra-s3/policy.py @@ -0,0 +1,31 @@ +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = obs['t'] + x, y, _, yaw = obs['low_dim_obs'][18:22] + a = self.hold.copy() + a[18] = 0.0 if t < 140 or t >= 760 else 1.0 + a[4:11] = [-0.55, 0, 0, 0.8, 0.3, -0.4, 0.7] + if t >= 210: + a[4] = -0.85 + if t >= 620: + a[2] = 0.69 + if t >= 810: + a[4:11] = [-1.15, 0, 0, 1.4, 0.3, -0.4, 0.7] + if t < 100 or 300 <= t < 620: + target_y = 0.08 if t < 100 else -0.46 + vx = np.clip((0.1 - x) * 1.5, -0.18, 0.18) + vy = np.clip((target_y - y) * 1.5, -0.09, 0.09) + if abs(vx) < 0.06: + vx = 0.0 + if abs(vy) < 0.06: + vy = 0.0 + a[0] = np.cos(yaw) * vx + np.sin(yaw) * vy + a[1] = -np.sin(yaw) * vx + np.cos(yaw) * vy + a[3] = np.clip(-2 * yaw, -0.4, 0.4) + return a diff --git a/policies/move_plate/gpt6sol-s1/episodes.csv b/policies/move_plate/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..5b65e0880f54a7c559a415b9072cd845cbc5ee4a --- /dev/null +++ b/policies/move_plate/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,242,terminated,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,903,terminated,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,247,terminated,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,255,terminated,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,233,terminated,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,1,1170,success,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,240,terminated,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,238,terminated,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,238,terminated,0 +620082,0,236,terminated,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,245,terminated,0 +620087,0,1700,timeout,0 +620088,0,238,terminated,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt6sol-s1/policy.py b/policies/move_plate/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a16a38f4c21f81d5cfb5d722ccbb1f5f19f6f8ee --- /dev/null +++ b/policies/move_plate/gpt6sol-s1/policy.py @@ -0,0 +1,78 @@ +"""Deterministic plate transfer controller for the simulated G1.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.raw = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = int(obs["t"]) + a = self.raw.copy() + s = obs["low_dim_obs"] + x, y, _, yaw = map(float, s[18:22]) + a[:4] = (0.0, 0.0, 0.74, 0.0) + a[4:18] = 0.0 + a[18] = 0.0 + a[19] = 0.6 + if t < 85: + a[0] = 0.15 + a[3] = np.clip(-2.0 * yaw, -0.2, 0.2) + elif t < 170: + a[1] = 0.10 + elif t < 195: + pass + elif t < 315: + a[6] = 0.23 + a[7] = -0.40 + if t >= 255: + a[2] = 0.66 + elif t < 360: + a[6] = 0.23 + a[7] = -0.40 + a[2] = 0.66 + a[18] = 1.0 + elif t < 530: + a[6] = 0.23 + a[7] = -0.40 + a[18] = 1.0 + elif t < 940: + a[6] = 0.23 + a[7] = -0.40 + a[18] = 1.0 + ex, ey = 0.13 - x, -0.50 - y + ux = float(np.clip(1.8 * ex, -0.10, 0.10)) + uy = float(np.clip(1.8 * ey, -0.12, 0.12)) + if abs(ex) < 0.02: + ux = 0.0 + if abs(ey) < 0.02: + uy = 0.0 + a[0] = np.cos(yaw) * ux + np.sin(yaw) * uy + a[1] = -np.sin(yaw) * ux + np.cos(yaw) * uy + a[3] = np.clip(2.0 * (-0.05 - yaw), -0.3, 0.3) + elif t < 980: + a[6] = 0.23 + a[7] = -0.40 + a[18] = 1.0 + elif t < 1040: + a[6] = 0.30 + a[7] = -0.40 + a[18] = 1.0 + elif t < 1120: + a[6] = 0.30 + a[7] = -0.40 + a[2] = 0.62 + a[18] = 1.0 + elif t < 1220: + a[6] = 0.30 + a[7] = -0.40 + a[2] = 0.62 + elif t < 1290: + a[6] = 0.30 + a[7] = -0.20 + a[2] = 0.62 + else: + a[6] = 0.30 + a[2] = 0.62 + return a diff --git a/policies/move_plate/gpt6sol-s2/episodes.csv b/policies/move_plate/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b0a3bd5792118968858197a50fab8fd0cfe06d3a --- /dev/null +++ b/policies/move_plate/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,943,success,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,918,terminated,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1290,terminated,0 +620008,0,1700,timeout,0 +620009,0,1459,terminated,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1247,terminated,0 +620027,0,934,terminated,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,1,948,success,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,905,terminated,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,1,950,success,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,1,953,success,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,1,950,success,0 +620079,0,973,terminated,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,1,921,success,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,1,949,success,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt6sol-s2/policy.py b/policies/move_plate/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..eecdef1d44dd80d4640ba3f7e3958dad8978885a --- /dev/null +++ b/policies/move_plate/gpt6sol-s2/policy.py @@ -0,0 +1,46 @@ +"""Deterministic hand-written plate transfer controller.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.hold[4:18] = 0.0 + self.hold[18:20] = 0.0 + + def act(self, obs, tools): + t = int(obs["t"]) + if t < 100: + tx, ty, height, arm_yaw, grip = 0.10, 0.03, 0.74, 0.0, 0.0 + elif t < 170: + tx, ty, height, arm_yaw, grip = 0.10, 0.03, 0.74, 0.3, 0.0 + elif t < 240: + tx, ty, height, arm_yaw, grip = 0.16, 0.03, 0.74, 0.3, 0.0 + elif t < 310: + tx, ty, height, arm_yaw, grip = 0.16, 0.03, 0.74, 0.3, 1.0 + elif t < 390: + tx, ty, height, arm_yaw, grip = 0.16, 0.03, 0.82, 0.3, 1.0 + elif t < 480: + tx, ty, height, arm_yaw, grip = -0.03, 0.03, 0.82, 0.3, 1.0 + elif t < 670: + tx, ty, height, arm_yaw, grip = -0.03, -0.44, 0.82, 0.3, 1.0 + elif t < 780: + tx, ty, height, arm_yaw, grip = 0.18, -0.44, 0.82, 0.3, 1.0 + elif t < 870: + tx, ty, height, arm_yaw, grip = 0.18, -0.44, 0.68, 0.3, 1.0 + elif t < 900: + tx, ty, height, arm_yaw, grip = 0.18, -0.44, 0.68, 0.3, 0.4 + else: + tx, ty, height, arm_yaw, grip = 0.18, -0.44, 0.68, 0.3, 0.0 + + p = obs["low_dim_obs"] + x, y, yaw = float(p[18]), float(p[19]), float(p[21]) + raw = self.hold.copy() + raw[0] = np.clip(2.0 * (tx - x), -0.2, 0.2) if abs(tx - x) > 0.018 else 0.0 + raw[1] = np.clip(2.0 * (ty - y), -0.18, 0.18) if abs(ty - y) > 0.018 else 0.0 + raw[2] = height + raw[3] = np.clip(-2.0 * yaw, -0.2, 0.2) if abs(yaw) > 0.03 else 0.0 + raw[6] = arm_yaw + raw[18] = grip + return raw diff --git a/policies/move_plate/gpt6sol-s3/episodes.csv b/policies/move_plate/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ca0092a08c77c7da6ac8d091e1543c57c96062f0 --- /dev/null +++ b/policies/move_plate/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,1,1096,success,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,591,terminated,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,628,terminated,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,1,631,success,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,271,terminated,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,1,568,success,0 +620066,0,1700,timeout,0 +620067,1,520,success,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,643,terminated,0 +620089,0,1700,timeout,0 +620090,1,571,success,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/gpt6sol-s3/policy.py b/policies/move_plate/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d7ecdb8ea6902f0849d3e39ee73fd30072fecb6e --- /dev/null +++ b/policies/move_plate/gpt6sol-s3/policy.py @@ -0,0 +1,95 @@ +"""Hand-written control policy for moving a plate between dish racks.""" + +import math +import numpy as np + + +class Policy: + GRASP = np.array([0.0, 0.15, 0.0, 0.0, 0.0, 0.0, 0.2], dtype=np.float32) + CARRY = np.array([-0.4, -0.3, -0.1, 0.0, 0.0, 0.0, 0.2], dtype=np.float32) + PLACE = np.array([0.0, -0.3, -0.1, 0.0, 0.0, 0.0, 0.2], dtype=np.float32) + + def reset(self, obs, tools): + self.phase = 0 + self.phase_steps = 0 + im = np.asarray(tools.image("left_wrist"), dtype=np.int16)[:25] + pale = (im.min(axis=2) > 190) & ((im.max(axis=2) - im.min(axis=2)) < 30) + count = int(pale.sum()) + if count < 5: + shoulder_yaw = 0.4 + center = 6.0 + else: + center = float(np.where(pale)[1].mean()) + if center < 7: + shoulder_yaw = 0.3 + elif center < 22: + shoulder_yaw = 0.2 + elif center <= 34: + shoulder_yaw = 0.0 + else: + shoulder_yaw = -0.1 + self.grasp = self.GRASP.copy() + self.grasp[2] = shoulder_yaw + # A plate farther along the left rack is carried to the corresponding + # slot offset on the right. Camera pixels give the starting offset. + self.target_y = float(np.clip(-0.4 + 0.013 * max(center - 24.0, 0.0), -0.4, -0.25)) + + def _next(self): + self.phase += 1 + self.phase_steps = 0 + + def act(self, obs, tools): + a = np.asarray(tools.hold_action(), dtype=np.float32) + p = obs["low_dim_obs"] + x, y, _, yaw = p[18:22] + self.phase_steps += 1 + + if self.phase == 0: # Walk toward the plate with open fingers. + a[4:11] = self.grasp + a[18] = 0.0 + if x < 0.14 and self.phase_steps < 170: + a[0] = 0.12 + else: + self._next() + elif self.phase == 1: # Close around the rim. + a[4:11] = self.grasp + a[18] = 1.0 + if self.phase_steps >= 35: + self._next() + elif self.phase == 2: # Pull clear of the left rack. + a[4:11] = self.grasp + a[18] = 1.0 + if x > 0.0 and self.phase_steps < 160: + a[0] = -0.12 + else: + self._next() + elif self.phase == 3: # Lift the plate before moving sideways. + a[4:11] = self.CARRY + a[18] = 1.0 + if self.phase_steps >= 45: + self._next() + elif self.phase == 4: # Bring the plate over the right rack. + a[4:11] = self.CARRY + a[18] = 1.0 + ex, ey = -x, self.target_y - y + if (abs(ex) < 0.018 and abs(ey) < 0.018 and abs(yaw) < 0.045) or self.phase_steps >= 230: + self._next() + else: + bx = math.cos(yaw) * ex + math.sin(yaw) * ey + by = -math.sin(yaw) * ex + math.cos(yaw) * ey + for j, err in ((0, bx), (1, by)): + if abs(err) > 0.018: + speed = float(np.clip(1.5 * err, -0.16, 0.16)) + if abs(speed) < 0.075: + speed = math.copysign(0.075, speed) + a[j] = speed + a[3] = float(np.clip(-2.0 * yaw, -0.4, 0.4)) + elif self.phase == 5: # Lower between the posts. + a[4:11] = self.PLACE + a[18] = 1.0 + if self.phase_steps >= 55: + self._next() + else: # Release without disturbing the plate. + a[4:11] = self.PLACE + a[18] = 0.0 + return a diff --git a/policies/move_plate/kimi31pro-s1/episodes.csv b/policies/move_plate/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..37f5ff1be480c21de90bf3f1ffa3344720f53249 --- /dev/null +++ b/policies/move_plate/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,685,terminated,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,761,terminated,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,661,terminated,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/kimi31pro-s1/policy.py b/policies/move_plate/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..53a16dc59e515976f80877ec18672337c6d94a28 --- /dev/null +++ b/policies/move_plate/kimi31pro-s1/policy.py @@ -0,0 +1,169 @@ +"""Deterministic vision-guided control for the plate-transfer task.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.q_start = self.hold[4:11].copy() + + # The same grasp is used after aligning the base with the detected slot. + self.q_pre = np.array([-1.0, 0, 0, 1.0, -0.35, 0.15, 0.0]) + self.q_lift = np.array([-1.5, 0, 0, 1.5, -0.35, 0.15, 0.0]) + self.q_transfer = np.array( + [-0.7513, -0.7977, 0.0794, 0.0018, 0.3477, 0.8120, 0.2466] + ) + self.q_place = np.array( + [-0.500243, -0.707069, 0.453799, 0.000419, + 0.525009, 0.432550, -0.279851] + ) + + self.left_y = self._estimate_left_y(tools.image("head")) + self.target_x = -0.05 + self.target_y = self.left_y + self.phase = 0 + self.phase_step = 0 + + @staticmethod + def _estimate_left_y(image): + """Estimate the plate slot from its tall bright rim in the head view.""" + mask = (np.min(image, axis=2) > 180).astype(np.uint8) + mask[30:] = 0 + mask[:, 45:] = 0 + count, _, stats, centroids = cv2.connectedComponentsWithStats(mask, 8) + rims = [] + for i in range(1, count): + x, y, w, h, area = stats[i] + if y < 6 and 3 <= w <= 20 and h >= 12 and area >= 20: + rims.append((area, float(centroids[i][0]))) + if not rims: + return 0.30 + plate_x = max(rims)[1] + # At the calibrated slot the rim is at x=13.1 and base y=0.32. + return float(np.clip(0.32 - 0.0065 * (plate_x - 13.1), 0.10, 0.40)) + + def _action(self, obs, tools, q=None, grip=None, speed=0.08): + raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + if q is not None: + raw[4:11] = q + if grip is not None: + raw[18] = grip + + state = obs["low_dim_obs"] + x, y, yaw = state[18], state[19], state[21] + ex, ey = self.target_x - x, self.target_y - y + c, s = np.cos(yaw), np.sin(yaw) + vx = c * ex + s * ey + vy = -s * ex + c * ey + active = abs(ex) > 0.012 or abs(ey) > 0.012 + raw[0] = np.clip(1.5 * vx, -speed, speed) if active else 0.0 + raw[1] = np.clip(1.5 * vy, -speed, speed) if active else 0.0 + planar = float(np.hypot(raw[0], raw[1])) + if 0 < planar < 0.06: + raw[0] *= 0.06 / planar + raw[1] *= 0.06 / planar + raw[3] = np.clip(-0.5 * yaw, -0.15, 0.15) + return raw + + def _next(self): + self.phase += 1 + self.phase_step = 0 + + def act(self, obs, tools): + s = self.phase_step + state = obs["low_dim_obs"] + + if self.phase == 0: # Walk to the plate before raising the arm. + raw = self._action(obs, tools) + close = (abs(self.target_x - state[18]) < 0.015 and + abs(self.target_y - state[19]) < 0.015) + if (close and s > 30) or s >= 259: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 1: # Let the base settle. + raw = self._action(obs, tools) + if s >= 29: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 2: # Open-gripper approach. + q = self.q_start + (self.q_pre - self.q_start) * (s + 1) / 85 + raw = self._action(obs, tools, q, 0.0) + if s >= 84: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 3: # Slow pinch. + raw = self._action(obs, tools, self.q_pre, (s + 1) / 100) + if s >= 99: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 4: # Lift clear of the rack. + q = self.q_pre + (self.q_lift - self.q_pre) * (s + 1) / 100 + raw = self._action(obs, tools, q, 1.0) + if s >= 99: + self._next() + self.target_y = -0.58 + else: + self.phase_step += 1 + + elif self.phase == 5: # Simultaneous smooth arm and base transfer. + fraction = min((s + 1) / 120, 1.0) + q = self.q_lift + (self.q_transfer - self.q_lift) * fraction + raw = self._action(obs, tools, q, 1.0, speed=0.18) + close = (abs(self.target_x - state[18]) < 0.018 and + abs(self.target_y - state[19]) < 0.018) + if (s >= 120 and close) or s >= 419: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 6: + raw = self._action(obs, tools, self.q_transfer, 1.0) + if s >= 29: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 7: # Lower into the destination slot. + q = self.q_transfer + (self.q_place - self.q_transfer) * (s + 1) / 100 + raw = self._action(obs, tools, q, 1.0) + if s >= 99: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 8: # Release. + raw = self._action(obs, tools, self.q_place, 0.0) + if s >= 49: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 9: # Keep the plate undisturbed while it settles. + raw = self._action(obs, tools, self.q_place, 0.0) + if s >= 149: + self._next() + else: + self.phase_step += 1 + + elif self.phase == 10: # Retract the open hand. + q = self.q_place + (self.q_transfer - self.q_place) * (s + 1) / 80 + raw = self._action(obs, tools, q, 0.0) + if s >= 79: + self._next() + else: + self.phase_step += 1 + + else: + raw = self._action(obs, tools, self.q_transfer, 0.0) + + return raw diff --git a/policies/move_plate/kimi31pro-s2/episodes.csv b/policies/move_plate/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4545c564a420119f0f19ec3d2d880f38b7022077 --- /dev/null +++ b/policies/move_plate/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,913,terminated,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1005,terminated,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,935,terminated,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,915,terminated,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,913,terminated,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/kimi31pro-s2/policy.py b/policies/move_plate/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..44334cc0fdae681d47e3a5e2e84c86023abde002 --- /dev/null +++ b/policies/move_plate/kimi31pro-s2/policy.py @@ -0,0 +1,145 @@ +"""Hand-written visual/proprioceptive controller for the plate-transfer task.""" + +import cv2 +import numpy as np + + +class Policy: + """Pick up the left-rack plate, carry it right, and stand it in the rack.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + low = np.asarray(obs["low_dim_obs"], dtype=np.float32) + self.x0, self.y0, self.yaw0 = map(float, (low[18], low[19], low[21])) + + # Measure object placements relative to a reference initial head view. + # These are geometric image measurements, not seed identification. + head = np.asarray(tools.image("head"), dtype=np.uint8) + plate_u, rack_u, rack_v = self._scene_references(head) + depth_delta = float(np.clip(0.008 * (16.50 - rack_v), -0.04, 0.09)) + + self.pick_x = self.x0 + 0.19 + depth_delta + self.pick_y = self.y0 - 0.007 - 0.004 * (plate_u - 13.17) + self.pick_y = float(np.clip(self.pick_y, self.y0 - 0.065, self.y0 + 0.065)) + + # Stay a little closer to the table after extraction. This avoids a + # separate forward walk while holding the plate at the destination. + self.hold_x = self.x0 + 0.15 + depth_delta + self.dest_y = self.y0 - 0.267 + 0.003 * (69.78 - rack_u) + self.dest_y = float(np.clip(self.dest_y, self.y0 - 0.34, self.y0 - 0.19)) + + self.pick_q = np.array([-0.35, 0.0, 0.0, 0.0, 0.0, 0.40, 0.70], dtype=np.float32) + self.carry_q = self.pick_q.copy() + self.carry_q[0] = -0.45 + self.place_q = self.pick_q.copy() + self.place_q[0] = -0.14 + self.release_q = self.place_q.copy() + self.release_q[0] = -0.22 + + self.arrival = None + self.dest_x = None + + @staticmethod + def _scene_references(im): + """Return plate center and rack center/depth in image coordinates.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = ((hsv[:, :, 2] > 195) & (hsv[:, :, 1] < 45)).astype(np.uint8) + mask[28:, :] = 0 + mask[:, 45:] = 0 + n, _, stats, centers = cv2.connectedComponentsWithStats(mask, 8) + candidates = [i for i in range(1, n) if stats[i, cv2.CC_STAT_AREA] >= 4] + if candidates: + i = max(candidates, key=lambda j: stats[j, cv2.CC_STAT_AREA]) + plate_u = float(centers[i, 0]) + else: + plate_u = 13.0 + + rgb = im.astype(np.int16) + r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] + wood = (r > g + 8) & (g > b + 4) & (r > 55) & (g > 35) + yy, xx = np.indices(wood.shape) + wood &= (xx > 45) & (yy < 30) + ys, xs = np.nonzero(wood) + if len(xs) >= 20: + rack_u, rack_v = float(xs.mean()), float(ys.mean()) + else: + rack_u, rack_v = 69.78, 16.50 + return plate_u, rack_u, rack_v + + @staticmethod + def _walk_component(error, slow, fast, deadband=0.018): + if abs(error) <= deadband: + return 0.0 + return float(np.copysign(np.clip(1.2 * abs(error), slow, fast), error)) + + def _base_to(self, raw, obs, x, y, slow=0.06, fast=0.11, deadband=0.018): + low = obs["low_dim_obs"] + raw[0] = self._walk_component(float(x - low[18]), slow, fast, deadband) + raw[1] = self._walk_component(float(y - low[19]), slow, fast, deadband) + + def act(self, obs, tools): + t = int(obs["t"]) + low = np.asarray(obs["low_dim_obs"], dtype=np.float32) + raw = self.hold.copy() + raw[0:4] = 0.0 + raw[2] = 0.74 + raw[3] = float(np.clip(-(float(low[21]) - self.yaw0), -0.10, 0.10)) + raw[11:18] = 0.0 + raw[19] = 0.6 + + if t < 70: + raw[4:11] = self.pick_q * ((t + 1) / 70.0) + raw[18] = 0.0 + elif t < 210: + raw[4:11] = self.pick_q + raw[18] = 0.0 + self._base_to(raw, obs, self.pick_x, self.pick_y) + elif t < 240: + raw[4:11] = self.pick_q + raw[18] = 0.0 + elif t < 300: + raw[4:11] = self.pick_q + raw[18] = (t - 239) / 60.0 + elif t < 340: + raw[4:11] = self.pick_q + raw[18] = 1.0 + elif t < 420: + raw[4:11] = self.pick_q + (self.carry_q - self.pick_q) * ((t - 339) / 81.0) + raw[18] = 1.0 + elif t < 500: + raw[4:11] = self.carry_q + raw[18] = 1.0 + self._base_to(raw, obs, self.hold_x, float(low[19]), fast=0.10) + elif t < 560: + raw[4:11] = self.carry_q + raw[18] = 1.0 + elif self.arrival is None: + raw[4:11] = self.carry_q + raw[18] = 1.0 + self._base_to(raw, obs, self.hold_x, self.dest_y, fast=0.12, deadband=0.020) + if abs(float(low[19]) - self.dest_y) <= 0.022: + self.arrival = t + self.dest_x = float(low[18]) + else: + dt = t - self.arrival + if dt <= 30: + q = self.carry_q + raw[18] = 1.0 + elif dt <= 100: + q = self.carry_q + (self.place_q - self.carry_q) * ((dt - 30) / 70.0) + raw[18] = 1.0 + elif dt <= 140: + q = self.place_q + raw[18] = 1.0 + elif dt <= 200: + u = (dt - 140) / 60.0 + q = self.place_q + (self.release_q - self.place_q) * u + raw[18] = 1.0 - u + else: + q = self.release_q + raw[18] = 0.0 + raw[4:11] = q + # Keep the plate over the same slot while lowering and releasing. + self._base_to(raw, obs, self.dest_x, self.dest_y, fast=0.06) + + return np.asarray(raw, dtype=np.float32) diff --git a/policies/move_plate/kimi31pro-s3/episodes.csv b/policies/move_plate/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b3821bae6f5ad9013dc2c2bf1d1b9874025e4c0d --- /dev/null +++ b/policies/move_plate/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1166,terminated,0 +620001,0,1700,timeout,0 +620002,0,1171,terminated,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,0,1700,timeout,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1169,terminated,0 +620014,0,1700,timeout,0 +620015,0,1227,terminated,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1161,terminated,0 +620023,0,1158,terminated,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1194,terminated,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1229,terminated,0 +620044,0,1700,timeout,0 +620045,0,1338,terminated,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1294,terminated,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1457,terminated,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1200,terminated,0 +620061,0,1700,timeout,0 +620062,0,1700,timeout,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,0,834,terminated,0 +620066,0,1203,terminated,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1186,terminated,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1181,terminated,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1476,terminated,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/kimi31pro-s3/policy.py b/policies/move_plate/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c13069f47c07bc1c3f72fb2b4e4dc9da012efbc4 --- /dev/null +++ b/policies/move_plate/kimi31pro-s3/policy.py @@ -0,0 +1,137 @@ +"""Deterministic hand-written controller for the plate-transfer task. + +The controller uses joint-space arm motions and closed-loop planar base +motions. No demonstration files, learned models, or external state are used. +""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "approach" + self.n = 0 + self.arm_from = self.hold[4:11].copy() + self.arm_to = self.arm_from.copy() + self.base_target = None + self.approach = np.array( + [-0.8, 0.3, 0.0, 0.8, -0.5, 0.0, 0.0], dtype=np.float32 + ) + self.carry = self.approach.copy() + self.carry[0] = -0.35 + + def _phase(self, name, raw, arm=None, base=None): + self.phase = name + self.n = 0 + self.arm_from = raw[4:11].copy() + self.arm_to = raw[4:11].copy() if arm is None else np.asarray(arm, dtype=np.float32) + self.base_target = base + + @staticmethod + def _blend(a, b, n, duration=60): + return a + (b - a) * min(1.0, n / duration) + + def _drive(self, raw, obs, target): + p = obs["low_dim_obs"] + ex, ey = target[0] - p[18], target[1] - p[19] + yaw = float(p[21]) + c, s = np.cos(yaw), np.sin(yaw) + vx, vy = c * ex + s * ey, -s * ex + c * ey + raw[0] = np.clip(2.2 * vx, -0.20, 0.20) + raw[1] = np.clip(2.2 * vy, -0.20, 0.20) + for k in (0, 1): + if abs(raw[k]) < 0.005: + raw[k] = 0.0 + elif abs(raw[k]) < 0.06: + raw[k] = np.sign(raw[k]) * 0.06 + raw[3] = np.clip(-1.2 * yaw, -0.25, 0.25) + return ex * ex + ey * ey < 0.00004 and abs(p[40]) + abs(p[41]) < 0.04 + + def act(self, obs, tools): + raw = self.hold.copy() + raw[18:20] = (0.0, 0.6) + self.n += 1 + n = self.n + + if self.phase == "approach": + raw[4:11] = self._blend(self.arm_from, self.approach, n) + if n >= 80: + self._phase("source", raw, self.approach, (0.05, 0.04)) + + elif self.phase in ("source", "target"): + raw[4:11] = self.arm_to + if self.phase == "target": + raw[18] = 1.0 + arrived = self._drive(raw, obs, self.base_target) + limit = 320 if self.phase == "source" else 520 + if arrived or n >= limit: + self._phase(self.phase + "_settle", raw, self.arm_to) + + elif self.phase in ("source_settle", "target_settle"): + raw[4:11] = self.arm_to + if self.phase == "target_settle": + raw[18] = 1.0 + if n >= 30: + if self.phase == "source_settle": + self._phase("close", raw, self.approach) + else: + self._phase("lower", raw, self.approach) + + elif self.phase == "close": + raw[4:11] = self.approach + raw[18] = 1.0 + if n >= 50: + self._phase("lift", raw, self.carry) + raw[18] = 1.0 + + elif self.phase == "lift": + raw[18] = 1.0 + raw[4:11] = self._blend(self.arm_from, self.carry, n) + if n >= 80: + self._phase("target", raw, self.carry, (0.15, -0.90)) + raw[18] = 1.0 + + elif self.phase == "lower": + raw[18] = 1.0 + raw[4:11] = self._blend(self.arm_from, self.approach, n) + if n >= 80: + self._phase("lower_hold", raw, self.approach) + raw[18] = 1.0 + + elif self.phase == "lower_hold": + raw[18] = 1.0 + raw[4:11] = self.approach + if n >= 30: + self._phase("squat", raw, self.approach) + raw[18] = 1.0 + + elif self.phase == "squat": + raw[18] = 1.0 + raw[4:11] = self.approach + raw[2] = 0.74 + (0.68 - 0.74) * min(1.0, n / 60.0) + if n >= 90: + self._phase("release", raw, self.approach) + raw[2] = 0.68 + raw[18] = 1.0 + + elif self.phase == "release": + raw[2] = 0.68 + raw[4:11] = self.approach + raw[18] = 0.0 + if n >= 90: + self._phase("retreat", raw, self.carry) + raw[2] = 0.68 + + elif self.phase == "retreat": + raw[4:11] = self._blend(self.arm_from, self.carry, n, 50) + raw[2] = 0.68 + (0.74 - 0.68) * min(1.0, n / 60.0) + if n >= 110: + self._phase("hold", raw, self.carry) + raw[2] = 0.74 + + else: + raw[4:11] = self.carry + raw[2] = 0.74 + + return raw diff --git a/policies/move_plate/opus-s1/episodes.csv b/policies/move_plate/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..fa9fa193ad53c0c9e641f1986c16317b6b7d5f3d --- /dev/null +++ b/policies/move_plate/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,1,1242,success,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,1,1102,success,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,0,1700,timeout,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,1,1126,success,0 +620025,0,1700,timeout,0 +620026,0,1700,timeout,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,0,1700,timeout,0 +620032,0,1700,timeout,0 +620033,1,1146,success,0 +620034,0,1700,timeout,0 +620035,1,1265,success,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,0,1700,timeout,0 +620041,0,1700,timeout,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,1,1260,success,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,1,1164,success,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,1,1102,success,0 +620061,1,1190,success,0 +620062,1,1196,success,0 +620063,0,1700,timeout,0 +620064,1,1100,success,0 +620065,0,1700,timeout,0 +620066,1,1057,success,0 +620067,0,1700,timeout,0 +620068,1,1166,success,0 +620069,0,1700,timeout,0 +620070,1,1234,success,0 +620071,1,1097,success,0 +620072,1,959,success,0 +620073,0,1700,timeout,0 +620074,1,1236,success,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,1,1212,success,0 +620086,1,1168,success,0 +620087,0,1700,timeout,0 +620088,0,1700,timeout,0 +620089,0,1700,timeout,0 +620090,1,1267,success,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,1,1140,success,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/opus-s1/policy.py b/policies/move_plate/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1cc8ff5c87c2b6985c755cbed4664bba2cc3fe --- /dev/null +++ b/policies/move_plate/opus-s1/policy.py @@ -0,0 +1,648 @@ +"""Move the plate from the left dish rack to the right dish rack (Unitree G1). + +Hand-written pipeline: + 1. look at the scene with the head camera (calibrated pinhole model, fixed + on the torso) and locate the racks on the counter plane; + 2. walk next to the left rack, fit a disk model of the plate to its + silhouette (plates are the only zero-saturation objects above the counter); + 3. grasp the top rim of the plate with the left gripper (fingers horizontal, + pointing forward), lift it; + 4. walk to the right rack, locate its rails and pegs, lower the plate into + a slot between two pegs, release and retract. +Arm targets come from a numerical IK on the G1 arm kinematics (URDF values). +""" + +import cv2 +import numpy as np +from scipy import ndimage +from scipy.optimize import least_squares, minimize + +# ---------------------------------------------------------------------------- +# kinematics + + +def _rpy(r, p, y): + cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y) + Rx = np.array([[1, 0, 0], [0, cr, -sr], [0, sr, cr]]) + Ry = np.array([[cp, 0, sp], [0, 1, 0], [-sp, 0, cp]]) + Rz = np.array([[cy, -sy, 0], [sy, cy, 0], [0, 0, 1]]) + return Rz @ Ry @ Rx + + +def _chain(s): + return [ + ((0.0039563, s * 0.10022, 0.23778), (s * 0.27931, 5.4949e-05, -s * 0.00019159), 1), + ((0, s * 0.038, -0.013831), (-s * 0.27925, 0, 0), 0), + ((0, s * 0.00624, -0.1032), (0, 0, 0), 2), + ((0.015783, 0, -0.080518), (0, 0, 0), 1), + ((0.100, s * 0.00188791, -0.010), (0, 0, 0), 0), + ((0.038, 0, 0), (0, 0, 0), 1), + ((0.046, 0, 0), (0, 0, 0), 2), + ] + + +CHAIN = {"L": _chain(1.0), "R": _chain(-1.0)} +_FIXED = {k: [(_rpy(*r), np.array(p), ax) for p, r, ax in v] for k, v in CHAIN.items()} +Q_LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +Q_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +TORSO_IN_PELVIS = np.array([-0.0039635, 0.0, 0.044]) +GRIP_OFF = np.array([0.09, 0.0, 0.0]) # pinch centre in the wrist-yaw frame +GRASP_DZ = 0.03 # how far below the rim top the grasp point goes +LIFT = 0.25 # lift of the grasp point above the grasp height (plate clears the pegs) +PLACE_DZ = 0.01 # release height relative to the grasp height +IK_STEP = 0.05 # max joint change per IK update while tracking (rad) + + +def _axis_rot(ax, q): + c, s = np.cos(q), np.sin(q) + if ax == 0: + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + if ax == 1: + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def fk(q, side="L", off=GRIP_OFF): + R = np.eye(3) + p = np.zeros(3) + for (Rf, pf, ax), qi in zip(_FIXED[side], q): + p = p + R @ pf + R = R @ Rf @ _axis_rot(ax, qi) + return p + R @ off, R + + +def limits(side): + if side == "L": + return Q_LO, Q_HI + lo, hi = Q_LO.copy(), Q_HI.copy() + for j in (1, 2, 4, 6): + lo[j], hi[j] = -Q_HI[j], -Q_LO[j] + return lo, hi + + +# Nominal arm posture for grasping/carrying: upper arm horizontal to the side, +# forearm pointing forward, wrist rolled so the fingers open horizontally. +Q_NOM_L = np.array([-0.58, 1.47, -0.34, 0.07, -1.68, 1.0, 0.23]) +Q_NOM_R = Q_NOM_L * np.array([1, -1, -1, 1, -1, 1, -1]) +GRASP_PITCH = 0.8 # fingers point forward and down + + +def ik(p, R, side, q0, wrot=0.3, reg=0.03, off=GRIP_OFF): + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-4, hi - 1e-4) + qn = Q_NOM_L if side == "L" else Q_NOM_R + + def res(q): + P, Rq = fk(q, side, off) + return np.concatenate([P - p, wrot * (Rq - R).ravel(), reg * (q - qn)]) + + s = least_squares(res, q0, bounds=(lo, hi), xtol=1e-6, ftol=1e-6) + P, _ = fk(s.x, side, off) + return s.x, float(np.linalg.norm(P - p)) + + +IK_SEEDS_L = [ + np.array([-0.94, 1.2, -0.77, -0.78, -1.58, 0.18, 1.29]), + np.array([-1.25, 0.86, -0.39, -0.18, -1.6, 0.77, 1.07]), + np.array([-1.13, 0.92, -0.25, -0.56, -1.89, 0.77, 1.42]), + np.array([-0.8, 0.3, 0.0, 0.5, 0.0, 0.0, 0.0]), + np.array([-1.5, 0.3, 0.0, 1.0, 0.0, 0.0, 0.0]), +] + + +def solve_ik(p, R, side, qcur): + """IK from the current configuration and from the nominal posture.""" + best = None + seeds = [qcur, Q_NOM_L if side == "L" else Q_NOM_R] + for k, q0 in enumerate(seeds): + q, err = ik(p, R, side, q0) + _, Rq = fk(q, side) + cost = err + 0.05 * float(np.linalg.norm(Rq - R)) + if best is None or cost < best[0] - 1e-4: + best = (cost, q, err) + if k == 0 and err < 0.004 and np.linalg.norm(Rq - R) < 0.1: + break + return best[1], best[2] + + +HAND_NOM = fk(Q_NOM_L, "L")[0][:2] + TORSO_IN_PELVIS[:2] # pinch point of Q_NOM_L rel. to pelvis + + +def hand_R(yaw, roll=0.0): + """Hand orientation (torso frame): heading yaw, fingers pitched down by + GRASP_PITCH, the finger plane tilted by roll about the heading axis.""" + return _rpy(0, 0, wrap(yaw)) @ _rpy(roll, 0, 0) @ _rpy(0, GRASP_PITCH, 0) + + +# ---------------------------------------------------------------------------- +# head camera (fixed on the torso): pinhole, 84x84 + +# z lowered by 0.11 after hand-eye checks with a grasped plate +CAM_POS = np.array([0.0154, -0.0002, 0.3968]) # torso frame +CAM_R = _rpy(0.0106, 1.0185, -0.0089) +CAM_F = 84.76 +Z_COUNTER = 0.706 +Z_RAIL = 0.716 + + +def cam_pose(pel): + Ry = _rpy(0, 0, pel[3]) + o = np.array(pel[:3]) + Ry @ (TORSO_IN_PELVIS + CAM_POS) + return o, Ry @ CAM_R + + +def world_to_pix(P, pel): + o, R = cam_pose(pel) + d = (np.atleast_2d(P) - o) @ R + return np.stack([42 - CAM_F * d[:, 1] / d[:, 0], 42 - CAM_F * d[:, 2] / d[:, 0]], 1) + + +def pix_to_plane(u, v, pel, z): + o, R = cam_pose(pel) + u = np.atleast_1d(np.asarray(u, float)) + v = np.atleast_1d(np.asarray(v, float)) + d = np.stack([np.ones_like(u), -(u - 42) / CAM_F, -(v - 42) / CAM_F], 1) @ R.T + t = (z - o[2]) / d[:, 2] + return o + t[:, None] * d + + +# ---------------------------------------------------------------------------- +# perception + + +def brown_mask(im): + g = im.astype(int) + r, gg, b = g[..., 0], g[..., 1], g[..., 2] + return (r - b > 35) & (r > 90) & (r > gg) + + +def plate_mask(im, vmax=60): + g = im.astype(int) + sat = g.max(-1) - g.min(-1) + m = (sat <= 3) & (g.min(-1) > 60) + m[vmax:] = False + lab, n = ndimage.label(m) + if n == 0: + return m + sizes = ndimage.sum(m, lab, range(1, n + 1)) + return lab == (np.argmax(sizes) + 1) + + +PLATE_R = 0.115 +PEG_PITCH = 0.04 + + +def disk_pts(p, n=48): + xc, yp, zc, psi, lean = p + t = np.linspace(0, 2 * np.pi, n, endpoint=False) + a = np.array([np.cos(psi), np.sin(psi), 0.0]) + nrm = np.array([-np.sin(psi), np.cos(psi), 0.0]) + b = np.cos(lean) * np.array([0, 0, 1.0]) + np.sin(lean) * nrm + return np.array([xc, yp, zc]) + PLATE_R * (np.cos(t)[:, None] * a + np.sin(t)[:, None] * b) + + +def render_disk(p, pel): + uv = world_to_pix(disk_pts(p), pel) + m = np.zeros((84, 84), np.uint8) + cv2.fillPoly(m, [np.round(uv * 8).astype(np.int32)], 1, shift=3) + return m.astype(bool) + + +PLATE_ZC = 0.826 + + +def fit_plate(mask, pel, p0): + """Fit (xc, y, yaw, lean) of the plate disk; its centre height is fixed.""" + def cost(x): + r = render_disk([x[0], x[1], PLATE_ZC, x[2], x[3]], pel) + return 1 - (r & mask).sum() / max((r | mask).sum(), 1) + + x0 = np.array(p0, float) + fun = None + for scale in (0.03, 0.01, 0.004): + simplex = np.vstack([x0] + [x0 + scale * np.eye(4)[k] for k in range(4)]) + s = minimize(cost, x0, method="Nelder-Mead", + options=dict(initial_simplex=simplex, xatol=1e-4, fatol=1e-5, maxiter=800)) + x0, fun = s.x, s.fun + return x0, fun + + +def rack_points(im, pel, side): + m = brown_mask(im) + vs, us = np.nonzero(m) + if len(us) == 0: + return np.zeros((0, 3)) + P = pix_to_plane(us, vs, pel, Z_RAIL) + keep = (P[:, 0] > 0.3) & (P[:, 0] < 0.8) + keep &= (P[:, 1] > 0.0) if side == "L" else (P[:, 1] < 0.0) + return P[keep] + + +def rack_pose(P): + """Fit rack yaw and front/back rail lines to projected brown points.""" + best = None + for th in np.arange(-0.4, 0.401, 0.01): + c, s = np.cos(th), np.sin(th) + xr = c * P[:, 0] + s * P[:, 1] + h, _ = np.histogram(xr, bins=np.arange(0.2, 0.9, 0.006)) + score = float((h.astype(float) ** 2).sum()) + if best is None or score > best[0]: + best = (score, th) + th = best[1] + for th2 in np.arange(th - 0.01, th + 0.0101, 0.002): + c, s = np.cos(th2), np.sin(th2) + xr = c * P[:, 0] + s * P[:, 1] + h, _ = np.histogram(xr, bins=np.arange(0.2, 0.9, 0.006)) + score = float((h.astype(float) ** 2).sum()) + if score > best[0]: + best = (score, th2) + th = best[1] + c, s = np.cos(th), np.sin(th) + xr = c * P[:, 0] + s * P[:, 1] + yr = -s * P[:, 0] + c * P[:, 1] + bins = np.arange(0.2, 0.9, 0.004) + h, e = np.histogram(xr, bins=bins) + h = ndimage.uniform_filter1d(h.astype(float), 3) + i1 = int(np.argmax(h)) + x1 = e[i1] + 0.002 + h2 = h.copy() + h2[max(0, i1 - 15):i1 + 16] = 0 + i2 = int(np.argmax(h2)) + x2 = e[i2] + 0.002 + xf, xb = min(x1, x2), max(x1, x2) + near = np.abs(xr - xf) < 0.012 + if near.sum() < 5: + near = np.abs(xr - xf) < 0.03 + y0, y1 = np.percentile(yr[near], [2, 98]) + return dict(yaw=th, xf=xf, xb=xb, y0=y0, y1=y1) + + +def rack_to_world(rp, xr, yr): + c, s = np.cos(rp["yaw"]), np.sin(rp["yaw"]) + return np.array([c * xr - s * yr, s * xr + c * yr]) + + +def peg_positions(im, pel, rp): + """Positions (rack-frame y) of the pegs standing on the front and back rails.""" + g = im.astype(int) + r, gg, b = g[..., 0], g[..., 1], g[..., 2] + m = (r - b > 20) & (r < 160) & (r > gg) & (gg > b) + vs, us = np.nonzero(m) + if len(us) == 0: + return [] + P = pix_to_plane(us, vs, pel, Z_RAIL + 0.04) + c, s = np.cos(rp["yaw"]), np.sin(rp["yaw"]) + xr = c * P[:, 0] + s * P[:, 1] + yr = -s * P[:, 0] + c * P[:, 1] + out = [] + for rail in (rp["xf"], rp["xb"]): + sel = (xr > rail - 0.03) & (xr < rail + 0.05) & (yr > rp["y0"] - 0.01) & (yr < rp["y1"] + 0.01) + bins = np.arange(rp["y0"] - 0.02, rp["y1"] + 0.02, 0.004) + h, e = np.histogram(yr[sel], bins=bins) + h = ndimage.uniform_filter1d(h.astype(float), 3) + peaks = [] + order = np.argsort(-h) + for i in order: + if h[i] < max(2.0, 0.25 * h.max()): + break + yc = e[i] + 0.002 + if all(abs(yc - p) > 0.025 for p in peaks): + peaks.append(yc) + out.append(sorted(peaks)) + return out + + +# ---------------------------------------------------------------------------- +# policy + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +TUCK_L = np.array([0.1, 0.15, 0.0, 1.3, 0.0, 0.0, 0.0]) +MIRROR = np.array([1, -1, -1, 1, -1, 1, -1]) +TUCK_R = TUCK_L * MIRROR + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + debug = False + + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.cur = np.asarray(tools.hold_action(), dtype=np.float64).copy() + self.log = [] + self.snaps = [] + self.gen = self.script() + + # -- helpers -------------------------------------------------------------- + def pel(self): + lo = self.obs["low_dim_obs"] + return np.array([lo[18], lo[19], lo[20], lo[21]], float) + + def qarm(self, side): + lo = self.obs["low_dim_obs"] + return np.array(lo[0:7] if side == "L" else lo[9:16], float) + + def note(self, *a): + if self.debug: + self.log.append((int(self.obs["t"]),) + a) + + def snap(self, name): + if self.debug: + self.snaps.append((name, int(self.obs["t"]), self.tools.image("head"), + self.tools.image("left_wrist"), self.tools.image("right_wrist"))) + + def act_hold(self, n): + for _ in range(n): + a = self.cur.copy() + a[0] = a[1] = a[3] = 0.0 + yield a + + def world_to_torso(self, P, pel=None): + pel = self.pel() if pel is None else pel + Ry = _rpy(0, 0, pel[3]) + return Ry.T @ (np.asarray(P, float) - pel[:3]) - TORSO_IN_PELVIS + + def walk(self, x, y, yaw, tol=0.015, ytol=0.02, maxn=300, vmax=0.4, settle=30): + for _ in range(maxn): + pel = self.pel() + ex, ey = x - pel[0], y - pel[1] + c, s = np.cos(pel[3]), np.sin(pel[3]) + bx, by = c * ex + s * ey, -s * ex + c * ey + eyaw = wrap(yaw - pel[3]) + dist = np.hypot(bx, by) + if dist < tol and abs(eyaw) < ytol: + break + vx, vy = 2.0 * bx, 2.0 * by + sp = np.hypot(vx, vy) + if sp > vmax: + vx, vy = vx / sp * vmax, vy / sp * vmax + if dist < tol: + vx = vy = 0.0 + elif np.hypot(vx, vy) < 0.07: + sp = np.hypot(vx, vy) + vx, vy = vx / sp * 0.07, vy / sp * 0.07 + wz = float(np.clip(1.5 * eyaw, -0.4, 0.4)) + if abs(eyaw) < ytol: + wz = 0.0 + a = self.cur.copy() + a[0], a[1], a[3] = vx, vy, wz + yield a + yield from self.act_hold(settle) + self.note("walk_done", [x, y, yaw], self.pel().round(3).tolist()) + + def arm_move(self, side, q, n, grip=None): + sl = slice(4, 11) if side == "L" else slice(11, 18) + gi = 18 if side == "L" else 19 + q0 = self.cur[sl].copy() + g0 = self.cur[gi] + for i in range(n): + s = (i + 1) / n + s = 0.5 - 0.5 * np.cos(np.pi * s) + self.cur[sl] = q0 + s * (q - q0) + if grip is not None: + self.cur[gi] = g0 + s * (grip - g0) + a = self.cur.copy() + a[0] = a[1] = a[3] = 0.0 + yield a + + def hand_to(self, side, Pw, yaw_w, n, grip=None, sag=0.02, hold=10, roll_w=0.0): + """Move the grasp point along a straight world-frame line (IK re-solved + against the measured pelvis pose, so base drift is compensated).""" + sl = slice(4, 11) if side == "L" else slice(11, 18) + gi = 18 if side == "L" else 19 + Pw = np.asarray(Pw, float) + if getattr(self, "hand_w", None) is None or self.hand_side != side: + pel = self.pel() + p, _ = fk(self.cur[sl], side) + Ry = _rpy(0, 0, pel[3]) + self.hand_w = pel[:3] + Ry @ (p + TORSO_IN_PELVIS - np.array([0, 0, sag])) + self.hand_side = side + P0 = self.hand_w.copy() + g0 = self.cur[gi] + q_start = self.cur[sl].copy() + pel = self.pel() + p = self.world_to_torso(Pw, pel) + p[2] += sag + q_goal, err = solve_ik(p, hand_R(yaw_w - pel[3], roll_w), side, q_start) + joint_mode = np.abs(q_goal - q_start).max() > 0.6 + for i in range(n + hold): + s = min(1.0, (i + 1) / n) + s = 0.5 - 0.5 * np.cos(np.pi * s) + Pt = P0 + s * (Pw - P0) + if joint_mode and i < n: + self.cur[sl] = q_start + s * (q_goal - q_start) + elif i % 2 == 0 or i == n - 1: + pel = self.pel() + p = self.world_to_torso(Pw if joint_mode else Pt, pel) + p[2] += sag + R = hand_R(yaw_w - pel[3], roll_w) + q, err = ik(p, R, side, self.cur[sl]) + self.cur[sl] += np.clip(q - self.cur[sl], -2 * IK_STEP, 2 * IK_STEP) + if grip is not None: + self.cur[gi] = g0 + s * (grip - g0) + a = self.cur.copy() + a[0] = a[1] = a[3] = 0.0 + yield a + self.hand_w = Pw.copy() + self.note("hand_to", side, np.round(Pw, 3).tolist(), round(err, 4)) + + # -- the task ------------------------------------------------------------- + def script(self): + # tuck arms so they clear the counter while walking + self.cur[4:11] = TUCK_L + self.cur[11:18] = TUCK_R + yield from self.act_hold(1) + pel0 = self.pel() + im0 = self.tools.image("head") + self.snap("start") + PL = rack_points(im0, pel0, "L") + PR = rack_points(im0, pel0, "R") + yl = float(np.median(PL[:, 1])) if len(PL) > 20 else 0.25 + rp0 = rack_pose(PR) if len(PR) > 30 else None + if rp0 is not None: + _, cy = rack_to_world(rp0, (rp0["xf"] + rp0["xb"]) / 2, (rp0["y0"] + rp0["y1"]) / 2) + ryaw0 = rp0["yaw"] + else: + cy, ryaw0 = -0.23, 0.0 + self.note("rough", yl, cy) + + # --- look at the right rack from straight in front of it: rails and pegs + yield from self.walk(0.17, cy, ryaw0) + pel = self.pel() + im = self.tools.image("head") + self.snap("rack_view") + PR2 = rack_points(im, pel, "R") + rp = rack_pose(PR2) if len(PR2) > 30 else rp0 + if rp is None: + rp = dict(yaw=0.0, xf=0.41, xb=0.51, y0=-0.35, y1=-0.11) + pegs = peg_positions(im, pel, rp) + slot = self.choose_slot(pegs, (rp["y0"] + rp["y1"]) / 2) + self.note("rackR", {k: round(float(v), 3) for k, v in rp.items()}, + [np.round(p, 3).tolist() for p in pegs], round(slot, 3)) + B = rack_to_world(rp, (rp["xf"] + rp["xb"]) / 2, slot) + ryaw = rp["yaw"] + + # --- view the plate from its right side, fit the disk, grasp the rim; + # one retry if the fingers close on nothing + view_y = yl - 0.12 + for attempt in range(2): + plate, cost = None, 1.0 + for look in range(2): + yield from self.walk(0.17, view_y, 0.0) + pel = self.pel() + im = self.tools.image("head") + self.snap("plate_view") + mask = plate_mask(im) + y_guess = pel[1] + 0.1 + if mask.sum() > 15: + vs, us = np.nonzero(mask) + y_guess = float(pix_to_plane(us.mean(), vs.mean(), pel, PLATE_ZC)[0, 1]) + best = None + for dy in (-0.03, 0.0, 0.03): + pp, c = fit_plate(mask, pel, [0.51, y_guess + dy, 0.0, 0.1]) + if best is None or c < best[1]: + best = (pp, c) + plate, cost = best + self.note("plate_fit", look, np.round(plate, 3).tolist(), round(cost, 3)) + off = plate[1] - pel[1] + if cost < 0.2 and 0.07 < off < 0.13 and not mask[:, :2].any(): + break + view_y = plate[1] - 0.1 if cost < 0.5 else view_y - 0.05 + plate = np.array([plate[0], plate[1], PLATE_ZC, plate[2], plate[3]]) + xc, yp, zc, psi, lean = plate + top = np.array([xc, yp, zc]) + PLATE_R * (np.cos(lean) * np.array([0, 0, 1.0]) + + np.sin(lean) * np.array([-np.sin(psi), np.cos(psi), 0])) + self.plate = plate + + yield from self.walk(top[0] - HAND_NOM[0], top[1] - HAND_NOM[1], psi) + g = top.copy() + self.hand_w = None + rl = -lean # match the plate's lean so the pads close flat on it + yield from self.hand_to("L", g + np.array([-0.2, 0.03, 0.10]), psi, 50, grip=0.0, roll_w=rl) + yield from self.hand_to("L", g + np.array([-0.05, 0, 0.05]), psi, 35, grip=0.0, roll_w=rl) + self.snap("pregrasp") + yield from self.hand_to("L", g + np.array([0.0, 0, -GRASP_DZ]), psi, 35, grip=0.0, roll_w=rl) + yield from self.act_hold(10) + self.snap("grasp") + for k in range(20): + self.cur[18] = min(1.0, (k + 1) / 15) + yield from self.act_hold(1) + yield from self.act_hold(10) + fingers = self.obs["low_dim_obs"][7:9] + self.note("grip", attempt, fingers.round(4).tolist()) + self.snap("closed") + if max(fingers) > -0.0185 or attempt == 1: # a miss closes both fingers fully + break + # missed: open, back off, look again + yield from self.hand_to("L", g + np.array([0.0, 0, -GRASP_DZ]), psi, 15, grip=0.0, roll_w=rl) + yield from self.hand_to("L", g + np.array([-0.2, 0.03, 0.10]), psi, 40, grip=0.0, roll_w=rl) + self.cur[4:11] = TUCK_L + yield from self.act_hold(30) + view_y = yp - 0.1 + zg = g[2] - GRASP_DZ + yield from self.hand_to("L", np.array([g[0], g[1], zg + LIFT]), psi, 50, sag=0.03, roll_w=rl) + # straighten the plate: the pads hold it rigidly, so it follows the hand + yield from self.hand_to("L", np.array([g[0], g[1] - PLATE_R * np.sin(lean), zg + LIFT]), psi, 30, sag=0.03) + self.snap("lifted") + + # --- carry: walk sideways until the hand is over the slot + c, s = np.cos(ryaw), np.sin(ryaw) + hx, hy = c * HAND_NOM[0] - s * HAND_NOM[1], s * HAND_NOM[0] + c * HAND_NOM[1] + yield from self.walk(B[0] - hx, B[1] - hy, ryaw, vmax=0.2) + self.note("grip_after_walk", self.obs["low_dim_obs"][7:9].round(4).tolist()) + self.snap("carried") + + # --- lower into the slot and release + self.hand_w = None + yield from self.insert(B, zg, ryaw) + self.snap("lowered") + for k in range(25): + self.cur[18] = max(0.0, 1.0 - (k + 1) / 20) + yield from self.act_hold(1) + yield from self.act_hold(10) + pel = self.pel() + ph, _ = fk(self.cur[4:11], "L") + self.hand_w = pel[:3] + _rpy(0, 0, pel[3]) @ (ph + TORSO_IN_PELVIS - np.array([0, 0, 0.03])) + self.snap("released") + yield from self.hand_to("L", np.array([B[0] - 0.05, B[1], zg + 0.12]), ryaw, 40, grip=0.0, sag=0.03) + self.snap("done") + while True: + yield from self.act_hold(1) + + def insert(self, B, zg, ryaw): + """Lower the plate into the slot; if it lands on a peg (hand stops going + down, or the plate twists in the fingers) lift and retry shifted sideways.""" + c, s = np.cos(ryaw), np.sin(ryaw) + for k, dy in enumerate((0.0, 0.016, -0.016)): + Pk = np.array([B[0] - s * dy, B[1] + c * dy]) + yield from self.hand_to("L", np.array([Pk[0], Pk[1], zg + 0.14]), ryaw, 25, sag=0.03, hold=8) + if k == 0: + self.snap("over_slot") + f0 = float(self.obs["low_dim_obs"][7:9].mean()) + bad = 0 + lag0 = 0.0 + n = 70 + for i in range(n): + z = zg + 0.14 + (i + 1) / n * (PLACE_DZ - 0.14) + if i % 2 == 0: + pel = self.pel() + p = self.world_to_torso(np.array([Pk[0], Pk[1], z]), pel) + p[2] += 0.03 + q, _ = ik(p, hand_R(ryaw - pel[3]), "L", self.cur[4:11]) + self.cur[4:11] += np.clip(q - self.cur[4:11], -IK_STEP, IK_STEP) + a = self.cur.copy() + a[0] = a[1] = a[3] = 0.0 + yield a + lo = self.obs["low_dim_obs"] + pel = self.pel() + pa, _ = fk(np.asarray(lo[0:7], float), "L") + za = pel[2] + (pa + TORSO_IN_PELVIS)[2] + df = float(lo[7:9].mean()) - f0 + lag = za - z + if i == 8: + lag0 = lag + if i > 10 and z <= zg + 0.05 and lag - lag0 > 0.012: + break # the plate stands on the rack: stop pushing + if (lag > 0.025 or df > 0.002) and i > 5 and z > zg + 0.04: + bad += 1 + else: + bad = 0 + if bad >= 3: + break + self.note("insert", k, round(dy, 3), i, bad, round(float(za - z), 3), round(float(lag0), 3), round(df, 4)) + self.hand_w = np.array([Pk[0], Pk[1], z]) + if bad < 3: + yield from self.act_hold(15) + return + yield from self.act_hold(10) + + @staticmethod + def choose_slot(pegs, ymid): + """Slot next to the middle peg. The rails carry 7 pegs 4 cm apart with the + middle one at the rack centre; the detected pegs fix the grid phase.""" + dets = np.array([p for pl in pegs for p in pl], float) + centre = ymid + if len(dets) >= 3: + best = None + for ph in np.arange(-0.02, 0.02, 0.001): + grid = ymid + ph + PEG_PITCH * np.arange(-3, 4) + d = np.abs(dets[:, None] - grid[None, :]).min(1) + score = float(np.exp(-(d / 0.006) ** 2).sum()) - 2.0 * abs(ph) + if best is None or score > best[0]: + best = (score, ph) + centre = ymid + best[1] + return float(centre + PEG_PITCH / 2) + + def act(self, obs, tools): + self.obs = obs + try: + a = next(self.gen) + except StopIteration: + a = self.cur.copy() + a[0] = a[1] = a[3] = 0.0 + return np.asarray(a, dtype=np.float32) diff --git a/policies/move_plate/opus-s2/episodes.csv b/policies/move_plate/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..14d58ede66a55d056fa55bbea5e83babf7b12eda --- /dev/null +++ b/policies/move_plate/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1700,timeout,0 +620001,0,1700,timeout,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,1,959,success,0 +620007,1,990,success,0 +620008,0,1700,timeout,0 +620009,0,1700,timeout,0 +620010,0,771,terminated,0 +620011,1,1060,success,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,796,terminated,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,1,1086,success,0 +620021,0,1183,terminated,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,1700,timeout,0 +620025,0,1700,timeout,0 +620026,1,944,success,0 +620027,0,1700,timeout,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,1,984,success,0 +620032,0,1700,timeout,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,0,1700,timeout,0 +620038,0,1700,timeout,0 +620039,0,1700,timeout,0 +620040,1,1072,success,0 +620041,0,1700,timeout,0 +620042,1,1120,success,0 +620043,0,1700,timeout,0 +620044,0,1700,timeout,0 +620045,1,1036,success,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1700,timeout,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,0,1700,timeout,0 +620052,0,1700,timeout,0 +620053,0,1700,timeout,0 +620054,0,1700,timeout,0 +620055,0,1700,timeout,0 +620056,0,1700,timeout,0 +620057,1,1121,success,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,1700,timeout,0 +620062,1,1177,success,0 +620063,0,1700,timeout,0 +620064,0,1700,timeout,0 +620065,1,1056,success,0 +620066,1,884,success,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,0,1700,timeout,0 +620070,0,1700,timeout,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1700,timeout,0 +620074,0,1700,timeout,0 +620075,0,1700,timeout,0 +620076,0,1700,timeout,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,0,1700,timeout,0 +620083,0,1700,timeout,0 +620084,0,1700,timeout,0 +620085,1,1075,success,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,1,962,success,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,0,1700,timeout,0 diff --git a/policies/move_plate/opus-s2/policy.py b/policies/move_plate/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..66ebe212f878a243854023d6f45a303f851b8b48 --- /dev/null +++ b/policies/move_plate/opus-s2/policy.py @@ -0,0 +1,532 @@ +"""Scripted G1 policy: take the plate from the left dish rack, stand it in the right rack. + +Hand-written control, no learned components: + * analytic G1 arm kinematics + numeric IK (scipy least squares), + * base position / yaw feedback from the pelvis pose, + * a pinhole model of the head camera (calibrated by hand from gripper + positions) to measure where the racks are in the first frame, + * colour / brightness features in the left wrist camera for visual servoing + (plate rim before the grasp, peg tips of the target rack before release). +Constants were tuned by running episodes on the development seeds. +""" + +import cv2 # noqa: F401 +import numpy as np +from scipy.ndimage import center_of_mass, label +from scipy.optimize import least_squares + + +# ---------------------------------------------------------------------------- +# Kinematics (G1 arm, pelvis frame: x forward, y left, z up) +# ---------------------------------------------------------------------------- +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +_AX = {"x": _rx, "y": _ry, "z": _rz} +_TORSO = np.array([-0.0039635, 0, 0.044]) +TOOL = np.array([0.165, 0, 0]) + + +def _chain(side): + s = 1 if side == "L" else -1 + return [ + (np.array([0.0039563, s * 0.10022, 0.24778]), _rx(s * 0.27931), "y"), + (np.array([0, s * 0.038, -0.013831]), _rx(-s * 0.27925), "x"), + (np.array([0, s * 0.00624, -0.1032]), np.eye(3), "z"), + (np.array([0.015783, 0, -0.080518]), np.eye(3), "y"), + (np.array([0.100, s * 0.00188791, -0.010]), np.eye(3), "x"), + (np.array([0.038, 0, 0]), np.eye(3), "y"), + (np.array([0.046, 0, 0]), np.eye(3), "z"), + ] + + +_CH = {"L": _chain("L"), "R": _chain("R")} + + +def fk(q, side="L", tool=TOOL): + p = _TORSO.copy() + R = np.eye(3) + for (o, R0, ax), qi in zip(_CH[side], q): + p = p + R @ o + R = R @ R0 @ _AX[ax](qi) + return p + R @ tool, R + + +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +MIR = np.array([1, -1, -1, 1, -1, 1, -1]) + + +def ik(target, fwd, up, q0, side="L", reg=0.01, w=1.0, wf=0.2, q_nom=None, wn=0.005): + """Tip position + finger axis (up) + soft approach axis (fwd) IK, warm-started at q0.""" + lo, hi = LO, HI + qn = q0 if q_nom is None else q_nom + + def res(q): + t, R = fk(q, side) + return np.concatenate([t - target, wf * (R[:, 0] - fwd), w * (R[:, 1] - up), reg * (q - q0), wn * (q - qn)]) + + s = least_squares(res, np.clip(q0, lo + 1e-4, hi - 1e-4), bounds=(lo, hi), max_nfev=60) + t, _ = fk(s.x, side) + return s.x, float(np.linalg.norm(t - target)) + + +# ---------------------------------------------------------------------------- +# Head camera model (pelvis frame), fitted to gripper-tip pixels. +# ---------------------------------------------------------------------------- +CAM_POS = np.array([0.103236, -0.002438, 0.444112]) +CAM_R = _rz(0.008749) @ _ry(1.068484) @ _rx(-0.019419) +CAM_F = 82.43935 + + +def pix_to_plane(u, v, zp): + """Head pixel (u col, v row) -> pelvis-frame point on the plane z = zp.""" + d = CAM_R @ np.array([1.0, (42 - u) / CAM_F, (42 - v) / CAM_F]) + t = (zp - CAM_POS[2]) / d[2] + return CAM_POS + t * d + + +def brown_mask(img): + im = img.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r - b > 40) & (r > g) & (g > b) + + +def rack_features(img): + """Front-rail row and end columns of the left / right rack in the first head frame.""" + m = brown_mask(img) + out = {} + for name, (c0, c1) in (("L", (0, 42)), ("R", (42, 84))): + mm = np.zeros_like(m) + mm[:, c0:c1] = m[:, c0:c1] + rows = mm.sum(axis=1).astype(float) + cand = np.nonzero(rows >= 6)[0] + if len(cand) == 0: + out[name] = None + continue + fr = cand.max() + lo = max(0, fr - 2) + w = rows[lo:fr + 1] + frow = float((np.arange(lo, fr + 1) * w).sum() / w.sum()) + ys, xs = np.nonzero(mm[lo:fr + 1]) + out[name] = (frow, float(xs.min()), float(xs.max())) + return out + + +def rack_world(feat, side): + """World (x, y) of the inner rail end (left rack: right end, right rack: left end).""" + frow, cmin, cmax = feat + u = cmax + 0.5 if side == "L" else cmin - 0.5 + p = pix_to_plane(u, frow, RAIL_Z - START_PELVIS[2]) + return np.array([p[0] + START_PELVIS[0], p[1] + START_PELVIS[1]]) + + +START_PELVIS = np.array([-0.0711, -0.0028, 0.7467]) +RAIL_Z = 0.72 +# seed-87 reference features (the seed the grasp / place targets were tuned on) +REF_L = (16.67, 0.0, 23.0) +REF_R = (22.52, 58.0, 83.0) + + +# ---------------------------------------------------------------------------- +# Wrist camera features +# ---------------------------------------------------------------------------- +def plate_col(img, rows=(0, 31), win=10, min_rows=8): + """Column of the plate (neutral grey / specular band) in the left wrist image.""" + im = img[rows[0]:rows[1]].astype(int) + mx = im.max(axis=2) + mn = im.min(axis=2) + m = ((mx - mn) < 12) & ((mx < 150) | (mn >= 238)) + m[:, :6] = False + m[:, 78:] = False + cnt = m.sum(axis=0).astype(float) + cs = np.convolve(cnt, np.ones(win), "same") + j = int(np.argmax(cs)) + if cs[j] < 20: + return None + lo, hi = max(0, j - win // 2), min(img.shape[1], j + win // 2 + 1) + band = m[:, lo:hi].any(axis=1) + if band.sum() < min_rows: + return None + w = cnt[lo:hi] + return float((np.arange(lo, hi) * w).sum() / w.sum()) + + +def peg_front_row(img, rmax=40): + """Peg tips of the front row of the target rack: (mean row, wrapped column phase error).""" + im = img[:rmax].astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + tips = (r >= 235) & (g >= 225) & (r - b >= 28) + lab, n = label(tips) + if n < 1: + return None + pegs = np.array(center_of_mass(tips, lab, range(1, n + 1))) + front = pegs[pegs[:, 0] >= pegs[:, 0].max() - 5] + s = PEG_SPACING_PX + ang = 2 * np.pi * (front[:, 1] - PEG_COL_REF) / s + e = np.arctan2(np.mean(np.sin(ang)), np.mean(np.cos(ang))) / (2 * np.pi) * s + return float(front[:, 0].mean()), float(e), len(front) + + +PEG_SPACING_PX = 13.5 +PEG_COL_REF = 29.7 # a front peg tip sits here when the plate is over a slot +PEG_ROW_REF = 21.5 +PEG_ROW_PX_PER_M = 300.0 + +# ---------------------------------------------------------------------------- +# Task constants (world frame unless noted) +# ---------------------------------------------------------------------------- +Q_TUCK_L = np.array([0.19, 0.29, 0.31, -0.77, -0.4, 0.58, -0.08]) +Q_PG_L = np.array([-1.753, 0.846, -0.503, 0.96, -0.612, 1.552, -0.3]) + +APPROACH_X = 0.04 +F_APP = np.array([0.63, 0.0, -0.77]) / np.linalg.norm([0.63, 0.0, -0.77]) +G_W = np.array([0.462, 0.26, 0.872]) + 0.035 * F_APP # grasp point (measured tip) on seed 87 +PRE_DIST = 0.10 +H_W = np.array([0.35, 0.26, 1.08]) # hand waypoint while walking in +LIFT_VEC = np.array([-0.06, 0.0, 0.15]) +COL_TARGET = 45.0 +PX_PER_M = 450.0 +KI = 0.06 +I_MAX = 0.06 +SURVEY_UP = np.array([0.0, 0.0, 0.12]) +SURVEY_COL = 40.0 +SURVEY_PX_PER_M = 450.0 + +P_W = np.array([0.395, -0.222, 1.0]) # hover point (measured tip) over the right rack on seed 87 +PLACE_DZ = 0.14 # lowering before release +CARRY_V = 0.10 +HAND_OFF_Y = 0.24 # pelvis-frame y of the left hand when placing +PEG_PX_PER_M = 365.0 + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.phase = "tuck" + self.k = 0 # steps in phase + self.arms = np.zeros(14) + self.grip = np.array([1.0, 1.0]) + self.debug = [] + self.log = [] + self.qL = Q_PG_L.copy() + self.T = None # world target of the left tool tip + self.Tf = F_APP.copy() + self.Tu = np.array([0.0, 1.0, 0.0]) + self.I = np.zeros(3) + # rack offsets relative to seed 87 from the first head frame + self.dL = np.zeros(2) + self.dR = np.zeros(2) + try: + f = rack_features(tools.image("head")) + if f["L"] is not None: + self.dL = rack_world(f["L"], "L") - rack_world(REF_L, "L") + if f["R"] is not None: + self.dR = rack_world(f["R"], "R") - rack_world(REF_R, "R") + self.log.append(("racks", f, self.dL, self.dR)) + except Exception as exc: # keep going with nominal targets + self.log.append(("rack_err", repr(exc))) + self.dL = np.clip(self.dL, -0.08, 0.08) + self.dR = np.clip(self.dR, -0.08, 0.08) + self.G = G_W + np.array([self.dL[0], self.dL[1], 0.0]) + self.P = P_W + np.array([self.dR[0], self.dR[1], 0.0]) + self.stance_place = np.array([APPROACH_X, self.P[1] - HAND_OFF_Y]) + + # -- frames + def pel(self, obs): + l = obs["low_dim_obs"] + return l[18], l[19], l[20], l[21] + + def to_pelvis(self, obs, pw): + x, y, z, th = self.pel(obs) + d = np.asarray(pw) - np.array([x, y, z]) + c, s = np.cos(th), np.sin(th) + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + def to_world(self, obs, pp): + x, y, z, th = self.pel(obs) + c, s = np.cos(th), np.sin(th) + return np.array([x + c * pp[0] - s * pp[1], y + s * pp[0] + c * pp[1], z + pp[2]]) + + def rot_to_pelvis(self, obs, v): + th = self.pel(obs)[3] + c, s = np.cos(th), np.sin(th) + return np.array([c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]]) + + def track_left(self, obs, integrate=True, moving=None): + """IK the left tool tip onto the world target self.T (with measured-tip integral correction). + + While moving along direction `moving`, only the error perpendicular to it is integrated + (sag), not the tracking lag along the path. + """ + if integrate: + meas = self.to_world(obs, fk(obs["low_dim_obs"][0:7], "L")[0]) + e = self.T - meas + if moving is not None: + e = e - moving * float(moving @ e) + self.I = np.clip(self.I + KI * e, -I_MAX, I_MAX) + tp = self.to_pelvis(obs, self.T + self.I) + f = self.rot_to_pelvis(obs, self.Tf) + u = self.rot_to_pelvis(obs, self.Tu) + q, e = ik(tp, f, u, self.qL, "L", q_nom=Q_PG_L) + self.qL = q + self.arms[:7] = q + return e + + def base_cmd(self, obs, xt=None, yt=None, yawt=0.0, vmax=0.2, tol=0.012, tolx=None, vmin=0.09): + x, y, z, th = self.pel(obs) + wz = float(np.clip(2.0 * (yawt - th), -0.5, 0.5)) + if abs(yawt - th) < 0.01: + wz = 0.0 + if xt is None: + return 0.0, 0.0, wz, True + ex, ey = xt - x, yt - y + c, s = np.cos(th), np.sin(th) + bx, by = c * ex + s * ey, -s * ex + c * ey + dist = np.hypot(ex, ey) + if dist < tol or (tolx is not None and abs(ex) < tolx and abs(ey) < tol): + return 0.0, 0.0, wz, True + v = np.array([1.0 * bx, 1.0 * by]) + n = np.linalg.norm(v) + if n > vmax: + v *= vmax / n + if n < vmin: + v *= vmin / max(n, 1e-6) + return float(v[0]), float(v[1]), wz, False + + def snap(self, tools, tag): + if getattr(self, "debug_on", False): + self.debug.append((tag, [tools.image(c) for c in ("head", "left_wrist", "right_wrist")])) + + def next(self, phase): + self.phase = phase + self.k = 0 + + def move_T(self, obs, k, n, start, goal, integrate=None): + a = min(1.0, (k + 1) / n) + self.T = start + (goal - start) * a + d = goal - start + nd = float(np.linalg.norm(d)) + moving = d / nd if (a < 1.0 and nd > 1e-6) else None + if integrate is None: + integrate = True + return self.track_left(obs, integrate=integrate, moving=moving) + + # -- main + def act(self, obs, tools): + try: + return self._act(obs, tools) + except Exception as exc: # never crash the episode: hold the last targets + self.log.append(("act_err", self.phase, repr(exc))) + raw = self.hold.copy() + raw[4:18] = self.arms + raw[18:20] = self.grip + return raw + + def _act(self, obs, tools): + k = self.k + self.k += 1 + vx = vy = wz = 0.0 + ph = self.phase + if ph == "tuck": + if k == 0: + h_p = H_W + np.array([self.dL[0], self.dL[1], 0]) - np.array([APPROACH_X, 0.0, START_PELVIS[2]]) + self.qA, _ = ik(h_p, self.Tf, self.Tu, Q_PG_L, "L") + tuck = np.concatenate([Q_TUCK_L, Q_TUCK_L * MIR]) + self.arms = tuck * min(1.0, (k + 1) / 30) + if k >= 30: + self.next("raise") + elif ph == "raise": + a = min(1.0, (k + 1) / 40) + self.arms[:7] = Q_TUCK_L + (self.qA - Q_TUCK_L) * a + if k >= 45: + self.next("approach") + elif ph == "approach": + vx, vy, wz, done = self.base_cmd(obs, APPROACH_X, 0.0, tolx=0.035, tol=0.03) + if (done and k > 10) or k > 200: + self.next("settle") + elif ph == "settle": + _, _, wz, _ = self.base_cmd(obs) + if k >= 20: + self.snap(tools, "settled") + self.qL = self.arms[:7].copy() + self.Tstart = self.to_world(obs, fk(self.arms[:7], "L")[0]) + self.next("to_pg") + elif ph == "to_pg": + _, _, wz, _ = self.base_cmd(obs) + self.move_T(obs, k, 30, self.Tstart, self.G - self.Tf * PRE_DIST + SURVEY_UP) + if k == 10: + self.grip[0] = 0.0 + if k >= 45: + self.snap(tools, "survey") + self.scols = [] + self.next("survey") + elif ph == "survey": + _, _, wz, _ = self.base_cmd(obs) + self.track_left(obs) + if k % 10 == 9: + col = plate_col(tools.image("left_wrist")) + self.scols.append(col) + if col is not None: + err = col - SURVEY_COL + self.G[1] -= 0.7 * err / SURVEY_PX_PER_M + self.T = self.G - self.Tf * PRE_DIST + SURVEY_UP + if abs(err) < 3.0 and k > 20: + self.k = 1000 + if k > 10 * 10: + self.k = 1000 + if self.k >= 1000: + self.log.append(("survey", [None if c is None else round(c, 1) for c in self.scols])) + self.stance = np.array([APPROACH_X, 0.0]) + if abs(self.G[1] - G_W[1]) > 0.04: + self.stance[1] = self.G[1] - G_W[1] + self.next("recenter") + elif ph == "recenter": + self.track_left(obs, integrate=False) + vx, vy, wz, done = self.base_cmd(obs, *self.stance, vmax=0.12, tol=0.015, tolx=0.04) + if (done and k > 5) or k > 150: + self.next("resettle") + elif ph == "resettle": + _, _, wz, _ = self.base_cmd(obs) + self.track_left(obs) + if k >= 20: + self.Tstart = self.T.copy() + self.next("to_pg2") + elif ph == "to_pg2": + _, _, wz, _ = self.base_cmd(obs) + self.move_T(obs, k, 25, self.Tstart, self.G - self.Tf * PRE_DIST) + if k >= 35: + self.snap(tools, "pregrasp") + self.prev_err = None + self.again = 0.6 + self.next("align") + elif ph == "align": + _, _, wz, _ = self.base_cmd(obs) + self.track_left(obs) + if k % 10 == 9: + col = plate_col(tools.image("left_wrist")) + self.log.append(("align", k, col)) + if col is not None: + err = col - COL_TARGET + if self.prev_err is not None and np.sign(err) != np.sign(self.prev_err): + self.again *= 0.5 + self.prev_err = err + self.G[1] -= self.again * err / PX_PER_M # hand +y moves the plate right in the image + self.T = self.G - self.Tf * PRE_DIST + if abs(err) < 2.0: + self.next("advance") + if k > 10 * 12: + self.next("advance") + elif ph == "advance": + _, _, wz, _ = self.base_cmd(obs) + if k == 0: + self.Tadv0 = self.T.copy() + self.move_T(obs, k, 40, self.Tadv0, self.G) + if k >= 70: + self.snap(tools, "advanced") + self.next("close") + elif ph == "close": + _, _, wz, _ = self.base_cmd(obs) + self.track_left(obs) + self.grip[0] = 1.0 + if k >= 25: + self.snap(tools, "closed") + self.Tl0 = self.T.copy() + self.next("lift") + elif ph == "lift": + _, _, wz, _ = self.base_cmd(obs) + up = np.array([0.0, 0.0, LIFT_VEC[2]]) + if k < 50: + self.move_T(obs, k, 45, self.Tl0, self.Tl0 + up) + else: + self.move_T(obs, k - 50, 25, self.Tl0 + up, self.Tl0 + LIFT_VEC) + if k >= 85: + self.snap(tools, "lifted") + self.qcarry = self.arms[:7].copy() + self.next("carry") + elif ph == "carry": + self.arms[:7] = self.qcarry + vx, vy, wz, done = self.base_cmd(obs, *self.stance_place, vmax=CARRY_V, tol=0.015, tolx=0.06) + if done and k > 10: + self.next("csettle") + elif ph == "csettle": + _, _, wz, _ = self.base_cmd(obs) + if k >= 20: + self.qL = self.arms[:7].copy() + self.Tstart = self.to_world(obs, fk(self.arms[:7], "L")[0]) + self.next("hover") + elif ph == "hover": + _, _, wz, _ = self.base_cmd(obs) + self.move_T(obs, k, 40, self.Tstart, self.P) + if k >= 50: + self.snap(tools, "hover") + self.perr = [] + self.next("palign") + elif ph == "palign": + _, _, wz, _ = self.base_cmd(obs) + self.track_left(obs) + if k % 4 == 3: + f = peg_front_row(tools.image("left_wrist")) + if f is not None: + self.perr.append(f) + if k % 16 == 15: + self.log.append(("palign", k, [tuple(np.round(p[:2], 1)) for p in self.perr])) + if len(self.perr) >= 2: + rows = np.array([p[0] for p in self.perr]) + ang = 2 * np.pi * np.array([p[1] for p in self.perr]) / PEG_SPACING_PX + ey = np.arctan2(np.mean(np.sin(ang)), np.mean(np.cos(ang))) / (2 * np.pi) * PEG_SPACING_PX + ex = PEG_ROW_REF - float(np.median(rows)) + self.P[1] -= 0.7 * ey / PEG_PX_PER_M # pegs right of reference -> move hand -y + self.P[0] += 0.7 * np.clip(ex, -12, 12) / PEG_ROW_PX_PER_M + self.T = self.P.copy() + if abs(ey) < 1.2 and abs(ex) < 2.0: + self.next("lower") + self.perr = [] + if k > 16 * 6: + self.next("lower") + elif ph == "lower": + _, _, wz, _ = self.base_cmd(obs) + if k == 0: + self.snap(tools, "aligned") + self.Tlow0 = self.T.copy() + self.move_T(obs, k, 60, self.Tlow0, self.Tlow0 - np.array([0, 0, PLACE_DZ]), integrate=False) + if k >= 70: + self.snap(tools, "lowered") + self.next("release") + elif ph == "release": + _, _, wz, _ = self.base_cmd(obs) + self.track_left(obs, integrate=False) + self.grip[0] = 0.0 + if k >= 25: + self.snap(tools, "released") + self.Tr0 = self.T.copy() + self.next("retreat") + elif ph == "retreat": + _, _, wz, _ = self.base_cmd(obs) + self.move_T(obs, k, 40, self.Tr0, self.Tr0 - self.Tf * 0.10, integrate=False) + if k >= 45: + self.snap(tools, "retreated") + self.next("done") + elif ph == "done": + _, _, wz, _ = self.base_cmd(obs) + if k % 25 == 0 and k <= 100: + self.snap(tools, f"done{k}") + raw = self.hold.copy() + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4:18] = self.arms + raw[18:20] = self.grip + return raw diff --git a/policies/move_plate/opus-s3/ctrl.py b/policies/move_plate/opus-s3/ctrl.py new file mode 100644 index 0000000000000000000000000000000000000000..97a8af1aa5b2eca730f0890d336592d71691268f --- /dev/null +++ b/policies/move_plate/opus-s3/ctrl.py @@ -0,0 +1,63 @@ +"""Shared control helpers: world<->pelvis transforms, IK wrappers, base hold.""" +import numpy as np +import fk + +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def pelvis(obs): + o = obs['low_dim_obs'] + return float(o[18]), float(o[19]), float(o[20]), float(o[21]) + + +def world_to_pelvis(p, obs): + x, y, z, yaw = pelvis(obs) + c, s = np.cos(yaw), np.sin(yaw) + d = np.asarray(p, float) - np.array([x, y, z]) + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + +def pelvis_to_world(p, obs): + x, y, z, yaw = pelvis(obs) + c, s = np.cos(yaw), np.sin(yaw) + p = np.asarray(p, float) + return np.array([x + c * p[0] - s * p[1], y + s * p[0] + c * p[1], z + p[2]]) + + +def rot_z(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def tilt_rot(ang, yaw=0.0): + """Tool frame with x pointing forward and `ang` rad downward, y left (world yaw `yaw`).""" + c, s = np.cos(ang), np.sin(ang) + R = np.column_stack([[c, 0, -s], [0, 1, 0], [s, 0, c]]) + return rot_z(yaw) @ R + + +def ik_world(p_world, R_world, obs, q0, side='left', tool=(0, 0, 0), iters=60): + """IK for a world-frame target given the current pelvis pose.""" + yaw = pelvis(obs)[3] + p = world_to_pelvis(p_world, obs) + R = rot_z(-yaw) @ R_world + return fk.arm_ik(p, q0, side, tool, rot=R, w_rot=0.3, iters=iters, lo=LO, hi=HI) + + +def hand_world(obs, side='left', tool=(0, 0, 0)): + o = obs['low_dim_obs'] + q = o[0:7] if side == 'left' else o[9:16] + p, R = fk.arm_fk(q, side, tool) + return pelvis_to_world(p, obs), rot_z(pelvis(obs)[3]) @ R + + +def yaw_hold(obs, yaw_ref=0.0, k=3.0, lim=0.5, wmin=0.1, dead=0.008): + yaw = pelvis(obs)[3] + e = (yaw_ref - yaw + np.pi) % (2 * np.pi) - np.pi + if abs(e) < dead: + return 0.0 + w = float(np.clip(k * e, -lim, lim)) + if abs(w) < wmin: + w = wmin * np.sign(w) + return w diff --git a/policies/move_plate/opus-s3/episodes.csv b/policies/move_plate/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f83919ba837ca33e28d95e8fdeca7c0782cfa2af --- /dev/null +++ b/policies/move_plate/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1384,success,0 +620001,1,1396,success,0 +620002,0,1700,timeout,0 +620003,0,1700,timeout,0 +620004,0,1700,timeout,0 +620005,0,1700,timeout,0 +620006,1,1385,success,0 +620007,0,1700,timeout,0 +620008,0,1700,timeout,0 +620009,1,1300,success,0 +620010,0,1700,timeout,0 +620011,0,1700,timeout,0 +620012,0,1700,timeout,0 +620013,0,1700,timeout,0 +620014,0,1700,timeout,0 +620015,0,1700,timeout,0 +620016,0,1700,timeout,0 +620017,0,1700,timeout,0 +620018,0,1700,timeout,0 +620019,0,1700,timeout,0 +620020,1,1365,success,0 +620021,0,1700,timeout,0 +620022,0,1700,timeout,0 +620023,0,1700,timeout,0 +620024,0,748,terminated,0 +620025,1,1537,success,0 +620026,0,1700,timeout,0 +620027,0,680,terminated,0 +620028,0,1700,timeout,0 +620029,0,1700,timeout,0 +620030,0,1700,timeout,0 +620031,1,1276,success,0 +620032,0,703,terminated,0 +620033,0,1700,timeout,0 +620034,0,1700,timeout,0 +620035,0,1700,timeout,0 +620036,0,1700,timeout,0 +620037,1,1328,success,0 +620038,0,1700,timeout,0 +620039,1,1346,success,0 +620040,0,1700,timeout,0 +620041,1,1354,success,0 +620042,0,1700,timeout,0 +620043,0,1700,timeout,0 +620044,1,1496,success,0 +620045,0,1700,timeout,0 +620046,0,1700,timeout,0 +620047,0,1700,timeout,0 +620048,0,1411,terminated,0 +620049,0,1700,timeout,0 +620050,0,1700,timeout,0 +620051,1,1411,success,0 +620052,1,1288,success,0 +620053,1,1485,success,0 +620054,0,1700,timeout,0 +620055,1,1298,success,0 +620056,1,1389,success,0 +620057,0,1700,timeout,0 +620058,0,1700,timeout,0 +620059,0,1700,timeout,0 +620060,0,1700,timeout,0 +620061,0,888,terminated,0 +620062,0,1700,timeout,0 +620063,1,1385,success,0 +620064,0,1700,timeout,0 +620065,0,1700,timeout,0 +620066,0,1700,timeout,0 +620067,0,1700,timeout,0 +620068,0,1700,timeout,0 +620069,1,1383,success,0 +620070,0,717,terminated,0 +620071,0,1700,timeout,0 +620072,0,1700,timeout,0 +620073,0,1453,terminated,0 +620074,0,1700,timeout,0 +620075,1,1358,success,0 +620076,0,777,terminated,0 +620077,0,1700,timeout,0 +620078,0,1700,timeout,0 +620079,0,1700,timeout,0 +620080,0,1700,timeout,0 +620081,0,1700,timeout,0 +620082,1,1334,success,0 +620083,1,1428,success,0 +620084,0,1700,timeout,0 +620085,0,1700,timeout,0 +620086,0,1700,timeout,0 +620087,0,1700,timeout,0 +620088,1,1334,success,0 +620089,0,1700,timeout,0 +620090,0,1700,timeout,0 +620091,0,1700,timeout,0 +620092,0,1700,timeout,0 +620093,0,1700,timeout,0 +620094,0,1700,timeout,0 +620095,0,1700,timeout,0 +620096,0,1700,timeout,0 +620097,0,1700,timeout,0 +620098,0,1700,timeout,0 +620099,1,1356,success,0 diff --git a/policies/move_plate/opus-s3/fk.py b/policies/move_plate/opus-s3/fk.py new file mode 100644 index 0000000000000000000000000000000000000000..52279031b06e18a05756a67c13e338ee682d38c9 --- /dev/null +++ b/policies/move_plate/opus-s3/fk.py @@ -0,0 +1,111 @@ +"""Hand-written forward kinematics of the Unitree G1 arms (pelvis frame). + +Link offsets follow the published G1 URDF; waist joints are assumed locked at 0. +""" +import numpy as np + + +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _rpy(r, p, y): + return _rz(y) @ _ry(p) @ _rx(r) + + +TORSO = np.array([-0.0039635, 0.0, 0.054]) +# (origin xyz, origin rpy, axis) per joint, for the left arm; right arm mirrors y. +_LEFT = [ + ((0.0039563, 0.10022, 0.23778), (0.27931, 5.4949e-05, -0.00019159), 'y'), + ((0.0, 0.038, -0.013831), (-0.27925, 0.0, 0.0), 'x'), + ((0.0, 0.00624, -0.1032), (0, 0, 0), 'z'), + ((0.015783, 0.0, -0.080518), (0, 0, 0), 'y'), + ((0.100, 0.00188791, -0.010), (0, 0, 0), 'x'), + ((0.038, 0.0, 0.0), (0, 0, 0), 'y'), + ((0.046, 0.0, 0.0), (0, 0, 0), 'z'), +] +_AX = {'x': _rx, 'y': _ry, 'z': _rz} + + +def arm_fk(q, side='left', tool=(0.0, 0.0, 0.0)): + """Return (position, rotation) of a point on the wrist-yaw link, pelvis frame. + + Args: + q: 7 joint angles. + side: 'left' or 'right'. + tool: Offset of the point in the wrist-yaw link frame. + """ + sgn = 1.0 if side == 'left' else -1.0 + p = TORSO.copy() + R = np.eye(3) + for (xyz, rpy, ax), a in zip(_LEFT, q): + xyz = np.array([xyz[0], sgn * xyz[1], xyz[2]]) + rpy = (sgn * rpy[0], rpy[1], sgn * rpy[2]) + p = p + R @ xyz + R = R @ _rpy(*rpy) @ _AX[ax](a) + return p + R @ np.asarray(tool), R + + +def arm_ik(target, q0, side='left', tool=(0.0, 0.0, 0.0), rot=None, w_rot=0.3, + iters=100, lo=None, hi=None, rot_axes=None): + """Damped least-squares IK for position (and optionally orientation). + + Args: + target: Desired tool point position (pelvis frame). + q0: Initial joint guess. + rot: Desired rotation matrix, or None. + w_rot: Weight of orientation error. + rot_axes: If given, list of (local_axis, world_dir) pairs to align + instead of a full rotation. + """ + q = np.array(q0, dtype=float) + for _ in range(iters): + p, R = arm_fk(q, side, tool) + err = [np.asarray(target) - p] + if rot is not None: + Re = rot @ R.T + ang = np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]]) * 0.5 + err.append(w_rot * ang) + if rot_axes is not None: + for la, wd in rot_axes: + v = R @ np.asarray(la) + err.append(w_rot * np.cross(v, np.asarray(wd))) + e = np.concatenate(err) + if np.linalg.norm(e) < 1e-4: + break + J = np.zeros((len(e), 7)) + eps = 1e-5 + for j in range(7): + dq = q.copy() + dq[j] += eps + p2, R2 = arm_fk(dq, side, tool) + col = [(p2 - p) / eps] + if rot is not None: + dR = R2 @ R.T + col.append(w_rot * np.array([dR[2, 1] - dR[1, 2], dR[0, 2] - dR[2, 0], dR[1, 0] - dR[0, 1]]) * 0.5 / eps) + if rot_axes is not None: + for la, wd in rot_axes: + v1 = R @ np.asarray(la) + v2 = R2 @ np.asarray(la) + col.append(w_rot * (np.cross(v2, np.asarray(wd)) - np.cross(v1, np.asarray(wd))) / eps) + J[:, j] = np.concatenate(col) + lam = 0.02 + dq = J.T @ np.linalg.solve(J @ J.T + lam * np.eye(len(e)), e) + n = np.linalg.norm(dq) + if n > 0.3: + dq *= 0.3 / n + q = q + dq + if lo is not None: + q = np.clip(q, lo, hi) + return q diff --git a/policies/move_plate/opus-s3/policy.py b/policies/move_plate/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..aa915e9231633e2a6f761e972d3def9dfd24db40 --- /dev/null +++ b/policies/move_plate/opus-s3/policy.py @@ -0,0 +1,328 @@ +"""Move the plate from the left dish rack to the right dish rack (Unitree G1). + +Hand-written phase machine: + measure both racks in the first head image -> raise the left arm (tool pointing 45 + degrees down) -> walk left -> find the plate column in the head image -> walk so the + plate is in front of the left shoulder -> measure the left rack's depth -> centre the + plate between the fingers with the left wrist camera -> descend along the tool axis -> + close -> lift -> back off -> walk right -> stand still and measure the right rack + against a calibrated head-image model -> move the wrist to the reference placing point + shifted by the measured rack offset -> lower until contact -> open -> retract. +Geometry comes from hand-written G1 arm kinematics (fk.py) and camera measurements +(vision.py); no learned components. +""" + +import os +import sys + +import numpy as np + +sys.path.append(os.path.dirname(os.path.abspath(__file__))) +import ctrl # noqa: E402 +import fk # noqa: E402 +import vision # noqa: E402 + +ANG = 0.8 # tool tilt below horizontal for grasp/place +SEEDQ = np.array([-1.752, 0.206, 1.323, 1.412, 1.115, 1.094, -0.073]) +TUCKR = np.array([0.3, -0.15, 0.0, 1.2, 0.0, 0.0, 0.0]) +HAND_REL_Y = 0.138 # wrist y relative to pelvis at grasp/place +GRASP_BASE_X = 0.02 # pelvis x at grasp +# Head-image models of the racks' front bar (right end column `ur`, row `bar`) as a +# function of pelvis (x, y), measured on the reference layout (seed 87) by walking a +# 3x3 grid of base positions. Offsets of another layout follow from the pixel residuals. +RACK_MODEL = { + 'left': dict(ur=(23.30, -11.6, 126.2), bar=(23.85, 88.0, 13.2)), + # right: intercepts re-measured while holding the plate at lift height (body lean) + 'right': dict(ur=(90.39, 0.77, 124.8), bar=(28.62, 84.9, 0.2)), +} +PX_PER_M_LAT = 125.5 +PX_PER_M_DEPTH = 86.5 +# Wrist x, y that seated the plate in the reference layout (seed 87), shifted one peg +# pitch (+y) away from the rack's right end so small lateral errors stay inside the rack. +PLACE_REF = (0.317, -0.331 + 0.04) +HAND_REL_X = 0.363 +LOOK_R_X = -0.10 # pelvis x where the right rack is measured (grid centre) +CARRY_V = 0.15 # walking speed limit while holding the plate +# Rack features in the first head image (identical robot pose in every episode) for +# the reference layout, and the pixel scales at that distance. +START_REF = dict(urL=23.0, barL=17.55, ulR=58.0, barR=23.06) +START_PX_LAT = 118.0 +START_PX_DEPTH = 62.0 +OBS_X = -0.02 +BACK_X = -0.22 # pelvis x while walking sideways with the plate +WRIST_U_STAR = 40.5 # wrist image column of a plate centred between fingers +CAM_DY = 0.0175 # head camera lateral offset from pelvis +PLATE_U_C = 41.5 +PLATE_K = 0.0068 # metres per pixel for the plate column estimate +PLATE_C = 0.053 # plate y - pelvis y for a plate at the image centre +LIFT_Z = 1.22 +GRASP_Z = 0.98 # wrist height with the rim deep between the fingers +GRASP_X = 0.35 # wrist x at grasp for the reference rack +APPROACH = 0.07 # pre-grasp distance back along the tool axis +AXIS = np.array([np.cos(ANG), 0.0, -np.sin(ANG)]) + + +def rack_offset(which, f, x, y): + """Rack displacement (dx, dy) from the reference layout given head features.""" + if f is None or f['touch_r']: + return np.zeros(2) + m = RACK_MODEL[which] + ur = m['ur'][0] + m['ur'][1] * x + m['ur'][2] * y + bar = m['bar'][0] + m['bar'][1] * x + m['bar'][2] * y + return np.array([-(f['bar'] - bar) / PX_PER_M_DEPTH, -(f['ur'] - ur) / PX_PER_M_LAT]) + + +def _base_cmd(obs, goal, vmax=0.2, tol=0.012): + x, y, _, yaw = ctrl.pelvis(obs) + ex, ey = goal[0] - x, goal[1] - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + vx, vy = np.clip(1.5 * bx, -vmax, vmax), np.clip(1.5 * by, -vmax, vmax) + d = np.hypot(bx, by) + sp = np.hypot(vx, vy) + if d < tol: + return 0.0, 0.0, d + if sp < 0.07: + vx, vy = vx / sp * 0.07, vy / sp * 0.07 + return float(vx), float(vy), d + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + def reset(self, obs, tools): + self.phase = 'raise' + self.k = 0 + self.t = 0 + self.log = [] + o = obs['low_dim_obs'] + self.ql = o[0:7].astype(float).copy() + self.qr = o[9:16].astype(float).copy() + self.grip = 0.6 + self.qhigh = fk.arm_ik((0.25, 0.12, 0.45), SEEDQ, 'left', rot=ctrl.tilt_rot(ANG), + w_rot=0.3, iters=400, lo=ctrl.LO, hi=ctrl.HI) + self.q_from = self.ql.copy() + self.qr_from = self.qr.copy() + self.goal = (OBS_X, 0.12) + self.settle = 0 + self.Rw = ctrl.tilt_rot(ANG) + self.hand_t = None + self.corr = np.zeros(3) + self.tries = 0 + self.looks = [] + self.plate_y = None + self.place_t = None + sf = vision.start_features(tools.image('head')) + self.dL0 = np.zeros(2) + self.dR0 = np.zeros(2) + if sf is not None: + r = START_REF + self.dL0 = np.array([-(sf['barL'] - r['barL']) / START_PX_DEPTH, -(sf['urL'] - r['urL']) / START_PX_LAT]) + self.dR0 = np.array([-(sf['barR'] - r['barR']) / START_PX_DEPTH, -(sf['ulR'] - r['ulR']) / START_PX_LAT]) + self.looks.append(('start', sf, self.dL0, self.dR0)) + + # ---- helpers + def _set_phase(self, p): + self.log.append((p, self.t)) + self.phase = p + self.k = 0 + self.settle = 0 + + def _hand_to(self, obs, target, rate=0.004, integrate=True): + """Move the IK target smoothly toward `target` (world wrist point).""" + hw = ctrl.hand_world(obs)[0] + if self.hand_t is None: + self.hand_t = hw.copy() + d = np.asarray(target, float) - self.hand_t + n = np.linalg.norm(d) + if n > rate: + d *= rate / n + self.hand_t = self.hand_t + d + if integrate: + self.corr = np.clip(self.corr + 0.03 * (self.hand_t - hw), -0.04, 0.04) + self.ql = ctrl.ik_world(self.hand_t + self.corr, self.Rw, obs, self.ql, iters=15) + return n + + def _walk(self, obs, a, tol=0.02, n_settle=8, max_k=150, vmax=0.2): + vx, vy, d = _base_cmd(obs, self.goal, vmax=vmax) + a[0], a[1] = vx, vy + self.settle = self.settle + 1 if d < tol else 0 + return self.settle > n_settle or self.k > max_k + + def _joint_interp(self, target, n): + s = min(1.0, self.k / n) + self.ql = self.q_from + (target - self.q_from) * s + return self.k >= n + + def _rack(self, tools, which): + im = tools.image('head') + blobs = [b for b in vision.rack_blobs(im) if b['n'] > 60] + if not blobs: + return None, im + b = min(blobs, key=lambda b: b['uc']) if which == 'left' else max(blobs, key=lambda b: b['uc']) + return b, im + + def act(self, obs, tools): + self.t = int(obs['t']) + a = np.asarray(tools.hold_action(), dtype=np.float64).copy() + a[3] = ctrl.yaw_hold(obs) + self.k += 1 + ph = self.phase + x, y, _, yaw = ctrl.pelvis(obs) + + if ph == 'raise': + s = min(1.0, self.k / 40) + self.ql = self.q_from + (self.qhigh - self.q_from) * s + self.qr = self.qr_from + (TUCKR - self.qr_from) * s + if self.k >= 45: + self._set_phase('walk_obs') + + elif ph == 'walk_obs': + if self._walk(obs, a): + self._set_phase('find_plate') + + elif ph == 'find_plate': + if self.k >= 5: + b, im = self._rack(tools, 'left') + up = vision.plate_column(im, b) if b is not None else None + self.looks.append(('plate', x, y, up)) + if up is None: + self.goal = (OBS_X, y + 0.08) + self._set_phase('walk_obs') + else: + self.plate_y = y + PLATE_C - (up - PLATE_U_C) * PLATE_K + self.goal = (GRASP_BASE_X, self.plate_y - HAND_REL_Y) + self._set_phase('walk_grasp') + + elif ph == 'walk_grasp': + if self._walk(obs, a): + self._set_phase('look_L') + + elif ph == 'look_L': + if self.k >= 5: + f = vision.rack_features(tools.image('head'), 'left') + self.poseL = np.array([x, y]) + self.dL = rack_offset('left', f, x, y) + self.looks.append(('L', x, y, yaw, None if f is None else (f['ur'], f['bar']), self.dL)) + self.hand_t = None + self.grasp_pt = np.array([GRASP_X + self.dL[0], self.plate_y, GRASP_Z]) + self.pre = self.grasp_pt + np.array([0.01, 0.0, 0.10]) + self._set_phase('pregrasp') + + elif ph == 'pregrasp': + n = self._hand_to(obs, self.pre, 0.005) + if n < 1e-3 and self.k > 30: + self._set_phase('wrist_servo') + + elif ph == 'wrist_servo': + self._hand_to(obs, self.pre, 0.003) + if self.k % 12 == 0: + uw = vision.wrist_plate_column(tools.image('left_wrist')) + self.looks.append(('wrist', self.pre[1], uw)) + done = uw is None or abs(uw - WRIST_U_STAR) < 1.5 or self.k > 150 + if not done: + self.pre[1] -= np.clip((uw - WRIST_U_STAR) * 0.0009, -0.01, 0.01) + else: + self.grasp_pt[1] = self.pre[1] + self._set_phase('descend') + + elif ph == 'descend': + tgt = self.grasp_pt + AXIS * 0.03 + n = self._hand_to(obs, tgt, 0.002, integrate=False) + if n < 1e-3: + self.settle += 1 + if self.settle > 15: + self.grasp_hand = ctrl.hand_world(obs)[0] + self._set_phase('close') + + elif ph == 'close': + self.grip = 1.0 + if self.k > 30: + self.hand_t = None + self.place_t = np.array([PLACE_REF[0] + self.dR0[0], PLACE_REF[1] + self.dR0[1], LIFT_Z]) + self.looks.append(('place0', self.place_t.copy(), self.dL0, self.dR0)) + self._set_phase('lift') + + elif ph == 'lift': + n = self._hand_to(obs, [self.grasp_hand[0] - 0.05, self.grasp_hand[1], LIFT_Z], 0.005) + if n < 1e-3 or self.k > 100: + self.goal = (BACK_X, y) + self._set_phase('back_off') + + elif ph == 'back_off': + if self._walk(obs, a, tol=0.04, n_settle=2, vmax=CARRY_V): + self.goal = (BACK_X, self.place_t[1] - HAND_REL_Y) + self._set_phase('walk_side') + + elif ph == 'walk_side': + if self._walk(obs, a, tol=0.03, n_settle=3, max_k=350, vmax=CARRY_V): + # stand so the right rack appears where it did during calibration + self.goal = (LOOK_R_X + float(np.clip(self.dR0[0], -0.06, 0.1)), self.place_t[1] - HAND_REL_Y) + self._set_phase('approach_R') + + elif ph == 'approach_R': + if self._walk(obs, a, tol=0.015, n_settle=25, max_k=250, vmax=CARRY_V): + self.feats = [] + self._set_phase('look_R') + + elif ph == 'look_R': + # let the walking transient decay, then take the median over ~0.7 s + f = vision.rack_features(tools.image('head'), 'right') if self.k >= 15 else None + if f is not None and not f['touch_r']: + self.feats.append(rack_offset('right', f, x, y)) + if self.k >= 50: + if self.feats: + self.dR = np.median(np.array(self.feats), axis=0) + if np.all(np.abs(self.dR - self.dR0) < 0.08): + self.place_t = np.array([PLACE_REF[0] + self.dR[0], PLACE_REF[1] + self.dR[1], LIFT_Z]) + self.looks.append(('place', self.place_t.copy(), self.feats[-1] if self.feats else None)) + self.rel_x = ctrl.hand_world(obs)[0][0] - x + self.hand_t = None + self.goal = (self.place_t[0] - HAND_REL_X, self.place_t[1] - HAND_REL_Y) + self._set_phase('insert') + + elif ph == 'insert': + done = self._walk(obs, a, max_k=200, vmax=CARRY_V) + tgt = self.place_t.copy() + tgt[0] = min(x + self.rel_x, self.place_t[0]) + self._hand_to(obs, tgt, 0.004) + if done: + self._set_phase('reach_place') + + elif ph == 'reach_place': + n = self._hand_to(obs, self.place_t, 0.003) + hw = ctrl.hand_world(obs)[0] + if n < 1e-3 and self.k > 15 and (np.linalg.norm(hw[:2] - self.place_t[:2]) < 0.008 or self.k > 90): + self._set_phase('lower_place') + + elif ph == 'lower_place': + tgt = np.array([self.place_t[0], self.place_t[1], self.grasp_hand[2] - 0.04]) + self._hand_to(obs, tgt, 0.002, integrate=False) + hw = ctrl.hand_world(obs)[0] + if self.hand_t[2] < hw[2] - 0.02 or self.k > 200: + self.release_z = hw[2] + self._set_phase('release') + + elif ph == 'release': + self.grip = 0.0 + if self.k > 20: + self.hand_t = None + self._set_phase('retract') + + elif ph == 'retract': + hw = self.place_t + if self.k < 30: + self._hand_to(obs, [hw[0] - 0.02, hw[1], self.release_z + 0.08], 0.003) + else: + self._hand_to(obs, [hw[0] - 0.12, hw[1], LIFT_Z], 0.004) + if self.k > 60: + self._set_phase('done') + + return self._finish(a) + + def _finish(self, a): + a[4:11] = self.ql + a[11:18] = self.qr + a[18] = self.grip + a[19] = 0.6 + return a.astype(np.float32) diff --git a/policies/move_plate/opus-s3/vision.py b/policies/move_plate/opus-s3/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..613192c647bae57826b89c93ddad6250dd8d3773 --- /dev/null +++ b/policies/move_plate/opus-s3/vision.py @@ -0,0 +1,187 @@ +"""Image measurements used by the policy.""" +import numpy as np +import cv2 + + +def hsv(im): + return cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + + +def counter_mask(im): + h = hsv(im) + return (h[..., 1] < 40) & (h[..., 2] > 150) + + +def wood_mask(im): + h = hsv(im) + return (h[..., 0] >= 5) & (h[..., 0] <= 25) & (h[..., 1] > 70) & (h[..., 2] > 60) + + +def rack_blobs(im, min_area=15): + """Connected wood regions (racks) in the head image: list of dicts, largest first.""" + m = wood_mask(im).astype(np.uint8) + m = cv2.dilate(m, np.ones((3, 3), np.uint8)) + n, lab, st, cen = cv2.connectedComponentsWithStats(m) + out = [] + for i in range(1, n): + if st[i, 4] < min_area: + continue + ys, xs = np.where((lab == i) & wood_mask(im)) + out.append(dict(u0=xs.min(), u1=xs.max(), v0=ys.min(), v1=ys.max(), uc=xs.mean(), vc=ys.mean(), + n=len(xs), touches=(xs.min() == 0 or xs.max() == im.shape[1] - 1))) + out.sort(key=lambda b: -b['n']) + return out + + +def rack_features(im, which): + """Front bar of the left- or right-most rack in the head image. + + Returns dict(bar=row, ul=left end, ur=right end, um=midpoint, touches) or None. + """ + blobs = [b for b in rack_blobs(im) if b['n'] > 50] + if not blobs: + return None + b = min(blobs, key=lambda b: b['uc']) if which == 'left' else max(blobs, key=lambda b: b['uc']) + m = wood_mask(im) + sub = np.zeros_like(m) + sub[b['v0']:b['v1'] + 1, b['u0']:b['u1'] + 1] = m[b['v0']:b['v1'] + 1, b['u0']:b['u1'] + 1] + rows = sub.sum(1) + thr = 0.5 * rows.max() + cand = np.where(rows >= thr)[0] + bar = int(cand.max()) + band = sub[max(0, bar - 1):bar + 2] + xs = np.where(band.any(0))[0] + # weighted bar row (sub-pixel) from the rows around the bar + r = np.arange(max(0, bar - 2), min(m.shape[0], bar + 3)) + w = rows[r].astype(float) + barf = float((r * w).sum() / max(w.sum(), 1e-6)) + return dict(bar=barf, ul=float(xs.min()), ur=float(xs.max()), um=0.5 * float(xs.min() + xs.max()), + touches=bool(xs.min() == 0 or xs.max() == m.shape[1] - 1), + touch_r=bool(xs.max() == m.shape[1] - 1), blob=b) + + +def dark_mask(im): + h = hsv(im) + return h[..., 2] < 110 + + +def peg_phase(im, f, periods=np.arange(4.0, 7.01, 0.05)): + """Sub-pixel phase of the peg comb of a rack in the head image. + + Uses dark pixels in the band just above the front bar, within the rack blob. + Returns (period, phase, strength) with pegs at phase + k * period, or None. + """ + b = f['blob'] + bar = int(round(f['bar'])) + r0, r1 = max(0, bar - 7), max(1, bar - 1) + u0, u1 = int(b['u0']), int(b['u1']) + 1 + band = dark_mask(im)[r0:r1, u0:u1].astype(float) + prof = band.sum(0) + if prof.sum() < 5: + return None + prof = prof - prof.mean() + u = np.arange(u0, u1, dtype=float) + best = None + for P in periods: + z = (prof * np.exp(-2j * np.pi * u / P)).sum() + if best is None or abs(z) > best[2]: + best = (float(P), float((np.angle(z) * P / (2 * np.pi)) % P), float(abs(z))) + return best + + +def start_features(im): + """Rack features in the head image at the initial pose (both racks in view). + + Left rack: right end of its front bar; right rack: left end of its front bar. + """ + fl = rack_features(im, 'left') + fr = rack_features(im, 'right') + if fl is None or fr is None or fl['blob'] is fr['blob']: + return None + return dict(urL=fl['ur'], barL=fl['bar'], ulR=fr['ul'], barR=fr['bar']) + + +def white_mask(im): + h = hsv(im) + return (h[..., 2] > 215) & (h[..., 1] < 25) + + +def plate_column(im, blob): + """Median column of plate (white) pixels over a rack blob in the head image.""" + m = white_mask(im) + u0, u1 = int(blob['u0']), int(blob['u1']) + v1 = int(blob['v1']) + sub = m[:v1 + 1, u0:u1 + 1] + ys, xs = np.where(sub) + if len(xs) < 5: + return None + return float(np.median(xs) + u0) + + +def wrist_plate_column(im, rows=(0, 42), cols=(12, 72)): + """Median column of the plate strip in the wrist image (plate seen edge-on).""" + m = white_mask(im)[rows[0]:rows[1], cols[0]:cols[1]] + ys, xs = np.where(m) + if len(xs) < 8: + return None + return float(np.median(xs) + cols[0]) + + +def peg_comb(im, excl=(36, 54)): + """Front-row peg columns in a wrist image looking at a rack. + + Returns (bar_row, period, phase, cols) or None. Pegs are at phase + k * period. + """ + m = wood_mask(im) + m[:, excl[0]:excl[1]] = False + rows = m.sum(1) + bar = int(np.argmax(rows)) + if rows[bar] < 8: + return None + r0, r1 = max(0, bar - 7), max(1, bar - 1) + band = m[r0:r1] + prof = band.sum(0).astype(float) + cols = [] + for u in range(1, len(prof) - 1): + if prof[u] >= 2 and prof[u] >= prof[u - 1] and prof[u] > prof[u + 1]: + # centroid of the local run + lo, hi = u, u + while lo > 0 and prof[lo - 1] > 0: + lo -= 1 + while hi < len(prof) - 1 and prof[hi + 1] > 0: + hi += 1 + w = prof[lo:hi + 1] + cols.append(float((np.arange(lo, hi + 1) * w).sum() / w.sum())) + cols = sorted(set(round(c, 2) for c in cols)) + if len(cols) < 3: + return None + d = np.diff(cols) + period = float(np.median(d[(d > 4) & (d < 20)])) if np.any((d > 4) & (d < 20)) else None + if period is None: + return None + # phase by circular mean + ang = 2 * np.pi * np.array(cols) / period + phase = float(np.arctan2(np.sin(ang).mean(), np.cos(ang).mean()) * period / (2 * np.pi)) % period + return bar, period, phase, cols + + +def gap_offset(comb, col): + """Signed pixel offset of `col` from the nearest gap centre of the peg comb.""" + bar, period, phase, cols = comb + g = phase + period / 2 + k = np.round((col - g) / period) + return float(col - (g + k * period)) + + +def counter_edge_row(im, cols=(30, 54)): + """Lowest row of the counter top (grey) in the central columns of the head image.""" + m = counter_mask(im)[:, cols[0]:cols[1]] + frac = m.mean(axis=1) + rows = np.where(frac > 0.5)[0] + if len(rows) == 0: + return None + # contiguous run from top + r = rows[0] + while r + 1 < m.shape[0] and frac[r + 1] > 0.5: + r += 1 + return int(r) diff --git a/policies/move_two_plates/astra-s1/episodes.csv b/policies/move_two_plates/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4529479721eca675d6342ad9272b879907cc2223 --- /dev/null +++ b/policies/move_two_plates/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/astra-s1/policy.py b/policies/move_two_plates/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..81c06e404bfda087e55d346b06fc6f7cca9760e1 --- /dev/null +++ b/policies/move_two_plates/astra-s1/policy.py @@ -0,0 +1,126 @@ +"""Deterministic visual rack alignment and staged, two-handed manipulation.""" +import numpy as np +import cv2 + + +def rack_features(im): + r,g,b=im.astype(float).transpose(2,0,1) + m=((r-g>7)&(g-b>7)&(r-b>22)&(r>65)).astype('uint8');m[50:]=0 + n,lab,st,cen=cv2.connectedComponentsWithStats(cv2.dilate(m,np.ones((3,3),np.uint8))) + out=[] + for i in range(1,n): + if st[i,4]<25 or st[i,2]<9:continue + ys,xs=np.where((lab==i)&(m>0)) + if len(xs)<12:continue + out.append(((xs.min()+xs.max())*.5,float(np.percentile(ys,95)),int(xs.min()),int(xs.max()))) + return sorted(out) + + +def plate_features(im): + r,g,b=im.astype(float).transpose(2,0,1) + m=((abs(r-g)<2)&(abs(g-b)<2)&(r>70)).astype('uint8');m[26:]=0 + n,l,s,c=cv2.connectedComponentsWithStats(m) + out=[] + for i in range(1,n): + x,y,w,h,a=s[i] + if a<12 or h<7 or y>12:continue + out.append((float(c[i,0]),int(a))) + return sorted(out) + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=float);self.a[19:]=.6 + self.phase=0;self.age=0;self.target=np.array([-.085,.25,0.]);self.still=False + self.source=np.array([.02,.21,.25]);self.dest=np.array([.08,-.22,0.]) + def nav(self,obs): + p=obs['low_dim_obs'][21:25];d=self.target-p[[0,1,3]] + v=np.clip(d[:2]*2,-.25,.25) + for j in range(2): + if abs(d[j])<.008:v[j]=0 + elif abs(v[j])<.06:v[j]=np.sign(v[j])*.06 + c,s=np.cos(p[3]),np.sin(p[3]);self.a[:2]=[c*v[0]+s*v[1],-s*v[0]+c*v[1]] + self.a[3]=np.clip(d[2]*3,-.5,.5) + def next(self): + self.phase+=1;self.age=0 + def act(self,obs,tools): + p=obs['low_dim_obs'][21:25];k=self.age;q=self.phase + self.a[:2]=0;self.a[3]=0 + if q==0: + self.nav(obs) + if k>=170:self.next() + elif q==1: + if k>=35: + im=tools.image('head');rs=rack_features(im);ps=plate_features(im) + rs=[z for z in rs if z[3]-z[2]>20] + if rs: + r=min(rs,key=lambda z:abs(z[0]-42));ps=[z for z in ps if r[2]-5<=z[0]<=r[3]+5] + self.source[0]=p[0]+.0095*(32-r[1])+.005 + if len(ps)>=2: + self.source[1]=p[1]+.0085*(23-ps[0][0]);self.source[2]=p[1]+.0085*(52-ps[-1][0]) + self.source[0]=np.clip(self.source[0],-.04,.14) + self.target=np.array([self.source[0]-.20,self.source[1],0]);self.next() + elif q==2: + self.nav(obs) + if k>=85:self.a[[5,12]]=-.4;self.a[[8,15]]=.4 + if k>=190:self.target[0]=self.source[0];self.next() + elif q==3: + self.nav(obs) + if k>=170:self.next() + elif q==4: + if k==1: + dx=np.clip(self.source[0]-.007-p[0],-.035,.05) + dy=np.clip(self.source[1]-.01-p[1],-.04,.04) + self.a[5]=-.4-dx/.20;self.a[8]=.4+1.3*dx/.20 + self.a[7]=dy/.28;self.a[11]=-dy/.28 + if k>=35:self.a[19]=1 + if k>=80:self.next() + elif q==5: + self.a[5]=-.85;self.a[8]=.55 + if k>=85:self.target=np.array([self.source[0]-.10,self.source[1],0]);self.next() + elif q==6: + self.nav(obs) + if k>=95:self.target[1]=self.source[2];self.next() + elif q==7: + self.nav(obs) + if k>=100:self.target[0]=self.source[0]+.005;self.next() + elif q==8: + self.nav(obs) + if k>=145:self.next() + elif q==9: + if k==1: + dx=np.clip(self.source[0]-.007-p[0],-.035,.05) + dy=np.clip(self.source[2]-.005-p[1],-.04,.04) + self.a[12]=-.4-dx/.20;self.a[15]=.4+1.3*dx/.20 + self.a[14]=dy/.28;self.a[18]=-dy/.28 + if k>=35:self.a[20]=1 + if k>=80:self.next() + elif q==10: + self.a[12]=-.85;self.a[15]=.55 + if k>=85:self.target=self.dest.copy();self.next() + elif q==11: + self.nav(obs) + if k>=330:self.next() + elif q==12: + if k==35: + rs=rack_features(tools.image('head'));rs=[z for z in rs if z[3]-z[2]>16] + if rs: + r=min(rs,key=lambda z:abs(z[0]-42)) + self.target=np.array([p[0]+.008*(35-r[1]),p[1]+.007*(42-r[0]),0]) + if k>=35:self.nav(obs) + if k>=150:self.next() + elif q==13: + f=min(1,(k+1)/70);self.a[[5,12]]=-.85+.45*f;self.a[[8,15]]=.55-.15*f + self.a[7]=-.3*f;self.a[14]=.3*f;self.a[11]=.3*f;self.a[18]=-.3*f + if k>=100:self.next() + elif q==14: + self.a[2]=.74-.04*min(1,(k+1)/80) + if k>=140:self.next() + elif q==15: + self.a[19:]=.6 + if k>=90:self.next() + elif q==16: + f=min(1,(k+1)/90) + self.a[[5,12]]=-.4+.2*f;self.a[[8,15]]=.4-.1*f;self.a[2]=.70+.04*f + if k>=120:self.a[19:]=0 + self.age+=1 + return self.a.copy() diff --git a/policies/move_two_plates/astra-s2/episodes.csv b/policies/move_two_plates/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..921f6460000aafaed3ddca2121e82b36a5482b0f --- /dev/null +++ b/policies/move_two_plates/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,2246,success,0 +620001,0,2300,timeout,0 +620002,1,1116,success,0 +620003,1,2171,success,0 +620004,0,2300,timeout,0 +620005,1,2171,success,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,1,2171,success,0 +620009,1,2243,success,0 +620010,1,2171,success,0 +620011,1,2170,success,0 +620012,1,2244,success,0 +620013,1,2207,success,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,1,1093,success,0 +620019,1,1041,success,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,1,2171,success,0 +620030,0,2300,timeout,0 +620031,1,2170,success,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,1,1052,success,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,1,2243,success,0 +620044,0,2300,timeout,0 +620045,1,2238,success,0 +620046,1,2246,success,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,1,1056,success,0 +620056,1,2171,success,0 +620057,1,1111,success,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,1,2171,success,0 +620061,1,2244,success,0 +620062,1,2245,success,0 +620063,1,2171,success,0 +620064,1,1114,success,0 +620065,1,1040,success,0 +620066,0,2300,timeout,0 +620067,1,2245,success,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,1,2244,success,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,1,2242,success,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,1,2243,success,0 +620084,0,2300,timeout,0 +620085,1,2243,success,0 +620086,1,2242,success,0 +620087,0,2300,timeout,0 +620088,1,2243,success,0 +620089,0,2300,timeout,0 +620090,1,2170,success,0 +620091,0,2300,timeout,0 +620092,1,2243,success,0 +620093,1,2181,success,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,1,2246,success,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/astra-s2/policy.py b/policies/move_two_plates/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0707dda3ec0b7f2685566bd7179f41e775043e65 --- /dev/null +++ b/policies/move_two_plates/astra-s2/policy.py @@ -0,0 +1,81 @@ +"""Hand-written visual servo controller for transferring two upright plates.""" +import numpy as np +import cv2 + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=float) + self.a[19:]=0 + self.i=0;self.tick=0;self.cycle=0 + self.target=np.array([-.12,.30,0.]) + self.lengths=[180,220,45,50,70,190,130,100,60,90] + self.debug={} + def vision(self,tools): + a=tools.image('head').astype(int) + neutral=(a.max(2)-a.min(2)<3)&(a[:,:,0]>65) + columns=np.where(neutral[:12].sum(0)>=5)[0] + columns=columns[(columns>5)&(columns<76)] + plate=None + if len(columns): + groups=np.split(columns,np.where(np.diff(columns)>1)[0]+1) + groups=[g for g in groups if len(g)>=2] + if groups:plate=float(np.mean(groups[-1])) + brown=(a[:,:,0]-a[:,:,2]>14)&(a[:,:,0]-a[:,:,1]>5)&(a[:,:,0]>65) + brown[38:]=0 + # Grid rails form connected components after a small morphological close. + mask=cv2.dilate(brown.astype('uint8'),np.ones((3,3),np.uint8)) + n,l,s,c=cv2.connectedComponentsWithStats(mask) + candidates=[k for k in range(1,n) if s[k,4]>70 and s[k,2]>14] + rack=None + if candidates: + k=max(candidates,key=lambda k:s[k,4] if self.i<5 else c[k,0]) + yy,xx=np.where(brown&(l==k)) + if len(xx): + rows=np.bincount(yy,minlength=84) + valid=np.where(rows>=max(5,rows.max()*.50))[0] + rack=(float(np.percentile(xx,2)),float(np.percentile(xx,98)),float(valid[-1] if len(valid) else yy.max())) + return plate,rack + def navigate(self,obs): + o=obs['low_dim_obs'];x,y,yaw=o[[21,22,24]] + delta=self.target[:2]-[x,y] + v=np.clip(delta*2,-.25,.25);v[np.abs(delta)<.008]=0 + for k in range(2): + if 0=2: + self.a[:2]=0;self.a[3]=0;return self.a.copy() + i=self.i;o=obs['low_dim_obs'] + self.a[:2]=0;self.a[3]=0 + goal=-.6 + if i in [4,5,6]:goal=-1.08 + if i==9:goal=-.4 + self.a[12]+=np.clip(goal-self.a[12],-.008,.008) + self.a[15]=.55 + self.a[20]=1 if i in [3,4,5,6,7] else 0 + if self.tick==0: + if i==0:self.target=np.array([-.12,.30 if self.cycle==0 else .36,0.]) + if i==1:self.target=o[[21,22,24]].copy();self.target[2]=0 + if i==5:self.target=np.array([.005,-.14,0.]) if self.cycle==0 else self.destination+np.array([0,.10,0]) + if i==6 and self.cycle==0:self.target=o[[21,22,24]].copy();self.target[2]=0 + if i==3 and self.cycle==0:self.source_x=float(o[21]) + if i==8 and self.cycle==0:self.destination=o[[21,22,24]].copy();self.destination[2]=0 + if i==9:self.target=np.array([-.12,o[22],0.]) + if (i==1 or (i==6 and self.cycle==0)) and self.tick%20==0: + plate,rack=self.vision(tools);self.debug={'plate':plate,'rack':rack} + if i==1 and plate is not None: + self.target[1]=o[22]+np.clip((52-plate)*.006,-.06,.06) + if rack is not None: + left,right,row=rack + self.target[0]=o[21]+np.clip(((35 if i==1 else 32)-row)*.006,-.04,.04) + if i==6:self.target[1]=o[22]+np.clip(((38 if self.cycle==0 else 50)-left)*.006,-.06,.06) + self.target[0]=np.clip(self.target[0],-.20,.13) + if i==1 and self.cycle==1:self.target[0]=self.source_x+.006 + if i in [0,1,5,6,9]:self.navigate(obs) + self.tick+=1 + if self.tick>=self.lengths[i]: + self.i+=1;self.tick=0 + if self.i==10:self.cycle+=1;self.i=0 + return self.a.copy() diff --git a/policies/move_two_plates/astra-s3/episodes.csv b/policies/move_two_plates/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..39db88041667e4971d22532ae0002e36811fa471 --- /dev/null +++ b/policies/move_two_plates/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,1,1471,success,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,1599,terminated,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,1,1472,success,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,1,1612,success,0 +620047,0,2300,timeout,0 +620048,1,1478,success,0 +620049,0,2300,timeout,0 +620050,0,1040,terminated,0 +620051,0,2300,timeout,0 +620052,0,967,terminated,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,1,1474,success,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,1,1483,success,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,989,terminated,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,655,terminated,0 +620082,0,2300,timeout,0 +620083,1,1471,success,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,1145,terminated,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,1648,terminated,0 +620094,1,1477,success,0 +620095,1,1601,success,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/astra-s3/policy.py b/policies/move_two_plates/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..445366aa77ccf6828f9b1e842fcdcdad62045293 --- /dev/null +++ b/policies/move_two_plates/astra-s3/policy.py @@ -0,0 +1,128 @@ +"""Deterministic, camera-guided plate transfer with hand-tuned motions. + +Pick the plates in succession with opposite hands, carry both above the rack, +then converge the hands while lowering. Perception uses only color and connected +components. All motion timing is in control steps. +""" + +import numpy as np +import cv2 +from scipy.spatial.transform import Rotation as R + +class Policy: + + def reset(self, o, tools): + self.a = np.array(tools.hold_action(), float) + self.a[19:] = 0 + self.phase = 0 + self.tick = 0 + self.arrived = False + # Steps, base x/y, shoulders, wrist pitches, and gripper commands. + self.plan = [ + (150, -0.04, 0.33, 0, 0, 0, 0, 0, 0), + (100, 0.14, 0.33, 0, -0.2, 0, 0, 0, 0), + (45, 0.14, 0.33, 0, -0.2, 0, 0, 0, 1), + (100, 0.04, 0.33, 0, -1.15, 0, 0.95, 0, 1), + (220, 0.06, 0.02, 0, -1.15, 0, 0.95, 0, 1), + (100, 0.14, 0.02, -0.2, -1.15, 0, 0.95, 0, 1), + (45, 0.14, 0.02, -0.2, -1.15, 0, 0.95, 1, 1), + (100, 0.04, 0.02, -1.15, -1.15, 0.95, 0.95, 1, 1), + (190, 0.04, -0.29, -1.15, -1.15, 0.95, 0.95, 1, 1), + (120, 0.13, -0.29, -1.15, -1.15, 0.95, 0.95, 1, 1), + (250, 0.13, -0.29, -0.05, -0.05, -0.15, -0.15, 1, 1), + (100, 0.13, -0.29, -0.05, -0.05, -0.15, -0.15, 0, 0), + (120, -0.1, -0.29, -0.2, -0.2, 0, 0, 0, 0) + ] + # Coarse scene offsets from ceramic edges and the wooden rack rails. + im = tools.image('head').astype(float) + r, g, b = im.transpose(2, 0, 1) + gray = (abs(r - g) < 3) & (abs(r - b) < 3) & (r > 65) + gray[26:] = False + gray[:, 45:] = False + _, _, st, _ = cv2.connectedComponentsWithStats(gray.astype('uint8')) + st = [v for v in st[1:] if v[4] > 15 and v[3] > 8] + edge = max([v[0] + v[2] - 1 for v in st], default=23) + brown = (r > g * 1.18) & (g > b * 1.15) & (r > 70) + brown[40:] = False + sy, sx = np.where(brown[:, :42]) + dy, dx = np.where(brown[:, 42:]) + dx = dx + 42 + source_x = np.clip((19 - np.percentile(sy, 95)) * 0.015, -0.15, 0.15) if len(sy) > 10 else 0 + source_y = np.clip((23 - edge) / 140, -0.2, 0.2) + dest_x = np.clip((21 - np.percentile(dy, 95)) * 0.015, -0.15, 0.15) if len(dy) > 10 else 0 + dest_y = np.clip((58 - np.min(dx)) / 140, -0.2, 0.2) if len(dx) > 10 else 0 + self.offsets = (source_x, source_y, dest_x, dest_y) + self.dest_samples = [] + self.plan = [(v[0], v[1] + (source_x if i < 8 else dest_x), v[2] + (source_y if i < 8 else dest_y), *v[3:]) for i, v in enumerate(self.plan)] + + def act(self, o, tools): + # Reobserve the remaining plate after the first hand has cleared it. + if self.phase == 4 and self.tick == 140: + im = tools.image('head').astype(float) + rr, gg, bb = im.transpose(2, 0, 1) + mask = (abs(rr - gg) < 3) & (abs(rr - bb) < 3) & (rr > 65) + mask[:, 32:] = False + mask[30:] = False + _, _, st, cen = cv2.connectedComponentsWithStats(mask.astype('uint8')) + ids = [i for i in range(1, len(st)) if st[i, 4] > 25 and st[i, 3] > 10 and (st[i, 1] < 10)] + if ids: + i = max(ids, key=lambda i: st[i, 4]) + cx = cen[i, 0] + yy = float(o['low_dim_obs'][22]) + (14 - cx) / 140 + 0.025 + for k in range(4, 8): + v = self.plan[k] + self.plan[k] = (v[0], v[1], yy, *v[3:]) + self.arrived = False + # Average the destination rail geometry over several gait frames. + if self.phase == 8 and self.tick >= 140 and (self.tick % 5 == 0): + im = tools.image('head').astype(float) + rr, gg, bb = im.transpose(2, 0, 1) + mask = (rr > gg * 1.18) & (gg > bb * 1.15) & (rr > 70) + mask[55:] = False + mask[:, :10] = False + mask[:, 76:] = False + ys, xs = np.where(mask) + if len(xs) > 35: + front = np.percentile(ys, 95) + xx = xs[ys >= front - 2] + if len(xx) > 8 and np.ptp(xx) > 20: + center = (np.min(xx) + np.max(xx)) / 2 + pp = o['low_dim_obs'][21:25] + self.dest_samples.append((pp[0] + (27 - front) / 100 + 0.113, pp[1] + (42 - center) / 150 - 0.005)) + if self.phase == 9 and self.tick == 0 and self.dest_samples: + dx, dy = np.median(self.dest_samples, axis=0) + for k in range(9, 13): + v = self.plan[k] + self.plan[k] = (v[0], float(dx) if k < 12 else float(dx) - 0.23, float(dy), *v[3:]) + # Close the base loop in world coordinates, then command body velocities. + n, x, y, sl, sr, wl, wr, gl, gr = self.plan[self.phase] + q = o['low_dim_obs'] + p = q[21:25] + e = np.array([x, y]) - p[:2] + v = np.clip(2 * e, -0.25, 0.25) + if np.linalg.norm(e) < 0.023: + self.arrived = True + if self.arrived or self.phase in (2, 3, 6, 7, 10, 11): + v[:] = 0 + elif 0 < np.linalg.norm(v) < 0.065: + v *= 0.065 / np.linalg.norm(v) + c = np.cos(p[3]) + ss = np.sin(p[3]) + self.a[:2] = [c * v[0] + ss * v[1], -ss * v[0] + c * v[1]] + self.a[3] = np.clip(-3 * p[3], -0.5, 0.5) + # Bring the plates inward only while lowering, avoiding hand collisions. + f = np.clip((self.a[5] + 1.15) / 1.1, 0, 1) if self.phase >= 10 else 0 + yl = -0.32 * f + yr = -0.06 + 0.3 * f + targ = np.array([sl, 0, yl, 0, 0, wl, -yl, sr, 0, yr, 0, 0, wr, -yr]) + if self.phase >= 10: + targ[4:7] = (R.from_euler('YZ', [sl, yl]).inv() * R.from_euler('Y', -0.2)).as_euler('XYZ') + targ[11:14] = (R.from_euler('YZ', [sr, yr]).inv() * R.from_euler('Y', -0.2)).as_euler('XYZ') + self.a[5:19] += np.clip(targ - self.a[5:19], -0.012, 0.012) + self.a[19:] = [gl, gr] + self.tick += 1 + if self.tick >= n and self.phase < len(self.plan) - 1: + self.tick = 0 + self.phase += 1 + self.arrived = False + return self.a.copy() diff --git a/policies/move_two_plates/deepseek1017-s1/episodes.csv b/policies/move_two_plates/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4529479721eca675d6342ad9272b879907cc2223 --- /dev/null +++ b/policies/move_two_plates/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/deepseek1017-s1/policy.py b/policies/move_two_plates/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b1adb51cf0f6f625b86fbf8a8f051dc776bbee91 --- /dev/null +++ b/policies/move_two_plates/deepseek1017-s1/policy.py @@ -0,0 +1,270 @@ +"""Hand-written control policy for moving two plates from the left dish rack +to the right dish rack with a Unitree G1. + +The scene is observed only through the robot's own cameras, but the policy is +a deterministic finite state machine built from the geometry probed during +development: + + * walk up to the table with the arms tucked, + * position the base on the left using the pelvis feedback, + * try a short list of right-arm reach/grasp poses at the left rack, using + the gripper state as contact feedback after closing, + * when the gripper reports contact, lift the arm/body, carry the plate to + the right rack by moving the base right and turning, lower and release, + * repeat once for the second plate. + +All constants are hand tuned. No learning, no randomness, no wall clock. +""" + +import numpy as np + + +class Policy: + # --- global timing ------------------------------------------------- + WALK_STEPS = 52 + ALIGN_STEPS = 55 + MOVE_STEPS = 22 + CLOSE_STEPS = 14 + OPEN_STEPS = 8 + LIFT_STEPS = 26 + CARRY_STEPS = 48 + PLACE_STEPS = 26 + RELEASE_STEPS = 20 + RETRACT_STEPS = 18 + SETTLE_STEPS = 10 + + # base pose used while working at the left dish rack + LEFT_X = 0.12 + LEFT_Y = 0.20 + LEFT_YAW = 0.0 + # base pose used at the right dish rack + RIGHT_X = 0.16 + RIGHT_Y = -0.22 + RIGHT_YAW = 0.30 + + # right-arm candidate reach poses: [sp, sr, sy, elbow, wr, wp, wy] + # (gripper is closed after each one and the finger state is read back) + CANDIDATES = [ + [-0.90, 0.00, -0.20, 0.70, 0.0, 0.20, 0.0], + [-1.00, 0.00, -0.10, 0.70, 0.0, 0.50, 0.0], + [-0.80, 0.00, -0.30, 0.60, 0.0, 0.40, 0.0], + [-1.00, 0.00, -0.10, 0.70, 0.0, 0.70, 0.0], + [-0.90, 0.00, -0.30, 0.90, 0.0, 0.50, 0.0], + ] + + # pose used to lower the plate into the right rack + PLACE_POSE = [-0.65, 0.30, 0.30, 0.45, 0.0, 0.60, 0.0] + + def reset(self, obs, tools): + """Prepare the state machine for a new episode.""" + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.action = self.hold.copy() + # start from a tucked, natural walking posture + self.action[0] = 0.0 + self.action[1] = 0.0 + self.action[2] = 0.74 + self.action[3] = 0.0 + self.action[4] = 0.10 + self.action[5:12] = [0.60, 0.30, 0.0, 0.20, 0.0, 0.0, 0.0] + self.action[12:19] = [0.60, -0.30, 0.0, 0.20, 0.0, 0.0, 0.0] + self.action[19] = 0.0 + self.action[20] = 0.0 + + self.state = "walk" + self.timer = 0 + self.plates_done = 0 + self.cand = 0 + self.found = False + self.arm = "right" + + # ------------------------------------------------------------------ + @staticmethod + def _wrap(a): + """Wrap an angle to (-pi, pi].""" + while a > np.pi: + a -= 2.0 * np.pi + while a < -np.pi: + a += 2.0 * np.pi + return a + + def _base_hold(self, obs, x, y, yaw, push=0.05): + """P-feedback base controller towards a planar pose.""" + ld = obs["low_dim_obs"] + cx, cy, _cz, cyaw = [float(v) for v in ld[21:25]] + ex = x - cx + ey = y - cy + eyaw = self._wrap(yaw - cyaw) + kx, ky, kw = 2.0, 3.0, 3.0 + c, s = np.cos(cyaw), np.sin(cyaw) + vxw = float(np.clip(kx * ex, -0.5, 0.5)) + push + vyw = float(np.clip(ky * ey, -0.5, 0.5)) + vxb = c * vxw + s * vyw + vyb = -s * vxw + c * vyw + self.action[0] = float(np.clip(vxb, -0.6, 0.6)) + self.action[1] = float(np.clip(vyb, -0.6, 0.6)) + self.action[3] = float(np.clip(kw * eyaw, -0.6, 0.6)) + # the base controller ignores tiny planar speeds + for idx in (0, 1, 3): + if 0.0 < abs(self.action[idx]) < 0.07: + self.action[idx] = 0.07 if self.action[idx] > 0 else -0.07 + + def _at_grip(self, obs, side): + """Return the measured finger state of one gripper.""" + ld = obs["low_dim_obs"] + return float(ld[50] if side == "left" else ld[51]) + + # ------------------------------------------------------------------ + def act(self, obs, tools): + """Step the finite state machine and return the 21-dof action.""" + a = self.action + self.timer += 1 + + # Keep the torso upright-ish and retain the height except in lift. + a[4] = 0.10 + + if self.state == "walk": + a[5:12] = [0.60, 0.30, 0.0, 0.20, 0.0, 0.0, 0.0] + a[12:19] = [0.60, -0.30, 0.0, 0.20, 0.0, 0.0, 0.0] + a[0], a[1], a[3] = 0.18, 0.0, 0.0 + a[2] = 0.74 + if self.timer >= self.WALK_STEPS: + a[0] = 0.0 + self.timer = 0 + self.state = "align" + + elif self.state == "align": + self._base_hold(obs, self.LEFT_X, self.LEFT_Y, self.LEFT_YAW, + push=0.05) + a[2] = 0.74 + if self.plates_done == 0: + a[12:19] = self.CANDIDATES[0] + else: + a[12:19] = self.CANDIDATES[0] + a[19] = 0.0 + a[20] = 0.0 + if self.timer >= self.ALIGN_STEPS: + self.timer = 0 + self.cand = 0 + self.found = False + a[12:19] = self.CANDIDATES[self.cand] + self.state = "move" + + elif self.state == "move": + self._base_hold(obs, self.LEFT_X, self.LEFT_Y, self.LEFT_YAW, + push=0.05) + a[2] = 0.74 + a[12:19] = self.CANDIDATES[self.cand] + a[19] = 0.0 + a[20] = 0.0 + if self.timer >= self.MOVE_STEPS: + self.timer = 0 + self.state = "close" + + elif self.state == "close": + self._base_hold(obs, self.LEFT_X, self.LEFT_Y, self.LEFT_YAW, + push=0.05) + a[2] = 0.74 + a[12:19] = self.CANDIDATES[self.cand] + a[19] = 0.0 + a[20] = 1.0 + if self.timer >= self.CLOSE_STEPS: + self.timer = 0 + g = self._at_grip(obs, "right") + if g < 0.94: + self.found = True + self.state = "lift" + else: + self.state = "open" + + elif self.state == "open": + self._base_hold(obs, self.LEFT_X, self.LEFT_Y, self.LEFT_YAW, + push=0.05) + a[2] = 0.74 + a[12:19] = self.CANDIDATES[self.cand] + a[20] = 0.0 + if self.timer >= self.OPEN_STEPS: + self.timer = 0 + self.cand += 1 + if self.cand >= len(self.CANDIDATES): + # nothing found: still return to a safe hold and stop + self.state = "done" + else: + a[12:19] = self.CANDIDATES[self.cand] + self.state = "move" + + elif self.state == "lift": + self._base_hold(obs, self.LEFT_X, self.LEFT_Y, self.LEFT_YAW, + push=0.05) + a[2] = 0.82 + p = list(self.CANDIDATES[self.cand]) + p[0] -= 0.35 + p[3] -= 0.18 + a[12:19] = p + a[20] = 1.0 + if self.timer >= self.LIFT_STEPS: + self.timer = 0 + self.state = "carry" + + elif self.state == "carry": + self._base_hold(obs, self.RIGHT_X, self.RIGHT_Y, self.RIGHT_YAW) + a[2] = 0.80 + p = list(self.CANDIDATES[self.cand]) + p[0] -= 0.25 + p[3] -= 0.10 + a[12:19] = p + a[20] = 1.0 + if self.timer >= self.CARRY_STEPS: + self.timer = 0 + self.state = "place" + + elif self.state == "place": + self._base_hold(obs, self.RIGHT_X, self.RIGHT_Y, self.RIGHT_YAW) + a[2] = 0.74 + a[12:19] = self.PLACE_POSE + a[20] = 1.0 + if self.timer >= self.PLACE_STEPS: + self.timer = 0 + self.state = "release" + + elif self.state == "release": + self._base_hold(obs, self.RIGHT_X, self.RIGHT_Y, self.RIGHT_YAW) + a[2] = 0.74 + a[12:19] = self.PLACE_POSE + a[20] = 0.0 + if self.timer >= self.RELEASE_STEPS: + self.timer = 0 + self.state = "retract" + + elif self.state == "retract": + self._base_hold(obs, self.RIGHT_X, self.RIGHT_Y, self.RIGHT_YAW) + a[2] = 0.74 + p = list(self.PLACE_POSE) + p[0] += 0.20 + p[3] += 0.30 + a[12:19] = p + a[20] = 0.0 + if self.timer >= self.RETRACT_STEPS: + self.timer = 0 + self.plates_done += 1 + if self.plates_done >= 2 or not self.found: + self.state = "done" + else: + self.state = "back" + + elif self.state == "back": + self._base_hold(obs, self.LEFT_X, self.LEFT_Y, self.LEFT_YAW, + push=0.05) + a[2] = 0.74 + a[12:19] = self.CANDIDATES[0] + a[20] = 0.0 + if self.timer >= (self.CARRY_STEPS + 20): + self.timer = 0 + self.state = "align" + + else: # done: hold quietly + a[0], a[1], a[3] = 0.0, 0.0, 0.0 + a[2] = 0.74 + a[19] = 0.0 + a[20] = 0.0 + + return a diff --git a/policies/move_two_plates/deepseek1017-s3/episodes.csv b/policies/move_two_plates/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a6d650e19a3aa2838f74d3af251f8a8174f40e7d --- /dev/null +++ b/policies/move_two_plates/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,264,terminated,0 +620004,0,2300,timeout,0 +620005,0,353,terminated,0 +620006,0,266,terminated,0 +620007,0,2300,timeout,0 +620008,0,267,terminated,0 +620009,0,2300,timeout,0 +620010,0,1545,terminated,0 +620011,0,273,terminated,0 +620012,0,281,terminated,0 +620013,0,2300,timeout,0 +620014,0,344,terminated,0 +620015,0,2300,timeout,0 +620016,0,277,terminated,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,264,terminated,0 +620020,0,266,terminated,0 +620021,0,2300,timeout,0 +620022,0,638,terminated,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,264,terminated,0 +620026,0,266,terminated,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,270,terminated,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,275,terminated,0 +620036,0,2300,timeout,0 +620037,0,626,terminated,0 +620038,0,1360,terminated,0 +620039,0,365,terminated,0 +620040,0,1212,terminated,0 +620041,0,550,terminated,0 +620042,0,274,terminated,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,265,terminated,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,269,terminated,0 +620054,0,2300,timeout,0 +620055,0,290,terminated,0 +620056,0,263,terminated,0 +620057,0,273,terminated,0 +620058,0,266,terminated,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,266,terminated,0 +620063,0,280,terminated,0 +620064,0,2300,timeout,0 +620065,0,272,terminated,0 +620066,0,277,terminated,0 +620067,0,2300,timeout,0 +620068,0,272,terminated,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,264,terminated,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,1599,terminated,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,269,terminated,0 +620083,0,264,terminated,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,272,terminated,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,272,terminated,0 +620091,0,2300,timeout,0 +620092,0,294,terminated,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,696,terminated,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/deepseek1017-s3/policy.py b/policies/move_two_plates/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5fef3c01b8854417a91165d04f9f0461ef4bf72e --- /dev/null +++ b/policies/move_two_plates/deepseek1017-s3/policy.py @@ -0,0 +1,145 @@ +"""Control policy for the G1 plate-transfer task. + +Hand-written, deterministic phase machine: approach the left dish rack, close +the left gripper on a plate rim, lift the plate with the elbow, swing it across +with the shoulder yaw, lower it onto the right dish rack and release. The +sequence is attempted twice (one plate per attempt). + +Only the observation and the tools described in docs/api.md are used. +""" + +import numpy as np + + +# Action indices of the left arm joints. +L_SH_P, L_SH_R, L_SH_Y, L_ELB, L_WR_R, L_WR_P, L_WR_Y = range(5, 12) +L_GRIP = 19 + +# Base position hold gains. +KX, KY, KW = 6.0, 6.0, 8.0 + + +def _p(kind, steps, base=None, arm=None, grip=None, dyaw=None): + return { + "kind": kind, + "steps": int(steps), + "base": base or {}, + "arm": arm or {}, + "grip": grip, + "dyaw": dyaw, + } + + +class Policy: + """Scripted two-trip plate transfer.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.phase = 0 + self.pt = 0 + self.tx = 0.0 + self.ty = 0.0 + self.tyaw = 0.0 + self.phases = self._build_phases() + + # ------------------------------------------------------------------ + @staticmethod + def _arm(sp=0.90, roll=0.05, yaw=0.0, elbow=0.0, wr=0.0, wp=0.0, wy=1.5): + return { + L_SH_P: sp, L_SH_R: roll, L_SH_Y: yaw, L_ELB: elbow, + L_WR_R: wr, L_WR_P: wp, L_WR_Y: wy, + } + + def _build_phases(self): + A = self._arm() + arms = [ + _p("hold", 18), + _p("move", 85, base={3: 0.30}), # turn left + _p("move", 105, base={0: 0.25}), # walk to the table + _p("hold", 25, arm={}), + _p("hold", 30, arm=A, grip=0.0), + _p("hold", 35, arm=A, grip=0.0, dyaw=-0.12), # centre one plate + _p("hold", 28, arm=A, grip=1.0), # close on the rim + # lift the plate with the elbow + _p("hold", 14, arm=self._arm(elbow=0.4)), + _p("hold", 14, arm=self._arm(elbow=0.8)), + _p("hold", 14, arm=self._arm(elbow=1.2)), + _p("hold", 46, arm=self._arm(elbow=1.5)), + # swing towards the right rack using the shoulder yaw + _p("hold", 12, arm=self._arm(yaw=0.3, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=0.6, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=0.9, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=1.1, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=1.3, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=1.5, wp=-1.2)), + # small step in towards the rack + _p("move", 24, base={0: 0.12}, + arm=self._arm(yaw=1.5, elbow=1.5, wp=-1.2), grip=1.0), + # lower the plate into the rack + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=1.2, wp=-0.9), grip=1.0), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=0.9, wp=-0.9), grip=1.0), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=0.6, wp=-0.9), grip=1.0), + _p("hold", 20, arm=self._arm(yaw=1.5, elbow=0.6, wp=-0.9), grip=0.0), + # retract outwards, away from the plate + _p("hold", 15, arm=self._arm(yaw=1.0, elbow=0.6, roll=-0.30), grip=0.0), + _p("hold", 20, arm=self._arm(sp=0.40, roll=0.0, wy=0.4), grip=0.0), + _p("hold", 60, arm={}), + # ---- second trip: turn back towards the left rack + _p("move", 150, base={3: 0.30}), + _p("move", 120, base={0: 0.25}), + _p("hold", 25, arm={}), + _p("hold", 30, arm=A, grip=0.0), + _p("hold", 35, arm=A, grip=0.0, dyaw=-0.12), + _p("hold", 28, arm=A, grip=1.0), + _p("hold", 14, arm=self._arm(elbow=0.4)), + _p("hold", 14, arm=self._arm(elbow=0.8)), + _p("hold", 14, arm=self._arm(elbow=1.2)), + _p("hold", 46, arm=self._arm(elbow=1.5)), + _p("hold", 12, arm=self._arm(yaw=0.3, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=0.6, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=0.9, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=1.1, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=1.3, elbow=1.5, wp=-1.2)), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=1.5, wp=-1.2)), + _p("move", 24, base={0: 0.12}, + arm=self._arm(yaw=1.5, elbow=1.5, wp=-1.2), grip=1.0), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=1.2, wp=-0.9), grip=1.0), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=0.9, wp=-0.9), grip=1.0), + _p("hold", 12, arm=self._arm(yaw=1.5, elbow=0.6, wp=-0.9), grip=1.0), + _p("hold", 20, arm=self._arm(yaw=1.5, elbow=0.6, wp=-0.9), grip=0.0), + _p("hold", 15, arm=self._arm(yaw=1.0, elbow=0.6, roll=-0.30), grip=0.0), + _p("hold", 20, arm=self._arm(sp=0.40, roll=0.0, wy=0.4), grip=0.0), + _p("hold", 500, arm={}), + ] + return arms + + # ------------------------------------------------------------------ + def act(self, obs, tools): + ph = self.phases[self.phase] + if self.pt == 0: + ld = obs["low_dim_obs"] + self.tx = float(ld[21]) + self.ty = float(ld[22]) + self.tyaw = float(ld[24]) + + ld = obs["low_dim_obs"] + x, y, yaw = float(ld[21]), float(ld[22]), float(ld[24]) + + raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + for k, v in ph["base"].items(): + raw[k] = v + if not ph["base"]: + tgt_yaw = self.tyaw + (ph["dyaw"] if ph["dyaw"] is not None else 0.0) + raw[0] = float(np.clip(KX * (self.tx - x), -0.35, 0.35)) + raw[1] = float(np.clip(KY * (self.ty - y), -0.35, 0.35)) + raw[3] = float(np.clip(KW * (tgt_yaw - yaw), -0.6, 0.6)) + for k, v in ph["arm"].items(): + raw[k] = v + if ph["grip"] is not None: + raw[L_GRIP] = ph["grip"] + + self.pt += 1 + if self.pt >= ph["steps"]: + self.pt = 0 + self.phase = min(self.phase + 1, len(self.phases) - 1) + return raw diff --git a/policies/move_two_plates/gpt61sol-s1/episodes.csv b/policies/move_two_plates/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..76c732e81f80fe571a3521dad3c983211e51f09e --- /dev/null +++ b/policies/move_two_plates/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2008,terminated,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt61sol-s1/policy.py b/policies/move_two_plates/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..43d789da58df6003b49df24c6fbaba5f044d3f9f --- /dev/null +++ b/policies/move_two_plates/gpt61sol-s1/policy.py @@ -0,0 +1,153 @@ +"""Deterministic rack transfer using colour geometry and joint waypoints.""" +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.action = np.asarray(tools.hold_action(), dtype=float) + self.action[5:12] = [0, 0, 0, 1.2, 0, 0, 0] + self.action[12:19] = [-1.3, 0, 0, 0, 0, 1.6, 0] + self.action[19:21] = 0 + self.cycle = 0 + self.scan = 0 + self.stage = 0 + self.started = 0 + self.finished = False + self.make_stages() + + def make_stages(self): + self.source = np.array([.2, .32]) + self.depth_correction = 0. + self.dest = np.array([.14, -.22]) + # duration, base destination, shoulder pitch, grip, purpose + self.stages = [ + [200, self.source.copy(), -1.3, 0, 'approach'], + [30, None, -1.3, 0, 'observe'], + [60, None, -.9, 0, 'lower'], + [35, None, -.9, 1, 'grasp'], + [60, None, -1.3, 1, 'lift'], + [100, np.array([.12, .17]), -1.3, 1, 'retract'], + [180, np.array([.12, -.22]), -1.3, 1, 'transport'], + [120, self.dest.copy(), -1.3, 1, 'position'], + [60, None, -.9, 1, 'insert'], + [60, None, -.9, 0, 'release'], + [80, np.array([0., -.22]), -1.3, 0, 'withdraw'], + [55, None, -1.3, 0, 'wait'], + ] + + @staticmethod + def plate_tops(im): + hi = im.max(axis=2).astype(float) + lo = im.min(axis=2).astype(float) + mask = ((((hi < 130) & (lo > 35)) | (lo > 220)) & (hi - lo < 25)).astype(np.uint8) + # The raised arm occupies the right edge; floor shadows lie below. + mask[:12] = 0 + mask[43:] = 0 + mask[:, 65:] = 0 + mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)) + _, labels, stats, _ = cv2.connectedComponentsWithStats(mask) + candidates = [] + for i, (x, y, w, h, area) in enumerate(stats[1:], 1): + if h < 7 or w > 35 or area < 10 or y < 13 or y > 29: + continue + yy, xx = np.where(labels == i) + top = yy.min() + cap = xx[yy <= top + 2] + if len(cap): + candidates.append((float(cap.mean()), float(top))) + return sorted(candidates) + + @staticmethod + def rack_center(im): + r, g, b = im.transpose(2, 0, 1).astype(float) + mask = ((r > g * 1.12) & (g > b * 1.16) & (r > 65)).astype(np.uint8) + mask[:15] = 0 + mask[70:] = 0 + joined = cv2.dilate(mask, np.ones((5, 5), np.uint8)) + _, labels, stats, _ = cv2.connectedComponentsWithStats(joined) + candidates = [] + for i, (x, y, w, h, area) in enumerate(stats[1:], 1): + if w < 16 or h < 10 or x + w < 20: + continue + yy, xx = np.where((labels == i) & (mask > 0)) + if len(xx) > 25: + candidates.append((len(xx), float(xx.mean()), float(yy.mean()))) + if not candidates: + return None + _, x, y = max(candidates) + return np.array([x, y]) + + def drive(self, a, q, target): + velocity = 2 * (target - q[21:23]) + speed = np.linalg.norm(velocity) + if speed > .22: + velocity *= .22 / speed + if speed < .025: + velocity *= 0 + elif speed < .065: + velocity *= .065 / speed + yaw = q[24] + a[0] = np.cos(yaw) * velocity[0] + np.sin(yaw) * velocity[1] + a[1] = -np.sin(yaw) * velocity[0] + np.cos(yaw) * velocity[1] + a[3] = np.clip(-5 * yaw, -.7, .7) + + def act(self, obs, tools): + q = obs['low_dim_obs'] + t = int(obs['t']) + a = self.action.copy() + a[0] = a[1] = a[3] = 0 + if self.finished: + return a + duration, target, pitch, grip, purpose = self.stages[self.stage] + a[12:19] = [pitch, 0, 0, 0, 0, 1.6, 0] + a[20] = grip + if target is not None: + self.drive(a, q, target) + + if t - self.started >= duration: + if purpose == 'observe': + points = self.plate_tops(tools.image('head')) + if points: + u, v = points[-1] + # A high rim has a smaller depth projection than the rack bars. + # Account for where the rim was pinched on the plate circumference. + self.depth_correction = float(np.clip(.010 * (v - 14), -.04, .12)) + correction = np.array([.005 * (14 - v), .005 * (57 - u)]) + if np.linalg.norm(correction) > .014: + self.source = np.clip(self.source + correction, [-.02, .08], [.30, .65]) + self.stages[self.stage + 1:self.stage + 1] = [ + [100, self.source.copy(), -1.3, 0, 'align'], + [30, None, -1.3, 0, 'settle'], + ] + elif self.scan < 2: + self.scan += 1 + self.source += np.array([.03, -.12]) + self.stages[self.stage + 1:self.stage + 1] = [ + [150, self.source.copy(), -1.3, 0, 'scan'], + [30, None, -1.3, 0, 'observe'], + ] + else: + self.finished = True + elif purpose == 'transport': + rack = self.rack_center(tools.image('head')) + if rack is not None: + correction = .005 * (np.array([48.94 + 9 * self.cycle, 38.34]) - rack) + # Camera columns correspond to lateral motion, rows to depth. + correction = correction[::-1] + if np.linalg.norm(correction) > .012: + self.dest = np.clip(self.dest + correction, [-.02, -.45], [.30, .08]) + elif self.cycle: + self.dest[1] += .045 + self.dest[0] = np.clip(self.dest[0] + self.depth_correction, -.02, .30) + self.stages[self.stage + 1][1] = self.dest.copy() + self.stages[-2][1] = np.array([0., self.dest[1]]) + elif purpose == 'wait': + self.cycle += 1 + self.scan = 0 + self.make_stages() + self.stage = -1 + self.stage += 1 + self.started = t + self.action = a + return a diff --git a/policies/move_two_plates/gpt61sol-s2/episodes.csv b/policies/move_two_plates/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..223089685afd04c8cef38c3774219fdc96eaefd9 --- /dev/null +++ b/policies/move_two_plates/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,1,1055,success,0 +620041,1,1121,success,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,1,1459,success,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2044,terminated,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,1,1121,success,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,1840,terminated,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,1,2060,success,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,1,1120,success,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,1,1121,success,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2041,terminated,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,1,1122,success,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,1720,terminated,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt61sol-s2/policy.py b/policies/move_two_plates/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b3912efa50aa46127bb7aeb232edc6e2dff8cd03 --- /dev/null +++ b/policies/move_two_plates/gpt61sol-s2/policy.py @@ -0,0 +1,144 @@ +"""Deterministic camera alignment and joint-space plate transfer control.""" +import numpy as np + + +class Policy: + DURATIONS = (200, 170, 100, 50, 90, 300, 90, 70, 180) + + @staticmethod + def _rack_points(image): + # The wooden front rails are below the plates and can be separated + # from the grey table and white robot by their colour. + r, g, b = [image[:, :, k].astype(float) for k in range(3)] + wood = (r > 1.13 * g) & (g > 1.10 * b) & (r > 75) + points = [] + for start, end in ((0, 40), (44, 84)): + pixels = np.argwhere(wood[:30, start:end]) + if len(pixels) < 20: + return None + v = int(np.quantile(pixels[:, 0], 0.93)) + xs = pixels[(pixels[:, 0] >= v - 2) + & (pixels[:, 0] <= v + 1), 1] + start + if len(xs) < 5: + return None + lo, hi = float(xs.min()), float(xs.max()) + u = (lo + hi) / 2 + # Restore the centre of a rail clipped by the image boundary. + width = 33 + 0.45 * (v - 24) + if lo <= 1: + u = hi - width / 2 + elif hi >= 82: + u = lo + width / 2 + points.append((u, float(v))) + return points + + @staticmethod + def _table_point(pixel): + # Pinhole ray intersection with the horizontal tabletop. Only + # differences from the reference views are used as waypoint offsets. + u, v = pixel + focal, elevation, pitch = 52.0, 0.31, 1.1 + d = v - 41.5 + denominator = focal * np.sin(pitch) + d * np.cos(pitch) + return np.array([ + elevation * (focal * np.cos(pitch) - d * np.sin(pitch)) / denominator, + -elevation * (u - 41.5) / denominator, + ]) + + def reset(self, obs, tools): + self.hold = np.array(tools.hold_action(), dtype=float) + self.hold[19:21] = 0 + self.phase = 0 + self.age = 0 + self.retries = 0 + self.retry_lower = 0 + self.pickup = np.array([-0.07, 0.30]) + self.approach = np.array([-0.015, 0.30]) + self.destination = np.array([0.08, -0.30]) + points = self._rack_points(tools.image('head')) + if points is not None: + left = np.clip(self._table_point(points[0]) + - self._table_point((6.95, 22.0)), -0.18, 0.18) + right = np.clip(self._table_point(points[1]) + - self._table_point((68.7, 16.0)), -0.18, 0.18) + self.pickup += left + self.approach += left + self.destination += right + + @staticmethod + def _navigate(action, obs, target): + pose = obs['low_dim_obs'][21:25] + delta = np.asarray(target) - pose[:2] + velocity = np.clip(2 * delta, -0.25, 0.25) + for k in range(2): + if abs(delta[k]) < 0.007: + velocity[k] = 0 + elif abs(velocity[k]) < 0.06: + velocity[k] = np.sign(velocity[k]) * 0.06 + yaw = pose[3] + action[0] = np.cos(yaw) * velocity[0] + np.sin(yaw) * velocity[1] + action[1] = -np.sin(yaw) * velocity[0] + np.cos(yaw) * velocity[1] + action[3] = np.clip(-3 * yaw, -0.4, 0.4) + + @staticmethod + def _reach(action): + action[5] = action[12] = -0.8 + action[8] = action[15] = 0.9 + action[13] = -0.15 + + def act(self, obs, tools): + action = self.hold.copy() + action[:2] = 0 + action[3] = 0 + + # Finger separation after lifting distinguishes a plate contact from + # an empty closure. Lower before reopening for a bounded retry. + if self.phase == 5 and self.age == 0 and not self.retry_lower: + state = obs['low_dim_obs'] + empty = (np.mean(state[10:12]) <= -0.018 + or np.mean(state[19:21]) <= -0.018) + if empty and self.retries < 2: + self.retries += 1 + self.retry_lower = 60 + self.approach[0] += 0.018 if self.retries == 1 else -0.036 + + if self.retry_lower: + self._reach(action) + action[19:21] = 1 + self.retry_lower -= 1 + if not self.retry_lower: + self.phase = 1 + self.age = 0 + return action + + phase = self.phase + if phase == 0: + self._navigate(action, obs, self.pickup) + if 1 <= phase < 8: + self._reach(action) + if phase == 2: + self._navigate(action, obs, self.approach) + if 3 <= phase <= 6: + action[19:21] = 1 + if phase in (4, 5): + action[5] = action[12] = -1.25 + if phase in (5, 6): + self._navigate(action, obs, self.destination) + if 5 <= phase <= 7: + fraction = min(self.age / 120.0, 1.0) if phase == 5 else 1.0 + # Move both plates into neighbouring slots and restore their + # vertical orientation before lowering and opening the fingers. + action[6] = -0.15 * fraction + action[9] = -0.10 * fraction + action[13] = -0.15 + 0.25 * fraction + action[16] = 0.50 * fraction + if phase >= 7: + action[19:21] = 0 + if phase >= 8: + action[5:19] = 0 + + self.age += 1 + if phase < len(self.DURATIONS) and self.age >= self.DURATIONS[phase]: + self.phase += 1 + self.age = 0 + return action diff --git a/policies/move_two_plates/gpt61sol-s3/episodes.csv b/policies/move_two_plates/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..1b9513d163dad2f3f62ff966e7e34c85a93dd5f1 --- /dev/null +++ b/policies/move_two_plates/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,794,terminated,0 +620006,0,2300,timeout,0 +620007,0,1527,terminated,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,1465,terminated,0 +620012,0,670,terminated,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,660,terminated,0 +620016,0,2300,timeout,0 +620017,0,1731,terminated,0 +620018,0,676,terminated,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,1831,terminated,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,1523,terminated,0 +620025,0,2300,timeout,0 +620026,0,1754,terminated,0 +620027,0,2300,timeout,0 +620028,0,1764,terminated,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,783,terminated,0 +620032,0,1492,terminated,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,1602,terminated,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,1479,terminated,0 +620041,0,1482,terminated,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,1870,terminated,0 +620046,0,1758,terminated,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,1490,terminated,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,1714,terminated,0 +620056,0,1384,terminated,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,1395,terminated,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,1510,terminated,0 +620083,0,1446,terminated,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,672,terminated,0 +620092,0,2300,timeout,0 +620093,0,528,terminated,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,820,terminated,0 +620097,0,719,terminated,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt61sol-s3/policy.py b/policies/move_two_plates/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f0196d0d7c7c17bcb1cfe38e9df49d14cd2e7791 --- /dev/null +++ b/policies/move_two_plates/gpt61sol-s3/policy.py @@ -0,0 +1,67 @@ +"""Deterministic, hand-written plate handling and base feedback.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.action = np.asarray(tools.hold_action(), dtype=float) + self.action[19:] = 0 + self.stage = self.age = self.good = 0 + self.integral = np.zeros(2) + self.plan = [('setup', None, -.2, 0, 50, 50), + ('approach', (.11, 0), -.2, 0, 150, 150)] + for plate in range(2): + pickup_y = .16 * plate + destination_y = -.58 - .06 * plate + lift = -.65 if plate == 0 else -.75 + if plate: + self.plan += [('return', (-.05, pickup_y), -.2, 0, 30, 300), + ('approach', (.11, pickup_y), -.2, 0, 150, 150)] + self.plan += [('grasp', None, -.2, 1, 50, 50), + ('lift', None, lift, 1, 70, 70), + ('carry', (.12, destination_y), lift, 1, 50, 400), + ('lower', (.12, destination_y), -.16, 1, 100, 100), + ('release', (.12, destination_y), -.16, 0, 50, 50), + ('withdraw', (-.06, destination_y), -.16, 0, 30, 80)] + + def act(self, obs, tools): + q = obs['low_dim_obs'] + a = self.action.copy() + a[:2] = 0 + a[2] = .74 + a[3] = np.clip(-3*q[24], -.4, .4) + a[4] = 0 + if self.stage >= len(self.plan): + return a + name, target, pitch, grip, minimum, maximum = self.plan[self.stage] + if name == 'lower': + pitch = a[5] + np.clip(pitch-a[5], -.007, .007) + wrist_yaw = -.2 + wrist_yaw = a[11] + np.clip(wrist_yaw-a[11], -.01, .01) + a[5:12] = [pitch, 0, .2, 0, 0, -pitch, wrist_yaw] + a[12:19] = [0]*7 if self.stage < 4 else [-.6, 0, 0, -.7, 0, 1.3, 0] + a[19:21] = [grip, 0] + if target is not None: + error = np.asarray(target)-q[21:23] + if name == 'approach': + velocity = np.clip(2*error, -.18, .18) + else: + self.integral = np.clip(self.integral+.02*error, -.1, .1) + speed = .4 + velocity = np.clip(4*error+1.5*self.integral, -speed, speed) + a[3] = np.clip(-7*q[24], -.6, .6) + norm = np.linalg.norm(velocity) + if np.linalg.norm(error) < .012: + velocity[:] = 0 + elif norm < .07: + velocity *= .07/max(norm, 1e-6) + yaw = q[24] + a[0] = np.cos(yaw)*velocity[0]+np.sin(yaw)*velocity[1] + a[1] = -np.sin(yaw)*velocity[0]+np.cos(yaw)*velocity[1] + self.good = self.good+1 if np.linalg.norm(error) < .023 else 0 + self.age += 1 + if self.age >= maximum or (self.age >= minimum and self.good >= 20): + self.stage += 1 + self.age = self.good = 0 + self.integral *= .2 + self.action = a + return a diff --git a/policies/move_two_plates/gpt61terra-s1/episodes.csv b/policies/move_two_plates/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..939a8f5bf20d56cc758431eda7943d652afa6c87 --- /dev/null +++ b/policies/move_two_plates/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,1219,terminated,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,737,terminated,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,1278,terminated,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,696,terminated,0 +620072,0,1313,terminated,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,1399,terminated,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,749,terminated,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,1337,terminated,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,1311,terminated,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt61terra-s1/policy.py b/policies/move_two_plates/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cace09343dcf81c52023dccd2f2d2e3403290bdd --- /dev/null +++ b/policies/move_two_plates/gpt61terra-s1/policy.py @@ -0,0 +1,59 @@ +"""Deterministic plate transfer controller.""" +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = int(obs['t']) + a = self.hold.copy() + a[0:2] = 0 + a[3] = 0 + a[19:21] = 0 + if t < 45: + a[1] = .2 + if t >= 90: + a[5], a[8], a[10] = -.7, 1., -.4 + if 200 <= t < 240: + a[0] = .15 + if t >= 300: + a[19] = 1 + if t >= 370: + z = min((t - 370) / 200, 1) + a[5], a[8] = -.7 - .8*z, 1. + .5*z + if 620 <= t < 970: + self.navigate(a, obs, -.03, -.27) + if t >= 970: + z = min((t - 970) / 150, 1) + a[5], a[8] = -1.5 + 1.1*z, 1.5 - .8*z + if t >= 1180: + a[19] = 0 + if t >= 1250: + a[5], a[8], a[10] = -.7, 1., -.4 + if 1250 <= t < 1470: + self.navigate(a, obs, -.08, .13) + if 1550 <= t < 1590: + a[0] = .15 + if t >= 1600: + a[19] = 1 + if t >= 1660: + z = min((t - 1660) / 140, 1) + a[5], a[8] = -.7 - .8*z, 1. + .5*z + if 1800 <= t < 2070: + self.navigate(a, obs, -.03, -.27) + if t >= 2070: + z = min((t - 2070) / 110, 1) + a[5], a[8] = -1.5 + 1.1*z, 1.5 - .8*z + if t >= 2190: + a[19] = 0 + return a + + @staticmethod + def navigate(a, obs, x, y): + q = obs['low_dim_obs'] + dx, dy, yaw = x - q[21], y - q[22], q[24] + a[1] = np.clip(2*dy, -.2, .2) if abs(dy) > .025 else 0 + a[0] = np.clip(2*dx, -.14, .14) if abs(dx) > .04 else 0 + a[3] = np.clip(-2*yaw, -.3, .3) if abs(yaw) > .03 else 0 diff --git a/policies/move_two_plates/gpt61terra-s2/episodes.csv b/policies/move_two_plates/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6c7f5121c4b399b80084f057661897a9d35f452a --- /dev/null +++ b/policies/move_two_plates/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2132,terminated,0 +620001,0,2300,timeout,0 +620002,0,2089,terminated,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2136,terminated,0 +620006,0,934,terminated,0 +620007,0,1061,terminated,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,949,terminated,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,1135,terminated,0 +620026,0,2099,terminated,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2267,terminated,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,975,terminated,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,1000,terminated,0 +620037,0,2300,timeout,0 +620038,0,1000,terminated,0 +620039,0,990,terminated,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,1056,terminated,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2154,terminated,0 +620050,0,2140,terminated,0 +620051,0,1165,terminated,0 +620052,0,2300,timeout,0 +620053,0,978,terminated,0 +620054,0,1165,terminated,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,939,terminated,0 +620059,0,2112,terminated,0 +620060,0,2300,timeout,0 +620061,0,2115,terminated,0 +620062,0,2300,timeout,0 +620063,0,2111,terminated,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2140,terminated,0 +620070,0,975,terminated,0 +620071,0,2203,terminated,0 +620072,0,2129,terminated,0 +620073,0,2300,timeout,0 +620074,0,976,terminated,0 +620075,0,2106,terminated,0 +620076,0,956,terminated,0 +620077,0,981,terminated,0 +620078,0,985,terminated,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2110,terminated,0 +620086,0,2300,timeout,0 +620087,0,1031,terminated,0 +620088,0,2300,timeout,0 +620089,0,1169,terminated,0 +620090,0,2300,timeout,0 +620091,0,1148,terminated,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2130,terminated,0 +620099,0,2115,terminated,0 diff --git a/policies/move_two_plates/gpt61terra-s2/policy.py b/policies/move_two_plates/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cd29425adf01c7e0fe9be5399d019841395cd2a2 --- /dev/null +++ b/policies/move_two_plates/gpt61terra-s2/policy.py @@ -0,0 +1,70 @@ +"""Deterministic feedback controller for the plate-transfer task.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.hold = np.array(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = int(obs['t']) + p = obs['low_dim_obs'] + a = self.hold.copy() + a[:5] = [0, 0, .74, np.clip(-2 * p[24], -.25, .25), 0] + a[5:19] = 0 + a[19:21] = 0 + goal = None + arm = [0, 0, 0, 0, 0, 0, 0] + grip = 0 + high = [-1.4, -.1, 0, 1.3, 0, 0, 0] + grasp = [-1.2, -.1, 0, 1.1, 0, 0, 0] + lifted = [-1.3, -.1, 0, 1.1, 0, 0, 0] + if t < 220: + goal = (-.30, .43) + elif t < 270: + arm[3] = 1.3 + elif t < 340: + arm = high + elif t < 640: + arm = high; goal = (.05, .43) + elif t < 700: + arm = grasp + elif t < 780: + arm = grasp; grip = 1 + elif t < 840: + arm = lifted; grip = 1 + elif t < 950: + arm = lifted; grip = 1; goal = (-.15, .43) + elif t < 1200: + arm = lifted; grip = 1; goal = (-.15, -.28) + elif t < 1300: + arm = lifted; grip = 1; goal = (.05, -.28) + elif t < 1360: + arm = grasp; grip = 1 + elif t < 1420: + arm = grasp + elif t < 1480: + arm = high + elif t < 1730: + arm = high; goal = (-.10, .25) + elif t < 1830: + arm = high; goal = (.06, .25) + elif t < 1880: + arm = grasp + elif t < 1940: + arm = grasp; grip = 1 + elif t < 1990: + arm = lifted; grip = 1 + elif t < 2200: + arm = lifted; grip = 1; goal = (-.12, -.46) + elif t < 2240: + arm = grasp; grip = 1 + else: + arm = grasp + a[5:12] = arm + a[19] = grip + if goal is not None: + for i in range(2): + d = goal[i] - p[21+i] + if abs(d) > .025: + a[i] = np.sign(d) * max(.06, min(.16, 2*abs(d))) + return a diff --git a/policies/move_two_plates/gpt61terra-s3/episodes.csv b/policies/move_two_plates/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e38632da3e37791af3ff3bd9eb2f2bcc84606cc9 --- /dev/null +++ b/policies/move_two_plates/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1220,success,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,1481,terminated,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2260,terminated,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,797,terminated,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,1478,terminated,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,1230,terminated,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,1465,terminated,0 +620048,0,2300,timeout,0 +620049,1,1178,success,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,1,1223,success,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,1,1221,success,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,1,1187,success,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt61terra-s3/policy.py b/policies/move_two_plates/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ce5cd8ad89368b0527ad12d6781b44a880c26a5e --- /dev/null +++ b/policies/move_two_plates/gpt61terra-s3/policy.py @@ -0,0 +1,52 @@ +"""Deterministic, proprioception-guided two-trip plate transfer.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = obs['t']; q = obs['low_dim_obs']; a = self.hold.copy() + a[0] = a[1] = a[3] = 0 + a[19:21] = 0 + if t < 150: + a[1] = .18 if q[22] < .18 else 0 + return a + if t < 1120: + a[5:12] = [-.7, -.1, .05, .5, 0, 0, -.25] + a[12:19] = [-.7, .1, .25, .5, 0, 0, .25] + if 250 <= t < 330: a[0] = .16 + if t >= 370: a[19:21] = 1 + if 470 <= t < 950: + a[5] = a[12] = -1.03 + a[2] = .8 + if 600 <= t < 950: + a[1] = -.08 if q[22] > -.29 else 0 + a[3] = np.clip(-1.5*q[24], -.25, .25) + dx = .04 - q[21] + if abs(dx) > .025: a[0] = np.clip(dx*2, -.12, .12) + if t >= 1070: a[19:21] = 0 + elif t < 1400: + a[5:12] = [-1.2, -.1, .05, 1.2, 0, 0, -.25] + a[12:19] = [-1.2, .1, .25, 1.2, 0, 0, .25] + if t >= 1170: + a[5:19] = 0 + a[1] = .15 if q[22] < .18 else 0 + a[3] = np.clip(-1.5*q[24], -.25, .25) + else: + a[5:12] = [-.7, -.1, .05, .5, 0, 0, -.25] + a[12:19] = [-.7, .1, .25, .5, 0, 0, .25] + if t >= 1500: a[19:21] = 1 + if 1570 <= t < 2000: + a[5] = a[12] = -1.03 + a[2] = .8 + if 1660 <= t < 2000: + a[1] = -.10 if q[22] > -.29 else 0 + a[3] = np.clip(-1.5*q[24], -.25, .25) + dx = .04 - q[21] + if abs(dx) > .025: a[0] = np.clip(dx*2, -.12, .12) + if t >= 2130: a[19:21] = 0 + if t >= 2200: + a[5] = a[12] = -1.2 + a[8] = a[15] = 1.2 + return a diff --git a/policies/move_two_plates/gpt6sol-s1/episodes.csv b/policies/move_two_plates/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..cd34eca8aa2aedd9d4303fd65de363af60a6b5bb --- /dev/null +++ b/policies/move_two_plates/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,326,terminated,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt6sol-s1/policy.py b/policies/move_two_plates/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8812e58836785c33114238b25b241bedcf2508 --- /dev/null +++ b/policies/move_two_plates/gpt6sol-s1/policy.py @@ -0,0 +1,125 @@ +"""Deterministic, hand-written controller for moving the dish-rack plates.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32) + self.a[19:21] = 0.0 + self.a[5:12] = [-0.65, 0.20, 0.0, 0.30, 0.0, 0.40, 0.0] + self.phase = 0 + self.count = 0 + self.pick_adjusted = True + + def _next(self): + self.phase += 1 + self.count = 0 + + def act(self, obs, tools): + state = np.asarray(obs["low_dim_obs"]) + x, y, _, yaw = map(float, state[21:25]) + self.a[0] = 0.0 + self.a[1] = 0.0 + self.a[3] = 0.0 + + for _ in range(2): + p = self.phase + if p == 0: + if self.count >= 70: + self._next() + continue + elif p == 1: + if x >= 0.02 or self.count >= 150: + self._next() + continue + self.a[0] = 0.16 + self.a[3] = np.clip(-2.0 * yaw, -0.4, 0.4) + elif p == 2: + if self.count >= 25: + self._next() + continue + elif p == 3: + if self.count == 0: + if not self.pick_adjusted: + image = tools.image("left_wrist") + mask = ((image[:, :, 0] > 220) & + (image[:, :, 1] > 215) & + (image[:, :, 2] > 210)).astype(np.uint8) + mask[:8] = 0 + mask[75:] = 0 + n, _, stats, centers = cv2.connectedComponentsWithStats(mask) + blobs = sorted(((int(stats[i, 4]), float(centers[i, 0])) + for i in range(1, n) if stats[i, 4] >= 200), + reverse=True) + if blobs: + if len(blobs) > 1 and blobs[1][0] >= 0.12 * blobs[0][0]: + center = (blobs[0][1] + blobs[1][1]) / 2.0 + else: + center = blobs[0][1] + change = float(np.clip((52.0 - center) * 0.015, -0.25, 0.40)) + if abs(change) > 0.08: + self.a[6] = 0.20 + change + self.pick_adjusted = True + self.phase = 12 + self.count = 0 + continue + self.pick_adjusted = True + self.a[19] = 1.0 + if self.count >= 70: + self._next() + continue + elif p == 4: + if self.count == 0: + self.a[5] = -0.85 + if self.count >= 50: + self._next() + continue + elif p == 5: + if y <= -0.46 or self.count >= 250: + self._next() + continue + self.a[1] = -0.24 + self.a[0] = np.clip(2.0 * (0.02 - x), -0.18, 0.18) + self.a[3] = np.clip(-4.0 * yaw - 0.5, -1.0, 1.0) + elif p == 6: + if self.count >= 25: + self._next() + continue + elif p == 7: + if self.count >= 170: + self._next() + continue + ey, ex = -0.47 - y, 0.02 - x + self.a[1] = np.sign(ey) * 0.09 if abs(ey) > 0.012 else 0.0 + self.a[0] = np.sign(ex) * 0.09 if abs(ex) > 0.02 else 0.0 + feed = -0.15 if self.a[1] < 0 else (0.15 if self.a[1] > 0 else 0.0) + self.a[3] = np.clip(-4.0 * yaw + feed, -0.8, 0.8) + elif p == 8: + if self.count >= 25: + self._next() + continue + elif p == 9: + if (abs(x - 0.02) < 0.012 and self.count >= 13) or self.count >= 150: + self._next() + continue + self.a[0] = 0.15 if x < 0.02 else -0.15 + self.a[3] = np.clip(-2.0 * yaw, -0.4, 0.4) + elif p == 10: + if self.count == 0: + self.a[2] = 0.65 + self.a[6] = 0.10 + if self.count >= 70: + self._next() + continue + elif p == 11: + self.a[19] = 0.0 + elif p == 12: + if self.count >= 50: + self.phase = 3 + self.count = 0 + continue + break + self.count += 1 + return self.a.copy() diff --git a/policies/move_two_plates/gpt6sol-s2/episodes.csv b/policies/move_two_plates/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..0650c64189092edfd7fcd151ed7bc8208aba0a99 --- /dev/null +++ b/policies/move_two_plates/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,1411,terminated,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,507,terminated,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,973,terminated,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/gpt6sol-s2/policy.py b/policies/move_two_plates/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2da37f8191366b26b9508cae55d739988a10f8 --- /dev/null +++ b/policies/move_two_plates/gpt6sol-s2/policy.py @@ -0,0 +1,111 @@ +"""Deterministic plate transfer controller for the simulated G1.""" + +import math +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.raw0 = np.asarray(tools.hold_action(), dtype=np.float32) + self.second_grip = False + + @staticmethod + def _walk(raw, state, target, max_speed): + x, y, _, yaw = map(float, state[21:25]) + dx = target[0] - x + dy = target[1] - y + c, s = math.cos(yaw), math.sin(yaw) + vx = max(-max_speed, min(max_speed, 1.5 * (c * dx + s * dy))) + vy = max(-max_speed, min(max_speed, 1.5 * (-s * dx + c * dy))) + if abs(vx) < 0.06: + vx = 0.0 + if abs(vy) < 0.06: + vy = 0.0 + wz = max(-0.4, min(0.4, 3.0 * (target[2] - yaw))) + raw[0], raw[1], raw[3] = vx, vy, wz + + def act(self, obs, tools): + t = int(obs["t"]) + state = obs["low_dim_obs"] + raw = self.raw0.copy() + raw[0] = raw[1] = raw[3] = 0.0 + raw[2] = 0.74 + raw[4] = 0.0 + raw[5:12] = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + raw[19] = 0.0 + if t < 175: + self._walk(raw, state, (0.12, 0.16, 0.0), 0.25) + elif t < 220: + raw[5:12] = (-0.8, -0.1, -0.3, 0.0, 0.0, 0.0, 0.0) + elif t < 265: + raw[5:12] = (-0.8, -0.1, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 300: + raw[5:12] = (-0.6, -0.1, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 335: + raw[5:12] = (-0.4, -0.1, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 425: + raw[5:12] = (-0.2, -0.1, -0.3, 0.5, 0.0, 0.0, 0.0) + if t >= 370: + raw[19] = 1.0 + elif t < 500: + raw[5:12] = (-0.9, -0.1, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 1.0 + elif t < 740: + raw[5:12] = (-0.9, -0.1, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 1.0 + self._walk(raw, state, (0.08, -0.28, 0.0), 0.18) + elif t < 805: + raw[5:12] = (-0.9, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 1.0 + elif t < 855: + raw[5:12] = (-0.7, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 1.0 + elif t < 905: + raw[5:12] = (-0.5, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 1.0 + elif t < 1020: + raw[5:12] = (-0.15, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + if t < 955: + raw[19] = 1.0 + elif t < 1090: + raw[5:12] = (-0.9, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1290: + raw[5:12] = (-0.8, -0.08, -0.3, 0.0, 0.0, 0.0, 0.0) + self._walk(raw, state, (0.12, 0.16, 0.0), 0.18) + elif t < 1340: + raw[5:12] = (-0.8, -0.08, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1370: + raw[5:12] = (-0.6, -0.08, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1400: + raw[5:12] = (-0.4, -0.08, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1475: + raw[5:12] = (-0.2, -0.08, -0.3, 0.5, 0.0, 0.0, 0.0) + if t >= 1430: + raw[19] = 1.0 + elif t < 1535: + raw[5:12] = (-0.9, -0.08, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 1.0 + else: + if t == 1535: + self.second_grip = bool(max(float(state[10]), float(state[11])) > -0.017) + if self.second_grip: + raw[19] = 1.0 + if t < 1750: + raw[5:12] = (-0.9, -0.08, -0.3, 0.5, 0.0, 0.0, 0.0) + self._walk(raw, state, (0.08, -0.28, 0.0), 0.18) + elif t < 1800: + raw[5:12] = (-0.9, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1840: + raw[5:12] = (-0.7, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1880: + raw[5:12] = (-0.5, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + elif t < 1970: + raw[5:12] = (-0.15, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + if t >= 1920: + raw[19] = 0.0 + else: + raw[5:12] = (-0.9, 0.3, -0.3, 0.5, 0.0, 0.0, 0.0) + raw[19] = 0.0 + else: + raw[5:12] = (-0.8, -0.08, -0.3, 0.0, 0.0, 0.0, 0.0) + return raw diff --git a/policies/move_two_plates/gpt6sol-s3/episodes.csv b/policies/move_two_plates/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..71bdab65fe3423970f6a037a293e7739eda7f505 --- /dev/null +++ b/policies/move_two_plates/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,374,terminated,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,349,terminated,0 +620025,0,2300,timeout,0 +620026,0,1040,terminated,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,1016,terminated,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,774,terminated,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,939,terminated,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,957,terminated,0 +620052,0,466,terminated,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,1650,terminated,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,1711,terminated,0 +620070,0,2300,timeout,0 +620071,0,1921,terminated,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,944,terminated,0 +620080,0,1858,terminated,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,653,terminated,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,959,terminated,0 +620099,0,797,terminated,0 diff --git a/policies/move_two_plates/gpt6sol-s3/policy.py b/policies/move_two_plates/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa9577b4a89b099d0229b7c11462e5ffc57a7c1 --- /dev/null +++ b/policies/move_two_plates/gpt6sol-s3/policy.py @@ -0,0 +1,41 @@ +import numpy as np +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32).copy();self.a[19:]=0 + self.stages=[] + def add(n,over=None,walk=None):self.stages.append((n,over or {},walk)) + for gy,py in [(.08,-.35),(.04,-.40)]: + add(80,walk=(.08,gy,.12)) + add(45,{5:-.2,6:.1,8:.25,10:0,19:0}) + add(45,{19:1}) + add(35,{5:-.4}) + add(55,{5:-.8}) + add(100,walk=(-.12,gy,.1)) + add(250,walk=(-.12,py,.09)) + add(120,walk=(.06,py,.09)) + add(40,{6:-.15}) + for h in [.66,.58,.54]:add(20,{2:h}) + add(40,{5:-.65,10:-.15}) + add(30,{19:0}) + add(50,{2:.74,5:-.8}) + add(80,walk=(-.12,py,.16)) + add(180,walk=(-.12,.04,.16)) + add(90,walk=(.08,.04,.16)) + self.idx=-1 + def act(self,obs,tools): + t=int(obs['t']);k=0;stage=len(self.stages)-1 + for j,(n,_,__) in enumerate(self.stages): + if t= len(self.stages): + raw = self.base.copy() + raw[0:2] = 0.0 + raw[3] = 0.0 + return raw + + name, target, grip, yt, duration, kind, pas, xs = self.stages[self.stage_index] + j = self.stage_step + p = obs["low_dim_obs"] + x, y, _, yaw = p[21:25] + raw = self.base.copy() + + source = kind in ("approach", "close", "lift", "recover_open", "recover_close") + if kind == "transfer": + xt = -0.10 + elif source: + xt = xs + self.x_bias[pas] + else: + xt = 0.10 + yt = yt + (self.y_bias[pas] if source else 0.0) + + vx = np.clip(1.8 * (xt - x), -0.18, 0.18) + vmax = 0.28 if kind == "transfer" else 0.18 + vy = np.clip(1.8 * (yt - y), -vmax, vmax) + if kind in ("approach", "close", "lift", "recover_open", "recover_close"): + bx, by = vx, vy + wz = np.clip(-1.5 * yaw, -0.3, 0.3) + else: + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * vx + s * vy, -s * vx + c * vy + wz = np.clip(-4.0 * yaw - 0.3 * p[49], -0.8, 0.8) + + if kind in ("transfer", "forward"): + pitch = -0.2 + elif kind == "lift": + pitch = -0.2 * min(1.0, (j + 1) / 50.0) + elif kind == "insert": + pitch = -0.2 + 0.2 * min(1.0, (j + 1) / 60.0) + else: + pitch = 0.0 + if kind == "lift": + height = 0.74 + 0.04 * min(1.0, (j + 1) / 50.0) + else: + height = 0.78 if kind == "transfer" else 0.74 + raw[:5] = [bx, by, height, wz, pitch] + if abs(raw[0]) < 0.06: + raw[0] = 0.0 + if abs(raw[1]) < 0.06: + raw[1] = 0.0 + + alpha = min(1.0, (j + 1) / 45.0) + raw[5:12] = self.q + (target - self.q) * alpha + raw[12:19] = 0.0 + raw[19] = self.grip + (grip - self.grip) * min(1.0, (j + 1) / 35.0) + raw[20] = 0.0 + + self.base = raw.copy() + self.stage_step += 1 + if self.stage_step >= duration: + # An unobstructed empty close is about -0.020 rad on both fingers. + # Give a missed plate one small repositioned retry before carrying. + if kind == "close" and not self.retried[pas]: + if float(np.mean(p[10:12])) < -0.017: + self.retried[pas] = True + self.x_bias[pas] += 0.015 + self.y_bias[pas] += 0.03 + retry = [ + (f"p{pas}_reopen", target, 0.0, yt, 60, "recover_open", pas, xs), + (f"p{pas}_reclose", target, 1.0, yt, 60, "recover_close", pas, xs), + ] + at = self.stage_index + 1 + self.stages[at:at] = retry + self.q = target.copy() + self.grip = grip + self.stage_index += 1 + self.stage_step = 0 + return raw diff --git a/policies/move_two_plates/kimi31pro-s2/episodes.csv b/policies/move_two_plates/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..217bf6c7f64c746d1da95cc6cfc319a68c762830 --- /dev/null +++ b/policies/move_two_plates/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,872,terminated,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,872,terminated,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,519,terminated,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,593,terminated,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/kimi31pro-s2/policy.py b/policies/move_two_plates/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d0d4adeca11a67e8309f9dfd6914b5ba321d560b --- /dev/null +++ b/policies/move_two_plates/kimi31pro-s2/policy.py @@ -0,0 +1,113 @@ +"""Deterministic hand-written controller for the two-plate rack transfer. + +The plate pair is grasped together near the middle of the source rack. The +base then translates beside the table with the arm and plate orientation held +fixed, which keeps the plates aligned with the target slots. +""" + +import numpy as np + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + APPROACH = np.array([-0.8, 0.1, 0.0, 0.4, 0.0, 0.4, 0.0]) + LIFT = np.array([-0.8, 0.1, 0.0, -0.2, 0.0, 1.0, 0.0]) + CARRY = np.array([-1.0, 0.1, 0.0, -0.2, 0.0, 1.2, 0.0]) + PLACE = np.array([-0.8, 0.1, 0.0, 0.4, 0.0, 0.4, 0.0]) + RETREAT = np.array([-0.8, 0.0, 0.0, 0.8, 0.0, 0.0, 0.0]) + + def reset(self, obs, tools): + self.arm = np.zeros(7, dtype=float) + self.phase = 0 + self.phase_step = 0 + self.phase_start = self.arm.copy() + self.phases = [ + {"kind": "base", "goal": (0.08, -0.07, 0.28), "steps": 240}, + {"kind": "arm", "target": self.APPROACH, "steps": 80, "grip": 0.0}, + {"kind": "arm", "target": self.APPROACH, "steps": 50, "grip": 1.0}, + {"kind": "arm", "target": self.LIFT, "steps": 80, "grip": 1.0}, + {"kind": "arm", "target": self.CARRY, "steps": 60, "grip": 1.0, "yaw": 0.28}, + {"kind": "base", "goal": (0.08, -0.52, 0.28), "steps": 250, + "arm": self.CARRY, "grip": 1.0}, + {"kind": "arm", "target": self.PLACE, "steps": 80, "grip": 1.0, "yaw": 0.28}, + {"kind": "arm", "target": self.PLACE, "steps": 50, "grip": 0.0, "yaw": 0.28}, + {"kind": "arm", "target": self.RETREAT, "steps": 60, "grip": 0.0, "yaw": 0.28}, + ] + + def _next_phase(self): + self.phase += 1 + self.phase_step = 0 + self.phase_start = self.arm.copy() + + @staticmethod + def _wrap(angle): + return (angle + np.pi) % (2.0 * np.pi) - np.pi + + def act(self, obs, tools): + raw = np.asarray(tools.hold_action(), dtype=float).copy() + if self.phase >= len(self.phases): + # Leave the released plates undisturbed while the success timer or + # the remainder of a failed episode elapses. + yaw = float(obs["low_dim_obs"][24]) + error = self._wrap(0.28 - yaw) + raw[:5] = [0.0, 0.0, 0.74, np.clip(1.2 * error, -0.15, 0.15), 0.0] + raw[5:12] = self.arm + raw[12:19] = 0.0 + raw[19:21] = [0.0, 0.6] + return raw + + spec = self.phases[self.phase] + low = obs["low_dim_obs"] + advance = False + + if spec["kind"] == "base": + goal = np.asarray(spec["goal"], dtype=float) + pos = low[21:24] + yaw = float(low[24]) + ex, ey = goal[:2] - pos[:2] + c, s = np.cos(yaw), np.sin(yaw) + vx, vy = c * ex + s * ey, -s * ex + c * ey + distance = float(np.hypot(vx, vy)) + if distance > 0.18: + vx, vy = vx / distance * 0.18, vy / distance * 0.18 + if distance < 0.012: + vx = vy = 0.0 + elif distance < 0.05 and distance > 0.0: + vx, vy = vx / distance * 0.07, vy / distance * 0.07 + yaw_error = self._wrap(goal[2] - yaw) + wz = (np.clip(1.5 * yaw_error, -0.45, 0.45) + if abs(yaw_error) >= 0.015 else 0.0) + raw[:5] = [vx, vy, 0.74, wz, 0.0] + if "arm" in spec: + raw[5:12] = spec["arm"] + raw[19] = spec["grip"] + else: + raw[5:12] = 0.0 + raw[19] = 0.6 + raw[12:19] = 0.0 + raw[20] = 0.6 + self.phase_step += 1 + arrived = (distance < 0.012 and abs(yaw_error) < 0.015 + and self.phase_step > 31) + advance = arrived or self.phase_step >= spec["steps"] + else: + j = self.phase_step + u = min(1.0, (j + 1) / max(1, spec["steps"] - 20)) + u = u * u * (3.0 - 2.0 * u) + self.arm = self.phase_start * (1.0 - u) + spec["target"] * u + wz = 0.0 + if "yaw" in spec: + yaw_error = self._wrap(spec["yaw"] - float(low[24])) + wz = (np.clip(1.2 * yaw_error, -0.15, 0.15) + if abs(yaw_error) > 0.012 else 0.0) + raw[:5] = [0.0, 0.0, 0.74, wz, 0.0] + raw[5:12] = self.arm + raw[12:19] = 0.0 + raw[19:21] = [spec["grip"], 0.6] + self.phase_step += 1 + advance = self.phase_step >= spec["steps"] + + if advance: + self._next_phase() + return raw diff --git a/policies/move_two_plates/kimi31pro-s3/episodes.csv b/policies/move_two_plates/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..00bc0c2d95ecf200affee6848b182a2ad1359d4a --- /dev/null +++ b/policies/move_two_plates/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,962,terminated,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,1251,terminated,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,1232,terminated,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,0,2300,timeout,0 +620056,0,2206,terminated,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,1139,terminated,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,0,2300,timeout,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/kimi31pro-s3/policy.py b/policies/move_two_plates/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f9de47ee0ccb8666b248eb422e52074e75d3114f --- /dev/null +++ b/policies/move_two_plates/kimi31pro-s3/policy.py @@ -0,0 +1,165 @@ +"""Hand-written sequential plate-transfer controller for the Unitree G1. + +The robot uses its left arm for both plates. The nearer plate is transferred +with an arm sweep. The remaining plate needs a deeper, wrist-corrected grasp; +it is carried by rotating the base and lowered by squatting. All motions are +joint-space interpolations with pelvis feedback, not a demonstration replay. +""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.left = np.asarray(obs["low_dim_obs"][3:10], dtype=np.float64).copy() + self.right = self.hold[12:19].astype(np.float64).copy() + self.lgrip = 0.0 + self.rgrip = 0.0 + self.height = 0.74 + self.pitch = 0.0 + self.base_x = 0.06 + self.base_y = 0.0 + self.base_yaw = 0.0 + + initial_left = self.hold[5:12].astype(np.float64) + pre = np.array([-.55, 0, 0, .55, 0, 0, 0.]) + near = np.array([-1., .45, 0, 1., 0, 0, 0.]) + nlift = np.array([-1.7, .45, 0, 1.7, 0, 0, 0.]) + nretreat = nlift.copy(); nretreat[1] = -.2; nretreat[4] = 1.57 + nplace = np.array([-.9, 0, -1.7, .9, 1.57, 0, 0.]) + nraise = np.array([-1.35, 0, -1.7, 1.35, 1.57, 0, 0.]) + far = np.array([-.926, .718, -.019, 1.056, -.05, .167, -.14]) + flift = np.array([-1.7, .8, 0, 1.85, 0, -.15, 0.]) + + # name, steps, ramp, left target, left gripper, right target, + # right gripper, height, pitch, base target. A tuple for pitch or + # height means interpolate from its first to its second value; a scalar + # is constant throughout the phase. + self.phases = [ + ("near_approach", 140, 70, pre, None, None, None, .74, .4, (0.06, 0., 0.)), + ("near_align", 100, 70, near, None, None, None, .74, .4, None), + ("near_close", 120, 70, None, 1., None, None, .74, .4, None), + ("near_lift", 130, 80, nlift, None, None, None, .74, .4, None), + ("near_retreat", 140, 100, nretreat, None, None, None, .74, (0.4, 0.), None), + ("near_place", 100, 70, nplace, None, None, None, .74, 0., (0.14, -0.15, 0.)), + ("near_release", 70, 30, None, 0., None, None, .74, 0., None), + ("near_raise", 70, 50, nraise, None, None, None, .74, 0., (0.14, -0.30, 0.)), + ("near_retract", 90, 65, pre, None, None, None, .74, 0., (0.06, 0., 0.)), + ("near_park", 100, 70, initial_left, None, None, None, .74, (0., .4), None), + ("far_approach", 140, 70, pre, None, None, None, .74, .4, (0.06, 0., 0.)), + ("far_align", 100, 70, far, None, None, None, .74, .4, None), + ("far_close", 120, 70, None, 1., None, None, .74, .4, None), + ("far_lift", 130, 80, flift, None, None, None, .74, .4, None), + ("far_carry", 240, 80, None, None, None, None, .74, .4, (0.06, 0., -0.7)), + ("far_squat", 100, 80, None, None, None, None, (.74, .65), .4, None), + ("far_release", 70, 30, None, 0., None, None, .65, .4, None), + ("far_settle", 100, 50, None, None, None, None, .65, .4, None), + ("stand", 140, 100, initial_left, None, None, None, (.65, .74), 0., (0.06, 0., 0.)), + ("hold", 100, 50, None, None, None, None, .74, 0., None), + ] + self.phase_index = -1 + self.phase_step = 0 + self.phase_name = "start" + self.center_offset = 0.0 + self._close_roll = self.left[1] + self._start_next_phase() + + def _start_next_phase(self): + self.phase_index += 1 + self.phase_step = 0 + if self.phase_index >= len(self.phases): + self.phase_index = len(self.phases) - 1 + self.phase_name = "finished" + return + p = self.phases[self.phase_index] + self.phase_name = p[0] + if p[0] in ("near_close", "far_close"): + self.center_offset = 0.0 + self._close_roll = self.left[1] + self._left0 = self.left.copy() + self._right0 = self.right.copy() + self._lgrip0 = self.lgrip + self._rgrip0 = self.rgrip + self._height0 = self.height + self._pitch0 = self.pitch + if p[9] is not None: + self.base_x, self.base_y, self.base_yaw = p[9] + # The approach deliberately requests torso pitch immediately, matching + # the stable low-reaching controller used in all later grasp phases. + if p[0] in ("near_approach", "far_approach"): + self.pitch = 0.4 + self._pitch0 = 0.4 + + @staticmethod + def _blend(a, b, u): + return (1.0 - u) * a + u * b + + def _base_servo(self, obs): + p = obs["low_dim_obs"][21:25] + ex, ey = self.base_x - p[0], self.base_y - p[1] + c, s = np.cos(p[3]), np.sin(p[3]) + vx = float(np.clip(2.2 * (c * ex + s * ey), -.3, .3)) + vy = float(np.clip(2.2 * (-s * ex + c * ey), -.3, .3)) + if abs(ex) < .012 and abs(ey) < .012: + vx = vy = 0.0 + else: + if 0 < abs(vx) < .06: + vx = np.sign(vx) * .06 + if 0 < abs(vy) < .06: + vy = np.sign(vy) * .06 + ye = (self.base_yaw - p[3] + np.pi) % (2 * np.pi) - np.pi + wz = float(np.clip(1.8 * ye, -.35, .35)) if abs(ye) > .015 else 0.0 + return vx, vy, wz + + def act(self, obs, tools): + if self.phase_name == "finished": + raw = self.hold.copy() + raw[5:12] = self.left + raw[12:19] = self.right + raw[19:21] = (self.lgrip, self.rgrip) + raw[2] = self.height + raw[4] = self.pitch + raw[0], raw[1], raw[3] = self._base_servo(obs) + return raw + + p = self.phases[self.phase_index] + _, n, ramp, lt, lg, rt, rg, height, pitch, _ = p + u = min(1.0, (self.phase_step + 1) / ramp) + if lt is not None: + self.left = self._blend(self._left0, lt, u) + if rt is not None: + self.right = self._blend(self._right0, rt, u) + if lg is not None: + self.lgrip = self._blend(self._lgrip0, lg, u) + if p[0] in ("near_close", "far_close"): + if self.phase_step >= 25: + f = obs["low_dim_obs"][10:12] + desired = float(np.clip(2.0 * (f[0] - f[1]), -.18, .18)) + self.center_offset = .9 * self.center_offset + .1 * desired + self.left[1] = self._close_roll + self.center_offset + elif p[0] in ("near_lift", "far_lift"): + self.left[1] += u * self.center_offset + if rg is not None: + self.rgrip = self._blend(self._rgrip0, rg, u) + if isinstance(height, tuple): + self.height = self._blend(self._height0, height[1], u) + else: + self.height = height + if isinstance(pitch, tuple): + self.pitch = self._blend(self._pitch0, pitch[1], u) + else: + self.pitch = pitch + + raw = self.hold.copy() + raw[5:12] = self.left + raw[12:19] = self.right + raw[19:21] = (self.lgrip, self.rgrip) + raw[2] = self.height + raw[4] = self.pitch + raw[0], raw[1], raw[3] = self._base_servo(obs) + + self.phase_step += 1 + if self.phase_step >= n: + self._start_next_phase() + return raw diff --git a/policies/move_two_plates/opus-s1/episodes.csv b/policies/move_two_plates/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6c1c09b929a7414f58ed783b2f2795cb1ca9ba44 --- /dev/null +++ b/policies/move_two_plates/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,1,1785,success,0 +620009,0,2300,timeout,0 +620010,0,2022,terminated,0 +620011,1,1609,success,0 +620012,1,1660,success,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,2300,timeout,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,1,1677,success,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,0,2300,timeout,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,0,2300,timeout,0 +620034,0,2300,timeout,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,0,2300,timeout,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,1,1747,success,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2248,terminated,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2229,terminated,0 +620065,0,2300,timeout,0 +620066,1,1656,success,0 +620067,0,2300,timeout,0 +620068,1,1624,success,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,0,2300,timeout,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,0,2300,timeout,0 +620091,1,2000,success,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,0,2300,timeout,0 +620096,0,2300,timeout,0 +620097,0,2170,terminated,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/opus-s1/policy.py b/policies/move_two_plates/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0cdb61c3cc30ca7412e2b3ac26dc5e2c30cd7f92 --- /dev/null +++ b/policies/move_two_plates/opus-s1/policy.py @@ -0,0 +1,807 @@ +"""Scripted policy for move_two_plates on the Unitree G1. + +Hand-written control: G1 arm forward kinematics + numeric IK, a head camera +model calibrated against the robot's own arms and the table edge, colour-based +detection of the dish racks and plates, and a sequential task script written +as a generator (one yielded action per control step). +""" + +import cv2 +import numpy as np +from scipy import ndimage +from scipy.optimize import least_squares + +# ---------------------------------------------------------------------------- +# kinematics (unitree g1_29dof URDF), pelvis frame + + +def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def rpy(r, p, y): + return rz(y) @ ry(p) @ rx(r) + + +AX = {'x': rx, 'y': ry, 'z': rz} + + +def T(R, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +def arm_chain(side): + s = 1.0 if side == 'L' else -1.0 + return [ + ((0.0039563, s * 0.10022, 0.24778), (s * 0.27931, 5.4949e-05, -s * 0.00019159), 'y'), + ((0.0, s * 0.038, -0.013831), (-s * 0.27925, 0, 0), 'x'), + ((0.0, s * 0.00624, -0.1032), (0, 0, 0), 'z'), + ((0.015783, 0, -0.080518), (0, 0, 0), 'y'), + ((0.100, s * 0.00188791, -0.010), (0, 0, 0), 'x'), + ((0.038, 0, 0), (0, 0, 0), 'y'), + ((0.046, 0, 0), (0, 0, 0), 'z'), + ] + + +CHAINS = {'L': [(T(rpy(*r), xyz), AX[ax]) for xyz, r, ax in arm_chain('L')], + 'R': [(T(rpy(*r), xyz), AX[ax]) for xyz, r, ax in arm_chain('R')]} + + +def torso_T(waist): + M = T(rz(waist[0]), (0, 0, 0)) + M = M @ T(rx(waist[1]), (-0.0039635, 0, 0.035)) + M = M @ T(ry(waist[2]), (0, 0, 0.019)) + return M + + +def fk(side, q, waist, tool=0.14): + M = torso_T(waist) + for (A, axf), qi in zip(CHAINS[side], q): + B = np.eye(4) + B[:3, :3] = axf(qi) + M = M @ A @ B + return M @ T(np.eye(3), (tool, 0, 0)) + + +LO = np.array([-3.0892, -0.05, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) +MIR = np.array([1, -1, -1, 1, -1, 1, -1]) +QN = np.array([-0.6, 0.15, 0.0, 0.2, 0.0, 0.6, 0.0]) + +# camera / torso model (calibrated) +CAM = np.array([0.0008, 0.0007, 0.411, 0.9462, 0.0002, 0.0002, 88.9724]) +P0, R0 = 0.0566, -0.0008 +TABLE_H = 0.6789 +W = 84 +RC = np.stack([[0, -1, 0], [0, 0, 1], [-1, 0, 0]], 1).astype(float) + + +def waist_of(o): + return (o[0], R0, P0) + + +def limits(side): + lo, hi = LO.copy(), HI.copy() + if side == 'R': + lo[1], hi[1] = -HI[1], -LO[1] + return lo + 1e-3, hi - 1e-3 + + +def tool_dirs(a, yaw=0.0): + d = np.array([np.cos(a) * np.cos(yaw), np.cos(a) * np.sin(yaw), -np.sin(a)]) + yv = np.array([-np.sin(yaw), np.cos(yaw), 0.0]) + return d, np.cross(d, yv) + + +def ik(side, p, a=0.0, yaw=0.0, q0=None, waist=(0, 0, 0), roll=0.0): + lo, hi = limits(side) + qn = QN if side == 'L' else QN * MIR + d, up = tool_dirs(a, yaw) + if roll != 0.0: + # tilt the jaws' up direction sideways: up = (0, sin r, cos r) for a level tool + jaw = np.array([-np.sin(yaw), np.cos(yaw), 0.0]) + up = np.cos(roll) * up + np.sin(roll) * jaw + p = np.asarray(p, float) + + qc = qn if q0 is None else np.asarray(q0, float) + + def res(q): + M = fk(side, q, waist) + return np.concatenate([M[:3, 3] - p, 0.3 * (M[:3, 0] - d), 0.3 * (M[:3, 2] - up), 0.004 * (q - qn), + 0.015 * (q - qc)]) + + best = None + for q_init in ([q0] if q0 is not None else []) + [qn]: + sol = least_squares(res, np.clip(q_init, lo, hi), bounds=(lo, hi)) + err = np.linalg.norm(fk(side, sol.x, waist)[:3, 3] - p) + if best is None or err < best[1] - 1e-4: + best = (sol.x, err) + return best + + +def world_to_rel(o, p): + return rz(-o[24]) @ (np.asarray(p, float) - np.array([o[21], o[22], o[23]])) + + +def rel_to_world(o, p): + return rz(o[24]) @ np.asarray(p, float) + np.array([o[21], o[22], o[23]]) + + +def cam_world(o): + x, y, z, pitch, yaw, roll, f = CAM + Tt = torso_T(waist_of(o)) + R = Tt[:3, :3] @ rpy(roll, pitch, yaw) @ RC + p = Tt[:3, :3] @ np.array([x, y, z]) + Tt[:3, 3] + Rz = rz(o[24]) + return Rz @ R, Rz @ p + np.array([o[21], o[22], o[23]]), f + + +def pix_ray(o, u, v): + R, p, f = cam_world(o) + return p, R @ np.array([(u - W / 2) / f, -(v - W / 2) / f, -1.0]) + + +def on_z(o, u, v, z): + p, d = pix_ray(o, u, v) + return p + (z - p[2]) / d[2] * d + + +def on_x(o, u, v, x): + p, d = pix_ray(o, u, v) + return p + (x - p[0]) / d[0] * d + + +# ---------------------------------------------------------------------------- +# perception + + +def bar_mask(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] + return (h >= 8) & (h <= 22) & (s > 60) & (v > 150) + + +def detect_bars(im, o): + m0 = bar_mask(im) + m = cv2.morphologyEx(m0.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((1, 5), np.uint8)).astype(bool) + lab, n = ndimage.label(m) + bars = [] + for i in range(1, n + 1): + ys, xs = np.nonzero(lab == i) + if len(xs) < 12 or xs.max() - xs.min() < 10: + continue + pts = [] + for c in range(xs.min(), xs.max() + 1): + rr = ys[xs == c] + if len(rr): + pts.append(on_z(o, c + 0.5, rr.max() + 1.0, TABLE_H + 0.02)) + pts = np.array(pts) + bars.append(dict(x=float(np.median(pts[:, 0])), y_lo=float(pts[:, 1].min()), y_hi=float(pts[:, 1].max()), + row=float(ys.mean()), c0=int(xs.min()), c1=int(xs.max()))) + return bars + + +PEG_DY = 0.0433 # peg pitch of the racks (7 pegs per bar) +PLATE_BIAS = 0.012 # head-camera plate estimates (upper part of the plate) read this much too far left + + +def peg_mask(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] + return (h >= 5) & (h <= 25) & (s > 50) & (v < 170) & (v > 40) + + +def detect_pegs(im, o, bar): + """world y of the pegs standing on a bar (dark brown columns just above it).""" + m = peg_mask(im) + r = int(round(bar['row'])) + prof = np.zeros(W) + for rr in range(max(0, r - 5), max(0, r - 1)): + prof += m[rr] + ys = [] + c = max(0, bar['c0'] - 2) + while c <= min(W - 1, bar['c1'] + 2): + if prof[c] >= 2: + c1 = c + while c1 + 1 < W and prof[c1 + 1] >= 2: + c1 += 1 + cc = float(np.average(np.arange(c, c1 + 1), weights=prof[c:c1 + 1])) + ys.append(on_x(o, cc + 0.5, r - 2.5, bar['x'] + 0.01)[1]) + c = c1 + 1 + else: + c += 1 + return ys + + +def grid_phase(ys): + """phase (mod PEG_DY) of a set of peg y's, robust circular mean.""" + if not ys: + return None + ang = 2 * np.pi * np.asarray(ys) / PEG_DY + z = np.exp(1j * ang) + m = np.angle(z.mean()) + # reject outliers and recompute + keep = np.abs(np.angle(z * np.exp(-1j * m))) < 1.2 + if keep.sum() >= 2: + m = np.angle(z[keep].mean()) + return m / (2 * np.pi) * PEG_DY + + +def snap_slot(y, phase): + """nearest slot centre (half way between pegs).""" + if phase is None: + return y + c = phase + PEG_DY / 2 + return c + np.round((y - c) / PEG_DY) * PEG_DY + + +def merge_pegs(pegs, tol=0.02): + """merge detections from both bars into peg positions (descending).""" + ps = sorted(pegs, reverse=True) + out = [] + for p in ps: + if out and out[-1][-1] - p < tol: + out[-1].append(p) + else: + out.append([p]) + return [float(np.mean(g)) for g in out if len(g) >= 1] + + +def rack_slots(pegs): + """all 6 slot centres (descending y) from partially detected pegs: fit a regular 7-peg grid.""" + ps = merge_pegs(pegs) if pegs else [] + if len(ps) < 2: + return None + d = -np.diff(ps) + pitch = float(np.clip(np.median(d[d < 0.065]) if np.any(d < 0.065) else 0.045, 0.040, 0.049)) + # integer index of each peg relative to the first + k = np.round((ps[0] - np.asarray(ps)) / pitch) + # least squares y = a - pitch_f * k + A = np.stack([np.ones_like(k), -k], 1) + a, pf = np.linalg.lstsq(A, np.asarray(ps), rcond=None)[0] + if not (0.040 <= pf <= 0.049): + pf = pitch + a = float(np.mean(np.asarray(ps) + pf * k)) + kmax = int(k.max()) + # the grid has 7 pegs; if fewer detected, extend towards the side with room + return a, pf, kmax + + +PITCH = 0.0442 +RETRY_DY = 0.012 # a failed grasp is retried this much further right (plates lean that way) +LINE_BIAS = 0.015 +MAX_LEAN = 0.45 # rad # on-axis head-camera plate line reads this much too far left + + +def vote_phase(pegs, pitch=PITCH, tol=0.005): + """grid phase (peg positions = phase + k*pitch) by voting; robust to spurious pegs.""" + ps = np.asarray(pegs, float) + if len(ps) < 2: + return None, 0 + best = (None, -1) + for ph in np.arange(0.0, pitch, 0.0005): + r = (ps - ph + pitch / 2) % pitch - pitch / 2 + score = np.sum(np.abs(r) < tol) - 0.01 * np.sum(np.minimum(np.abs(r), tol)) + if score > best[1]: + best = (ph, score) + # refine: mean residual of inliers + ph = best[0] + r = (ps - ph + pitch / 2) % pitch - pitch / 2 + inl = np.abs(r) < tol + ph = ph + r[inl].mean() + return ph, int(inl.sum()) + + +def plate_slots(ys, pegs, bar): + """snap plate estimates to slot centres of the source rack.""" + base = [y - PLATE_BIAS for y in ys] + if not pegs: + return base + ph, n = vote_phase(pegs) + if ph is None or n < 3: + return base + out = [] + for y in base: + c = ph + PITCH / 2 + out.append(c + np.round((y - c) / PITCH) * PITCH) + if len(out) == 2 and abs(out[0] - out[1]) < 0.5 * PITCH: + # both snapped into one slot: split by raw order + out[1] = out[0] - PITCH + return out + + +def target_slots(pegs): + """left-most and right-most slot centres of the target rack.""" + ps = merge_pegs(pegs) if pegs else [] + if len(ps) >= 2: + pitch = np.clip(np.median(-np.diff(ps)), 0.038, 0.05) + else: + pitch = 0.045 + if len(ps) == 7: + ytop, ybot = ps[0], ps[-1] + elif len(ps) >= 2: + # anchor on the end whose neighbour spacing looks regular + ytop = ps[0] + ybot = ytop - 6 * pitch + if ps[-1] < ybot - 0.02: + ybot = ps[-1] + ytop = ybot + 6 * pitch + else: + ytop, ybot = -0.15, -0.42 + pitch = (ytop - ybot) / 6 + # slots 1 and 4 of 0..5: inner slots, pegs on both sides of each plate + return ytop - 1.5 * pitch, ybot + 2.5 * pitch, ytop, ybot + + +def plate_cols(im, r0=2, r1=18): + f = im.astype(float) + sat = f.max(2) - f.min(2) + g = f.mean(2) + bg = np.median(g[r0:r1], axis=1, keepdims=True) + m = (np.abs(g[r0:r1] - bg) > 18) & (sat[r0:r1] < 30) + prof = m.sum(0) + groups = [] + for c in range(W): + if prof[c] > 5: + if groups and c - groups[-1][-1] <= 2: + groups[-1].append(c) + else: + groups.append([c]) + return [(float(np.average(g_, weights=prof[g_])), int(prof[g_].sum()), g_[0], g_[-1]) for g_ in groups] + + +def world_to_pix(o, P): + R, p, f = cam_world(o) + Pc = R.T @ (np.asarray(P, float) - p) + return W / 2 + f * Pc[0] / -Pc[2], W / 2 - f * Pc[1] / -Pc[2] + + +def plate_line(im, o, y_rough, front_x, r0=2, r1=26, win=7): + """Fit the edge-on plate seen near the image axis (col = a + b*row) and return the plate's y + at the grasp point (rim in front of the front bar at GRASP_Z), or None.""" + f = im.astype(float) + sat = f.max(2) - f.min(2) + g = f.mean(2) + c_exp = world_to_pix(o, [front_x + 0.06, y_rough, 0.93])[0] + pts = [] + for r in range(r0, r1): + m = (np.abs(g[r] - np.median(g[r])) > 18) & (sat[r] < 30) + cols = np.nonzero(m)[0] + cols = cols[np.abs(cols - c_exp) <= win] + if len(cols) == 0: + continue + # contiguous run containing the column nearest the expectation + c0 = cols[np.argmin(np.abs(cols - c_exp))] + run = [c0] + while run[-1] + 1 in cols: + run.append(run[-1] + 1) + while run[0] - 1 in cols: + run.insert(0, run[0] - 1) + if len(run) <= 6: + pts.append((r, float(np.mean(run)))) + if len(pts) < 6: + return None + pts = np.array(pts) + a = np.polyfit(pts[:, 0], pts[:, 1], 1) + res = np.abs(np.polyval(a, pts[:, 0]) - pts[:, 1]) + keep = res < 1.5 + if keep.sum() >= 6: + a = np.polyfit(pts[keep, 0], pts[keep, 1], 1) + xr = front_x - 0.05 + rg = world_to_pix(o, [xr, y_rough, GRASP_Z])[1] + cg = np.polyval(a, rg) + return float(on_x(o, cg + 0.5, rg + 0.5, xr)[1]), float(a[0]), len(pts) + + +def plate_lean(im, o, y_rough, front_x, r0=2, r1=26, win=8): + """Lean of the plate seen roughly on-axis: returns (theta, y at grasp height, n points) or None. + theta > 0: the plate's top leans towards +y (plate up direction = (0, sin, cos)).""" + f = im.astype(float) + sat = f.max(2) - f.min(2) + g = f.mean(2) + c_exp = world_to_pix(o, [front_x + 0.06, y_rough, 0.93])[0] + pts = [] + for r in range(r0, r1): + m = (np.abs(g[r] - np.median(g[r])) > 18) & (sat[r] < 30) + cols = np.nonzero(m)[0] + cols = cols[np.abs(cols - c_exp) <= win] + if len(cols) == 0: + continue + c0 = cols[np.argmin(np.abs(cols - c_exp))] + run = [c0] + while run[-1] + 1 in cols: + run.append(run[-1] + 1) + while run[0] - 1 in cols: + run.insert(0, run[0] - 1) + if len(run) <= 9: + pts.append((r, float(np.mean(run)))) + if len(pts) < 8: + return None + pts = np.array(pts) + a = np.polyfit(pts[:, 0], pts[:, 1], 1) + res = np.abs(np.polyval(a, pts[:, 0]) - pts[:, 1]) + keep = res < 1.5 + if keep.sum() >= 8: + a = np.polyfit(pts[keep, 0], pts[keep, 1], 1) + best = None + p1 = np.array([front_x + 0.06, y_rough, 0.88]) + c1, r1_ = world_to_pix(o, p1) + for th in np.linspace(-0.6, 0.6, 121): + c2, r2 = world_to_pix(o, p1 + 0.1 * np.array([0, np.sin(th), np.cos(th)])) + s = (c2 - c1) / (r2 - r1_) + if best is None or abs(s - a[0]) < best[0]: + best = (abs(s - a[0]), th) + xr = front_x - 0.05 + rg = world_to_pix(o, [xr, y_rough, GRASP_Z])[1] + yg = float(on_x(o, np.polyval(a, rg) + 0.5, rg + 0.5, xr)[1]) + return float(best[1]), yg, len(pts) + + +def plate_estimates(im, o, front): + """y of the plates (left to right) seen from the look pose; a wide blob is two adjacent plates.""" + groups = [g for g in plate_cols(im) if g[1] >= 25] + groups.sort(key=lambda g: -g[1]) + if len(groups) >= 2: + cs = [groups[0][0], groups[1][0]] + elif len(groups) == 1: + c, w, c0, c1 = groups[0] + cs = [c0 + 2.0, c1 - 2.0] if c1 - c0 >= 7 else [c] + else: + cs = [] + return sorted([on_x(o, cc + 0.5, 10.5, front + 0.04)[1] for cc in cs], reverse=True) + + +# ---------------------------------------------------------------------------- +# base control + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +def base_cmd(o, target, kp=2.2, kyaw=1.5, vmax=0.4, tol=0.015): + x, y, yaw = o[21], o[22], o[24] + dx, dy = target[0] - x, target[1] - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * dx + s * dy, -s * dx + c * dy + vx, vy = kp * bx, kp * by + sp = np.hypot(vx, vy) + if sp > vmax: + vx, vy = vx * vmax / sp, vy * vmax / sp + dist = np.hypot(bx, by) + sp = np.hypot(vx, vy) + if dist < tol: + vx = vy = 0.0 + elif sp < 0.07: + vx, vy = vx * 0.07 / sp, vy * 0.07 / sp + e = wrap(target[2] - yaw) + wz = 0.0 if abs(e) < 0.02 else float(np.clip(kyaw * e, -0.5, 0.5)) + return vx, vy, wz, dist + + +# ---------------------------------------------------------------------------- +# policy + +READY_REL = {'L': np.array([0.13, 0.24, 0.05]), 'R': np.array([0.13, -0.24, 0.05])} # tucked: clear of the plates while walking +STAND_X = 0.17 +LOOK_X = 0.12 +HAND_DY = 0.16 # lateral offset of the working hand from the pelvis +GRASP_Z = 0.83 +LIFT_Z = 1.0 +GRASP_DX = 0.0 # tool (0.14) x at the detected front bar: rim ~5 cm inside the fingers +CLEAR_DZ = 0.12 # vertical lift that takes a plate's foot above the pegs (tops ~0.76 m) +PULL_DX = 0.03 # then pull the plate back towards the robot, off the rack +SLOT_DY_L = 0.008 # set each plate down against the peg it would otherwise lean onto: +SLOT_DY_R = -0.010 # the left-hand plate leans to +y once released, the right-hand one to -y +PLACE_DX = 0.0 # set the plate down a little deeper than it was picked (it tends to rotate forward in the grip) +DROP_DZ = 0.02 # release this far above the pick-up height: the plate drops into the slot +RELEASE_GRIP = 0.3 # open fully when letting go (a finger left touching the plate counts as holding it) +PRE_GRIP = 0.6 # half-open gripper (~4.4 cm) so the fingers fit between adjacent plates + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.log = [] + self.snaps = [] + self.zgrasp = {'L': GRASP_Z - 0.013, 'R': GRASP_Z - 0.013} + self.roll = {'L': 0.0, 'R': 0.0} + self.t = 0 + self.done = False + self.q = {} + self.grip = {'L': 0.0, 'R': 0.0} + for side in 'LR': + self.q[side] = ik(side, READY_REL[side], 0.0, 0.0, waist=(0, R0, P0))[0] + self.gen = self.main() + + def act(self, obs, tools): + self.obs = obs + self.tools = tools + self.t = int(obs.get('t', 0)) + if self.done: + return self.action() + try: + return next(self.gen) + except Exception: # StopIteration, or anything unexpected: keep holding still + self.done = True + return self.action() + + # -- helpers + def o(self): + return np.asarray(self.obs['low_dim_obs'], float) + + def action(self, v=(0.0, 0.0, 0.0)): + a = np.zeros(21, np.float32) + a[0], a[1], a[3] = v[0], v[1], v[2] + a[2] = 0.74 + a[4] = 0.0 + a[5:12] = self.q['L'] + a[12:19] = self.q['R'] + a[19] = self.grip['L'] + a[20] = self.grip['R'] + return a + + def hold(self, n): + for _ in range(n): + yield self.action() + + def goto(self, tgt, maxk=400, settle=25, tol=0.025): + for k in range(maxk): + vx, vy, wz, dist = base_cmd(self.o(), tgt, tol=tol * 0.6) + if dist < tol and abs(wrap(tgt[2] - self.o()[24])) < 0.04 and k > 10: + break + yield self.action((vx, vy, wz)) + yield from self.hold(settle) + + def tip_world(self, side, q=None, tool=0.10): + o = self.o() + sl = slice(3, 10) if side == 'L' else slice(12, 19) + q = o[sl] if q is None else q + return rel_to_world(o, fk(side, q, waist_of(o), tool)[:3, 3]) + + def approach(self, side, y, z, x0, x1, speed=0.0018, near=None): + """advance the tool (0.14 point) along +x at (y, z) until contact; returns True on contact.""" + pel0 = self.o()[21].copy() + x = x0 + lag_n = 0 + near = x1 - 0.14 if near is None else near + while x < x1: + x = min(x1, x + 2 * speed) + self.set_hand_world(side, [x, y, z]) + yield from self.hold(2) + cmd = self.tip_world(side, self.q[side]) + meas = self.tip_world(side) + lag = cmd[0] - meas[0] + pushed = (pel0 - self.o()[21]) > 0.04 and meas[0] > near and lag > 0.01 + lag_n = lag_n + 1 if (lag > 0.022 and meas[0] > near) else 0 + if lag_n >= 2 or pushed: + self.log.append(('contact', round(float(meas[0]), 3), round(float(lag), 3), bool(pushed), self.t)) + # hold the hand where it is + self.set_hand_world(side, [meas[0] + 0.04 + 0.005, y, z]) + return True + return False + + def set_hand_world(self, side, p, a=0.0, yaw=0.0, roll=None): + o = self.o() + roll = self.roll[side] if roll is None else roll + q, err = ik(side, world_to_rel(o, p), a, yaw - o[24], q0=self.q[side], waist=waist_of(o), roll=roll) + self.q[side] = q + return err + + def move_hand(self, side, p0, p1, steps, per=4): + """straight line in world from p0 to p1 over `steps` waypoints, `per` control steps each.""" + for i in range(1, steps + 1): + p = np.asarray(p0) + (np.asarray(p1) - np.asarray(p0)) * i / steps + self.set_hand_world(side, p) + yield from self.hold(per) + + def hand_world(self, side): + o = self.o() + sl = slice(3, 10) if side == 'L' else slice(12, 19) + return rel_to_world(o, fk(side, o[sl], waist_of(o))[:3, 3]) + + def look(self, tag): + im = self.tools.image('head') + o = self.o() + self.snaps.append((tag, self.t, im, o.copy())) + return im, o + + def move_hands(self, targets, steps, per=4): + """move several hands along straight world lines together. targets: {side: (p0, p1)}""" + for i in range(1, steps + 1): + for side, (p0, p1) in targets.items(): + p = np.asarray(p0, float) + (np.asarray(p1, float) - np.asarray(p0, float)) * i / steps + self.set_hand_world(side, p) + yield from self.hold(per) + + def rack_info(self, im, o, want_left): + bars = [b for b in detect_bars(im, o) if ((b['y_lo'] + b['y_hi']) / 2 > 0) == want_left] + if not bars: + return None, None, bars + front = dict(min(bars, key=lambda b: b['x'])) + if len(bars) == 1 and front['x'] > 0.54: + front['x'] -= 0.115 # only the back bar was seen + pegs = [] + for b in bars: + pegs += detect_pegs(im, o, b) + return front, pegs, bars + + def grasp(self, side, y, front_x, tries=2, pre=0.0, away=0.0, lean=0.0): + """grasp the plate standing at y (rim facing the robot); returns (ok, tip x at grasp). + lean: the plate's sideways lean; the jaws are rolled to match and rolled back after lifting.""" + gi = 50 if side == 'L' else 51 + self.roll[side] = lean + y0 = y + for attempt in range(tries): + y = y0 - RETRY_DY * attempt + self.grip[side] = pre + p_pre = np.array([front_x - 0.14, y, GRASP_Z]) + hp = self.hand_world(side) + yield from self.move_hand(side, hp, p_pre, 6, 4) + yield from self.hold(15) + yield from self.approach(side, y, GRASP_Z, p_pre[0], front_x + GRASP_DX, near=front_x - 0.075) + tip = self.tip_world(side) + self.zgrasp[side] = float(self.hand_world(side)[2]) + self.grip[side] = 1.0 + yield from self.hold(25) + ok = self.o()[gi] < 0.97 + self.log.append(('grasp', side, attempt, round(float(y), 3), bool(ok), round(float(tip[0] - front_x), 3), self.t)) + if ok: + break + self.grip[side] = 0.0 + yield from self.hold(10) + # lean the plate away from its neighbour, lift it slowly straight out of the slot, + # pull it back off the rack, then raise it to carrying height + hp = self.hand_world(side) + p1 = np.array([hp[0], y + away, hp[2]]) + p2 = p1 + [0, 0, CLEAR_DZ] + p3 = p2 + [-PULL_DX, 0, 0] + p4 = np.array([p3[0], p3[1], LIFT_Z]) + yield from self.move_hand(side, hp, p1, 5, 3) + yield from self.move_hand(side, p1, p2, 16, 5) + yield from self.move_hand(side, p2, p3, 10, 5) + # clear of the rack: roll the plate upright while raising it to carrying height + for i in range(1, 11): + self.roll[side] = lean * (1 - i / 10) + self.set_hand_world(side, p3 + (p4 - p3) * i / 10) + yield from self.hold(5) + return ok, tip[0] - front_x + + def refine(self, y, fx, tag): + """walk the head camera in front of a plate and measure its y at the grasp point.""" + yield from self.goto((LOOK_X, y, 0.0), settle=12, tol=0.02, maxk=200) + im, o = self.look('ref' + tag) + r = plate_line(im, o, y + LINE_BIAS, fx) + out = y + if r is not None and abs(r[0] - LINE_BIAS - y) < 0.03: + out = r[0] - LINE_BIAS + self.log.append(('refine', tag, round(float(y), 4), None if r is None else round(r[0] - LINE_BIAS, 4), round(float(out), 4))) + return out + + def look_lean(self, y, fx, tag): + """on-axis look at a plate: returns (y at grasp height, lean angle).""" + yield from self.goto((LOOK_X, y, 0.0), settle=12, tol=0.02, maxk=200) + im, o = self.look('lean' + tag) + r = plate_lean(im, o, y + LINE_BIAS, fx) + yo, th = y, 0.0 + if r is not None: + th = float(np.clip(r[0], -MAX_LEAN, MAX_LEAN)) + if abs(r[1] - LINE_BIAS - y) < 0.03: + yo = r[1] - LINE_BIAS + self.log.append(('lean', tag, round(float(y), 4), None if r is None else (round(np.degrees(r[0]), 1), round(r[1] - LINE_BIAS, 4)), round(float(yo), 4))) + return yo, th + + # -- task + def main(self): + yield from self.hold(10) + # 0. look at the target rack while the hands are still empty + yield from self.goto((LOOK_X, -0.28, 0.0), settle=15, tol=0.015, maxk=250) + im, o = self.look('dst') + front, pegs, bars = self.rack_info(im, o, False) + tx = front['x'] if front else 0.47 + sL, sR, ytop, ybot = target_slots(pegs) + self.log.append(('dst', round(tx, 3), round(float(ytop), 3), round(float(ybot), 3), round(float(sL), 3), round(float(sR), 3))) + # 1. look at the source rack + yield from self.goto((LOOK_X, 0.21, 0.0), settle=15, tol=0.015, maxk=250) + im, o = self.look('src') + front, pegs, bars = self.rack_info(im, o, True) + fx = front['x'] if front else 0.49 + phase = grid_phase(pegs) if pegs and len(pegs) >= 3 else None + ys = plate_estimates(im, o, fx) + ys_s = plate_slots(ys, pegs, front) + self.log.append(('src', round(fx, 3), np.round(ys, 3).tolist(), np.round(ys_s, 3).tolist(), phase)) + if len(ys_s) < 2: + ys_s = (ys_s + [ys_s[0] - 2 * PEG_DY] if ys_s else [0.25, 0.20]) + yA, yB = ys_s[0], ys_s[1] + close = yA - yB < 0.07 + # 2. left hand takes the left plate (after an on-axis look at it) + if abs(yA - o[22]) > 0.06: + yA = yield from self.refine(yA, fx, 'A') + self.sx_src = float(np.clip(fx - 0.30, 0.13, 0.22)) + yield from self.goto((self.sx_src, yA - HAND_DY, 0.0), settle=15) + okA, dA = yield from self.grasp('L', yA, fx, pre=PRE_GRIP if close else 0.0, away=0.015) + # 3. right hand takes the other one (left arm stays fixed in the body frame); look at it + # on-axis first: without its neighbour it may now lean + yB, leanB = yield from self.look_lean(yB, fx, 'B') + yield from self.goto((self.sx_src, yB + HAND_DY, 0.0), settle=15) + okB, dB = yield from self.grasp('R', yB, fx, lean=leanB) + # 4. carry both to the target rack + sL, sR = sL + SLOT_DY_L, sR + SLOT_DY_R + ymid = 0.5 * (sL + sR) + yield from self.goto((float(np.clip(tx - 0.30, 0.13, 0.23)), ymid, 0.0), settle=15) + # 5. place both + xL = tx + dA + 0.04 + PLACE_DX + xR = tx + dB + 0.04 + PLACE_DX + hL, hR = self.hand_world('L'), self.hand_world('R') + yield from self.move_hands({'L': (hL, [xL, sL, LIFT_Z]), 'R': (hR, [xR, sR, LIFT_Z])}, 12, 5) + yield from self.hold(10) + # lower each plate until its (measured) height is a little above where it was picked up + tgt = {'L': [xL, sL, LIFT_Z], 'R': [xR, sR, LIFT_Z]} + stop = {'L': False, 'R': False} + # fast down to a few cm above the pick-up height, then slowly until the rack takes the + # plate's weight (the arm stops sagging: measured-minus-commanded height rises) + for side in 'LR': + tgt[side][2] = self.zgrasp[side] + 0.05 + yield from self.move_hands({'L': ([xL, sL, LIFT_Z], list(tgt['L'])), 'R': ([xR, sR, LIFT_Z], list(tgt['R']))}, 12, 5) + yield from self.hold(10) + lags = {'L': [], 'R': []} + cnt = {'L': 0, 'R': 0} + for k in range(90): + for side in 'LR': + if stop[side]: + continue + lag = self.hand_world(side)[2] - self.tip_world(side, self.q[side], 0.14)[2] + lags[side].append(lag) + base = np.median(lags[side][:8]) if len(lags[side]) >= 8 else None + cnt[side] = cnt[side] + 1 if (base is not None and lag - base > 0.01) else 0 + if cnt[side] >= 2 or tgt[side][2] < self.zgrasp[side] - 0.05: + stop[side] = True + tgt[side][2] = self.hand_world(side)[2] + 0.004 + self.set_hand_world(side, tgt[side]) + continue + tgt[side][2] -= 0.0015 + self.set_hand_world(side, tgt[side]) + if stop['L'] and stop['R']: + break + yield from self.hold(2) + self.log.append(('lowered', round(self.hand_world('L')[2] - self.zgrasp['L'], 3), + round(self.hand_world('R')[2] - self.zgrasp['R'], 3), self.t)) + yield from self.hold(15) + # open slowly: snapping the fingers open flicks the plates sideways + for i in range(1, 41): + self.grip['L'] = self.grip['R'] = 1.0 - (1.0 - RELEASE_GRIP) * i / 40 + yield from self.hold(1) + yield from self.hold(15) + # ease the open fingers off the rims, then keep still: the plates must stand untouched + self.grip['L'] = self.grip['R'] = 0.0 + yield from self.hold(10) + hL, hR = list(tgt['L']), list(tgt['R']) + tgt = {'L': [hL[0] - 0.10, hL[1], hL[2] + 0.005], 'R': [hR[0] - 0.10, hR[1], hR[2] + 0.005]} + yield from self.move_hands({'L': (hL, tgt['L']), 'R': (hR, tgt['R'])}, 15, 3) + yield from self.hold(80) + self.grip['L'] = 0.0 + self.grip['R'] = 0.0 + yield from self.hold(10) + hL, hR = list(tgt['L']), list(tgt['R']) + yield from self.move_hands({'L': (hL, [hL[0] - 0.14, hL[1], hL[2] + 0.02]), + 'R': (hR, [hR[0] - 0.14, hR[1], hR[2] + 0.02])}, 20, 5) + yield from self.hold(20) + for side in 'LR': + self.q[side] = ik(side, READY_REL[side], 0.0, 0.0, q0=self.q[side], waist=(0, R0, P0))[0] + while True: + yield self.action() diff --git a/policies/move_two_plates/opus-s2/episodes.csv b/policies/move_two_plates/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4ff7fdc91066ffb257c9352068650a5552edbe22 --- /dev/null +++ b/policies/move_two_plates/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,778,success,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,0,2300,timeout,0 +620009,0,2300,timeout,0 +620010,0,2300,timeout,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,0,2300,timeout,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,0,628,terminated,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,0,2300,timeout,0 +620022,0,2300,timeout,0 +620023,0,2300,timeout,0 +620024,0,2300,timeout,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,1,786,success,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,2300,timeout,0 +620032,0,2300,timeout,0 +620033,1,907,success,0 +620034,0,2300,timeout,0 +620035,1,777,success,0 +620036,0,2300,timeout,0 +620037,1,863,success,0 +620038,0,2300,timeout,0 +620039,1,787,success,0 +620040,0,2300,timeout,0 +620041,0,2300,timeout,0 +620042,0,2300,timeout,0 +620043,0,2300,timeout,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,1,788,success,0 +620047,0,2300,timeout,0 +620048,0,2300,timeout,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,2300,timeout,0 +620052,1,787,success,0 +620053,0,2300,timeout,0 +620054,0,2300,timeout,0 +620055,1,885,success,0 +620056,0,2300,timeout,0 +620057,0,2300,timeout,0 +620058,0,2300,timeout,0 +620059,0,2300,timeout,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,0,2300,timeout,0 +620063,0,2300,timeout,0 +620064,0,2300,timeout,0 +620065,1,807,success,0 +620066,0,2300,timeout,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,646,terminated,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,1,857,success,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,0,2300,timeout,0 +620081,1,857,success,0 +620082,0,2300,timeout,0 +620083,0,2300,timeout,0 +620084,0,2300,timeout,0 +620085,0,2300,timeout,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,1,808,success,0 +620091,0,2300,timeout,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,1,877,success,0 +620095,1,836,success,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,2300,timeout,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/opus-s2/policy.py b/policies/move_two_plates/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b053f1c40eb8399a03440e93572961a606c5e8af --- /dev/null +++ b/policies/move_two_plates/opus-s2/policy.py @@ -0,0 +1,475 @@ +"""Move both plates from the left dish rack to the right dish rack (Unitree G1). + +Hand-written script: head-camera perception of racks/plates (colour masks), approximate +arm kinematics with a resolved-rate / IK Cartesian controller, wrist-camera alignment +before grasping, walking with closed-loop odometry. +""" + +import cv2 +import numpy as np +from scipy import ndimage +from scipy.optimize import least_squares + +# ----------------------------------------------------------------------------- kinematics + + +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _T(R, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +_AX = {'x': _rx, 'y': _ry, 'z': _rz} + + +def _chain(side): + s = 1 if side == 'L' else -1 + return [ + ((0.0039563, s * 0.10022, 0.23778), (s * 0.27931, 0, 0), 'y'), + ((0, s * 0.038, -0.013831), (-s * 0.27925, 0, 0), 'x'), + ((0, s * 0.00624, -0.1032), (0, 0, 0), 'z'), + ((0.015783, 0, -0.080518), (0, 0, 0), 'y'), + ((0.100, s * 0.00188791, -0.010), (0, 0, 0), 'x'), + ((0.038, 0, 0), (0, 0, 0), 'y'), + ((0.046, 0, 0), (0, 0, 0), 'z'), + ] + + +_CH = {'L': _chain('L'), 'R': _chain('R')} +_FIX = {side: [_T(_rz(r[2]) @ _ry(r[1]) @ _rx(r[0]), p) for (p, r, ax) in _CH[side]] for side in 'LR'} +GA = np.arctan2(0.117, 0.155) +TIP = np.array([0.155, 0.0, -0.117]) +RG = _ry(GA) + + +def arm_fk(q, side): + M = np.eye(4) + for F, (p, r, ax), qi in zip(_FIX[side], _CH[side], q): + R = np.eye(4) + R[:3, :3] = _AX[ax](qi) + M = M @ F @ R + return M + + +def grip_pose(q, side): + M = arm_fk(q, side) + return M[:3, 3] + M[:3, :3] @ TIP, M[:3, :3] @ RG + + +_LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def limits(side): + lo, hi = _LO.copy(), _HI.copy() + if side == 'R': + lo[1], hi[1] = -2.2515, 1.5882 + return lo, hi + + +MIRROR = np.array([1, -1, -1, 1, -1, 1, -1.0]) + + +def ik_grip(side, pos, gx, gy, q0, w_ori=1.0, w_ref=0.05, w_gx=1.0): + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-3, hi - 1e-3) + + def res(q): + p, R = grip_pose(q, side) + return np.concatenate([p - pos, w_gx * w_ori * (R[:, 0] - gx), w_ori * (R[:, 1] - gy), w_ref * (q - q0)]) + + s = least_squares(res, q0, bounds=(lo, hi)) + p, _ = grip_pose(s.x, side) + return s.x, float(np.linalg.norm(p - pos)) + + +def down_frame(): + """gripper axis along torso -z, closing axis along torso y""" + return np.array([0, 0, -1.0]), np.array([0, 1.0, 0]) + + +# ----------------------------------------------------------------------------- perception + + +def _hsv(im): + return cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + + +def rack_mask(im): + hsv = _hsv(im) + return (hsv[..., 0] >= 3) & (hsv[..., 0] <= 25) & (hsv[..., 1] >= 55) & (hsv[..., 2] >= 60) + + +def find_rack(im, ymax=55, xlim=(0, 84)): + m = rack_mask(im) + m[ymax:, :] = False + m[:, :xlim[0]] = False + m[:, xlim[1]:] = False + m = ndimage.binary_closing(m, np.ones((3, 3))) + lab, n = ndimage.label(m) + if n == 0: + return None + sizes = ndimage.sum(m, lab, range(1, n + 1)) + k = int(np.argmax(sizes)) + 1 + if sizes[k - 1] < 30: + return None + ys, xs = np.nonzero(lab == k) + return dict(x0=int(xs.min()), x1=int(xs.max()), y0=int(ys.min()), y1=int(ys.max()), + cx=float(xs.mean()), cy=float(ys.mean()), n=len(xs), mask=(lab == k)) + + +def gray_mask(im): + hsv = _hsv(im) + return (hsv[..., 1] <= 4) & (hsv[..., 2] >= 40) + + +def head_plates(im): + """plate columns in a band just above the left rack. returns rack, list of (col, weight)""" + rk = find_rack(im) + if rk is None: + return None, [] + m = gray_mask(im) + m[rk['y1'] + 1:] = False + m[:, :max(0, rk['x0'] - 12)] = False + m[:, min(84, rk['x1'] + 12):] = False + band = m[max(0, rk['y0'] - 12):rk['y0'] + 1] + cols = band.sum(0) + lab, n = ndimage.label(cols >= 2) + comps = [] + for k in range(1, n + 1): + xs = np.nonzero(lab == k)[0] + w = cols[xs] + if w.sum() >= 6: + a, b = max(0, xs.min() - 3), min(84, xs.max() + 4) + sub = m[:rk['y0'] + 1, a:b] + ys_, xs_ = np.nonzero(sub) + ytop = ys_.min() + utop = float(xs_[ys_ <= ytop + 1].mean()) + a + comps.append([float(np.average(xs, weights=w)), float(w.sum()), int(xs.min()), int(xs.max()), utop, int(ytop)]) + return rk, comps + + +def wrist_plates(im): + """plate regions in a wrist image looking down: list of (col_center, col_min, col_max, npix)""" + m = gray_mask(im) + hsv = _hsv(im) + m &= hsv[..., 2] >= 70 + m[:, :3] = False + m[:, 81:] = False + m = ndimage.binary_opening(m, np.ones((3, 2))) + colsum = m[5:75].sum(0) + lab, n = ndimage.label(colsum >= 4) + out = [] + for k in range(1, n + 1): + xs = np.nonzero(lab == k)[0] + w = colsum[xs] + if w.sum() >= 40: + out.append((float(np.average(xs, weights=w)), int(xs.min()), int(xs.max()), int(w.sum()))) + return out + + +# ----------------------------------------------------------------------------- constants + +PITCH = -0.2 +P0 = (0.0, 0.2) # perception stance for the left rack +P1 = (0.0, -0.3) # perception stance for the right rack +KU = 150.0 # px per metre, lateral, at rack distance from P0/P1 +KV = 80.0 # px per metre, depth (rack centre row) +FPX = 80.0 # px per rad (head camera yaw) +# linearisation reference: image column REF_U / rack row REF_CY <-> offset (REF_TX, REF_TY) from the pelvis +REF_U, REF_CY, REF_TX, REF_TY = 40.4, 28.2, 0.498, 0.04 +GRASP_X = 0.35 # stance: plate this far ahead of the pelvis +PRE_Z, GRASP_Z, LIFT_Z = 0.10, 0.035, 0.20 +PLACE_Z = 0.045 +SINGLE_Z = 0.025 # grasp height for a lone (possibly leaning) plate +PAIR_Z = 0.17 # wrist-camera alignment height above a plate pair +TILT_X0, TILT_K = 0.36, 8.0 # gripper tilts forward (about the plate normal) beyond this reach +BACKOFF = 0.12 # step back from the counter before walking between the racks +MAX_SPREAD = 0.0 # plates further apart than this need two stances (single stance proved unreliable) +RACK_DX = 0.0 +WRIST_KPX = 500.0 # wrist-camera px per metre lateral at pre-grasp height +PAIR_DIST = 0.065 # plates closer than this are pinched together +PLACE_SEP = 0.035 # lateral offset of each plate from the rack centre (two-hand case) +PRE_Q = np.array([-1.86, 0.09, 0.98, 1.39, 0.3, 1.26, 0.45]) +MID_Q = np.array([-1.0, 0.2, 0.3, 1.0, 0.3, 1.2, 0.3]) +CARRY_Q = np.array([-2.42, 0.612, 0.908, 1.72, 0.255, 1.614, 0.477]) # gripper ~(0.27, 0.15, 0.27), pointing down + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.h = np.asarray(tools.hold_action(), dtype=float).copy() + self.h[4] = PITCH + self.h[5:19] = 0.0 + self.h[19:21] = 0.0 + self.log = [] + self.gen = self.script() + + # ------------------------------------------------------------------ helpers (generators) + def lo(self): + return np.asarray(self.obs['low_dim_obs'], float) + + def mark(self, name): + self.log.append(('t', name, int(self.obs['t']))) + if getattr(self, 'debug', False): + self.snaps.append((name, [self.tools.image(c) for c in ('head', 'left_wrist', 'right_wrist')])) + + def hold(self, n): + for _ in range(n): + yield self.h.copy() + + def _arm_sched(self, moves): + """generator applying joint interpolations (side, q, n) one after another to self.h""" + for side, q, n in moves: + sl = slice(5, 12) if side == 'L' else slice(12, 19) + q0 = self.h[sl].copy() + for i in range(1, n + 1): + self.h[sl] = q0 + (np.asarray(q) - q0) * i / n + yield + + def walk_to(self, xt, yt, yawt, n=300, tol=0.015, vmax=0.35, arm=(), loose=0.03, loose_after=120): + sched = self._arm_sched(arm) + arm_done = False + for i in range(n): + if not arm_done: + arm_done = next(sched, 'end') == 'end' + l = self.lo() + x, y, yaw = l[21], l[22], l[24] + ex, ey = xt - x, yt - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + eyaw = (yawt - yaw + np.pi) % (2 * np.pi) - np.pi + if abs(bx) < tol and abs(by) < tol and abs(eyaw) < 0.03: + break + if i > loose_after and abs(bx) < loose and abs(by) < loose and abs(eyaw) < 0.06: + break + vx = np.clip(2.0 * bx, -vmax, vmax) + vy = np.clip(2.0 * by, -vmax, vmax) + sp = np.hypot(vx, vy) + if 0 < sp < 0.07: + vx, vy = vx / sp * 0.07, vy / sp * 0.07 + if abs(bx) < tol and abs(by) < tol: + vx = vy = 0.0 + wz = np.clip(2 * eyaw, -0.5, 0.5) + if abs(eyaw) < 0.03: + wz = 0.0 + a = self.h.copy() + a[0], a[1], a[3] = vx, vy, wz + yield a + self.log.append(('walk', i, round(float(bx), 3), round(float(by), 3), round(float(eyaw), 3))) + while not arm_done: + arm_done = next(sched, 'end') == 'end' + yield self.h.copy() + + def joint_move(self, side, q, n): + for _ in self._arm_sched([(side, q, n)]): + yield self.h.copy() + + def cart_steps(self, side, pos, step=0.02, w_gx=1.0): + """list of joint vectors along a straight gripper path from the commanded pose""" + sl = slice(5, 12) if side == 'L' else slice(12, 19) + gx, gy = down_frame() + q = self.h[sl].copy() + p0, _ = grip_pose(q, side) + pos = np.asarray(pos, float) + ns = max(1, int(np.ceil(np.linalg.norm(pos - p0) / step))) + out = [] + for i in range(1, ns + 1): + p = p0 + (pos - p0) * i / ns + a = float(np.clip((p[0] - TILT_X0) * TILT_K, 0.0, 0.6)) # tilt forward to reach far + gx = np.array([np.sin(a), 0.0, -np.cos(a)]) + q, e = ik_grip(side, p, gx, gy, q, w_gx=w_gx) + out.append(q) + self.log.append(('ik', side, [round(float(v), 3) for v in pos], round(e, 3))) + return out + + def cart_path(self, side, pos, step=0.02, n_step=8, n_final=20, w_gx=1.0): + sl = slice(5, 12) if side == 'L' else slice(12, 19) + for q in self.cart_steps(side, pos, step, w_gx): + q0 = self.h[sl].copy() + for i in range(1, n_step + 1): + self.h[sl] = q0 + (q - q0) * i / n_step + yield self.h.copy() + yield from self.hold(n_final) + + def torso_xy(self, wx, wy): + l = self.lo() + dx, dy = wx - l[21], wy - l[22] + c, s = np.cos(l[24]), np.sin(l[24]) + return c * dx + s * dy, -s * dx + c * dy + + # ------------------------------------------------------------------ perception helpers + def pix_world(self, u, v): + """world (x, y) of an image column u / rack-centre row v, linearised about the reference""" + l = self.lo() + u0 = u - (l[24] + l[0]) * FPX + wy = l[22] + REF_TY - (u0 - REF_U) / KU + wx = l[21] + REF_TX - (v - REF_CY) / KV + return wx, wy + + def plate_targets(self): + im = self.tools.image('head') + rk, comps = head_plates(im) + if rk is None or not comps: + return None + res = [] + for c in comps: + px, py = self.pix_world(c[0], rk['cy']) + _, pyt = self.pix_world(c[4], rk['cy']) + res.append([px, py, c[1], c[2], c[3], pyt]) + self.log.append(('plates', rk['cx'], rk['cy'], comps, self.lo()[21:25].tolist())) + return res + + def rack_target(self): + im = self.tools.image('head') + rk = find_rack(im) + if rk is None: + return None + self.log.append(('rack', rk['cx'], rk['cy'], rk['x0'], rk['x1'], self.lo()[21:25].tolist())) + return self.pix_world(rk['cx'], rk['cy']) + + # ------------------------------------------------------------------ skills + def wrist_align_pair(self, side, tx, ty): + cam = 'left_wrist' if side == 'L' else 'right_wrist' + for it in range(3): + wp = wrist_plates(self.tools.image(cam)) + self.log.append(('wrist', side, it, [tuple(round(v, 1) for v in w) for w in wp])) + if len(wp) < 2: + break + wp.sort(key=lambda w: abs(w[0] - 41.5)) + if abs(wp[1][0] - wp[0][0]) > 35: + break + err = 0.5 * (wp[0][0] + wp[1][0]) - 41.5 + if abs(err) < 3: + break + ty += float(np.clip(-err / WRIST_KPX, -0.04, 0.04)) + yield from self.cart_path(side, [tx, ty, PAIR_Z], n_final=12) + self.wy_final = ty + + def wrist_align_single(self, side, tx, ty): + cam = 'left_wrist' if side == 'L' else 'right_wrist' + for it in range(2): + wp = wrist_plates(self.tools.image(cam)) + self.log.append(('wrist1', side, it, [tuple(round(v, 1) for v in w) for w in wp])) + if not wp: + break + wp.sort(key=lambda w: abs(w[0] - 41.5)) + u = wp[0][0] + err = u - 41.5 + if abs(err) < 3: + break + ty += float(np.clip(-err / WRIST_KPX, -0.04, 0.04)) + yield from self.cart_path(side, [tx, ty, PRE_Z], n_final=12) + self.wy_final = ty + + def grasp_arm(self, side, px, py, mode): + """robot already at a stance: raise arm, go above plate, (align), descend, grip, lift""" + gi = 19 if side == 'L' else 20 + m = 1.0 if side == 'L' else MIRROR + self.mark('grasp' + side) + sl = slice(5, 12) if side == 'L' else slice(12, 19) + if np.abs(self.h[sl] - PRE_Q * m).max() > 0.05: + yield from self.joint_move(side, MID_Q * m, 25) + yield from self.joint_move(side, PRE_Q * m, 25) + tx, ty = self.torso_xy(px, py) + yield from self.cart_path(side, [tx, ty, PAIR_Z if mode == 'pair' else PRE_Z], step=0.03, n_step=8, n_final=12) + self.wy_final = ty + if mode == 'pair': + yield from self.wrist_align_pair(side, tx, ty) + ty = self.wy_final + self.mark('descend' + side) + yield from self.cart_path(side, [tx, ty, GRASP_Z if mode == 'pair' else SINGLE_Z], step=0.025, n_step=8, n_final=12) + self.h[gi] = 1.0 + yield from self.hold(25) + l = self.lo() + self.log.append(('fingers', side, l[10:12].tolist() if side == 'L' else l[19:21].tolist())) + yield from self.cart_path(side, [tx - 0.03, ty, LIFT_Z], step=0.03, n_step=7, n_final=3) + self.mark('lifted' + side) + + def place(self, side, wx, wy, retreat_q): + gi = 19 if side == 'L' else 20 + tx, ty = self.torso_xy(wx, wy) + yield from self.cart_path(side, [tx, ty, LIFT_Z], step=0.03, n_step=8, n_final=10) + yield from self.cart_path(side, [tx, ty, PLACE_Z], step=0.015, n_step=8, n_final=15) + self.mark('placed' + side) + self.h[gi] = 0.0 + yield from self.hold(25) + self.mark('released' + side) + yield from self.cart_path(side, [tx - 0.02, ty, LIFT_Z], step=0.03, n_step=7, n_final=3) + if retreat_q is not None: + yield from self.joint_move(side, retreat_q, 25) + + # ------------------------------------------------------------------ main script + def script(self): + yield from self.walk_to(P1[0], P1[1], 0.0, tol=0.015) + yield from self.hold(15) + rt = self.rack_target() + if rt is None: + rt = (REF_TX, P1[1] + REF_TY) + wx, wy = rt + wx += RACK_DX + yield from self.walk_to(P0[0], P0[1], 0.0, tol=0.01) + yield from self.hold(15) + plates = self.plate_targets() + if not plates: + plates = [[REF_TX, P0[1] + REF_TY, 1, 0, 0, P0[1] + REF_TY]] + plates.sort(key=lambda p: -p[1]) # left first + if len(plates) >= 2 and plates[0][1] - plates[-1][1] < PAIR_DIST: + groups = [[float(np.mean([p[0] for p in plates])), float(np.mean([p[1] for p in plates])), 'pair']] + elif len(plates) >= 2: + groups = [[plates[0][0], plates[0][5], 'single'], [plates[-1][0], plates[-1][5], 'single']] + else: + groups = [[plates[0][0], plates[0][1], 'pair']] + self.log.append(('groups', groups)) + if len(groups) == 1: + # both plates pinched together by the left hand in one trip + px, py = groups[0][0], groups[0][1] + yield from self.walk_to(px - GRASP_X, py - 0.02, 0.0, arm=[('L', MID_Q, 30), ('L', PRE_Q, 30)]) + yield from self.grasp_arm('L', px, py, groups[0][2]) + self.mark('to_rack') + yield from self.walk_to(wx - GRASP_X, wy, 0.0, tol=0.015, loose=0.045, loose_after=60) + yield from self.hold(10) + yield from self.place('L', wx, wy, MID_Q) + else: + # two trips with the left hand: right slot first, then left slot + slots = [wy - PLACE_SEP, wy + PLACE_SEP] + for k in range(2): + px, py = groups[k][0], groups[k][1] + # keep the arm low at the side while crossing between racks, raise it near the end + if k == 0: + arm = [('L', MID_Q, 30), ('L', PRE_Q, 30)] + else: + # back away from the counter before crossing over to the left rack + arm = [('L', PRE_Q, 30)] + yield from self.walk_to(px - GRASP_X - BACKOFF, py - 0.02, 0.0, tol=0.04, loose=0.06, loose_after=80) + yield from self.walk_to(px - GRASP_X, py - 0.02, 0.0, arm=arm) + yield from self.grasp_arm('L', px, py, 'single') + self.mark('to_rack') + yield from self.walk_to(wx - GRASP_X, slots[k] - 0.02, 0.0, tol=0.015, loose=0.045, loose_after=60) + yield from self.hold(10) + # after the first plate keep the arm raised (clear of racks) for the walk back + yield from self.place('L', wx, slots[k], None if k == 0 else MID_Q) + self.mark('done') + while True: + yield from self.hold(50) + + def act(self, obs, tools): + self.obs = obs + return next(self.gen) diff --git a/policies/move_two_plates/opus-s3/episodes.csv b/policies/move_two_plates/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..cf8d28919f4e2d8e1c9173eda119c8f10ecf3db7 --- /dev/null +++ b/policies/move_two_plates/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2300,timeout,0 +620001,0,2300,timeout,0 +620002,0,2300,timeout,0 +620003,0,2300,timeout,0 +620004,0,2300,timeout,0 +620005,0,2300,timeout,0 +620006,0,2300,timeout,0 +620007,0,2300,timeout,0 +620008,1,1048,success,0 +620009,0,2300,timeout,0 +620010,0,1660,terminated,0 +620011,0,2300,timeout,0 +620012,0,2300,timeout,0 +620013,0,2300,timeout,0 +620014,1,1119,success,0 +620015,0,2300,timeout,0 +620016,0,2300,timeout,0 +620017,0,2300,timeout,0 +620018,1,1019,success,0 +620019,0,2300,timeout,0 +620020,0,2300,timeout,0 +620021,1,1906,success,0 +620022,1,1017,success,0 +620023,1,1789,success,0 +620024,0,1762,terminated,0 +620025,0,2300,timeout,0 +620026,0,2300,timeout,0 +620027,1,1905,success,0 +620028,0,2300,timeout,0 +620029,0,2300,timeout,0 +620030,0,2300,timeout,0 +620031,0,1838,terminated,0 +620032,0,2300,timeout,0 +620033,1,1061,success,0 +620034,1,1045,success,0 +620035,0,2300,timeout,0 +620036,0,2300,timeout,0 +620037,1,1040,success,0 +620038,0,2300,timeout,0 +620039,0,2300,timeout,0 +620040,0,2300,timeout,0 +620041,1,1808,success,0 +620042,0,2300,timeout,0 +620043,0,734,terminated,0 +620044,0,2300,timeout,0 +620045,0,2300,timeout,0 +620046,0,2300,timeout,0 +620047,1,1860,success,0 +620048,1,1966,success,0 +620049,0,2300,timeout,0 +620050,0,2300,timeout,0 +620051,0,1918,terminated,0 +620052,0,2300,timeout,0 +620053,0,2300,timeout,0 +620054,0,1962,terminated,0 +620055,0,2300,timeout,0 +620056,0,2300,timeout,0 +620057,0,748,terminated,0 +620058,1,1157,success,0 +620059,0,1840,terminated,0 +620060,0,2300,timeout,0 +620061,0,2300,timeout,0 +620062,1,1917,success,0 +620063,0,1913,terminated,0 +620064,1,1061,success,0 +620065,1,1856,success,0 +620066,0,1778,terminated,0 +620067,0,2300,timeout,0 +620068,0,2300,timeout,0 +620069,0,2300,timeout,0 +620070,0,2300,timeout,0 +620071,0,2300,timeout,0 +620072,0,2300,timeout,0 +620073,0,2300,timeout,0 +620074,0,2300,timeout,0 +620075,0,2300,timeout,0 +620076,0,2300,timeout,0 +620077,0,2300,timeout,0 +620078,0,2300,timeout,0 +620079,0,2300,timeout,0 +620080,1,1882,success,0 +620081,0,1610,terminated,0 +620082,0,2300,timeout,0 +620083,1,1906,success,0 +620084,1,1128,success,0 +620085,0,1851,terminated,0 +620086,0,2300,timeout,0 +620087,0,2300,timeout,0 +620088,0,2300,timeout,0 +620089,0,2300,timeout,0 +620090,1,974,success,0 +620091,0,1733,terminated,0 +620092,0,2300,timeout,0 +620093,0,2300,timeout,0 +620094,0,2300,timeout,0 +620095,1,1066,success,0 +620096,0,2300,timeout,0 +620097,0,2300,timeout,0 +620098,0,1735,terminated,0 +620099,0,2300,timeout,0 diff --git a/policies/move_two_plates/opus-s3/policy.py b/policies/move_two_plates/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1db5265f79a44f693912a1cb50932426f57bd059 --- /dev/null +++ b/policies/move_two_plates/opus-s3/policy.py @@ -0,0 +1,509 @@ +"""Scripted two-plate transfer for the G1: left rack -> right rack. + +Structure: the episode is a generator (`_run`) that yields one action per +control step. Geometry comes from + * an approximate G1 arm kinematic model (URDF numbers) + numeric IK, + * the head camera (pinhole model) to locate both racks at t=0, + * the wrist cameras to centre the gripper over a plate rim before grasping. +""" + +import numpy as np + +# ----------------------------------------------------------------------------- kinematics + + +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _T(R, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +_AX = {'x': _rx, 'y': _ry, 'z': _rz} +_LEFT = [ + ((0.0039563, 0.10022, 0.24778), (0.27931, 5.4949e-05, -0.00019159), 'y'), + ((0, 0.038, -0.013831), (-0.27925, 0, 0), 'x'), + ((0, 0.00624, -0.1032), (0, 0, 0), 'z'), + ((0.015783, 0, -0.080518), (0, 0, 0), 'y'), + ((0.100, 0.00188791, -0.010), (0, 0, 0), 'x'), + ((0.038, 0, 0), (0, 0, 0), 'y'), + ((0.046, 0, 0), (0, 0, 0), 'z'), +] + + +def _chain(side): + out = [] + for (x, y, z), (r, p, yy), ax in _LEFT: + if side == 'right': + y, r, yy = -y, -r, -yy + R = _rz(yy) @ _ry(p) @ _rx(r) + out.append((_T(R, [x, y, z]), _AX[ax])) + return out + + +_CH = {'left': _chain('left'), 'right': _chain('right')} +TOOL = 0.15 + + +def torso_T(waist): + return (_T(_rz(waist[0]), [0, 0, 0]) @ _T(_rx(waist[1]), [-0.0039635, 0, 0.035]) + @ _T(_ry(waist[2]), [0, 0, 0.019])) + + +def fk(q, side, waist, tool=TOOL): + M = torso_T(waist) + for qi, (Tj, axf) in zip(q, _CH[side]): + M = M @ Tj + M[:3, :3] = M[:3, :3] @ axf(qi) + M = M.copy() + M[:3, 3] = M[:3, 3] + M[:3, 0] * tool + return M + + +_LO = np.array([-3.0892, 0.0, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) + 0.05 +_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) - 0.05 +LIM = {'left': (_LO, _HI), + 'right': (np.r_[_LO[0], -2.2515 + 0.05, _LO[2:]], np.r_[_HI[0], -0.05, _HI[2:]])} + + +def _rotvec(Re): + return 0.5 * np.array([Re[2, 1] - Re[1, 2], Re[0, 2] - Re[2, 0], Re[1, 0] - Re[0, 1]]) + + +def ik(p, R, q0, side, waist, iters=15, w_rot=0.3): + q = np.array(q0, dtype=float) + lo, hi = LIM[side] + for _ in range(iters): + M = fk(q, side, waist) + err = np.r_[p - M[:3, 3], w_rot * _rotvec(R @ M[:3, :3].T)] + if np.linalg.norm(err) < 1e-5: + break + J = np.zeros((6, 7)) + for i in range(7): + dq = np.zeros(7) + dq[i] = 1e-5 + M2 = fk(q + dq, side, waist) + J[:3, i] = (M2[:3, 3] - M[:3, 3]) / 1e-5 + J[3:, i] = w_rot * _rotvec(M2[:3, :3] @ M[:3, :3].T) / 1e-5 + dq = J.T @ np.linalg.solve(J @ J.T + 1e-3 * np.eye(6), err) + q = np.clip(q + np.clip(dq, -0.3, 0.3), lo, hi) + return q + + +# ----------------------------------------------------------------------------- head camera + +CAM = (0.0576235, 0.01753, 0.42987, 0.8307767 + 0.22) +FOVY = 62.0 +Y_BIAS = -0.035 # head-camera lateral bias measured against the wrist camera / grasps + + +def unproject(uv, z_pel, waist=(0, 0, 0.055), W=84): + cx, cy, cz, pitch = CAM + Mc = torso_T(waist) @ _T(_ry(pitch), [cx, cy, cz]) + f = (W / 2) / np.tan(np.radians(FOVY) / 2) + d = Mc[:3, :3] @ np.array([1.0, (W / 2 - uv[0]) / f, (W / 2 - uv[1]) / f]) + o = Mc[:3, 3] + t = (z_pel - o[2]) / d[2] + return o + t * d + + +def brown(im): + g = im.astype(int) + r, gg, b = g[..., 0], g[..., 1], g[..., 2] + return (r - b > 35) & (r > gg) & (gg > b) + + +def racks_t0(im): + """Front-bar row and inner end column of the left and right rack in the t=0 head image.""" + m = brown(im)[:40] + has = m.sum(0) > 0 + best, gap, u = (30, 50), 0, 0 + while u < 84: + if not has[u]: + s = u + while u < 84 and not has[u]: + u += 1 + if s > 0 and u < 84 and u - s > gap: + gap, best = u - s, (s, u) + else: + u += 1 + out = {} + for name, sl in (('left', slice(0, best[0])), ('right', slice(best[1], 84))): + mm = np.zeros_like(m) + mm[:, sl] = m[:, sl] + rows = mm.sum(1) + if rows.max() == 0: + out[name] = None + continue + thr = 0.5 * rows.max() + vb = max(i for i in range(40) if rows[i] >= thr) + band = mm[max(0, vb - 1):vb + 2] + us = np.nonzero(band.any(0))[0] + end = us.max() + 1.0 if name == 'left' else float(us.min()) + out[name] = (end, vb + 0.5) + return out + + +# ----------------------------------------------------------------------------- wrist camera + + +def rim_columns(im, v0=15, v1=84, thr=215, min_rows=6): + """(u, weight) of bright, near-vertical plate-rim highlights.""" + m = (im.astype(int).min(2) > thr)[v0:v1] + cnt = m.sum(0) + out, u = [], 0 + while u < len(cnt): + if cnt[u] >= 2: + s = u + while u < len(cnt) and cnt[u] >= 2: + u += 1 + seg = cnt[s:u] + tot = seg.sum() + if tot >= min_rows: + out.append((float((np.arange(s, u) * seg).sum() / tot), int(tot), u - s)) + else: + u += 1 + return out + + +def cluster_plates(dets, y_end, gap=0.035, min_w=60): + """Group rim detections (world y, weight) into plates; return plate y's sorted ascending.""" + dets = sorted([d for d in dets if y_end - 0.02 < d[0] < y_end + 0.32], key=lambda d: d[0]) + groups = [] + for y, w, _ in dets: + if groups and y - groups[-1][-1][0] < gap: + groups[-1].append((y, w)) + else: + groups.append([(y, w)]) + out = [] + for g in groups: + w = np.array([x[1] for x in g], dtype=float) + if w.sum() >= min_w: + out.append((float(np.dot(w, [x[0] for x in g]) / w.sum()), float(w.sum()))) + out = sorted(out, key=lambda o: -o[1]) + return sorted(o[0] for o in out[:2]), [o[0] for o in out[2:3]] + + +# ----------------------------------------------------------------------------- policy + +GR = _ry(0.15) # gripper orientation: pointing forward, pitched 0.15 rad down +U0 = 41.0 # wrist-image column of the gripper centre +PX_PER_M = 350.0 # wrist-image scale at the pre-grasp height (px per m) +Z_PRE = 0.25 # tool height (pelvis frame) above the plates +Z_SCAN = 0.27 +Z_CARRY = 0.30 +Z_GRASP = 0.125 +Z_PLACE = 0.14 +G_OPEN = 0.5 # pre-grasp opening +REACH = 0.14 # lateral tool offset from the pelvis used for grasp/place +X_BASE = 0.42 # plate x minus pelvis x at the work pose +CARRY_YAW = 1.2 # hand yaw while walking: plate plane close to the walking direction +PLATE_DX = 0.035 # plate x relative to the detected front bar +SLOT_DY = {'right': -0.20, 'left': -0.11} # target slots from the right rack's inner end +CARRY_OUT = 0.04 # hands move outward by this while carrying +RIGHT_TUCK = (0.18, -0.22, 0.12) # idle right-hand tool position (pelvis frame) +X_BACK = 0.10 # base set-back while walking between the racks +PAIR_SEP = 0.065 # plates closer than this are grasped together directly +NEST_DY = 0.02 # set the moved plate down this far on the -y side of the other plate's rim +Z_NEST = 0.13 # tool height at which the moved plate is released +PAIR_OFF = 0.012 # pair grasp centre relative to the outer plate's rim + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.a = np.asarray(tools.hold_action(), dtype=np.float64).copy() + self.q = {'left': np.zeros(7), 'right': np.zeros(7)} + self.qi = {'left': np.zeros(7), 'right': np.zeros(7)} + self.R = {'left': GR, 'right': GR} + self.log = [] + self.dbg = [] + self.gen = self._run() + + def act(self, obs, tools): + self.obs = obs + try: + a = next(self.gen) + except Exception: # finished (StopIteration) or an unexpected failure: stand still + self.gen = self._idle() + a = next(self.gen) + return np.asarray(a, dtype=np.float32) + + # ------------------------------------------------------------------ low level + @property + def l(self): + return self.obs['low_dim_obs'] + + def qobs(self, side): + return self.l[3:10] if side == 'left' else self.l[12:19] + + def _arms(self): + for side, sl in (('left', slice(5, 12)), ('right', slice(12, 19))): + e = self.q[side] - self.qobs(side) + self.qi[side] = np.clip(self.qi[side] + 0.05 * e, -0.15, 0.15) + self.a[sl] = self.q[side] + self.qi[side] + + def _step(self): + self._arms() + return self.a.copy() + + def _idle(self): + self.finished = True + while True: + self.a[0] = self.a[1] = self.a[3] = 0.0 + yield self._step() + + def hold(self, n): + for _ in range(n): + yield self._step() + + def to_pel(self, pw): + x, y, yaw = self.l[21], self.l[22], self.l[24] + dx, dy = pw[0] - x, pw[1] - y + c, s = np.cos(yaw), np.sin(yaw) + return np.array([c * dx + s * dy, -s * dx + c * dy, pw[2]]) + + def to_world(self, pp): + x, y, yaw = self.l[21], self.l[22], self.l[24] + c, s = np.cos(yaw), np.sin(yaw) + return np.array([x + c * pp[0] - s * pp[1], y + s * pp[0] + c * pp[1], pp[2]]) + + def tool_cmd(self, side): + return fk(self.q[side], side, self.l[0:3])[:3, 3] + + def tool_meas(self, side): + return fk(self.qobs(side), side, self.l[0:3])[:3, 3] + + def move(self, side, p_pel, n, R=None): + p0 = self.tool_cmd(side) + R = self.R[side] if R is None else R + p_pel = np.asarray(p_pel, dtype=float) + for k in range(1, n + 1): + p = p0 + (p_pel - p0) * k / n + self.q[side] = ik(p, R, self.q[side], side, self.l[0:3]) + yield self._step() + + def move_w(self, side, pw, n): + yield from self.move(side, self.to_pel(pw), n) + + def rel(self, side, d, n): + yield from self.move(side, self.tool_cmd(side) + np.asarray(d), n) + + def rotate(self, side, yaw, n, d=(0, 0, 0)): + """Turn the hand to yaw (about vertical, relative to GR) while shifting by d.""" + p0 = self.tool_cmd(side) + p1 = p0 + np.asarray(d) + y0 = np.arctan2(self.R[side][1, 0], self.R[side][0, 0]) + for k in range(1, n + 1): + f = k / n + R = _rz(y0 + (yaw - y0) * f) @ GR + self.q[side] = ik(p0 + (p1 - p0) * f, R, self.q[side], side, self.l[0:3], iters=20) + yield self._step() + self.R[side] = _rz(yaw) @ GR + + def grip(self, side, g, n=30): + self.a[19 if side == 'left' else 20] = g + yield from self.hold(n) + + def walk(self, tx, ty, vmax=0.2, acc=0.006, tol=0.015, tries=2, maxn=260): + for t in range(tries): + if t > 0 and np.hypot(tx - self.l[21], ty - self.l[22]) < 1.5 * tol: + break + vprev = np.zeros(2) + for _ in range(maxn): + x, y, yaw = self.l[21], self.l[22], self.l[24] + ex, ey = tx - x, ty - y + eyaw = (-yaw + np.pi) % (2 * np.pi) - np.pi + if np.hypot(ex, ey) < tol and abs(eyaw) < 0.06: + break + c, s = np.cos(yaw), np.sin(yaw) + v = 2.5 * np.array([c * ex + s * ey, -s * ex + c * ey]) + n = np.linalg.norm(v) + if n > vmax: + v *= vmax / n + if 1e-6 < n < 0.07: + v *= 0.07 / n + dv = v - vprev + dn = np.linalg.norm(dv) + if dn > acc: + v = vprev + dv * acc / dn + vprev = v + self.a[0], self.a[1] = v + self.a[3] = np.clip(2.0 * eyaw, -0.5, 0.5) + yield self._step() + self.a[0] = self.a[1] = self.a[3] = 0.0 + yield from self.hold(20) + + def gstate(self, side): + return self.l[50] if side == 'left' else self.l[51] + + # ------------------------------------------------------------------ perception + def locate_racks(self): + im = self.tools.image('head') + r = racks_t0(im) + res = {} + for name in ('left', 'right'): + if r[name] is None: + res[name] = None + continue + p = self.to_world(unproject(r[name], 0.065, self.l[0:3])) + res[name] = np.array([p[0], p[1] + Y_BIAS]) + if res['left'] is None: + res['left'] = np.array([0.425, 0.115]) + if res['right'] is None: + res['right'] = np.array([0.393, -0.161]) + return res + + def scan(self, side, x, y0, y1, n): + """Sweep the hand over the rack; return world-y of rim highlights (y, weight).""" + dets = [] + self.a[19 if side == 'left' else 20] = 0.0 + for k in range(n): + y = y0 + (y1 - y0) * k / max(1, n - 1) + yield from self.move_w(side, (x, y, Z_SCAN), 22 if k else 50) + yield from self.hold(6) + im = self.tools.image(side + '_wrist') + self.dbg.append((side, im)) + tw = self.to_world(self.tool_meas(side)) + for u, w, _ in rim_columns(im): + dets.append((tw[1] - (u - U0) / PX_PER_M, w, k)) + self.log.append(('scan', [(round(d[0], 3), d[1], d[2]) for d in dets])) + return dets + + def servo_rim(self, side, n_iter=3, gain=0.8, max_off=32): + cam = side + '_wrist' + for _ in range(n_iter): + im = self.tools.image(cam) + self.dbg.append((side, im)) + rims = [r for r in rim_columns(im) if abs(r[0] - U0) < max_off] + self.log.append((side, 'rims', rims)) + if not rims: + return + narrow = [r for r in rims if r[2] <= 4] + u = min(narrow or rims, key=lambda r: abs(r[0] - U0))[0] + dy = -(u - U0) / PX_PER_M * gain + if abs(dy) < 0.002: + return + yield from self.rel(side, (0, float(np.clip(dy, -0.05, 0.05)), 0), 14) + yield from self.hold(8) + + def servo_pair(self, side, n_iter=3, gain=0.8, max_off=30): + """Centre the open gripper between the two strongest rims near the centre.""" + cam = side + '_wrist' + for _ in range(n_iter): + im = self.tools.image(cam) + self.dbg.append((side, im)) + rims = [r for r in rim_columns(im) if abs(r[0] - U0) < max_off] + self.log.append((side, 'pair_rims', rims)) + if not rims: + return + rims = sorted(rims, key=lambda r: -r[1])[:2] + u = float(np.mean([r[0] for r in rims])) + dy = -(u - U0) / PX_PER_M * gain + if abs(dy) < 0.002: + return + yield from self.rel(side, (0, float(np.clip(dy, -0.04, 0.04)), 0), 12) + yield from self.hold(8) + + # ------------------------------------------------------------------ skills + def grasp(self, side, pw, g_open=G_OPEN, rotate=True, servo=True): + self.grasp_ok = False + yield from self.grip(side, g_open, 1) + yield from self.move_w(side, (pw[0], pw[1], Z_PRE), 40) + yield from self.hold(8) + for attempt in range(2): + if servo == 'pair': + yield from self.servo_pair(side) + elif servo: + yield from self.servo_rim(side) + yield from self.rel(side, (0, 0, Z_GRASP + (0.0, -0.02, 0.02)[attempt] - self.tool_cmd(side)[2]), 35) + yield from self.hold(6) + yield from self.grip(side, 1.0, 22) + self.log.append((side, 'grip', float(self.gstate(side)), int(self.obs['t']))) + self.grasp_ok = self.gstate(side) < 0.97 + if self.grasp_ok: + break + yield from self.grip(side, g_open, 12) + yield from self.rel(side, (0, 0, Z_PRE - self.tool_cmd(side)[2]), 35) + yield from self.hold(8) + yield from self.rel(side, (0, 0, Z_CARRY - self.tool_cmd(side)[2]), 50) + if rotate and self.grasp_ok: + sgn = -1.0 if side == 'left' else 1.0 + yield from self.rotate(side, sgn * CARRY_YAW, 45, d=(-0.03, -sgn * CARRY_OUT, 0)) + + def place(self, side, pw, unrotate=True): + if unrotate: + yield from self.rotate(side, 0.0, 40, d=(0.03, 0, 0)) + yield from self.move_w(side, (pw[0], pw[1], Z_CARRY), 35) + yield from self.hold(12) + yield from self.rel(side, (0, 0, Z_PLACE - Z_CARRY), 65) + yield from self.hold(10) + self.log.append((side, 'place_z', self.tool_meas(side).round(3).tolist(), int(self.obs['t']))) + yield from self.grip(side, 0.0, 20) + yield from self.rel(side, (0, 0, Z_CARRY - self.tool_cmd(side)[2]), 35) + + # ------------------------------------------------------------------ script + def _run(self): + yield from self.hold(2) + racks = self.locate_racks() + self.racks = racks + L, Rr = racks['left'], racks['right'] + xL = L[0] + PLATE_DX + xR = Rr[0] + PLATE_DX + xb = min(xL, xR) - X_BASE - X_BACK + # keep the idle right arm tucked away from tables and racks + yield from self.move('right', RIGHT_TUCK, 30) + # scan the start rack with the left wrist camera + yield from self.walk(xL - X_BASE, L[1], vmax=0.25) + dets = yield from self.scan('left', xL, L[1] + 0.04, L[1] + 0.25, 4) + plates, alt = cluster_plates(dets, L[1]) + self.log.append(('plates', plates, alt)) + if len(plates) >= 2 and plates[1] - plates[0] > PAIR_SEP: + todo = [plates[1], plates[0]] + g_open, servo = G_OPEN, True + else: + todo = [float(np.mean(plates)) if plates else L[1] + 0.10] + g_open, servo = 0.0, 'pair' + slots = [Rr[1] + SLOT_DY['right'], Rr[1] + SLOT_DY['left']] + yield from self.move('left', (0.30, 0.25, 0.20), 25) + for i, yp in enumerate(todo): + self.log.append(('t_go', i, int(self.obs['t']))) + yield from self.walk(xL - X_BASE, yp - REACH, vmax=0.3 if i else 0.2, tol=0.02, tries=1, maxn=320) + yield from self.grasp('left', (xL, yp), g_open=g_open, servo=servo) + if not self.grasp_ok and alt: + # nothing caught: try the remaining rim candidate + yield from self.grip('left', G_OPEN, 10) + yield from self.walk(xL - X_BASE, alt[0] - REACH, tol=0.02, tries=1, maxn=200) + yield from self.grasp('left', (xL, alt[0]), g_open=g_open, servo=servo) + alt = [] + self.log.append(('t_grasped', i, int(self.obs['t']), float(self.gstate('left')))) + if not self.grasp_ok: + continue + both = self.gstate('left') < 0.85 + s = slots[0] if (i == 0 or both) else slots[1] + yield from self.walk(xR - X_BASE, s - REACH, vmax=0.25, tol=0.02, tries=1, maxn=320) + yield from self.place('left', (xR, s)) + self.log.append(('t_placed', i, int(self.obs['t']))) + if both: + break + if i + 1 < len(todo): + yield from self.move('left', (0.30, 0.25, 0.25), 25) + pass + yield from self.move('left', (0.25, 0.30, 0.15), 30) + yield from self.hold(10) diff --git a/policies/pick_box/astra-s1/episodes.csv b/policies/pick_box/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3f22f9d78d422f75134c2a138cada633d1ce36d1 --- /dev/null +++ b/policies/pick_box/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1893,success,0 +620001,1,1900,success,0 +620002,0,4400,timeout,0 +620003,1,1922,success,0 +620004,0,4400,timeout,0 +620005,1,2111,success,0 +620006,1,2098,success,0 +620007,1,2046,success,0 +620008,1,1997,success,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,1,2080,success,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,1,2041,success,0 +620017,1,2064,success,0 +620018,1,2063,success,0 +620019,0,4400,timeout,0 +620020,1,2101,success,0 +620021,1,2010,success,0 +620022,1,2341,success,0 +620023,1,1992,success,0 +620024,1,2120,success,0 +620025,1,2098,success,0 +620026,1,1964,success,0 +620027,0,4400,timeout,0 +620028,1,2108,success,0 +620029,1,2081,success,0 +620030,1,2065,success,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,1,2218,success,0 +620034,0,4400,timeout,0 +620035,1,2122,success,0 +620036,1,2177,success,0 +620037,1,1929,success,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,1,2032,success,0 +620041,1,2382,success,0 +620042,0,4400,timeout,0 +620043,1,2037,success,0 +620044,0,4400,timeout,0 +620045,1,1963,success,0 +620046,0,4400,timeout,0 +620047,1,2246,success,0 +620048,1,1941,success,0 +620049,1,1941,success,0 +620050,0,4400,timeout,0 +620051,1,2116,success,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,1,2053,success,0 +620055,0,4400,timeout,0 +620056,1,2071,success,0 +620057,0,4400,timeout,0 +620058,1,2022,success,0 +620059,0,4400,timeout,0 +620060,1,1956,success,0 +620061,0,4400,timeout,0 +620062,1,2178,success,0 +620063,0,4400,timeout,0 +620064,1,2113,success,0 +620065,0,4400,timeout,0 +620066,1,2102,success,0 +620067,0,4400,timeout,0 +620068,1,2071,success,0 +620069,1,2225,success,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,1,2003,success,0 +620073,1,2043,success,0 +620074,1,2060,success,0 +620075,0,4400,timeout,0 +620076,1,2332,success,0 +620077,0,4400,timeout,0 +620078,1,1820,success,0 +620079,1,2117,success,0 +620080,1,2269,success,0 +620081,1,2040,success,0 +620082,1,2281,success,0 +620083,0,4400,timeout,0 +620084,1,2091,success,0 +620085,1,2017,success,0 +620086,1,1881,success,0 +620087,0,4400,timeout,0 +620088,1,2163,success,0 +620089,1,2008,success,0 +620090,1,2243,success,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,1,2088,success,0 +620094,1,2020,success,0 +620095,1,1938,success,0 +620096,1,1991,success,0 +620097,1,2234,success,0 +620098,1,2308,success,0 +620099,1,2417,success,0 diff --git a/policies/pick_box/astra-s1/policy.py b/policies/pick_box/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f36b6e98119aa208512fa5ecf21774fd4516273e --- /dev/null +++ b/policies/pick_box/astra-s1/policy.py @@ -0,0 +1,86 @@ +"""Hand-written, deterministic bimanual box transfer. + +Colour segmentation supplies a small approach correction and distinguishes +narrow presentations of the box. Smooth joint targets squeeze the box between +the hands; measured pelvis position closes the walking loop. Counter contact +is handled by increasing clearance if forward motion stalls. +""" + +import numpy as np +import cv2 + +class Policy: + + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float) + self.a[19:] = 0 + self.i = 0 + self.k = 0 + self.start = self.a.copy() + self.adjusted = False + self.clearance = -1.25 + self.last_x = None + self.offset = 0 + self.stages = [('move', (-0.07, -1.0), 400), ('wait', {}, 30), ('pose', {6: 0.35, 13: -0.35}, 60), ('move', (0.4, -1.0), 400), ('wait', {}, 30), ('pose', {2: 0.55, 5: -0.6, 12: -0.6, 8: 0.8, 15: 0.8}, 100), ('pose', {6: 0, 13: 0, 7: -0.25, 14: 0.25}, 80), ('wait', {}, 50), ('pose', {2: 0.74}, 150), ('move', (-0.18, -1.0), 400), ('wait', {}, 30), ('pose', {2: 0.78, 5: -1.25, 12: -1.25, 10: 0.65, 17: 0.65}, 200), ('move', (-0.18, 0), 400), ('wait', {}, 30), ('move', (0.32, 0), 400), ('wait', {}, 30), ('pose', {5: -1.1, 12: -1.1, 10: 0.3, 17: 0.3}, 150), ('pose', {6: 0.4, 13: -0.4, 7: 0, 14: 0}, 100), ('wait', {}, 1000)] + + def act(self, obs, tools): + if self.i == 5 and (not self.adjusted): + self.adjusted = True + im = tools.image('head') + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = ((hsv[:, :, 0] > 10) & (hsv[:, :, 0] < 40) & (hsv[:, :, 1] > 60) & (hsv[:, :, 2] < 225)).astype(np.uint8) + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + if n > 1: + x, y, w, h, area = stats[1 + np.argmax(stats[1:, 4])] + if area > 30: + narrow = w < 25 + if narrow or y + h <= 67: + self.stages[5][1][2] = 0.65 + self.clearance = -1.6 + self.stages[11][1].update({5: -1.6, 12: -1.6, 10: 1.0, 17: 1.0}) + if narrow: + self.stages[6][1].update({6: -0.12, 13: 0.12, 7: -0.35, 14: 0.35}) + p = obs['low_dim_obs'][21:25] + goal = (float(p[0] + np.clip(0.007 * (70 - y - h), -0.06, 0.06)), float(p[1] - np.clip(0.006 * (x + w / 2 - 42), -0.06, 0.06))) + if np.linalg.norm(np.array(goal) - p[:2]) > 0.025: + self.offset = 2 + self.stages.insert(5, ('move', goal, 160)) + self.stages.insert(6, ('wait', {}, 30)) + typ, val, duration = self.stages[self.i] + self.a[:2] = 0 + self.a[3] = 0 + if typ == 'move': + p = obs['low_dim_obs'][21:25] + err = np.array(val) - p[:2] + c, s = (np.cos(p[3]), np.sin(p[3])) + v = np.array([[c, s], [-s, c]]) @ err * 1.6 + self.a[:2] = np.clip(v, -0.3, 0.3) + self.a[3] = np.clip(-2 * p[3], -0.5, 0.5) + if np.linalg.norm(err) < 0.025: + self.k = duration + self.a[:2] = 0 + self.a[3] = 0 + elif typ == 'pose': + f = min(1, (self.k + 1) / (duration * 0.7)) + for j, v in val.items(): + self.a[j] = self.start[j] + (v - self.start[j]) * f + elif typ == 'back': + self.a[0] = -0.15 + if self.i == 14 + self.offset: + if self.k % 50 == 0: + x = float(obs['low_dim_obs'][21]) + if self.last_x is not None and x - self.last_x < 0.02 and (x < 0.27): + self.clearance = max(-1.85, self.clearance - 0.08) + self.last_x = x + self.a[5] = self.a[12] = self.clearance + self.a[10] = self.a[17] = -self.clearance - 0.6 + if self.i == 16 + self.offset: + f = min(1, (self.k + 1) / (duration * 0.7)) + self.a[5] = self.a[12] = self.clearance + 0.15 * f + self.a[10] = self.a[17] = -self.clearance - 0.6 - 0.15 * f + self.k += 1 + if self.k >= duration and self.i < len(self.stages) - 1: + self.i += 1 + self.k = 0 + self.start = self.a.copy() + return self.a.copy() diff --git a/policies/pick_box/astra-s2/episodes.csv b/policies/pick_box/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..91b59763328d6522c31837625703412613588092 --- /dev/null +++ b/policies/pick_box/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,3167,success,0 +620001,1,3222,success,0 +620002,1,2828,success,0 +620003,1,2811,success,0 +620004,1,3072,success,0 +620005,1,3207,success,0 +620006,1,2803,success,0 +620007,1,2740,success,0 +620008,1,2819,success,0 +620009,1,3055,success,0 +620010,1,3107,success,0 +620011,0,4400,timeout,0 +620012,1,2825,success,0 +620013,1,2804,success,0 +620014,1,3057,success,0 +620015,1,2987,success,0 +620016,1,2853,success,0 +620017,1,2860,success,0 +620018,1,3183,success,0 +620019,0,4400,timeout,0 +620020,1,2891,success,0 +620021,1,3203,success,0 +620022,0,4400,timeout,0 +620023,1,2856,success,0 +620024,1,2887,success,0 +620025,1,3066,success,0 +620026,0,4400,timeout,0 +620027,1,2797,success,0 +620028,1,3050,success,0 +620029,1,3062,success,0 +620030,1,3049,success,0 +620031,1,3227,success,0 +620032,1,2804,success,0 +620033,1,3206,success,0 +620034,1,3048,success,0 +620035,0,4400,timeout,0 +620036,1,2820,success,0 +620037,1,2816,success,0 +620038,1,3029,success,0 +620039,1,3147,success,0 +620040,1,2885,success,0 +620041,1,2908,success,0 +620042,0,4400,timeout,0 +620043,1,2795,success,0 +620044,1,3251,success,0 +620045,1,2852,success,0 +620046,1,2851,success,0 +620047,1,3033,success,0 +620048,1,2798,success,0 +620049,1,2687,success,0 +620050,1,2877,success,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,1,3078,success,0 +620055,1,3058,success,0 +620056,1,2814,success,0 +620057,1,2853,success,0 +620058,1,3083,success,0 +620059,1,3063,success,0 +620060,1,2879,success,0 +620061,1,2814,success,0 +620062,1,2844,success,0 +620063,0,4400,timeout,0 +620064,1,3044,success,0 +620065,1,3210,success,0 +620066,1,2853,success,0 +620067,1,3069,success,0 +620068,0,4400,timeout,0 +620069,1,3211,success,0 +620070,1,3056,success,0 +620071,1,3043,success,0 +620072,1,3156,success,0 +620073,1,3230,success,0 +620074,1,2815,success,0 +620075,1,3055,success,0 +620076,1,2792,success,0 +620077,1,3152,success,0 +620078,1,3228,success,0 +620079,1,3047,success,0 +620080,1,3201,success,0 +620081,1,2817,success,0 +620082,1,3054,success,0 +620083,1,3178,success,0 +620084,0,4400,timeout,0 +620085,1,3230,success,0 +620086,1,3243,success,0 +620087,1,3170,success,0 +620088,1,3222,success,0 +620089,0,4400,timeout,0 +620090,1,3074,success,0 +620091,1,3222,success,0 +620092,1,3068,success,0 +620093,1,3221,success,0 +620094,1,2813,success,0 +620095,1,3069,success,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,1,3239,success,0 +620099,1,2925,success,0 diff --git a/policies/pick_box/astra-s2/policy.py b/policies/pick_box/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f8a3c872ddd42f5ce928f0877a4b69fdd1cfd4 --- /dev/null +++ b/policies/pick_box/astra-s2/policy.py @@ -0,0 +1,115 @@ +"""Deterministic bimanual box transfer using RGB and joint feedback only. + +The base follows pelvis-pose feedback. Colour segmentation aligns the approach; +arm motions are interpolated, with wrist compensation during lifting. During +transport, shoulder tracking error provides a bounded grip-pressure heuristic. +All geometry, gains, and waypoints are manually chosen control constants. +""" +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.a=np.asarray(tools.hold_action(),float) + self.a[19:]=0 + self.stage=0; self.age=0; self.start=self.a.copy() + self.y=-1.04; self.err=0; self.grip_control=False + self.force_roll=None + self.narrow=False + self.fine_error=None + # First move sideways clear of the furniture, then approach with spread arms. + # Squat, close, stand, lift, retreat, transfer, lower, and release. + self.stages=[ + ('nav',430,[-.07,-1.04,0],{}), + ('align',110,None,{}), + ('pose',100,None,{6:.25,13:-.25,5:-.6,12:-.6,8:1,15:1}), + ('nav',320,[.42,None,0],{}), + ('pose',140,None,{2:.68}), + ('pose',160,None,{6:-.06,13:.06}), + ('pose',180,None,{2:.78}), + ('pose',230,None,{5:-1.65,12:-1.65,10:1.05,17:1.05,6:.09,13:-.09}), + ('nav',160,[.18,None,0],{}), + ('nav',650,[-.08,-.02,0],{}), + ('nav',280,[.43,-.02,0],{}), + ('pose',160,None,{5:-1.2,12:-1.2,10:.6,17:.6,6:.03,13:-.03}), + ('pose',160,None,{6:.32,13:-.32}), + ('nav',200,[-.12,-.02,0],{}), + ('pose',120,None,{5:0,12:0,8:0,15:0,10:0,17:0,6:0,13:0,2:.74}), + ] + @staticmethod + def detect(im): + hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV) + m=((hsv[:,:,0]>9)&(hsv[:,:,0]<40)&(hsv[:,:,1]>45)&(hsv[:,:,2]>45)).astype(np.uint8) + n,l,s,c=cv2.connectedComponentsWithStats(m) + ids=[i for i in range(1,n) if s[i,4]>12] + if not ids:return None + i=max(ids,key=lambda j:s[j,4]);return (s[i,0]+s[i,2]/2,s[i,1]+s[i,3]/2,s[i,2],s[i,3]) + def navigate(self,p,goal): + goal=np.array([goal[0],self.y if goal[1] is None else goal[1]]) + v=np.clip((goal-p[:2])*1.5,-.18,.18) + mag=np.linalg.norm(v) + if mag<.019:v[:]=0 + elif mag<.065:v*=.065/mag + yaw=p[3] + self.a[:2]=np.array([[np.cos(yaw),np.sin(yaw)],[-np.sin(yaw),np.cos(yaw)]])@v + self.a[3]=np.clip(-yaw*2,-.35,.35) + def act(self,obs,tools): + p=obs['low_dim_obs'][21:25] + if self.stage>=len(self.stages): + self.a[:2]=0;self.a[3]=0;return self.a.copy() + typ,dur,goal,ch=self.stages[self.stage] + self.a[:2]=0;self.a[3]=0 + if typ=='pose': + if self.age==0 and ch.get(5)==-1.65: + ch[6]=float(obs['low_dim_obs'][4])+.02 + ch[13]=float(obs['low_dim_obs'][13])-.02 + self.carry_roll=(ch[6],ch[13]) + if self.age==0 and ch.get(5)==-1.2: + ch[6]=self.carry_roll[0]-.06 + ch[13]=self.carry_roll[1]+.06 + if ch.get(5)==-1.65 and self.age==dur-30: + self.grip_control=True + if 6 in ch and ch[6]==.32: + self.grip_control=False + f=min(1,(self.age+1)/max(1,dur-20)) + for k,v in ch.items():self.a[k]=self.start[k]+f*(v-self.start[k]) + elif typ=='nav': + self.navigate(p,goal) + # Narrow end-on boxes need a closer check of the fore-aft grasp alignment. + if self.stage==3 and self.age>=220: + if self.age%10==0: + b=self.detect(tools.image('head')) + if self.age==220: + self.narrow=b is not None and b[2] < .9*b[3] + if b is not None: + self.fine_error=np.array([70-b[1]-b[3]/2,42-b[0]]) + if self.narrow and self.fine_error is not None: + v=np.clip(self.fine_error*.01,-.10,.10) + mag=np.linalg.norm(v) + if np.max(np.abs(self.fine_error))<1.5:v[:]=0 + elif mag<.065 and mag>0:v*=.065/mag + self.a[:2]=v + else: + if self.age%10==0: + b=self.detect(tools.image('head')) + self.err=0 if b is None else b[0]-42 + self.a[1]=-.07*np.sign(self.err) if abs(self.err)>1.5 else 0 + self.a[3]=np.clip(-p[3]*2,-.25,.25) + # Maintain a small joint tracking error against the box. This is feedback + # from the current grasp, not an estimate learned from past episodes. + if self.grip_control: + q=obs['low_dim_obs'] + if self.force_roll is None: + self.force_roll=np.array([self.a[6],self.a[13]]) + error=np.array([q[4]-.11,q[13]+.11])-self.force_roll + self.force_roll+=np.clip(.035*error,-.0015,.0015) + self.force_roll=np.clip(self.force_roll,[-.15,-.3],[.3,.15]) + self.a[6],self.a[13]=self.force_roll + self.age+=1 + if self.age>=dur: + # A short extension can free the stance if contact prevented standing. + if self.stage==6 and p[2]<.72: + self.stages[self.stage+1:self.stage+1]=[('pose',180,None,{2:1.0}),('pose',100,None,{2:.78})] + if typ=='align':self.y=float(p[1]) + self.stage+=1;self.age=0;self.start=self.a.copy() + return self.a.copy() diff --git a/policies/pick_box/astra-s3/episodes.csv b/policies/pick_box/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..049c71aa5fe59c9c6094e6b6a2842537401f06d9 --- /dev/null +++ b/policies/pick_box/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,1,2400,success,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,1,2430,success,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,1,2516,success,0 +620039,1,2474,success,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,1,2463,success,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,1,2451,success,0 +620071,1,2552,success,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,1,2521,success,0 +620076,0,4400,timeout,0 +620077,1,2515,success,0 +620078,0,4400,timeout,0 +620079,1,2398,success,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,1,2489,success,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,1,2555,success,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/astra-s3/policy.py b/policies/pick_box/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6aff401a2ce3a3eb4f223b7bb5334b8e7efcb8c8 --- /dev/null +++ b/policies/pick_box/astra-s3/policy.py @@ -0,0 +1,98 @@ +"""Deterministic visual approach and two-arm box transfer controller.""" +import cv2 +import numpy as np + + +def box_bounds(im): + r, g, b = im.astype(np.float32).transpose(2, 0, 1) + mask = ((r > g * 1.18) & (g > b * 1.25) & (r > 65)).astype(np.uint8) + n, _, stats, _ = cv2.connectedComponentsWithStats(mask) + if n < 2: + return None + return stats[1 + np.argmax(stats[1:, 4])] + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.a[19:] = 0 + self.a[5] = self.a[12] = -.35 + self.a[8] = self.a[15] = .35 + self.av = self.al = 0. + self.reach_x = None + self.wide = False + + def act(self, obs, tools): + t = int(obs['t']) + p = obs['low_dim_obs'] + a = self.a + a[:2] = 0 + a[3] = 0 + if t < 250: + a[1] = -.22 + elif t < 700: + a[3] = np.clip(-p[24] * 2, -.4, .4) + if t % 10 == 0: + bounds = box_bounds(tools.image('head')) + if bounds is not None: + x, y, w, h, _ = bounds + self.av = np.clip((55 - y - h / 2) * .018, -.15, .18) + self.al = np.clip((42 - x - w / 2) * .025, -.18, .18) + else: + self.av, self.al = 0., -.1 + a[0] = self.av if abs(self.av) > .055 else 0 + a[1] = self.al if abs(self.al) > .055 else 0 + elif t < 850: + if self.reach_x is None: + self.reach_x = float(p[21]) + .116 + a[0] = .14 if p[21] < self.reach_x else 0 + elif t < 1000: + if t == 850: + im = tools.image('head').astype(np.float32) + r, g, b = im.transpose(2, 0, 1) + mask = ((r > b*1.3) & (g > b*1.15) & (r > 75)).astype(np.uint8) + n, _, stats, _ = cv2.connectedComponentsWithStats(mask) + if n > 1: + st = stats[1 + np.argmax(stats[1:, 4])] + self.wide = st[2] > 27 + a[2] = .60 + a[5] = a[12] = 0. if self.wide else -.25 + a[8] = a[15] = 0 + a[6], a[13] = .25, -.25 + elif t < 1150: + a[6] = a[13] = 0 + a[7], a[14] = (-.25, .25) if self.wide else (-.4, .4) + elif t < 1300: + a[19:] = 1 + a[7], a[14] = (-.35, .35) if self.wide else (-.55, .55) + if self.wide: + a[11], a[18] = .35, -.35 + elif t < 1450: + a[2] = .74 + elif t < 1600: + a[0] = -.15 + elif t < 1800: + u = min(1., (t - 1600) / 150.) + a[5] = a[12] = (-.85 * u) if self.wide else (-.25 - 1.05 * u) + a[8] = a[15] = (.6 if self.wide else .2) * u + a[2] = .78 + elif t < 2250: + a[3] = np.clip(-p[24] * 2, -.3, .3) + a[1] = .18 if p[22] < -.02 else 0 + a[0] = np.clip(-p[21] * 1.5, -.15, .15) + elif t < 2700: + a[3] = np.clip(-p[24] * 2, -.3, .3) + a[0] = .14 if p[21] < .38 else 0 + a[1] = np.clip(-p[22] * 1.5, -.12, .12) + if self.wide: + u = min(1., (t - 2250) / 180.) + a[5] = a[12] = -.85 - .65 * u + a[8] = a[15] = .6 - .4 * u + else: + a[5] = a[12] = -1.3 - .2 * min(1., (t - 2250) / 120.) + elif t < 2950: + a[5] = a[12] = -1.5 + .25 * min(1., (t - 2700) / 200.) + else: + a[19:] = 0 + a[6], a[13] = .3, -.3 + return a.copy() diff --git a/policies/pick_box/deepseek1017-s1/episodes.csv b/policies/pick_box/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/deepseek1017-s1/policy.py b/policies/pick_box/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca6343b923f2a88b082cf7cc868e53e236e8103 --- /dev/null +++ b/policies/pick_box/deepseek1017-s1/policy.py @@ -0,0 +1,219 @@ +"""Control policy: pick the cardboard box from the side table, set it on the counter. + +Deterministic, hand written. State machine driven by proprioception and the +robot's own cameras only. +""" + +import cv2 +import numpy as np + +CARD_LO = np.array([12, 60, 90], dtype=np.uint8) +CARD_HI = np.array([42, 255, 255], dtype=np.uint8) + + +def box_detect(im): + """Largest cardboard-coloured blob as (cx, cy, w, h, area) or None.""" + if im is None: + return None + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + m = cv2.inRange(hsv, CARD_LO, CARD_HI) + m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8)) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, 8) + best = None + for i in range(1, n): + x, y, w, h, area = stats[i] + if area < 40 or w < 5 or h < 5: + continue + if best is None or area > best[4]: + best = (float(cent[i][0]), float(cent[i][1]), int(w), int(h), int(area)) + return best + + +def clamp(v, lo, hi): + return float(min(max(v, lo), hi)) + + +# grasp pose candidates: (height, shoulder_pitch, elbow, shoulder_yaw, roll) +POSES = [ + (0.62, -0.10, 0.32, 0.00, -0.15), + (0.66, -0.16, 0.28, 0.15, -0.10), +] + + +class Policy: + """Scripted loco-manipulation policy.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.pt = 0 + self.yaw0 = float(np.asarray(obs["low_dim_obs"])[24]) + self.attempt = 0 + self.held = False + self.box_w = 0 + + @staticmethod + def lo(obs): + return np.asarray(obs["low_dim_obs"], dtype=np.float32) + + def go(self, tools, vx=0.0, vy=0.0, wz=0.0, h=0.74, pitch=0.0, + la=None, ra=None, gl=None, gr=None): + a = np.asarray(tools.hold_action(), dtype=np.float32) + a[0], a[1], a[2], a[3], a[4] = vx, vy, h, wz, pitch + if la is not None: + a[5:12] = la + if ra is not None: + a[12:19] = ra + if gl is not None: + a[19] = gl + if gr is not None: + a[20] = gr + return a + + def arms(self, pose): + h, sp, el, sy, roll = pose + return (h, + [sp, roll, sy, el, 0.0, 0.0, 0.0], + [sp, -roll, -sy, el, 0.0, 0.0, 0.0]) + + def act(self, obs, tools): + lo = self.lo(obs) + yaw = float(lo[24]) + self.pt += 1 + p = self.phase + + if p == 0: # turn right to side table + err = -0.75 - yaw + if abs(err) < 0.05 or self.pt > 90: + self.phase, self.pt = 1, 0 + return self.go(tools) + return self.go(tools, wz=clamp(1.4 * err, -0.65, 0.65)) + + if p == 1: # walk towards it + if self.pt > 150: + self.phase, self.pt = 2, 0 + return self.go(tools) + err = -0.75 - yaw + return self.go(tools, vx=0.45, wz=clamp(1.4 * err, -0.5, 0.5)) + + if p == 2: # servo on box (head cam) + det = None + try: + det = box_detect(tools.image("head", 84, 84)) + except Exception: + det = None + vx = wz = 0.0 + done = False + if det is not None: + cx, cy, w, h, area = det + self.box_w = w + wz = clamp(-0.013 * (cx - 45.0), -0.32, 0.32) + if w < 31: + vx = 0.22 + if w >= 31 and abs(cx - 45.0) < 4.0: + done = True + else: + wz = 0.25 + if done or self.pt > 130: + self.phase, self.pt = 3, 0 + return self.go(tools) + return self.go(tools, vx=vx, wz=wz) + + if p == 3: # go to grasp pose + h, la, ra = self.arms(POSES[min(self.attempt, len(POSES) - 1)]) + if self.pt > 24: + self.phase, self.pt = 4, 0 + return self.go(tools, h=h, la=la, ra=ra, gl=0.0, gr=0.0) + + if p == 4: # close and squeeze + h, la, ra = self.arms(POSES[min(self.attempt, len(POSES) - 1)]) + g = clamp(self.pt / 16.0, 0.0, 1.0) + sq = 0.0 + if self.pt > 16: + sq = clamp((self.pt - 16) / 16.0, 0.0, 1.0) * 0.25 + la2 = [la[0], la[1], la[2] + sq, la[3], 0, 0, 0] + ra2 = [ra[0], ra[1], ra[2] - sq, ra[3], 0, 0, 0] + if self.pt > 34: + self.phase, self.pt = 5, 0 + return self.go(tools, h=h - 0.01, la=la2, ra=ra2, gl=g, gr=g) + + if p == 5: # tuck up and check + h, la, ra = self.arms(POSES[min(self.attempt, len(POSES) - 1)]) + t = clamp(self.pt / 18.0, 0.0, 1.0) + la2 = [la[0] - 0.45 * t, la[1], la[2] + 0.25, la[3] + 0.25 * t, 0, 0, 0] + ra2 = [ra[0] - 0.45 * t, ra[1], ra[2] - 0.25, ra[3] + 0.25 * t, 0, 0, 0] + if self.pt > 20: + ok = True + try: + det = box_detect(tools.image("head", 84, 84)) + except Exception: + det = None + if det is not None and det[4] >= 300 and det[1] > 34: + ok = False + self.held = ok + if ok or self.attempt >= len(POSES) - 1: + self.phase, self.pt = 6, 0 + else: + self.attempt += 1 + self.phase, self.pt = 3, 0 + return self.go(tools, h=h - 0.01, la=la2, ra=ra2, gl=1.0, gr=1.0) + return self.go(tools, h=h - 0.01, la=la2, ra=ra2, gl=1.0, gr=1.0) + + if p == 6: # back away, crouched + if self.pt > 50: + self.phase, self.pt = 7, 0 + return self.go(tools, vx=-0.22, h=0.62, + la=[-0.55, -0.15, 0.25, 0.57, 0, 0, 0], + ra=[-0.55, 0.05, -0.25, 0.57, 0, 0, 0], + gl=1.0, gr=1.0) + + if p == 7: # turn towards counter + target = self.yaw0 + 0.55 + err = target - yaw + if abs(err) < 0.06 or self.pt > 120: + self.phase, self.pt = 8, 0 + return self.go(tools) + return self.go(tools, wz=clamp(1.1 * err, -0.45, 0.45), h=0.62, + la=[-0.55, -0.15, 0.25, 0.57, 0, 0, 0], + ra=[-0.55, 0.05, -0.25, 0.57, 0, 0, 0], + gl=1.0, gr=1.0) + + if p == 8: # walk to the counter + if self.pt > 85: + self.phase, self.pt = 9, 0 + return self.go(tools) + err = (self.yaw0 + 0.55) - yaw + return self.go(tools, vx=0.35, wz=clamp(1.1 * err, -0.4, 0.4), h=0.62, + la=[-0.55, -0.15, 0.25, 0.57, 0, 0, 0], + ra=[-0.55, 0.05, -0.25, 0.57, 0, 0, 0], + gl=1.0, gr=1.0) + + if p == 9: # extend to counter, lower + t = clamp(self.pt / 26.0, 0.0, 1.0) + if self.pt > 30: + self.phase, self.pt = 10, 0 + return self.go(tools, h=0.62 + 0.06 * t, pitch=0.12 * t, + la=[-0.55 + 0.45 * t, -0.15, 0.25, 0.57 - 0.25 * t, 0, 0, 0], + ra=[-0.55 + 0.45 * t, 0.05, -0.25, 0.57 - 0.25 * t, 0, 0, 0], + gl=1.0, gr=1.0) + + if p == 10: # release + if self.pt > 16: + self.phase, self.pt = 11, 0 + return self.go(tools, h=0.64, pitch=0.15, + la=[-0.30, -0.15, 0.28, 0.55, 0, 0, 0], + ra=[-0.30, 0.05, -0.28, 0.55, 0, 0, 0], + gl=0.0, gr=0.0) + + if p == 11: # retreat a little, hold + if self.pt > 60: + return self.go(tools, h=0.74, + la=[-0.30, -0.15, 0.28, 0.55, 0, 0, 0], + ra=[-0.30, 0.05, -0.28, 0.55, 0, 0, 0], + gl=0.0, gr=0.0) + return self.go(tools, vx=-0.30, h=0.72, + la=[-0.30, -0.15, 0.28, 0.55, 0, 0, 0], + ra=[-0.30, 0.05, -0.28, 0.55, 0, 0, 0], + gl=0.0, gr=0.0) + + return np.asarray(tools.hold_action(), dtype=np.float32) diff --git a/policies/pick_box/deepseek1017-s2/episodes.csv b/policies/pick_box/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/deepseek1017-s2/policy.py b/policies/pick_box/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d7683199aab2c342f819119c4f8d03ce6d3a1d92 --- /dev/null +++ b/policies/pick_box/deepseek1017-s2/policy.py @@ -0,0 +1,393 @@ +"""Control policy: pick the cardboard box from the side table and set it +down on the kitchen counter. + +Hand-written, deterministic, closed-loop on the robot's own cameras and +proprioception. A small state machine drives the robot: + + turn -> settle -> walk to the table -> lean/reach -> final approach -> + squat -> roll the left wrist -> grip search (contact feedback) -> lift -> + carry back -> turn to the counter -> place. + +The grasp pinches the box rim with the left gripper while the robot is +squatted and the torso is pitched forward over the table. Candidate arm +offsets are tested and the one with the strongest finger contact (read from +low_dim_obs) is kept. +""" + +import numpy as np + +# tunables ------------------------------------------------------------------- +YAW_APPROACH = -0.97 +WALK1_STEPS = 140 +WALK2_STEPS = 60 +LEAN_PITCH = 0.40 +LEAN_SP = -0.40 +GRIP_HEIGHT = 0.50 +GRIP_ROLL = 1.42 +LIFT_HEIGHT = 0.74 +CARRY_HEIGHT = 0.70 + +CANDIDATES = [ + (0.00, 0.00), + (-0.04, 0.00), + (0.04, 0.00), + (0.00, -0.06), + (0.00, 0.06), + (-0.05, -0.05), + (-0.05, 0.05), +] + + +def _low(obs): + return np.asarray(obs["low_dim_obs"], dtype=np.float64) + + +def _box_mask(im): + r = im[:, :, 0].astype(np.int16) + g = im[:, :, 1].astype(np.int16) + b = im[:, :, 2].astype(np.int16) + brown = ( + (r > 90) & (r < 235) & (g > 60) & (g < 215) & (b < 155) + & (r - b > 35) & (r - g > 8) & (g - b > 5) + ) + bright = ( + (r > 185) & (g > 175) & (b > 100) & (b < 220) + & (r - b > 22) & (g - b > 12) + ) + return brown | bright + + +class Policy: + """Pick the box and set it on the counter.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "turn" + self.phase_t = 0 + self.step = 0 + self.target_yaw = YAW_APPROACH + self.cand_i = 0 + self.best = (0.0, 0.0) + self.best_score = -1.0 + self.lift_lost = 0 + self.attempt = 0 + self.grip_ok = False + self.lift_start_t = 0 + self.servo_sp = 0.0 + self.servo_wy = 0.0 + self.servo_i = 0 + + # -- helpers ------------------------------------------------------------- + def _go(self, name): + self.phase = name + self.phase_t = 0 + + def _yaw_hold(self, yaw, target, gain=1.5, lim=0.25): + e = target - yaw + w = gain * e + if abs(w) < 0.06: + w = 0.0 + return float(np.clip(w, -lim, lim)) + + def _pose(self, yaw, target, hgt, pitch, sp, wr, wy, close, gx=0.0, + yaw_hold=True): + a = self.hold.copy() + a[2] = hgt + a[3] = self._yaw_hold(yaw, target) if yaw_hold else 0.0 + a[4] = pitch + a[5:12] = [sp, -0.03, 0.0, -0.08, wr, -0.10, 0.15 + wy] + a[12:19] = [LEAN_SP, 0.03, 0.0, 0.0, 0.0, 0.0, 0.0] + a[0] = gx + g = 1.0 if close else 0.0 + a[19] = g + a[20] = g + return a + + def _box_stats(self, im): + m = _box_mask(im) + n = int(m.sum()) + if n < 40: + return None + ys, xs = np.nonzero(m) + return dict(n=n, cx=float(xs.mean()), cy=float(ys.mean())) + + # -- main ---------------------------------------------------------------- + def act(self, obs, tools): + low = _low(obs) + yaw = float(low[24]) + fL0, fL1 = float(low[10]), float(low[11]) + t = self.phase_t + self.phase_t += 1 + self.step += 1 + + # ------------------------------------------------------------ turn + if self.phase == "turn": + if yaw <= self.target_yaw + 0.005 or t > 500: + self._go("settle0") + return self.hold.copy() + a = self.hold.copy() + a[3] = -0.40 + return a + + if self.phase == "settle0": + if t >= 2: + self._go("walk1") + return self.hold.copy() + + # -------------------------------------------------------- long walk + if self.phase == "walk1": + if t >= WALK1_STEPS: + self._go("open0") + return self.hold.copy() + a = self.hold.copy() + a[0] = 0.30 + return a + + if self.phase == "open0": + if t >= 15: + self._go("lean") + a = self.hold.copy() + a[19] = 0.0 + a[20] = 0.0 + return a + + # ------------------------------------------------------------ lean + if self.phase == "lean": + if t >= 32: + self._go("walk2") + return self._lean_action() + return self._lean_action() + + # ---------------------------------------------- final short walk + if self.phase == "walk2": + if t >= WALK2_STEPS: + self._go("settle2") + return self._lean_action() + a = self._lean_action() + a[0] = 0.12 + return a + + if self.phase == "settle2": + if t >= 10: + self._go("squat") + return self._lean_action() + + # ----------------------------------------------------------- squat + if self.phase == "squat": + if t >= 34: + self._go("roll_prep") + return self._squat_action(yaw) + return self._squat_action(yaw) + + if self.phase == "roll_prep": + if t >= 24: + self._go("grip_prep") + self.best = (-0.03, 0.0) + return self._squat_action(yaw) + return self._squat_action(yaw) + + # -------------------------------------------------- grip search + if self.phase == "search_prep": + sp, wy = CANDIDATES[self.cand_i] + if t >= 10: + self._go("search_close") + return self._grip_action(sp, wy, False, yaw) + + if self.phase == "search_close": + sp, wy = CANDIDATES[self.cand_i] + if t >= 15: + score = min(fL0, fL1) + if score > self.best_score: + self.best_score = score + self.best = (sp, wy) + self._go("search_open") + return self._grip_action(sp, wy, True, yaw) + + if self.phase == "search_open": + sp, wy = CANDIDATES[self.cand_i] + if t >= 6: + self.cand_i += 1 + if self.cand_i >= len(CANDIDATES): + if self.best is None: + self.best = (0.0, 0.0) + self._go("grip_prep") + else: + self._go("search_prep") + return self._grip_action(sp, wy, False, yaw) + + # ----------------------------------------------------- final grip + if self.phase == "grip_prep": + sp, wy = self.best + if t >= 16: + self._go("grip_close") + return self._grip_action(sp, wy, False, yaw) + + if self.phase == "grip_close": + sp, wy = self.best + if t >= 26: + self.lift_start_t = self.step + self._go("lift") + return self._grip_action(sp, wy, True, yaw) + + # ------------------------------------------------------------ lift + if self.phase == "lift": + sp, wy = self.best + frac = min(1.0, t / 90.0) + hgt = GRIP_HEIGHT + (LIFT_HEIGHT - GRIP_HEIGHT) * frac + pit = LEAN_PITCH * (1.0 - frac) + if min(fL0, fL1) < -0.0185: + self.lift_lost += 1 + else: + self.lift_lost = 0 + if self.lift_lost > 5: + held = False + elif t >= 96: + held = min(fL0, fL1) > -0.0185 + else: + return self._pose(yaw, self.target_yaw, hgt, pit, + LEAN_SP + sp, GRIP_ROLL, wy, True) + if held: + self.grip_ok = True + self._go("back1") + else: + self.attempt += 1 + if self.attempt <= 1: + self._go("retry_squat") + else: + self._go("giveup") + return self._pose(yaw, self.target_yaw, hgt, pit, + LEAN_SP + sp, GRIP_ROLL, wy, True) + + # ---------------------------------------------------------- retry + if self.phase == "retry_squat": + if t >= 28: + self._go("retry_prep") + self.cand_i = 0 + self.best = None + self.best_score = -1.0 + return self._grip_action(0.0, 0.0, False, yaw) + + if self.phase == "retry_prep": + sp, wy = CANDIDATES[self.cand_i] + if t >= 10: + self._go("retry_close") + return self._grip_action(sp, wy, False, yaw) + + if self.phase == "retry_close": + sp, wy = CANDIDATES[self.cand_i] + if t >= 26: + score = min(fL0, fL1) + if score > self.best_score: + self.best_score = score + self.best = (sp, wy) + self._go("retry_open") + return self._grip_action(sp, wy, True, yaw) + + if self.phase == "retry_open": + sp, wy = CANDIDATES[self.cand_i] + if t >= 6: + self.cand_i += 1 + if self.cand_i >= len(CANDIDATES): + if self.best is None: + self._go("giveup") + else: + self._go("retry_grip_prep") + else: + self._go("retry_prep") + return self._grip_action(sp, wy, False, yaw) + + if self.phase == "retry_grip_prep": + sp, wy = self.best + if t >= 10: + self._go("retry_grip_close") + return self._grip_action(sp, wy, False, yaw) + + if self.phase == "retry_grip_close": + sp, wy = self.best + if t >= 26: + self._go("lift") + return self._grip_action(sp, wy, True, yaw) + + # -------------------------------------------------------- carry + if self.phase == "back1": + sp, wy = self.best + if t >= 34: + self._go("turn_counter") + return self.hold.copy() + return self._pose(yaw, self.target_yaw, CARRY_HEIGHT, 0.10, + LEAN_SP + sp, GRIP_ROLL, wy, True, gx=-0.22) + + if self.phase == "turn_counter": + if yaw >= 0.55 or t > 160: + self._go("walk_counter") + return self.hold.copy() + a = self.hold.copy() + a[3] = 0.45 + return a + + if self.phase == "walk_counter": + if t >= 46: + self._go("place") + return self.hold.copy() + a = self.hold.copy() + a[0] = 0.28 + a[3] = self._yaw_hold(yaw, 0.60, gain=1.0, lim=0.15) + return a + + if self.phase == "place": + if t >= 26: + self._go("release") + return self._place_action() + + if self.phase == "release": + a = self.hold.copy() + a[19] = 0.0 + a[20] = 0.0 + return a + + return self.hold.copy() + + # -- builders ------------------------------------------------------------ + def _lean_action(self): + a = self.hold.copy() + a[4] = LEAN_PITCH + a[5:12] = [LEAN_SP, -0.03, 0.0, 0.0, 0.0, 0.0, 0.0] + a[12:19] = [LEAN_SP, 0.03, 0.0, 0.0, 0.0, 0.0, 0.0] + a[19] = 0.0 + a[20] = 0.0 + return a + + def _squat_action(self, yaw=0.0): + a = self.hold.copy() + a[2] = GRIP_HEIGHT + a[3] = self._yaw_hold(yaw, YAW_APPROACH, gain=1.2, lim=0.2) + a[4] = LEAN_PITCH + a[5:12] = [LEAN_SP, -0.03, 0.0, 0.0, GRIP_ROLL, 0.0, 0.0] + a[12:19] = [LEAN_SP, 0.03, 0.0, 0.0, 0.0, 0.0, 0.0] + a[19] = 0.0 + a[20] = 0.0 + return a + + def _grip_action(self, sp_off, wy_off, close, yaw=None): + a = self.hold.copy() + a[2] = GRIP_HEIGHT + if yaw is not None: + a[3] = self._yaw_hold(yaw, YAW_APPROACH, gain=1.2, lim=0.2) + a[4] = LEAN_PITCH + a[5:12] = [LEAN_SP + sp_off, -0.03, 0.0, -0.08, GRIP_ROLL, -0.10, 0.15 + wy_off] + a[12:19] = [LEAN_SP, 0.03, 0.0, 0.0, 0.0, 0.0, 0.0] + g = 1.0 if close else 0.0 + a[19] = g + a[20] = g + return a + + def _place_action(self): + a = self.hold.copy() + a[0] = 0.10 + a[2] = 0.74 + a[4] = 0.15 + a[5:12] = [0.35, -0.05, 0.0, -0.35, 0.0, 0.0, 0.0] + a[12:19] = [0.35, 0.05, 0.0, -0.35, 0.0, 0.0, 0.0] + a[19] = 1.0 + a[20] = 1.0 + return a diff --git a/policies/pick_box/gpt61sol-s1/episodes.csv b/policies/pick_box/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt61sol-s1/policy.py b/policies/pick_box/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a0027445ceae1345e52a61106208be25944abdb2 --- /dev/null +++ b/policies/pick_box/gpt61sol-s1/policy.py @@ -0,0 +1,94 @@ +"""Deterministic visual approach and two-arm box transfer.""" +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.a=np.asarray(tools.hold_action(),dtype=float) + self.stage=0;self.start=0;self.destination=np.array([.25,-1.02]) + self.center=None;self.attempt=0 + + @staticmethod + def box(im): + r,g,b=im.astype(np.float32).transpose(2,0,1) + mask=((r>1.12*g)&(g>1.15*b)&(r>60)&(g>35)).astype(np.uint8) + n,labels,stats,centers=cv2.connectedComponentsWithStats(mask) + if n<=1:return None + i=1+int(np.argmax(stats[1:,4])) + if stats[i,4]<35:return None + return centers[i] + + def move(self, target, p): + delta=np.asarray(target)-p[:2] + v=delta*1.8 + norm=np.linalg.norm(v) + if norm>.20:v*=.20/norm + if norm<.045:v[:]=0 + elif norm<.065:v*=.065/norm + c,s=np.cos(p[3]),np.sin(p[3]) + return [c*v[0]+s*v[1],-s*v[0]+c*v[1]] + + def act(self, obs, tools): + t=int(obs['t']);p=np.asarray(obs['low_dim_obs'][21:25]);q=self.a.copy() + q[:2]=0;q[3]=np.clip(-p[3]*2,-.35,.35);q[4]=0 + age=t-self.start + if self.stage==0: + q[2]=.74;q[5:19]=0;q[19:]=0 + q[:2]=self.move([.08,-1.02],p) + if age>260 and abs(p[1]+1.02)<.06: + self.stage=1;self.start=t + elif self.stage==1: + q[2]=.74;q[5:19]=0;q[19:]=0 + if t%5==0: + self.center=self.box(tools.image('head')) + target=self.destination.copy() + if self.center is not None: + target[1]=p[1]+np.clip((42-self.center[0])*.006,-.10,.10) + target[0]=p[0]+np.clip((50-self.center[1])*.006,-.06,.08) + target[0]=np.clip(target[0],.24,.35) + self.destination=target + q[:2]=self.move(target,p) + if age>210: + self.stage=2;self.start=t + elif self.stage in (2,3): + q[2]=.65-.025*self.attempt + elbow=.8+.08*self.attempt + inward=-.05 if self.stage==2 else -.22 + q[5:12]=[-.6,inward,.35,elbow,0,0,0] + q[12:19]=[-.6,-inward,-.35,elbow,0,0,0] + q[19:]=0 if self.stage==2 else 1 + if age>(120 if self.stage==2 else 120): + self.stage+=1;self.start=t + elif self.stage==4: + q[2]=.74;q[5:12]=[-.9,-.27,0,0,0,0,0] + q[12:19]=[-.9,.27,0,0,0,0,0];q[19:]=1 + if age>160: + visible=self.box(tools.image('head')) + if visible is not None and visible[1]>42 and self.attempt<3: + self.attempt+=1;self.stage=2 + else:self.stage=5 + self.start=t + elif self.stage in (5,6,7): + q[2]=.74;q[5:12]=[-.9,-.27,0,0,0,0,0] + q[12:19]=[-.9,.27,0,0,0,0,0];q[19:]=1 + target=[-.10,p[1]] if self.stage==5 else ([-.10,0] if self.stage==6 else [.27,0]) + q[:2]=self.move(target,p) + if (np.linalg.norm(np.asarray(target)-p[:2])<.035 and age>100) or age>(230 if self.stage!=6 else 390): + self.stage+=1;self.start=t + elif self.stage==8: + q[2]=.74;q[5:12]=[-.9,-.27,0,.15,0,0,0] + q[12:19]=[-.9,.27,0,.15,0,0,0];q[19:]=1 + if age>110:self.stage=9;self.start=t + elif self.stage==9: + q[19:]=0 + if age>90:self.stage=10;self.start=t + else: + q[2]=.74;q[5:12]=[-.5,.3,0,.7,0,0,0] + q[12:19]=[-.5,-.3,0,.7,0,0,0];q[19:]=0 + if age<180:q[:2]=self.move([-.12,0],p) + # Smooth physical targets while leaving the base feedback responsive. + self.a[2]+=np.clip(q[2]-self.a[2],-.003,.003) + self.a[4:19]+=np.clip(q[4:19]-self.a[4:19],-.018,.018) + self.a[:2]=q[:2];self.a[3]=q[3];self.a[19:]=q[19:] + if obs.get('fell',False):self.a[:2]=0;self.a[3]=0 + return self.a.copy() diff --git a/policies/pick_box/gpt61sol-s2/episodes.csv b/policies/pick_box/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..0a303832f3fcca998fd71a485bde950bec626454 --- /dev/null +++ b/policies/pick_box/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,1,2474,success,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,1,2832,success,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,1,3599,success,0 +620010,1,2738,success,0 +620011,1,3594,success,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,1,3521,success,0 +620015,0,4400,timeout,0 +620016,1,2954,success,0 +620017,1,2945,success,0 +620018,0,4400,timeout,0 +620019,1,3052,success,0 +620020,1,2853,success,0 +620021,1,2527,success,0 +620022,1,2867,success,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,1,3288,success,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,1,2951,success,0 +620029,1,3336,success,0 +620030,1,3016,success,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,1,2842,success,0 +620034,1,3501,success,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,1,3079,success,0 +620039,0,4400,timeout,0 +620040,1,2868,success,0 +620041,0,4400,timeout,0 +620042,1,3120,success,0 +620043,0,4400,timeout,0 +620044,1,3352,success,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,1,3467,success,0 +620050,0,4400,timeout,0 +620051,1,2649,success,0 +620052,1,3318,success,0 +620053,1,2972,success,0 +620054,1,3285,success,0 +620055,1,3258,success,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,1,3274,success,0 +620059,1,3337,success,0 +620060,1,2836,success,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,1,2666,success,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,1,3413,success,0 +620068,1,3334,success,0 +620069,1,2912,success,0 +620070,1,3046,success,0 +620071,1,2928,success,0 +620072,0,4400,timeout,0 +620073,1,2831,success,0 +620074,0,4400,timeout,0 +620075,1,3419,success,0 +620076,0,4400,timeout,0 +620077,1,3406,success,0 +620078,1,3050,success,0 +620079,1,3175,success,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,1,2483,success,0 +620084,1,2827,success,0 +620085,1,2608,success,0 +620086,1,3003,success,0 +620087,0,2823,fell,1 +620088,0,4400,timeout,0 +620089,1,2911,success,0 +620090,1,2867,success,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,1,2533,success,0 +620094,0,4400,timeout,0 +620095,1,3283,success,0 +620096,1,3019,success,0 +620097,1,2813,success,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt61sol-s2/policy.py b/policies/pick_box/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a772424ee2139de12ee094c1e3ee716efc767f --- /dev/null +++ b/policies/pick_box/gpt61sol-s2/policy.py @@ -0,0 +1,92 @@ +"""Hand-written, deterministic camera-guided two-arm box transfer. + +The box is segmented by cardboard colour. Its image aspect determines a +reach pose; all motions use fixed gains and proprioceptive base feedback. +""" +import cv2 +import numpy as np + +class Policy: + def reset(self,obs,tools): + self.raw=np.asarray(tools.hold_action(),dtype=float) + self.raw[19:21]=0 + self.phase='side';self.start=0;self.good=0;self.box=None;self.narrow=1 + def detect(self,im): + # Cardboard faces and the pale yellow top form one component. + hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV) + mask=cv2.inRange(hsv,np.array([10,45,65]),np.array([40,255,255])) + n,l,s,c=cv2.connectedComponentsWithStats(mask) + ids=[j for j in range(1,n) if s[j,4]>15] + if not ids:return None + j=max(ids,key=lambda j:s[j,4]);return s[j],c[j] + def change(self,phase,t): + self.phase=phase;self.start=t;self.good=0 + def move(self,a,p,target,speed=.2): + d=np.asarray(target)-p[:2];v=np.clip(d*1.4,-speed,speed) + a[:2]=[np.cos(p[3])*v[0]+np.sin(p[3])*v[1],-np.sin(p[3])*v[0]+np.cos(p[3])*v[1]] + if np.linalg.norm(d)<.027:a[:2]=0;return True + return False + def arms(self,a,pitch,roll,elbow): + if not self.narrow and roll<0:roll*=2.5 + a[5:12]=[pitch,roll,0,elbow,0,0,0] + a[12:19]=[pitch,-roll,0,elbow,0,0,0] + def act(self,obs,tools): + t=obs['t'];dt=t-self.start;p=obs['low_dim_obs'][21:25] + a=self.raw.copy();a[:5]=[0,0,.74,np.clip(-2*p[3],-.3,.3),0];a[19:]=0 + if self.phase=='side': + if self.move(a,p,[-.02,-.95],.25):self.change('forward',t) + elif self.phase=='forward': + if self.move(a,p,[.25,-.95],.2):self.change('align',t) + elif self.phase=='align': + if t%5==0:self.box=self.detect(tools.image('head')) + if self.box is not None: + s,c=self.box;self.narrow=1 if s[2]/max(1,s[3])<.85 else 0;ex=c[0]-42;goal=45;ey=c[1]-goal + a[1]=-np.clip(ex*.01,-.14,.14) if abs(ex)>1.5 else 0 + a[0]=-np.clip(ey*.008,-.17,.17) if abs(ey)>1.5 else 0 + self.good=self.good+1 if abs(ex)<2 and abs(ey)<2 else 0 + if self.good>20:self.change('spread',t) + if dt>450:self.change('spread',t) + elif self.phase=='spread': + # Clear the box before moving the hands forward and squatting. + self.arms(a,0,.4*min(1,dt/70),0) + if dt>=100:self.change('lower',t) + elif self.phase=='lower': + u=min(1,dt/100);self.arms(a,(-.4 if self.narrow else -.65)*u,.4,.6*u);a[2]=.74-.12*u;a[4]=.2*self.narrow*u + if dt>=120:self.change('clamp',t) + elif self.phase=='clamp': + a[2]=.62;a[4]=.2*self.narrow;self.arms(a,-.4 if self.narrow else -.65,.4-.8*min(1,dt/100),.6) + if dt>=130:self.change('rise',t) + elif self.phase=='rise': + a[19:]=1 + u=min(1,dt/130);a[2]=.62+.12*u;a[4]=.2*self.narrow;self.arms(a,-.4-.2*u if self.narrow else -.65,-.4,.6) + if dt>=160:self.change('lift',t) + elif self.phase=='lift': + a[19:]=1 + u=min(1,dt/140);a[4]=.2*self.narrow;self.arms(a,-.6-.15*u if self.narrow else -.65-.2*u,-.4,.6+(0 if self.narrow else .2)*u) + if dt>=170:self.change('back',t) + elif self.phase in ('back','carry','counter'): + a[19:]=1 + self.arms(a,-.75 if self.narrow else -.9,-.4,-.4 if self.phase=='counter' else (.6 if self.narrow else .8));a[4]=.2*self.narrow + if self.phase=='counter':a[10]=a[17]=.8 + targets={'back':[-.2,-1.0],'carry':[-.2,0],'counter':[.38,0]} + if self.move(a,p,targets[self.phase],.15): + self.change({'back':'carry','carry':'raise','counter':'place'}[self.phase],t) + elif self.phase=='raise': + # Elbow flexion raises the load while preserving shoulder contact. + a[19:]=1 + u=min(1,dt/220);a[4]=.2*self.narrow;self.arms(a,-.75 if self.narrow else -.9,-.4,(.6 if self.narrow else .8)-(1.0 if self.narrow else 1.2)*u);a[10]=a[17]=.8*u + if dt>=250:self.change('counter',t) + elif self.phase=='place': + # Lower gradually over the counter, then separate the hands. + a[19:]=1 + u=min(1,dt/150);a[4]=.2*self.narrow;self.arms(a,-.75 if self.narrow else -.9,-.4,-.4+.3*u);a[10]=a[17]=.8-.25*u + if dt>=180:self.change('release',t) + elif self.phase=='release': + a[4]=.2*self.narrow;self.arms(a,-.75 if self.narrow else -.9,-.4+.8*min(1,dt/100),-.1);a[10]=a[17]=.55 + if dt>=120:self.change('withdraw',t) + elif self.phase=='withdraw': + self.arms(a,-.4,.2,.5) + self.move(a,p,[.08,0],.15) + for j in [0,1]: + if 0 65) & (r > 1.25*b) & (g > 1.12*b) + & (r > 1.04*g) & (r < 2.0*g)).astype(np.uint8) + n, labels, stats, centroids = cv2.connectedComponentsWithStats(mask) + if n <= 1: + return None + choices = [i for i in range(1, n) if stats[i, 4] >= 12] + if not choices: + return None + i = max(choices, key=lambda k: stats[k, 4]) + return centroids[i], stats[i], labels == i + + def locate(self, obs, tools): + im = tools.image('head') + region = self.region(im) + if region is None: + return False + uv, stats, mask = region + p = obs['low_dim_obs'][21:25] + # Pinhole rays intersect the plane through the middle of the box. + tilt = .785 + float(obs['low_dim_obs'][2]) + ray = np.array([1., -(uv[0]-41.5)/42., -(uv[1]-41.5)/42.]) + c, s = np.cos(tilt), np.sin(tilt) + ray = np.array([c*ray[0]+s*ray[2], ray[1], -s*ray[0]+c*ray[2]]) + height = float(p[2]) + .55 + scale = (.95-height) / min(ray[2], -.05) + local = np.array([.05, 0.]) + scale*ray[:2] + c, s = np.cos(p[3]), np.sin(p[3]) + xy = p[:2] + np.array([c*local[0]-s*local[1], s*local[0]+c*local[1]]) + if .35 < xy[0]-self.initial[0] < 1.35 and -1.6 < xy[1]-self.initial[1] < -.45: + self.box = xy + return True + return False + + def pose(self, height=.74, pitch=0., sp=0., elbow=.8, + roll=.0, yaw=0., wp=0., wy=0., grip=0.): + target = self.action.copy() + target[2:5:2] = [height, pitch] + target[5:12] = [sp, roll, -yaw, elbow, 0., wp, -wy] + target[12:19] = [sp, -roll, yaw, elbow, 0., wp, wy] + target[19:] = grip + # Position targets have no built-in slew protection. + self.action[2] += np.clip(target[2]-self.action[2], -.002, .002) + self.action[4:19] += np.clip(target[4:19]-self.action[4:19], -.012, .012) + self.action[19:] += np.clip(target[19:]-self.action[19:], -.025, .025) + + def act(self, obs, tools): + self.age += 1 + self.action[[0, 1, 3]] = 0 + offset = self.initial[:2] - np.array([-.071, 0.]) + if obs.get('fell', False): + return self.action.copy() + if self.phase == 'survey': + self.pose(elbow=.8) + reached = self.move([.10+offset[0], -.85+offset[1], 0.], obs) + if reached or self.age > 420: + self.change('observe') + elif self.phase == 'observe': + self.pose(elbow=.8) + if self.age == 40: + self.locate(obs, tools) + if self.age >= 65: + self.change('approach') + elif self.phase == 'approach': + self.pose(elbow=.8) + # Keep the torso clear of the table edge while bringing hands over it. + destination = self.box + np.array([-.38, 0.]) + destination[0] = np.clip(destination[0], .22+offset[0], .36+offset[0]) + reached = self.move([*destination, self.angle], obs, .18) + if reached or self.age > 400: + self.change('align') + elif self.phase == 'align': + self.pose(elbow=.8) + if self.age % 8 == 1: + self.last_image = self.region(tools.image('head')) + if self.last_image is not None: + error = float(self.last_image[0][0]) - 41.5 + if abs(error) > 2.0: + self.action[1] = -np.sign(error) * min(.14, max(.075, abs(error)*.008)) + self.wait_count = 0 + else: + self.wait_count += 1 + if self.wait_count > 24 or self.age > 200: + self.change('prepare') + elif self.phase == 'prepare': + self.pose(height=.74, sp=.15, elbow=0., roll=.12, wy=1.15) + if self.age > 160: + self.change('grasp') + elif self.phase == 'grasp': + self.pose(height=.70, sp=.15, elbow=0., roll=-.16, wy=1.15, grip=1.) + if self.age > 180: + self.change('lift') + elif self.phase == 'lift': + self.pose(height=.74, sp=-.15, elbow=0., roll=-.16, wy=1.15, grip=1.) + if self.age > 160: + p = obs['low_dim_obs'][21:25] + self.retreat = np.array([p[0]-.17, p[1], self.angle]) + self.change('retreat') + elif self.phase == 'retreat': + self.pose(sp=-.15, elbow=0., roll=-.16, wy=1.15, grip=1.) + if self.move(self.retreat, obs, .12) or self.age > 250: + self.change('transport') + elif self.phase == 'transport': + self.pose(sp=-.15, elbow=0., roll=-.16, wy=1.15, grip=1.) + destination = [.10+offset[0], -.12+offset[1], 0.] + if self.move(destination, obs, .15) or self.age > 700: + self.change('counter') + elif self.phase == 'counter': + self.pose(sp=-.15, elbow=0., roll=-.16, wy=1.15, grip=1.) + if self.move([.26+offset[0], -.02+offset[1], 0.], obs, .12) or self.age > 350: + self.change('lower') + elif self.phase == 'lower': + self.pose(height=.72, sp=.10, elbow=0., roll=-.16, wy=1.15, grip=1.) + if self.age > 160: + self.change('release') + elif self.phase == 'release': + self.pose(height=.74, sp=.10, elbow=0., roll=.18, wy=.6, grip=0.) + if self.age > 140: + self.change('clear') + elif self.phase == 'clear': + self.pose(elbow=.8) + if self.age < 100: + self.action[0] = -.1 + return self.action.copy() diff --git a/policies/pick_box/gpt61terra-s1/episodes.csv b/policies/pick_box/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..69478ff7a5a9ff540a9e231f3d3a2db7d86e3310 --- /dev/null +++ b/policies/pick_box/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,1,2337,success,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,1,2408,success,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,1,2331,success,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt61terra-s1/policy.py b/policies/pick_box/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1fb8665baae36c7ad465f722842f58ca617844f4 --- /dev/null +++ b/policies/pick_box/gpt61terra-s1/policy.py @@ -0,0 +1,37 @@ +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + + def act(self, obs, tools): + t = obs['t'] + a = self.base.copy() + a[19:21] = 0 + a[3] = -0.5 if t < 115 else (0.5 if 320 <= t < 435 else 0) + if t >= 1150: + a[3] = np.clip(-1.5 * obs['low_dim_obs'][24], -0.35, 0.35) + a[0] = (0.3 if 125 <= t < 300 else + 0.12 if 650 <= t < 750 else + -0.2 if 1150 <= t < 1350 else + 0.12 if 2150 <= t < 2310 else 0) + a[1] = -0.16 if 450 <= t < 500 else (0.2 if 1350 <= t < 1800 else 0) + if t >= 550: + a[5:12] = [0, 0.2, 0, 0.3, 0, 0, 0] + a[12:19] = [0, -0.2, 0, 0.3, 0, 0, 0] + if t >= 800: + a[6] = -0.15 + a[13] = 0.15 + if t >= 900: + a[19:21] = 1 + if t >= 1000: + a[5] = a[12] = -0.4 + if t >= 1800: + a[5] = a[12] = -0.4 - 0.7 * min(1, (t - 1800) / 250) + a[2] = 0.85 + if t >= 2350: + a[5] = a[12] = -0.95 + if t >= 2500: + a[19:21] = 0 + a[6], a[13] = 0.2, -0.2 + return a diff --git a/policies/pick_box/gpt61terra-s2/episodes.csv b/policies/pick_box/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..dbd9ea9f880d6a609e3a729fef45b04311ad4524 --- /dev/null +++ b/policies/pick_box/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,1,2993,success,0 +620020,1,2777,success,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,1,3141,success,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,1,3003,success,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,1,3099,success,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,1,2789,success,0 +620068,1,2938,success,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,1,2923,success,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt61terra-s2/policy.py b/policies/pick_box/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..99a2a48d0170007d7d93f11cdcda3670e4e49197 --- /dev/null +++ b/policies/pick_box/gpt61terra-s2/policy.py @@ -0,0 +1,35 @@ +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.hold=np.array(tools.hold_action(),dtype=np.float32);self.cx=42. + def move(self,a,p,x,y,lim=.17): + yaw=p[3];dx=x-p[0];dy=y-p[1];vx=dx*np.cos(yaw)+dy*np.sin(yaw);vy=-dx*np.sin(yaw)+dy*np.cos(yaw) + if np.hypot(vx,vy)>.05:a[0]=np.clip(vx,-lim,lim);a[1]=np.clip(vy,-lim,lim) + a[3]=np.clip(-yaw*1.3,-.3,.3) + def act(self,obs,tools): + t=obs['t'];p=obs['low_dim_obs'][21:25];a=self.hold.copy();a[:2]=0;a[3]=0 + if t<420: + self.move(a,p,.35,-1.,.25) + elif t<700: + if t%10==0: + im=tools.image('head').astype(float);r,g,b=im[:,:,0],im[:,:,1],im[:,:,2];m=(r>70)&(r>g*1.06)&(g>b*1.25)&(r>b*1.5);m[65:]=0;ys,xs=np.where(m) + if len(xs)>20:self.cx=float(np.mean(xs)) + if abs(self.cx-42)>2:a[1]=np.clip((42-self.cx)*.012,-.16,.16) + a[3]=np.clip(-p[3],-.2,.2) + else: + a[2]=.68;a[4]=.25;amt=min((t-700)/100,1.);roll=.25 if t<900 else -.10 + a[5:12]=[-.8*amt,roll*amt,0,1.*amt,-1.4,0,0];a[12:19]=[-.8*amt,-roll*amt,0,1.*amt,1.4,0,0];a[19:21]=0 if t<1050 else 1 + if t>=1200:a[2]=.78 + if t>=1350: + a[5]=a[12]=-.8-.45*min((t-1350)/100,1.) + if t>=2300: + a[5]=a[12]=-1.25-.25*min((t-2300)/300,1.);a[4]=.25 + if 1400<=t<1800:self.move(a,p,-.10,-1.05) + elif 1800<=t<2450:self.move(a,p,-.10,-.05) + elif 2600<=t<3050:self.move(a,p,.25,-.05,.12) + elif t>=3050: + a[2]=.78 + if t>=3300:a[19:21]=0 + if t>=3500:a[5:12]=[-1.25,.3,0,1.,-1.4,0,0];a[12:19]=[-1.25,-.3,0,1.,1.4,0,0] + return a diff --git a/policies/pick_box/gpt61terra-s3/episodes.csv b/policies/pick_box/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt61terra-s3/policy.py b/policies/pick_box/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..df37896a47b00206eba7dddfe694dc33589f3bd6 --- /dev/null +++ b/policies/pick_box/gpt61terra-s3/policy.py @@ -0,0 +1,110 @@ +"""Deterministic vision-guided box transfer for the G1.""" +import numpy as np +import cv2 + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.enter = 0 + self.cx = None + + def _phase(self, n, t): + self.phase = n + self.enter = t + + def act(self, obs, tools): + t = int(obs['t']) + p = np.asarray(obs['low_dim_obs'][21:25]) + x, y, z, yaw = map(float, p) + age = t-self.enter + a = self.base.copy() + a[0:5] = [0, 0, .74, 0, 0] + a[19:21] = 0 + if abs(yaw) > .035: + a[3] = np.clip(-2*yaw, -.4, .4) + + if self.phase == 0: + if y > -.91: + a[1] = -.23 + else: + self._phase(1,t) + elif self.phase == 1: + if age < 50: + pass + elif x < .16: + a[0] = .18 + else: + self._phase(2,t) + elif self.phase == 2: + # The box is tan; the table is neutral grey. The camera looks down, + # so the largest tan region in the upper image is the box. + if t % 8 == 0: + im = tools.image('head') + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = cv2.inRange(hsv, (10, 38, 65), (40, 255, 255)) + mask[62:,:] = 0 + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + choices = [i for i in range(1,n) if stats[i,4] >= 35] + if choices: + i = max(choices, key=lambda j: int(stats[j,4])) + self.cx = float(centers[i,0]) + if age > 30 and self.cx is not None: + err = self.cx - 42 + if abs(err) > 3.5 and age < 180: + a[1] = -.09 if err > 0 else .09 + else: + self._phase(3,t) + elif age > 180: + self._phase(3,t) + elif self.phase == 3: + if age < 35: + pass + elif x < .34 and age < 180: + a[0] = .12 + else: + self._phase(4,t) + else: + a[5:12] = [-.4,.15,-1.1,1.2,0,0,0] + a[12:19] = [-.4,-.15,1.1,1.2,0,0,0] + if self.phase == 4: + a[4]=.5 + if age > 170: self._phase(5,t) + elif self.phase == 5: + a[4]=.5 + a[19:21] = 1 + if age > 120: self._phase(6,t) + elif self.phase == 6: + a[4]=.35 + a[19:21] = 1 + a[5]=a[12]=-.8 + if age > 150: self._phase(7,t) + elif self.phase == 7: + a[4]=.35 + a[19:21] = 1 + a[5]=a[12]=-.8 + if x > .18 and age < 180: + a[0] = -.10 + else: + self._phase(8,t) + elif self.phase == 8: + a[4]=.35 + a[19:21] = 1 + a[5]=a[12]=-.8 + if y < -.10 and age < 900: + a[1] = .16 + else: + self._phase(9,t) + elif self.phase == 9: + a[19:21] = 1 + a[5]=a[12]=-.8 + if x < .36 and age < 200: + a[0] = .09 + else: + self._phase(10,t) + elif self.phase == 10: + a[19:21] = 1 + if age > 140: self._phase(11,t) + else: + a[19:21] = 0 + return a diff --git a/policies/pick_box/gpt6sol-s1/episodes.csv b/policies/pick_box/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt6sol-s1/policy.py b/policies/pick_box/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7d20bab0e443a33414960028d0a84d6606b50453 --- /dev/null +++ b/policies/pick_box/gpt6sol-s1/policy.py @@ -0,0 +1,147 @@ +"""Hand-written control for moving the box from the side table to the counter.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.box_offset = 0.0 + self.measured_box = False + + @staticmethod + def _box_center(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + mask = cv2.inRange(hsv, (7, 35, 50), (45, 255, 255)) + count, _, stats, centers = cv2.connectedComponentsWithStats(mask) + if count <= 1: + return None + idx = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + if stats[idx, cv2.CC_STAT_AREA] < 45: + return None + return float(centers[idx, 0]) + + @staticmethod + def _yaw_to(current, target, gain=2.0, maximum=0.5): + err = (target - current + np.pi) % (2 * np.pi) - np.pi + return float(np.clip(gain * err, -maximum, maximum)) + + @staticmethod + def _walk_to(action, x, y, yaw, target_x, target_y): + dx, dy = target_x - x, target_y - y + if dx * dx + dy * dy < 0.0016: + return + wx = float(np.clip(0.9 * dx, -0.18, 0.18)) + wy = float(np.clip(0.9 * dy, -0.18, 0.18)) + c, s = np.cos(yaw), np.sin(yaw) + action[0] = c * wx + s * wy + action[1] = -s * wx + c * wy + + def act(self, obs, tools): + t = int(obs["t"]) + body = obs["low_dim_obs"] + x, y, _, yaw = map(float, body[21:25]) + a = np.zeros(21, dtype=np.float32) + a[2] = 0.74 + a[4] = -0.2 + + if t == 300 and not self.measured_box: + center = self._box_center(tools.image("head")) + if center is not None: + self.box_offset = float(np.clip((40.0 - center) * 0.008, -0.12, 0.12)) + self.measured_box = True + + if t < 300: + a[1] = -0.2 + elif t < 460: + a[0] = 0.16 + a[3] = self._yaw_to(yaw, -0.28 + self.box_offset, maximum=0.3) + elif t < 540: + a[3] = self._yaw_to(yaw, 0.0, maximum=0.35) + else: + a[5:12] = [0.15, 0.0, -0.35, 0.3, 0.0, 0.0, 0.0] + a[12:19] = [0.15, 0.0, 0.2, 0.3, 0.0, 0.0, 0.0] + if t >= 660: + a[19:21] = 1.0 + if t >= 700: + a[14] = 0.5 + if 800 <= t < 880: + a[0] = -0.12 + a[3] = self._yaw_to(yaw, 0.15) + if 860 <= t < 880: + a[19:21] = 0.0 + if t >= 920: + a[5] = a[12] = -0.3 + a[8] = a[15] = 0.5 + a[2] = 0.76 + if 980 <= t < 1100: + a[0] = -0.12 + if 1100 <= t < 1300: + a[3] = 0.5 + if 1300 <= t < 1600: + a[0] = 0.16 + if 1600 <= t < 1800: + a[3] = self._yaw_to(yaw, 0.0) + if 1800 <= t < 2120: + a[3] = self._yaw_to(yaw, 0.0) + if x < 0.17: + a[0] = 0.16 + if 2120 <= t < 2250: + a[4] = 0.2 + a[5] = a[12] = -0.55 + a[8] = a[15] = 0.5 + if 2250 <= t < 2370: + a[4] = 0.2 + a[2] = 0.68 + a[5] = a[12] = -0.4 + a[8] = a[15] = 0.5 + if t >= 2300: + a[19:21] = 0.0 + if t >= 2370: + a[19:21] = 0.0 + a[0] = -0.12 if t < 2520 else 0.0 + + # A second approach uses the near corner of the box. The right + # hand draws it outward while the left hand supports its path. + if t >= 2520: + a[:] = 0.0 + a[2] = 0.74 + a[4] = -0.2 + if t < 3000: + self._walk_to(a, x, y, yaw, 0.39, -0.75) + a[3] = self._yaw_to(yaw, 0.0) + else: + a[4] = 0.1 if t < 3250 else -0.2 + a[12:19] = [0.3, 0.0, -0.6, 0.5, 0.0, 0.0, 0.0] + if t >= 3100: + a[20] = 1.0 + if t >= 3150: + a[15] = 1.2 + a[5:12] = [0.1, 0.0, -1.2, 0.8, 0.0, 0.0, 0.0] + if t >= 3250: + a[15] = 1.5 + if t >= 3300: + a[19] = 1.0 + if t >= 3350: + a[5] = a[12] = -0.3 + a[8] = a[15] = 1.1 + a[2] = 0.76 + if 3450 <= t < 3550: + a[0] = -0.12 + if 3550 <= t < 3750: + a[3] = self._yaw_to(yaw, 1.8) + if 3750 <= t < 3950: + a[0] = 0.16 + if 3950 <= t < 4050: + a[3] = self._yaw_to(yaw, 0.0) + if 4050 <= t < 4200: + self._walk_to(a, x, y, yaw, 0.17, -0.40) + a[3] = self._yaw_to(yaw, 0.0) + if t >= 4200: + a[4] = 0.2 + a[2] = 0.69 + a[5] = a[12] = -0.45 + a[8] = a[15] = 0.5 + a[19:21] = 0.0 + + return a diff --git a/policies/pick_box/gpt6sol-s2/episodes.csv b/policies/pick_box/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt6sol-s2/policy.py b/policies/pick_box/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7f9343a8d8599489a78f3342b3927aa9006e6554 --- /dev/null +++ b/policies/pick_box/gpt6sol-s2/policy.py @@ -0,0 +1,81 @@ +"""Deterministic box transfer controller for the G1 task.""" + +import math +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.target = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.target[19:21] = 0.0 + self.stage = 0 + self.stage_age = 0 + self.plan = [ + ("walk", (.25, -.80, -.55, 450)), + ("pose", (80, .74, 0., 0., 0., 0., 1.1, 0.)), + ("walk", (.36, -.80, -.55, 200)), + ("pose", (100, .66, .2, 0., 0., 0., 1.1, 0.)), + ("pose", (100, .66, .2, -.30, -.10, .10, 1.1, 0.)), + ("pose", (100, .66, .2, -.58, -.15, .15, 1.1, 0.)), + ("pose", (80, .66, .2, -.58, -.15, .15, 1.1, 1.)), + ("pose", (80, .66, .2, -.58, -.25, .25, 1.1, 1.)), + ("pose", (80, .66, .2, -.58, -.25, .25, .7, 1.)), + ("pose", (80, .66, .2, -.58, -.25, .25, .3, 1.)), + ("pose", (100, .74, 0., -.58, -.25, .25, .3, 1.)), + ("pose", (100, .74, 0., -.70, -.25, .25, .3, 1.)), + ("walk", (.25, -.73, -.55, 350)), + ("walk", (.10, -.60, -.55, 350)), + ("pose", (80, .74, 0., -.78, -.25, .25, .3, 1.)), + ("pose", (80, .74, 0., -.88, -.25, .25, .3, 1.)), + ("pose", (80, .74, 0., -.98, -.25, .25, .3, 1.)), + ("walk", (-.07, 0., 0., 400)), + ("pose", (100, .90, 0., -.98, -.25, .25, .3, 1.)), + ("pose", (100, .90, .20, -.98, -.25, .25, .3, 1.)), + ("pose", (100, .90, .20, -.98, -.25, .25, .3, 0.)), + ("pose", (100, .74, 0., -.20, -.10, .10, .3, 0.)), + ] + + def act(self, obs, tools): + pose = obs["low_dim_obs"][21:25] + for _ in range(3): + if self.stage >= len(self.plan): + break + kind, data = self.plan[self.stage] + if kind == "pose": + ready = self.stage_age >= data[0] + else: + gx, gy, gyaw, limit = data + yaw_error = (gyaw - float(pose[3]) + math.pi) % (2 * math.pi) - math.pi + dist = math.hypot(gx - float(pose[0]), gy - float(pose[1])) + ready = self.stage_age >= limit or (dist < .03 and abs(yaw_error) < .05) + if ready: + self.stage += 1 + self.stage_age = 0 + else: + break + + out = self.target.copy() + out[0] = out[1] = out[3] = 0. + if self.stage < len(self.plan): + kind, data = self.plan[self.stage] + if kind == "pose": + _, height, torso, shoulder_pitch, left_yaw, right_yaw, wrist_pitch, grip = data + out[2] = height + out[4] = torso + out[5:12] = [shoulder_pitch, 0., left_yaw, 0., 0., wrist_pitch, 0.] + out[12:19] = [shoulder_pitch, 0., right_yaw, 0., 0., wrist_pitch, 0.] + out[19:21] = grip + else: + gx, gy, gyaw, _ = data + x, y, _, yaw = map(float, pose) + dx, dy = gx - x, gy - y + c, s = math.cos(yaw), math.sin(yaw) + body_x = c * dx + s * dy + body_y = -s * dx + c * dy + out[0] = np.clip(1.6 * body_x, -.22, .22) if abs(body_x) > .025 else 0. + out[1] = np.clip(1.6 * body_y, -.22, .22) if abs(body_y) > .025 else 0. + yaw_error = (gyaw - yaw + math.pi) % (2 * math.pi) - math.pi + out[3] = np.clip(1.7 * yaw_error, -.5, .5) if abs(yaw_error) > .04 else 0. + self.target = out.copy() + self.stage_age += 1 + return out diff --git a/policies/pick_box/gpt6sol-s3/episodes.csv b/policies/pick_box/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/gpt6sol-s3/policy.py b/policies/pick_box/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..74a2445ae5a3ccf9c4b3a03e2ca69a5c65eeeead --- /dev/null +++ b/policies/pick_box/gpt6sol-s3/policy.py @@ -0,0 +1,152 @@ +"""Deterministic camera and proprioception based box manipulation controller.""" +import math +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.base[19:21] = 0.0 + self.phase = 'side' + self.phase_t = 0 + self.target_x = 0.33 + self.target_y = -0.96 + self.held = False + + def _switch(self, phase): + self.phase = phase + self.phase_t = 0 + + def _box(self, tools): + im = tools.image('head') + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = ((hsv[:, :, 0] >= 4) & (hsv[:, :, 0] <= 45) & + (hsv[:, :, 1] > 38) & (hsv[:, :, 2] > 55)) + yy, xx = np.nonzero(mask) + if len(xx) < 20: + return 0, 42.0 + return len(xx), float(xx.mean()) + + @staticmethod + def _body_velocity(a, pose, gx, gy, speed=0.16): + dx, dy = gx - float(pose[0]), gy - float(pose[1]) + dist = math.hypot(dx, dy) + if dist < 0.025: + return dist + c, s = math.cos(float(pose[3])), math.sin(float(pose[3])) + a[0] = np.clip((c * dx + s * dy) * 1.8, -speed, speed) + a[1] = np.clip((-s * dx + c * dy) * 1.8, -speed, speed) + return dist + + def act(self, obs, tools): + pose = obs['low_dim_obs'][21:25] + a = self.base.copy() + a[2] = .74 + p = self.phase + n = self.phase_t + self.phase_t += 1 + + if p == 'side': + a[1] = -.3 + if pose[1] < -.86 or n > 240: + self._switch('approach') + elif p == 'approach': + a[0] = .3 + if pose[0] > .32 or n > 160: + count, cx = self._box(tools) + if count > 690: + self.target_x = .27 + self.target_y = -.96 + np.clip((cx - 38.) * .007, -.05, .05) + self._switch('align') + elif p == 'align': + dist = self._body_velocity(a, pose, self.target_x, self.target_y, .12) + if dist < .045 or n > 100: + self._switch('squat') + elif p == 'squat': + a[2] = .52 + if n >= 65: + self._switch('reach') + elif p == 'reach': + a[2] = .52 + a[5], a[12] = -1., -1. + a[8], a[15] = .5, .5 + if n >= 55: + self._switch('close') + elif p == 'close': + a[2] = .52 + a[5], a[12] = -1., -1. + a[8], a[15] = .5, .5 + a[19:21] = 1. + if n >= 100: + self._switch('lift') + elif p == 'lift': + a[2] = .52 + a[5], a[12] = -1.25, -1.25 + a[8], a[15] = .8, .8 + a[19:21] = 1. + if n >= 80: + self._switch('stand') + elif p == 'stand': + self._carry(a) + if n >= 80: + self._switch('squeeze') + elif p == 'squeeze': + self._carry(a) + a[6], a[13] = -.04, .04 + if n >= 60: + self._switch('break_contact') + elif p == 'break_contact': + self._carry(a) + a[6], a[13] = -.04, .04 + a[0] = -.1 + if n >= 80 or pose[0] < .14: + self._switch('relax') + elif p == 'relax': + self._carry(a) + if n >= 25: + self._switch('retreat') + elif p == 'retreat': + self._carry(a) + a[0] = -.1 + if pose[0] < .04 or n > 160: + self._switch('turn') + elif p == 'turn': + self._carry(a) + e = .9 - float(pose[3]) + a[3] = np.clip(e * 1.2, -.3, .3) + if abs(e) < .08 or n > 330: + self._switch('cross') + elif p == 'cross': + self._carry(a) + self._body_velocity(a, pose, .2, .55, .13) + e = 1.0 - float(pose[3]) + a[3] = np.clip(e * 1.0, -.2, .2) + if (math.hypot(float(pose[0])-.2, float(pose[1])-.55) < .18 + or n > 650): + self._switch('place') + elif p == 'place': + self._carry(a) + a[2] = .62 + a[5], a[12] = -.9, -.9 + a[8], a[15] = .45, .45 + if n >= 80: + self._switch('release') + elif p == 'release': + self._carry(a) + a[2] = .62 + a[5], a[12] = -.9, -.9 + a[8], a[15] = .45, .45 + a[19:21] = 0. + if n >= 100: + self._switch('done') + elif p == 'done': + a[2] = .74 + a[19:21] = 0. + return a + + @staticmethod + def _carry(a): + a[5], a[12] = -1.25, -1.25 + a[8], a[15] = .8, .8 + a[19:21] = 1. diff --git a/policies/pick_box/kimi31pro-s1/episodes.csv b/policies/pick_box/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/kimi31pro-s1/policy.py b/policies/pick_box/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b77177d4b45b42a975aec456f4e3602c18ef3c54 --- /dev/null +++ b/policies/pick_box/kimi31pro-s1/policy.py @@ -0,0 +1,175 @@ +"""Deterministic hand-written controller for the box transfer task.""" + +import cv2 +import numpy as np + + +def _wrap(angle): + return (angle + np.pi) % (2 * np.pi) - np.pi + + +def _arms(sp, el, wp, left_yaw=0.0, right_yaw=0.0): + """Symmetric arm posture with independently controlled shoulder yaw.""" + return np.array([ + sp, 0.0, left_yaw, el, 0.0, wp, 0.0, + sp, 0.0, right_yaw, el, 0.0, wp, 0.0, + ], dtype=np.float64) + + +class Policy: + def reset(self, obs, tools): + self.q = np.zeros(14, dtype=np.float64) + self.height = 0.74 + self.pitch = 0.0 + self.grip = 0.0 + self.i = 0 + self.k = 0 + self.enter = True + self.visual_hits = 0 + self.last_raw = np.asarray(tools.hold_action(), dtype=np.float64) + + # The first two poses raise the arms clear of the table. The grasp is + # deliberately asymmetric: from this approach the right hand starts + # farther from the cardboard than the left hand. + self.program = [ + {"kind": "turn", "yaw": -1.10, "rate": 0.50, "n": 260}, + {"kind": "pose", "q": _arms(-0.65, 0.80, 0.0), "n": 90, "grip": 0.0}, + {"kind": "move", "forward": 0.45, "left": 0.15, "yaw": -1.10, "n": 360}, + {"kind": "move", "forward": 0.15, "left": 0.05, "yaw": -1.10, "n": 240}, + {"kind": "visual", "yaw": -1.10, "n": 300}, + # Start below the side faces, then move upward with open fingers. + {"kind": "pose", "q": _arms(-0.45, 0.40, 0.0, 0.0, 0.35), "n": 90, "grip": 0.0}, + {"kind": "pose", "q": _arms(-0.75, 0.20, 0.55, 0.0, 0.35), "n": 90, "grip": 0.0}, + {"kind": "pose", "q": _arms(-0.75, 0.20, 0.55, 0.0, 0.35), "n": 70, "grip": 1.0}, + # Fold the elbows to lift vertically without changing hand angle. + {"kind": "pose", "q": _arms(-1.00, 0.80, 0.20, 0.0, 0.35), "n": 110, "grip": 1.0}, + {"kind": "move", "forward": -0.25, "left": 0.0, "yaw": -1.10, "n": 190}, + {"kind": "pose", "q": _arms(-0.90, 0.60, 0.45, 0.0, 0.35), "n": 100, "grip": 1.0}, + {"kind": "turn", "yaw": 0.0, "rate": 0.20, "n": 260}, + {"kind": "move", "forward": 0.35, "left": 0.0, "yaw": 0.0, "n": 280, "speed": 0.10}, + {"kind": "pose", "q": _arms(-0.75, 0.70, 0.30, 0.0, 0.35), "n": 120, "grip": 1.0, "pitch": 0.15}, + # Open and spread the hands so the box is left supported. + {"kind": "pose", "q": _arms(-0.75, 0.70, 0.30, 0.15, -0.15), "n": 100, "grip": 0.0, "pitch": 0.15}, + {"kind": "wait", "n": 180}, + ] + + def _advance(self): + self.i += 1 + self.k = 0 + self.enter = True + self.visual_hits = 0 + + def _box(self, image): + """Locate the bright cardboard side, rejecting the dark table trim.""" + im = np.asarray(image) + r = im[:, :, 0].astype(np.int16) + g = im[:, :, 1].astype(np.int16) + b = im[:, :, 2].astype(np.int16) + mask = ((r > 110) & (r < 240) & (g > 75) & + (r > g + 7) & (g > b + 18) & (b < 160)).astype(np.uint8) + mask[66:, :] = 0 + count, labels, stats, centroids = cv2.connectedComponentsWithStats(mask, 8) + best = None + best_area = 0 + for j in range(1, count): + x, y, w, h, area = (int(v) for v in stats[j]) + if area < 20 or w < 4 or h < 5 or w > 65: + continue + if area > best_area: + best_area = area + best = (float(centroids[j, 0]), float(y + h - 1)) + return best + + @staticmethod + def _walking_speed(value, limit): + value = float(np.clip(value, -limit, limit)) + if 0.0 < abs(value) < 0.06: + return np.copysign(0.06, value) + return value + + def act(self, obs, tools): + if self.i >= len(self.program): + raw = self.last_raw.copy() + raw[0] = raw[1] = raw[3] = 0.0 + return raw + + p = self.program[self.i] + kind = p["kind"] + state = obs["low_dim_obs"] + pose = state[21:25] + yaw = float(pose[3]) + vx = vy = wz = 0.0 + + if self.enter: + self.q0 = self.q.copy() + self.h0 = self.height + self.p0 = self.pitch + self.g0 = self.grip + if kind == "move": + heading = p["yaw"] + c, s = np.cos(heading), np.sin(heading) + self.target_xy = pose[:2] + np.array([c, s]) * p["forward"] + np.array([-s, c]) * p["left"] + self.enter = False + + if kind == "pose": + u = min(1.0, (self.k + 1) / max(1.0, p["n"] * 0.70)) + self.q = self.q0 + (p["q"] - self.q0) * u + self.height = self.h0 + (p.get("height", self.h0) - self.h0) * u + self.pitch = self.p0 + (p.get("pitch", self.p0) - self.p0) * u + self.grip = self.g0 + (p["grip"] - self.g0) * u + complete = self.k + 1 >= p["n"] + + elif kind == "turn": + error = _wrap(p["yaw"] - yaw) + if abs(error) > 0.015: + wz = float(np.clip(2.5 * error, -p["rate"], p["rate"])) + complete = (self.k > 60 and abs(error) < 0.020) or self.k + 1 >= p["n"] + + elif kind == "move": + delta = self.target_xy - pose[:2] + body_vx = np.cos(yaw) * delta[0] + np.sin(yaw) * delta[1] + body_vy = -np.sin(yaw) * delta[0] + np.cos(yaw) * delta[1] + speed = p.get("speed", 0.13) + if np.linalg.norm(delta) >= 0.018: + vx = self._walking_speed(3.0 * body_vx, speed) + vy = self._walking_speed(3.0 * body_vy, speed) + yaw_error = _wrap(p["yaw"] - yaw) + if abs(yaw_error) > 0.020: + wz = float(np.clip(2.5 * yaw_error, -0.30, 0.30)) + complete = (self.k > 45 and np.linalg.norm(delta) < 0.020) or self.k + 1 >= p["n"] + + elif kind == "visual": + feature = self._box(tools.image("head")) + centered = False + if feature is not None: + cx, bottom = feature + ex = 32.0 - cx + ey = 34.0 - bottom + if abs(ex) > 3.0: + vy = self._walking_speed(0.005 * ex, 0.10) + if abs(ey) > 3.0: + vx = self._walking_speed(0.008 * ey, 0.09) + centered = abs(ex) <= 3.5 and abs(ey) <= 4.0 + self.visual_hits = self.visual_hits + 1 if centered else 0 + error = _wrap(p["yaw"] - yaw) + if abs(error) > 0.020: + wz = float(np.clip(2.5 * error, -0.25, 0.25)) + complete = self.visual_hits >= 25 or self.k + 1 >= p["n"] + + else: # wait + complete = self.k + 1 >= p["n"] + + raw = np.zeros(21, dtype=np.float64) + raw[0] = vx + raw[1] = vy + raw[2] = self.height + raw[3] = wz + raw[4] = self.pitch + raw[5:19] = self.q + raw[19:21] = self.grip + raw = np.nan_to_num(raw, nan=0.0, posinf=0.0, neginf=0.0) + self.last_raw = raw.copy() + self.k += 1 + if complete: + self._advance() + return raw diff --git a/policies/pick_box/kimi31pro-s2/episodes.csv b/policies/pick_box/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/kimi31pro-s2/policy.py b/policies/pick_box/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..37f5190f32ba8c5697606ed8beb026667e57e40e --- /dev/null +++ b/policies/pick_box/kimi31pro-s2/policy.py @@ -0,0 +1,302 @@ +"""Deterministic hand-written controller for the box pick-and-place task.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.base[19:21] = 0.0 + self.carry = self.base.copy() + self.reach = self.base.copy() + self.phase = 0 + self.n = 0 + self.det = None + self.stable = 0 + + @staticmethod + def _angle(x): + return (x + np.pi) % (2 * np.pi) - np.pi + + @staticmethod + def _box(im): + a = im.astype(np.float32) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + mask = ((r > 75) & (r < 235) & (r > 1.13 * g) & + (g > 1.12 * b) & (b < 145)).astype(np.uint8) + count, _, stats, cents = cv2.connectedComponentsWithStats(mask, 8) + candidates = [] + for i in range(1, count): + x, y, w, h, area = stats[i] + if area >= 4: + candidates.append((area, x, y, w, h, cents[i])) + if not candidates: + return None + return max(candidates, key=lambda z: z[0]) + + def _next(self, phase, action, carry=False): + self.phase = phase + self.n = 0 + if carry: + self.carry = action.copy() + + def act(self, obs, tools): + n = self.n + self.n += 1 + q = obs["low_dim_obs"] + yaw = q[24] + p = self.phase + a = self.base.copy() + + # Initial right turn and image-guided approach to the box. + if p == 0: + err = self._angle(-0.90 - yaw) + a[3] = np.clip(2.0 * err, -0.65, 0.65) + if n >= 114: + self._next(1, a) + elif p == 1: + if n % 2 == 0: + self.det = self._box(tools.image("head")) + if self.det is not None: + _, x, y, w, h, c = self.det + bottom = y + h + a[3] = np.clip(-0.018 * (c[0] - 42) - 0.12 * q[49], -0.4, 0.4) + a[0] = 0.17 if bottom < 50 else 0.0 + if bottom >= 50 and w >= 20: + self._next(2, a) + else: + a[3] = -0.25 + if n >= 299: + self._next(2, a) + elif p == 2: + if n >= 39: + self._next(3, a) + elif p == 3: + err = self._angle(-0.45 - yaw) + a[3] = np.clip(1.8 * err, -0.5, 0.5) + if (abs(err) < 0.03 and abs(q[49]) < 0.08) or n >= 179: + self.stable = 0 + self._next(4, a) + elif p == 4: + if n % 2 == 0: + self.det = self._box(tools.image("head")) + err = self._angle(-0.45 - yaw) + a[3] = np.clip(1.5 * err, -0.25, 0.25) + if self.det is not None: + _, x, y, w, h, c = self.det + bottom = y + h + if abs(c[0] - 42) > 3: + a[1] = -0.08 if c[0] > 42 else 0.08 + if bottom < 47: + a[0] = 0.08 + elif bottom > 53: + a[0] = -0.08 + good = abs(c[0] - 42) < 4 and 47 <= bottom <= 53 and abs(err) < 0.06 + self.stable = self.stable + 1 if good else 0 + if self.stable > 18: + self._next(5, a) + else: + self.stable = 0 + if n >= 279: + self._next(5, a) + elif p == 5: + if n >= 44: + self._next(6, a) + + # Open-hand reach, insertion along the cardboard walls, and closure. + elif p == 6: + al = min(1.0, (n + 1) / 70.0) + a[5:12] = [-0.55 * al, -0.25 * al, 0, 0.65 * al, 0, 0, 0] + a[12:19] = [-0.55 * al, 0.25 * al, 0, 0.65 * al, 0, 0, 0] + if n >= 99: + self.reach = a.copy() + self._next(7, a) + elif p == 7: + a = self.reach.copy() + al = min(1.0, (n + 1) / 60.0) + a[19:21] = 0.0 + a[5] = a[12] = -0.55 - 0.15 * al + a[10] = a[17] = 0.15 * al + if n >= 79: + self.reach = a.copy() + self._next(8, a) + elif p == 8: + a = self.reach.copy() + a[19:21] = min(1.0, (n + 1) / 60.0) + if n >= 79: + self.reach = a.copy() + self._next(9, a) + + # Whole-body lift followed by a stable shoulder-clearing motion. + elif p == 9: + a = self.reach.copy() + al = min(1.0, (n + 1) / 90.0) if n < 120 else 1.0 + a[:5] = [0, 0, 0.74 + 0.05 * al, 0, -0.18 * al] + a[19:21] = 1.0 + if n >= 159: + self._next(10, a, carry=True) + elif p == 10: + a = self.carry.copy() + al = min(1.0, (n + 1) / 90.0) if n < 120 else 1.0 + a[:5] = [0, 0, 0.79, 0, -0.18] + a[19:21] = 1.0 + a[5] = a[12] = -0.70 - 0.20 * al + a[10] = a[17] = 0.15 + 0.20 * al + if n >= 154: + self._next(11, a, carry=True) + elif p == 11: + a = self.carry.copy() + a[0] = -0.12 if n < 60 else 0.0 + if n >= 94: + self._next(12, a, carry=True) + elif p == 12: + a = self.carry.copy() + err = self._angle(-yaw) + a[3] = np.clip(1.8 * err, -0.55, 0.55) + if (abs(err) < 0.025 and abs(q[49]) < 0.08) or n >= 229: + self._next(13, a, carry=True) + elif p == 13: + a = self.carry.copy() + if n >= 39: + self._next(14, a, carry=True) + elif p == 14: + a = self.carry.copy() + if n < 700: + a[1] = 0.08 + a[3] = np.clip(self._angle(-yaw), -0.15, 0.15) + if n >= 739: + self._next(15, a, carry=True) + elif p == 15: + a = self.carry.copy() + if n < 600 and q[21] < 0.25: + a[0] = 0.06 + a[3] = np.clip(self._angle(-yaw), -0.15, 0.15) + if n >= 639 or (q[21] >= 0.25 and n >= 39): + self._next(16, a, carry=True) + + # First placement attempt at the counter boundary. + elif p == 16: + a = self.carry.copy() + al = min(1.0, (n + 1) / 110.0) if n < 140 else 1.0 + a[:5] = [0, 0, 0.79, 0, -0.18] + a[19:21] = 1.0 + a[5] = a[12] = -0.90 - 0.15 * al + a[10] = a[17] = 0.35 + 0.15 * al + if n >= 174: + self._next(17, a, carry=True) + elif p == 17: + a = self.carry.copy() + al = min(1.0, (n + 1) / 80.0) if n < 100 else 1.0 + a[7] = a[14] = 0.20 * al + if n >= 134: + self._next(18, a, carry=True) + elif p == 18: + a = self.carry.copy() + al = min(1.0, (n + 1) / 90.0) + a[5] = a[12] = -1.05 + 0.15 * al + a[10] = a[17] = 0.50 - 0.15 * al + if n >= 109: + self._next(19, a, carry=True) + elif p == 19: + a = self.carry.copy() + al = min(1.0, (n + 1) / 110.0) if n < 140 else 1.0 + a[2] = 0.79 - 0.05 * al + a[4] = -0.18 + 0.38 * al + if n >= 179: + self._next(20, a, carry=True) + elif p == 20: + a = self.carry.copy() + a[19:21] = max(0.0, 1.0 - (n + 1) / 60.0) + if n >= 99: + self._next(21, a, carry=True) + elif p == 21: + a = self.carry.copy() + a[19:21] = 0.0 + al = min(1.0, (n + 1) / 90.0) + a[6] = -0.25 + 0.50 * al + a[13] = 0.25 - 0.50 * al + if n >= 119: + self._next(22, a, carry=True) + + # If still on the side table, visually re-center and regrasp once. + elif p == 22: + a = self.carry.copy() + if n % 2 == 0: + self.det = self._box(tools.image("head")) + a[3] = np.clip(self._angle(-yaw), -0.12, 0.12) + if self.det is not None: + _, x, y, w, h, c = self.det + bottom = y + h + if abs(c[0] - 42) > 4: + a[1] = -0.06 if c[0] > 42 else 0.06 + if bottom < 43: + a[0] = 0.06 + elif bottom > 55: + a[0] = -0.06 + good = abs(c[0] - 42) < 5 and 43 <= bottom <= 55 + self.stable = self.stable + 1 if good else 0 + if self.stable > 15 or n >= 119: + self.stable = 0 + self._next(23, a, carry=True) + elif p == 23: + a = self.carry.copy() + al = min(1.0, (n + 1) / 80.0) + a[:5] = [0, 0, 0.74, 0, 0] + a[19:21] = 0.0 + a[5:12] = [-0.858 * (1-al) - 0.70*al, 0.25*(1-al)-0.25*al, + 0.20*(1-al), 0.677*(1-al)+0.65*al, 0, 0.385*(1-al)+0.15*al, 0] + a[12:19] = [-0.858*(1-al)-0.70*al, -0.25*(1-al)+0.25*al, + 0.20*(1-al), 0.677*(1-al)+0.65*al, 0, 0.385*(1-al)+0.15*al, 0] + if n >= 99: + self.reach = a.copy() + self._next(24, a) + elif p == 24: + a = self.reach.copy() + a[19:21] = min(1.0, (n + 1) / 45.0) + if n >= 59: + self.reach = a.copy() + self._next(25, a) + elif p == 25: + a = self.reach.copy() + al = min(1.0, (n + 1) / 110.0) if n < 140 else 1.0 + a[:5] = [0, 0, 0.74 + 0.05*al, 0, -0.18*al] + a[19:21] = 1.0 + a[5] = a[12] = -0.70 - 0.35 * al + a[10] = a[17] = 0.15 + 0.35 * al + if n >= 159: + self._next(26, a, carry=True) + elif p == 26: + a = self.carry.copy() + err = self._angle(0.35 - yaw) + a[3] = np.clip(1.2 * err, -0.25, 0.25) + if (abs(err) < 0.03 and abs(q[49]) < 0.07) or n >= 179: + self._next(27, a, carry=True) + elif p == 27: + a = self.carry.copy() + al = min(1.0, (n + 1) / 90.0) + a[5] = a[12] = -1.05 + 0.15 * al + a[10] = a[17] = 0.50 - 0.15 * al + a[2] = 0.79 - 0.05 * al + a[4] = -0.18 + 0.38 * al + if n >= 109: + self._next(28, a, carry=True) + elif p == 28: + a = self.carry.copy() + a[19:21] = max(0.0, 1.0 - (n + 1) / 55.0) + if n >= 79: + self._next(29, a, carry=True) + elif p == 29: + a = self.carry.copy() + a[19:21] = 0.0 + al = min(1.0, (n + 1) / 65.0) + a[6] = -0.25 + 0.50 * al + a[13] = 0.25 - 0.50 * al + if n >= 89: + self._next(30, a, carry=True) + else: + a = self.carry.copy() + a[0] = a[1] = a[3] = 0.0 + a[19:21] = 0.0 + + return np.asarray(a, dtype=np.float32) diff --git a/policies/pick_box/kimi31pro-s3/episodes.csv b/policies/pick_box/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8c0665866b033d643ea6c5bd9ad1fc04131e7e87 --- /dev/null +++ b/policies/pick_box/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,0,4400,timeout,0 +620006,0,4400,timeout,0 +620007,0,4400,timeout,0 +620008,0,4400,timeout,0 +620009,0,4400,timeout,0 +620010,0,4400,timeout,0 +620011,0,4400,timeout,0 +620012,0,4400,timeout,0 +620013,0,4400,timeout,0 +620014,0,4400,timeout,0 +620015,0,4400,timeout,0 +620016,0,4400,timeout,0 +620017,0,4400,timeout,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,0,4400,timeout,0 +620021,0,4400,timeout,0 +620022,0,4400,timeout,0 +620023,0,4400,timeout,0 +620024,0,4400,timeout,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,0,4400,timeout,0 +620029,0,4400,timeout,0 +620030,0,4400,timeout,0 +620031,0,4400,timeout,0 +620032,0,4400,timeout,0 +620033,0,4400,timeout,0 +620034,0,4400,timeout,0 +620035,0,4400,timeout,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,0,4400,timeout,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,0,4400,timeout,0 +620046,0,4400,timeout,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,0,4400,timeout,0 +620052,0,4400,timeout,0 +620053,0,4400,timeout,0 +620054,0,4400,timeout,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,0,4400,timeout,0 +620058,0,4400,timeout,0 +620059,0,4400,timeout,0 +620060,0,4400,timeout,0 +620061,0,4400,timeout,0 +620062,0,4400,timeout,0 +620063,0,4400,timeout,0 +620064,0,4400,timeout,0 +620065,0,4400,timeout,0 +620066,0,4400,timeout,0 +620067,0,4400,timeout,0 +620068,0,4400,timeout,0 +620069,0,4400,timeout,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,0,4400,timeout,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,0,4400,timeout,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,0,4400,timeout,0 +620085,0,4400,timeout,0 +620086,0,4400,timeout,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,timeout,0 +620095,0,4400,timeout,0 +620096,0,4400,timeout,0 +620097,0,4400,timeout,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/kimi31pro-s3/policy.py b/policies/pick_box/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c2080b5196f5bd2277e0d03d9fece91550d86f38 --- /dev/null +++ b/policies/pick_box/kimi31pro-s3/policy.py @@ -0,0 +1,196 @@ +"""Deterministic hand-written controller for the G1 box-transfer task.""" + +import cv2 +import numpy as np + + +class Policy: + """Approach, grasp with both hands, and place the box on the counter.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.align_yaw = -1.10 + self.last_u = 42.0 + + self.reach = np.array([ + -.90, .35, 0, .80, 0, 0, 0, + -.90, -.35, 0, .80, 0, 0, 0, + ], dtype=np.float32) + self.squeeze = self.reach.copy() + self.squeeze[[1, 8]] = [0.0, 0.0] + self.place = self.squeeze.copy() + self.place[[0, 7]] = -1.35 + self.place[[3, 10]] = .55 + self.place[[5, 12]] = -.50 + self.release = self.place.copy() + self.release[[1, 8]] = [.35, -.35] + + @staticmethod + def _ramp(t, start, stop): + return float(np.clip((t - start) / float(stop - start), 0.0, 1.0)) + + @staticmethod + def _wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + def _drive(self, raw, q, target, speed=.20, yaw_speed=.60): + """Servo a world-frame pelvis waypoint using body-frame commands.""" + x, y, yaw = target + dx, dy = x - q[21], y - q[22] + c, s = np.cos(q[24]), np.sin(q[24]) + raw[0] = np.clip(1.45 * (c * dx + s * dy), -speed, speed) + raw[1] = np.clip(1.45 * (-s * dx + c * dy), -speed, speed) + if np.hypot(dx, dy) < .02: + raw[0] = raw[1] = 0.0 + raw[3] = np.clip(2.0 * self._wrap(yaw - q[24]), -yaw_speed, yaw_speed) + + @staticmethod + def _box_u(image): + """Find the cardboard-coloured component; return its horizontal centre.""" + rgb = image.astype(np.int16) + r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] + mask = ((r > 115) & (g > 75) & (r > b + 35) & (g > b + 15)).astype(np.uint8) + n, _, stats, centroids = cv2.connectedComponentsWithStats(mask, 8) + if n <= 1: + return None + areas = stats[1:, cv2.CC_STAT_AREA] + i = 1 + int(np.argmax(areas)) + area = stats[i, cv2.CC_STAT_AREA] + if area < 12 or area > 1800: + return None + return float(centroids[i, 0]) + + def act(self, obs, tools): + t = self.t + self.t += 1 + q = obs["low_dim_obs"] + raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + raw[19:21] = 0.0 + raw[2] = .74 + raw[5:19] = 0.0 + + # Turn toward the side table and walk to its vicinity. + if t < 100: + raw[4] = -.20 + raw[3] = np.clip(2.0 * self._wrap(-.85 - q[24]), -.60, .60) + return raw + + if t < 280: + raw[4] = -.20 + self._drive(raw, q, (.32, -.40, -.85)) + return raw + + # Align while still standing: yaw control cannot step once squatting. + if t < 460: + raw[4] = -.20 + if t < 420 and t % 4 == 0: + u = self._box_u(tools.image("head")) + if u is not None: + self.last_u = u + correction = np.clip((42.0 - u) * .0015, -.018, .018) + self.align_yaw = float(np.clip(self.align_yaw + correction, -1.42, -.78)) + self._drive(raw, q, (.43, -.43, self.align_yaw)) + return raw + + # Lower the torso and bring the open hands around the box. + if t < 560: + u = self._ramp(t, 460, 560) + self._drive(raw, q, (.43, -.43, self.align_yaw)) + raw[2] = .74 + (.64 - .74) * u + raw[4] = -.20 * (1.0 - u) + raw[5:19] = u * self.reach + return raw + + if t < 620: + self._drive(raw, q, (.43, -.43, self.align_yaw)) + raw[2] = .64 + raw[4] = 0.0 + raw[5:19] = self.reach + raw[19:21] = self._ramp(t, 560, 600) + return raw + + # Close the arms around the sides, then lift without changing hand pose. + if t < 700: + u = self._ramp(t, 620, 700) + self._drive(raw, q, (.43, -.43, self.align_yaw)) + raw[2] = .64 + raw[4] = 0.0 + raw[5:19] = (1.0 - u) * self.reach + u * self.squeeze + raw[19:21] = 1.0 + return raw + + if t < 820: + u = self._ramp(t, 700, 820) + self._drive(raw, q, (.43, -.43, self.align_yaw)) + raw[2] = .64 + .14 * u + raw[4] = 0.0 + raw[5:19] = self.squeeze + raw[19:21] = 1.0 + return raw + + # Back clear of the table before making a slow turn toward the counter. + if t < 1040: + self._drive(raw, q, (.28, -.22, self.align_yaw), speed=.16, yaw_speed=.30) + raw[2] = .78 + raw[4] = 0.0 + raw[5:19] = self.squeeze + raw[19:21] = 1.0 + return raw + + if t < 1320: + self._drive(raw, q, (.28, -.22, 0.0), speed=.14, yaw_speed=.28) + raw[2] = .78 + raw[4] = 0.0 + raw[5:19] = self.squeeze + raw[19:21] = 1.0 + return raw + + if t < 1620: + self._drive(raw, q, (.38, 0.0, 0.0), speed=.16, yaw_speed=.30) + raw[2] = .78 + raw[4] = 0.0 + raw[5:19] = self.squeeze + raw[19:21] = 1.0 + return raw + + # Extend over the counter and lean forward slightly to support the box. + if t < 1850: + u = self._ramp(t, 1620, 1850) + self._drive(raw, q, (.38, 0.0, 0.0), speed=.12, yaw_speed=.25) + raw[2] = .78 + raw[4] = .20 * u + raw[5:19] = (1.0 - u) * self.squeeze + u * self.place + raw[19:21] = 1.0 + return raw + + if t < 1950: + u = self._ramp(t, 1850, 1950) + self._drive(raw, q, (.38, 0.0, 0.0), speed=.10, yaw_speed=.20) + raw[2] = .78 + raw[4] = .20 + raw[5:19] = (1.0 - u) * self.place + u * self.release + raw[19:21] = 1.0 - self._ramp(t, 1850, 1890) + return raw + + if t < 2050: + self._drive(raw, q, (.38, 0.0, 0.0), speed=.10, yaw_speed=.20) + raw[2] = .78 + raw[4] = .20 + raw[5:19] = self.release + return raw + + # Leave the box undisturbed and withdraw the hands. + if t < 2220: + u = self._ramp(t, 2050, 2220) + self._drive(raw, q, (.22, 0.0, 0.0), speed=.12, yaw_speed=.20) + raw[2] = .78 + (.74 - .78) * u + raw[4] = .20 * (1.0 - u) + raw[5:19] = (1.0 - u) * self.release + return raw + + self._drive(raw, q, (.22, 0.0, 0.0), speed=.10, yaw_speed=.20) + raw[2] = .74 + raw[4] = 0.0 + raw[5:19] = 0.0 + return raw diff --git a/policies/pick_box/opus-s1/episodes.csv b/policies/pick_box/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..871be44b48d0a681e40b76686001d655fada766c --- /dev/null +++ b/policies/pick_box/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4400,timeout,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,0,4400,timeout,0 +620004,0,4400,timeout,0 +620005,1,2172,success,0 +620006,0,4400,fell,1 +620007,0,4400,timeout,0 +620008,1,1965,success,0 +620009,0,4400,timeout,0 +620010,1,2128,success,0 +620011,0,4400,timeout,0 +620012,1,2014,success,0 +620013,1,1781,success,0 +620014,0,4400,timeout,0 +620015,1,1947,success,0 +620016,1,2233,success,0 +620017,1,2238,success,0 +620018,0,4400,timeout,0 +620019,0,4400,timeout,0 +620020,1,2221,success,0 +620021,1,2308,success,0 +620022,1,2224,success,0 +620023,1,2082,success,0 +620024,1,2101,success,0 +620025,0,4400,timeout,0 +620026,0,4400,timeout,0 +620027,0,4400,timeout,0 +620028,1,2229,success,0 +620029,0,4400,timeout,0 +620030,1,2182,success,0 +620031,1,2280,success,0 +620032,0,4400,timeout,0 +620033,1,2066,success,0 +620034,0,4400,timeout,0 +620035,1,2126,success,0 +620036,0,4400,timeout,0 +620037,0,4400,timeout,0 +620038,0,4400,timeout,0 +620039,0,4400,timeout,0 +620040,1,2174,success,0 +620041,0,4400,timeout,0 +620042,0,4400,timeout,0 +620043,0,4400,timeout,0 +620044,0,4400,timeout,0 +620045,1,2311,success,0 +620046,1,2077,success,0 +620047,0,4400,timeout,0 +620048,0,4400,timeout,0 +620049,0,4400,timeout,0 +620050,0,4400,timeout,0 +620051,1,2165,success,0 +620052,0,4400,timeout,0 +620053,1,1980,success,0 +620054,1,2210,success,0 +620055,0,4400,timeout,0 +620056,0,4400,timeout,0 +620057,1,2109,success,0 +620058,0,4400,timeout,0 +620059,1,1956,success,0 +620060,1,2125,success,0 +620061,0,4400,timeout,0 +620062,1,2363,success,0 +620063,0,4400,timeout,0 +620064,1,2198,success,0 +620065,0,4400,timeout,0 +620066,1,2159,success,0 +620067,1,1923,success,0 +620068,0,4400,timeout,0 +620069,1,2198,success,0 +620070,0,4400,timeout,0 +620071,0,4400,timeout,0 +620072,0,4400,timeout,0 +620073,1,2176,success,0 +620074,0,4400,timeout,0 +620075,0,4400,timeout,0 +620076,0,4400,timeout,0 +620077,0,4400,timeout,0 +620078,1,1921,success,0 +620079,1,2163,success,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,1,2184,success,0 +620085,1,2082,success,0 +620086,1,2230,success,0 +620087,0,4400,timeout,0 +620088,0,4400,timeout,0 +620089,1,2272,success,0 +620090,1,2114,success,0 +620091,0,4400,timeout,0 +620092,0,4400,timeout,0 +620093,0,4400,timeout,0 +620094,0,4400,fell,1 +620095,1,1849,success,0 +620096,0,4400,timeout,0 +620097,1,2120,success,0 +620098,1,2186,success,0 +620099,1,2302,success,0 diff --git a/policies/pick_box/opus-s1/policy.py b/policies/pick_box/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0cb01cfb867d7c195fe63e30661bd83a8eda0c --- /dev/null +++ b/policies/pick_box/opus-s1/policy.py @@ -0,0 +1,435 @@ +"""Pick the cardboard box from the side table and set it down on the kitchen counter. + +Hand-written state machine: + 1. walk to a viewpoint in front of the side table (world frame, pelvis pose from obs) + 2. locate the box (head camera, colour segmentation of the box top face, ray/plane + intersection with a pinhole model of the head camera) + 3. walk in front of the box, aligned with its faces, squat + 4. bimanual squeeze (hands closed until joint tracking shows contact), lift, stand + 5. back off, walk to the counter, lower the box until contact, open hands, back off +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +# ----------------------------------------------------------------------------- kinematics + + +def _rot(axis, a): + c, s = np.cos(a), np.sin(a) + if axis == 'x': + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + if axis == 'y': + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def _rpy(r, p, y): + return _rot('z', y) @ _rot('y', p) @ _rot('x', r) + + +def _T(R, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +_TORSO = _T(np.eye(3), [-0.0039635, 0, 0.054]) + + +def _chain(side): + s = 1 if side == 'L' else -1 + return [ + ([0.0039563, s * 0.10022, 0.23778], (s * 0.27931, 5.4949e-05, -s * 0.00019159), 'y'), + ([0, s * 0.038, -0.013831], (-s * 0.27925, 0, 0), 'x'), + ([0, s * 0.00624, -0.1032], (0, 0, 0), 'z'), + ([0.015783, 0, -0.080518], (0, 0, 0), 'y'), + ([0.100, s * 0.00188791, -0.010], (0, 0, 0), 'x'), + ([0.038, 0, 0], (0, 0, 0), 'y'), + ([0.046, 0, 0], (0, 0, 0), 'z'), + ] + + +_CHAINS = {sd: [(_T(_rpy(*r), p), ax) for p, r, ax in _chain(sd)] for sd in 'LR'} +TOOL = np.array([0.137, 0.0, 0.0, 1.0]) + + +def arm_fk(q, side): + M = _TORSO.copy() + frames = [] + for (Tj, ax), qi in zip(_CHAINS[side], q): + M = M @ Tj @ _T(_rot(ax, qi), [0, 0, 0]) + frames.append(M) + return frames, (M @ TOOL)[:3] + + +_LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def _limits(side): + lo, hi = _LO.copy(), _HI.copy() + if side == 'R': + lo[1], hi[1] = -_HI[1], -_LO[1] + return lo, hi + + +WAIST = np.array([0.0, 0.0, 0.054]) + + +def level_to_torso(p, pitch): + """Point in the level pelvis frame -> frame of an upright torso when leaning by pitch.""" + R = _rot('y', pitch) + return R.T @ (np.asarray(p) - WAIST) + WAIST + + +def torso_to_level(p, pitch): + R = _rot('y', pitch) + return R @ (np.asarray(p) - WAIST) + WAIST + + +def arm_ik(target, side, q0, pitch=0.0): + """Tool point target (level pelvis frame), gripper pointing forward, elbow kept out.""" + lo, hi = _limits(side) + s_ = 1 if side == 'L' else -1 + Rt = _rot('y', pitch).T + target = level_to_torso(target, pitch) + fwd = Rt @ np.array([1.0, 0, 0]) + up = Rt @ np.array([0, 0, 1.0]) + q0 = np.clip(np.asarray(q0, float), lo + 1e-3, hi - 1e-3) + + def res(q): + fr, tip = arm_fk(q, side) + R = fr[-1][:3, :3] + r = list(tip - target) + r += list(0.3 * (R[:, 0] - fwd)) + r += list(0.3 * (R[:, 2] - up)) + r.append(min(0.0, s_ * fr[3][1, 3] - 0.2)) + r += list(0.02 * (q - q0)) + return np.array(r) + + return least_squares(res, q0, bounds=(lo, hi), max_nfev=60).x + + +# ----------------------------------------------------------------------------- vision + +CAM_PITCH, CAM_F, CAM_X, CAM_Y, CAM_Z = 1.108, 83.5, 0.079, 0.0175, 0.518 +TABLE_H = 0.55 +BOX_H = 0.29 +_CAM = _TORSO @ _T(_rot('y', CAM_PITCH), [CAM_X, CAM_Y, CAM_Z]) + + +def unproject(u, v, z_world, pelvis_z): + d = _CAM[:3, :3] @ np.array([np.ones_like(u), -(u - 41.5) / CAM_F, -(v - 41.5) / CAM_F]) + o = _CAM[:3, 3] + t = (z_world - pelvis_z - o[2]) / d[2] + return o[:, None] + t * d + + +def box_top(im, pelvis_z): + """Box top face in the yaw-aligned pelvis frame: (center xy, axis angle, n pixels).""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + h, s, v = hsv[:, :, 0], hsv[:, :, 1], hsv[:, :, 2] + brown = (h >= 5) & (h <= 25) & (s > 90) & (v > 50) + top = (h >= 18) & (h <= 35) & (s > 40) & (s <= 150) & (v > 170) + m = (brown | top).astype(np.uint8) + n, lab, st, _ = cv2.connectedComponentsWithStats(m) + if n <= 1: + return None + k = 1 + int(np.argmax(st[1:, 4])) + t = (lab == k) & top + ty, tx = np.nonzero(t) + if len(tx) < 15: + return None + uu = np.concatenate([tx + 0.25, tx + 0.75, tx + 0.25, tx + 0.75]) + vv = np.concatenate([ty + 0.25, ty + 0.25, ty + 0.75, ty + 0.75]) + Q = unproject(uu, vv, TABLE_H + BOX_H, pelvis_z) + rect = cv2.minAreaRect((Q[:2].T * 1000).astype(np.float32)) + pts = cv2.boxPoints(rect) / 1000.0 + e1, e2 = pts[1] - pts[0], pts[2] - pts[1] + ang = np.arctan2(e1[1], e1[0]) + return np.array(rect[0]) / 1000.0, ang, np.linalg.norm(e1), np.linalg.norm(e2) + + +# ----------------------------------------------------------------------------- helpers + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +VIEW = (0.10, -0.90, 0.0) # viewpoint in front of the side table +GRASP_D = 0.29 # pelvis -> box centre (vision units) at grasp +GRASP_PITCH = 0.45 # torso lean while grasping +REACH_OFF = 0.047 # tool x = box centre distance + REACH_OFF + DEPTH_K*(depth-0.12) +DEPTH_K = 0.6 +GRASP_Z = -0.03 # tool z at grasp (pelvis frame), above the box's centre of mass +SQ_EXTRA = 0.06 # squeeze beyond contact +LIFT_X, LIFT_Z = 0.33, 0.28 +CARRY_V = 0.14 +PLACE_X = 0.40 # push the box this far forward over the counter before lowering +COUNTER = (0.40, 0.0, 0.0) # pelvis pose for placing on the counter +SQUAT = 0.74 # pelvis height while grasping (no squat: keeps the pelvis close) +PRE = np.array([0.30, 0.20, 0.20]) # arms while walking to the table + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.a = self.hold.copy() + self.qL = np.zeros(7) + self.qR = np.zeros(7) + self.tip = PRE.copy() + self.cy_off = 0.0 + self.depth = 0.12 + self.set_tips(self.tip) + self.state = 'to_view' + self.k = 0 + self.meas = [] + self.goal = None + self.log = [] + + # -- arms + def set_tips(self, tip, c=None): + tip = np.asarray(tip, float) + if c is None: + c = self.cy_off + self.cy_off = c + off = np.array([0, c, 0]) + p = self.a[4] + self.qL = arm_ik(tip + off, 'L', self.qL, p) + self.qR = arm_ik(tip * [1, -1, 1] + off, 'R', self.qR, p) + self.a[5:12] = self.qL + self.a[12:19] = self.qR + self.tip = tip + + def tips_obs(self, L): + _, tl = arm_fk(L[3:10], 'L') + _, tr = arm_fk(L[12:19], 'R') + p = self.a[4] + return torso_to_level(tl, p), torso_to_level(tr, p) + + # -- base + def goto(self, L, tx, ty, tyaw, vmax=0.25, turn_first=True): + x, y, yaw = L[21], L[22], L[24] + dx, dy = tx - x, ty - y + c, s = np.cos(yaw), np.sin(yaw) + fx, fy = c * dx + s * dy, -s * dx + c * dy + vx = np.clip(1.5 * fx, -vmax, vmax) + vy = np.clip(1.5 * fy, -vmax, vmax) + sp = np.hypot(vx, vy) + dist = np.hypot(dx, dy) + eyaw = wrap(tyaw - yaw) + if dist < 0.012: + vx = vy = 0.0 + elif sp < 0.06: + vx, vy = vx / sp * 0.06, vy / sp * 0.06 + if turn_first and abs(eyaw) > 0.4: + vx = vy = 0.0 + self.a[0], self.a[1] = vx, vy + self.a[3] = np.clip(2.0 * eyaw, -0.6, 0.6) + return dist, abs(eyaw) + + def stop(self): + self.a[0] = self.a[1] = self.a[3] = 0.0 + + def goto_state(self, s): + self.state = s + self.k = 0 + self.best = (1e9, 0) + + def stalled(self, d, n=40): + if d < self.best[0] - 0.005: + self.best = (d, self.k) + return self.k - self.best[1] > n + + def measure_box(self, L, tools): + r = box_top(tools.image('head'), L[23]) + if r is None: + return None + (px, py), ang, l1, l2 = r + yaw = L[24] + c, s = np.cos(yaw), np.sin(yaw) + wx = L[21] + c * px - s * py + wy = L[22] + s * px + c * py + a1 = wrap(ang + yaw) + axis = (a1 + np.pi / 4) % (np.pi / 2) - np.pi / 4 + # edge 1 runs along a1: it is the depth if it is (anti)parallel to the approach axis + depth = l1 if abs(wrap(2 * (a1 - axis))) < 1.0 else l2 + return np.array([wx, wy, axis, depth]) + + def plan_grasp(self): + m = np.array(self.meas) + cx, cy = np.median(m[:, 0]), np.median(m[:, 1]) + ax = np.median(m[:, 2]) + self.depth = np.median(m[:, 3]) + self.box = (cx, cy, ax) + gx = cx - GRASP_D * np.cos(ax) + gy = cy - GRASP_D * np.sin(ax) + self.goal = (gx, gy, ax) + + # -- main + def act(self, obs, tools): + L = np.asarray(obs['low_dim_obs'], dtype=np.float64) + self.k += 1 + st = self.state + if st == 'to_view': + d, e = self.goto(L, *VIEW) + if (d < 0.02 and e < 0.03) or self.k > 600: + self.stop() + self.meas = [] + self.goto_state('look') + elif st == 'look': + self.stop() + if self.k > 15: + m = self.measure_box(L, tools) + if m is not None: + self.meas.append(m) + if self.k >= 25: + if not self.meas: + self.goto_state('done') + else: + self.plan_grasp() + self.goto_state('pre_approach') + elif st == 'pre_approach': + gx, gy, gyaw = self.goal + px, py = gx - 0.15 * np.cos(gyaw), gy - 0.15 * np.sin(gyaw) + d, e = self.goto(L, px, py, gyaw) + if (d < 0.02 and e < 0.03) or self.k > 500: + self.stop() + self.meas = [] + self.goto_state('look2') + elif st == 'look2': + self.stop() + if self.k > 15: + m = self.measure_box(L, tools) + if m is not None: + self.meas.append(m) + if self.k >= 25: + if self.meas: + self.plan_grasp() + self.goto_state('approach') + elif st == 'approach': + d, e = self.goto(L, *self.goal, vmax=0.12, turn_first=False) + if (d < 0.015 and e < 0.03) or self.stalled(d) or self.k > 300: + self.stop() + self.goto_state('squat') + elif st == 'squat': + self.stop() + f = min(1.0, self.k / 50) + self.a[2] = 0.74 + (SQUAT - 0.74) * f + self.a[4] = GRASP_PITCH * f + self.set_tips(self.tip) + if self.k > 50: + self.start_tip = self.tip.copy() + self.goto_state('reach') + elif st == 'reach': + if self.k == 1: + cx, cy, _ = self.box + yaw = L[24] + dx, dy = cx - L[21], cy - L[22] + along = np.cos(yaw) * dx + np.sin(yaw) * dy + cross = -np.sin(yaw) * dx + np.cos(yaw) * dy + self.rx = float(np.clip(along + REACH_OFF + DEPTH_K * (self.depth - 0.12), 0.34, 0.50)) + self.cy_goal = float(np.clip(cross, -0.05, 0.05)) + self.start_tip = self.tip.copy() + n1, n2 = 40, 50 + if self.k <= n1: + t = self.start_tip + (np.array([self.rx, 0.20, 0.15]) - self.start_tip) * self.k / n1 + else: + t = np.array([self.rx, 0.20, 0.15 + (GRASP_Z - 0.15) * min(1, (self.k - n1) / n2)]) + self.set_tips(t, self.cy_goal * min(1, self.k / n1)) + if self.k >= n1 + n2 + 10: + self.goto_state('squeeze') + elif st == 'squeeze': + y = max(0.06, 0.20 - 0.001 * self.k) + t = self.tip.copy() + t[1] = y + self.set_tips(t, self.cy_off) + tl, tr = self.tips_obs(L) + el, er = tl[1] - self.cy_off - y, self.cy_off - tr[1] - y + if self.k == 25: + self.e0 = (el, er) + if self.k > 25 and el - self.e0[0] > 0.012 and er - self.e0[1] > 0.012: + self.hw = (tl[1] - tr[1]) / 2 + self.sq_from = t.copy() + self.goto_state('press') + elif y <= 0.06: + self.hw = 0.08 + self.sq_from = t.copy() + self.goto_state('press') + elif st == 'press': + t = self.sq_from.copy() + t[1] = self.sq_from[1] + (self.hw - SQ_EXTRA - self.sq_from[1]) * min(1, self.k / 30) + self.set_tips(t) + if self.k >= 35: + self.lift_from = t.copy() + self.goto_state('lift') + elif st == 'lift': + tgt = np.array([LIFT_X, self.lift_from[1] - 0.01, LIFT_Z]) + f = min(1.0, self.k / 100) + self.set_tips(self.lift_from + (tgt - self.lift_from) * f) + if self.k > 100: + f2 = min(1.0, (self.k - 100) / 50) + self.a[2] = SQUAT + (0.74 - SQUAT) * f2 + self.a[4] = GRASP_PITCH * (1 - f2) + if self.k >= 170: + self.goto_state('back_off') + elif st == 'back_off': + gx, gy, gyaw = self.goal + px, py = gx - 0.25 * np.cos(gyaw), gy - 0.25 * np.sin(gyaw) + d, e = self.goto(L, px, py, gyaw, vmax=CARRY_V) + if (d < 0.03) or self.k > 300: + self.goto_state('to_counter') + elif st == 'to_counter': + d, e = self.goto(L, COUNTER[0] - 0.25, COUNTER[1], COUNTER[2], vmax=CARRY_V) + if (d < 0.02 and e < 0.03) or self.k > 800: + self.goto_state('counter_in') + elif st == 'counter_in': + d, e = self.goto(L, *COUNTER, vmax=0.1, turn_first=False) + if (d < 0.015 and e < 0.03) or self.stalled(d) or self.k > 300: + self.stop() + self.ext_from = self.tip.copy() + self.goto_state('extend') + elif st == 'extend': + self.stop() + t = self.ext_from.copy() + t[0] = self.ext_from[0] + (PLACE_X - self.ext_from[0]) * min(1, self.k / 50) + self.set_tips(t) + if self.k >= 60: + self.place_from = self.tip.copy() + self.goto_state('lower') + elif st == 'lower': + self.stop() + t = self.place_from.copy() + t[2] = self.place_from[2] - 0.0006 * self.k + self.set_tips(t) + tl, tr = self.tips_obs(L) + ez = (tl[2] + tr[2]) / 2 - t[2] + if self.k == 10: + self.ez0 = ez + if (self.k > 10 and ez - self.ez0 > 0.015) or t[2] < -0.15: + self.rel_from = t.copy() + self.goto_state('release') + elif st == 'release': + t = self.rel_from.copy() + t[1] = self.rel_from[1] + 0.07 * min(1, self.k / 40) + self.set_tips(t) + if self.k >= 50: + self.rel_from = t.copy() + self.goto_state('retreat') + elif st == 'retreat': + t = self.rel_from.copy() + t[0] -= 0.1 * min(1, self.k / 50) + self.set_tips(t) + if self.k > 50: + d, e = self.goto(L, COUNTER[0] - 0.25, COUNTER[1], COUNTER[2], vmax=0.1, turn_first=False) + if self.k > 200: + self.stop() + self.goto_state('done') + else: + self.stop() + self.log.append((st, self.k)) + return self.a.astype(np.float32).tolist() diff --git a/policies/pick_box/opus-s2/episodes.csv b/policies/pick_box/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..9fcef21cc92db963ac46a1787b2f6be735dc84f8 --- /dev/null +++ b/policies/pick_box/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,2134,success,0 +620001,1,1847,success,0 +620002,1,1921,success,0 +620003,1,2118,success,0 +620004,1,2169,success,0 +620005,1,1953,success,0 +620006,1,1853,success,0 +620007,1,2118,success,0 +620008,1,1884,success,0 +620009,1,1919,success,0 +620010,1,1967,success,0 +620011,1,2173,success,0 +620012,1,1910,success,0 +620013,1,2117,success,0 +620014,1,1885,success,0 +620015,1,1954,success,0 +620016,1,1907,success,0 +620017,1,1953,success,0 +620018,1,1859,success,0 +620019,1,1907,success,0 +620020,1,1964,success,0 +620021,1,1954,success,0 +620022,1,1967,success,0 +620023,1,1888,success,0 +620024,1,2116,success,0 +620025,1,1914,success,0 +620026,1,1864,success,0 +620027,1,2125,success,0 +620028,1,1955,success,0 +620029,1,2188,success,0 +620030,1,1908,success,0 +620031,1,1937,success,0 +620032,0,4400,timeout,0 +620033,1,1906,success,0 +620034,1,1919,success,0 +620035,1,1893,success,0 +620036,1,2126,success,0 +620037,1,1861,success,0 +620038,1,1902,success,0 +620039,1,2131,success,0 +620040,1,1907,success,0 +620041,1,1941,success,0 +620042,1,1938,success,0 +620043,1,2118,success,0 +620044,1,1884,success,0 +620045,1,2091,success,0 +620046,1,1909,success,0 +620047,1,1898,success,0 +620048,1,2147,success,0 +620049,1,1938,success,0 +620050,1,1871,success,0 +620051,1,1917,success,0 +620052,1,2117,success,0 +620053,1,1916,success,0 +620054,1,1912,success,0 +620055,1,1931,success,0 +620056,1,1944,success,0 +620057,1,1969,success,0 +620058,1,1907,success,0 +620059,1,1943,success,0 +620060,1,1957,success,0 +620061,1,2229,success,0 +620062,1,1937,success,0 +620063,1,2142,success,0 +620064,1,1932,success,0 +620065,1,1880,success,0 +620066,1,1954,success,0 +620067,1,1914,success,0 +620068,1,1940,success,0 +620069,1,1902,success,0 +620070,1,1906,success,0 +620071,1,1936,success,0 +620072,1,2143,success,0 +620073,1,1965,success,0 +620074,1,2107,success,0 +620075,1,1945,success,0 +620076,1,2107,success,0 +620077,1,2170,success,0 +620078,1,1917,success,0 +620079,1,1959,success,0 +620080,1,1854,success,0 +620081,1,1845,success,0 +620082,1,1919,success,0 +620083,1,1877,success,0 +620084,1,1901,success,0 +620085,1,1908,success,0 +620086,1,1911,success,0 +620087,1,1886,success,0 +620088,1,1864,success,0 +620089,1,1909,success,0 +620090,1,1951,success,0 +620091,1,1871,success,0 +620092,1,2203,success,0 +620093,1,1909,success,0 +620094,1,1916,success,0 +620095,1,1969,success,0 +620096,1,1914,success,0 +620097,1,1986,success,0 +620098,1,1957,success,0 +620099,1,1843,success,0 diff --git a/policies/pick_box/opus-s2/policy.py b/policies/pick_box/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3ede1bbc04097e8b54572e597a0f8228835a42d9 --- /dev/null +++ b/policies/pick_box/opus-s2/policy.py @@ -0,0 +1,352 @@ +"""Pick the cardboard box from the side table and set it on the kitchen counter. + +Hand-written state machine (world frame: the robot starts facing +x toward the +counter; the side table is to its right, along the same wall): + side side-step right (facing +x) until the box is in view of the head camera + align servo laterally on the box's image column, walk up to the table + look stand still briefly (settle; box image statistics are recorded) + crouch squat + lean forward, arms open wide above the table + lower lower the open hands to just above the table top + squeeze close each hand until it stalls on the box, then press 5 cm further + lift stand up / un-lean with the hands kept level (task-space IK), raise the box + back step back from the table + toc side-step left to the counter's y + approach walk forward until the legs touch the counter + reach raise the box, push it out, then lean forward over the counter + place lower the box onto the counter + release open the arms, straighten up, step back +Arm poses come from forward kinematics of the G1 arm (URDF geometry) and a +numeric inverse kinematics solve for hand-tip targets. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +# ----------------------------------------------------------------------------- kinematics + + +def _rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def _ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def _rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +_AX = {"x": _rx, "y": _ry, "z": _rz} + + +def _chain(side): + sg = 1 if side == "L" else -1 + return [ + ((0.0039563, sg * 0.10022, 0.23778), (sg * 0.27931, 0, 0), "y"), + ((0, sg * 0.038, -0.013831), (-sg * 0.27925, 0, 0), "x"), + ((0, sg * 0.00624, -0.1032), (0, 0, 0), "z"), + ((0.015783, 0, -0.080518), (0, 0, 0), "y"), + ((0.100, sg * 0.00188791, -0.010), (0, 0, 0), "x"), + ((0.038, 0, 0), (0, 0, 0), "y"), + ((0.046, 0, 0), (0, 0, 0), "z"), + ] + + +_CHAINS = {s: _chain(s) for s in "LR"} +TORSO_OFF = np.array([-0.0039635, 0, 0.054]) # waist pitch pivot above the pelvis + + +def fk(q, side, tool=0.10): + """Hand-tip position and hand rotation in the torso frame.""" + R = np.eye(3) + p = np.zeros(3) + for (xyz, r, ax), qi in zip(_CHAINS[side], q): + p = p + R @ np.array(xyz) + R = R @ _rx(r[0]) @ _AX[ax](qi) + return p + R @ np.array([tool, 0, 0]), R + + +def tip_world(q, side, lean): + """Hand-tip position / rotation relative to the pelvis, torso pitched by lean.""" + tp, R = fk(q, side) + Rw = _ry(lean) + return TORSO_OFF + Rw @ tp, Rw @ R + + +_LO = np.array([-2.5, -1.5, -2.5, -1.0, -1.9, -1.6, -1.6]) +_HI = np.array([2.6, 2.2, 2.6, 2.0, 1.9, 1.6, 1.6]) + + +def ik(target, side, lean, q0=None): + """Joint angles putting the hand tip at target (pelvis frame), hand level and pointing forward.""" + if q0 is None: + q0 = np.zeros(7) + lo, hi = _LO.copy(), _HI.copy() + if side == "R": + lo[1], hi[1] = -2.2, 1.5 + want_x = np.array([1.0, 0, 0]) + + def res(q): + p, R = tip_world(q, side, lean) + r = list((p - target) * 10) + r += list((R[:, 0] - want_x) * 0.3) + r += [R[2, 1] * 0.3] + r += list(q * 0.02) + return r + + return least_squares(res, np.clip(q0, lo + 1e-6, hi - 1e-6), bounds=(lo, hi)).x + + +YGRID = np.round(np.arange(0.0, 0.2601, 0.01), 3) + + +class PoseFamily: + """IK solutions over hand half-spacing y for a fixed tip (x, z) and torso lean.""" + + def __init__(self, x, z, lean): + self.lean = lean + self.q = {} + for side, sg in (("L", 1), ("R", -1)): + qs, q0 = [], None + for y in YGRID[::-1]: + q0 = ik(np.array([x, sg * y, z]), side, lean, q0) + qs.append(q0) + self.q[side] = np.array(qs[::-1]) + + def at(self, side, y): + y = float(np.clip(y, YGRID[0], YGRID[-1])) + i = min(int((y - YGRID[0]) / 0.01), len(YGRID) - 2) + a = (y - YGRID[i]) / 0.01 + return (1 - a) * self.q[side][i] + a * self.q[side][i + 1] + + def pair(self, yl, yr=None): + return self.at("L", yl), self.at("R", yl if yr is None else yr) + + +# ----------------------------------------------------------------------------- vision + + +def box_mask(img): + hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) + h, s, v = hsv[..., 0].astype(int), hsv[..., 1].astype(int), hsv[..., 2].astype(int) + return (h >= 8) & (h <= 35) & (s >= 50) & (v >= 60) + + +# ----------------------------------------------------------------------------- policy + +P = dict( + col_target=42, x_stop=0.37, H=0.62, lean=0.45, X=0.45, Z=0.0, Zhi=0.10, + Yopen=0.22, sq_rate=0.002, sq_press=0.06, sq_min=0.02, contact_err=0.012, + lift_T=160, carry_X=0.36, carry_Z=0.30, reach_Z=0.38, back_x=0.10, counter_y=0.0, + place_X=0.52, place_lean=0.3, place_T=200, place_Zend=0.12, open_Y=0.25, +) + +_FAMILIES = {} + + +def families(): + if not _FAMILIES: + _FAMILIES["grasp_hi"] = PoseFamily(P["X"], P["Zhi"], P["lean"]) + _FAMILIES["grasp"] = PoseFamily(P["X"], P["Z"], P["lean"]) + return _FAMILIES + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.F = families() + self.phase = "side" + self.t0 = 0 + self.col = None + self.q0 = (np.array([0, 0.25, 0, 0, 0, 0, 0.0]), np.array([0, -0.25, 0, 0, 0, 0, 0.0])) + self.ycmd = {"L": P["Yopen"], "R": P["Yopen"]} + self.yhold = {"L": None, "R": None} + self.xprev = [] + self.qcur = None + self.stats = [] + self.boxstat = None + self.task_key = None + self.sq_done = None + self.stop = False + + def _arms(self, raw, qa, qb=None, a=1.0): + if qb is None: + qb = qa + a = float(np.clip(a, 0, 1)) + raw[5:12] = (1 - a) * qa[0] + a * qb[0] + raw[12:19] = (1 - a) * qa[1] + a * qb[1] + + def _go(self, phase, t): + self.phase, self.t0 = phase, t + + def _held(self, fam): + return self.F[fam].pair(self.yhold["L"], self.yhold["R"]) + + def act(self, obs, tools): + lo = obs["low_dim_obs"] + t = int(obs["t"]) + raw = self.hold.copy() + raw[2] = 0.74 + raw[4] = 0.0 + raw[19] = raw[20] = 0.6 + x, y, yaw = lo[21], lo[22], lo[24] + raw[3] = np.clip(1.5 * (0 - yaw), -0.6, 0.6) + ph = self.phase + dt = t - self.t0 + self._arms(raw, self.q0) + F = self.F + + if ph in ("side", "align"): + m = box_mask(tools.image("head")) + xs = np.nonzero(m)[1] + self.col = xs.mean() if len(xs) > 30 else None + + if ph == "side": + raw[1] = np.clip(1.5 * (-0.8 - y), -0.25, 0.25) + if y < -0.78 or dt > 400: + self._go("align", t) + elif ph == "align": + if self.col is not None: + e = self.col - P["col_target"] + vy = np.clip(-0.01 * e, -0.15, 0.15) if abs(e) > 1.5 else 0.0 + if vy != 0 and abs(vy) < 0.06: + vy = 0.06 * np.sign(vy) + raw[1] = vy + if x < P["x_stop"]: + if abs(e) < 3: + raw[0] = 0.12 + elif abs(e) < 6: + raw[0] = 0.08 + if x >= P["x_stop"] or dt > 600: + self._go("look", t) + elif ph == "look": + # stand still and measure where the box lies on the table + if dt >= 20: + m = box_mask(tools.image("head")) + ys, xs = np.nonzero(m) + if len(ys) > 30: + self.stats.append((ys.mean(), ys.min(), ys.max(), xs.min(), xs.max(), len(ys))) + if dt >= 40: + self.boxstat = np.mean(self.stats, 0) if self.stats else None + self._go("crouch", t) + elif ph == "crouch": + a = min(1, dt / 100) + raw[4] = a * P["lean"] + raw[2] = 0.74 + a * (P["H"] - 0.74) + self._arms(raw, self.q0, F["grasp_hi"].pair(P["Yopen"]), a) + if dt > 120: + self._go("lower", t) + elif ph == "lower": + raw[4], raw[2] = P["lean"], P["H"] + self._arms(raw, F["grasp_hi"].pair(P["Yopen"]), F["grasp"].pair(P["Yopen"]), dt / 50) + if dt > 70: + self._go("squeeze", t) + elif ph == "squeeze": + raw[4], raw[2] = P["lean"], P["H"] + qm = {"L": lo[3:10], "R": lo[12:19]} + for s, sg in (("L", 1), ("R", -1)): + if self.yhold[s] is None: + qc = F["grasp"].at(s, self.ycmd[s]) + yc = sg * tip_world(qc, s, P["lean"])[0][1] + ya = sg * tip_world(qm[s], s, P["lean"])[0][1] + if ya - yc > P["contact_err"]: + self.yhold[s] = max(P["sq_min"], ya - P["sq_press"]) + elif self.ycmd[s] <= P["sq_min"] + 0.04: + self.yhold[s] = P["sq_min"] + else: + self.ycmd[s] -= P["sq_rate"] + if self.yhold[s] is not None: + self.ycmd[s] = max(self.yhold[s], self.ycmd[s] - 2 * P["sq_rate"]) + self._arms(raw, F["grasp"].pair(self.ycmd["L"], self.ycmd["R"])) + done = all(self.yhold[s] is not None and self.ycmd[s] <= self.yhold[s] for s in "LR") + if done and self.sq_done is None: + self.sq_done = t + if (done and t - self.sq_done > 25) or dt > 200: + for s in "LR": + if self.yhold[s] is None: + self.yhold[s] = self.ycmd[s] + self._go("lift", t) + elif ph == "lift": + # task-space lift: hands stay level while the torso straightens + a = min(1, dt / P["lift_T"]) + a = a * a * (3 - 2 * a) + raw[2] = P["H"] + a * (0.74 - P["H"]) + self._task(raw, P["X"] + a * (P["carry_X"] - P["X"]), P["Z"] + a * (P["carry_Z"] - P["Z"]), + (1 - a) * P["lean"]) + if dt > P["lift_T"] + 20: + self._go("back", t) + elif ph == "back": + self._task(raw, P["carry_X"], P["carry_Z"], 0.0) + raw[0] = np.clip(2.0 * (P["back_x"] - x), -0.2, -0.06) if x > P["back_x"] + 0.02 else 0.0 + if (x <= P["back_x"] + 0.02 and dt > 30) or dt > 400: + self._go("toc", t) + elif ph == "toc": + self._task(raw, P["carry_X"], P["carry_Z"], 0.0) + ey = P["counter_y"] - y + raw[1] = np.clip(1.2 * ey, -0.25, 0.25) if abs(ey) > 0.03 else 0.0 + if raw[1] != 0 and abs(raw[1]) < 0.07: + raw[1] = 0.07 * np.sign(raw[1]) + raw[0] = np.clip(1.0 * (P["back_x"] - x), -0.1, 0.1) + if abs(raw[0]) < 0.06: + raw[0] = 0.0 + if (abs(ey) < 0.04 and dt > 30) or dt > 600: + self._go("approach", t) + elif ph == "approach": + self._task(raw, P["carry_X"], P["carry_Z"], 0.0) + raw[0] = 0.12 + ey = P["counter_y"] - y + raw[1] = np.clip(1.0 * ey, -0.1, 0.1) if abs(ey) > 0.05 else 0.0 + if raw[1] != 0 and abs(raw[1]) < 0.06: + raw[1] = 0.06 * np.sign(raw[1]) + self.xprev.append(x) + stalled = len(self.xprev) > 60 and self.xprev[-1] - self.xprev[-40] < 0.02 + if stalled or dt > 500: + self._go("reach", t) + elif ph == "reach": + # raise the box above the counter edge first, then lean and extend over the counter + # (the box may hang upright in front of the head: move it out before leaning) + a = min(1, dt / 60) + a = a * a * (3 - 2 * a) + b = min(1, max(0, dt - 60) / 100) + b = b * b * (3 - 2 * b) + xm = P["carry_X"] + 0.1 + self._task(raw, P["carry_X"] + a * (xm - P["carry_X"]) + b * (P["place_X"] - xm), + P["carry_Z"] + a * (P["reach_Z"] - P["carry_Z"]), b * P["place_lean"]) + if dt > 170: + self._go("place", t) + elif ph == "place": + a = min(1, dt / P["place_T"]) + self._task(raw, P["place_X"], P["reach_Z"] + a * (P["place_Zend"] - P["reach_Z"]), P["place_lean"]) + if dt > P["place_T"] + 20: + self._go("release", t) + elif ph == "release": + a = min(1, dt / 40) + yo = {s: self.yhold[s] + a * (P["open_Y"] - self.yhold[s]) for s in "LR"} + b = min(1, max(0, dt - 50) / 80) + self._task(raw, P["place_X"] - 0.1 * b, P["place_Zend"] + 0.05 * a, (1 - b) * P["place_lean"], yo["L"], yo["R"]) + if dt > 140: + raw[0] = -0.1 if dt < 260 else 0.0 + if dt > 260: + self.stop = True + return raw + + def _task(self, raw, x, z, lean, yl=None, yr=None): + """Hands at tip (x, +-y, z) relative to the pelvis, level, torso pitched by lean (IK, warm-started).""" + yl = self.yhold["L"] if yl is None else yl + yr = self.yhold["R"] if yr is None else yr + if self.qcur is None: + self.qcur = self._held("grasp") + key = (round(x, 4), round(z, 4), round(lean, 4), round(yl, 4), round(yr, 4)) + if key != self.task_key: + self.qcur = ( + ik(np.array([x, yl, z]), "L", lean, self.qcur[0]), + ik(np.array([x, -yr, z]), "R", lean, self.qcur[1]), + ) + self.task_key = key + raw[4] = lean + self._arms(raw, self.qcur) diff --git a/policies/pick_box/opus-s3/episodes.csv b/policies/pick_box/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b49d82b3bb2f4aac22f9600ec09e72c42e01d521 --- /dev/null +++ b/policies/pick_box/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,1628,success,0 +620001,0,4400,timeout,0 +620002,0,4400,timeout,0 +620003,1,1551,success,0 +620004,1,1555,success,0 +620005,1,1513,success,0 +620006,1,2662,success,0 +620007,1,1606,success,0 +620008,1,1674,success,0 +620009,1,1553,success,0 +620010,0,4400,timeout,0 +620011,1,1538,success,0 +620012,0,4400,timeout,0 +620013,1,1483,success,0 +620014,1,1903,success,0 +620015,0,4400,timeout,0 +620016,1,1510,success,0 +620017,1,1652,success,0 +620018,0,4400,timeout,0 +620019,1,1600,success,0 +620020,1,1462,success,0 +620021,1,1536,success,0 +620022,1,2283,success,0 +620023,1,1476,success,0 +620024,0,4400,timeout,0 +620025,1,1546,success,0 +620026,1,2165,success,0 +620027,1,1511,success,0 +620028,1,1692,success,0 +620029,1,1559,success,0 +620030,0,4400,timeout,0 +620031,1,1568,success,0 +620032,1,1545,success,0 +620033,1,1996,success,0 +620034,1,1497,success,0 +620035,1,1727,success,0 +620036,1,1629,success,0 +620037,1,1862,success,0 +620038,1,1612,success,0 +620039,1,1522,success,0 +620040,1,1691,success,0 +620041,0,4400,timeout,0 +620042,1,1521,success,0 +620043,1,1848,success,0 +620044,1,1558,success,0 +620045,0,4400,timeout,0 +620046,1,1493,success,0 +620047,0,4400,timeout,0 +620048,1,1470,success,0 +620049,1,1673,success,0 +620050,0,4400,timeout,0 +620051,1,1516,success,0 +620052,1,1633,success,0 +620053,1,1500,success,0 +620054,1,1581,success,0 +620055,1,1546,success,0 +620056,1,2030,success,0 +620057,0,4400,timeout,0 +620058,1,1557,success,0 +620059,1,1568,success,0 +620060,0,4400,timeout,0 +620061,1,1563,success,0 +620062,0,4400,timeout,0 +620063,1,1685,success,0 +620064,1,1751,success,0 +620065,0,4400,timeout,0 +620066,1,1642,success,0 +620067,1,1586,success,0 +620068,1,1537,success,0 +620069,1,1478,success,0 +620070,1,1677,success,0 +620071,1,1639,success,0 +620072,1,1582,success,0 +620073,1,1935,success,0 +620074,0,4400,timeout,0 +620075,1,1555,success,0 +620076,1,1448,success,0 +620077,1,2168,success,0 +620078,1,1535,success,0 +620079,0,4400,timeout,0 +620080,0,4400,timeout,0 +620081,0,4400,timeout,0 +620082,0,4400,timeout,0 +620083,0,4400,timeout,0 +620084,1,1519,success,0 +620085,1,2015,success,0 +620086,1,1538,success,0 +620087,1,1644,success,0 +620088,0,4400,timeout,0 +620089,0,4400,timeout,0 +620090,0,4400,timeout,0 +620091,0,4400,timeout,0 +620092,1,1606,success,0 +620093,0,4400,timeout,0 +620094,1,2234,success,0 +620095,1,1480,success,0 +620096,1,1479,success,0 +620097,1,1514,success,0 +620098,0,4400,timeout,0 +620099,0,4400,timeout,0 diff --git a/policies/pick_box/opus-s3/policy.py b/policies/pick_box/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..eec19aa25a684e31969ba02acfacece26952307c --- /dev/null +++ b/policies/pick_box/opus-s3/policy.py @@ -0,0 +1,458 @@ +"""Pick the cardboard box from the side table and set it on the kitchen counter. + +Hand-written state machine: + 1. lean back slightly (the posture the head camera model was calibrated in) + 2. walk to a fixed observation pose, estimate the box pose (x, y, yaw) from + the yellow top face seen by the head camera (pinhole model + least squares) + 3. walk to a stance in front of the box, aligned with one of its axes, and + re-estimate the box from close range + 4. squat + lean forward, bimanual squeeze grasp: world-frame hand waypoints + re-solved every step against the current pelvis pose (analytic FK + IK) + 5. stand up leaning back (raises the box), walk to the counter; the box + touching down on the counter top completes the task (else squat to set + it down), then release and step back. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +# ---------------------------------------------------------------------------- +# head camera model, pelvis frame, posture height 0.74 / pitch -0.2 +F, CDX, CAMZ, PHI = 69.984, 0.0823, 0.3845, 0.9236 # CAMZ: camera height above the box top +BOX_TOP_REL = 0.0 # box top relative to the standing pelvis height +BW, BD = 0.1097, 0.1856 # box top face dimensions (box x, box y) + +OBS_POSE = (0.2, -0.5, -0.8) +DEFAULT_BOX = (0.72, -1.01, 0.0) + +P = dict( + dist=0.315, # pelvis to box centre at the stance + max_heading=np.pi, # stance heading limit (clipping it was tried: worse) + align_rot=False, # rotating the grippers to the box faces (tried: worse) + grip_depth=0.15, # grasp this far below the box top + grasp_h=0.62, # pelvis height command while grasping + grasp_pitch=0.15, # torso lean while grasping (extends the reach) + carry_h=0.78, + carry_pitch=-0.2, # leaning back raises the box by ~8 cm + dn=(0.15, 0, -1), # hand direction while grasping + open_m=0.07, # lateral clearance before squeeze + squeeze=0.06, # commanded penetration + lift=0.08, # hands raised this much (world) while still squatting + dn_lift=(0.4, 0, -1), + counter_x=0.42, # pelvis x at the counter + place_h=0.66, # squat to this height to set the box down +) + + +def wrap(a): + return (a + np.pi) % (2*np.pi) - np.pi + + +def top_mask(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] + return ((h > 15) & (h < 40) & (s > 28) & (s < 170) & (v > 200)).astype(np.uint8) + + +def corners(im): + m = top_mask(im) + cs, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + if not cs: + return None + c = max(cs, key=cv2.contourArea) + if cv2.contourArea(c) < 8: + return None + peri = cv2.arcLength(c, True) + for eps in np.linspace(0.02, 0.2, 40): + ap = cv2.approxPolyDP(c, eps*peri, True) + if len(ap) == 4: + return ap[:, 0, :].astype(float) + 0.5 + return None + + +def proj_body(Pt): + fx = Pt[:, 0] - CDX + ly = Pt[:, 1] + z = Pt[:, 2] - CAMZ + Z = fx*np.cos(PHI) - z*np.sin(PHI) + Yd = -fx*np.sin(PHI) - z*np.cos(PHI) + return np.stack([F*(-ly)/Z + 42, F*Yd/Z + 42], 1) + + +def box_top_body(bx, by, th, z=BOX_TOP_REL): + loc = np.array([[BW/2, BD/2], [-BW/2, BD/2], [-BW/2, -BD/2], [BW/2, -BD/2]]) + c, s = np.cos(th), np.sin(th) + xy = loc @ np.array([[c, s], [-s, c]]) + [bx, by] + return np.c_[xy, np.full(4, z)] + + +PERMS = [] +for _k in range(4): + _p = [(j + _k) % 4 for j in range(4)] + PERMS.append(_p) + PERMS.append(_p[::-1]) + + +def est_body(im): + c = corners(im) + if c is None: + return None, 99.0 + + def res(p): + uv = proj_body(box_top_body(*p)) + best = min((np.sum((uv[q] - c)**2), q) for q in PERMS)[1] + return (uv[best] - c).ravel() + best = None + for t0 in np.linspace(-np.pi/2, np.pi/2, 6, endpoint=False): + r = least_squares(res, [0.5, 0.0, t0]) + if best is None or r.cost < best.cost: + best = r + p = best.x.copy() + p[2] = (p[2] + np.pi/2) % np.pi - np.pi/2 + return p, float(np.sqrt(np.mean(best.fun**2))) + + +# ---------------------------------------------------------------------------- +# arm kinematics (G1 29dof geometry) +def rx(a): + c, s = np.cos(a), np.sin(a) + return np.array([[1, 0, 0], [0, c, -s], [0, s, c]]) + + +def ry(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +TILT = 2*np.arcsin(0.139201) +WP0 = -0.1217 +TOOL = 0.12 +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def arm_fk(q, side, waist=WP0): + sp, sr, sy, el, wr, wp, wy = q + R = ry(waist) + p = np.array([-0.0039635, 0, 0.054]) + p = p + R @ np.array([0.0039563, side*0.10022, 0.24778]) + R = R @ rx(side*TILT) @ ry(sp) + p = p + R @ np.array([0, side*0.038, -0.013831]) + R = R @ rx(-side*TILT) @ rx(sr) + p = p + R @ np.array([0, side*0.00624, -0.1032]) + R = R @ rz(sy) + p = p + R @ np.array([0.015783, 0, -0.080518]) + R = R @ ry(el) + p = p + R @ np.array([0.100, side*0.00188791, -0.010]) + R = R @ rx(wr) + p = p + R @ np.array([0.038, 0, 0]) + R = R @ ry(wp) + p = p + R @ np.array([0.046, 0, 0]) + R = R @ rz(wy) + p = p + R @ np.array([TOOL, 0, 0]) + return p, R + + +def ik(target, fwd, side, q0, waist=WP0, rot=0.0): + """rot: rotate the desired hand orientation about the vertical axis (pelvis frame).""" + target = np.asarray(target, float) + fwd = rz(rot) @ np.asarray(fwd, float) + fwd = fwd / np.linalg.norm(fwd) + ys = rz(rot) @ np.array([0.0, float(side), 0.0]) + qn = np.array([-0.5, 0.2*side, 0, 0.5, 0, 0, 0]) + + def res(q): + p, R = arm_fk(q, side, waist) + return np.r_[3*(p - target), 0.3*(R[:, 0] - fwd), 0.2*(R[:, 1] - ys), 0.01*(q - qn), 0.02*(q - q0)] + s = least_squares(res, np.clip(q0, LO, HI), bounds=(LO, HI)) + return s.x + + +# ---------------------------------------------------------------------------- +class Policy: + """Task-queue state machine. Each task is a small generator-like record.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.a = self.hold.copy() + self.a[19:21] = 1.0 + self.tasks = [ + ('pose', dict(pitch=-0.2, n=30)), + ('walk', dict(goal=OBS_POSE, vmax=0.3, tol=0.03)), + ('settle', dict(n=25)), + ('observe', dict(n=6)), + ('call', self.plan_grasp), + ] + self.cur = None + self.ests = [] + self.box = None + self.qlast = self.a[5:19].copy() + self.log = [] + + # --- motion helpers + def goto_cmd(self, o, goal, vmax=0.3, tol=0.02, ytol=0.03): + x, y, yaw = goal + ex, ey = x - o[21], y - o[22] + c, s = np.cos(o[24]), np.sin(o[24]) + bx, by = c*ex + s*ey, -s*ex + c*ey + eyaw = wrap(yaw - o[24]) + dist = np.hypot(bx, by) + done = dist < tol and abs(eyaw) < ytol + if dist > 0.3: + # long move: face the direction of travel and walk forward + etr = wrap(np.arctan2(ey, ex) - o[24]) + sgn = 1.0 + if abs(etr) > np.pi/2 and abs(eyaw) < np.pi/2: # goal behind: walk backwards + etr, sgn = wrap(etr + np.pi), -1.0 + w = float(np.clip(2.0*etr, -0.6, 0.6)) + vx = sgn*vmax*max(0.0, np.cos(etr))**4 + if abs(vx) < 0.07: + vx = 0.0 + if abs(w) < 0.06: + w = 0.0 + return False, vx, 0.0, w + vx, vy = 2.0*bx, 2.0*by + sp = np.hypot(vx, vy) + if sp > vmax: + vx, vy = vx*vmax/sp, vy*vmax/sp + elif sp < 0.07: + if dist < tol: + vx = vy = 0.0 + else: + vx, vy = vx*0.07/sp, vy*0.07/sp + w = float(np.clip(2.0*eyaw, -0.6, 0.6)) + if abs(w) < 0.06: + w = 0.0 if abs(eyaw) < ytol else 0.06*np.sign(w) + return done, vx, vy, w + + def expand(self, wps, yb, steps_per=2, ramp=20): + """wps: (x, y_half, z, fwd); left hand at yb + y, right at yb - y (pelvis frame).""" + out = [] + ql, qr = self.qlast[:7].copy(), self.qlast[7:].copy() + prev = None + for (x, y, z, fwd) in wps: + cur = np.array([x, yb + y, yb - y, z]) + n = 1 if prev is None else max(1, int(np.ceil(np.max(np.abs(cur - prev[0])) / 0.01))) + for k in range(1, n + 1): + al = k / n + if prev is None: + pt, fw = cur, np.asarray(fwd, float) + else: + pt = prev[0] + (cur - prev[0])*al + fw = np.asarray(prev[1], float)*(1 - al) + np.asarray(fwd, float)*al + ql = ik((pt[0], pt[1], pt[3]), fw, 1, ql) + qr = ik((pt[0], pt[2], pt[3]), fw, -1, qr) + out.extend([np.r_[ql, qr]]*steps_per) + prev = (cur, fwd) + q0 = self.qlast.copy() + first = out[0] + out = [q0 + (first - q0)*(k + 1)/ramp for k in range(ramp)] + out + self.qlast = out[-1].copy() + return out + + def rel_path(self, waist, moves, steps_per=3): + """Move both hands by pelvis-frame offsets from their current FK positions. + moves: list of (dl, dr) cumulative offsets (3-vectors); orientation is held.""" + q = self.qlast.copy() + pl, Rl = arm_fk(q[:7], 1, waist) + pr, Rr = arm_fk(q[7:], -1, waist) + fl, fr = Rl[:, 0], Rr[:, 0] + out = [] + prev = (np.zeros(3), np.zeros(3)) + ql, qr = q[:7].copy(), q[7:].copy() + for dl, dr in moves: + dl, dr = np.asarray(dl, float), np.asarray(dr, float) + m = max(1, int(np.ceil(max(np.max(np.abs(dl - prev[0])), np.max(np.abs(dr - prev[1]))) / 0.01))) + for k in range(1, m + 1): + a = k / m + ql = ik(pl + prev[0] + (dl - prev[0])*a, fl, 1, ql, waist) + qr = ik(pr + prev[1] + (dr - prev[1])*a, fr, -1, qr, waist) + out.extend([np.r_[ql, qr]]*steps_per) + prev = (dl, dr) + self.qlast = out[-1].copy() + return out + + def body(self, o, x, y): + c, s = np.cos(o[24]), np.sin(o[24]) + ex, ey = x - o[21], y - o[22] + return c*ex + s*ey, -s*ex + c*ey + + # --- planning callbacks + def box_from_ests(self, default): + if not self.ests: + return default + e = np.array(self.ests) + bx, by = float(np.median(e[:, 0])), float(np.median(e[:, 1])) + th = float(e[np.argsort(e[:, 0])[len(e)//2], 2]) + return bx, by, th + + def plan_grasp(self, o): + bx, by, th = self.box_from_ests(DEFAULT_BOX) + self.log.append(('box0', (bx, by, th), len(self.ests))) + h = min((wrap(th + k*np.pi/2) for k in range(-2, 3)), key=abs) + h = float(np.clip(h, -P['max_heading'], P['max_heading'])) + self.box = (bx, by, th) + self.h = h + d = P['dist'] + ready = self.expand([(0.25, 0.25, 0.20, (1, 0, -0.5))], 0.0, ramp=30) + self.ests = [] + return [('arms', dict(q=ready + [ready[-1]]*10)), + ('walk', dict(goal=(bx - d*np.cos(h), by - d*np.sin(h), h), vmax=0.25, tol=0.02)), + ('settle', dict(n=20)), + ('observe', dict(n=6)), + ('call', self.plan_squeeze)] + + def plan_squeeze(self, o): + bx, by, th = self.box_from_ests(self.box) + self.log.append(('box1', (bx, by, th), len(self.ests))) + h = self.h + # box axis closest to the heading: squeeze across the other one + k = min(range(-2, 3), key=lambda k: abs(wrap(th + k*np.pi/2 - h))) + half = BD/2 if k % 2 == 0 else BW/2 + ax = th + k*np.pi/2 # facing axis of the box (world) + self.ax = ax + n = np.array([-np.sin(ax), np.cos(ax)]) # squeeze direction (to the left) + c = np.array([bx, by]) + om, sq = P['open_m'], P['squeeze'] + top = 0.747 + BOX_TOP_REL + zg = top - P['grip_depth'] + dn = P['dn'] + + def hp(w, z): + l, r = c + n*w, c - n*w + return np.array([l[0], l[1], r[0], r[1], z]) + up = P['dn_lift'] + way = [(hp(half + om, top + 0.08), 1, dn), (hp(half + om, zg), 2, dn), (hp(half - sq, zg), 3, dn), + (hp(half - sq, zg), 20, dn), (hp(half - sq, zg + P['lift']), 4, up)] + return [('pose', dict(pitch=P['grasp_pitch'], n=40, height=P['grasp_h'])), + ('settle', dict(n=20)), + ('track', dict(way=way)), + ('call', self.do_carry)] + + def do_carry(self, o): + xl, yl, xr, yr, z = self.track_body + self.yb = (yl + yr)/2 + c, s = np.cos(o[24]), np.sin(o[24]) + back = (o[21] - 0.25*c, o[22] - 0.25*s, o[24]) + cx = P['counter_x'] + # arms keep their joint targets; the body stands up with the box + return [('pose', dict(pitch=P['carry_pitch'], n=60, height=P['carry_h'])), + ('settle', dict(n=10)), + ('walk', dict(goal=back, vmax=0.25, tol=0.05)), + ('walk', dict(goal=(0.1, -0.3, 0.0), vmax=0.3, tol=0.06)), + ('walk', dict(goal=(cx, -self.yb, 0.0), vmax=0.2, tol=0.015)), + ('settle', dict(n=25)), + ('call', self.do_place)] + + def do_place(self, o): + return [('pose', dict(pitch=P['carry_pitch'], n=100, height=P['place_h'])), + ('settle', dict(n=20)), + ('call', self.do_release)] + + def do_release(self, o): + om = P['open_m'] + P['squeeze'] + q = self.rel_path(o[2], [((0, om, 0), (0, -om, 0)), ((-0.05, om, 0.08), (-0.05, -om, 0.08))]) + c, s = np.cos(o[24]), np.sin(o[24]) + rest = np.zeros(14) + down = [q[-1] + (rest - q[-1])*(k + 1)/40 for k in range(40)] + return [('arms', dict(q=q)), + ('pose', dict(pitch=-0.2, n=40, height=0.74)), + ('walk', dict(goal=(o[21] - 0.45*c, o[22] - 0.45*s, o[24]), vmax=0.2, tol=0.04)), + ('arms', dict(q=down)), + ('settle', dict(n=10 ** 6))] + + # --- main loop + def act(self, obs, tools): + o = np.asarray(obs['low_dim_obs'], dtype=np.float64) + a = self.a + a[0] = a[1] = a[3] = 0.0 + while self.cur is None and self.tasks and self.tasks[0][0] == 'call': + _, fn = self.tasks.pop(0) + self.tasks = fn(o) + self.tasks + if self.cur is None and self.tasks: + kind, arg = self.tasks.pop(0) + self.cur = [kind, dict(arg), 0] + self.log.append((int(obs['t']), kind)) + kind, arg, n = self.cur if self.cur else (None, None, 0) + if kind == 'pose': + if n == 0: + arg['p0'], arg['h0'] = float(a[4]), float(a[2]) + al = min(1.0, (n + 1)/arg['n']) + a[4] = arg['p0'] + (arg['pitch'] - arg['p0'])*al + a[2] = arg['h0'] + (arg.get('height', arg['h0']) - arg['h0'])*al + if n + 1 >= arg['n']: + self.cur = None + elif kind == 'walk': + done, vx, vy, w = self.goto_cmd(o, arg['goal'], arg['vmax'], arg['tol']) + dist = np.hypot(arg['goal'][0] - o[21], arg['goal'][1] - o[22]) + if n % 50 == 0: + if n > 0 and arg['d50'] - dist < 0.01 and dist < 0.08: + done = True # stalled close to the goal (blocked by furniture) + arg['d50'] = dist + if done or n > 700: + self.cur = None + else: + a[0], a[1], a[3] = vx, vy, w + elif kind == 'settle': + if n + 1 >= arg['n']: + self.cur = None + elif kind == 'observe': + p, e = est_body(tools.image('head')) + if p is not None and e < 2.0: + bx, by = self.body_inv(o, p[0], p[1]) + self.ests.append((bx, by, wrap(p[2] + o[24]))) + if n + 1 >= arg['n']: + self.cur = None + elif kind == 'track': + if n == 0: + sched = [] + way = arg['way'] + for i in range(1, len(way)): + p0, p1, spc = way[i-1][0], way[i][0], way[i][1] + f0, f1 = np.asarray(way[i-1][2], float), np.asarray(way[i][2], float) + m = max(1, int(np.ceil(np.max(np.abs(p1 - p0)) / 0.01))) + for k in range(1, m + 1): + sched.extend([(p0 + (p1 - p0)*k/m, f0 + (f1 - f0)*k/m)]*spc) + arg['sched'] = sched + arg['q0'] = self.qlast.copy() + arg['qt'] = self.track_ik(o, way[0][0], way[0][2], self.qlast) + if n < 40: + q = arg['q0'] + (arg['qt'] - arg['q0'])*(n + 1)/40 + else: + pw, fw = arg['sched'][n - 40] + q = self.track_ik(o, pw, fw, self.qlast) + q = self.qlast + np.clip(q - self.qlast, -0.06, 0.06) + a[5:19] = q + self.qlast = q.copy() + if n + 1 >= 40 + len(arg['sched']): + self.cur = None + elif kind == 'arms': + q = arg['q'] + if n < len(q): + a[5:19] = q[n] + if n + 1 >= len(q): + self.cur = None + if self.cur is not None: + self.cur[2] += 1 + return a.astype(np.float32).tolist() + + def track_ik(self, o, pw, fwd, qprev): + """World-frame hand targets [xl, yl, xr, yr, z] -> joints, using the current pelvis pose.""" + xl, yl = self.body(o, pw[0], pw[1]) + xr, yr = self.body(o, pw[2], pw[3]) + z = pw[4] - o[23] + self.track_body = (xl, yl, xr, yr, z) + rot = wrap(self.ax - o[24]) if P['align_rot'] else 0.0 # align the grippers with the box faces + ql = ik((xl, yl, z), fwd, 1, qprev[:7], o[2], rot) + qr = ik((xr, yr, z), fwd, -1, qprev[7:], o[2], rot) + return np.r_[ql, qr] + + def body_inv(self, o, x, y): + c, s = np.cos(o[24]), np.sin(o[24]) + return o[21] + c*x - s*y, o[22] + s*x + c*y diff --git a/policies/put_cups/astra-s1/episodes.csv b/policies/put_cups/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/astra-s1/policy.py b/policies/put_cups/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b98dcad1b0d15aa36fc2849849513bf84752db9d --- /dev/null +++ b/policies/put_cups/astra-s1/policy.py @@ -0,0 +1,139 @@ +"""Deterministic visual and proprioceptive control for putting away cups. + +No demonstration files, fitted models, or seed-dependent parameters are used. +""" +import numpy as np +import cv2 + + +def cup_feature(im, side): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = ((hsv[:, :, 1] < 45) & (hsv[:, :, 2] > 70) & + (hsv[:, :, 2] < 230)).astype(np.uint8) + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + candidates = [] + for k in range(1, n): + x, y, w, h, area = stats[k] + if area >= 150 and h >= 15 and y <= 35: + candidates.append(k) + if not candidates: + return None + key = lambda k: centers[k, 0] + k = min(candidates, key=key) if side == 0 else max(candidates, key=key) + ys, xs = np.where(labels == k) + bottom = float(np.percentile(ys, 97)) + tip = float(np.median(xs[ys >= bottom - 3])) + return tip, bottom + + +class Policy: + def reset(self, obs, tools): + self.action = np.asarray(tools.hold_action(), dtype=float) + self.stages = [] + self.index = 0 + self.age = 0 + self.start = self.action.copy() + self.target = self.action.copy() + self.correction = np.zeros(4) + self.retries = [0, 0] + self._build() + self._enter() + + def add(self, name, n, values=None, base=None, smooth=30, servo=(), check=None): + self.stages.append(dict(name=name, n=n, values=values or {}, base=base, + smooth=smooth, servo=servo, check=check)) + + def _build(self): + self.add('fold',70,{5:.3,12:.3,8:-1,15:-1,19:0,20:0}) + self.add('handles',100,{5:-1.8,12:-1.8,8:.2,15:.2,7:.4,14:-.4,10:1.6,17:1.6}) + self.add('reach handles',160,base=(.34,0,0)) + self.add('grasp handles',50,{19:1,20:1},(.34,0,0)) + self.add('pull doors',100,base=(.18,0,0)) + self.add('swing doors',100,{6:.8,13:-.8},(.18,0,0)) + self.add('release doors',100,{19:0,20:0},(.18,0,0)) + self.add('clear doors',100,{5:.3,12:.3,8:-1,15:-1,6:0,13:0,7:0,14:0,10:0,17:0},(.18,0,0)) + for cycle,y in enumerate([-.04,-.22]): + py = -.04 if cycle == 0 else -.18 + shelf_x = .45 if cycle == 0 else .40 + self.add('pickup hover',100 if cycle == 0 else 60,{2:.74,4:0,5:-1.5,12:-1.5,8:0,15:0,6:0,13:0,10:1.5,17:1.5,19:0,20:0},(.24,y,0),30) + self.add('cup approach',120 if cycle == 0 else 80,{5:-1.35,12:-1.35,8:1.35,15:1.35,6:.07,13:-.1,10:0,17:0},(.24,y,0),100 if cycle == 0 else 65) + self.add('align left',120 if cycle == 0 else 80,base=(.24,y,0),servo=(0,1)) + self.add('grasp left',70 if cycle == 0 else 50,{19:1},(.24,y,0)) + self.add('lift left',90 if cycle == 0 else 70,{5:-1.6,8:1.6,6:.55},(.22,y,0),75 if cycle == 0 else 60,check=0) + self.add('withdraw cup',100,base=(.0,py,0)) + self.add('raise cup',110,{5:-2.7,12:-.3,8:1.1,15:-1,6:.22,13:-.2,10:1.6,17:1.3},(.0,py,0),90) + self.add('shelf approach',180,{4:.1,10:1.5,17:1.2},(shelf_x,py,0),90) + self.add('settle shelf',70,{2:.78},(shelf_x,py,0),40) + self.add('place cup',80,{19:0,20:0},(shelf_x,py,0),40) + self.add('withdraw hands',90,base=(.14,py,0),smooth=65) + self.add('rest',500,{2:.74,4:0,5:.3,12:.3,8:-1,15:-1,6:0,13:0,10:0,17:0},(.14,-.22,0),100) + + def _enter(self): + self.age = 0 + self.start = self.action.copy() + self.target = self.action.copy() + self.target[:2] = 0 + self.target[3] = 0 + self.correction[:] = 0 + stage = self.stages[self.index] + for k, v in stage['values'].items(): + self.target[k] = v + + def act(self, obs, tools): + stage = self.stages[self.index] + if self.age >= stage['n']: + side = stage.get('check') + if side is not None and self.retries[side] == 0 and obs['low_dim_obs'][50+side] > .96 and obs['t'] < 2400: + self.retries[side] += 1 + j = 5+7*side + bx = .27 if side == 0 else .35 + retry_y = stage['base'][1] + retry = [ + dict(name='retry approach',n=70,values={j:-1.35,j+1:.07 if side == 0 else -.1,j+3:1.35,19+side:0},base=(bx,retry_y,0),smooth=50,servo=(),check=None), + dict(name='retry alignment',n=90,values={},base=(bx,retry_y,0),smooth=30,servo=(side,),check=None), + dict(name='retry grasp',n=60,values={19+side:1},base=(bx,retry_y,0),smooth=25,servo=(),check=None), + dict(name='retry lift',n=70,values={j:-1.6,j+1:.55 if side == 0 else -.55,j+3:1.6},base=(bx-.02,retry_y,0),smooth=60,servo=(),check=None), + ] + self.stages[self.index+1:self.index+1] = retry + # Reserve time for placement and withdrawal after a failed grasp. + remaining = self.stages[self.index+1:-1] + available = max(1, obs['time_limit']-obs['t']-110) + duration = sum(s['n'] for s in remaining) + if duration > available: + scale = available/duration + for s in remaining: + s['n'] = max(1, int(s['n']*scale)) + s['smooth'] = min(s['smooth'], s['n']) + if self.index < len(self.stages)-1: + self.index += 1 + self._enter() + stage = self.stages[self.index] + self.age += 1 + u = min(1., self.age/max(1,stage['smooth'])) + a = self.start+(self.target-self.start)*u + if stage['servo']: + if self.age % 5 == 1: + for side in stage['servo']: + f = cup_feature(tools.image(('left_wrist','right_wrist')[side]),side) + if f is not None: + self.correction[side] = np.clip(self.correction[side]+.0006*(42-f[0]),-.2,.2) + self.correction[side+2] = np.clip(self.correction[side+2]+.0008*(f[1]-60),-.3,.3) + for side in stage['servo']: + j=5+side*7 + a[j+1] += self.correction[side] + a[j] += self.correction[side+2] + a[j+3] -= self.correction[side+2] + if stage['base'] is not None: + p=obs['low_dim_obs'][21:25] + x,y,yaw=stage['base'] + d=np.array([x,y])-p[:2] + c,s=np.cos(p[3]),np.sin(p[3]) + v=np.array([[c,s],[-s,c]])@d*1.7 + v=np.clip(v,-.18,.18) + for k in range(2): + if abs(d[k])<.008:v[k]=0 + elif abs(v[k])<.06:v[k]=np.sign(v[k])*.06 + a[:2]=v + a[3]=np.clip((yaw-p[3])*2,-.2,.2) + self.action=a.copy() + return a.astype(np.float32) diff --git a/policies/put_cups/astra-s2/episodes.csv b/policies/put_cups/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d3bef347e7c1c2a404764f19c1d864a365bbb51e --- /dev/null +++ b/policies/put_cups/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,1,2687,success,0 +620003,1,2657,success,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,1,2635,success,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,1,2686,success,0 +620017,1,2687,success,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,1,2634,success,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,1,2622,success,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,1,2889,success,0 +620049,1,2679,success,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,1,2814,success,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,1,2826,success,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,1,2588,success,0 +620069,1,2674,success,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,1,2798,success,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,1,2654,success,0 diff --git a/policies/put_cups/astra-s2/policy.py b/policies/put_cups/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..368b059c4240ec2a07dca20b8803f05357b1d55f --- /dev/null +++ b/policies/put_cups/astra-s2/policy.py @@ -0,0 +1,252 @@ +"""Deterministic cabinet controller using wrist vision and body feedback. + +The stages open a cabinet door, visually align each gripper with a cup +handle, lift and retract the cups, then raise them clear of the cabinet +before advancing and releasing on the shelf. All geometry and gains are +hand-specified; there are no learned models or recorded action sequences. +""" +import numpy as np +import cv2 + +def head_cups(im): + p=im[:20].astype(float) + mask=((p.max(2)-p.min(2)<27)&(p.min(2)>55)&(p.max(2)<220)).astype('uint8') + n,lab,st,cs=cv2.connectedComponentsWithStats(mask,8) + candidates=[] + for i in range(1,n): + x,y,w,h,area=st[i] + if 3<=w<=28 and h>=3 and area>=12 and y<10: + candidates.append((area,float(cs[i][0]))) + candidates.sort(reverse=True) + if len(candidates)<2:return None + return (candidates[0][1]+candidates[1][1])/2 + +def cup_blob(im): + p=im.astype(float); hi=p.max(2);lo=p.min(2) + raw=((hi-lo<25)&(lo>65)&(hi<245)).astype('uint8') + mask=cv2.morphologyEx(raw,cv2.MORPH_OPEN,np.ones((5,5),np.uint8)) + mask[:3]=0;mask[:,:3]=0;mask[:,81:]=0 + contours,hierarchy=cv2.findContours(raw,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE) + holes=[] + if hierarchy is not None: + for j,c in enumerate(contours): + x,y,w,h=cv2.boundingRect(c) + if hierarchy[0,j,3]>=0 and h>=9 and h>1.7*w and w>=3: + holes.append((x+w/2,y+h/2,w,h)) + n,lab,stats,cents=cv2.connectedComponentsWithStats(mask,8) + choices=[] + for i in range(1,n): + x,y,w,h,area=stats[i] + if area<60 or w<7 or h<12 or w>77:continue + if y<4 and w>65:continue + cx,cy=cents[i];aimx=float(cx);aimy=float(y+h/2);depth=float(w) + for hx,hy,hw,hh in holes: + if y+4=80 and t%10==0 and self.aligned_at is None: + center=head_cups(tools.image('head')) + if center is not None: + self.center_error=42-center + self.base[1]=float(obs['low_dim_obs'][22])+np.clip(self.center_error*.006,-.14,.14) + if t>=170 and (abs(self.center_error)<3 or t>=350) and self.aligned_at is None:self.aligned_at=t + if self.aligned_at is not None: + self.a[4]=-.2*(1-min((t-self.aligned_at)/60,1)) + if t-self.aligned_at>=90:self.transition(obs,1) + elif self.phase==1: + g[2]=.64;g[4]=.2;g[5:12]=self.q;g[12:19]=self.qr + self.pose(g,t,90) + if t>=130:self.q=self.a[5:12].copy();self.qr=self.a[12:19].copy();self.transition(obs,2) + elif self.phase==2: + if t%10==0: + for side in (0,1): + b=cup_blob(tools.image('right_wrist' if side else 'left_wrist'));self.last_blob=b + q=self.qr if side else self.q + if b: + cx,cy,w,h,area=b + dx=np.clip(.3*(4.05/max(w,8)-4.05/62),-.005,.010) + dz=np.clip((35-cy)*.0007,-.008,.008) + q=shift(q,dx,dz) + q[1]=np.clip(q[1]+np.clip((42-cx)*.003,-.035,.035),-.7 if side else -.5,.5 if side else .7) + good=w>=57 and abs(cx-42)<5 and abs(cy-35)<8 + if side:self.qr=q;self.goodr=self.goodr+1 if good else 0 + else:self.q=q;self.good=self.good+1 if good else 0 + self.a[5:12]=self.q;self.a[12:19]=self.qr + if (self.good>=3 and self.goodr>=3) or t>=400:self.transition(obs,3) + elif self.phase==3: + self.a[19:21]=1 + if t>=60: + self.grasp=np.mean(obs['low_dim_obs'][10:12])>-.017 + self.transition(obs,4) + elif self.phase==4: + g[2]=.68;self.pose(g,t,80) + if t>=110:self.q=self.a[5:12].copy();self.qr=self.a[12:19].copy();self.transition(obs,5) + elif self.phase==5: + if t%10==0 and t<100:self.q=shift(self.q,-.008,0);self.qr=shift(self.qr,-.008,0) + self.a[5:12]=self.q;self.a[12:19]=self.qr + if t>=130:self.transition(obs,6) + elif self.phase==6: + g[2]=.74;g[4]=0;self.pose(g,t,100);self.base=np.array([.17,-.04,0]) + if t>=150:self.transition(obs,7) + self.a[0:2]=0;self.a[3]=0 + if self.phase in (0,6,7): + x,y,z,yaw=obs['low_dim_obs'][21:25];d=self.base[:2]-[x,y];v=np.clip(d*2,-.2,.2) + if np.linalg.norm(d)<.02:v*=0 + elif np.linalg.norm(v)<.07:v*=.07/np.linalg.norm(v) + self.a[0]=np.cos(yaw)*v[0]+np.sin(yaw)*v[1];self.a[1]=-np.sin(yaw)*v[0]+np.cos(yaw)*v[1] + self.a[3]=np.clip((self.base[2]-yaw)*3,-.3,.3) + return self.a.copy() + +def rx(t): + c,s=np.cos(t),np.sin(t);return np.array([[1,0,0],[0,c,-s],[0,s,c]]) +def ry(t): + c,s=np.cos(t),np.sin(t);return np.array([[c,0,s],[0,1,0],[-s,0,c]]) +def rz(t): + c,s=np.cos(t),np.sin(t);return np.array([[c,-s,0],[s,c,0],[0,0,1]]) +def fk(q): + s,r,y,e,wr,wp,wy=q + R=ry(s)@rx(r)@rz(y) + p=R@np.array([0.,0.,-.185]) + R=R@ry(e);p+=R@np.array([.138,0,-.01]) + R=R@rx(wr)@ry(wp)@rz(wy) + p+=R@np.array([.10,0,0]) + return p,R + + +def handle_blob(im): + p=im.astype(float);lo=p.min(2);hi=p.max(2) + m=((hi-lo<22)&(lo>42)&(hi<140)).astype('uint8');m[:,:5]=0;m[:,79:]=0 + n,l,st,cs=cv2.connectedComponentsWithStats(m,8);cand=[] + for i in range(1,n): + x,y,w,h,area=st[i] + if h<18 or area<45 or w>40 or h<1.5*w:continue + ys,xs=np.where(l==i);sel=(ys>25)&(ys<60) + if sel.sum()<12:continue + cx=float(xs[sel].mean());width=float(np.median(np.bincount(ys)[np.bincount(ys)>0])) + + if width>=3:cand.append((abs(cx-42),[cx,y+h/2,width,h])) + return min(cand)[1] if cand else None + +class Door: + def reset(self,obs,tools): + self.a=np.array(tools.hold_action(),float);self.a[19:]=.2;self.phase=0;self.start=obs['t'];self.old=self.a.copy();self.base=np.array([.19,-.04,0.]);self.qs=[];self.blobs=[None,None];self.good=[0,0] + def transition(self,obs,phase): + self.phase=phase;self.start=obs['t'];self.old=self.a.copy();self.qs=[self.a[5:12].copy(),self.a[12:19].copy()] + if phase==5: + self.bp=obs["low_dim_obs"][[21,22,24]].copy();self.v=fk(self.qs[0])[0][:2]+[0,.15] + def pose(self,g,t,d): + f=min(1,t/d);f=f*f*(3-2*f);self.a=self.old+(g-self.old)*f + def act(self,obs,tools): + t=obs['t']-self.start;g=self.old.copy() + if self.phase==0: + for i in [5,12]:g[i:i+7]=[-.5,0,0,-1,0,0,0] + g[12:19]=[-.2,0,0,-.9,0,0,.3] + self.pose(g,t,35) + if t>=60:self.transition(obs,1) + elif self.phase==1: + for i,sign in [(5,1)]:g[i:i+7]=[-2.3,.3*sign,0,-.5,0,1.3,0] + self.pose(g,t,45) + if t>=65:self.transition(obs,2) + elif self.phase==2: + for i,sign in [(5,1)]:g[i:i+7]=[-1.8,.15*sign,0,-.2,0,1.3,0] + self.pose(g,t,45) + if t>=60:self.transition(obs,3) + elif self.phase==3: + if t%5==0: + for k,c in enumerate(['left_wrist']): + b=handle_blob(tools.image(c));self.blobs[k]=b + if b: + x,y,w,h=b;q=self.qs[k] + dx=np.clip(.3*(.95/max(w,2)-.95/13),-.003,.008) + dz=np.clip((43-y)*.0004,-.006,.006) if h<75 else 0 + q=shift(q,dx,dz,-.7) + q[1]=np.clip(q[1]+np.clip((42-x)*.003,-.025,.025),-.13 if k==0 else -.7,.7 if k==0 else .13) + self.qs[k]=q + self.good[k]=self.good[k]+1 if w>=11.5 and abs(x-42)<4 else 0 + self.a[5:12]=self.qs[0] + if self.good[0]>=3 or t>=180:self.transition(obs,4) + elif self.phase==4: + self.a[19]=1 + if t>=40:self.transition(obs,5) + elif self.phase==5: + th=min(t/210,1)*1.4 + arc=np.array([-.25*np.sin(th),.25*(1-np.cos(th))]) + rot=rz(-th)[:2,:2] + self.base=np.r_[self.bp[:2]+arc+self.v-rot@self.v,self.bp[2]-th] + if t>=260:self.transition(obs,7) + elif self.phase==7: + g[19:]=0;g[5:12]=[-.5,0,0,-1,0,0,0];g[12:19]=[-.2,0,0,-.9,0,0,0] + self.pose(g,t,45);self.base=np.array([.05,0.,0.]) + if t>=190:self.transition(obs,8) + self.a[0:2]=0;self.a[3]=0 + if self.phase<=1 or self.phase in (5,7): + x,y,z,yaw=obs['low_dim_obs'][21:25];d=self.base[:2]-[x,y];v=np.clip(d*2,-.15,.15) + if np.linalg.norm(d)<.012:v*=0 + elif np.linalg.norm(v)<.065:v*=.065/np.linalg.norm(v) + self.a[0]=np.cos(yaw)*v[0]+np.sin(yaw)*v[1];self.a[1]=-np.sin(yaw)*v[0]+np.cos(yaw)*v[1];self.a[3]=np.clip((self.base[2]-yaw)*3,-.65,.65) + return self.a.copy() + +class Place: + def reset(self,obs,tools): + self.a=np.array(tools.hold_action(),float);self.a[19:]=1;self.start=obs['t'];self.phase=0;self.old=self.a.copy();self.base=np.array([.0,-.04,0.]);self.qs=[self.a[5:12].copy(),self.a[12:19].copy()] + def act(self,obs,tools): + t=obs['t']-self.start;self.phase=t//100;g=self.old.copy() + for k,i in enumerate((5,12)): + q=self.qs[k].copy();q[0]=-2.3;q[3]=.8;q[5]=1.;g[i:i+7]=q + if t<120:self.a=self.old.copy() + elif t<300: + f=min((t-120)/150,1);f=f*f*(3-2*f);self.a=self.old+(g-self.old)*f + else: + self.a=g.copy();self.base=np.array([.40,-.04,0.]) + if t>520: + f=min((t-520)/80,1);self.a[[5,12]]+=.20*f;self.a[[10,17]]-=.20*f + if t>620:self.a[19:]=0 + if t>670:self.base=np.array([.08,-.04,0.]) + x,y,z,yaw=obs['low_dim_obs'][21:25];v=np.clip((self.base[:2]-[x,y])*2,-.14,.14) + if np.linalg.norm(v)<.04:v*=0 + elif np.linalg.norm(v)<.065:v*=.065/np.linalg.norm(v) + self.a[0]=np.cos(yaw)*v[0]+np.sin(yaw)*v[1];self.a[1]=-np.sin(yaw)*v[0]+np.cos(yaw)*v[1];self.a[3]=np.clip(-yaw*3,-.3,.3) + return self.a.copy() + +class Policy: + def reset(self,o,e):self.mode=0;self.p=Door();self.p.reset(o,e) + def act(self,o,e): + a=self.p.act(o,e) + if self.mode==0 and self.p.phase==8: + self.mode=2;self.p=Cup();self.p.reset(o,e);self.p.start=o['t'] + elif self.mode==2 and self.p.phase==7: + self.mode=3;self.p=Place();self.p.reset(o,e) + return a diff --git a/policies/put_cups/astra-s3/episodes.csv b/policies/put_cups/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4872d5d958eff453b33f59e5a5be58dde8c59a02 --- /dev/null +++ b/policies/put_cups/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,1,2847,success,0 +620002,1,2688,success,0 +620003,0,3000,timeout,0 +620004,1,2688,success,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,1,2972,success,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,1,2700,success,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,1,2687,success,0 +620035,0,3000,timeout,0 +620036,1,2593,success,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,1,2540,success,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,1,2592,success,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/astra-s3/policy.py b/policies/put_cups/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b33b7b687d7018b7d838fb889c3de92416482656 --- /dev/null +++ b/policies/put_cups/astra-s3/policy.py @@ -0,0 +1,185 @@ +"""Hand-written, deterministic control for putting cups in a wall cabinet. + +Only live wrist-camera pixels and robot proprioception are used. Color and +contour geometry locate cups and handle openings. A finite-state controller +opens the doors, retries grasps, preserves hand orientation during lifting, +and reaches onto the shelf before gradually opening the fingers. +""" +import numpy as np +import cv2 +from scipy.spatial.transform import Rotation + +class Policy: + + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float) + self.phase = 'doors' + self.start = 0 + self.cup = 0 + self.retry = 0 + self.target = np.array([0.23, 0.08]) + self.fast = False + self.door = [(100, [-1.5, 0, 0, -1, 0, 0, 0], 0, 0), (100, [-1.5, 0, 0, 0.3, 0, 0.4, 0], 0, 0), (80, [-1.5, 0, 0, 0.3, 0, 0.4, 0.08], 1, 0), (60, [-1.5, 0, 0, 0.3, 0, 0.4, 0.08], 1, -0.1), (60, [-1.5, 0, 0, 0.3, 0, 0.4, 0.08], 1, 0), (80, [-1.5, 0.3, 0, 0.3, 0, 0.4, 0.3], 1, -0.15), (60, [-1.5, 0.3, 0, 0.3, 0, 0.4, 0.3], 1, 0)] + + def change(self, name, t): + self.phase = name + self.start = t + + def drive(self, obs, target): + p = obs['low_dim_obs'][21:25] + delta = np.asarray(target) - p[:2] + v = np.clip(delta * 2, -0.22, 0.22) + norm = np.linalg.norm(v) + if norm < 0.055: + v = v * 0.06 / max(norm, 1e-09) if np.linalg.norm(delta) > 0.012 else v * 0 + c, s = (np.cos(p[3]), np.sin(p[3])) + self.a[0] = c * v[0] + s * v[1] + self.a[1] = -s * v[0] + c * v[1] + self.a[3] = np.clip(-3 * p[3], -0.3, 0.3) + + def cups(self, im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = ((hsv[:, :, 1] < 45) & (hsv[:, :, 2] > 75) & (hsv[:, :, 2] < 240)).astype(np.uint8) + n, l, st, cen = cv2.connectedComponentsWithStats(mask) + out = [] + for i in range(1, n): + x, y, w, h, area = st[i] + if area > 200 and w > 12 and (h > 20) and (w < 85) and (cen[i, 1] > 15): + out.append((cen[i], st[i], l == i)) + return out + + def handle_x(self, im): + cs = self.cups(im) + if not cs: + return None + c, st, m = min(cs, key=lambda v: abs(v[0][0] - 42)) + contours, hierarchy = cv2.findContours(m.astype(np.uint8), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + if hierarchy is not None: + holes = [] + for co, hi in zip(contours, hierarchy[0]): + x, y, w, h = cv2.boundingRect(co) + if hi[3] >= 0 and cv2.contourArea(co) > 15 and (h > 10) and (w > 3): + cx = x + w / 2 + holes.append((h, cx)) + if holes: + return max(holes)[1] + ys, xs = np.where(m) + end = np.max(ys) + band = xs[ys >= end - 8] + return float(np.median(band)) if len(band) > 0 else float(c[0]) + + def arm_rotation(self, q, n): + axes = [[0, 1, 0], [1, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]] + r = Rotation.identity() + for i in range(n): + r = r * Rotation.from_rotvec(np.array(axes[i]) * q[i]) + return r + + def act(self, obs, tools): + t = obs['t'] + a = self.a + a[0:2] = 0 + a[3] = 0 + a[4] = 0 + if self.phase == 'doors': + k = t + for dur, q, g, v in self.door: + if k < dur: + a[5:12] = q + a[12:19] = np.array(q) * [1, -1, -1, 1, -1, 1, -1] + a[19:21] = g + a[0] = v + return a.copy() + k -= dur + self.change('prepare', t) + dt = t - self.start + py = [-0.05, -0.16, -0.16][min(self.cup, 2)] + a[12:19] = [0.5, 0, 0, 1.2, 0, 0, 0] + a[20] = 1 + if self.phase == 'prepare': + a[2] = 0.74 + a[5:12] = [-0.8, 0, 0, 0, 0, 0.4, 0] + a[19] = 0 + self.target = np.array([0.15, 0.0]) + self.change('survey', t) + elif self.phase == 'survey': + self.drive(obs, self.target) + if dt in ((120, 150, 180) if self.fast else (120, 150, 180, 210)): + cs = [c for c in self.cups(tools.image('left_wrist')) if c[0][1] > 25 and c[1][4] < 4500] + if cs: + c, st, m = min(cs, key=lambda z: abs(z[0][0] - 42)) + self.target[1] = obs['low_dim_obs'][22] + np.clip((42 - c[0]) * 0.002, -0.06, 0.06) + self.target[1] = np.clip(self.target[1], -0.25, 0.25) + if dt >= (210 if self.fast else 240): + self.target[0] = 0.23 + a[10] = 0.8 + self.change('seek', t) + elif self.phase == 'seek': + self.drive(obs, self.target) + if dt >= (90 if self.fast else 100): + self.change('settle', t) + elif self.phase == 'settle': + if dt >= (30 if self.fast else 45): + self.change('lower', t) + elif self.phase == 'lower': + if dt in ((15, 30, 45) if self.fast else (15, 30, 45, 60, 75)): + u = self.handle_x(tools.image('left_wrist')) + if u is not None: + a[11] = np.clip(a[11] + np.clip((42 - u) * 0.008, -0.18, 0.18), -0.65, 0.65) + if dt >= (60 if self.fast else 90): + self.change('grasp', t) + elif self.phase == 'grasp': + a[19] = 1 + if dt >= (35 if self.fast else 50): + if (obs['low_dim_obs'][50] > 0.85 or obs['low_dim_obs'][50] < 0.3) and self.retry < 2: + self.retry += 1 + self.fast = True + a[19] = 0 + self.target = np.array(obs['low_dim_obs'][21:23]) + self.target[0] += 0.018 + self.change('retry', t) + else: + self.change('back', t) + elif self.phase == 'retry': + self.drive(obs, self.target) + if dt >= 50: + self.change('lower', t) + elif self.phase == 'back': + self.drive(obs, [0.02, py]) + if dt >= (90 if self.fast else 100): + self.lift_start = a[5:12].copy() + self.lift_rot = self.arm_rotation(self.lift_start, 7) + self.change('raise', t) + elif self.phase == 'raise': + a[2] = 0.78 + self.drive(obs, [0.02, py]) + f = min(1, dt / (120 if self.fast else 140)) + f = f * f * (3 - 2 * f) + q = self.lift_start.copy() + q[:4] = q[:4] * (1 - f) + np.array([-2.6, 0.3, -0.5, 1.1]) * f + q[4:7] = (self.arm_rotation(q, 4).inv() * self.lift_rot).as_euler('XYZ') + a[5:12] = q + if dt >= (130 if self.fast else 150): + self.change('insert', t) + elif self.phase == 'insert': + self.drive(obs, [0.3, py]) + f = min(1, dt / 90) + a[4] = 0.3 * f + a[5] = -2.6 - 0.3 * f + if dt >= (110 if self.fast else 125): + self.change('release', t) + elif self.phase == 'release': + a[4] = 0.3 + a[19] = max(0, 0.8 - dt * 0.02) + if dt >= (45 if self.fast else 50): + self.change('withdraw', t) + elif self.phase == 'withdraw': + a[4] = 0.3 + self.drive(obs, [0.02, py]) + if dt >= (90 if self.fast else 100): + self.cup += 1 + self.retry = 0 + self.change('prepare' if self.cup < 2 else 'finish', t) + else: + a[19] = 0 + return a.copy() diff --git a/policies/put_cups/deepseek1017-s1/episodes.csv b/policies/put_cups/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/deepseek1017-s1/policy.py b/policies/put_cups/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..70fcd1e2a620f69a341f34acc1ba35ae59bce9ea --- /dev/null +++ b/policies/put_cups/deepseek1017-s1/policy.py @@ -0,0 +1,211 @@ +"""Control policy for the Unitree G1: move the cups from the counter into +the wall cabinet. + +The policy is a deterministic hand-written state machine: + + 1. step back from the counter to get room for the arm + 2. raise the right arm to counter height with the gripper open + 3. walk slowly towards the counter while using a simple colour/shape + detector on the right wrist camera to keep a cup centred; stop once + the cup is large (close) and the robot has reached the counter + 4. lean the torso forward so the open gripper slides around the cup + 5. close the gripper and lift the cup + 6. reach up towards the wall cabinet and release the cup + 7. repeat for the next cup + +Everything is driven by the observations (proprioception + wrist camera), +no learned components and no randomness. +""" + +import numpy as np + +# right arm joint targets used for the approach (rad) +_ARM_APPROACH = (-1.0, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0) +# right arm pose used to lift the cup off the counter +_ARM_UP = (-1.80, 0.0, 0.0, 1.35, 0.0, -0.40, 0.0) +# right arm pose used while pressing the cup into the cabinet +_ARM_PRESS = (-1.55, 0.0, 0.0, 1.05, 0.0, -0.20, 0.0) + +_PHASES = [ + ("backup", 60), + ("raise", 45), + ("approach", 220), + ("lean", 25), + ("close", 20), + ("lift", 45), + ("press", 35), + ("release", 20), + ("retract", 25), +] + + +def _clip(x, lo, hi): + """Clamp a scalar to [lo, hi].""" + return lo if x < lo else (hi if x > hi else x) + + +def _detect_cups(image): + """Return cup candidates as (area, x, y, w, h). + + Cups are light grey cylinders standing on the wooden counter, so they + show up as compact neutral coloured blobs that are much smaller than + the white cabinet panels. + """ + import cv2 + + im = image.astype(np.int16) + mx = im.max(axis=2) + mn = im.min(axis=2) + mask = (((mx - mn) < 34) & (mx > 95)).astype(np.uint8) + mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((2, 2), np.uint8)) + mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8)) + n, _lab, stats, _cent = cv2.connectedComponentsWithStats(mask, 8) + hgt, wid = image.shape[:2] + out = [] + for i in range(1, n): + x = int(stats[i, 0]) + y = int(stats[i, 1]) + w = int(stats[i, 2]) + h = int(stats[i, 3]) + area = int(stats[i, 4]) + if area < 60 or area > 3000: + continue + if w < 5 or h < 5: + continue + if w > 0.55 * wid or h > 0.55 * hgt: + continue + ratio = w / float(h) + if ratio < 0.40 or ratio > 2.3: + continue + if area / float(w * h) < 0.30: + continue + if y + h >= hgt - 1 and h > 0.25 * hgt: + continue # the robot's own hand plate + out.append((area, x, y, w, h)) + return out + + +def _best_cup(image): + """Pick the most promising cup candidate, or None.""" + best = None + best_score = -1.0 + for area, x, y, w, h in _detect_cups(image): + cx = (x + w / 2.0) / float(image.shape[1]) + cy = (y + h / 2.0) / float(image.shape[0]) + score = area * (1.0 - 1.1 * abs(cx - 0.5)) + if cy > 0.95: + score *= 0.5 + if score > best_score: + best_score = score + best = (area, cx, cy, h) + return best + + +class Policy: + """Deterministic visual-servoing pick-and-place policy.""" + + def reset(self, obs, tools): + """Prepare for one episode.""" + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.timer = 0 + self.cycles = 0 + self.last_cup = None + + def _action_for_phase(self, obs, tools): + """Build the raw action for the current phase.""" + raw = self.hold.copy() + name = _PHASES[self.phase][0] + low = np.asarray(obs["low_dim_obs"]) + yaw = float(low[24]) + + if name == "backup": + raw[0] = -0.30 + raw[4] = 0.20 + raw[19] = 0.0 + raw[20] = 0.0 + elif name == "raise": + raw[4] = 0.20 + raw[19] = 0.0 + raw[20] = 0.0 + raw[12:19] = _ARM_APPROACH + elif name == "approach": + raw[4] = 0.20 + raw[19] = 0.0 + raw[20] = 0.0 + raw[12:19] = _ARM_APPROACH + cup = _best_cup(tools.image("right_wrist", 84, 84)) + if cup is not None: + self.last_cup = cup + raw[3] = _clip(-2.0 * yaw, -0.5, 0.5) + if cup is not None: + _area, cx, _cy, h = cup + raw[1] = _clip(1.0 * (0.5 - cx), -0.25, 0.25) + raw[0] = 0.10 if h < 55 else 0.0 + else: + raw[1] = 0.0 + raw[0] = 0.06 + elif name == "lean": + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + raw[4] = 0.50 + raw[19] = 0.0 + raw[20] = 0.0 + raw[12:19] = _ARM_APPROACH + elif name == "close": + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + raw[4] = 0.50 + raw[20] = 1.0 + raw[12:19] = _ARM_APPROACH + elif name == "lift": + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + raw[4] = 0.18 + raw[20] = 1.0 + raw[12:19] = _ARM_UP + elif name == "press": + raw[0] = 0.10 + raw[1] = 0.0 + raw[3] = _clip(-2.0 * yaw, -0.4, 0.4) + raw[4] = 0.45 + raw[20] = 1.0 + raw[12:19] = _ARM_PRESS + elif name == "release": + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + raw[4] = 0.45 + raw[20] = 0.0 + raw[12:19] = _ARM_PRESS + elif name == "retract": + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = _clip(-2.0 * yaw, -0.4, 0.4) + raw[4] = 0.20 + raw[20] = 0.0 + raw[12] = -0.90 + raw[15] = 0.90 + return raw + + def act(self, obs, tools): + """Return the action for this control step.""" + if self.phase >= len(_PHASES): + # start another attempt for one of the remaining cups + self.cycles += 1 + if self.cycles >= 5: + return np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.timer = 0 + + raw = self._action_for_phase(obs, tools) + + self.timer += 1 + if self.timer >= _PHASES[self.phase][1]: + self.phase += 1 + self.timer = 0 + + return np.asarray(raw, dtype=np.float32) diff --git a/policies/put_cups/deepseek1017-s2/episodes.csv b/policies/put_cups/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/deepseek1017-s2/policy.py b/policies/put_cups/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..873466763b71a9aaa749dafa6fd5e24d3f901d73 --- /dev/null +++ b/policies/put_cups/deepseek1017-s2/policy.py @@ -0,0 +1,175 @@ +"""Hand-written scripted controller for the G1 put-cups task. + +The robot faces a counter with cups standing on it and a cupboard below/behind +the counter top. The controller repeats a pick-and-place cycle: + + 1. lean over the counter and pick a cup with the left hand (the wrist is + pitched down so the jaws point at the cup), + 2. lift the cup upright slowly (the grip is marginal, so every motion is + ramped), + 3. bring the cup down in front of the cupboard opening and push it in, + 4. return to the pick pose for the next cup. + +Everything is joint-position control; the base is velocity-controlled from the +pelvis pose in ``low_dim_obs``. +""" + +import math + +import numpy as np + + +def _wrap(a): + while a > math.pi: + a -= 2.0 * math.pi + while a < -math.pi: + a += 2.0 * math.pi + return a + + +def _lerp(a, b, f): + return a + (b - a) * f + + +KEYS = ("pitch", "h", "j5", "j5r", "j6", "j6r", "j7", "j7r", + "j8", "j8r", "j10", "j10r", "gl", "gr") + +REST = dict(pitch=-0.2, h=0.74, j5=0.0, j5r=0.0, j6=0.0, j6r=0.0, + j7=0.0, j7r=0.0, j8=0.0, j8r=0.0, j10=0.0, j10r=0.0, + gl=0.6, gr=0.6) + +PICK_POSE = dict(REST, pitch=0.5, h=0.68, j5=-1.0, j5r=-1.0, j10=0.7, j10r=0.7) +LIFT_POSE = dict(REST, pitch=-0.2, h=0.74, j5=-1.0, j5r=-1.0, j10=0.7, j10r=0.7) +PLACE_POSE = dict(REST, pitch=0.4, h=0.6, j5=-0.2, j5r=-0.2, j10=0.0) + + +def _mix(dst, *srcs): + out = dict(dst) + for s in srcs: + out.update(s) + return out + + +class Policy: + def reset(self, obs, tools): + self.hold0 = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.seg_t = 0 + self.cur = dict(REST) + self.prev = dict(REST) + self.grasp_ok = False + self.cups = 0 + self.segments = self._build() + + def _cycle(self, y0=0.0): + return [ + dict(name="pick_lean", n=30, target=PICK_POSE), + dict(name="pick_fwd", n=20, target=PICK_POSE, vx=0.35), + dict(name="pick_close", n=45, target=_mix(PICK_POSE, dict(gl=1.0))), + dict(name="lift", n=130, interp_to=_mix(LIFT_POSE, dict(j10=0.7, j10r=0.7)), gl=1.0), + dict(name="place_lower", n=100, interp_to=PLACE_POSE, gl=1.0), + dict(name="place_push", n=45, target=_mix(PLACE_POSE, dict(gl=1.0)), + servo=(0.28, 0.0, 0.0), gain=4.0), + dict(name="place_release", n=20, target=_mix(PLACE_POSE, dict(gl=0.0))), + dict(name="back", n=40, target=dict(REST, pitch=-0.2), servo=(-0.05, 0.0, 0.0), + gain=3.0), + dict(name="reset_base", n=90, target=REST, servo=(0.16, y0, 0.0), gain=4.0), + ] + + def _build(self): + S = [dict(name="settle", n=15, target=REST)] + S += self._cycle(0.0) + S += self._cycle(-0.13) + S += self._cycle(-0.28) + S += self._cycle(-0.36) + S.append(dict(name="done", n=10 ** 9, target=REST)) + return S + + # ------------------------------------------------------------------ + def _base_velocity(self, lo, target, gain=5.0): + x, y, yaw = float(lo[21]), float(lo[22]), float(lo[24]) + ex, ey, eyaw = target[0] - x, target[1] - y, _wrap(target[2] - yaw) + c, s = math.cos(yaw), math.sin(yaw) + vx_b = c * ex + s * ey + vy_b = -s * ex + c * ey + vx = float(np.clip(gain * vx_b, -0.6, 0.6)) + vy = float(np.clip(gain * vy_b, -0.6, 0.6)) + wz = float(np.clip(2.0 * eyaw, -0.8, 0.8)) + if abs(vx) < 0.06 and abs(vx_b) > 0.004: + vx = 0.06 * math.copysign(1.0, vx_b) + if abs(vy) < 0.06 and abs(vy_b) > 0.004: + vy = 0.06 * math.copysign(1.0, vy_b) + if abs(vx_b) < 0.006: + vx = 0.0 + if abs(vy_b) < 0.006: + vy = 0.0 + if abs(eyaw) < 0.02: + wz = 0.0 + return vx, vy, wz + + # ------------------------------------------------------------------ + def act(self, obs, tools): + lo = np.asarray(obs["low_dim_obs"], dtype=np.float32) + seg = self.segments[self.phase] + n = seg["n"] + + if "interp_to" in seg: + f = min(1.0, (self.seg_t + 1) / float(n)) + tgt = {} + for k in KEYS: + start = self.prev.get(k, REST[k]) + end = seg["interp_to"].get(k, start) + tgt[k] = _lerp(start, end, f) + if "gl" in seg: + tgt["gl"] = seg["gl"] + else: + base_t = dict(seg["target"]) + if self.seg_t == 0: + self.prev = dict(self.cur) + f = min(1.0, (self.seg_t + 1) / float(n)) + tgt = {k: _lerp(self.prev.get(k, base_t[k]), base_t[k], f) for k in KEYS} + + if "servo" in seg: + vx, vy, wz = self._base_velocity(lo, seg["servo"], seg.get("gain", 5.0)) + else: + vx = seg.get("vx", 0.0) + vy = seg.get("vy", 0.0) + wz = seg.get("wz", 0.0) + + if seg["name"] == "pick_close" and self.seg_t >= n - 1: + if float(lo[50]) < 0.95: + self.grasp_ok = True + self.cups += 1 + + self.cur = dict(tgt) + self.seg_t += 1 + if self.seg_t >= n: + self.phase = min(self.phase + 1, len(self.segments) - 1) + self.seg_t = 0 + self.prev = dict(self.cur) + + a = self.hold0.copy() + a[4] = tgt["pitch"] + a[2] = tgt["h"] + a[5] = tgt["j5"] + a[12] = tgt["j5r"] + a[6] = tgt["j6"] + a[13] = tgt["j6r"] + a[7] = tgt["j7"] + a[14] = tgt["j7r"] + a[8] = tgt["j8"] + a[15] = tgt["j8r"] + a[10] = tgt["j10"] + a[17] = tgt["j10r"] + a[19] = tgt["gl"] + a[20] = tgt["gr"] + a[0] = vx + a[1] = vy + a[3] = wz + return a + + def _index(self, name, from_phase=0): + for i in range(from_phase, len(self.segments)): + if self.segments[i]["name"] == name: + return i + return len(self.segments) - 1 diff --git a/policies/put_cups/deepseek1017-s3/episodes.csv b/policies/put_cups/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/deepseek1017-s3/policy.py b/policies/put_cups/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7bdd19506162b1ae2f39b8d8254d9ea784f5b09c --- /dev/null +++ b/policies/put_cups/deepseek1017-s3/policy.py @@ -0,0 +1,160 @@ +"""Hand-written deterministic control policy for the 'put cups away' task. + +The cups stand on a high counter directly in front of the reset pose. The +policy drives the robot through a fixed sequence of upper-body poses: + + 1. raise the pelvis-height command in steps while swinging the left arm + up towards the counter, which lets the balance controller settle the + robot right up against the counter (the counter surface comes into the + wrist/head camera view); + 2. pull back a little, raise the arm above the counter edge and lean + forward again so that the open gripper sits on the counter top next to + the cups; + 3. close the gripper, lift the arm up towards the wall cabinet and open + the gripper again, repeating this over a few lateral offsets; + 4. do the same with the other arm. + +No learned components are used: the controller is a fixed time-indexed +sequence of absolute joint / base targets and gripper commands. +""" + +import numpy as np + + +def _arm(sp, roll, yaw, elbow, wr=0.0, wp=0.0, wy=0.0): + """Pack one 7-DoF arm target.""" + return [sp, roll, yaw, elbow, wr, wp, wy] + + +class Policy: + """Time-indexed scripted controller.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), np.float32) + self.seg = [] # list of (duration, action array) + self._schedule() + self.bounds = [] + acc = 0 + for n, _ in self.seg: + acc += int(n) + self.bounds.append(acc) + + # ------------------------------------------------------------------ # + def _add(self, n, h=0.74, pitch=0.0, vx=0.0, vy=0.0, wz=0.0, + la=None, ra=None, gl=0.0, gr=0.0): + a = np.zeros(21, np.float32) + a[0], a[1], a[2], a[3], a[4] = vx, vy, h, wz, pitch + if la is not None: + a[5:12] = la + if ra is not None: + a[12:19] = ra + a[19], a[20] = gl, gr + self.seg.append((int(n), a)) + + def _schedule(self): + add = self._add + + # ---- 1. settle, then creep up to the counter ------------------- + add(10, h=0.74) + for h, sp in ((0.85, 0.8), (0.85, 1.1), (0.85, 1.4), + (0.95, 0.8), (0.95, 1.1), (0.95, 1.4)): + add(45, h=h, la=_arm(sp, 0.3, 0.0, 0.4)) + add(20, h=h) + # tall stance, left hand next to the counter edge + add(45, h=1.0, la=_arm(0.8, 0.3, 0.0, 0.4)) + + # ---- 2. make room, lift the arm, come back in ------------------ + add(14, h=0.85, vx=-0.5, la=_arm(0.8, 0.3, 0.0, 0.4)) + add(30, h=0.85, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4)) + add(30, h=1.0, vx=0.25, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4)) + + # ---- 3. left-arm grasp / lift / release cycles ----------------- + # The hand sits at the counter top, inboard yaw brings the fingers + # towards the cups. Each cycle closes at a slightly different pose + # to cover the lateral placement variation of the cups. + for yaw, sp, roll, el in ((-1.0, 1.5, 0.3, 0.2), + (-0.6, 1.55, 0.3, 0.2), + (-1.0, 1.6, 0.2, 0.3), + (-0.3, 1.5, 0.3, 0.15)): + add(20, h=1.0, vx=0.10, la=_arm(sp, roll, yaw, el, wp=-0.4)) + add(12, h=1.0, la=_arm(sp, roll, yaw, el, wp=-0.4), gl=1.0) + add(26, h=1.0, la=_arm(min(sp + 0.45, 2.3), roll, yaw * 0.5, + min(el + 0.7, 1.9)), gl=1.0) + add(10, h=1.0, la=_arm(min(sp + 0.45, 2.3), roll, yaw * 0.5, + min(el + 0.7, 1.9)), gl=0.0) + add(14, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4)) + + # ---- 4. right-arm variant -------------------------------------- + add(20, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(1.5, -0.3, 0.0, 0.2, wp=-0.4)) + for yaw, sp, roll, el in ((1.0, 1.5, -0.3, 0.2), + (0.6, 1.55, -0.3, 0.2), + (1.0, 1.6, -0.2, 0.3), + (0.3, 1.5, -0.3, 0.15)): + add(20, h=1.0, vx=0.10, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(sp, roll, yaw, el, wp=-0.4)) + add(12, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(sp, roll, yaw, el, wp=-0.4), gr=1.0) + add(26, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(min(sp + 0.45, 2.3), roll, yaw * 0.5, + min(el + 0.7, 1.9)), gr=1.0) + add(10, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(min(sp + 0.45, 2.3), roll, yaw * 0.5, + min(el + 0.7, 1.9)), gr=0.0) + add(14, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(1.5, -0.3, 0.0, 0.2, wp=-0.4)) + + # ---- 5. final two-arm carry up into the cabinet ----------------- + add(20, h=1.0, la=_arm(1.6, 0.25, -0.3, 0.5, wp=-0.4), + ra=_arm(1.6, -0.25, 0.3, 0.5, wp=-0.4)) + add(16, h=1.0, la=_arm(1.6, 0.25, -0.3, 0.5, wp=-0.4), + ra=_arm(1.6, -0.25, 0.3, 0.5, wp=-0.4), gl=1.0, gr=1.0) + add(28, h=1.0, la=_arm(2.1, 0.2, -0.2, 1.2), + ra=_arm(2.1, -0.2, 0.2, 1.2), gl=1.0, gr=1.0) + add(24, h=0.95, la=_arm(2.2, 0.15, 0.0, 1.5), + ra=_arm(2.2, -0.15, 0.0, 1.5), gl=1.0, gr=1.0) + add(18, h=0.95, la=_arm(2.2, 0.15, 0.0, 1.5), + ra=_arm(2.2, -0.15, 0.0, 1.5), gl=0.0, gr=0.0) + add(50, h=0.90) + + # ---- 6. second pass with the base shifted sideways. The cups are + # placed at different offsets along the counter on every seed, so a + # small lateral shift of the whole body sweeps the gripper over a + # different part of the counter top. + for vy0 in (0.22, -0.30): + add(10, h=0.85, vy=vy0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(1.5, -0.3, 0.0, 0.2, wp=-0.4)) + add(18, h=0.85, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(1.5, -0.3, 0.0, 0.2, wp=-0.4)) + add(24, h=1.0, vx=0.20, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(1.5, -0.3, 0.0, 0.2, wp=-0.4)) + for yaw, sp, roll, el in ((-1.0, 1.5, 0.3, 0.2), + (-0.4, 1.6, 0.2, 0.3)): + add(18, h=1.0, vx=0.08, + la=_arm(sp, roll, yaw, el, wp=-0.4), + ra=_arm(sp, -roll, -yaw, el, wp=-0.4)) + add(12, h=1.0, la=_arm(sp, roll, yaw, el, wp=-0.4), + ra=_arm(sp, -roll, -yaw, el, wp=-0.4), gl=1.0, gr=1.0) + add(24, h=1.0, + la=_arm(min(sp + 0.4, 2.3), roll, yaw * 0.5, + min(el + 0.6, 1.9)), + ra=_arm(min(sp + 0.4, 2.3), -roll, -yaw * 0.5, + min(el + 0.6, 1.9)), gl=1.0, gr=1.0) + add(12, h=1.0, + la=_arm(min(sp + 0.4, 2.3), roll, yaw * 0.5, + min(el + 0.6, 1.9)), + ra=_arm(min(sp + 0.4, 2.3), -roll, -yaw * 0.5, + min(el + 0.6, 1.9)), gl=0.0, gr=0.0) + add(12, h=1.0, la=_arm(1.5, 0.3, 0.0, 0.2, wp=-0.4), + ra=_arm(1.5, -0.3, 0.0, 0.2, wp=-0.4)) + add(100, h=0.90) + add(10 ** 9, h=0.85) + + # ------------------------------------------------------------------ # + def act(self, obs, tools): + t = int(obs.get("t", 0)) + i = 0 + n = len(self.bounds) + while i < n - 1 and t >= self.bounds[i]: + i += 1 + return self.seg[i][1].copy() diff --git a/policies/put_cups/gpt61sol-s1/episodes.csv b/policies/put_cups/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/gpt61sol-s1/policy.py b/policies/put_cups/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d2bd0e0ccd27edcf307ccd80ec988f3795ff3a1c --- /dev/null +++ b/policies/put_cups/gpt61sol-s1/policy.py @@ -0,0 +1,155 @@ +"""Deterministic geometric vision and staged manipulation controller.""" +import numpy as np +import cv2 + + +class Policy: + def reset(self, obs, tools): + self.cmd = np.asarray(tools.hold_action(), dtype=float) + self.phase = 0 + self.age = 0 + self.retries = 0 + self.left = np.zeros(7) + self.right = np.array([0., -.2, 0, 1.5, 0, 0, 0]) + self.cup_left = np.array([-.85, .15, 0, 0, 0, .25, 0.]) + self.cup_right = np.array([-.95, -.2, 0, 0, 0, .35, 0.]) + self.door = np.array([-2.5, .05, 0, 1.2, 0, 1.55, 0.]) + self.angle = [-.6, -.6] + self.empty = [False, False] + self.phases = [ + ('back',120), ('raise_door',150), ('approach_door',190), + ('align_door',20), ('grip_door',60), ('pull_door',80), + ('sweep_door',230), ('second_door',200), ('second_grip',50), + ('second_pull',80), ('second_sweep',190), ('withdraw',180), + ('lower',120), ('approach_cups',150), ('reach_cups',130), + ('grip_cups',60), ('stand',100), ('clear_cups',150), + ('raise_cups',230), ('insert',260), ('settle',100), ('release',40), + ('rest',10000)] + + @staticmethod + def cup(im): + a=im.astype(np.int16) + mask=((a.max(2)-a.min(2)<30)&(a.min(2)>80)&(a.max(2)<239)).astype(np.uint8) + mask[76:]=0 + n,labels,stats,cents=cv2.connectedComponentsWithStats(mask,8) + choices=[] + for k in range(1,n): + x,y,w,h,area=stats[k] + if area<65 or area>2600 or w<9 or h<15 or w>70 or w>h*1.7: continue + cx,cy=cents[k] + choices.append((abs(cx-59)+.3*abs(cy-36),float(cx),float(cy),float(w))) + if not choices:return None + return min(choices)[1:] + + @staticmethod + def handle(im): + a=im.astype(np.int16) + m=((a.max(2)-a.min(2)<18)&(a.min(2)>55)&(a.max(2)<165)).astype(np.uint8) + contours,_=cv2.findContours(m,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) + found=[] + for c in contours: + if cv2.contourArea(c)<22:continue + (x,y),(w,h),ang=cv2.minAreaRect(c) + short,long=sorted((w,h)) + if short<2 or short>14 or long<17 or long<3*short or long>82:continue + if x<8 or x>77:continue + found.append((abs(x-42)+.4*abs(y-32),x,y)) + return min(found)[1:] if found else None + + def move_base(self, a, obs, pos): + p=np.asarray(obs['low_dim_obs'][21:25],float) + dyaw=(0-p[3]+np.pi)%(2*np.pi)-np.pi + a[3]=np.clip(2.5*dyaw,-.5,.5) + if pos is None:a[:2]=0;return + d=np.asarray(pos)-p[:2] + cs,sn=np.cos(p[3]),np.sin(p[3]) + v=np.array([cs*d[0]+sn*d[1],-sn*d[0]+cs*d[1]]) + a[:2]=np.where(np.abs(v)>.012,np.sign(v)*np.clip(2*np.abs(v),.065,.20),0) + + def servo_cup(self, arm, im): + found=self.cup(im) + if found is None:return + u,v,w=found + arm[1]=np.clip(arm[1]+np.clip(.004*(59-u),-.018,.018),-.42,.42) + if w<52: + ds=-min(.014,.0015*(52-w)) + arm[0]=max(-1.18,arm[0]+ds) + arm[5]-=ds + arm[5]=np.clip(arm[5]+np.clip(.003*(v-36),-.018,.018),-.1,1.1) + + def act(self, obs, tools): + name,duration=self.phases[self.phase] + low=obs['low_dim_obs'] + stow=np.array([0.,-.2,0,1.5,0,0,0]) + high=self.door.copy() + h=.74;pos=None;grips=[1.,0.];speed=.014 + L=self.left.copy();R=self.right.copy() + if name=='back': L=np.zeros(7);R=stow;pos=[-.12,0] + elif name=='raise_door':L=high;R=stow;pos=[-.12,0] + elif name in ('approach_door','align_door','grip_door'): + L=high;R=stow;pos=[.40,0];grips=[float(name=='grip_door'),0] + elif name=='pull_door':L=high;R=stow;pos=None;speed=.004 + elif name=='sweep_door':L=high;L[1]=-.25;R=stow;pos=[-.04,-.50];speed=.002 + elif name in ('second_door','second_grip'): + L=high;L[1]=-.05;R=stow;pos=[.40,.10];grips=[float(name=='second_grip'),0] + elif name=='second_pull':L=high;L[1]=-.05;R=stow;pos=None;speed=.004 + elif name=='second_sweep':L=high;L[1]=.35;R=stow;pos=[-.04,.60];speed=.002 + elif name=='withdraw': + L=np.array([-2.6,.1,0,.4,0,1.3,0]);R=stow;pos=[-.12,.12];grips=[0,0] + elif name=='lower': + L=np.array([-.6,0,0,0,0,0,0.]);R=np.array([-.6,-.1,0,0,0,0,0.]);pos=[-.12,.12];grips=[0,0] + elif name=='approach_cups': + L=np.array([-.6,0,0,0,0,0,0.]);R=np.array([-.6,-.1,0,0,0,0,0.]);pos=[.26,.12];grips=[0,0] + elif name in ('reach_cups','grip_cups','retry_cups','retry_grip'): + h=.61 if self.retries==0 else .60;L=self.cup_left.copy();R=self.cup_right.copy() + if name in ('reach_cups','retry_cups'): + grips=[float(not self.empty[0]) if name=='retry_cups' else 0,float(not self.empty[1]) if name=='retry_cups' else 0] + if self.age>35 and self.age%8==0: + if name=='reach_cups' or self.empty[0]:self.servo_cup(self.cup_left,tools.image('left_wrist')) + if name=='reach_cups' or self.empty[1]:self.servo_cup(self.cup_right,tools.image('right_wrist')) + L=self.cup_left.copy();R=self.cup_right.copy() + else:grips=[1,1] + elif name in ('stand','clear_cups'): + L=self.cup_left.copy();R=self.cup_right.copy();grips=[1,1];speed=.008 + if name=='clear_cups':pos=[-.14,.20] + elif name in ('raise_cups','insert','settle','release','rest'): + L=np.array([-2.6,.1,0,.4,0,self.angle[0]+2.2,0]) + R=np.array([-2.6,-.15,0,.4,0,self.angle[1]+2.2,0]) + L[5]=np.clip(L[5],-.9,1.6);R[5]=np.clip(R[5],-.9,1.6) + speed=.008;grips=[1,1];h=.77 + pos=[-.14,.20] if name=='raise_cups' else [.40,.20] + if name in ('settle','release','rest') and low[21]>.34: + h=.74 + L[0]=-2.5;R[0]=-2.5;L[3]=.5;R[3]=.5 + L[5]=self.angle[0]+1.85;R[5]=self.angle[1]+1.85 + if name in ('release','rest') and low[21]>.34: + ready=max(np.max(np.abs(self.cmd[5:12]-L)),np.max(np.abs(self.cmd[12:19]-R)))<.06 + if ready:grips=[0,0] + self.left=L;self.right=R + out=self.cmd.copy() + for sl,target in ((slice(5,12),L),(slice(12,19),R)): + diff=target-out[sl];scale=min(1.,speed/max(np.max(np.abs(diff)),1e-8)) + out[sl]+=diff*scale + out[2]+=np.clip(h-out[2],-.002,.002) + pitch=.15 if name in ('settle','release','rest') and low[21]>.34 else 0. + out[4]+=np.clip(pitch-out[4],-.003,.003) + out[19:]=grips + self.move_base(out,obs,pos) + if name in ('pull_door','second_pull'):out[0]=-.08;out[1]=0;out[3]=0 + self.cmd=out.copy() + self.age+=1 + if self.age>=duration: + if name in ('grip_cups','retry_grip'): + self.empty=[float(np.mean(low[10:12]))<-.0175,float(np.mean(low[19:21]))<-.0175] + if any(self.empty) and self.retries<2 and obs['t']<2050: + self.retries+=1 + for arm,empty in ((self.cup_left,self.empty[0]),(self.cup_right,self.empty[1])): + if empty:arm[0]=max(-1.18,arm[0]-.07);arm[5]+=.07 + if name=='grip_cups': + self.phases[self.phase+1:self.phase+1]=[('retry_cups',100),('retry_grip',60)] + else: + self.phases[self.phase+1:self.phase+1]=[('retry_cups',100),('retry_grip',60)] + else: + self.angle=[float(self.cup_left[0]+self.cup_left[3]+self.cup_left[5]),float(self.cup_right[0]+self.cup_right[3]+self.cup_right[5])] + self.phase=min(self.phase+1,len(self.phases)-1);self.age=0 + return out.astype(np.float32) diff --git a/policies/put_cups/gpt61sol-s2/episodes.csv b/policies/put_cups/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/gpt61sol-s2/policy.py b/policies/put_cups/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e5d94b35061f1f47a81ff500d859ddf76a6c4afd --- /dev/null +++ b/policies/put_cups/gpt61sol-s2/policy.py @@ -0,0 +1,182 @@ +"""Hand-written, deterministic cup and cupboard controller. + +All scene feedback comes from the wrist RGB cameras. Pelvis feedback closes +walking commands; manipulation targets and image thresholds are fixed constants. +""" +import cv2 +import numpy as np + + +class Policy: + # Prepare, open right door, open left door, pick cups, lift and place. + DURATIONS = (130, 160, 100, 140, 50, 230, 35, + 170, 100, 140, 50, 230, 35, + 160, 120, 250, 130, 140, 130, + 160, 200, 80, 150, 1000) + HIGH = np.array([-1.8, 0., 0., 0., 0., 0., 0.]) + PICK = np.array([-.3, 0., 0., -.4, 0., .6, 0.]) + + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float).copy() + self.phase = self.age = 0 + self.xy = np.array([.17, 0.]) + self.yaw = 0. + self.arm = np.tile(self.HIGH, 2) + self.grip = np.zeros(2) + self.height = .74 + self.pitch = 0. + + @staticmethod + def ry(v): + c, s = np.cos(v), np.sin(v) + return np.array([[c, 0., s], [0., 1., 0.], [-s, 0., c]]) + + @staticmethod + def rz(v): + c, s = np.cos(v), np.sin(v) + return np.array([[c, -s, 0.], [s, c, 0.], [0., 0., 1.]]) + + @staticmethod + def wrist_angles(mat): + return np.array([np.arctan2(-mat[1, 2], mat[2, 2]), + np.arcsin(np.clip(mat[0, 2], -1., 1.)), + np.arctan2(-mat[0, 1], mat[0, 0])]) + + @staticmethod + def objects(im, handles=False, handle_limit=138): + rgb = im.astype(np.int16) + value = rgb.mean(axis=2) + neutral = rgb.max(axis=2) - rgb.min(axis=2) < 24 + if handles: + mask = (neutral & (value > 65) & (value < handle_limit)).astype(np.uint8) + mask[:4] = 0 + mask[:, :4] = 0 + mask[:, 80:] = 0 + else: + mask = (neutral & (value > 75) & (value < 235)).astype(np.uint8) + mask[:15] = 0 + count, _, stats, centers = cv2.connectedComponentsWithStats(mask) + result = [] + for k in range(1, count): + x, y, w, h, area = stats[k] + valid = (area > 65 and h > 22 and w < 25 and h > 2*w + if handles else area > 60 and h > 10 and w > 5 and y < 75) + if valid: + result.append((int(w), centers[k])) + return result + + def begin(self, obs): + p = self.phase + if p == 1: + self.xy = np.array([.36, 0.]) + elif p in (2, 8): + side = 1 if p == 2 else 0 + self.arm[7*side:7*side+7] = [-1.2, 0., 0., 0., 0., .3, 0.] + elif p in (4, 10): + self.grip[1 if p == 4 else 0] = 1. + elif p in (5, 11): + self.door_side = 1 if p == 5 else 0 + self.pull_origin = obs['low_dim_obs'][21:23].astype(float).copy() + self.yaw = float(obs['low_dim_obs'][24]) + self.door_wp = self.arm[7*self.door_side+5] + elif p in (6, 12): + self.grip[1 if p == 6 else 0] = 0. + elif p == 7: + self.arm = np.tile(self.HIGH, 2) + self.arm[7:] = [.5, -.3, 0., .5, 0., 0., 0.] + self.xy = np.array([.35, 0.]) + self.yaw = 0. + elif p == 13: + self.arm = np.tile(self.HIGH, 2) + self.xy = np.array([.25, .04]) + self.yaw = 0. + elif p == 14: + self.arm = np.tile(self.PICK, 2) + self.grip[:] = 0. + elif p in (16, 18): + self.pick_side = 0 if p == 16 else 1 + self.grip[self.pick_side] = 1. + self.pick_start = self.arm[7*self.pick_side:7*self.pick_side+7].copy() + elif p == 17: + self.xy = np.array([.32, .12]) + self.arm[7:] = [-.3, 0., 0., -.4, 0., .85, 0.] + elif p == 19: + self.carry_start = self.a[5:19].copy() + self.xy = np.array([.34, 0.]) + elif p == 20: + self.xy = np.array([.42, 0.]) + elif p == 21: + self.grip[:] = 0. + elif p == 22: + self.xy = np.array([.17, 0.]) + self.pitch = .1 + self.height = .74 + self.arm = np.tile(self.HIGH, 2) + + def act(self, obs, tools): + if self.age == 0: + self.begin(obs) + p = self.phase + if p in (3, 9) and self.age % 10 == 0: + side = 1 if p == 3 else 0 + candidates = self.objects(tools.image(('left_wrist', 'right_wrist')[side]), True, 138 if side else 165) + if candidates: + obj = (max if side else min)(candidates, key=lambda item: item[1][0]) + cx, cy = obj[1] + self.xy[1] = np.clip(self.xy[1] + np.clip((42-cx)*.0005, -.012, .012), -.22, .22) + self.arm[7*side+5] += np.clip((cy-38)*.0006, -.012, .012) + if p in (5, 11): + side = self.door_side + sign = 1. if side else -1. + theta = 1.55*(self.age+1)/self.DURATIONS[p] + self.xy = self.pull_origin + np.array([ + -.44*np.sin(theta)+.066*(1-np.cos(theta)), + sign*(-.44*(1-np.cos(theta))-.066*np.sin(theta))]) + mat = self.ry(1.2) @ self.rz(sign*theta) @ self.ry(-1.2+self.door_wp) + self.arm[7*side+4:7*side+7] = self.wrist_angles(mat) + if p == 15 and self.age % 10 == 0: + candidates = self.objects(tools.image('left_wrist')) + if candidates: + width, (cx, cy) = min(candidates, key=lambda item: item[1][0]) + self.xy[1] = np.clip(self.xy[1] + np.clip((42-cx)*.00035, -.008, .008), -.15, .25) + if self.age >= 80 and width < 75: + self.xy[0] = min(.44, self.xy[0]+.005) + self.arm[5] = np.clip(self.arm[5] + np.clip((cy-38)*.0007, -.012, .012), .35, 1.1) + if p in (16, 18) and self.age >= 45: + t = min(1., (self.age-44)/65.) + i = 7*self.pick_side + self.arm[i:i+7] = self.pick_start + self.arm[i] = self.pick_start[0] - .75*t + self.arm[i+5] = min(1.6, self.pick_start[5] + .75*t) + if p == 19: + t = min(1., (self.age+1)/140.) + target = np.tile([-1.6, 0., 0., -.7, 0., 1.6, 0.], 2) + self.arm = self.carry_start + t*(target-self.carry_start) + if p == 20: + self.pitch = .4 + if self.age > 90: + self.height = .79 + # Bring the cups down toward the shelf after extending the torso. + t = np.clip((self.age-100)/100., 0., 1.) + self.arm[3] = self.arm[10] = -.7 + .35*t + self.a[5:19] += np.clip(self.arm-self.a[5:19], -.015, .015) + self.a[19:] = self.grip + self.a[2] += np.clip(self.height-self.a[2], -.001, .001) + self.a[4] += np.clip(self.pitch-self.a[4], -.0025, .0025) + q = obs['low_dim_obs'] + yaw = float(q[24]) + error = self.xy-q[21:23] + distance = np.linalg.norm(error) + if distance > .016: + velocity = error/distance*max(.08, min(.4, distance*5)) + self.a[0] = np.cos(yaw)*velocity[0] + np.sin(yaw)*velocity[1] + self.a[1] = -np.sin(yaw)*velocity[0] + np.cos(yaw)*velocity[1] + else: + self.a[:2] = 0. + yaw_error = (self.yaw-yaw+np.pi) % (2*np.pi)-np.pi + self.a[3] = np.clip(3*yaw_error, -.6, .6) + self.age += 1 + if self.age >= self.DURATIONS[p] and p < len(self.DURATIONS)-1: + self.phase += 1 + self.age = 0 + return self.a.copy() diff --git a/policies/put_cups/gpt61sol-s3/episodes.csv b/policies/put_cups/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/gpt61sol-s3/policy.py b/policies/put_cups/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..581dedeb26b33bb12ba58511837cddeccbc27862 --- /dev/null +++ b/policies/put_cups/gpt61sol-s3/policy.py @@ -0,0 +1,169 @@ +"""Deterministic finite-state controller using wrist vision and finger contact. + +The door is aligned visually, grasped, and pulled along an arc. Cups are +handled sequentially with smooth joint targets and closed-loop base motion. +""" +import numpy as np +import cv2 + +class Policy: + @staticmethod + def handles(im): + gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY) + spread=im.max(2).astype(int)-im.min(2).astype(int) + m=((gray>45)&(gray<135)&(spread<22)).astype('uint8') + n,lab,st,cent=cv2.connectedComponentsWithStats(m);out=[] + for i in range(1,n): + x,y,w,h,area=st[i] + if h>18 and 2<=w<18 and area>25 and .12 and x+w<82: + out.append((float(cent[i,0]),float(cent[i,1]))) + return sorted(out) + + @staticmethod + def cups(im): + gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY) + spread=im.max(2).astype(int)-im.min(2).astype(int) + m=((gray>65)&(gray<225)&(spread<22)).astype('uint8') + n,lab,st,cent=cv2.connectedComponentsWithStats(m);out=[] + for i in range(1,n): + x,y,w,h,area=st[i] + if area>120 and 1416 and 25yy.max()-5 + out.append((float(xx[bottom].mean()),float(yy[bottom].mean()),w,h)) + return sorted(out,key=lambda a:abs(a[0]-42)) + + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=float);self.a[19:]=0 + self.state='door';self.mode='ready';self.s=-1.5;self.pitch=.15 + self.dxy=np.array([.20,-.015]);self.attempt=0;self.mark=0 + self.stage=0;self.cupside=0;self.side=0;self.cup_count=0 + self.start=0;self.prev=self.a.copy();self.roll=0;self.wp=.4 + self.arc=None;self.retry=0 + + def next_stage(self,obs): + self.stage+=1;self.start=int(obs['t']);self.prev=self.a.copy() + self.state='cup_'+str(self.stage) + + def base(self,a,obs,goal,speed=.16,walk=True): + p=obs['low_dim_obs'][21:25] + v=np.clip((np.asarray(goal)-p[:2])*2,-speed,speed) + n=np.linalg.norm(v) + if not walk or n<.025:v[:]=0 + elif n<.065:v*=.065/n + a[0]=v[0]*np.cos(p[3])+v[1]*np.sin(p[3]) + a[1]=-v[0]*np.sin(p[3])+v[1]*np.cos(p[3]) + a[3]=np.clip(-p[3]*3,-.3,.3) + return a + + def act(self,obs,tools): + t=int(obs['t']);ld=obs['low_dim_obs'];p=ld[21:25] + ready=np.array([-1,0,0,-.8,0,.7,0.]) + if self.state=='door': + a=self.a.copy();a[2]=.74 + if t<100: + a[5:12]=ready*min(1,t/70);a[4]=0 + goal=np.array([.08,-.015]) + else: + tar=np.array([self.s,-.15,.65,.5,0,-self.s-1.5,-.65]) + a[5:12]=ready+(tar-ready)*min(1,(t-100)/100) + a[4]=self.pitch;goal=self.dxy.copy() + if t>=200 and self.mode in ('ready','aim'): + self.mode='aim' + if t%10==0: + hs=self.handles(tools.image('left_wrist')) + if hs: + x,y=hs[0] + self.dxy[1]=p[1]-(x-42)*.002 + self.s=float(np.clip(self.s+(y-36)*.0007,-1.7,-1.3)) + if t>=350+self.attempt*120: + self.mode='close';self.mark=t;a[19]=1 + if self.mode=='close' and t-self.mark>45: + if ld[10:12].mean()<-.018 and self.attempt<2: + self.attempt+=1;self.mode='aim';a[19]=0;self.pitch=min(.4,self.pitch+.06) + else: + self.mode='pull';self.mark=t;self.arc=p[:2].copy() + if self.mode=='pull': + theta=min(1,(t-self.mark)/440)*1.65 + goal=self.arc+np.array([-.35*np.sin(theta),.35*(1-np.cos(theta))]) + if t-self.mark>440: + self.mode='release';self.mark=t;self.prev=a.copy() + if self.mode=='release': + u=t-self.mark;a[19]=0 + z=min(1,u/60);a[5:12]=self.prev[5:12]*(1-z);a[4]=self.prev[4]*(1-z) + goal=self.arc+np.array([-.35,.38]) + if u>=70: + self.state='transit';self.start=t;self.prev=a.copy();self.retry=0 + self.a=self.base(a,obs,goal,.14) + return self.a.copy() + + if self.state=='transit': + a=self.a.copy();a[5:19]=0;a[19:]=0;a[4]=0 + self.a=self.base(a,obs,[-.20,-.04],.22) + if t-self.start>=140: + self.state='cup_0';self.stage=0;self.start=t;self.prev=self.a.copy() + return self.a.copy() + + if self.state=='finish': + a=self.a.copy();a[2]=.74;a[4]=0;a[19:]=0 + a[5:12]+=(0-a[5:12])*.025 + a[12:19]+=(0-a[12:19])*.025 + self.a=self.base(a,obs,[-.15,.1],.16) + return self.a.copy() + + u=t-self.start;stage=self.stage + pick_y=-.04 if self.cup_count==0 else .20 + slot_y=.20 if self.cup_count==0 else .32 + tar=self.a.copy();tar[2]=.74;tar[12:19]=0;tar[20]=0 + goal=np.array([.05,pick_y]);walk=True;duration=60;limit=100 + pose=np.array([-.8,self.roll,0,.2,0,self.wp,0.]);tar[19]=0;tar[4]=0 + if stage==0: + pose=ready;duration=70;limit=100 + self.roll=0;self.wp=.4 + elif stage==1: + duration=60;limit=70 + elif stage==2: + goal=np.array([.20+.035*self.retry,pick_y]);tar[4]=.2+.10*self.retry;duration=75;limit=130 + if u>80 and t%10==0: + cs=self.cups(tools.image('left_wrist')) + if cs: + x,y,w,h=cs[0] + self.roll=float(np.clip(self.roll+(42-x)*.001,-.15,.25)) + self.wp=float(np.clip(self.wp+(y-42)*.001,.20,.65)) + if u>(105 if self.cup_count==0 and not self.retry else 120):walk=False + elif stage==3: + tar[4]=.2+.10*self.retry;tar[19]=1;walk=False;duration=1;limit=40 + if u>=40 and ld[10:12].mean()<-.0175 and self.retry<1: + self.retry+=1;self.stage=2;self.start=t-75;self.prev=self.a.copy() + self.wp=max(.15,self.wp-.10) + elif stage==4: + tar[19]=1;pose=np.array([-1.4,self.roll,0,.2,0,min(1.6,self.wp+.8),0.]) + goal=np.array([-.13,pick_y]);duration=90;limit=125;walk=u>=35 + elif stage==5: + tar[19]=1;pose=np.array([-1.8,self.roll,0,.5,0,1.3,0.]) + goal=np.array([-.13,pick_y]);duration=75;limit=80 + elif stage==6: + tar[19]=1;pose=np.array([-1.8,self.roll,0,.5,0,1.3,0.]) + goal=np.array([.23,slot_y]);duration=1;limit=130 + elif stage==7: + tar[19]=1;tar[4]=.15;goal=np.array([.32,slot_y]) + pose=np.array([-1.8,self.roll,0,.5,0,1.15,0.]);duration=55;limit=60 + elif stage==8: + tar[19]=1;tar[4]=.30;goal=np.array([.32,slot_y]) + pose=np.array([-1.8,self.roll,0,.5,0,1.0,0.]);duration=45;limit=80 + elif stage==9: + tar[19]=0;tar[4]=.30;goal=np.array([.32,slot_y]) + pose=np.array([-1.8,self.roll,0,.5,0,1.0,0.]);duration=15;limit=30 + elif stage==10: + pose=np.array([-1.5,self.roll,0,.5,0,1.0,0.]);goal=np.array([-.10,slot_y]) + duration=45;limit=70;walk=u>30 + tar[5:12]=pose + alpha=min(1,(u+1)/duration) + a=self.prev+(tar-self.prev)*alpha + self.a=self.base(a,obs,goal,.22 if stage in (0,4,6,10) else .16,walk) + if u>=limit: + if stage==10: + self.cup_count+=1;self.retry=0 + if self.cup_count>=2:self.state='finish' + else:self.stage=-1;self.next_stage(obs) + elif stage==self.stage:self.next_stage(obs) + return self.a.copy() diff --git a/policies/put_cups/gpt61terra-s1/episodes.csv b/policies/put_cups/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3000,timeout,0 +620001,0,3000,timeout,0 +620002,0,3000,timeout,0 +620003,0,3000,timeout,0 +620004,0,3000,timeout,0 +620005,0,3000,timeout,0 +620006,0,3000,timeout,0 +620007,0,3000,timeout,0 +620008,0,3000,timeout,0 +620009,0,3000,timeout,0 +620010,0,3000,timeout,0 +620011,0,3000,timeout,0 +620012,0,3000,timeout,0 +620013,0,3000,timeout,0 +620014,0,3000,timeout,0 +620015,0,3000,timeout,0 +620016,0,3000,timeout,0 +620017,0,3000,timeout,0 +620018,0,3000,timeout,0 +620019,0,3000,timeout,0 +620020,0,3000,timeout,0 +620021,0,3000,timeout,0 +620022,0,3000,timeout,0 +620023,0,3000,timeout,0 +620024,0,3000,timeout,0 +620025,0,3000,timeout,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,0,3000,timeout,0 +620031,0,3000,timeout,0 +620032,0,3000,timeout,0 +620033,0,3000,timeout,0 +620034,0,3000,timeout,0 +620035,0,3000,timeout,0 +620036,0,3000,timeout,0 +620037,0,3000,timeout,0 +620038,0,3000,timeout,0 +620039,0,3000,timeout,0 +620040,0,3000,timeout,0 +620041,0,3000,timeout,0 +620042,0,3000,timeout,0 +620043,0,3000,timeout,0 +620044,0,3000,timeout,0 +620045,0,3000,timeout,0 +620046,0,3000,timeout,0 +620047,0,3000,timeout,0 +620048,0,3000,timeout,0 +620049,0,3000,timeout,0 +620050,0,3000,timeout,0 +620051,0,3000,timeout,0 +620052,0,3000,timeout,0 +620053,0,3000,timeout,0 +620054,0,3000,timeout,0 +620055,0,3000,timeout,0 +620056,0,3000,timeout,0 +620057,0,3000,timeout,0 +620058,0,3000,timeout,0 +620059,0,3000,timeout,0 +620060,0,3000,timeout,0 +620061,0,3000,timeout,0 +620062,0,3000,timeout,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,0,3000,timeout,0 +620068,0,3000,timeout,0 +620069,0,3000,timeout,0 +620070,0,3000,timeout,0 +620071,0,3000,timeout,0 +620072,0,3000,timeout,0 +620073,0,3000,timeout,0 +620074,0,3000,timeout,0 +620075,0,3000,timeout,0 +620076,0,3000,timeout,0 +620077,0,3000,timeout,0 +620078,0,3000,timeout,0 +620079,0,3000,timeout,0 +620080,0,3000,timeout,0 +620081,0,3000,timeout,0 +620082,0,3000,timeout,0 +620083,0,3000,timeout,0 +620084,0,3000,timeout,0 +620085,0,3000,timeout,0 +620086,0,3000,timeout,0 +620087,0,3000,timeout,0 +620088,0,3000,timeout,0 +620089,0,3000,timeout,0 +620090,0,3000,timeout,0 +620091,0,3000,timeout,0 +620092,0,3000,timeout,0 +620093,0,3000,timeout,0 +620094,0,3000,timeout,0 +620095,0,3000,timeout,0 +620096,0,3000,timeout,0 +620097,0,3000,timeout,0 +620098,0,3000,timeout,0 +620099,0,3000,timeout,0 diff --git a/policies/put_cups/gpt61terra-s1/policy.py b/policies/put_cups/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b34729eaed08f4c98fae07de2fbe7c62e5dfa5fe --- /dev/null +++ b/policies/put_cups/gpt61terra-s1/policy.py @@ -0,0 +1,49 @@ +"""Staged deterministic controller for the cabinet and cups.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + self.initial[19:21] = 0 + self.start_x = float(obs["low_dim_obs"][21]) + self.start_yaw = float(obs["low_dim_obs"][24]) + self.poses = [] + p = self.initial.copy() + def add(duration, changes): + nonlocal p + p=p.copy() + for k,v in changes.items(): p[k]=v + self.poses.append((duration,p.copy())) + add(100,{5:-1.5}) + add(100,{4:.2,5:-1.5,6:.1,8:.5}) + add(80,{19:1}) + add(120,{8:1.1}) + add(100,{8:1.25}) + add(80,{19:0}) + add(100,{4:0,5:-1.5,6:0,8:0}) + add(120,{4:.4,5:-1.5,6:.1,8:.9}) + add(80,{19:1}) + add(100,{4:.3,8:.7}) + add(100,{4:.2,5:-1.6,8:.5}) + add(100,{4:0,5:-1.7}) + add(120,{4:.25,5:-1.8,8:.15}) + add(80,{19:0}) + add(100,{4:0,5:-1.5,6:0,8:0}) + add(100,{5:0,12:-1.5}) + add(120,{4:.4,12:-1.5,13:-.1,15:.9}) + add(80,{20:1}) + add(100,{4:.3,15:.7}) + add(100,{4:.2,12:-1.6,15:.5}) + add(100,{4:0,12:-1.7}) + add(120,{4:.25,12:-1.8,15:.15}) + add(80,{20:0}) + add(100,{4:0,12:-1.5,13:0,15:0}) + def act(self, obs, tools): + t=int(obs['t']); prev=self.initial + for duration,target in self.poses: + if t